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..dc96b96e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,46 @@ 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=`) and saveable + as named views ("Saved views": my views and views others shared, kept as + `saved_view` objects in OpenRegister). 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/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..6916ceafb 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: 89.0% of statements (PHP 89.0% of 21,987 statements), at commit `d2a99e94` on 2026-11-13. The JavaScript frontend is not in this figure, because it has no coverage measurement yet. 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/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..3b084cb2a 100644 --- a/appinfo/info.xml +++ b/appinfo/info.xml @@ -52,7 +52,7 @@ Ideaal voor organisaties die consistente, samengestelde dashboards willen voor h Vrij en open source onder de EUPL-1.2-licentie. ]]> - 1.1.6-beta.20261002211709 + 1.1.9-unstable.20261121000000EUPL-1.2ConductionLaunchPad @@ -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 @@ -118,6 +128,17 @@ 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\SetDefaultApp OCA\LaunchPad\Repair\InitializeActions @@ -139,6 +160,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 +186,7 @@ Vrij en open source onder de EUPL-1.2-licentie. OCA\LaunchPad\Command\DemoShowcasesInstallCommandOCA\LaunchPad\Command\DemoShowcasesListCommand + OCA\LaunchPad\Command\TemplateInstallCommandOCA\LaunchPad\Command\SetupCommand @@ -172,6 +197,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/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..31b68e4b2 --- /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/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/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/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/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/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..033a5b32d 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,26 +158,41 @@ 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; + $dashboard = $this->sharedDashboard(dashboardId: (int)$dashboardId, userId: $userId); + if ($dashboard !== null) { + $entries[] = [ + 'dashboard' => $dashboard, + 'source' => Dashboard::SOURCE_SHARED, + ]; } - - if ($dashboard->getUserId() === $userId) { - continue; - } - - $entries[] = [ - 'dashboard' => $dashboard, - 'source' => Dashboard::SOURCE_SHARED, - ]; } return $entries; }//end findSharedDashboards() + /** + * A dashboard shared with the user; null for an orphaned share row + * (the cleanup job reaps these) or a dashboard the user owns. + * + * @param int $dashboardId The shared dashboard ID. + * @param string $userId The user ID. + * + * @return Dashboard|null The dashboard, or null. + */ + private function sharedDashboard(int $dashboardId, string $userId): Dashboard|null { + try { + $dashboard = $this->dashboardMapper->find(id: $dashboardId); + } catch (DoesNotExistException) { + return null; + } + + if ($dashboard->getUserId() === $userId) { + return null; + } + + return $dashboard; + }//end sharedDashboard() + /** * Try to resolve a dashboard shared with the user as their active one. * @@ -220,33 +222,22 @@ public function findSharedDashboards(string $userId, array $userGroupIds): array * * @spec openspec/specs/dashboard-sharing/spec.md */ - public function tryGetSharedDashboard(string $userId, array $userGroupIds): ?array { + public function tryGetSharedDashboard(string $userId, array $userGroupIds): array|null { $levels = $this->findSharedLevels( userId: $userId, userGroupIds: $userGroupIds ); foreach ($levels as $dashboardId => $level) { - try { - $dashboard = $this->dashboardMapper->find(id: (int)$dashboardId); - } catch (DoesNotExistException) { - continue; + $dashboard = $this->sharedDashboard(dashboardId: (int)$dashboardId, userId: $userId); + if ($dashboard !== null) { + return [ + 'dashboard' => $dashboard, + 'placements' => $this->placementsOf(dashboard: $dashboard), + 'permissionLevel' => $level, + ]; } - - if ($dashboard->getUserId() === $userId) { - continue; - } - - $placements = $this->placementMapper->findByDashboardId( - dashboardId: $dashboard->getId() - ); - - return [ - 'dashboard' => $dashboard, - 'placements' => $placements, - 'permissionLevel' => $level, - ]; - }//end foreach + } return null; }//end tryGetSharedDashboard() @@ -272,22 +263,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 +299,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..ed9a0701e 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,18 @@ * @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, + ]; + /** * HTTP-like error message for non-admin attempting an admin-only mutation. * @@ -146,194 +154,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 +257,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 +277,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 +309,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 +328,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); + } + + $layered = $this->withPersonalLayer( + placements: $placements, + dashboard: $dashboard, + userId: $userId + ); + + if ($sharedLevel !== null) { + return [ + 'dashboard' => $dashboard, + 'placements' => $layered, + 'permissionLevel' => $sharedLevel, + ]; } - return $this->dashResolver->buildResult( + return $this->builders->dashResolver->buildResult( dashboard: $dashboard, - placements: $this->withPersonalLayer( - placements: $placements, - 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 +413,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 +424,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 +446,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,73 +473,174 @@ 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( + 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() + ); + return $this->builders->dashResolver->buildResult( + dashboard: $dashboard, + placements: $placements + ); + }//end buildResultWithPlacements() + + /** + * 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; } - $result = $this->resolveRoleLayoutOrDefaultGroupDashboard(userId: $userId); - if ($result !== null) { - return $result; - } + return $this->builders->dashResolver->tryActivateExistingDashboard( + userId: $userId + ); + }//end resolveOwnedEffectiveDashboard() - // 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( + /** + * 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 { + $result = $this->builders->dashResolver->tryGetSharedDashboard( userId: $userId, - userGroupIds: $this->adminTemplateService->getUserGroupIdsFor( + userGroupIds: $this->builders->adminTemplateService->getUserGroupIdsFor( userId: $userId ) ); @@ -611,7 +649,7 @@ private function resolveEffectiveDashboard(string $userId): ?array { } 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 +664,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 +688,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 +734,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 +754,230 @@ 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']); - $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, userId: $userId, 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'], + ]; + }//end factoryOptions() - // Icon is an opaque string (registry key or URL) — see the - // `dashboard-icons` capability. NULL/empty means "use the - // frontend default glyph". + /** + * 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 another + * user's dashboard holds. + * + * @param Dashboard $dashboard The new dashboard. + * @param string $userId The owner. + * @param array $options The create options: parentUuid, slug. + * + * @return void + */ + private function assertNewSlugUnique(Dashboard $dashboard, string $userId, array $options): void { $resolvedSlug = $dashboard->getSlug(); - if ($resolvedSlug !== null && $resolvedSlug !== '') { - $this->treeService->validateSlugUnique( - parentUuid: $parentUuid, - slug: $resolvedSlug - ); + if ($resolvedSlug === null || $resolvedSlug === '') { + return; + } + + if ($options['slug'] === null && $options['parentUuid'] === null) { + $resolvedSlug = $this->freeRootSlug(userId: $userId, slug: $resolvedSlug); + // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $dashboard->setSlug($resolvedSlug); } - $this->dashboardMapper->deactivateAllForUser(userId: $userId); + $this->structure->treeService->validateSlugUnique( + parentUuid: $options['parentUuid'], + slug: $resolvedSlug + ); + }//end assertNewSlugUnique() - $persisted = $this->dashboardMapper->insert(entity: $dashboard); + /** + * The first of `slug`, `slug-2`, `slug-3`… that no other user's root + * dashboard holds. A slug the owner's own root dashboard holds is + * returned as it is, so the sibling check refuses it. + * + * @param string $userId The owner. + * @param string $slug The slug derived from the name. + * + * @return string The slug to store. + */ + private function freeRootSlug(string $userId, 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; + } - // 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()] - ); + $holder = $this->stores->dashboardMapper->findChildBySlug(parentUuid: null, slug: $candidate); + if ($holder === null || ($number === 1 && $holder->getUserId() === $userId)) { + 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) { + 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()); } + }//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 +992,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 +1005,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 +1036,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 +1081,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 +1116,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 +1179,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 +1229,7 @@ private function dispatchDashboardDeleted( string $uuid, string $fallbackOwnerId, ): void { - if ($this->eventDispatcher === null || $uuid === '') { + if ($this->outlets->eventDispatcher === null || $uuid === '') { return; } @@ -1077,7 +1239,7 @@ private function dispatchDashboardDeleted( $resolvedOwnerId = $ownerId; } - $this->eventDispatcher->dispatchTyped( + $this->outlets->eventDispatcher->dispatchTyped( new DashboardDeletedEvent( dashboardUuid: $uuid, ownerUserId: $resolvedOwnerId, @@ -1102,13 +1264,13 @@ 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'); } - $this->dashboardMapper->setActive( + $this->stores->dashboardMapper->setActive( $dashboardId, userId: $userId ); @@ -1133,7 +1295,7 @@ 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() /** @@ -1148,7 +1310,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 +1336,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 +1356,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 +1396,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 +1449,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 +1481,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; + } + + $count = $this->stores->dashboardMapper->countByGroup( + groupId: $groupId + ); + if ($count <= 1) { + throw new Exception(message: self::ERR_LAST_IN_GROUP); } + }//end assertNotLastInGroup() - $this->placementMapper->deleteByDashboardId( + /** + * 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 +1567,7 @@ public function deleteGroupShared( ) ); } - }//end deleteGroupShared() + }//end dispatchGroupSharedDeleted() /** * Promote a single group-shared dashboard to the group's default. @@ -1394,9 +1606,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 +1635,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 +1664,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 +1674,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 ); @@ -1489,7 +1721,7 @@ public function getVisibleToUser(string $userId): array { $seenUuids[(string)$entry['dashboard']->getUuid()] = true; } - $sharedEntries = $this->dashResolver->findSharedDashboards( + $sharedEntries = $this->builders->dashResolver->findSharedDashboards( userId: $userId, userGroupIds: $userGroupIds ); @@ -1529,19 +1761,33 @@ private function materialiseDueSchedule(Dashboard $dashboard): void { return; } + if ($this->isDue(dashboard: $dashboard, now: new DateTime()) === true) { + $dashboard->setPublicationStatus(Dashboard::STATUS_PUBLISHED); + } + }//end materialiseDueSchedule() + + /** + * 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 +1804,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 +1836,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 +1877,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 +1957,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 +2019,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 +2046,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 +2077,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 +2106,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 +2122,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,132 +2136,297 @@ 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); - - $rungs = []; - if ($hasPrimaryGroup === true) { - // Step 2: primary group default. - $rungs[] = [$groupId, Dashboard::SOURCE_GROUP, true]; + 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); } - // Step 3: default-group default. - $rungs[] = [Dashboard::DEFAULT_GROUP_ID, Dashboard::SOURCE_DEFAULT, true]; - - if ($hasPrimaryGroup === true) { - // Step 4: primary group first. - $rungs[] = [$groupId, Dashboard::SOURCE_GROUP, false]; - } - - // Step 5: default-group first. - $rungs[] = [Dashboard::DEFAULT_GROUP_ID, Dashboard::SOURCE_DEFAULT, false]; - - foreach ($rungs as $rung) { - $result = $this->findFirstGroupSharedWhere( - visible: $visible, - groupId: $rung[0], - source: $rung[1], - requireDefault: $rung[2] - ); - if ($result !== null) { - return $result; - } + $source = Dashboard::SOURCE_USER; + if ($fromTemplate['viewOnly'] === true) { + $source = Dashboard::SOURCE_GROUP; } - return null; - }//end resolveGroupSharedDashboard() + return ['dashboard' => $fromTemplate['dashboard'], 'source' => $source]; + }//end resolveTemplateOrGroupShared() /** - * Return the first visible entry carrying the given source, in - * iteration order. + * The template rung of both resolution chains (REQ-TMPL-019). * - * @param array $visible The visible set. - * @param string $source The source discriminator. + * 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. * - * @return array{dashboard: Dashboard, source: string}|NULL The hit, or NULL when none match. + * 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. * - * @spec openspec/specs/dashboards/spec.md + * 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 findFirstBySource(array $visible, string $source): ?array { - foreach ($visible as $entry) { - if ($entry['source'] === $source) { - return $entry; - } + 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; } - return null; - }//end findFirstBySource() + if ($this->getAllowUserDashboards() === false) { + return ['dashboard' => $template, 'viewOnly' => true]; + } + + return ['dashboard' => $this->copyTemplateFor(userId: $userId, template: $template), 'viewOnly' => false]; + }//end resolveTemplateRung() /** - * Persist (or clear) the user's active-dashboard preference. + * 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. * - * Accepts any non-empty UUID string without performing an existence - * check — the resolver's stale-pref path handles invalid UUIDs on next - * read (REQ-DASH-019 "no existence check on write"). - * - * @param string $userId The user ID. - * @param string $uuid The dashboard UUID, or empty string to clear. + * "First time" means: owns nothing yet. Whoever has a personal + * dashboard already made, or was given, their start. * - * @return void + * @param string $userId The user. + * @param Dashboard $template The applicable template. * - * @spec openspec/specs/dashboards/spec.md + * @return bool True when the template is not shown. */ - public function setActivePreference(string $userId, string $uuid): void { - if ($uuid === '') { - $this->config->deleteUserValue( - userId: $userId, - appName: Application::APP_ID, - key: self::ACTIVE_DASHBOARD_UUID_PREF_KEY - ); - return; - } + private function templateStepsAside(string $userId, Dashboard $template): bool { + return $this->stores->dashboardMapper->findByUserId(userId: $userId) !== [] + || ($template->getTargetGroupsArray() === [] + && $this->hasPrimaryGroupDefault(userId: $userId) === true); + }//end templateStepsAside() - $this->config->setUserValue( + /** + * 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: $uuid + value: (string)$copy->getUuid() ); - }//end setActivePreference() + + return $copy; + }//end copyTemplateFor() /** - * Persist (or clear) the user's EXPLICIT default-dashboard pin - * (wave3.7). - * - * Distinct from {@see self::setActivePreference()} — this pref is - * only ever written when the user clicks "Set as default" on a - * row's cog menu (it is NOT auto-overwritten on every switch). - * The resolver checks it before the active pref so an explicit - * pin survives across switches. - * - * Same write semantics as `setActivePreference`: no existence - * check on write, the resolver's stale-pref path handles missing - * UUIDs on next read. + * Whether the user's primary group has a default group dashboard. * - * @param string $userId The user ID. - * @param string $uuid The dashboard UUID, or empty string to clear. + * @param string $userId The user. * - * @return void + * @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; + } + + 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 ($rung['viewOnly'] === true) { + return [ + 'dashboard' => $rung['dashboard'], + 'placements' => $placements, + 'permissionLevel' => Dashboard::PERMISSION_VIEW_ONLY, + ]; + } + + return $this->builders->dashResolver->buildResult( + dashboard: $rung['dashboard'], + placements: $placements + ); + }//end describeTemplateRung() + + /** + * 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], + source: $rung[1], + requireDefault: $rung[2] + ); + if ($result !== null) { + return $result; + } + } + + 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. + * + * @param array $visible The visible set. + * @param string $source The source discriminator. + * + * @return array{dashboard: Dashboard, source: string}|NULL The hit, or NULL when none match. + * + * @spec openspec/specs/dashboards/spec.md + */ + private function findFirstBySource(array $visible, string $source): ?array { + foreach ($visible as $entry) { + if ($entry['source'] === $source) { + return $entry; + } + } + + return null; + }//end findFirstBySource() + + /** + * Persist (or clear) the user's active-dashboard preference. + * + * Accepts any non-empty UUID string without performing an existence + * check — the resolver's stale-pref path handles invalid UUIDs on next + * read (REQ-DASH-019 "no existence check on write"). + * + * @param string $userId The user ID. + * @param string $uuid The dashboard UUID, or empty string to clear. + * + * @return void + * + * @spec openspec/specs/dashboards/spec.md + */ + public function setActivePreference(string $userId, string $uuid): void { + if ($uuid === '') { + $this->platform->config->deleteUserValue( + userId: $userId, + appName: Application::APP_ID, + key: self::ACTIVE_DASHBOARD_UUID_PREF_KEY + ); + return; + } + + $this->platform->config->setUserValue( + userId: $userId, + appName: Application::APP_ID, + key: self::ACTIVE_DASHBOARD_UUID_PREF_KEY, + value: $uuid + ); + }//end setActivePreference() + + /** + * Persist (or clear) the user's EXPLICIT default-dashboard pin + * (wave3.7). + * + * Distinct from {@see self::setActivePreference()} — this pref is + * only ever written when the user clicks "Set as default" on a + * row's cog menu (it is NOT auto-overwritten on every switch). + * The resolver checks it before the active pref so an explicit + * pin survives across switches. + * + * Same write semantics as `setActivePreference`: no existence + * check on write, the resolver's stale-pref path handles missing + * UUIDs on next read. + * + * @param string $userId The user ID. + * @param string $uuid The dashboard UUID, or empty string to clear. + * + * @return void * * @spec openspec/specs/dashboards/spec.md */ 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 +2434,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 +2457,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 +2487,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 +2503,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 +2528,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 +2555,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 +2576,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 +2611,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 +2657,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 +2702,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 +2728,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 +2819,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 +2868,7 @@ public function forkAsPersonal( ); } finally { if ($lockAcquired === true) { - $this->lockingProvider?->releaseLock( + $this->limits->lockingProvider?->releaseLock( path: $lockKey, type: ILockingProvider::LOCK_EXCLUSIVE ); @@ -2373,42 +2894,47 @@ public function forkAsPersonal( * @throws Throwable Whatever the transaction body threw, after rollback. * * @spec openspec/specs/dashboards/spec.md + * @spec openspec/changes/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 +2951,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 +2979,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 +2997,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 +3013,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 +3038,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 +3079,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 +3114,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 +3148,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 +3165,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 +3201,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 +3254,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 +3329,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 +3348,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 +3359,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' => $placements, - 'permissionLevel' => Dashboard::PERMISSION_FULL, - ]; - }//end if + return [ + 'dashboard' => $dashboard, + 'placements' => $this->provisionedPlacements(dashboard: $dashboard, seeded: $seeded), + 'permissionLevel' => Dashboard::PERMISSION_FULL, + ]; + }//end provisionPersonalDashboard() - return null; - }//end tryCreateFromTemplate() + /** + * 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() + ); + } + + if ($seeded === 0) { + return $this->createDefaultPlacements( + dashboardId: $dashboard->getId() + ); + } + + return []; + }//end provisionedPlacements() /** * Create default widget placements for a new dashboard. @@ -2885,7 +3479,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 +3529,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 +3552,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. * @@ -2996,7 +3607,7 @@ private function seedDefaultWidgets(int $dashboardId): array { $placements = []; foreach ($this->defaultWidgetSeeds() as $config) { - $placements[] = $this->placementMapper->insert( + $placements[] = $this->stores->placementMapper->insert( entity: $this->buildSeedPlacement( dashboardId: $dashboardId, config: $config, @@ -3021,68 +3632,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() /** @@ -3115,6 +3673,20 @@ private function buildSeedPlacement(int $dashboardId, array $config, string $now 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 +3695,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 +3716,266 @@ 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); - 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/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 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 +4014,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 +4060,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 +4139,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 +4166,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 +4182,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..809177ae8 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 @@ -378,70 +432,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() - // No-op: same level. + /** + * 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() + + /** + * 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 +509,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]; - } - - // Group share — expand members. - $groupId = (string)$share->getShareWith(); - $group = $this->groupManager->get(gid: $groupId); - if ($group === null) { - return []; + 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'); } - $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 +578,7 @@ private function validateInput( ); } - if ($shareWith === '') { + if ($grant->shareWith === '') { throw new InvalidArgumentException(message: 'shareWith is required'); } @@ -609,13 +602,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..110f36b88 100644 --- a/lib/Service/DashboardTranslationService.php +++ b/lib/Service/DashboardTranslationService.php @@ -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. @@ -436,17 +468,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 +477,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 +555,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 +590,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..47cecd2ae 100644 --- a/lib/Service/DashboardVersionService.php +++ b/lib/Service/DashboardVersionService.php @@ -40,15 +40,12 @@ 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 OCP\AppFramework\Db\DoesNotExistException; use OCP\ICache; use OCP\ICacheFactory; -use OCP\IDBConnection; use OCP\IGroupManager; use Psr\Log\LoggerInterface; use Throwable; @@ -81,6 +78,7 @@ class DashboardVersionService { private const BLOB_SETTERS = [ 'styleConfig' => 'setStyleConfigArray', 'content' => 'setContentArray', + 'calculatedFields' => 'setCalculatedFieldsArray', ]; /** @@ -126,39 +124,17 @@ 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. */ 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, ) { }//end __construct() @@ -185,14 +161,12 @@ 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) and + * `explicit` (bypass the debounce; false). * * @return DashboardVersion|null The persisted version row, or null * when an automatic snapshot was @@ -200,14 +174,9 @@ public function __construct( * * @spec openspec/specs/dashboard-versioning/spec.md */ - 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 +184,53 @@ 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. + */ + 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 +238,11 @@ public function captureSnapshot( } $coercedNote = null; - if ($explicit === true && $note !== null && $note !== '') { + if ($options['explicit'] === true && $note !== null && $note !== '') { $coercedNote = $note; } - $next = ($this->versionMapper->findMaxVersionNumber( + $next = ($this->stores->versionMapper->findMaxVersionNumber( dashboardUuid: $uuid ) + 1); @@ -241,18 +253,30 @@ 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() + + /** + * 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 +288,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 +328,7 @@ public function listVersions( ]; } - $rows = $this->versionMapper->findLatestByDashboard( + $rows = $this->stores->versionMapper->findLatestByDashboard( dashboardUuid: (string)$dashboard->getUuid(), limit: self::RETENTION_LIMIT ); @@ -349,7 +373,7 @@ public function fetchSnapshot( ); } - return $this->versionMapper->findByDashboardAndVersion( + return $this->stores->versionMapper->findByDashboardAndVersion( dashboardUuid: (string)$dashboard->getUuid(), versionNumber: $versionNumber ); @@ -389,10 +413,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 +435,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 +463,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 +484,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 = $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); - $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 - ); - - // 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() - if ($this->db !== null) { - $this->db->commit(); + /** + * 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']; + } + + $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 +578,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 +777,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 +837,7 @@ private function applySnapshotPayload(Dashboard $dashboard, array $payload): voi } try { - $this->placementMapper->deleteByDashboardId( + $this->stores->placementMapper->deleteByDashboardId( dashboardId: $dashboardId ); @@ -751,7 +854,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/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..b0f554ffb --- /dev/null +++ b/lib/Service/DemoAnnouncements.php @@ -0,0 +1,140 @@ + + * @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(($kind === Announcement::KIND_NOTICE) ? 'warning' : null); + $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/DemoShowcasesService.php b/lib/Service/DemoShowcasesService.php index c5b77edb8..c2f161fc8 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,55 @@ 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(); + $registered = $this->registeredWidgetIds(); + $known = $this->getLaunchpadWidgetTypes() + $registered; $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 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 (isset($ownTypes[$widgetId]) === true - || isset($registered[$widgetId]) === true - ) { - $valid[] = $widget; - continue; - } + return $registered; + }//end registeredWidgetIds() - if ($widgetId !== '') { - $skipped[] = $widgetId; - } - }//end foreach + /** + * 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 [$valid, $skipped]; - }//end partitionWidgets() + return isset($known[(string)($widget['widgetId'] ?? '')]) === true; + }//end isPlaceable() /** * Load LaunchPad's own widget types from `lib/widget-types.json`. @@ -598,29 +683,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 +758,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 +870,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 +912,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 +927,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 +949,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..e89a2d364 --- /dev/null +++ b/lib/Service/Embed/EmbedObjectStore.php @@ -0,0 +1,268 @@ + + * @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 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'; + + /** + * 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 = $service->searchObjectsBySlug( + registerSlug: self::REGISTER, + schemaSlug: $schema, + filters: $filters, + _rbac: false, + _multitenancy: false + ); + 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() + + /** + * 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..0eea82737 --- /dev/null +++ b/lib/Service/Embed/EmbedRenderService.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 + * @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). + * + * @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-when-cross-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..fca9a6441 --- /dev/null +++ b/lib/Service/Embed/EmbedTokenService.php @@ -0,0 +1,695 @@ + + * @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(at: $this->nowIso(), reason: $reason, notes: $notes, by: $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(at: $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) { + $this->store->save(schema: EmbedObjectStore::TOKENS, object: $token->revoked(at: $now, reason: 're-issued', notes: null, by: $userId)->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..a68d9f364 --- /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 (mixed $value, int|string $dimension): bool => in_array((string)$dimension, $allowed, true) === true, + ARRAY_FILTER_USE_BOTH + ); + + 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..82fa95a62 --- /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/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/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/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/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/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/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/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/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/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..89ca384b5 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]); + + return '<' . $tag . $this->renderAttributes(kept: $kept) . $this->externalLinkAttributes(tag: $tag, kept: $kept) . $this->tagEnd(tag: $tag); + }//end sanitiseTag() - $rendered = '<' . $tag; + /** + * 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,41 @@ 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 { if (preg_match_all( pattern: '#([a-zA-Z][a-zA-Z0-9_-]*)\s*=\s*("([^"]*)"|\'([^\']*)\'|([^\s"\'>]+))#', subject: $attrs, @@ -467,38 +627,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,6 +695,27 @@ 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. + * + * @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( @@ -521,40 +723,69 @@ public function validateStructuredConfig(array $config): void { ); } } + }//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 +810,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 +818,124 @@ 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 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..6b6b7f792 100644 --- a/lib/Service/HealthPingService.php +++ b/lib/Service/HealthPingService.php @@ -47,11 +47,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 +62,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 @@ -155,21 +153,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() @@ -271,7 +265,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 +291,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 +313,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 +333,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; } @@ -407,12 +402,12 @@ private function isDue(int $placementId, array $config): bool { */ 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,23 +420,14 @@ 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( + $this->settings->logger->info( message: 'HealthPingService: ping transport failure, classifying offline', context: ['app' => Application::APP_ID, 'exception' => $exception->getMessage()] ); @@ -490,7 +476,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 @@ -503,18 +489,6 @@ private function latencyThreshold(): int { return self::DEFAULT_LATENCY_THRESHOLD_MS; }//end latencyThreshold() - /** - * 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 `healthping_allowed_hosts`. FAIL-CLOSED: * an empty, missing, or unparseable allow-list permits NO host — the @@ -525,31 +499,8 @@ private function hasValidScheme(string $url): bool { * @return boolean True only when the host is explicitly allow-listed. */ 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: '' - ); - - $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; + $allowList = new HostAllowList(appConfig: $this->settings->appConfig, configKey: self::CONFIG_KEY_ALLOWED_HOSTS); + return $allowList->permits(url: $url); }//end isHostAllowed() /** @@ -607,34 +558,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 +570,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/HostAllowList.php b/lib/Service/HostAllowList.php new file mode 100644 index 000000000..847cbaab2 --- /dev/null +++ b/lib/Service/HostAllowList.php @@ -0,0 +1,119 @@ +<?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. + */ + public function __construct( + private readonly IAppConfig $appConfig, + private readonly string $configKey, + ) { + }//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). The list is + * 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 + */ + public function permits(string $url): bool { + $host = parse_url(url: $url, component: PHP_URL_HOST); + if (is_string(value: $host) === false || $host === '') { + return false; + } + + $decoded = json_decode(json: $this->rawList(), associative: true); + if (is_array(value: $decoded) === false || $decoded === []) { + // FAIL-CLOSED — no configured list means no host is allowed. + return false; + } + + return $this->listsHost(allowed: $decoded, host: $host); + }//end permits() + + /** + * 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/ImportService.php b/lib/Service/ImportService.php index 09f3d5169..95a876b49 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/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/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..f7baacb68 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 @@ -77,7 +81,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 +119,10 @@ class InitialStateBuilder { 'allowUserDashboards', 'linkCreateFileExtensions', ], + // Sharing-public-start-page D3: the link the start page shows. + Page::PUBLIC_START->value => [ + 'publicStartToken', + ], ]; /** @@ -338,6 +346,177 @@ 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 whether the dashboard view renders without the left navigation + * panel (workspace). + * + * Optional key, like {@see self::setQuicksearchFallbackTarget()}: NOT + * in {@see self::REQUIRED_KEYS}, so a server that has not called this + * setter still passes {@see self::apply()}, and the JS reader's `false` + * default keeps the rail for an older deploy (runtime-shell + * REQ-SHELL-009). + * + * @param bool $withoutNavigation True to leave the panel out of the dashboard view. + * + * @return self Fluent. + * + * @spec openspec/specs/runtime-shell/spec.md#req-shell-009 + */ + public function setStartPageWithoutNavigation(bool $withoutNavigation): self { + $this->values['startPageWithoutNavigation'] = $withoutNavigation; + return $this; + }//end setStartPageWithoutNavigation() + + /** + * Set the administrator CSS for all of LaunchPad (workspace). + * + * Optional key, like {@see self::setStartPageWithoutNavigation()}. 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/drill-down-cross-widget-filter/tasks.md#task-17 + */ + public function setFilterTelemetryEnabled(bool $enabled): self { + $this->values['filterTelemetryEnabled'] = $enabled; + return $this; + }//end setFilterTelemetryEnabled() + + /** + * 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::setStartPageWithoutNavigation()}: 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 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 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 +565,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()}. 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..86a19bc3e 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,72 @@ 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 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 +367,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 +377,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 +409,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/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..9be075ed5 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 @@ -169,33 +167,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 +213,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: $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() - return $this->publicShape(reading: $fresh, config: $config, stale: false); + /** + * 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() + + /** + * 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 +328,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 +342,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 +418,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 +426,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 +475,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 +487,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 +562,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 +669,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 +699,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 +723,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 +839,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. @@ -681,18 +917,6 @@ private function badgeShape(array $threshold): array { return ['state' => $state, 'label' => $label]; }//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 * empty, missing, or unparseable allow-list permits NO host — the @@ -703,64 +927,10 @@ private function hasValidScheme(string $url): bool { * @return boolean True only when the host is explicitly allow-listed. */ 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: '' - ); - - $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; + $allowList = new HostAllowList(appConfig: $this->settings->appConfig, configKey: self::CONFIG_KEY_ALLOWED_HOSTS); + 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 +960,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 +997,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 +1009,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..12bba33aa 100644 --- a/lib/Service/MetadataService.php +++ b/lib/Service/MetadataService.php @@ -108,9 +108,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 +118,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); @@ -143,7 +138,7 @@ public function createFieldDefinition( $now = (new DateTime())->format(format: 'c'); $field = new MetadataField(); $requiredFlag = 0; - if ($required === 1) { + if ($settings['required'] === 1) { $requiredFlag = 1; } @@ -155,7 +150,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 +185,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: 'c')); + // 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 +387,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 +600,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 (string)$uuid; + return self::rowUuid(dashboard: $dashboard); + }//end extractUuid() + + /** + * 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 +708,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 +718,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 +754,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 +904,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 +916,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 +949,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 +970,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/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/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..fd3dbfc77 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. @@ -663,39 +849,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 +970,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 +980,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 +1002,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 +1022,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..a47ccdc84 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,12 +119,7 @@ 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; } @@ -134,7 +128,35 @@ public function canEditDashboard(string $userId, int $dashboardId): bool { return false; } - $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,19 +238,42 @@ public function canAddWidget(string $userId, int $dashboardId): bool { return false; } + return $this->allowsEditing( + level: $this->resolveAccessLevel(userId: $userId, dashboardId: $dashboardId) + ); + }//end canAddWidget() + + /** + * 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 === null) { - return false; + if ($level === Dashboard::PERMISSION_VIEW_ONLY) { + return 'This dashboard is view-only'; } - return in_array( - needle: $level, - haystack: [ - Dashboard::PERMISSION_ADD_ONLY, - Dashboard::PERMISSION_FULL, - ] - ); - }//end canAddWidget() + 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 +291,27 @@ 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; - } + $level = $this->resolveAccessLevel(userId: $userId, dashboard: $placed->dashboard); - if ($level === Dashboard::PERMISSION_VIEW_ONLY) { - return false; - } + 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 +321,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 +339,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 +366,13 @@ 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) { - return false; - } - - $level = $this->resolveAccessLevel(userId: $userId, dashboard: $dashboard); - if ($level === null) { + $placed = $this->findPlacedWidget(placementId: $placementId); + if ($placed === null) { return false; } - 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() @@ -406,33 +458,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. @@ -447,6 +479,51 @@ public function getEffectivePermissionLevel( ); }//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 +545,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 +577,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 +644,7 @@ public function resolveAccessLevel( ); return $shares[$dashboard->getId()] ?? null; - }//end resolveAccessLevel() + }//end sharedAccessLevel() /** * Verify user owns a dashboard. @@ -540,7 +665,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 +673,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 +699,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 +819,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/PlacementPayloadHydrator.php b/lib/Service/PlacementPayloadHydrator.php index f1321f222..4267e5f2d 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,28 @@ 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 + */ + 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)); + // 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..f6b2b8f81 100644 --- a/lib/Service/PlacementService.php +++ b/lib/Service/PlacementService.php @@ -19,39 +19,54 @@ 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, + ]; + /** * 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 +75,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 +90,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 +104,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); + $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(0); $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 +150,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 ); @@ -181,20 +195,21 @@ 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->placementUpdater->applyDisplayUpdates( + $this->updaters->placementUpdater->applyDisplayUpdates( placement: $placement, data: $data ); - $this->tileUpdater->applyTileUpdates( + $this->updaters->tileUpdater->applyTileUpdates( placement: $placement, data: $data ); - $this->placementUpdater->applyAcknowledgementUpdates( + $this->updaters->placementUpdater->applyAcknowledgementUpdates( placement: $placement, data: $data ); @@ -206,6 +221,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 +348,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..404e011b9 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() /** @@ -240,23 +246,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..62536a603 --- /dev/null +++ b/lib/Service/ProfileFieldService.php @@ -0,0 +1,847 @@ +<?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']; + 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. + */ + 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; + $result[] = $definition; + } + + return $result; + }//end validateDefinitions() + + /** + * 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. + */ + 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'), + ]; + }//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. + */ + 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']); + } + + return trim(string: $item); + }//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[] + */ + 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'] === '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..bc9b8327a 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; @@ -109,24 +112,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 +158,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 +248,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 +357,97 @@ public function revokeShare( public function renderShareContent( string $token, string $ipAddress, + #[\SensitiveParameter] ?string $password = null, ): array { $share = $this->resolveActiveShare(token: $token, ipAddress: $ipAddress); // Password gate. - if ($share->getPasswordHash() !== null) { - if ($password === null || $password === '') { - throw new SharePasswordRequiredException(); - } + if ($this->lacksPassword(share: $share, password: $password) === true) { + throw new SharePasswordRequiredException(); + } - 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 ($this->rejectsPassword(share: $share, password: $password) === true) { + $this->registerPasswordFailure(ipAddress: $ipAddress); + throw new SharePasswordRequiredException(); } + return $this->shareContent(share: $share, visit: new PublicShareVisit(token: $token, ipAddress: $ipAddress)); + }//end renderShareContent() + + /** + * Whether a password-protected share was opened without a password. + * + * @param PublicShare $share The active share. + * @param string|null $password The supplied password. + * + * @return bool True when a password is needed but missing. + */ + private function lacksPassword( + PublicShare $share, + #[\SensitiveParameter] + ?string $password, + ): bool { + return $share->getPasswordHash() !== null && ($password === null || $password === ''); + }//end lacksPassword() + + /** + * Whether a password-protected share was opened with a wrong password. + * + * @param PublicShare $share The active share. + * @param string|null $password The supplied, non-empty password. + * + * @return bool True when the password does not match. + */ + private function rejectsPassword( + PublicShare $share, + #[\SensitiveParameter] + ?string $password, + ): bool { + return $share->getPasswordHash() !== null + && $this->hasher->verify( + message: (string)$password, + hash: (string)$share->getPasswordHash() + ) === false; + }//end rejectsPassword() + + /** + * 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::ACTION_SHARE_PASSWORD, + 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,6 +467,7 @@ public function renderShareContent( */ public function unlockShare( string $token, + #[\SensitiveParameter] string $password, string $ipAddress, ): bool { @@ -341,10 +490,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 +514,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/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/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..35093f52d --- /dev/null +++ b/lib/Service/ReactionDirectory.php @@ -0,0 +1,46 @@ +<?php + +/** + * ReactionDirectory + * + * The app config and the user manager 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 OCP\IAppConfig; +use OCP\IUserManager; + +/** + * The app config and the user manager 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. + */ + public function __construct( + public readonly IAppConfig $appConfig, + public readonly IUserManager $userManager, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/ReactionService.php b/lib/Service/ReactionService.php index ffc4b056f..b060af268 100644 --- a/lib/Service/ReactionService.php +++ b/lib/Service/ReactionService.php @@ -31,8 +31,6 @@ use OCA\LaunchPad\Db\DashboardReactionMapper; 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 +76,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 +116,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 +141,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: '' @@ -418,13 +411,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 +424,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 +439,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/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..a94ec0dfe --- /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 $d): int => $d % 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, $m) !== 1) { + throw new InvalidArgumentException(sprintf('The cron field "%s" is not valid.', $field)); + } + + $step = (int)($m[2] ?? 1); + [$from, $to] = self::cronRange(range: $m[1], bounds: $bounds, stepped: isset($m[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, $m) !== 1) { + return null; + } + + return [(int)$m[1], (int)$m[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..587f1810a --- /dev/null +++ b/lib/Service/Reporting/ReportDefinitions.php @@ -0,0 +1,242 @@ +<?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 = @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/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..8056f0cf7 --- /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; + $at = DateTimeImmutable::createFromInterface($attempt->now); + + if ($attempt->succeeded === true) { + $delivery['status'] = self::STATUS_SUCCESS; + $delivery['deliveredAt'] = $at->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'] = $at->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 $d): string => (string)($d['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/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..50d3e835e 100644 --- a/lib/Service/SetupWizardService.php +++ b/lib/Service/SetupWizardService.php @@ -24,10 +24,9 @@ namespace OCA\LaunchPad\Service; -use InvalidArgumentException; use OCA\LaunchPad\Db\AdminSetting; use OCA\LaunchPad\Db\AdminSettingMapper; -use OCP\App\IAppManager; +use OCA\LaunchPad\Kernel\Contracts\SetupWizardServiceInterface; /** * Service backing the setup wizard state + completion endpoints. @@ -35,49 +34,24 @@ * 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 optional steps 4/5 — when their guarded capability isn't available, * the heuristic returns `'skipped'` so the UI can collapse the step. */ -class SetupWizardService { +class SetupWizardService implements SetupWizardServiceInterface { /** * Total number of wizard steps (REQ-WIZ-002). * * @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 = 6; /** * Constructor. * * @param AdminSettingMapper $settingMapper Admin-setting persistence. - * @param IAppManager $appManager Used to detect the optional - * `groupfolders` Nextcloud - * app for Step 2's gate. */ public function __construct( private readonly AdminSettingMapper $settingMapper, - private readonly IAppManager $appManager, ) { }//end __construct() @@ -86,7 +60,7 @@ 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 6 stays `'pending'` until the admin clicks Finish. * * @return array{complete: bool, currentRecommendedStep: int, stepStatuses: array<int,string>} * The wizard state payload. @@ -124,58 +98,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. * @@ -203,21 +125,15 @@ private function isWizardComplete(): bool { 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 + // Steps 3 (demos) and 4 (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'; @@ -235,12 +151,11 @@ private function computeStepStatuses(bool $complete): array { return [ '1' => 'done', - '2' => $statusStorage, - '3' => $statusGroup, + '2' => $statusGroup, + '3' => 'skipped', '4' => 'skipped', - '5' => 'skipped', - '6' => $statusFooter, - '7' => $statusDone, + '5' => $statusFooter, + '6' => $statusDone, ]; }//end computeStepStatuses() 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..8fe7801ce --- /dev/null +++ b/lib/Service/SharingLimits.php @@ -0,0 +1,186 @@ +<?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 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\AdminSettingKey; +use OCA\LaunchPad\Db\AdminSettingMapper; +use OCA\LaunchPad\Db\DashboardShare; +use OCA\LaunchPad\Exception\ForbiddenException; + +/** + * 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]; + + /** + * 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 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. + * + * @param string $userId The sharer. + * + * @return bool True when no groups are set, or the user is in one of them. + * + * @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 mayShare(string $userId): bool { + $allowed = $this->allowedGroups(); + if ($allowed === []) { + return true; + } + + return array_intersect($allowed, $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() + + /** + * 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..4cbd59610 --- /dev/null +++ b/lib/Service/ShippedTemplateUpdateService.php @@ -0,0 +1,579 @@ +<?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 DateTime; +use OCA\LaunchPad\AppInfo\Application; +use OCA\LaunchPad\Db\Dashboard; +use OCA\LaunchPad\Db\WidgetPlacement; +use OCA\LaunchPad\Exception\TemplateNotInstalledException; +use OCA\LaunchPad\Kernel\Contracts\ShippedTemplateUpdateServiceInterface; +use RuntimeException; +use Throwable; + +/** + * 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 { + /** + * 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 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, + ) { + }//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->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->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->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() + + /** + * 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>} + */ + private 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} + */ + private 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. + */ + private function apply(Dashboard $template, array $plan): void { + $now = (new DateTime())->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/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/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/StoreService.php b/lib/Service/StoreService.php index af51ac181..50ff0d87d 100644 --- a/lib/Service/StoreService.php +++ b/lib/Service/StoreService.php @@ -422,16 +422,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 +437,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/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/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..03be21b7c 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. */ @@ -95,54 +94,23 @@ class TemplateResyncService { /** * 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 PersonalLayerService $personalLayers Drops personal-layer entries for removed placements (REQ-DWMS-001). */ 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 PersonalLayerService $personalLayers, ) { }//end __construct() @@ -177,56 +145,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 + /** + * 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 + ); - return $this->applyResync( - templateId: $templateId, - strategy: $strategy, - actingAdminId: $actingAdminId + $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). @@ -246,10 +259,10 @@ public function resync( */ 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 ); @@ -257,7 +270,7 @@ public function planResync(int $templateId, string $strategy): array { $affectedCount = 0; foreach ($copies as $copy) { - $copyPlacements = $this->placementMapper->findByDashboardId( + $copyPlacements = $this->stores->placementMapper->findByDashboardId( dashboardId: $copy->getId() ); $diff = $this->diffCopy( @@ -316,75 +329,134 @@ 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 + ); + + 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->diffCopy( + templatePlacements: $tally->templatePlacements, + copyPlacements: $this->stores->placementMapper->findByDashboardId(dashboardId: $copy->getId()), + strategy: $tally->strategy + ); + $changed = $this->diffHasChanges(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); + } + }//end resyncCopy() - 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->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 @@ -404,11 +476,11 @@ 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( + $this->stores->placementMapper->insert( entity: $this->cloneTemplatePlacementInto( template: $templatePlacement, dashboardId: $copy->getId() @@ -421,16 +493,16 @@ private function applyDiffToCopy(Dashboard $copy, array $diff): ?string { copy: $pair['copy'], template: $pair['template'] ); - $this->placementMapper->update(entity: $pair['copy']); + $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: [ @@ -500,45 +572,28 @@ private function diffCopy( } $matchedTemplateIds = []; - $toUpdate = []; - $toRemove = []; - $toPreserve = []; + $buckets = [ + '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; + [$bucket, $entry] = $this->classifyCopyPlacement(copy: $cp, templateById: $templateById); + if ($bucket === null) { + // No known origin — a genuinely user-added placement. + $bucket = 'toPreserve'; + if ($strategy === self::STRATEGY_OVERWRITE) { + $bucket = 'toRemove'; + } } - $toPreserve[] = $cp; + $buckets[$bucket][] = $entry; }//end foreach return [ @@ -546,12 +601,52 @@ private function diffCopy( templatePlacements: $templatePlacements, matchedTemplateIds: $matchedTemplateIds ), - 'toUpdate' => $toUpdate, - 'toRemove' => $toRemove, - 'toPreserve' => $toPreserve, + 'toUpdate' => $buckets['toUpdate'], + 'toRemove' => $buckets['toRemove'], + 'toPreserve' => $buckets['toPreserve'], ]; }//end diffCopy() + /** + * 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. + * + * @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}} + * The bucket name (null for a user-added placement) and the entry to put in it. + */ + private function classifyCopyPlacement(WidgetPlacement $copy, array $templateById): array { + $originId = $copy->getTemplatePlacementId(); + if ($originId === null) { + return [null, $copy]; + } + + if (isset($templateById[$originId]) === false) { + return ['toRemove', $copy]; + } + + $template = $templateById[$originId]; + if ($this->placementDiffers(copy: $copy, template: $template) === true) { + return [ + 'toUpdate', + [ + 'copy' => $copy, + 'template' => $template, + ], + ]; + } + + return ['toPreserve', $copy]; + }//end classifyCopyPlacement() + /** * Template placements the copy has no counterpart for — i.e. the * additions a re-sync must make. @@ -784,7 +879,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', @@ -848,29 +943,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 +971,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..8174cc6bd --- /dev/null +++ b/lib/Service/TemplateResyncTally.php @@ -0,0 +1,61 @@ +<?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. + */ + public function __construct( + public readonly array $templatePlacements, + public readonly string $strategy, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/TemplateService.php b/lib/Service/TemplateService.php index b664d023b..d46fae682 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/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. * 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/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..2944b5db5 --- /dev/null +++ b/lib/Service/VideoFileService.php @@ -0,0 +1,202 @@ +<?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\File; +use OCP\Files\IRootFolder; +use OCP\Files\Node; +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. + */ + public function __construct( + private readonly IRootFolder $rootFolder, + private readonly WidgetPlacementMapper $placements, + private readonly IURLGenerator $urls, + ) { + }//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). + * + * @param int $fileId The file id. + * + * @return string NOT_ACCESSIBLE or NOT_FOUND. + */ + private function absentStatus(int $fileId): string { + try { + $node = $this->rootFolder->getFirstNodeById(id: $fileId); + } catch (Throwable) { + $node = null; + } + + if ($node instanceof Node && preg_match(pattern: '#^/[^/]+/files/#', subject: $node->getPath()) === 1) { + 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/VisibilityChecker.php b/lib/Service/VisibilityChecker.php index 64a6b6e8e..85ab21b53 100644 --- a/lib/Service/VisibilityChecker.php +++ b/lib/Service/VisibilityChecker.php @@ -18,11 +18,14 @@ namespace OCA\LaunchPad\Service; +use Closure; use DateTimeInterface; use OCA\LaunchPad\Db\ConditionalRule; /** * Service for checking widget visibility based on conditional rules. + * + * @spec openspec/specs/conditional-visibility/spec.md */ class VisibilityChecker { /** @@ -89,6 +92,26 @@ public function evaluateRuleSet( ?array $groupsOverride = null, ?DateTimeInterface $nowOverride = null, ): array { + $matches = fn (ConditionalRule $rule): bool => $this->ruleEvaluator->evaluateRule( + rule: $rule, + userId: $userId, + groupsOverride: $groupsOverride, + nowOverride: $nowOverride + ) === true; + + return $this->evaluateWith(rules: $rules, matches: $matches); + }//end evaluateRuleSet() + + /** + * Evaluate a rule set with a match predicate: include rules OR-ed (an + * empty include group passes), exclude rules AND-ed. + * + * @param ConditionalRule[] $rules The rules to evaluate. + * @param Closure(ConditionalRule): bool $matches Whether one rule matches. + * + * @return array{visible: bool, matchedIncludeRuleIds: int[], matchedExcludeRuleIds: int[]} + */ + private function evaluateWith(array $rules, Closure $matches): array { $includeRules = $this->filterByType( rules: $rules, isInclude: true @@ -98,36 +121,25 @@ 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 must pass (OR). + $includeIds = $this->matchingRuleIds(rules: $includeRules, matches: $matches); + if ($includeRules !== [] && $includeIds === []) { 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() /** * Filter rules by include/exclude type. @@ -149,55 +161,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. - * - * 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. + * 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. * - * @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. + * @param ConditionalRule[] $rules The rules of one include or exclude group. + * @param callable $matches Whether one rule matches the user. * - * @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..7f6aa2b75 --- /dev/null +++ b/lib/Service/WidgetPlatform.php @@ -0,0 +1,46 @@ +<?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. + */ + public function __construct( + public readonly IManager $dashboardManager, + public readonly IUserSession $userSession, + ) { + }//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..0abec0fe0 100644 --- a/lib/Service/WidgetService.php +++ b/lib/Service/WidgetService.php @@ -19,50 +19,96 @@ 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 { /** * 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)); + } + + if ($widgetType === 'map') { + (new MapContentValidator())->validate(content: $content); + return; + } + + if ($widgetType === 'links') { + (new LinksContentValidator())->validate(content: $content); + return; + } + + if ($widgetType === 'text') { + (new TextTableValidator())->validate(content: $content); + return; + } + + if ($widgetType === 'iframe') { + $this->validateIframeHost(content: $content); + return; + } + if ($widgetType !== 'menu') { return; } @@ -74,7 +120,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 +153,17 @@ 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(); + $widgets = $this->platform->dashboardManager->getWidgets(); $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 ); @@ -126,9 +195,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 +210,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 +254,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/Settings/AdminFormState.php b/lib/Settings/AdminFormState.php new file mode 100644 index 000000000..11432d727 --- /dev/null +++ b/lib/Settings/AdminFormState.php @@ -0,0 +1,113 @@ +<?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 + */ + 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() + ) + ->apply(); + }//end provide() +}//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..c672e39eb 100644 --- a/lib/Settings/LaunchPadAdmin.php +++ b/lib/Settings/LaunchPadAdmin.php @@ -26,13 +26,7 @@ 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; @@ -43,28 +37,17 @@ 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 + * @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). - * @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( private readonly IInitialState $initialState, private readonly IGroupManager $groupManager, - private readonly WidgetService $widgetService, - private readonly AdminSettingMapper $settingMapper, + private readonly AdminPageSources $sources, private readonly AdminSettingsService $settingsService, - private readonly DashboardService $dashboardService, - private readonly FileService $fileService, ) { }//end __construct() @@ -88,49 +71,12 @@ public function getForm(): TemplateResponse { 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( + (new AdminFormState( initialState: $this->initialState, - page: Page::ADMIN - )) - ->setAllGroups($allGroups) - ->setConfiguredGroups($configuredGroups) - ->setWidgets($this->widgetService->getAvailableWidgets()) - ->setAllowUserDashboards($allowUserDashboards) - ->setLinkCreateFileExtensions( - $this->fileService->getAllowedExtensions() - ) - ->apply(); + groupManager: $this->groupManager, + sources: $this->sources, + settingsService: $this->settingsService + ))->provide(); return new TemplateResponse( appName: Application::APP_ID, diff --git a/lib/Settings/launchpad_mock_register.json b/lib/Settings/launchpad_mock_register.json index 125bbe3e9..fc5ac6ab9 100644 --- a/lib/Settings/launchpad_mock_register.json +++ b/lib/Settings/launchpad_mock_register.json @@ -354,6 +354,762 @@ "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": "saved_view", + "slug": "saved-view-voorbeeld-name-1-1" + }, + "dashboardId": "00000000-0000-4000-8000-000000000000", + "name": "Voorbeeld Name 1", + "filters": [ + { + "dimension": "Voorbeeld Dimension 1", + "operator": "eq", + "source": "userExplicit", + "sourceWidgetId": "Voorbeeld Sourcewidgetid 1", + "pinned": false, + "value": "Voorbeeld Value 1" + } + ], + "createdBy": "Voorbeeld Createdby 1", + "description": "Voorbeeld Description 1", + "isShared": false, + "sharedWith": [ + "Voorbeeld Sharedwith 1" + ], + "createdAt": "2026-03-01T09:00:00+00:00" + }, + { + "@self": { + "register": "launchpad", + "schema": "saved_view", + "slug": "saved-view-voorbeeld-name-2-2" + }, + "dashboardId": "00000000-0000-4000-8000-000000000001", + "name": "Voorbeeld Name 2", + "filters": [ + { + "dimension": "Voorbeeld Dimension 2", + "operator": "in", + "source": "widgetClick", + "sourceWidgetId": "Voorbeeld Sourcewidgetid 2", + "pinned": false, + "value": "Voorbeeld Value 2" + } + ], + "createdBy": "Voorbeeld Createdby 2", + "description": "Voorbeeld Description 2", + "isShared": false, + "sharedWith": [ + "Voorbeeld Sharedwith 2" + ], + "createdAt": "2026-03-02T09:00:00+00:00" + }, + { + "@self": { + "register": "launchpad", + "schema": "saved_view", + "slug": "saved-view-voorbeeld-name-3-3" + }, + "dashboardId": "00000000-0000-4000-8000-000000000002", + "name": "Voorbeeld Name 3", + "filters": [ + { + "dimension": "Voorbeeld Dimension 3", + "operator": "between", + "source": "urlBootstrap", + "sourceWidgetId": "Voorbeeld Sourcewidgetid 3", + "pinned": false, + "value": "Voorbeeld Value 3" + } + ], + "createdBy": "Voorbeeld Createdby 3", + "description": "Voorbeeld Description 3", + "isShared": false, + "sharedWith": [ + "Voorbeeld Sharedwith 3" + ], + "createdAt": "2026-03-03T09:00:00+00:00" + }, + { + "@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..96f0cd33c --- /dev/null +++ b/lib/Settings/register.d/drill-down-cross-widget-filter.json @@ -0,0 +1,254 @@ +{ + "components": { + "registers": { + "launchpad": { + "schemas": [ + "saved_view", + "filter_event" + ] + } + }, + "schemas": { + "saved_view": { + "slug": "saved_view", + "icon": "BookmarkOutline", + "version": "1.0.0", + "title": "Saved view", + "description": "A named set of dashboard filters that can be applied in one click, kept for one dashboard.", + "type": "object", + "x-openregister": { + "active": true, + "hardDelete": false, + "searchable": true, + "mailEnabled": false + }, + "required": [ + "dashboardId", + "name", + "filters", + "createdBy" + ], + "properties": { + "dashboardId": { + "type": "string", + "format": "uuid", + "title": "Dashboard", + "description": "The dashboard the view belongs to." + }, + "name": { + "type": "string", + "title": "Name", + "description": "The name in the saved views list.", + "minLength": 1, + "maxLength": 255 + }, + "description": { + "type": "string", + "title": "Description", + "description": "What the view shows." + }, + "filters": { + "type": "array", + "title": "Filters", + "description": "The filter clauses the view applies.", + "items": { + "type": "object", + "required": [ + "dimension", + "operator" + ], + "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 + }, + "value": { + "title": "Value", + "description": "A scalar, a list, or a [low, high] pair, by operator." + } + } + } + }, + "isShared": { + "type": "boolean", + "title": "Shared", + "description": "Whether other users may apply the view.", + "default": false + }, + "sharedWith": { + "type": "array", + "title": "Shared with", + "description": "The users and groups it is shared with, when shared.", + "items": { + "type": "string" + } + }, + "createdBy": { + "type": "string", + "title": "Created by", + "description": "The user who saved the view." + }, + "createdAt": { + "type": "string", + "format": "date-time", + "title": "Created at", + "description": "When the view was saved." + } + } + }, + "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..7d3621a92 --- /dev/null +++ b/lib/Support/WidgetTypeList.php @@ -0,0 +1,112 @@ +<?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 array_values(array_unique(array_merge(self::DEFAULT_RULE_DASHBOARD_WIDGETS, $this->types()))); + }//end defaultRuleWidgets() + + /** + * 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..86b7d5bae 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"], + "announcement.read": ["admin", "@all"], + "announcement.manage": ["admin", "@all"], + "announcement.follow": ["admin", "@all"], + "announcement.comment": ["admin", "@all"], "admin-org-navigation.get-org-navigation": ["admin"], "admin-org-navigation.get-position": ["admin"], "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..468e7c026 100644 --- a/lib/widget-types.json +++ b/lib/widget-types.json @@ -8,10 +8,16 @@ "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-tiles", + "attention", "calendar", "chart", "clock", + "colleague-activity", + "communities", "container", "delta", "divider", @@ -34,6 +40,7 @@ "spend-analytics", "stat", "stats-block", + "status-report", "table", "text", "tile", 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..cb1904007 --- /dev/null +++ b/openapi.json @@ -0,0 +1,15225 @@ +{ + "openapi": "3.1.0", + "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": [] + } + ], + "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": "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": "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": "iframe", + "description": "Controller for the `iframe` widget's allow-list validation." + }, + { + "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": "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": "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": "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." + } + ], + "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/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/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/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`." + }, + "startPageWithoutNavigation": { + "type": [ + "boolean", + "null" + ], + "description": "Dashboard view without the navigation panel (REQ-SHELL-009)." + }, + "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/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\", 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'` or `'merge'`." + }, + "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": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "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": {} + } + } + }, + "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": { + "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": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/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": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/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": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/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": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "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": {} + } + } + }, + "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": { + "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": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/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": {} + } + } + }, + "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" + } + } + }, + "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": {} + } + } + }, + "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" + } + } + } + }, + "/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": {} + } + } + }, + "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" + } + } + }, + "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": {} + } + } + }, + "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" + } + } + } + }, + "/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": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/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. 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." + } + } + } + } + } + }, + "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." + } + } + } + } + } + }, + "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 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." + } + } + } + } + } + } + }, + "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" + } + } + }, + "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": {} + } + } + }, + "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.", + "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" + } + } + } + }, + "/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" + } + } + } + }, + "/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. 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}`." + } + } + } + } + } + }, + "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" + } + } + } + }, + "/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": {}, + "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" + } + } + } + } + }, + "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/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/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/search-ai-prefix-shortcuts/design.md b/openspec/changes/archive/2026-09-30-search-ai-prefix-shortcuts/design.md similarity index 79% rename from openspec/changes/search-ai-prefix-shortcuts/design.md rename to openspec/changes/archive/2026-09-30-search-ai-prefix-shortcuts/design.md index fdc114c03..cba698c48 100644 --- a/openspec/changes/search-ai-prefix-shortcuts/design.md +++ b/openspec/changes/archive/2026-09-30-search-ai-prefix-shortcuts/design.md @@ -36,3 +36,10 @@ Only administrators edit the list. Every user can use it. The query leaves the b - 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/widgets-people-expertise-and-fields/design.md b/openspec/changes/archive/2026-09-30-widgets-people-expertise-and-fields/design.md similarity index 78% rename from openspec/changes/widgets-people-expertise-and-fields/design.md rename to openspec/changes/archive/2026-09-30-widgets-people-expertise-and-fields/design.md index 01eba1f22..b9413e933 100644 --- a/openspec/changes/widgets-people-expertise-and-fields/design.md +++ b/openspec/changes/archive/2026-09-30-widgets-people-expertise-and-fields/design.md @@ -51,3 +51,13 @@ Demo installs define "Kantoorlocatie" (text, self), "Kostenplaats" (text, self, - 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/widgets-people-expertise-and-fields/tasks.md b/openspec/changes/archive/2026-09-30-widgets-people-expertise-and-fields/tasks.md similarity index 53% rename from openspec/changes/widgets-people-expertise-and-fields/tasks.md rename to openspec/changes/archive/2026-09-30-widgets-people-expertise-and-fields/tasks.md index 833f431f1..fe8bf7a24 100644 --- a/openspec/changes/widgets-people-expertise-and-fields/tasks.md +++ b/openspec/changes/archive/2026-09-30-widgets-people-expertise-and-fields/tasks.md @@ -2,21 +2,21 @@ ## 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. +- [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 -- [ ] 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. +- [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 -- [ ] 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. +- [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/keyboard-accessible-widget-repositioning/tasks.md b/openspec/changes/archive/2026-10-07-keyboard-accessible-widget-repositioning/tasks.md similarity index 59% rename from openspec/changes/keyboard-accessible-widget-repositioning/tasks.md rename to openspec/changes/archive/2026-10-07-keyboard-accessible-widget-repositioning/tasks.md index c32c15de8..feba36b4c 100644 --- a/openspec/changes/keyboard-accessible-widget-repositioning/tasks.md +++ b/openspec/changes/archive/2026-10-07-keyboard-accessible-widget-repositioning/tasks.md @@ -1,15 +1,26 @@ # 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 -- [ ] Task 1: In `src/components/DashboardGrid.vue`, add `role="group"`, +- [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). -- [ ] Task 2: Add `:focus-visible` CSS to `.grid-stack-item` using NC +- [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. -- [ ] Task 3: Wire `keydown.enter` and `keydown.space` on the grid item (in +- [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 @@ -17,11 +28,11 @@ ## Move action -- [ ] Task 4: In `src/components/Widgets/WidgetContextMenu.vue`, add a new +- [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`. -- [ ] Task 5: Create `src/components/Widgets/WidgetMovePanel.vue` — a +- [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`. @@ -33,29 +44,29 @@ `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 +- [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. -- [ ] Task 7: Wire `DashboardGrid.vue`'s `move` event (from the context +- [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 -- [ ] Task 8: Add a Vitest test for `WidgetMovePanel.vue` asserting arrow +- [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`. -- [ ] Task 9: Add a Vitest test for `WidgetContextMenu.vue` asserting the +- [x] 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` +- [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. -- [ ] Task 11: Add an axe-core (or equivalent) accessibility check to the +- [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/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 similarity index 99% rename from openspec/changes/store-plane-dashboard-sharing/specs/dashboard-store/spec.md rename to openspec/changes/archive/2026-10-07-store-plane-dashboard-sharing/specs/dashboard-store/spec.md index e8da25dc2..8f14239a3 100644 --- a/openspec/changes/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 @@ -27,7 +27,7 @@ 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 +## ADDED Requirements ### Requirement: REQ-STORE-001 The store routes MUST exist wherever the store page is declared 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/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 similarity index 60% rename from openspec/changes/fix-people-widget-unbounded-user-scan/specs/people-widget/spec.md rename to openspec/changes/archive/2026-10-09-fix-people-widget-unbounded-user-scan/specs/people-widget/spec.md index 2aad4cbdd..1086fdcd7 100644 --- a/openspec/changes/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 @@ -6,16 +6,19 @@ status: draft # People Widget — Bounded Candidate Resolution -## MODIFIED Requirements +## ADDED Requirements -### Requirement: REQ-PPL-007 Candidate resolution MUST be bounded by the requested page +### Requirement: Candidate resolution is bounded by the requested page (REQ-PPL-013) -`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. +@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 @@ -23,7 +26,7 @@ accounts on the instance. - **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 +- **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 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/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 similarity index 80% rename from openspec/changes/grid-bottom-append-placement/specs/grid-layout/spec.md rename to openspec/changes/archive/2026-10-09-grid-bottom-append-placement/specs/grid-layout/spec.md index 25ddd4a72..ccc1a0655 100644 --- a/openspec/changes/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 @@ -62,3 +62,17 @@ This requirement deliberately replaces the former "GridStack auto-position + top - **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/grid-bottom-append-placement/tasks.md b/openspec/changes/archive/2026-10-09-grid-bottom-append-placement/tasks.md similarity index 97% rename from openspec/changes/grid-bottom-append-placement/tasks.md rename to openspec/changes/archive/2026-10-09-grid-bottom-append-placement/tasks.md index 92d99dc0b..56f4e52da 100644 --- a/openspec/changes/grid-bottom-append-placement/tasks.md +++ b/openspec/changes/archive/2026-10-09-grid-bottom-append-placement/tasks.md @@ -5,7 +5,7 @@ - [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 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 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/retire-groupfolder-storage-backend/tasks.md b/openspec/changes/archive/2026-10-09-retire-groupfolder-storage-backend/tasks.md similarity index 82% rename from openspec/changes/retire-groupfolder-storage-backend/tasks.md rename to openspec/changes/archive/2026-10-09-retire-groupfolder-storage-backend/tasks.md index 1c9fceb8c..4a2e83b7b 100644 --- a/openspec/changes/retire-groupfolder-storage-backend/tasks.md +++ b/openspec/changes/archive/2026-10-09-retire-groupfolder-storage-backend/tasks.md @@ -9,7 +9,11 @@ - [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` + + +## 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 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/adopt-connection-registry/tasks.md b/openspec/changes/archive/2026-11-12-adopt-connection-registry/tasks.md similarity index 85% rename from openspec/changes/adopt-connection-registry/tasks.md rename to openspec/changes/archive/2026-11-12-adopt-connection-registry/tasks.md index 8bb96e810..755b4beac 100644 --- a/openspec/changes/adopt-connection-registry/tasks.md +++ b/openspec/changes/archive/2026-11-12-adopt-connection-registry/tasks.md @@ -29,4 +29,4 @@ ## 5. After an instance runs both apps -- [ ] 5.1 Run the e2e spec against an instance with launchpad and integriq, then archive this change. +- [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/bbv-programma-templates/proposal.md b/openspec/changes/archive/2026-11-12-bbv-programma-templates/proposal.md similarity index 96% rename from openspec/changes/bbv-programma-templates/proposal.md rename to openspec/changes/archive/2026-11-12-bbv-programma-templates/proposal.md index 08987c912..d7269c6f4 100644 --- a/openspec/changes/bbv-programma-templates/proposal.md +++ b/openspec/changes/archive/2026-11-12-bbv-programma-templates/proposal.md @@ -1,3 +1,5 @@ +> 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 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/2026-04-30-dashboard-sharing-followups/tasks.md b/openspec/changes/archive/2026-11-12-dashboard-sharing-followups-stale-copy/tasks.md similarity index 96% rename from openspec/changes/2026-04-30-dashboard-sharing-followups/tasks.md rename to openspec/changes/archive/2026-11-12-dashboard-sharing-followups-stale-copy/tasks.md index 53e42a0c1..df33b1760 100644 --- a/openspec/changes/2026-04-30-dashboard-sharing-followups/tasks.md +++ b/openspec/changes/archive/2026-11-12-dashboard-sharing-followups-stale-copy/tasks.md @@ -99,3 +99,5 @@ - [ ] 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/dashboard-switcher/tasks.md b/openspec/changes/archive/2026-11-12-dashboard-switcher/tasks.md similarity index 96% rename from openspec/changes/dashboard-switcher/tasks.md rename to openspec/changes/archive/2026-11-12-dashboard-switcher/tasks.md index 2eb6ce963..8ba001b66 100644 --- a/openspec/changes/dashboard-switcher/tasks.md +++ b/openspec/changes/archive/2026-11-12-dashboard-switcher/tasks.md @@ -81,3 +81,5 @@ Changelog entry per Task 48. Inline component docstring (JSDoc) documenting prop ## 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/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 similarity index 98% rename from openspec/changes/fix-group-dashboard-admin-auth-attribute/specs/dashboards/spec.md rename to openspec/changes/archive/2026-11-12-fix-group-dashboard-admin-auth-attribute/specs/dashboards/spec.md index 4c86d69b5..096ea5f8e 100644 --- a/openspec/changes/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 @@ -6,7 +6,7 @@ status: draft # Dashboards — Group-Shared CRUD Authorization Attribute -## MODIFIED Requirements +## ADDED Requirements ### Requirement: REQ-DASH-014 Group-shared dashboard CRUD is admin-only and declared as such diff --git a/openspec/changes/fix-group-dashboard-admin-auth-attribute/tasks.md b/openspec/changes/archive/2026-11-12-fix-group-dashboard-admin-auth-attribute/tasks.md similarity index 69% rename from openspec/changes/fix-group-dashboard-admin-auth-attribute/tasks.md rename to openspec/changes/archive/2026-11-12-fix-group-dashboard-admin-auth-attribute/tasks.md index 254902261..ca3fa8e67 100644 --- a/openspec/changes/fix-group-dashboard-admin-auth-attribute/tasks.md +++ b/openspec/changes/archive/2026-11-12-fix-group-dashboard-admin-auth-attribute/tasks.md @@ -2,51 +2,51 @@ ## DashboardApiController -- [ ] Task 1: In `lib/Controller/DashboardApiController.php`, import +- [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. -- [ ] Task 2: Replace `#[NoAdminRequired]` with +- [x] Task 2: Replace `#[NoAdminRequired]` with `#[AuthorizedAdminSetting(Application::APP_ID)]` on `createGroup()` (currently line 916). -- [ ] Task 3: Replace `#[NoAdminRequired]` with +- [x] Task 3: Replace `#[NoAdminRequired]` with `#[AuthorizedAdminSetting(Application::APP_ID)]` on `updateGroup()` (currently line 1026). -- [ ] Task 4: Replace `#[NoAdminRequired]` with +- [x] Task 4: Replace `#[NoAdminRequired]` with `#[AuthorizedAdminSetting(Application::APP_ID)]` on `deleteGroup()` (currently line 1090). -- [ ] Task 5: Replace `#[NoAdminRequired]` with +- [x] Task 5: Replace `#[NoAdminRequired]` with `#[AuthorizedAdminSetting(Application::APP_ID)]` on `setGroupDefault()` (currently line 1143). -- [ ] Task 6: Remove the redundant in-body `$this->dashboardService->isAdmin(...)` +- [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. -- [ ] Task 7: Update the docblocks above `createGroup()` (lines ~902-905), +- [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. -- [ ] Task 8: Confirm `$this->dashboardService->isAdmin()` still has at +- [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 -- [ ] Task 9: In `lib/Controller/AdminSettingsController.php`, import +- [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`). -- [ ] Task 10: Add `#[AuthorizedAdminSetting(Application::APP_ID)]` above +- [x] Task 10: Add `#[AuthorizedAdminSetting(Application::APP_ID)]` above `listGroups()` (currently line 89). -- [ ] Task 11: Add `#[AuthorizedAdminSetting(Application::APP_ID)]` above +- [x] Task 11: Add `#[AuthorizedAdminSetting(Application::APP_ID)]` above `updateGroupOrder()` (currently line 162). -- [ ] Task 12: Leave the existing private `assertAdmin()` helper and its +- [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 @@ -54,17 +54,19 @@ ## Verification -- [ ] Task 13: Run `hydra-gate-semantic-auth` (or the equivalent +- [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. -- [ ] Task 14: Re-run the existing PHPUnit suite for +- [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. -- [ ] Task 15: Manually verify via curl/Newman that a non-admin +- [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/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 similarity index 99% rename from openspec/changes/harden-activity-debounce-cache-reliability/specs/activity-feed-integration/spec.md rename to openspec/changes/archive/2026-11-12-harden-activity-debounce-cache-reliability/specs/activity-feed-integration/spec.md index 3102f4d4f..97abdeea4 100644 --- a/openspec/changes/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 @@ -6,7 +6,7 @@ status: draft # Activity Feed Integration — Debounce Backend Reliability -## MODIFIED Requirements +## ADDED Requirements ### Requirement: REQ-ACT-007 Reaction debounce holds regardless of deployment topology diff --git a/openspec/changes/harden-activity-debounce-cache-reliability/tasks.md b/openspec/changes/archive/2026-11-12-harden-activity-debounce-cache-reliability/tasks.md similarity index 74% rename from openspec/changes/harden-activity-debounce-cache-reliability/tasks.md rename to openspec/changes/archive/2026-11-12-harden-activity-debounce-cache-reliability/tasks.md index 841d5873d..eacd6818d 100644 --- a/openspec/changes/harden-activity-debounce-cache-reliability/tasks.md +++ b/openspec/changes/archive/2026-11-12-harden-activity-debounce-cache-reliability/tasks.md @@ -2,11 +2,11 @@ ## DebounceHelper -- [ ] Task 1: In `lib/Activity/DebounceHelper.php`, add a constructor +- [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. -- [ ] Task 2: In `claim()` (currently lines 142-167), when +- [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: @@ -14,38 +14,40 @@ `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 +- [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). -- [ ] Task 4: Update the class docblock (lines 14-17) and the `claim()` +- [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 -- [ ] Task 5: In `lib/AppInfo/Application.php` (lines 98-107), change the +- [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). -- [ ] Task 6: Update the inline comment at line 98 ("register +- [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 -- [ ] Task 7: Add a PHPUnit test that constructs `DebounceHelper` with a +- [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. -- [ ] Task 8: Add a regression test that simulates "APCu absent, cache +- [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. -- [ ] Task 9: Re-run the existing `activity-feed-integration` PHPUnit +- [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/launchpad-ai-dashboard-assistant/proposal.md b/openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/proposal.md similarity index 93% rename from openspec/changes/launchpad-ai-dashboard-assistant/proposal.md rename to openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/proposal.md index d9399305a..c4ae2d474 100644 --- a/openspec/changes/launchpad-ai-dashboard-assistant/proposal.md +++ b/openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/proposal.md @@ -1,3 +1,5 @@ +> 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. 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/launchpad-enterprise-security-access/proposal.md b/openspec/changes/archive/2026-11-12-launchpad-enterprise-security-access/proposal.md similarity index 95% rename from openspec/changes/launchpad-enterprise-security-access/proposal.md rename to openspec/changes/archive/2026-11-12-launchpad-enterprise-security-access/proposal.md index 4077929d0..47e9cd608 100644 --- a/openspec/changes/launchpad-enterprise-security-access/proposal.md +++ b/openspec/changes/archive/2026-11-12-launchpad-enterprise-security-access/proposal.md @@ -1,3 +1,5 @@ +> 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. 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/launchpad-file-access-widget/proposal.md b/openspec/changes/archive/2026-11-12-launchpad-file-access-widget/proposal.md similarity index 95% rename from openspec/changes/launchpad-file-access-widget/proposal.md rename to openspec/changes/archive/2026-11-12-launchpad-file-access-widget/proposal.md index a95aaeb72..989b61841 100644 --- a/openspec/changes/launchpad-file-access-widget/proposal.md +++ b/openspec/changes/archive/2026-11-12-launchpad-file-access-widget/proposal.md @@ -1,3 +1,5 @@ +> 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. 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/launchpad-meeting-calendar-actions/.openspec.yaml b/openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/.openspec.yaml similarity index 100% rename from openspec/changes/launchpad-meeting-calendar-actions/.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/launchpad-meeting-calendar-actions/proposal.md b/openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/proposal.md similarity index 95% rename from openspec/changes/launchpad-meeting-calendar-actions/proposal.md rename to openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/proposal.md index 6937b331b..1162ab70d 100644 --- a/openspec/changes/launchpad-meeting-calendar-actions/proposal.md +++ b/openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/proposal.md @@ -1,3 +1,5 @@ +> Superseded: meeting notes belong to decidiq or Calendar; LaunchPad shows the calendar (row w-calendar). Decision 399. + # Meeting and calendar actions from dashboard ## Why 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/launchpad-mobile-remote-access/proposal.md b/openspec/changes/archive/2026-11-12-launchpad-mobile-remote-access/proposal.md similarity index 98% rename from openspec/changes/launchpad-mobile-remote-access/proposal.md rename to openspec/changes/archive/2026-11-12-launchpad-mobile-remote-access/proposal.md index 29e43a8a8..395a93660 100644 --- a/openspec/changes/launchpad-mobile-remote-access/proposal.md +++ b/openspec/changes/archive/2026-11-12-launchpad-mobile-remote-access/proposal.md @@ -2,6 +2,8 @@ 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 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/public-dashboard-publication/.openspec.yaml b/openspec/changes/archive/2026-11-12-public-dashboard-publication/.openspec.yaml similarity index 100% rename from openspec/changes/public-dashboard-publication/.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/public-dashboard-publication/proposal.md b/openspec/changes/archive/2026-11-12-public-dashboard-publication/proposal.md similarity index 96% rename from openspec/changes/public-dashboard-publication/proposal.md rename to openspec/changes/archive/2026-11-12-public-dashboard-publication/proposal.md index 533db3655..b904d3cf1 100644 --- a/openspec/changes/public-dashboard-publication/proposal.md +++ b/openspec/changes/archive/2026-11-12-public-dashboard-publication/proposal.md @@ -1,3 +1,5 @@ +> 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. 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/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 similarity index 98% rename from openspec/changes/add-dashboard-sharing-e2e-coverage/specs/dashboard-sharing/spec.md rename to openspec/changes/archive/2026-11-17-add-dashboard-sharing-e2e-coverage/specs/dashboard-sharing/spec.md index ec74d34f5..89899cfb0 100644 --- a/openspec/changes/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 @@ -4,6 +4,8 @@ ### 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 diff --git a/openspec/changes/add-dashboard-sharing-e2e-coverage/tasks.md b/openspec/changes/archive/2026-11-17-add-dashboard-sharing-e2e-coverage/tasks.md similarity index 64% rename from openspec/changes/add-dashboard-sharing-e2e-coverage/tasks.md rename to openspec/changes/archive/2026-11-17-add-dashboard-sharing-e2e-coverage/tasks.md index f6e678d66..b44f8ed63 100644 --- a/openspec/changes/add-dashboard-sharing-e2e-coverage/tasks.md +++ b/openspec/changes/archive/2026-11-17-add-dashboard-sharing-e2e-coverage/tasks.md @@ -2,23 +2,23 @@ ## New e2e spec -- [ ] Task 1: Create `tests/e2e/dashboard-sharing.spec.ts` following the +- [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). -- [ ] Task 2: Test 1 — "Owner adds a user share": create/open a personal +- [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`. -- [ ] Task 3: Test 2 — "Owner changes a share's permission level": with an +- [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. -- [ ] Task 4: Test 3 — "Owner removes a share": click the remove-share +- [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. -- [ ] Task 5: Test 4 (if feasible with the test fixture) — "Recipient sees +- [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). @@ -29,10 +29,10 @@ ## Spec annotation cleanup -- [ ] Task 6: In `openspec/specs/dashboard-sharing/spec.md`, remove the +- [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). -- [ ] Task 7: For each `### Requirement:` in the same spec, add either a +- [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 @@ -41,9 +41,11 @@ ## Verification -- [ ] Task 8: Run `npx playwright test dashboard-sharing` and confirm all +- [x] 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 +- [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/fix-l10n-domain-mismatch-mydash-calls/tasks.md b/openspec/changes/archive/2026-11-17-fix-l10n-domain-mismatch-mydash-calls/tasks.md similarity index 60% rename from openspec/changes/fix-l10n-domain-mismatch-mydash-calls/tasks.md rename to openspec/changes/archive/2026-11-17-fix-l10n-domain-mismatch-mydash-calls/tasks.md index 77aec0d81..044dd2196 100644 --- a/openspec/changes/fix-l10n-domain-mismatch-mydash-calls/tasks.md +++ b/openspec/changes/archive/2026-11-17-fix-l10n-domain-mismatch-mydash-calls/tasks.md @@ -2,19 +2,21 @@ ## Verify scope -- [ ] Task 1: Re-run `grep -rnoP "(?<![A-Za-z_])t\('mydash'" src --include=*.vue --include=*.js` and +- [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). + stale count if other work has landed in the meantime). Rerun 9 Oct 2026 on + build/openspecs-1: 0 calls. ## Fix call sites -- [ ] Task 2: In each of the 20 affected files, change every +- [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. + 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) @@ -35,32 +37,41 @@ - `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 +- [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. + 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 -- [ ] Task 4: Add a lint guard (new script under `scripts/`, e.g. +- [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. -- [ ] Task 5: Add the new script to `package.json`'s `lint` script + `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 -- [ ] 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: +- [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. -- [ ] Task 8: Re-run the Vitest suite (`npm run test`) — component tests + 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/launchpad-manifest-tier-3/tasks.md b/openspec/changes/archive/2026-11-17-launchpad-manifest-tier-3/tasks.md similarity index 65% rename from openspec/changes/launchpad-manifest-tier-3/tasks.md rename to openspec/changes/archive/2026-11-17-launchpad-manifest-tier-3/tasks.md index 508880547..759ef3a8d 100644 --- a/openspec/changes/launchpad-manifest-tier-3/tasks.md +++ b/openspec/changes/archive/2026-11-17-launchpad-manifest-tier-3/tasks.md @@ -43,9 +43,9 @@ - [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. +- [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. -## Left for later, deliberately +## 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. +- 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/cleanup-category-boolean-getter-name/proposal.md b/openspec/changes/archive/2026-11-19-cleanup-category-boolean-getter-name/proposal.md similarity index 96% rename from openspec/changes/cleanup-category-boolean-getter-name/proposal.md rename to openspec/changes/archive/2026-11-19-cleanup-category-boolean-getter-name/proposal.md index be09e9826..ecaa45955 100644 --- a/openspec/changes/cleanup-category-boolean-getter-name/proposal.md +++ b/openspec/changes/archive/2026-11-19-cleanup-category-boolean-getter-name/proposal.md @@ -1,7 +1,7 @@ # Rename `CleanupCategoryInterface::getSafeToPurgeAutomatically()` to `isSafeToPurgeAutomatically()` -> **STATUS: RAISED FOR HUMAN DECISION — NOT APPROVED, NOT STARTED.** -> Spec-first by design. No code has been changed. +> **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 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/governance-rest-api-reference/design.md b/openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md similarity index 60% rename from openspec/changes/governance-rest-api-reference/design.md rename to openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md index fc80756bf..9ee55cf9f 100644 --- a/openspec/changes/governance-rest-api-reference/design.md +++ b/openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md @@ -16,9 +16,11 @@ Read at development `d767c282`. 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`. 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. +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 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/governance-rest-api-reference/tasks.md b/openspec/changes/archive/2026-11-19-governance-rest-api-reference/tasks.md similarity index 61% rename from openspec/changes/governance-rest-api-reference/tasks.md rename to openspec/changes/archive/2026-11-19-governance-rest-api-reference/tasks.md index f071489a6..1fc14e786 100644 --- a/openspec/changes/governance-rest-api-reference/tasks.md +++ b/openspec/changes/archive/2026-11-19-governance-rest-api-reference/tasks.md @@ -1,8 +1,8 @@ # 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. +- [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/launcher-tile-open-behaviour/specs/tiles/spec.md b/openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md similarity index 95% rename from openspec/changes/launcher-tile-open-behaviour/specs/tiles/spec.md rename to openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md index 4013bd63e..c1e20e838 100644 --- a/openspec/changes/launcher-tile-open-behaviour/specs/tiles/spec.md +++ b/openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md @@ -59,13 +59,13 @@ The panel MUST frame a Nextcloud address on the same instance, and MUST frame an - **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" +- **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 "Ask an administrator to allow this site for embedding" +- **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) 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/responsehelper-instance-api/proposal.md b/openspec/changes/archive/2026-11-19-responsehelper-instance-api/proposal.md similarity index 95% rename from openspec/changes/responsehelper-instance-api/proposal.md rename to openspec/changes/archive/2026-11-19-responsehelper-instance-api/proposal.md index b0d498e0d..22933bbfa 100644 --- a/openspec/changes/responsehelper-instance-api/proposal.md +++ b/openspec/changes/archive/2026-11-19-responsehelper-instance-api/proposal.md @@ -1,8 +1,10 @@ # 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. +> **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 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/mcp-tool-surface/design.md b/openspec/changes/archive/2026-11-21-mcp-tool-surface/design.md similarity index 99% rename from openspec/changes/mcp-tool-surface/design.md rename to openspec/changes/archive/2026-11-21-mcp-tool-surface/design.md index f44389818..b7eab4fd7 100644 --- a/openspec/changes/mcp-tool-surface/design.md +++ b/openspec/changes/archive/2026-11-21-mcp-tool-surface/design.md @@ -25,7 +25,7 @@ The fleet reference is `decidesk/lib/Mcp/` — `DecideskToolProvider` (dispatche ### 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`. +**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:** 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/mcp-tool-surface/proposal.md b/openspec/changes/archive/2026-11-21-mcp-tool-surface/proposal.md similarity index 97% rename from openspec/changes/mcp-tool-surface/proposal.md rename to openspec/changes/archive/2026-11-21-mcp-tool-surface/proposal.md index 28696318b..ad05e8b39 100644 --- a/openspec/changes/mcp-tool-surface/proposal.md +++ b/openspec/changes/archive/2026-11-21-mcp-tool-surface/proposal.md @@ -12,7 +12,7 @@ The fleet mechanism is proven: decidesk ships the reference implementation (`dec ## 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}`. +- 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. @@ -32,7 +32,7 @@ The fleet mechanism is proven: decidesk ships the reference implementation (`dec **Affected code:** -- `lib/Mcp/LaunchpadToolProvider.php` — dispatcher + tool catalogue (new) +- `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) 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/mcp-tool-surface/specs/mcp-tools/spec.md b/openspec/changes/archive/2026-11-21-mcp-tool-surface/specs/mcp-tools/spec.md similarity index 90% rename from openspec/changes/mcp-tool-surface/specs/mcp-tools/spec.md rename to openspec/changes/archive/2026-11-21-mcp-tool-surface/specs/mcp-tools/spec.md index 75e4a37b0..e62700073 100644 --- a/openspec/changes/mcp-tool-surface/specs/mcp-tools/spec.md +++ b/openspec/changes/archive/2026-11-21-mcp-tool-surface/specs/mcp-tools/spec.md @@ -19,13 +19,13 @@ Write tools are annotated on hermiq's two grant axes: ### 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. +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 +- **THEN** it MUST return a `LaunchPadToolProvider` instance - **AND** every id in its catalogue MUST start with `launchpad.` #### Scenario: Boot without OpenRegister @@ -154,7 +154,7 @@ Every tool handler MUST enforce the exact same authorization as the correspondin - **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 +- **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 @@ -171,7 +171,7 @@ Every tool handler MUST enforce the exact same authorization as the correspondin ### 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. +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 @@ -187,7 +187,7 @@ Every tool MUST validate its arguments against its declared `inputSchema` before ### 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. +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 @@ -242,8 +242,20 @@ The catalogue MUST be sufficient for hermiq to execute common chat commands as s - **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. 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/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/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/screens.md b/openspec/changes/drill-down-cross-widget-filter/screens.md new file mode 100644 index 000000000..bc444af05 --- /dev/null +++ b/openspec/changes/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/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 index e545a49de..4d77c3449 100644 --- 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 @@ -227,6 +227,48 @@ When org-level telemetry is enabled, the system SHALL persist `filter_event` row --- +### 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 diff --git a/openspec/changes/drill-down-cross-widget-filter/tasks.md b/openspec/changes/drill-down-cross-widget-filter/tasks.md index b22ffc944..4a335a835 100644 --- a/openspec/changes/drill-down-cross-widget-filter/tasks.md +++ b/openspec/changes/drill-down-cross-widget-filter/tasks.md @@ -4,85 +4,132 @@ ### 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. +- [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. -- [ ] 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 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. +- [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. -- [ ] 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. +- [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`. -- [ ] 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. +- [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`. -- [ ] 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. +- [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 -- [ ] 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. +- [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`. -- [ ] 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. +- [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`. -- [ ] 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. +- [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. -- [ ] 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. +- [ ] 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 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`. ### 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. +- [x] 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. + - Done as `src/modals/SaveViewModal.vue` (name, description, a share switch), opened by "Save view" in `SavedViewsMenu.vue`, which shows only to a user who may edit the dashboard while a filter is active. `src/services/savedViews.js` (`createSavedView`) writes the `saved_view` object through OpenRegister's object endpoint for `launchpad/saved_view` with the bus's clauses, the creator and the time; the list reloads after a save, and a failed save is shown in the modal. Tests: `savedViews.spec.js`, `SavedViewsMenu.spec.js`. -- [ ] 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. +- [x] 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. + - Done as `src/components/Workspace/DashboardSavedViews.vue` with `SavedViewsMenu.vue` under the breadcrumb in `Views.vue`: the dashboard's views load from OpenRegister when it opens, split into "My views" (created by the user) and "Shared views" (shared by others). Picking one calls the filter session's `applyView`, which hydrates the bus with the view's clauses as `savedView` (every non-pinned clause replaced, pinned ones kept); the URL sync then rewrites `f`. Tests: `SavedViewsMenu.spec.js`, `useDashboardFilterSession.spec.js`. -- [ ] 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. +- [x] 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. + - Done: the creator's own views have edit (name, description, sharing in the same modal), share/unshare and delete buttons (OpenRegister `PATCH`/`DELETE` on the object); a view another user shared has none, and the container refuses those actions for a view the user did not create. Tests: `SavedViewsMenu.spec.js`, `savedViews.spec.js`. ### 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. +- [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 `saved_view` (the fields above; `filters` are filter clauses with the spec's operator and source enums) and `filter_event` to the launchpad register, and `ImportLaunchpadRegister::REGISTER_VERSION` moves to 1.0.3 so existing installs take them. The four endpoints are OpenRegister's object endpoints for `launchpad/saved_view`. Test: `tests/Unit/Repair/CrossWidgetFilterSchemasTest.php` (through the real import step; the spec's seed rows validate, a view without dashboard, name, filters or creator is refused). -- [ ] 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. +- [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`. -- [ ] 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. +- [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`. -- [ ] 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. +- [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 -- [ ] 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 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. +- [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. -- [ ] 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 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. +- [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`. - [ ] 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. + - Partly written: `tests/e2e/cross-widget-filter.spec.ts` covers the URL half (a filtered URL restores the same filters in a fresh login). The click half waits for Task 7. Open: the run against a live instance. - [ ] 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. + - 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`). Open: the run against a live instance. - [ ] 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: `tests/e2e/cross-widget-filter.spec.ts` (source note, lock and missing remove button on the pinned clause, removing one clause updates `f`). Clearing the publishing widget's selection waits for Task 7. Open: the run against a live instance. - [ ] 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. + - Written: `tests/e2e/cross-widget-filter-saved-views.spec.ts` (save, restore over another filter, share, read-only for a second user the dashboard is shared with). Open: the run against a live instance. - [ ] 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. + - Partly 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). The `apply` row of a click waits for Task 7. Open: the run against a live instance. - [ ] 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. +- [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 -- [ ] 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). +- [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. -- [ ] 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). +- [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"), "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). + - Done 19 Nov: every string of the filter panel, the saved views and the chart pick (`ActiveFiltersPanel.vue`, `SavedViewsMenu.vue`, `DashboardSavedViews.vue`, `ChartHost.vue`; 19 strings, 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", the telemetry switch and every saved-views string ("Save view", "Saved views", "My views", "Shared views", the modal and its errors) 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). -- [ ] 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). +- [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`. -- [ ] 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. +- [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 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. + - 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. -- [ ] 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. +- [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), saved views (11-13), the register and telemetry (14-17), the Playwright and performance tasks (22-30, 35), and 31-34. ## Verification 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..1a097f6db 100644 --- a/openspec/changes/e2e-coverage-programme/tasks.md +++ b/openspec/changes/e2e-coverage-programme/tasks.md @@ -14,12 +14,19 @@ 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. + - 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) - [ ] 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) - [ ] 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) - [ ] 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) - [ ] 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) - [ ] 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) - [ ] 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) - [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 @@ -27,88 +34,182 @@ Counts are scenarios, and scenarios cited by a Playwright test, measured on `dev 11 specs, 341 scenarios. - [ ] 2.1 `dashboard-bulk-operations`: 50 scenarios, 0 cited, blanket. -- [ ] 2.2 `resource-uploads`: 46 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. +- [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). - [ ] 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. + - 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. +- [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). - [ ] 2.6 `dashboard-locking`: 29 scenarios, 0 cited, blanket. -- [ ] 2.7 `dashboard-metadata-fields`: 28 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. +- [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. - [ ] 2.8 `dashboard-quota-limits`: 24 scenarios, 0 cited, blanket. -- [ ] 2.9 `legacy-widget-bridge`: 21 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. +- [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. + - 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. - [ ] 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. ## 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) - [ ] 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) - [ ] 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. - [ ] 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) - [ ] 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) - [ ] 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) - [ ] 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) - [ ] 3.8 `tiles`: 38 scenarios, 0 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) - [ ] 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) - [ ] 3.10 `dashboard-reactions`: 31 scenarios, 0 cited, blanket. -- [ ] 3.11 `tile-quick-search`: 28 scenarios, 8 cited. + - 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) +- [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. - [ ] 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) - [ ] 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) - [ ] 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) - [ ] 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) - [ ] 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) - [ ] 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. +- [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. ## 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) - [ ] 4.2 `news-widget`: 58 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) - [ ] 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) - [ ] 4.4 `header-widget`: 56 scenarios, 0 cited. + - 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) - [ ] 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) - [ ] 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) - [ ] 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) - [ ] 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) - [ ] 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) - [ ] 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) - [ ] 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) - [ ] 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) - [ ] 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. + - Spec written: tests/e2e/divider-widget.spec.ts, 24 scenarios cited, not yet run (cloud, 2026-11-19), 2 excluded with a reason +- [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). - [ ] 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) - [ ] 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 - [ ] 4.20 `launchpad-meeting-calendar-actions`: 14 scenarios, 0 cited, blanket. + - 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. - [ ] 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) - [ ] 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. +- [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) ## 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 +- [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. + - 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) - [ ] 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 - [ ] 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: tests/e2e/nc-unified-search-integration.spec.ts, 42 scenarios cited, not yet run (cloud, 2026-11-19), 6 excluded with reasons +- [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) +- [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 +- [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) - [ ] 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) - [ ] 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) ## 6. Close the programme diff --git a/openspec/changes/embedded-analytics/context-brief.md b/openspec/changes/embedded-analytics/context-brief.md index 3ff58a52e..b05e12421 100644 --- a/openspec/changes/embedded-analytics/context-brief.md +++ b/openspec/changes/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/embedded-analytics/design.md b/openspec/changes/embedded-analytics/design.md index 8d5ccba43..8916f4d33 100644 --- a/openspec/changes/embedded-analytics/design.md +++ b/openspec/changes/embedded-analytics/design.md @@ -271,7 +271,7 @@ Three realistic scenarios for Netherlands municipalities: 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. +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 diff --git a/openspec/changes/embedded-analytics/proposal.md b/openspec/changes/embedded-analytics/proposal.md index e1f60c51a..88f747245 100644 --- a/openspec/changes/embedded-analytics/proposal.md +++ b/openspec/changes/embedded-analytics/proposal.md @@ -13,7 +13,7 @@ LaunchPad widgets today require a logged-in Nextcloud session to view. This fore - **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** `@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 @@ -25,7 +25,7 @@ LaunchPad widgets today require a logged-in Nextcloud session to view. This fore - `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-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 diff --git a/openspec/changes/embedded-analytics/screens.md b/openspec/changes/embedded-analytics/screens.md new file mode 100644 index 000000000..60c824023 --- /dev/null +++ b/openspec/changes/embedded-analytics/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpPubliek https://identity.conduction.nl/screens/board?id=launchpad/LpPubliek 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/embedded-analytics/spec.md b/openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md new file mode 100644 index 000000000..792d3df01 --- /dev/null +++ b/openspec/changes/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/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 index 61f3d5cd2..09a0100c2 100644 --- a/openspec/changes/embedded-analytics/tasks.md +++ b/openspec/changes/embedded-analytics/tasks.md @@ -2,36 +2,40 @@ ## Infrastructure & Data Layer -- [ ] Task 1: Create OpenRegister schemas in `lib/Settings/launchpad_register.json` for four new register types: +- [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). -- [ ] Task 2: Create entity mapping classes under `lib/Entity/`: +- [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. -- [ ] Task 3: Create `lib/Service/JwtSigningService.php` for JWT lifecycle: +- [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). -- [ ] Task 4: Create `lib/Service/EmbedTokenService.php` for token persistence: +- [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). -- [ ] Task 5: Create `lib/Service/RateLimitService.php` (token-bucket algorithm): +- [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 @@ -39,19 +43,21 @@ ## JWT Validation & Scope Enforcement -- [ ] Task 6: Create `lib/Middleware/EmbedTokenMiddleware.php`: +- [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). -- [ ] Task 7: Create `lib/Service/ScopeEnforcementService.php` (REQ-EMB-004): +- [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). -- [ ] Task 8: Create `lib/Service/CspService.php` for CSP header generation (REQ-EMB-003): +- [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 @@ -59,7 +65,7 @@ ## Public Render Route -- [ ] Task 9: Create `lib/Controller/EmbedController.php`: +- [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) @@ -69,20 +75,23 @@ - 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). -- [ ] Task 10: Create `lib/Service/EmbedRenderService.php`: +- [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 -- [ ] Task 11: Create `lib/Service/TenantThemeService.php`: +- [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). - [ ] Task 12: Add axe-core integration to build pipeline: - In `npm run build`, add a linting step that: @@ -93,21 +102,24 @@ 5. Warns on medium/low violations - Create `src/axe-core-check.js` script - Output report saved to `docs/accessibility/axe-results.json` for review + > Not done: needs axe-core added as a build dependency and a renderer for representative widget shapes; left for a separate change to the build pipeline. -- [ ] Task 13: Modify dashboard/widget rendering to accept token context: +- [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). -- [ ] Task 14: Create `src/composables/useEmbedContext.js`: +- [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 -- [ ] Task 15: Create `src/components/EmbedTokenManager.vue`: +- [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 @@ -115,16 +127,18 @@ - 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). -- [ ] Task 16: Create `src/components/TenantThemeManager.vue`: +- [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). -- [ ] Task 17: Create `src/components/EmbedUsageReport.vue`: +- [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 @@ -133,8 +147,9 @@ - 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). -- [ ] Task 18: Create `src/components/EmbedTokenForm.vue` (sub-component): +- [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) @@ -149,18 +164,20 @@ - 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 -- [ ] Task 19: Create `@launchpad/embed-sdk` package structure: +- [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. -- [ ] Task 20: Implement `LaunchPadEmbed.render(container, config)` (REQ-EMB-006): +- [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 @@ -168,58 +185,66 @@ - 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. -- [ ] Task 21: Implement event relay in SDK (REQ-EMB-006): +- [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. -- [ ] Task 22: Implement `.resize()` method (REQ-EMB-006): +- [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. -- [ ] Task 23: Create iframe-side entry point for SDK (`src/embed-entry.js`): +- [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`). -- [ ] 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) +- [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 -- [ ] Task 25: Implement revocation cache + propagation: +- [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`. -- [ ] Task 26: Integrate RateLimitService into render route: +- [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`. -- [ ] Task 27: Create revocation UI flow in EmbedTokenManager: +- [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 -- [ ] Task 28: Implement usage event capture (REQ-EMB-008): +- [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 @@ -228,49 +253,56 @@ 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). -- [ ] Task 29: Create usage report API: +- [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). -- [ ] Task 30: Implement telemetry kill-switch: +- [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 -- [ ] Task 31: PHPUnit tests for JWT signing: +- [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`. -- [ ] Task 32: PHPUnit tests for token lifecycle: +- [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`. -- [ ] Task 33: PHPUnit tests for scope enforcement: +- [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). -- [ ] Task 34: Vitest tests for JS-SDK: +- [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. -- [ ] Task 35: Playwright integration tests: +- [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 @@ -279,27 +311,31 @@ - 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. -- [ ] Task 36: Create documentation: +- [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). -- [ ] Task 37: i18n for new UI strings: +- [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 -- [ ] Task 38: ESLint clean on new files: +- [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. - [ ] Task 39: Security audit checklist: - JWT signature verification is unconditional (no bypass paths) @@ -311,11 +347,12 @@ - Read-only tokens cannot mutate state - Wildcard origins rejected at creation time -- [ ] Task 40: Integration with existing LaunchPad features: +- [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 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-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/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/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/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/map-support/proposal.md b/openspec/changes/map-support/proposal.md index bfa81f589..12051aa25 100644 --- a/openspec/changes/map-support/proposal.md +++ b/openspec/changes/map-support/proposal.md @@ -4,10 +4,8 @@ Render geospatial properties from OpenRegister objects on a map widget inside la ## 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`). +- `@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 @@ -16,7 +14,7 @@ Map rendering is a contained UI surface that depends on geospatial data shipped ## Approach -- Leaflet 1.9 as the map library — lightweight, well-maintained, plays well with PDOK tile layers and Vue 2 via `vue2-leaflet`. +- 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. diff --git a/openspec/changes/map-support/screens.md b/openspec/changes/map-support/screens.md new file mode 100644 index 000000000..d5853978e --- /dev/null +++ b/openspec/changes/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/map-support/specs/map-widget/spec.md b/openspec/changes/map-support/specs/map-widget/spec.md new file mode 100644 index 000000000..1b39cac7e --- /dev/null +++ b/openspec/changes/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/map-support/tasks.md b/openspec/changes/map-support/tasks.md index 63ab6dbf9..3e67081bf 100644 --- a/openspec/changes/map-support/tasks.md +++ b/openspec/changes/map-support/tasks.md @@ -2,28 +2,42 @@ ## 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. +> 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 -- [ ] 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`. +- [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 -- [ ] Unit test for `MapWidgetConfig.vue` validation logic. -- [ ] Unit test for the spatial-filter to API-query translator in the store. +- [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). - [ ] 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. +- [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) 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 index 80ee75496..6eec261a6 100644 --- a/openspec/changes/openregister-leaf-integrations/design.md +++ b/openspec/changes/openregister-leaf-integrations/design.md @@ -63,6 +63,14 @@ OpenRegister's integration leaves are adopted declaratively (`configuration.link **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. diff --git a/openspec/changes/openregister-leaf-integrations/screens.md b/openspec/changes/openregister-leaf-integrations/screens.md new file mode 100644 index 000000000..7766af50b --- /dev/null +++ b/openspec/changes/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/openregister-leaf-integrations/specs/dashboard-talk-leaf/spec.md b/openspec/changes/openregister-leaf-integrations/specs/dashboard-talk-leaf/spec.md index 2757bffdd..33c406951 100644 --- a/openspec/changes/openregister-leaf-integrations/specs/dashboard-talk-leaf/spec.md +++ b/openspec/changes/openregister-leaf-integrations/specs/dashboard-talk-leaf/spec.md @@ -62,6 +62,13 @@ Access to a dashboard's discussion MUST be gated by the same authorization the d - **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 @@ -80,7 +87,7 @@ When the Talk app is not installed or is disabled, the leaf MUST degrade silentl ### 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. +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 diff --git a/openspec/changes/openregister-leaf-integrations/tasks.md b/openspec/changes/openregister-leaf-integrations/tasks.md index 3fa9862c5..d2d3714b5 100644 --- a/openspec/changes/openregister-leaf-integrations/tasks.md +++ b/openspec/changes/openregister-leaf-integrations/tasks.md @@ -2,25 +2,35 @@ ## 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 +- [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 - [ ] 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"]`. ## 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 +- [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 -- [ ] 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 +- [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 -- [ ] 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 +- [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 @@ -28,7 +38,8 @@ - [ ] 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 +- [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 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/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/scheduled-exports/design.md b/openspec/changes/scheduled-exports/design.md index d8134602f..b79e939a5 100644 --- a/openspec/changes/scheduled-exports/design.md +++ b/openspec/changes/scheduled-exports/design.md @@ -191,3 +191,33 @@ No duplication detected. All core abstractions (CRUD, permissions, retention, au 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/screens.md b/openspec/changes/scheduled-exports/screens.md new file mode 100644 index 000000000..e17c1086b --- /dev/null +++ b/openspec/changes/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/tasks.md b/openspec/changes/scheduled-exports/tasks.md index c3f331ef9..f6296e67d 100644 --- a/openspec/changes/scheduled-exports/tasks.md +++ b/openspec/changes/scheduled-exports/tasks.md @@ -4,22 +4,22 @@ ### 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) +- [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 -- [ ] 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 +- [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 -- [ ] Task 10: Implement `ScheduledExportController` with endpoints: +- [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 @@ -31,28 +31,34 @@ - `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` +- [x] 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 +- [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 -- [ ] 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 +- [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 - [ ] 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 @@ -61,13 +67,17 @@ ### 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) + - 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. +- [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 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/widget-calculated-fields/design.md b/openspec/changes/widget-calculated-fields/design.md index ac931c76b..7da325c04 100644 --- a/openspec/changes/widget-calculated-fields/design.md +++ b/openspec/changes/widget-calculated-fields/design.md @@ -201,7 +201,7 @@ The core design choice is **dual evaluation**: client-side for instant feedback {"type": "literal", "valueType": "string", "value": "days"} ] }, - "returnType": "duration", + "returnType": "number", "evaluationMode": "client", "formatOptions": { "pattern": "d 'dagen'" @@ -317,3 +317,46 @@ Widget A (register: sales) tries to reference Widget B (register: crm) in a serv - 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/screens.md b/openspec/changes/widget-calculated-fields/screens.md new file mode 100644 index 000000000..9f6ee9800 --- /dev/null +++ b/openspec/changes/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/widget-calculated-fields/specs/calculated-fields/spec.md b/openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md index 4abdb6766..23d2449b7 100644 --- a/openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md +++ b/openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md @@ -8,60 +8,62 @@ status: draft 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 +## 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 +#### 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 +#### 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 +#### 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 +### 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 +#### 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 +#### 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 +#### 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 +### 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 +#### Scenario: Recompute on filter change - GIVEN a widget with calculated field `profit = revenue - cost` - AND the widget displays `revenue = 100000, cost = 60000, profit = 40000` @@ -69,116 +71,116 @@ The client-side evaluator SHALL recompute every `client` and `both` mode calcula - 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 +#### 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 +#### 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 +### 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 +#### 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 +#### 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 +#### 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 +### 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 +#### 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 +#### 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 +#### 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 +### 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 +#### 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 +#### 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 +#### 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 +### 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 +#### 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 +#### 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 +### 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 +#### 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 @@ -186,14 +188,14 @@ When a calculated field fails to evaluate at runtime, the system SHALL render an - 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 +#### 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 +#### Scenario: Error does not block widget render - GIVEN a widget with 10 calculated fields, 1 of which fails to evaluate - WHEN the widget renders @@ -201,49 +203,49 @@ When a calculated field fails to evaluate at runtime, the system SHALL render an - 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 +### 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 +#### 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 +#### 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 +#### 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 +### 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 +#### 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 +#### 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 +#### 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 diff --git a/openspec/changes/widget-calculated-fields/tasks.md b/openspec/changes/widget-calculated-fields/tasks.md index 7eedd2a2e..4bac911de 100644 --- a/openspec/changes/widget-calculated-fields/tasks.md +++ b/openspec/changes/widget-calculated-fields/tasks.md @@ -2,92 +2,125 @@ ## 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) +- [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 -- [ ] 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) +- [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) -- [ ] 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) +- [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 -- [ ] 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) +- [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) -- [ ] 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) +- [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) -- [ ] 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) +- [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) -- [ ] 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 +- [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) -- [ ] 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) +- [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 -- [ ] 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) +- [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 -- [ ] 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) +- [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 -- [ ] 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) +- [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) - [ ] 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 +- [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). - [ ] Task 53: All hydra-gates pass (route-auth, admin-idor, semantic-auth, spdx-headers, etc.) + - Not ticked: `run-hydra-gates.sh` reports 12 failing gates, none in this change's files (composer audit, manifest, OR-abstraction in the Embed and permission services, Embed spec anchors and write capabilities, schema titles, icons, reports page, app chrome, walkthrough flows); every gate that reads this change's files passes. ## Verification diff --git a/openspec/parity/capabilities.json b/openspec/parity/capabilities.json index 3317819e7..109a218c9 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:165 (startPageWithoutNavigation); src/components/Workspace/DashboardMoreMenu.vue (the More menu holds the destinations while the panel is left out); 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": "Admin settings, layout options: Start page without navigation panel; the start page then shows its destinations in a Menu button", + "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,7 +1990,13 @@ "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", "evidence": { @@ -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/drill-down-cross-widget-filter", + "requirement": [ + "openspec/changes/drill-down-cross-widget-filter/specs/cross-widget-filter :: REQ-CWF-001 Widget click publishes to the filter bus", + "openspec/changes/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); src/components/Widgets/Renderers/PeopleWidget.vue; 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); src/components/Widgets/Renderers/PeopleWidget.vue; 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..cbb777cb1 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,25 +26,30 @@ 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) | | `quicksearch_fallback_target` | `quicksearchFallbackTarget` | string | `none` | Quick-search no-match fallback: `none`, `unified-search` or an https URL template (REQ-QSEARCH-004). A stored value that no longer validates reads as `none`. | +| `start_page_without_navigation` | `startPageWithoutNavigation` | boolean | `false` | Whether the dashboard view renders without the left navigation panel (runtime-shell REQ-SHELL-009). Only a stored `true` turns it on. | | `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 fourteen 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 +@e2e exclude needs a fresh installation with no settings row; the suite shares one instance and no endpoint deletes a stored setting (PUT treats null as not supplied). Pinned by tests/Unit/Service/AdminSettingsServiceTest.php::testGetSettingsReturnsExactlyTheDocumentedKeysAtTheirDefaults (which lists 23 keys, not fourteen; see the format-consistency test). - 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 fourteen settings at their default values: ```json { "defaultPermissionLevel": "add_only", @@ -54,13 +57,15 @@ 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, - "quicksearchFallbackTarget": "none" + "quicksearchFallbackTarget": "none", + "startPageWithoutNavigation": false } ``` - NOTE: `allowUserDashboards` defaults to `false` (REQ-ASET-003) — admins MUST opt in to personal dashboard creation. @@ -69,7 +74,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 thirteen keys MUST still be present with their current values #### Scenario: Non-admin user retrieves settings - GIVEN a regular user "alice" @@ -86,11 +91,18 @@ 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 fourteen keys listed under Defined Settings: `defaultPermissionLevel`, `allowUserDashboards`, `allowMultipleDashboards`, `defaultGridColumns`, `linkCreateFileExtensions`, `defaultSharePermissionLevel`, `forcedShareGroups`, `sharingAllowedGroups`, `sharingRecipientScope`, `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 +@e2e exclude needs a content_storage row written straight into oc_launchpad_admin_settings; no endpoint writes that key (PUT ignores unknown keys) and "stays unread" is a database-only fact. Pinned by tests/Unit/Service/AdminSettingsServiceTest.php::testGetSettingsReturnsCamelCaseKeys and tests/Unit/Db/AdminSettingKeyTest.php::testContentStorageKeyIsRetired. +- 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) + ### Requirement: Update Admin Settings (REQ-ASET-002) Administrators MUST be able to update individual or multiple admin settings in a single PUT request. @@ -130,18 +142,21 @@ Administrators MUST be able to update individual or multiple admin settings in a - AND settings not included in the request MUST remain unchanged #### Scenario: Update with invalid permission level value +@e2e exclude never built: AdminSettingsService::updateSettings() stores defaultPermLevel unchecked (git log --all -S finds no validation for it in lib/), so "super_admin" is stored and answered 200. No PHPUnit or Newman test pins a 400. - 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 #### Scenario: Update with invalid grid columns value +@e2e exclude never built: defaultGridCols is stored unchecked (no range check exists in lib/ history), so 0 is stored and answered 200. No PHPUnit or Newman test pins a 400. - 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 #### Scenario: Update with invalid boolean value +@e2e exclude never built: no boolean check exists; Nextcloud casts "maybe" to true for the bool parameter and it is stored with 200. No PHPUnit or Newman test pins a 400. - 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` @@ -209,6 +224,7 @@ Admins MAY always create dashboards regardless of the flag (the `PermissionServi - AND no rows in `oc_launchpad_dashboards` or `oc_launchpad_widget_placements` MUST have been touched #### Scenario: Default value when setting is missing +@e2e exclude needs the allow_user_dashboards row to be absent; no endpoint deletes a stored setting and the shared instance has one. Pinned by tests/Unit/Service/DashboardServiceAllowFlagTest.php::testDefaultValueBlocksCreation and tests/Unit/Service/AdminSettingsServiceTest.php::testGetSettingsReturnsDefaults. - GIVEN a fresh LaunchPad install with no row for `allow_user_dashboards` in `oc_launchpad_admin_settings` - WHEN any code reads the setting (via `DashboardService::getAllowUserDashboards()`, `PermissionService::canCreateDashboard()`, or `AdminSettingsService::getSettings()`) - THEN it MUST evaluate to `false` (creation blocked) — the secure default @@ -279,6 +295,7 @@ The `defaultPermissionLevel` setting MUST be applied as a fallback when resolvin - AND the `defaultPermissionLevel` admin setting acts as a fallback in `PermissionService::getEffectivePermissionLevel()` only when the dashboard's own `permissionLevel` is empty #### Scenario: Factory default permission (add_only) +@e2e exclude needs a dashboard with no permissionLevel and no template, which no endpoint creates (DashboardFactory sets full, template copies take the template level). Pinned by tests/Unit/Service/PermissionServiceAccessGoldenTest.php (dashboard 8: empty level, stored default add_only). Note: with the row absent PermissionService::getEffectivePermissionLevel() falls back to full, not add_only. - GIVEN `defaultPermissionLevel` is at its factory default of `add_only` - WHEN `PermissionService::getEffectivePermissionLevel()` is called for a dashboard with no `permissionLevel` set and no `basedOnTemplate` - THEN the effective level MUST resolve to `add_only` (the admin default) @@ -305,7 +322,7 @@ 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` @@ -330,12 +347,14 @@ The `defaultGridColumns` setting MUST be applied to new dashboards when no expli Admin settings MUST be persisted across server restarts and app updates. #### Scenario: Settings survive server restart +@e2e exclude needs restarting the Nextcloud server mid-test, which the shared e2e instance cannot do. No PHPUnit or Newman test pins it. - GIVEN the admin has configured `allowUserDashboards: false` - WHEN the Nextcloud server is restarted - THEN GET /api/admin/settings MUST still return `allowUserDashboards: false` - AND the setting MUST NOT revert to its default value #### Scenario: Settings survive app update +@e2e exclude needs upgrading the installed app mid-test. No PHPUnit or Newman test pins it. - GIVEN the admin has configured custom settings - WHEN the LaunchPad app is updated to a new version - THEN all previously configured settings MUST be preserved @@ -377,7 +396,7 @@ 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 select for "Default grid columns" offering 6, 8 and 12 (Ruben, 21 Nov 2026, following the product) - A "Save" button - AND each setting MUST show its current value @@ -431,12 +450,14 @@ Concurrent admin settings updates MUST be handled safely. The settings API MUST return consistent error responses for various failure scenarios. #### Scenario: Database connection failure during settings retrieval +@e2e exclude needs the database taken down under a running instance shared by the suite. No PHPUnit or Newman test pins it (AdminController::getSettings() has no try/catch). - GIVEN the database is temporarily unavailable - WHEN the admin sends GET /api/admin/settings - THEN the system MUST return HTTP 500 with an error message - AND the error MUST NOT expose internal database details #### Scenario: Database connection failure during settings update +@e2e exclude needs the database taken down under a running instance shared by the suite. No PHPUnit or Newman test pins it. - GIVEN the database is temporarily unavailable - WHEN the admin sends PUT /api/admin/settings with valid data - THEN the system MUST return HTTP 500 with an error message @@ -472,6 +493,7 @@ The system MUST persist an ordered list of Nextcloud group IDs as the global set - AND `"a"` MUST be removed (no implicit merge) #### Scenario: Corrupt DB JSON falls back to empty array +@e2e exclude needs a hand-written corrupt group_order row; no endpoint stores invalid JSON. Pinned by tests/Unit/Service/AdminSettingsServiceTest.php::testGetGroupOrderReturnsEmptyOnCorruptValue. - GIVEN the row `group_order` exists in `oc_launchpad_admin_settings` with `setting_value = '{not-json'` - WHEN any caller invokes `AdminSettingsService::getGroupOrder()` @@ -480,6 +502,7 @@ The system MUST persist an ordered list of Nextcloud group IDs as the global set - AND `GET /api/admin/groups` MUST return `active: []` in this state #### Scenario: Default when setting absent +@e2e exclude needs the group_order row to be absent; no endpoint deletes it. Pinned by tests/Unit/Service/AdminSettingsServiceTest.php::testGetGroupOrderReturnsEmptyWhenRowAbsent. - GIVEN no `group_order` row has ever been written to `oc_launchpad_admin_settings` - WHEN `AdminSettingsService::getGroupOrder()` is called @@ -605,133 +628,21 @@ 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 - -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. - -#### Scenario: Persist ordered list - -- 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` - -#### Scenario: Empty list clears active groups - -- 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) - -#### Scenario: Replace-wholesale, not merge - -- 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) - -#### Scenario: Corrupt DB JSON falls back to empty array - -- 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 - -#### Scenario: Default when setting absent - -- 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) - -### Requirement: REQ-ASET-013 List groups for admin UI - -The system MUST expose `GET /api/admin/groups` returning `{active: [id…], inactive: [id…], allKnown: [{id, displayName}…]}`: - -- `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. - -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. - -#### Scenario: Lists are disjoint and exhaustive - -- 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 - -#### Scenario: Order in `active` matches admin-chosen order - -- 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` - -#### Scenario: Empty group_order — all groups inactive - -- 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"` - -#### Scenario: Stale group IDs surface in active list - -- 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 +### Requirement: Program schemes and single sign-on launch templates are admin settings (REQ-ASET-020) -- GIVEN user "alice" who is not an administrator -- WHEN she sends `GET /api/admin/groups` -- THEN the system MUST return HTTP 403 +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: Missing `groups` key rejected +#### Scenario: A script scheme cannot be allowed -- GIVEN admin sends `POST /api/admin/groups` with body `{}` -- THEN the system MUST return HTTP 400 -- AND the persisted `group_order` MUST be unchanged +- **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: Non-string element rejected +#### Scenario: A launch template must be https with the app id -- 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"]` +- **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 ## Non-Functional Requirements 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..87a3ffbfd 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. @@ -130,6 +128,8 @@ Administrators MUST be able to view all existing templates with their configurat - 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 +228,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 +238,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 @@ -448,9 +450,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 +494,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 +534,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 +655,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 +784,268 @@ 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 +@e2e exclude Needs more than 50 provisioned copies and a cron run of TemplateResyncJob, which the e2e instance does not run on demand. Pinned by TemplateResyncServiceTest::testLargeGroupsEnqueueTheAsyncJobInsteadOfApplyingInline and TemplateResyncJobTest::testRunDelegatesToApplyResyncWithTheGivenArguments. + +### 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 + +When a member asks to delete a compulsory widget from a copy made from an admin template whose permission level is not `full`, 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. It MUST NOT send the delete (the server would answer 403, REQ-TMPL-006) and MUST NOT change the page. This holds for the widget's own menu ("Delete widget") and for the right-click menu ("Remove"), which both end in the page's `removeWidget`. + +**Why.** The entry was offered and did nothing: no request, no message, the widget stayed after a reload (#780). The shared edit cog has no way to withhold its delete entry, so the entry stays and explains itself. + +#### 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 chooses "Delete widget" on it +- THEN a message MUST say "Vandaag eerst" is part of the start page his administrator set for his group and cannot be removed +- 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()`). diff --git a/openspec/specs/announcements/spec.md b/openspec/specs/announcements/spec.md new file mode 100644 index 000000000..56aa06173 --- /dev/null +++ b/openspec/specs/announcements/spec.md @@ -0,0 +1,74 @@ +# 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, publish time and optional end time. 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. + +#### Scenario: News for one group + +- **GIVEN** Karin is in the announcement editor group +- **WHEN** she publishes "Inloopspreekuur privacy" in category "Privacy" for group "Medewerkers" +- **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 + +### 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" 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..caebe8cd6 --- /dev/null +++ b/openspec/specs/app-connections/spec.md @@ -0,0 +1,128 @@ +# 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 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..6fbe8dc55 --- /dev/null +++ b/openspec/specs/attention-feed/spec.md @@ -0,0 +1,183 @@ +--- +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. 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/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..0d4a569df 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 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..af347352a 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: @@ -147,6 +144,7 @@ Commands are registered via Nextcloud's standard pattern: The system MUST establish `launchpad:` as the canonical namespace prefix for ALL LaunchPad CLI commands. Every command name MUST begin with `launchpad:` followed by a verb-noun or category-verb pattern (e.g., `launchpad:export`, `launchpad:dashboard:list`, `launchpad:cleanup:scan`). No LaunchPad command SHALL use a bare name or a different prefix. #### Scenario: Discover all LaunchPad commands +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: no test pins the `occ list launchpad` listing, its descriptions or its order. Every name in lib/Command/ starts with `launchpad:` (read from setName), but nothing asserts it. - GIVEN a Nextcloud operator runs `php occ list launchpad` - WHEN the system enumerates all registered commands @@ -155,6 +153,7 @@ The system MUST establish `launchpad:` as the canonical namespace prefix for ALL - AND the list is alphabetically ordered by full command name #### Scenario: Sibling specs all fall under the namespace +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: no test asserts the registered names; appinfo/info.xml registers launchpad:export, launchpad:import, launchpad:import:confluence and launchpad:demo-showcases:install, none collide, unpinned. - GIVEN the `dashboard-export-import` spec defines `launchpad:export` and `launchpad:import` - AND the `confluence-html-import` spec defines `launchpad:import:confluence` @@ -164,6 +163,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` @@ -171,6 +171,7 @@ The system MUST establish `launchpad:` as the canonical namespace prefix for ALL - AND the convention is enforced by code review and ADR reference #### Scenario: Commands with multi-level verbs +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: no test runs `occ list launchpad:i18n`; the name launchpad:i18n:copy-navigation is only exercised through tests/Unit/Command/I18nNavigationCommandsGoldenTest.php::testCopyNavigation. - GIVEN the command `launchpad:i18n:copy-navigation --from=nl --to=en` - WHEN an operator runs it @@ -178,6 +179,7 @@ The system MUST establish `launchpad:` as the canonical namespace prefix for ALL - AND `php occ list launchpad:i18n` returns only i18n-related commands #### Scenario: Namespace not shared with other apps +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: it is a property of the Symfony/occ namespace lookup across apps; no test exists. - GIVEN another Nextcloud app (e.g., Calendar) registers `occ calendar:list` - WHEN `php occ list launchpad` is run @@ -189,6 +191,7 @@ The system MUST establish `launchpad:` as the canonical namespace prefix for ALL Every LaunchPad command MUST support three consistent global flags: `--quiet|-q` (suppress non-essential output), `--json` (emit machine-readable JSON), and `--no-interaction|-n` (skip prompts). These flags MUST be defined in the shared `CommandBase` abstract class so all commands inherit them without duplication. #### Scenario: Quiet mode suppresses progress but not errors +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: pinned by tests/Unit/Command/DashboardListCommandGoldenTest.php::testScopesAndOutput (--quiet prints nothing) and tests/Unit/Command/CommandErrorGoldenTest.php::testPrintedFailuresMatchTheRecordedFixture (the "quiet" cases still print the error on stderr with the error exit code). - GIVEN an operator runs `php occ launchpad:dashboard:list --quiet` - WHEN the command finishes @@ -197,6 +200,7 @@ Every LaunchPad command MUST support three consistent global flags: `--quiet|-q` - AND the exit code is correct (0 for success, non-zero for error) #### Scenario: JSON flag emits structured output only +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: pinned by tests/Unit/Command/DashboardListCommandGoldenTest.php::testScopesAndOutput (the --json envelope) and tests/Unit/Service/CommandServiceTest.php::testEnvelopeSuccessShape and ::testEncodeEnvelopeProducesValidJson. Escaping of newlines/special characters in data is not pinned. - GIVEN an operator runs `php occ launchpad:dashboard:list --json` - WHEN the command finishes @@ -205,6 +209,7 @@ Every LaunchPad command MUST support three consistent global flags: `--quiet|-q` - AND newlines and special characters in data are properly escaped #### Scenario: No-interaction flag skips prompts in CI +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: pinned by tests/Unit/Command/DashboardDeleteCommandTest.php::testDeletionsMatchTheRecording (deletes with --no-interaction, exit 0) and tests/Unit/Command/DashboardDeleteCommandConfirmTest.php::testEventTypeFallbackAndMissingDispatcher. The exit 3 path was never built: no command returns EXIT_PERMISSION_DENIED (grep lib/Command). - GIVEN a CI script runs `php occ launchpad:dashboard:delete a1b2c3d4 --no-interaction` - WHEN the command would normally prompt "Delete dashboard X? (y/N)" @@ -212,6 +217,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 A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: never built for this command: lib/Command/ImportCommand.php extends Symfony Command, not CommandBase, so `launchpad:import --json` is an unknown option. No test exists. - GIVEN `php occ launchpad:import --file=/tmp/x.zip --quiet --no-interaction --json` - WHEN the import runs @@ -219,6 +225,7 @@ Every LaunchPad command MUST support three consistent global flags: `--quiet|-q` - AND all three flags work together without conflict #### Scenario: Global flags inherited by every command +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: the flags are registered once in lib/Command/CommandBase.php::configure(); their working on children is pinned by tests/Unit/Command/DashboardListCommandGoldenTest.php::testScopesAndOutput, tests/Unit/Command/DashboardDumpCommandsGoldenTest.php::testShowCommandOutput and tests/Unit/Command/I18nNavigationCommandsGoldenTest.php::testMigrateLanguageStructure. No test reads --help output. - GIVEN any newly registered `launchpad:*` command extending `CommandBase` - WHEN `php occ launchpad:my-new-command --help` is run @@ -230,6 +237,7 @@ Every LaunchPad command MUST support three consistent global flags: `--quiet|-q` The system MUST provide four new operator-facing dashboard commands: `launchpad:dashboard:list`, `launchpad:dashboard:show`, `launchpad:dashboard:delete`, and `launchpad:dashboard:debug-share`. These MUST cover listing with filters, full-config inspection, safe deletion with cascade option, and support-oriented sharing/state diagnostics. #### Scenario: List dashboards with optional filters +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: pinned by tests/Unit/Command/DashboardListCommandGoldenTest.php::testScopesAndOutput and ::testRefusedFilters (the --user and --status filters and the --json dashboard objects). - GIVEN an admin runs `php occ launchpad:dashboard:list --user=alice --status=published` - WHEN the system queries dashboards @@ -237,6 +245,7 @@ The system MUST provide four new operator-facing dashboard commands: `launchpad: - AND with `--json` the data field MUST be an array of dashboard objects with uuid, name, status, owner #### Scenario: Show one dashboard's full widget tree +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: pinned by tests/Unit/Command/DashboardDumpCommandsGoldenTest.php::testShowCommandOutput (dashboard plus widget placements, plain and in the --json envelope). - GIVEN `php occ launchpad:dashboard:show a1b2c3d4-e5f6-4789-abcd-ef1234567890` - WHEN the command runs @@ -245,6 +254,7 @@ The system MUST provide four new operator-facing dashboard commands: `launchpad: - AND with `--json` the data is wrapped in the standard response schema #### Scenario: Delete without cascade fails when children exist +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: pinned by tests/Unit/Command/CommandErrorGoldenTest.php::testPrintedFailuresMatchTheRecordedFixture (cases "delete parent plain/json": exit 2, the --cascade message on stderr) and tests/Unit/Command/DashboardDeleteCommandTest.php::testDeletionsMatchTheRecording ("parent without cascade": nothing deleted). - GIVEN `php occ launchpad:dashboard:delete a1b2c3d4 --no-interaction` - WHEN the dashboard has child dashboards (depends on `dashboard-tree` capability) @@ -253,6 +263,7 @@ The system MUST provide four new operator-facing dashboard commands: `launchpad: - AND stderr MUST print "Use --cascade to also delete child dashboards" #### Scenario: Delete with cascade removes children +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: pinned by tests/Unit/Command/DashboardDeleteCommandTest.php::testDeletionsMatchTheRecording ("parent cascade": the subtree is deleted, exit 0); the audit line is pinned generically by tests/Unit/Command/CommandAuditTrailTest.php::testARunIsAuditedUnderItsOwnName, not for a cascade. - GIVEN `php occ launchpad:dashboard:delete a1b2c3d4 --cascade --no-interaction` - WHEN the dashboard and its two children exist @@ -261,6 +272,7 @@ The system MUST provide four new operator-facing dashboard commands: `launchpad: - AND the audit log records the cascaded deletion #### Scenario: Debug-share prints all sharing state for support +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: pinned by tests/Unit/Command/DashboardDumpCommandsGoldenTest.php::testDebugShareCommandOutput (the six keys and the share rows). - GIVEN `php occ launchpad:dashboard:debug-share a1b2c3d4 --json` - WHEN the command queries the sharing and locking state @@ -273,6 +285,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 +294,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 +302,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 +310,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 @@ -312,6 +329,7 @@ The system MUST provide the command `launchpad:user:revoke-feed-token ` to The system MUST provide three i18n commands: `launchpad:i18n:export-strings` (extract translatable strings to POT), `launchpad:i18n:migrate-language-structure` (one-time flat-to-per-language-table migration, depends on `dashboard-language-content`), and `launchpad:i18n:copy-navigation --from= --to=` (clone org-navigation tree across language variants). Each command MUST document its prerequisites in `--help`. #### Scenario: Export translatable strings to POT +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: pinned by tests/Unit/Command/I18nExportStringsCommandTest.php::testACheckoutStillWritesTheDefaultPot and tests/Unit/Command/I18nExportStringsCollectionTest.php::testOnlySourceFilesUnderLibAndSrcAreRead. - GIVEN a developer runs `php occ launchpad:i18n:export-strings` on a development checkout - WHEN the command scans `lib/` and `src/` for i18n markers @@ -320,6 +338,7 @@ The system MUST provide three i18n commands: `launchpad:i18n:export-strings` (ex - AND the file contains all discovered translatable strings #### Scenario: A signed release is never written to +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: pinned by the two release-tree refusal tests in tests/Unit/Command/I18nExportStringsCommandTest.php (exit 2, names --output, no file added). - GIVEN the app is a signed release, so `appinfo/signature.json` exists - WHEN an operator runs `php occ launchpad:i18n:export-strings` without `--output`, or with an `--output` path inside the app folder @@ -327,12 +346,14 @@ The system MUST provide three i18n commands: `launchpad:i18n:export-strings` (ex - AND the exit code MUST be 2, with a message naming `--output` #### Scenario: The POT file goes where the operator says +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: pinned by tests/Unit/Command/I18nExportStringsCommandTest.php::testADashPrintsThePot and its release-tree outside-path test. - WHEN an operator runs the command with `--output=` outside the app folder, or `--output=-` - THEN the POT file MUST be written to that path, or printed to standard output - AND the exit code MUST be 0 #### Scenario: Migrate language structure one-time +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: pinned only as a zero-row run by tests/Unit/Command/I18nNavigationCommandsGoldenTest.php::testMigrateLanguageStructure; the command body migrates nothing (lib/Command/I18nMigrateLanguageStructureCommand.php sets $migrated = 0), so the migration itself was never built. - GIVEN the old flat-language storage schema is in place - AND the `dashboard-language-content` capability is enabled @@ -342,6 +363,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 A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: 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 +371,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 A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: never built: lib/Command/I18nCopyNavigationCommand.php reports `copied: 0` without copying; 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` @@ -357,6 +380,7 @@ The system MUST provide three i18n commands: `launchpad:i18n:export-strings` (ex - AND the exit code MUST be 0 #### Scenario: Copy navigation fails on unknown language +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: pinned by tests/Unit/Command/I18nNavigationCommandsGoldenTest.php::testCopyNavigation (exit 4, "No navigation tree found for language"), though the product keys it on the table being absent, not on the language having no data. - GIVEN `php occ launchpad:i18n:copy-navigation --from=xx --to=en` where `xx` has no navigation data - WHEN the command looks up the source language @@ -368,12 +392,14 @@ The system MUST provide three i18n commands: `launchpad:i18n:export-strings` (ex All LaunchPad commands MUST emit exactly one of the six standard exit codes (0, 1, 2, 3, 4, 5) on every execution path, including panics and unhandled exceptions. No command SHALL exit with any other code. The exit codes MUST be defined as constants in the shared `CommandService` and referenced consistently. #### Scenario: Success exit code 0 +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: pinned by tests/Unit/Command/DashboardListCommandGoldenTest.php::testScopesAndOutput (exit 0). - GIVEN `php occ launchpad:dashboard:list` completes with no errors - WHEN the exit code is inspected via `echo $?` - THEN the value MUST be `0` #### Scenario: Invalid argument exit code 2 +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: pinned by tests/Unit/Command/DashboardDumpCommandsGoldenTest.php::testShowCommandOutput (exit 2, "Invalid UUID format"). - GIVEN `php occ launchpad:dashboard:show not-a-uuid` - WHEN the command validates the UUID argument @@ -381,6 +407,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 @@ -388,6 +415,7 @@ All LaunchPad commands MUST emit exactly one of the six standard exit codes (0, - AND stderr MUST print "Permission denied: administrator required" #### Scenario: Resource not found exit code 4 +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: pinned by tests/Unit/Command/CommandErrorGoldenTest.php::testPrintedFailuresMatchTheRecordedFixture ("delete missing": exit 4, "Dashboard not found"); show shares the same CommandBase::emitDashboardNotFound, and tests/Unit/Command/DashboardDumpCommandsGoldenTest.php::testShowCommandOutput asserts only a non-zero exit for it. - GIVEN `php occ launchpad:dashboard:show 00000000-0000-0000-0000-000000000000` where that UUID is absent - WHEN the command queries the database @@ -395,6 +423,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 @@ -406,6 +435,7 @@ All LaunchPad commands MUST emit exactly one of the six standard exit codes (0, All commands invoked with `--json` MUST emit a single JSON object to stdout conforming to the schema `{success: bool, exitCode: int, data: object|array|null, errors: [{code, message, context}]}`. No other text or whitespace MUST appear before or after the JSON object on stdout. #### Scenario: Successful JSON response +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: pinned by tests/Unit/Command/DashboardListCommandGoldenTest.php::testScopesAndOutput (data.dashboards array in the envelope). - GIVEN `php occ launchpad:dashboard:list --json` - WHEN the command finds 3 dashboards @@ -413,6 +443,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 +451,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 @@ -427,6 +459,7 @@ All commands invoked with `--json` MUST emit a single JSON object to stdout conf - AND each error object MUST have `code`, `message`, and `context` fields #### Scenario: stdout clean of non-JSON bytes +@e2e exclude A console (occ) command, no HTTP or browser surface and Playwright cannot run occ: pinned for CommandBase commands by tests/Unit/Command/CommandErrorGoldenTest.php::testPrintedFailuresMatchTheRecordedFixture (json cases: stdout is the envelope, stderr empty) and tests/Unit/Command/CommandBaseFailureTest.php::testJsonFailureEmitsAnErrorEnvelope. Commands outside CommandBase have no --json. - GIVEN any command run with `--json` - WHEN the output is piped to `jq .` @@ -434,6 +467,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 @@ -445,6 +479,7 @@ All commands invoked with `--json` MUST emit a single JSON object to stdout conf All LaunchPad CLI commands MUST be registered in `appinfo/info.xml` under a `` element listing each command's fully qualified class name. No command SHALL be discoverable by Nextcloud unless it appears in this block. Each class MUST extend a shared `CommandBase` abstract class (itself extending `OC\Core\Command\Base`). #### Scenario: Commands are registered at install +@e2e exclude Static registration in appinfo/info.xml read by Nextcloud at app load, no HTTP outcome; no test reads the block or runs occ list. - GIVEN a fresh LaunchPad installation with `appinfo/info.xml` containing a `` block - WHEN Nextcloud loads the app @@ -452,12 +487,14 @@ All LaunchPad CLI commands MUST be registered in `appinfo/info.xml` under a `` block in `appinfo/info.xml` - THEN `php occ list launchpad` MUST include `launchpad:export` without further manual registration #### Scenario: CommandBase centralizes shared flag logic +@e2e exclude Internal PHP wiring: lib/Command/CommandBase.php::configure() is final and registers the three flags; exercised through children by tests/Unit/Command/DashboardListCommandGoldenTest.php::testScopesAndOutput and tests/Unit/Command/I18nNavigationCommandsGoldenTest.php::testMigrateLanguageStructure. - GIVEN a command class extends `CommandBase` - WHEN `CommandBase::configure()` registers `--quiet`, `--json`, and `--no-interaction` @@ -469,6 +506,7 @@ All LaunchPad CLI commands MUST be registered in `appinfo/info.xml` under a `