8 Commits
Author SHA1 Message Date
Patrick Niebeling 0904292c73 Remove the assigned-user and label filters
Build package / php-lint (8.4) (push) Successful in 1m33s
Build package / php-lint (8.5) (push) Successful in 49s
Build package / xml-lint (push) Successful in 13s
Build package / unit-tests (push) Successful in 38s
Build package / package (push) Successful in 1m44s
Workflows now move every overdue card of their source stack. A new
migration drops filter_user_ids and filter_label_ids; workflows that
had a filter keep running unfiltered. The version goes to 35.1.0 so
the migration runs on update.

Removed along with the filters: the labels and participants endpoints
and their Deck lookups, the dead-filter warnings and markers, and
CardService::enrichCards() in the card read. enrichCards() only added
labels, assignees and comment counts, and ran a permission check
against Deck's frozen uid.
2026-09-30 09:55:54 +02:00
Patrick Niebeling e84123654e Tie workflows to the board owner instead of their creator
Build package / php-lint (8.4) (push) Successful in 2m22s
Build package / php-lint (8.5) (push) Successful in 57s
Build package / xml-lint (push) Successful in 18s
Build package / unit-tests (push) Successful in 1m5s
Build package / package (push) Successful in 1m21s
A workflow now belongs to whoever owns its board. The settings page
lists, edits and deletes workflows by board ownership alone, using
Deck's BoardMapper::findAllByOwner(), a single owner query that never
returns shared boards and carries no frozen uid. A transferred board's
workflows therefore show up for the new owner immediately.

The background job still needs one user to run as and mail, so it
looks up the board owner before every run and stores it in user_id
when it changed. Archived boards stay listed so their workflows keep
a name, but are no longer offered or accepted as a target.
2026-09-30 09:38:11 +02:00
Patrick Niebeling ada16cb101 Only allow workflows on owned boards, and show the board in the table
Build package / php-lint (8.4) (push) Successful in 1m7s
Build package / php-lint (8.5) (push) Successful in 56s
Build package / xml-lint (push) Successful in 17s
Build package / unit-tests (push) Successful in 42s
Build package / package (push) Successful in 1m4s
The board list now only contains boards the current user owns, which
also makes the controller's board validation enforce the owner rule.

The workflow table gains a Board column (Board, Titel, Von Stapel,
Nach Stapel, Filter, E-Mail, Aktiv) and is sorted alphabetically by
those columns in that order.
2026-09-30 09:16:09 +02:00
gnilebein 7c7c52cb1c Merge pull request 'Start a permanent Nextcloud 35 version line at 35.0.0' (#1) from nextcloud-35 into main
Build package / php-lint (8.4) (push) Successful in 45s
Build package / php-lint (8.5) (push) Successful in 41s
Build package / xml-lint (push) Successful in 15s
Build package / unit-tests (push) Successful in 41s
Build package / package (push) Successful in 58s
Reviewed-on: #1
2026-09-22 07:37:47 +02:00
Patrick Niebeling dfec88d396 Start a permanent Nextcloud 35 version line at 35.0.0
Build package / php-lint (8.4) (push) Successful in 52s
Build package / php-lint (8.5) (push) Successful in 49s
Build package / xml-lint (push) Successful in 15s
Build package / unit-tests (push) Successful in 45s
Build package / php-lint (8.4) (pull_request) Successful in 47s
Build package / php-lint (8.5) (pull_request) Successful in 45s
Build package / xml-lint (pull_request) Successful in 13s
Build package / unit-tests (pull_request) Successful in 49s
Build package / package (push) Successful in 57s
Build package / package (pull_request) Successful in 49s
Nextcloud Hub Summer 26 (server 35.x) is declared as the sole
supported major on this branch, per the existing versioning scheme
(leading version number tracks the declared NC major). main keeps
tracking Nextcloud 34 (Hub 26 Spring) at the 34.x.x line; the two are
maintained in parallel rather than one replacing the other.
2026-09-22 07:36:15 +02:00
gnilebein 28b4edc811 revert 0e66319a06
Build package / php-lint (8.4) (push) Successful in 43s
Build package / php-lint (8.5) (push) Successful in 40s
Build package / xml-lint (push) Successful in 12s
Build package / unit-tests (push) Successful in 38s
Build package / package (push) Successful in 52s
revert Let each workflow watch the due date or the start date

Deck 1.18 added a start date to cards (Card::$startdate), so a workflow
no longer has to mean "overdue". Each rule now carries a date_field
('due' | 'start'), chosen in the settings form next to board and stacks.

Existing rules keep the due date: the new column's default supplies it
for every stored row, so there is no backfill step, and
Workflow::getDateFieldOrDue() covers entities that were never near the
database as well as hand-edited values. The controller is the one place
that rejects an unknown value instead of normalising it - a client
asking for a rule it would not get should hear about it.

The probe for the field is property_exists(), not method_exists():
Deck's entities declare no getter as real code - getStartdate(),
getDuedate(), even getId() all go through Entity::__call(), which
method_exists() ignores by definition. A method_exists() guard would
have been false on every Deck version and would have turned every
start-date rule into a silent no-op.

assertDeckAvailable() now also refuses Deck older than 1.18.0. That
floor cannot live in appinfo/info.xml - neither the server's nor the app
store's schema has an app-to-app dependency element - but
<nextcloud min-version="34"> already implies it, since 1.18.x is the
only Deck release line published for Nextcloud 34.

isOverdue() becomes hasPassed(): one function for both dates, since the
comparison and the argument against Deck's day-truncating
getDaysUntilDue() are identical for either.

Also carries a pending NcSelect icon-alignment fix that was already in
the working tree.

Bump to 34.1.0.
2026-08-26 07:10:55 +02:00
Patrick Niebeling 0e66319a06 Let each workflow watch the due date or the start date
Build package / php-lint (8.4) (push) Successful in 39s
Build package / php-lint (8.5) (push) Successful in 43s
Build package / xml-lint (push) Successful in 13s
Build package / unit-tests (push) Failing after 39s
Build package / package (push) Skipped
Deck 1.18 added a start date to cards (Card::$startdate), so a workflow
no longer has to mean "overdue". Each rule now carries a date_field
('due' | 'start'), chosen in the settings form next to board and stacks.

Existing rules keep the due date: the new column's default supplies it
for every stored row, so there is no backfill step, and
Workflow::getDateFieldOrDue() covers entities that were never near the
database as well as hand-edited values. The controller is the one place
that rejects an unknown value instead of normalising it - a client
asking for a rule it would not get should hear about it.

The probe for the field is property_exists(), not method_exists():
Deck's entities declare no getter as real code - getStartdate(),
getDuedate(), even getId() all go through Entity::__call(), which
method_exists() ignores by definition. A method_exists() guard would
have been false on every Deck version and would have turned every
start-date rule into a silent no-op.

assertDeckAvailable() now also refuses Deck older than 1.18.0. That
floor cannot live in appinfo/info.xml - neither the server's nor the app
store's schema has an app-to-app dependency element - but
<nextcloud min-version="34"> already implies it, since 1.18.x is the
only Deck release line published for Nextcloud 34.

isOverdue() becomes hasPassed(): one function for both dates, since the
comparison and the argument against Deck's day-truncating
getDaysUntilDue() are identical for either.

Also carries a pending NcSelect icon-alignment fix that was already in
the working tree.

Bump to 34.1.0.
2026-08-25 15:28:30 +02:00
Patrick Niebeling 43648f3728 Use app.svg for the personal settings section icon
Was already pending in the working tree; committed unchanged.
2026-08-25 15:28:21 +02:00
16 changed files with 356 additions and 707 deletions

No files matched your search

+25 -21
View File
@@ -4,11 +4,11 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## What this is ## What this is
A Nextcloud app (`workflow_deck_automation`, namespace `WorkflowDeckAutomation`) targeting **Nextcloud Hub 26 Spring (server 34.x)**. It lets each user configure, from their personal settings, automation "workflows" that move overdue [Deck](https://github.com/nextcloud/deck) cards from one stack to another, with optional assigned-user/label filters and an email notification. A background `Job` evaluates all enabled workflows on every cron pass. A Nextcloud app (`workflow_deck_automation`, namespace `WorkflowDeckAutomation`) targeting **Nextcloud Hub Summer 26 (server 35.x)** on this branch (`main` tracks Hub 26 Spring / server 34.x). It lets each user configure, from their personal settings, automation "workflows" that move overdue [Deck](https://github.com/nextcloud/deck) cards from one stack to another, with an optional email notification. There are deliberately **no card filters** (assigned users/labels existed until they were removed on request): a workflow moves *every* overdue card of its source stack. A background `Job` evaluates all enabled workflows on every cron pass.
## Non-negotiable architectural constraint ## Non-negotiable architectural constraint
**No HTTP/OCS calls against Deck, anywhere.** Every read (boards, stacks, cards, labels, assigned users) and the card move itself must go through Deck's own internal PHP classes (`OCA\Deck\Service\CardService`, `StackService`, `BoardService`, `OCA\Deck\Db\CardMapper`, …), resolved in-process via `\OCP\Server::get()`. This was an explicit, repeated product requirement from the user — do not "fix" it by switching to `IClientService`/`curl` against `/ocs/...`, even though that would be the more conventional cross-app integration approach. **No HTTP/OCS calls against Deck, anywhere.** Every read (boards, stacks, cards) and the card move itself must go through Deck's own internal PHP classes (`OCA\Deck\Service\CardService`, `StackService`, `BoardService`, `OCA\Deck\Db\CardMapper`, …), resolved in-process via `\OCP\Server::get()`. This was an explicit, repeated product requirement from the user — do not "fix" it by switching to `IClientService`/`curl` against `/ocs/...`, even though that would be the more conventional cross-app integration approach.
All Deck access is funneled through `lib/Service/DeckIntegrationService.php` — it is the *only* class that references `OCA\Deck\*`. If you need new Deck data, extend that class rather than reaching into Deck internals from elsewhere. Every call in there is wrapped (`class_exists()` checks, `IAppManager::isEnabledForUser('deck', …)`, try/catch → `DeckUnavailableException`) because `OCA\Deck\*` is not a documented/stable public API — it has no `@since` markers and can change between Deck releases without notice. All Deck access is funneled through `lib/Service/DeckIntegrationService.php` — it is the *only* class that references `OCA\Deck\*`. If you need new Deck data, extend that class rather than reaching into Deck internals from elsewhere. Every call in there is wrapped (`class_exists()` checks, `IAppManager::isEnabledForUser('deck', …)`, try/catch → `DeckUnavailableException`) because `OCA\Deck\*` is not a documented/stable public API — it has no `@since` markers and can change between Deck releases without notice.
@@ -25,9 +25,9 @@ Both are undone in a `finally` (`WorkflowRunner::clearImpersonation()`).
In cron that is *never* the user being impersonated: `null` if any Deck-owned background job ran earlier in the same `cron.php` pass, otherwise the first workflow owner touched. `null` fails every check, so Deck answers `NoPermissionException` for perfectly intact boards. This produced a real bug — see the next section. `beginUserContext()` therefore swaps that private field directly (there is no API), records the old value, and `endUserContext()` puts it back. `PermissionService` is mandatory: if it can't be pinned, `beginUserContext()` throws and the runner **skips that user entirely** rather than acting under someone else's permissions. The other three are best-effort (they only affect activity attribution and unread counts). In cron that is *never* the user being impersonated: `null` if any Deck-owned background job ran earlier in the same `cron.php` pass, otherwise the first workflow owner touched. `null` fails every check, so Deck answers `NoPermissionException` for perfectly intact boards. This produced a real bug — see the next section. `beginUserContext()` therefore swaps that private field directly (there is no API), records the old value, and `endUserContext()` puts it back. `PermissionService` is mandatory: if it can't be pinned, `beginUserContext()` throws and the runner **skips that user entirely** rather than acting under someone else's permissions. The other three are best-effort (they only affect activity attribution and unread counts).
Consequence for `getUserBoards()`: `listBoardsForCurrentUser()` stays **request-only** anyway — Deck may already have cached board lists behind that field, and the job has no use for a board *list*; it asks `findStackIds()` about one known board id. Before using any other `OCA\Deck\*` service from the runner, check whether it carries a frozen `$userId` — the failure mode is silent and user-crossing, not an error. Consequence for board lists: the app does not use `BoardService::getUserBoards()` at all (it reads that frozen field). `listOwnedBoards()` goes through `BoardMapper::findAllByOwner($uid)` instead, which takes the uid explicitly; the job still has no use for a board *list* and asks `findStackIds()` about one known board id. Before using any other `OCA\Deck\*` service from the runner, check whether it carries a frozen `$userId` — the failure mode is silent and user-crossing, not an error.
The filter logic (`WorkflowRunner::cardMatchesFilters()`, `::isOverdue()`, `::findDeadFilters()`) is deliberately `static` and side-effect-free so it's unit-testable without a real Deck installation — see `tests/Unit/Service/WorkflowRunnerFilterTest.php`. Keep new pure logic in that shape; it is the only part of this app that has tests at all. The due-date logic (`WorkflowRunner::isOverdue()`) is deliberately `static` and side-effect-free so it's unit-testable without a real Deck installation — see `tests/Unit/Service/WorkflowRunnerTest.php`. Keep new pure logic in that shape; it is the only part of this app that has tests at all.
## Workflows are auto-disabled when their Deck targets vanish ## Workflows are auto-disabled when their Deck targets vanish
@@ -40,20 +40,22 @@ The filter logic (`WorkflowRunner::cardMatchesFilters()`, `::isOverdue()`, `::fi
Archived boards deliberately do *not* trigger this (they stay readable, so `findStackIds()` succeeds), even though they're filtered out of the settings dropdowns. Archived boards deliberately do *not* trigger this (they stay readable, so `findStackIds()` succeeds), even though they're filtered out of the settings dropdowns.
## Dead filters are surfaced, never disabled ## A workflow belongs to its board's owner, not its creator
`findBrokenTarget()` covers the board and the two stacks — **not** `filter_user_ids` / `filter_label_ids`. Those are plain id lists compared with `array_intersect()` in `cardMatchesFilters()`, so an entry that no longer exists simply stops matching. With three labels of which one was deleted that is exactly right, and disabling would be wrong. The relation is **board owner ↔ workflow**, not creator ↔ workflow. When Deck transfers a board, its workflows move to the new owner.
The pathological case is a filter whose entries are *all* gone: the workflow keeps running, updates `last_run`, and matches nothing — forever, with no mail, no log line and a healthy-looking row. It happens on deleted labels and just as easily on a user losing board access, because Deck's `BoardService::deleteAcl()` calls `assignedUsersMapper->deleteByParticipantOnBoard()` and wipes that user's card assignments. - **Which boards count as "mine"**: `DeckIntegrationService::listOwnedBoards($uid)` → Deck's `BoardMapper::findAllByOwner($uid)`, one `WHERE owner = :uid` query — shared boards never come back, and as a plain QBMapper it carries no frozen uid. Trashed boards are dropped; archived ones are kept with `archived: true` so their workflows stay visible, but they're hidden from the board dropdown and rejected by `validate()`. It *throws* rather than returning `[]`, since `[]` would silently hide all of the user's workflows.
- **Listing/editing/deleting** is purely `board_id IN (listOwnedBoards)` (`WorkflowMapper::findAllForBoards()`, `WorkflowController::findOwnWorkflow()`). `user_id` plays no part, so a transferred board's workflows show up for the new owner immediately — no cron pass needed. Workflows whose board is gone disappear from the UI; the runner disables them and mails the last owner.
- **Creating/saving** validates the board against the same list. `create()`/`update()` set `user_id` to the current user.
- **The runner** needs a single user to impersonate, so it calls `WorkflowRunner::followBoardOwner()` → `DeckIntegrationService::findBoardOwner()` (plain `BoardMapper::find()`) before grouping: a known owner different from `user_id` rewrites and persists it, so the run is impersonated as — and mails go to — the current owner. A gone board keeps its last owner, so `findBrokenTarget()` can still disable it and mail them.
Two low-stakes signals, no state and no migration: `user_id` is therefore only "who the job runs as / who gets mail", refreshed from the board owner on every run — not the source of truth for who sees a workflow. Don't reintroduce `user_id` lookups in the controller.
- `WorkflowRunner::warnAboutDeadFilters()` logs a warning on every run. ## Card filters were removed — don't bring them back casually
- `workflowIssues` in `src/PersonalSettings.vue` marks the row red.
Both obey the same rule as the disable path: **only positive knowledge**. `DeckIntegrationService::findFilterOptions()` therefore *throws* instead of degrading to `[]` — unlike its siblings `listLabels()`/`listParticipants()`, which are wrapped in `call(…, [])` for the dropdowns, where an empty list is harmless. On the JS side the per-board caches store `null` for a failed request, and `isDeadFilter()` returns false for `null`; storing `[]` there would report every stack and filter of the board as deleted the moment one request fails. Don't collapse those two states back together. Workflows used to carry optional assigned-user and label filters (`filter_user_ids` / `filter_label_ids`, JSON id lists). They were removed on request; `Version1001Date20260930120000` drops both columns, and workflows that had a filter kept running *unfiltered* — an explicit decision, not an oversight. The columns must stay dropped rather than ignored: `Entity::fromRow()` calls a setter per selected column, and `Workflow` no longer has those properties.
Deliberately no mail and no `enabled = false`: one board edit can revive the filter, and there is no "already warned" column to keep a mail one-off with (unlike the disable case, which is one-off for free because a disabled workflow is never picked up again). With them went everything that only existed for them: the labels/participants endpoints, `listLabels()`/`listParticipants()`/`findFilterOptions()`, the dead-filter warnings, and `CardService::enrichCards()` in `getActiveCardsInStack()` (it only added labels/assignees/comment counts, and runs `BoardService::find()` — a permission check against Deck's frozen uid).
## The job has no interval — one run per cron pass ## The job has no interval — one run per cron pass
@@ -103,13 +105,15 @@ npm run build # production build
npm run watch # rebuild on change during development npm run watch # rebuild on change during development
``` ```
To run a single PHPUnit test: `vendor/bin/phpunit --filter testUserFilterIsOrAgainstAssignedUsers tests/Unit/Service/WorkflowRunnerFilterTest.php`. To run a single PHPUnit test: `vendor/bin/phpunit --filter testIsOverdueReturnsTrueForPastDueDate tests/Unit/Service/WorkflowRunnerTest.php`.
There is no meaningful way to test the Deck integration itself outside a real Nextcloud+Deck instance (`php occ background-job:worker 'OCA\WorkflowDeckAutomation\BackgroundJob\RunWorkflowsJob'` — the argument is a job *class*, not an app id) — the unit tests intentionally stop at the pure filter logic. There is no meaningful way to test the Deck integration itself outside a real Nextcloud+Deck instance (`php occ background-job:worker 'OCA\WorkflowDeckAutomation\BackgroundJob\RunWorkflowsJob'` — the argument is a job *class*, not an app id) — the unit tests intentionally stop at the pure due-date logic.
### Release process ### Release process
**Versioning scheme (from 34.0.0 on): `<nextcloud-major>.<minor>.<patch>`.** The leading number tracks the minimum/maximum Nextcloud major version declared in `appinfo/info.xml`'s `<dependencies><nextcloud .../>` (currently `min-version="34" max-version="34"`), not this app's own feature history - so it only changes when the supported Nextcloud major changes (e.g. dropping/adding NC 34 support bumps to `35.0.0`), and resets `minor`/`patch` to `0.0` at that point. Ordinary fixes/features within the same supported NC major bump `minor`/`patch` as usual (semver-ish, without a leading `0.`). Versions before `34.0.0` (`0.1.x`/`0.2.x`) predate this scheme. **Versioning scheme (from 34.0.0 on): `<nextcloud-major>.<minor>.<patch>`.** The leading number tracks the minimum/maximum Nextcloud major version declared in `appinfo/info.xml`'s `<dependencies><nextcloud .../>` (on this branch `min-version="35" max-version="35"`), not this app's own feature history - so it only changes when the supported Nextcloud major changes, and resets `minor`/`patch` to `0.0` at that point. Ordinary fixes/features within the same supported NC major bump `minor`/`patch` as usual (semver-ish, without a leading `0.`). Versions before `34.0.0` (`0.1.x`/`0.2.x`) predate this scheme.
This branch (`nextcloud-35`) is a permanent, separately maintained version line for Nextcloud 35, started at `35.0.0` alongside the `34.x.x` line on `main`. Backport fixes between the two lines manually where relevant; they are not merged into each other.
1. Bump `<version>` in `appinfo/info.xml` and `version` in `package.json` (keep them in sync). 1. Bump `<version>` in `appinfo/info.xml` and `version` in `package.json` (keep them in sync).
2. Commit, push to `main`, confirm the run of `.gitea/workflows/build-main.yml` is green. 2. Commit, push to `main`, confirm the run of `.gitea/workflows/build-main.yml` is green.
@@ -145,9 +149,9 @@ This replaced an earlier hand-made `RELEASE_TOKEN` repo secret. If the publish s
## Data flow / architecture map ## Data flow / architecture map
- **UI**: `src/PersonalSettings.vue` (Vue 3, mounted from `templates/settings/personal.php` into the section registered by `lib/Settings/PersonalSection.php` + `lib/Settings/Personal.php`) talks to `lib/Controller/WorkflowController.php` (an `OCSController`) via `src/api.js`, hitting OCS routes declared in `appinfo/routes.php` (`/ocs/v2.php/apps/workflow_deck_automation/api/v1/...`). - **UI**: `src/PersonalSettings.vue` (Vue 3, mounted from `templates/settings/personal.php` into the section registered by `lib/Settings/PersonalSection.php` + `lib/Settings/Personal.php`) talks to `lib/Controller/WorkflowController.php` (an `OCSController`) via `src/api.js`, hitting OCS routes declared in `appinfo/routes.php` (`/ocs/v2.php/apps/workflow_deck_automation/api/v1/...`).
- **Storage**: `lib/Db/Workflow.php` (Entity) / `lib/Db/WorkflowMapper.php` (QBMapper) over the `wfda_workflows` table, created in `lib/Migration/Version1000Date20260813120000.php`. Filter fields (`filter_user_ids`, `filter_label_ids`) are stored as JSON-encoded arrays in text columns, not join tables. - **Storage**: `lib/Db/Workflow.php` (Entity) / `lib/Db/WorkflowMapper.php` (QBMapper) over the `wfda_workflows` table, created in `lib/Migration/Version1000Date20260813120000.php`. `Version1001Date20260930120000` drops the former filter columns.
- **Automation**: `lib/BackgroundJob/RunWorkflowsJob.php` (plain `Job`, one run per cron pass) → `lib/Service/WorkflowRunner.php` (per-user impersonation + filtering, both filters OR-within-themselves and AND-between-each-other) → `lib/Service/DeckIntegrationService.php` (all actual Deck class calls) and `lib/Service/NotificationMailer.php` (email via `OCP\Mail\IMailer` to the workflow owner's account address, never a manually-entered address). - **Automation**: `lib/BackgroundJob/RunWorkflowsJob.php` (plain `Job`, one run per cron pass) → `lib/Service/WorkflowRunner.php` (per-owner impersonation, moves every overdue card) → `lib/Service/DeckIntegrationService.php` (all actual Deck class calls) and `lib/Service/NotificationMailer.php` (email via `OCP\Mail\IMailer` to the workflow owner's account address, never a manually-entered address).
- Both the controller's board/stack/label/participant lookups (for populating the settings UI dropdowns) and the runner's card reads/moves go through the same `DeckIntegrationService` — there is no separate read path. - Both the controller's board/stack lookups (for populating the settings UI dropdowns) and the runner's card reads/moves go through the same `DeckIntegrationService` — there is no separate read path.
## Composer/npm lockfiles are intentionally not committed ## Composer/npm lockfiles are intentionally not committed
@@ -176,11 +180,11 @@ This app is on `@nextcloud/vue` ^9 / Vue 3. The v8 (Vue 2) prop spellings that m
## Deck entities are "relational": getters don't return the uid string ## Deck entities are "relational": getters don't return the uid string
Deck's `RelationalEntity` swaps resolved relations for an `OCA\Deck\Db\RelationalObject` once an entity is enriched. So on an enriched board/card, `$acl->getParticipant()`, `$board->getOwner()` and a card assignment's participant return a `RelationalObject` (wrapping `OCA\Deck\Db\User`/`Group`/`Circle`), **not** a uid — the uid is its `getPrimaryKey()`. Probing for `getUID()` on the returned object finds nothing and yields `null`, which is how the settings UI's user dropdown came up empty *and* why the runner's assigned-user filter could never match. `DeckIntegrationService::unwrapUid()` handles both shapes (bare string and `RelationalObject`); route any new participant/owner field through it. Deck's `RelationalEntity` swaps resolved relations for an `OCA\Deck\Db\RelationalObject` once an entity is enriched. So on an enriched board/card, `$acl->getParticipant()`, `$board->getOwner()` and a card assignment's participant return a `RelationalObject` (wrapping `OCA\Deck\Db\User`/`Group`/`Circle`), **not** a uid — the uid is its `getPrimaryKey()`. Probing for `getUID()` on the returned object finds nothing and yields `null`, which is how the (since removed) user filter once came up empty. `DeckIntegrationService::unwrapUid()` handles both shapes (bare string and `RelationalObject`); route any new participant/owner field through it.
Two more Deck facts that bit us in the same pass: a board's ACL does **not** contain its owner (a private board has an empty ACL, so participants must be seeded with `$board->getOwner()`), and ACL entries can be groups (`type === 1`) whose members have to be expanded via `IGroupManager`. Two more Deck facts worth keeping in mind if participants are ever needed again: a board's ACL does **not** contain its owner (a private board has an empty ACL), and ACL entries can be groups (`type === 1`) whose members have to be expanded via `IGroupManager`.
**`BoardService::getUserBoards()` defaults to `$includeArchived = true`, and that flag also gates the `deleted_at = 0` condition** — with the default you get archived *and* trashed boards back. We call `getUserBoards(null, false)` (with a fallback to the no-arg form if Deck ever changes the signature) and still dedupe by id afterwards, because it merges own/group/circle boards and can return the same board twice. Stacks need no such handling: `StackMapper::findAll()` filters `deleted_at = 0` unconditionally and stacks have no archived state. **`BoardMapper::findAllByOwner()` has no archived/`deleted_at` filter at all** — trashed and archived boards come back too, which is why `listOwnedBoards()` drops trashed ones and flags archived ones itself. (`BoardService::getUserBoards()`, used earlier, merges own/shared/group/circle boards and is no longer used.) Stacks need no such handling: `StackMapper::findAll()` filters `deleted_at = 0` unconditionally and stacks have no archived state.
## Local-only notes ## Local-only notes
+7 -22
View File
@@ -1,6 +1,6 @@
# Deck Workflow-Automatisierung # Deck Workflow-Automatisierung
Nextcloud-App für **Nextcloud Hub 26 Spring (Server 34.x)**, die überfällige Karten der [Deck](https://github.com/nextcloud/deck)-App automatisch von einem Stapel in einen anderen verschiebt und optional eine E-Mail-Benachrichtigung verschickt. Nextcloud-App für **Nextcloud Hub Summer 26 (Server 35.x)**, die überfällige Karten der [Deck](https://github.com/nextcloud/deck)-App automatisch von einem Stapel in einen anderen verschiebt und optional eine E-Mail-Benachrichtigung verschickt.
Ersetzt das früher genutzte eigenständige PHP-Cron-Skript durch eine vollwertige App mit Oberfläche in den **persönlichen Einstellungen** — jeder Nutzer kann dort seine eigenen Regeln ("Workflows") anlegen, ohne Admin-Rechte oder Server-Zugriff zu benötigen. Ersetzt das früher genutzte eigenständige PHP-Cron-Skript durch eine vollwertige App mit Oberfläche in den **persönlichen Einstellungen** — jeder Nutzer kann dort seine eigenen Regeln ("Workflows") anlegen, ohne Admin-Rechte oder Server-Zugriff zu benötigen.
@@ -9,16 +9,14 @@ Ersetzt das früher genutzte eigenständige PHP-Cron-Skript durch eine vollwerti
Pro Workflow lässt sich konfigurieren: Pro Workflow lässt sich konfigurieren:
- Quell-Board und Quell-Stapel - Quell-Board und Quell-Stapel
- Ziel-Stapel, in den überfällige Karten verschoben werden - Ziel-Stapel, in den **alle** überfälligen Karten des Quell-Stapels verschoben werden
- optionaler Filter auf zugewiesene Benutzer (Karte muss **mindestens einem** der gewählten Benutzer zugewiesen sein)
- optionaler Filter auf Labels/Tags (Karte muss **mindestens eines** der gewählten Labels haben)
- Checkbox: E-Mail-Benachrichtigung an den Workflow-Besitzer, sobald eine Karte verschoben wurde - Checkbox: E-Mail-Benachrichtigung an den Workflow-Besitzer, sobald eine Karte verschoben wurde
Ein Nutzer kann beliebig viele Workflows anlegen, bearbeiten, deaktivieren oder löschen. Workflows lassen sich nur für Boards anlegen, deren Eigentümer man ist. Ein Workflow gehört dem jeweiligen Board-Eigentümer, nicht dem, der ihn angelegt hat: Wird ein Board in Deck übertragen, sieht und verwaltet ab sofort der neue Eigentümer seine Workflows, und der Hintergrundjob läuft in dessen Namen. Ein Nutzer kann beliebig viele Workflows anlegen, bearbeiten, deaktivieren oder löschen.
## Architektur ## Architektur
- **Keine HTTP/OCS-Aufrufe gegen Deck.** Alles Lesen (Boards, Stapel, Karten, Labels, zugewiesene Benutzer) und das Verschieben von Karten läuft ausschließlich über Decks eigene interne PHP-Klassen (`OCA\Deck\Service\CardService`, `StackService`, `BoardService`, `OCA\Deck\Db\CardMapper`, …), aufgelöst per Dependency Injection direkt im selben PHP-Prozess. Sämtlicher Deck-Zugriff ist in [`lib/Service/DeckIntegrationService.php`](lib/Service/DeckIntegrationService.php) gebündelt. - **Keine HTTP/OCS-Aufrufe gegen Deck.** Alles Lesen (Boards, Stapel, Karten) und das Verschieben von Karten läuft ausschließlich über Decks eigene interne PHP-Klassen (`OCA\Deck\Service\CardService`, `StackService`, `BoardService`, `OCA\Deck\Db\CardMapper`, …), aufgelöst per Dependency Injection direkt im selben PHP-Prozess. Sämtlicher Deck-Zugriff ist in [`lib/Service/DeckIntegrationService.php`](lib/Service/DeckIntegrationService.php) gebündelt.
- **Hintergrundjob statt Seitenaufruf.** [`lib/BackgroundJob/RunWorkflowsJob.php`](lib/BackgroundJob/RunWorkflowsJob.php) ist ein einfacher `Job` ohne eigenes Intervall: Er läuft bei jedem Cron-Durchlauf von Nextcloud (üblicherweise alle 5 Minuten) und ruft [`lib/Service/WorkflowRunner.php`](lib/Service/WorkflowRunner.php) auf. - **Hintergrundjob statt Seitenaufruf.** [`lib/BackgroundJob/RunWorkflowsJob.php`](lib/BackgroundJob/RunWorkflowsJob.php) ist ein einfacher `Job` ohne eigenes Intervall: Er läuft bei jedem Cron-Durchlauf von Nextcloud (üblicherweise alle 5 Minuten) und ruft [`lib/Service/WorkflowRunner.php`](lib/Service/WorkflowRunner.php) auf.
- **Rechte-Kontext je Nutzer.** Ein Hintergrundjob hat standardmäßig keinen eingeloggten Nutzer, muss aber die Regeln mehrerer Nutzer in einem einzigen Lauf auswerten. Der `WorkflowRunner` "verkörpert" deshalb für die Dauer der jeweiligen Workflows kurzzeitig den entsprechenden Besitzer. Dazu gehört mehr als `IUserSession::setUser()`: Decks Berechtigungsprüfungen lesen die Session gar nicht, sondern eine Benutzer-ID, die beim Bau des Deck-Containers einmal pro Prozess eingefroren wird. `DeckIntegrationService::beginUserContext()` setzt diesen Wert für die Dauer der Verkörperung auf den Workflow-Besitzer und stellt ihn danach wieder her; schlägt das fehl, wird der Nutzer in diesem Lauf übersprungen, statt unter fremden Rechten zu arbeiten. - **Rechte-Kontext je Nutzer.** Ein Hintergrundjob hat standardmäßig keinen eingeloggten Nutzer, muss aber die Regeln mehrerer Nutzer in einem einzigen Lauf auswerten. Der `WorkflowRunner` "verkörpert" deshalb für die Dauer der jeweiligen Workflows kurzzeitig den entsprechenden Besitzer. Dazu gehört mehr als `IUserSession::setUser()`: Decks Berechtigungsprüfungen lesen die Session gar nicht, sondern eine Benutzer-ID, die beim Bau des Deck-Containers einmal pro Prozess eingefroren wird. `DeckIntegrationService::beginUserContext()` setzt diesen Wert für die Dauer der Verkörperung auf den Workflow-Besitzer und stellt ihn danach wieder her; schlägt das fehl, wird der Nutzer in diesem Lauf übersprungen, statt unter fremden Rechten zu arbeiten.
- **E-Mail** läuft über Nextclouds eigenen `IMailer` (nutzt also den in der Nextcloud-Administration hinterlegten Mailserver) und geht an die im Profil des Workflow-Besitzers hinterlegte Adresse. - **E-Mail** läuft über Nextclouds eigenen `IMailer` (nutzt also den in der Nextcloud-Administration hinterlegten Mailserver) und geht an die im Profil des Workflow-Besitzers hinterlegte Adresse.
@@ -36,7 +34,7 @@ Ein Nutzer kann beliebig viele Workflows anlegen, bearbeiten, deaktivieren oder
## Benutzung ## Benutzung
Jeder Nutzer findet die Einstellungen unter **Persönliche Einstellungen → Deck Workflow-Automatisierung**. Dort können neue Workflows angelegt, bestehende bearbeitet oder gelöscht werden. Die Dropdowns für Board/Stapel/Label/Benutzer werden live aus Deck geladen. Zur Auswahl stehen nur aktive Boards — archivierte und im Papierkorb liegende Boards sowie gelöschte Stapel blendet Deck bzw. die App aus. Jeder Nutzer findet die Einstellungen unter **Persönliche Einstellungen → Deck Workflow-Automatisierung**. Dort können neue Workflows angelegt, bestehende bearbeitet oder gelöscht werden. Die Dropdowns für Board und Stapel werden live aus Deck geladen. Zur Auswahl stehen nur aktive Boards, deren Eigentümer man ist — geteilte, archivierte und im Papierkorb liegende Boards sowie gelöschte Stapel blendet die App aus.
### Gelöschte Boards und Stapel ### Gelöschte Boards und Stapel
@@ -48,19 +46,6 @@ Ein Workflow verweist per ID auf ein Board und zwei Stapel. Wird eines davon in
Ist Deck vorübergehend nicht erreichbar, wird **nicht** deaktiviert — der Job überspringt den Workflow und versucht es beim nächsten Lauf erneut. Archivierte Boards lösen die Deaktivierung ebenfalls nicht aus, sie sind nur in den Auswahlfeldern ausgeblendet. Ist Deck vorübergehend nicht erreichbar, wird **nicht** deaktiviert — der Job überspringt den Workflow und versucht es beim nächsten Lauf erneut. Archivierte Boards lösen die Deaktivierung ebenfalls nicht aus, sie sind nur in den Auswahlfeldern ausgeblendet.
### Gelöschte Labels und entfernte Benutzer
Filter sind ein anderer Fall: Sie werden **nicht** deaktiviert. Wird eines von drei ausgewählten Labels gelöscht, greifen die anderen beiden weiter — das abzuschalten wäre falsch.
Problematisch ist nur der Grenzfall, dass **alle** Einträge eines Filters verschwunden sind. Der Workflow läuft dann weiter, kann aber keine einzige Karte mehr treffen. Das passiert bei gelöschten Labels und ebenso, wenn ein gefilterter Benutzer die Board-Freigabe verliert — Deck entfernt dabei alle seine Kartenzuweisungen auf diesem Board.
Damit dieser Zustand nicht unsichtbar bleibt:
- **In der Übersicht** wird der Workflow rot markiert („Label-Filter trifft keine Karte mehr", „Benutzer-Filter trifft keine Karte mehr").
- **Im Hintergrundjob** landet bei jedem Lauf eine Warnung im `nextcloud.log`.
Keine E-Mail und keine Deaktivierung: Ein einziger Board-Klick kann den Filter wieder lebendig machen. Und wie bei Board und Stapel gilt auch hier — lässt sich das Board gerade nicht abfragen, wird nichts gemeldet statt etwas Falsches.
## Ausführungstakt ## Ausführungstakt
Der Hintergrundjob hat **kein eigenes Intervall** und ist auch nicht konfigurierbar: Er läuft bei **jedem** Cron-Durchlauf von Nextcloud. Der Takt ist damit exakt der des System-Crons — üblicherweise alle 5 Minuten, bei einem häufiger eingerichteten Cron entsprechend öfter. Der Hintergrundjob hat **kein eigenes Intervall** und ist auch nicht konfigurierbar: Er läuft bei **jedem** Cron-Durchlauf von Nextcloud. Der Takt ist damit exakt der des System-Crons — üblicherweise alle 5 Minuten, bei einem häufiger eingerichteten Cron entsprechend öfter.
@@ -107,7 +92,7 @@ npm run watch # Entwicklung mit automatischem Rebuild
```bash ```bash
composer run lint # php -l über lib/ und tests/ composer run lint # php -l über lib/ und tests/
composer run cs:check # nextcloud/coding-standard (php-cs-fixer) composer run cs:check # nextcloud/coding-standard (php-cs-fixer)
composer run test:unit # PHPUnit — reine Filter-Logik, benötigt keine Deck-Installation composer run test:unit # PHPUnit — reine Logik (Fälligkeitsprüfung), benötigt keine Deck-Installation
``` ```
Ein echter End-to-End-Test (Karte anlegen, Workflow konfigurieren, Hintergrundjob auslösen, Verschiebung + Mail prüfen) lässt sich nur gegen eine echte Nextcloud-34-Instanz mit installierter Deck-App durchführen, z. B. per: Ein echter End-to-End-Test (Karte anlegen, Workflow konfigurieren, Hintergrundjob auslösen, Verschiebung + Mail prüfen) lässt sich nur gegen eine echte Nextcloud-34-Instanz mit installierter Deck-App durchführen, z. B. per:
@@ -144,7 +129,7 @@ In [`.gitea/workflows/`](.gitea/workflows/):
## Datenmodell ## Datenmodell
Workflows werden in der Tabelle `wfda_workflows` gespeichert (siehe [`lib/Migration/Version1000Date20260813120000.php`](lib/Migration/Version1000Date20260813120000.php)): eine Zeile pro Workflow, mit `user_id`-Bezug, Board-/Stapel-IDs, JSON-kodierten Filterlisten sowie `enabled`/`notify_email`/`last_run`. Workflows werden in der Tabelle `wfda_workflows` gespeichert (siehe [`lib/Migration/Version1000Date20260813120000.php`](lib/Migration/Version1000Date20260813120000.php)): eine Zeile pro Workflow, mit Board-/Stapel-IDs, `user_id` (der Board-Eigentümer, in dessen Namen der Job läuft — wird bei jedem Lauf aus Deck aktualisiert) sowie `enabled`/`notify_email`/`last_run`. Die früheren Filter-Spalten `filter_user_ids`/`filter_label_ids` entfernt [`Version1001Date20260930120000`](lib/Migration/Version1001Date20260930120000.php).
## Lizenz ## Lizenz
+4 -8
View File
@@ -7,28 +7,24 @@
<summary lang="de">Verschiebt überfällige Deck-Karten automatisch anhand konfigurierbarer Regeln</summary> <summary lang="de">Verschiebt überfällige Deck-Karten automatisch anhand konfigurierbarer Regeln</summary>
<summary lang="en">Automatically moves overdue Deck cards based on configurable rules</summary> <summary lang="en">Automatically moves overdue Deck cards based on configurable rules</summary>
<description lang="de"><![CDATA[ <description lang="de"><![CDATA[
Diese App erlaubt es jedem Nutzer, in den persönlichen Einstellungen eigene Automatisierungs-Workflows für die Deck-App anzulegen: Diese App erlaubt es jedem Nutzer, in den persönlichen Einstellungen Automatisierungs-Workflows für seine eigenen Deck-Boards anzulegen:
* Quell-Board und Quell-Stapel wählen * Quell-Board und Quell-Stapel wählen
* Ziel-Stapel wählen, in den überfällige Karten verschoben werden * Ziel-Stapel wählen, in den überfällige Karten verschoben werden
* optional nach zugewiesenen Benutzern filtern
* optional nach Labels/Tags filtern
* optional eine E-Mail-Benachrichtigung an sich selbst aktivieren * optional eine E-Mail-Benachrichtigung an sich selbst aktivieren
Ein Hintergrundjob prüft regelmäßig alle aktiven Workflows und verschiebt Karten, deren Fälligkeitsdatum überschritten wurde, ausschließlich über die internen PHP-Klassen der Deck-App (keine HTTP/OCS-Aufrufe). Ein Hintergrundjob prüft regelmäßig alle aktiven Workflows und verschiebt Karten, deren Fälligkeitsdatum überschritten wurde, ausschließlich über die internen PHP-Klassen der Deck-App (keine HTTP/OCS-Aufrufe).
]]></description> ]]></description>
<description lang="en"><![CDATA[ <description lang="en"><![CDATA[
This app lets every user configure their own Deck automation workflows from Personal settings: This app lets every user configure Deck automation workflows for the boards they own from Personal settings:
* pick a source board and source stack * pick a source board and source stack
* pick a destination stack overdue cards get moved to * pick a destination stack overdue cards get moved to
* optionally filter by assigned users
* optionally filter by labels/tags
* optionally enable an email notification to themselves * optionally enable an email notification to themselves
A background job periodically evaluates all enabled workflows and moves cards whose due date has passed, using Deck's own internal PHP classes only (no HTTP/OCS calls). A background job periodically evaluates all enabled workflows and moves cards whose due date has passed, using Deck's own internal PHP classes only (no HTTP/OCS calls).
]]></description> ]]></description>
<version>34.0.2</version> <version>35.1.0</version>
<licence>agpl</licence> <licence>agpl</licence>
<author mail="patrick@niebel.ing">Patrick Niebeling</author> <author mail="patrick@niebel.ing">Patrick Niebeling</author>
<namespace>WorkflowDeckAutomation</namespace> <namespace>WorkflowDeckAutomation</namespace>
@@ -40,7 +36,7 @@ A background job periodically evaluates all enabled workflows and moves cards wh
<database min-version="9.4">pgsql</database> <database min-version="9.4">pgsql</database>
<database>sqlite</database> <database>sqlite</database>
<database min-version="8.0">mysql</database> <database min-version="8.0">mysql</database>
<nextcloud min-version="34" max-version="34"/> <nextcloud min-version="35" max-version="35"/>
</dependencies> </dependencies>
<background-jobs> <background-jobs>
<job>OCA\WorkflowDeckAutomation\BackgroundJob\RunWorkflowsJob</job> <job>OCA\WorkflowDeckAutomation\BackgroundJob\RunWorkflowsJob</job>
-2
View File
@@ -11,7 +11,5 @@ return [
['name' => 'workflow#boards', 'url' => '/api/v1/boards', 'verb' => 'GET'], ['name' => 'workflow#boards', 'url' => '/api/v1/boards', 'verb' => 'GET'],
['name' => 'workflow#stacks', 'url' => '/api/v1/boards/{boardId}/stacks', 'verb' => 'GET'], ['name' => 'workflow#stacks', 'url' => '/api/v1/boards/{boardId}/stacks', 'verb' => 'GET'],
['name' => 'workflow#labels', 'url' => '/api/v1/boards/{boardId}/labels', 'verb' => 'GET'],
['name' => 'workflow#participants', 'url' => '/api/v1/boards/{boardId}/participants', 'verb' => 'GET'],
], ],
]; ];
+55 -49
View File
@@ -38,24 +38,23 @@ class WorkflowController extends OCSController {
return $user->getUID(); return $user->getUID();
} }
/**
* Every workflow on a board the user owns, no matter who created it: a
* workflow belongs to its board's owner, and follows the board when
* Deck transfers it.
*/
#[NoAdminRequired] #[NoAdminRequired]
public function index(): DataResponse { public function index(): DataResponse {
$workflows = $this->workflowMapper->findAllForUser($this->currentUserId()); $workflows = $this->workflowMapper->findAllForBoards($this->ownedBoardIds());
return new DataResponse(array_map(static fn (Workflow $w) => $w->jsonSerialize(), $workflows)); return new DataResponse(array_map(static fn (Workflow $w) => $w->jsonSerialize(), $workflows));
} }
/**
* @param string[] $filterUserIds
* @param int[] $filterLabelIds
*/
#[NoAdminRequired] #[NoAdminRequired]
public function create( public function create(
string $title, string $title,
int $boardId, int $boardId,
int $sourceStackId, int $sourceStackId,
int $targetStackId, int $targetStackId,
array $filterUserIds = [],
array $filterLabelIds = [],
bool $notifyEmail = false, bool $notifyEmail = false,
bool $enabled = true, bool $enabled = true,
): DataResponse { ): DataResponse {
@@ -63,16 +62,12 @@ class WorkflowController extends OCSController {
$workflow = new Workflow(); $workflow = new Workflow();
$workflow->setUserId($this->currentUserId()); $workflow->setUserId($this->currentUserId());
$this->applyFields($workflow, $title, $boardId, $sourceStackId, $targetStackId, $filterUserIds, $filterLabelIds, $notifyEmail, $enabled); $this->applyFields($workflow, $title, $boardId, $sourceStackId, $targetStackId, $notifyEmail, $enabled);
$workflow = $this->workflowMapper->insert($workflow); $workflow = $this->workflowMapper->insert($workflow);
return new DataResponse($workflow->jsonSerialize(), Http::STATUS_CREATED); return new DataResponse($workflow->jsonSerialize(), Http::STATUS_CREATED);
} }
/**
* @param string[] $filterUserIds
* @param int[] $filterLabelIds
*/
#[NoAdminRequired] #[NoAdminRequired]
public function update( public function update(
int $id, int $id,
@@ -80,20 +75,16 @@ class WorkflowController extends OCSController {
int $boardId, int $boardId,
int $sourceStackId, int $sourceStackId,
int $targetStackId, int $targetStackId,
array $filterUserIds = [],
array $filterLabelIds = [],
bool $notifyEmail = false, bool $notifyEmail = false,
bool $enabled = true, bool $enabled = true,
): DataResponse { ): DataResponse {
$workflow = $this->findOwnWorkflow($id);
$this->validate($title, $boardId, $sourceStackId, $targetStackId); $this->validate($title, $boardId, $sourceStackId, $targetStackId);
try { // Kept in step with the board owner so the job runs as, and mails,
$workflow = $this->workflowMapper->findForUser($id, $this->currentUserId()); // the right user; validate() made sure the editor owns the board.
} catch (DoesNotExistException $e) { $workflow->setUserId($this->currentUserId());
throw new OCSNotFoundException('Workflow not found'); $this->applyFields($workflow, $title, $boardId, $sourceStackId, $targetStackId, $notifyEmail, $enabled);
}
$this->applyFields($workflow, $title, $boardId, $sourceStackId, $targetStackId, $filterUserIds, $filterLabelIds, $notifyEmail, $enabled);
$workflow = $this->workflowMapper->update($workflow); $workflow = $this->workflowMapper->update($workflow);
return new DataResponse($workflow->jsonSerialize()); return new DataResponse($workflow->jsonSerialize());
@@ -101,12 +92,7 @@ class WorkflowController extends OCSController {
#[NoAdminRequired] #[NoAdminRequired]
public function destroy(int $id): DataResponse { public function destroy(int $id): DataResponse {
try { $workflow = $this->findOwnWorkflow($id);
$workflow = $this->workflowMapper->findForUser($id, $this->currentUserId());
} catch (DoesNotExistException $e) {
throw new OCSNotFoundException('Workflow not found');
}
$this->workflowMapper->delete($workflow); $this->workflowMapper->delete($workflow);
return new DataResponse([]); return new DataResponse([]);
} }
@@ -114,7 +100,7 @@ class WorkflowController extends OCSController {
#[NoAdminRequired] #[NoAdminRequired]
public function boards(): DataResponse { public function boards(): DataResponse {
$this->assertDeck(); $this->assertDeck();
return new DataResponse($this->deckService->listBoardsForCurrentUser()); return new DataResponse($this->ownedBoards());
} }
#[NoAdminRequired] #[NoAdminRequired]
@@ -123,16 +109,38 @@ class WorkflowController extends OCSController {
return new DataResponse($this->deckService->listStacks($boardId)); return new DataResponse($this->deckService->listStacks($boardId));
} }
#[NoAdminRequired] private function findOwnWorkflow(int $id): Workflow {
public function labels(int $boardId): DataResponse { try {
$this->assertDeck(); $workflow = $this->workflowMapper->findById($id);
return new DataResponse($this->deckService->listLabels($boardId)); } catch (DoesNotExistException $e) {
throw new OCSNotFoundException('Workflow not found');
}
if (!in_array($workflow->getBoardId(), $this->ownedBoardIds(), true)) {
// Same answer as for a missing id: don't reveal other users' workflows.
throw new OCSNotFoundException('Workflow not found');
}
return $workflow;
} }
#[NoAdminRequired] /**
public function participants(int $boardId): DataResponse { * @return array<int, array{id: int, title: string, archived: bool}>
*/
private function ownedBoards(): array {
$userId = $this->currentUserId();
$this->assertDeck(); $this->assertDeck();
return new DataResponse($this->deckService->listParticipants($boardId)); try {
return $this->deckService->listOwnedBoards($userId);
} catch (DeckUnavailableException $e) {
throw new OCSPreconditionFailedException('Could not load your Deck boards: ' . $e->getMessage());
}
}
/**
* @return int[]
*/
private function ownedBoardIds(): array {
return array_map(static fn (array $board) => $board['id'], $this->ownedBoards());
} }
private function assertDeck(): void { private function assertDeck(): void {
@@ -161,12 +169,18 @@ class WorkflowController extends OCSController {
// not "Deck is unreachable". // not "Deck is unreachable".
$this->assertDeck(); $this->assertDeck();
$boardIds = array_map( // Only boards the user owns are listed, so this also enforces the
static fn (array $board) => (int)$board['id'], // owner rule. Archived boards stay listed (their workflows must stay
$this->deckService->listBoardsForCurrentUser(), // visible) but are no target for a new or changed workflow.
); $board = null;
if (!in_array($boardId, $boardIds, true)) { foreach ($this->ownedBoards() as $candidate) {
throw new OCSBadRequestException('The selected board does not exist or is not accessible'); if ($candidate['id'] === $boardId) {
$board = $candidate;
break;
}
}
if ($board === null || $board['archived']) {
throw new OCSBadRequestException('The selected board does not exist, is archived or is not owned by you');
} }
$stackIds = array_map( $stackIds = array_map(
@@ -178,18 +192,12 @@ class WorkflowController extends OCSController {
} }
} }
/**
* @param string[] $filterUserIds
* @param int[] $filterLabelIds
*/
private function applyFields( private function applyFields(
Workflow $workflow, Workflow $workflow,
string $title, string $title,
int $boardId, int $boardId,
int $sourceStackId, int $sourceStackId,
int $targetStackId, int $targetStackId,
array $filterUserIds,
array $filterLabelIds,
bool $notifyEmail, bool $notifyEmail,
bool $enabled, bool $enabled,
): void { ): void {
@@ -197,8 +205,6 @@ class WorkflowController extends OCSController {
$workflow->setBoardId($boardId); $workflow->setBoardId($boardId);
$workflow->setSourceStackId($sourceStackId); $workflow->setSourceStackId($sourceStackId);
$workflow->setTargetStackId($targetStackId); $workflow->setTargetStackId($targetStackId);
$workflow->setFilterUserIds($filterUserIds === [] ? null : json_encode(array_values($filterUserIds)));
$workflow->setFilterLabelIds($filterLabelIds === [] ? null : json_encode(array_values($filterLabelIds)));
$workflow->setNotifyEmail($notifyEmail); $workflow->setNotifyEmail($notifyEmail);
$workflow->setEnabled($enabled); $workflow->setEnabled($enabled);
} }
-35
View File
@@ -18,10 +18,6 @@ use OCP\DB\Types;
* @method void setSourceStackId(int $sourceStackId) * @method void setSourceStackId(int $sourceStackId)
* @method int getTargetStackId() * @method int getTargetStackId()
* @method void setTargetStackId(int $targetStackId) * @method void setTargetStackId(int $targetStackId)
* @method string|null getFilterUserIds()
* @method void setFilterUserIds(?string $filterUserIds)
* @method string|null getFilterLabelIds()
* @method void setFilterLabelIds(?string $filterLabelIds)
* @method bool getNotifyEmail() * @method bool getNotifyEmail()
* @method void setNotifyEmail(bool $notifyEmail) * @method void setNotifyEmail(bool $notifyEmail)
* @method bool getEnabled() * @method bool getEnabled()
@@ -35,8 +31,6 @@ class Workflow extends Entity implements \JsonSerializable {
protected $boardId; protected $boardId;
protected $sourceStackId; protected $sourceStackId;
protected $targetStackId; protected $targetStackId;
protected $filterUserIds;
protected $filterLabelIds;
protected $notifyEmail; protected $notifyEmail;
protected $enabled; protected $enabled;
protected $lastRun; protected $lastRun;
@@ -48,38 +42,11 @@ class Workflow extends Entity implements \JsonSerializable {
$this->addType('boardId', Types::INTEGER); $this->addType('boardId', Types::INTEGER);
$this->addType('sourceStackId', Types::INTEGER); $this->addType('sourceStackId', Types::INTEGER);
$this->addType('targetStackId', Types::INTEGER); $this->addType('targetStackId', Types::INTEGER);
$this->addType('filterUserIds', Types::STRING);
$this->addType('filterLabelIds', Types::STRING);
$this->addType('notifyEmail', Types::BOOLEAN); $this->addType('notifyEmail', Types::BOOLEAN);
$this->addType('enabled', Types::BOOLEAN); $this->addType('enabled', Types::BOOLEAN);
$this->addType('lastRun', Types::DATETIME); $this->addType('lastRun', Types::DATETIME);
} }
/**
* @return string[]
*/
public function getFilterUserIdsArray(): array {
return $this->decodeIds($this->getFilterUserIds());
}
/**
* @return int[]
*/
public function getFilterLabelIdsArray(): array {
return array_map('intval', $this->decodeIds($this->getFilterLabelIds()));
}
/**
* @return string[]
*/
private function decodeIds(?string $json): array {
if ($json === null || $json === '') {
return [];
}
$decoded = json_decode($json, true);
return is_array($decoded) ? array_values($decoded) : [];
}
public function jsonSerialize(): array { public function jsonSerialize(): array {
return [ return [
'id' => $this->getId(), 'id' => $this->getId(),
@@ -88,8 +55,6 @@ class Workflow extends Entity implements \JsonSerializable {
'boardId' => $this->getBoardId(), 'boardId' => $this->getBoardId(),
'sourceStackId' => $this->getSourceStackId(), 'sourceStackId' => $this->getSourceStackId(),
'targetStackId' => $this->getTargetStackId(), 'targetStackId' => $this->getTargetStackId(),
'filterUserIds' => $this->getFilterUserIdsArray(),
'filterLabelIds' => $this->getFilterLabelIdsArray(),
'notifyEmail' => (bool)$this->getNotifyEmail(), 'notifyEmail' => (bool)$this->getNotifyEmail(),
'enabled' => (bool)$this->getEnabled(), 'enabled' => (bool)$this->getEnabled(),
'lastRun' => $this->getLastRun()?->format(\DateTimeInterface::ATOM), 'lastRun' => $this->getLastRun()?->format(\DateTimeInterface::ATOM),
+8 -5
View File
@@ -22,24 +22,27 @@ class WorkflowMapper extends QBMapper {
* @throws DoesNotExistException * @throws DoesNotExistException
* @throws MultipleObjectsReturnedException * @throws MultipleObjectsReturnedException
*/ */
public function findForUser(int $id, string $userId): Workflow { public function findById(int $id): Workflow {
$qb = $this->db->getQueryBuilder(); $qb = $this->db->getQueryBuilder();
$qb->select('*') $qb->select('*')
->from($this->getTableName()) ->from($this->getTableName())
->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT))) ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
->andWhere($qb->expr()->eq('user_id', $qb->createNamedParameter($userId)));
return $this->findEntity($qb); return $this->findEntity($qb);
} }
/** /**
* @param int[] $boardIds
* @return Workflow[] * @return Workflow[]
*/ */
public function findAllForUser(string $userId): array { public function findAllForBoards(array $boardIds): array {
if ($boardIds === []) {
return [];
}
$qb = $this->db->getQueryBuilder(); $qb = $this->db->getQueryBuilder();
$qb->select('*') $qb->select('*')
->from($this->getTableName()) ->from($this->getTableName())
->where($qb->expr()->eq('user_id', $qb->createNamedParameter($userId))) ->where($qb->expr()->in('board_id', $qb->createNamedParameter($boardIds, IQueryBuilder::PARAM_INT_ARRAY)))
->orderBy('id', 'ASC'); ->orderBy('id', 'ASC');
return $this->findEntities($qb); return $this->findEntities($qb);
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace OCA\WorkflowDeckAutomation\Migration;
use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;
/**
* Drops the assigned-user and label filters. Workflows that had one keep
* running, now unfiltered — that was an explicit product decision.
*
* The columns have to go rather than just be ignored: Entity::fromRow()
* calls a setter for every selected column, and the Workflow entity no
* longer has these properties.
*/
class Version1001Date20260930120000 extends SimpleMigrationStep {
public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
/** @var ISchemaWrapper $schema */
$schema = $schemaClosure();
if (!$schema->hasTable('wfda_workflows')) {
return null;
}
$table = $schema->getTable('wfda_workflows');
$changed = false;
foreach (['filter_user_ids', 'filter_label_ids'] as $column) {
if ($table->hasColumn($column)) {
$table->dropColumn($column);
$changed = true;
}
}
return $changed ? $schema : null;
}
}
+65 -237
View File
@@ -14,9 +14,7 @@ use OCA\Deck\Service\PermissionService;
use OCA\Deck\Service\StackService; use OCA\Deck\Service\StackService;
use OCP\App\IAppManager; use OCP\App\IAppManager;
use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Db\DoesNotExistException;
use OCP\IGroupManager;
use OCP\IUser; use OCP\IUser;
use OCP\IUserManager;
use OCP\Server; use OCP\Server;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use ReflectionProperty; use ReflectionProperty;
@@ -36,16 +34,9 @@ class DeckIntegrationService {
private const DECK_APP_ID = 'deck'; private const DECK_APP_ID = 'deck';
/** /**
* Deck's Acl::PERMISSION_TYPE_* values, inlined so this class keeps * Deck's Acl::PERMISSION_READ, inlined so a moved or renamed constant
* working (degrading to "treat it as a user") if Deck ever moves or * cannot fatal this class. It is the key under which
* renames the constants. * PermissionService::getPermissions() reports read access.
*/
private const ACL_TYPE_USER = 0;
private const ACL_TYPE_GROUP = 1;
/**
* Deck's Acl::PERMISSION_READ, inlined for the same reason. It is the key
* under which PermissionService::getPermissions() reports read access.
*/ */
private const ACL_PERMISSION_READ = 0; private const ACL_PERMISSION_READ = 0;
@@ -75,8 +66,6 @@ class DeckIntegrationService {
public function __construct( public function __construct(
private IAppManager $appManager, private IAppManager $appManager,
private IUserManager $userManager,
private IGroupManager $groupManager,
private LoggerInterface $logger, private LoggerInterface $logger,
) { ) {
} }
@@ -172,55 +161,44 @@ class DeckIntegrationService {
} }
/** /**
* @return array<int, array{id: int, title: string}> * The boards `$userId` owns — the only boards workflows may live on, and
* the boards whose workflows that user sees and manages.
* *
* Only ever call this from a *request*: getUserBoards() reads the uid * One query: BoardMapper::findAllByOwner() is `WHERE owner = :uid`, so
* BoardService froze at construction time, and beginUserContext() cannot * shared boards never come back, and as a plain QBMapper it has none of
* help here — it repoints that field, but Deck may already have cached * the frozen-uid state of BoardService::getUserBoards(). It does return
* board lists behind it, and the job has no use for a board *list* * archived and trashed boards; trashed ones are dropped here, archived
* anyway. It asks findStackIds() about one known board id instead. * ones are kept but flagged — their workflows still exist and must stay
* visible, they just aren't offered as a new target.
*
* Throws instead of degrading to `[]`: an empty list would read as "you
* own no boards" and hide every workflow the user has.
*
* @return array<int, array{id: int, title: string, archived: bool}>
* @throws DeckUnavailableException
*/ */
public function listBoardsForCurrentUser(): array { public function listOwnedBoards(string $userId): array {
$boards = $this->call(function () { $boards = $this->call(
$boardService = $this->resolve(BoardService::class); fn () => $this->resolve(BoardMapper::class)->findAllByOwner($userId),
try { [],
// getUserBoards(?int $since, bool $includeArchived, …): with true,
// the default $includeArchived = true, Deck skips the );
// `archived = false AND deleted_at = 0` conditions entirely,
// so archived *and* trashed boards come back. Ask for the
// filtered query instead of sorting them out afterwards.
return $boardService->getUserBoards(null, false);
} catch (Throwable $e) {
// Older/newer Deck with a different signature: fall back to
// the unfiltered call, isBoardHidden() below still filters.
return $boardService->getUserBoards();
}
}, []);
// Deck merges own/group/circle boards, so the same board can come
// back more than once; and boards in the trash or archived ones are
// no useful automation target. Keyed by id => deduplicated.
$result = []; $result = [];
foreach ($boards as $board) { foreach ($boards as $board) {
$id = (int)$board->getId(); if (method_exists($board, 'getDeletedAt') && (int)$board->getDeletedAt() > 0) {
if (isset($result[$id]) || $this->isBoardHidden($board)) {
continue; continue;
} }
$id = (int)$board->getId();
$title = $board->getTitle(); $title = $board->getTitle();
$result[$id] = [ $result[] = [
'id' => $id, 'id' => $id,
'title' => (is_string($title) && $title !== '') ? $title : ('#' . $id), 'title' => (is_string($title) && $title !== '') ? $title : ('#' . $id),
'archived' => method_exists($board, 'getArchived') && (bool)$board->getArchived(),
]; ];
} }
return array_values($result); return $result;
}
private function isBoardHidden(mixed $board): bool {
if (method_exists($board, 'getDeletedAt') && (int)$board->getDeletedAt() > 0) {
return true;
}
return method_exists($board, 'getArchived') && $board->getArchived() === true;
} }
/** /**
@@ -293,6 +271,37 @@ class DeckIntegrationService {
return array_map(static fn ($stack) => (int)$stack->getId(), $stacks); return array_map(static fn ($stack) => (int)$stack->getId(), $stacks);
} }
/**
* The uid of the board's current owner — the user a workflow on that
* board belongs to. Workflows follow the board: when Deck transfers its
* ownership, they move to the new owner along with it.
*
* Read through BoardMapper, a plain QBMapper without user state, so it
* answers the same in a request and in cron. Trashed and archived boards
* still report their owner. `null` only if the board row is gone; every
* other failure throws, like findStackIds().
*
* @throws DeckUnavailableException
*/
public function findBoardOwner(int $boardId): ?string {
try {
$board = $this->resolve(BoardMapper::class)->find($boardId);
} catch (DeckUnavailableException $e) {
throw $e;
} catch (Throwable $e) {
if ($this->isMissing($e)) {
return null;
}
throw new DeckUnavailableException('Could not read owner of board ' . $boardId . ': ' . $e->getMessage(), 0, $e);
}
$owner = $this->unwrapUid($board->getOwner());
if ($owner === null) {
throw new DeckUnavailableException('Board ' . $boardId . ' has no readable owner');
}
return $owner;
}
/** /**
* Deck's own exception classes are referenced by name: `is_a()` with a * Deck's own exception classes are referenced by name: `is_a()` with a
* string simply returns false when the class does not exist, so a missing * string simply returns false when the class does not exist, so a missing
@@ -311,51 +320,6 @@ class DeckIntegrationService {
return is_a($e, 'OCA\Deck\NotFoundException'); return is_a($e, 'OCA\Deck\NotFoundException');
} }
/**
* @return array<int, array{id: int, title: string, color: string|null}>
*/
public function listLabels(int $boardId): array {
$labels = $this->call(fn () => $this->readLabels($boardId), []);
return array_map(
static fn ($label) => ['id' => (int)$label->getId(), 'title' => $label->getTitle(), 'color' => $label->getColor()],
$labels,
);
}
/**
* What a workflow's filters *could* legitimately refer to on this board.
*
* Unlike listLabels()/listParticipants() this throws instead of degrading
* to an empty list, because its only caller draws a conclusion from
* emptiness ("this filter cannot match anything any more"). Same rule as
* findStackIds(): a Deck hiccup must never be read as positive knowledge.
*
* @return array{labelIds: int[], participantUids: string[]}
* @throws DeckUnavailableException
*/
public function findFilterOptions(int $boardId): array {
try {
$board = $this->readBoard($boardId);
return [
'labelIds' => array_map(
static fn ($label) => (int)$label->getId(),
$board->getLabels() ?? [],
),
'participantUids' => array_values(array_unique($this->collectParticipantUids($board))),
];
} catch (DeckUnavailableException $e) {
throw $e;
} catch (Throwable $e) {
$this->logger->error('Could not read filter options of board ' . $boardId . ': ' . $e->getMessage(), [
'app' => 'workflow_deck_automation',
'exception' => $e,
]);
throw new DeckUnavailableException('Deck call failed: ' . $e->getMessage(), 0, $e);
}
}
/** /**
* Titles of a workflow's board and stacks, for the notification mail. * Titles of a workflow's board and stacks, for the notification mail.
* *
@@ -389,85 +353,9 @@ class DeckIntegrationService {
return $title !== '' ? $title : ('#' . $id); return $title !== '' ? $title : ('#' . $id);
} }
/**
* Everyone who can hold a card on this board: the board owner (who is
* *not* part of the ACL — a private board has an empty ACL) plus every
* ACL entry, with group shares expanded to their members.
*
* @return array<int, array{uid: string, displayName: string}>
*/
public function listParticipants(int $boardId): array {
$uids = $this->call(fn () => $this->collectParticipantUids($this->readBoard($boardId)), []);
$participants = [];
foreach ($uids as $uid) {
if (isset($participants[$uid])) {
continue;
}
$participants[$uid] = [
'uid' => $uid,
'displayName' => $this->userManager->get($uid)?->getDisplayName() ?? $uid,
];
}
return array_values($participants);
}
/**
* The enriched board — `$fullDetails = true` is what populates labels and
* the ACL. Shared by every caller that needs one so a single Deck read
* serves them all.
*/
private function readBoard(int $boardId): mixed {
return $this->resolve(BoardService::class)->find($boardId, true);
}
private function readLabels(int $boardId): array {
return $this->readBoard($boardId)->getLabels() ?? [];
}
/**
* @return string[] may contain duplicates
*/
private function collectParticipantUids(mixed $board): array {
$uids = [];
$owner = $this->unwrapUid($board->getOwner());
if ($owner !== null) {
$uids[] = $owner;
}
foreach ($board->getAcl() ?? [] as $entry) {
$principal = $this->extractParticipantUid($entry);
if ($principal === null) {
continue;
}
$type = method_exists($entry, 'getType') ? (int)$entry->getType() : self::ACL_TYPE_USER;
if ($type === self::ACL_TYPE_GROUP) {
array_push($uids, ...$this->groupMemberUids($principal));
} elseif ($type === self::ACL_TYPE_USER) {
$uids[] = $principal;
}
// Circles and federated shares are skipped: their members
// cannot be resolved to plain uids here.
}
return $uids;
}
/**
* @return string[]
*/
private function groupMemberUids(string $groupId): array {
$group = $this->groupManager->get($groupId);
if ($group === null) {
return [];
}
return array_map(static fn (IUser $user) => $user->getUID(), $group->getUsers());
}
/** /**
* Cards in the given stack that are neither archived, deleted nor marked * Cards in the given stack that are neither archived, deleted nor marked
* done, enriched so getAssignedUsers()/getLabels() are populated. * done.
* *
* The `deletedAt` check is not redundant: Deck's * The `deletedAt` check is not redundant: Deck's
* `CardMapper::findAllByStack()` filters on `stack_id` and * `CardMapper::findAllByStack()` filters on `stack_id` and
@@ -479,17 +367,11 @@ class DeckIntegrationService {
*/ */
public function getActiveCardsInStack(int $stackId): array { public function getActiveCardsInStack(int $stackId): array {
return $this->call(function () use ($stackId) { return $this->call(function () use ($stackId) {
$cardMapper = $this->resolve(CardMapper::class); // Deliberately not enriched: CardService::enrichCards() only adds
$cardService = $this->resolve(CardService::class); // labels, assignees and comment counts — none of which is used —
// and runs BoardService::find(), a permission check against
$cards = $cardMapper->findAllByStack($stackId); // Deck's frozen uid (see beginUserContext()).
// enrichCards() mutates each $cards entry in place (labels, assigned users, ...) but $cards = $this->resolve(CardMapper::class)->findAllByStack($stackId);
// *returns* CardDetails wrappers whose own fields (duedate, stackId, ...) were never
// copied from the wrapped card - only its overridden jsonSerialize() reads through to
// them. Capturing that return value here made every card's getDuedate()/getDaysUntilDue()
// resolve to null, so isOverdue() was always false and no workflow ever matched a card.
// Keep using the original, now-enriched $cards instead.
$cardService->enrichCards($cards);
return array_values(array_filter($cards, static function (Card $card) { return array_values(array_filter($cards, static function (Card $card) {
if (method_exists($card, 'getDeletedAt') && (int)$card->getDeletedAt() > 0) { if (method_exists($card, 'getDeletedAt') && (int)$card->getDeletedAt() > 0) {
@@ -500,35 +382,6 @@ class DeckIntegrationService {
}, []); }, []);
} }
/**
* @return string[]
*/
public function getCardAssignedUserIds(Card $card): array {
$assigned = $card->getAssignedUsers() ?? [];
$uids = [];
foreach ($assigned as $entry) {
$uid = $this->extractParticipantUid($entry);
if ($uid !== null) {
$uids[] = $uid;
}
}
return $uids;
}
/**
* @return int[]
*/
public function getCardLabelIds(Card $card): array {
$labels = $card->getLabels() ?? [];
$ids = [];
foreach ($labels as $label) {
if (method_exists($label, 'getId')) {
$ids[] = (int)$label->getId();
}
}
return $ids;
}
/** /**
* Moves a card to another stack using Deck's own reorder logic * Moves a card to another stack using Deck's own reorder logic
* (the exact same code path behind Deck's "move card" action). * (the exact same code path behind Deck's "move card" action).
@@ -575,31 +428,6 @@ class DeckIntegrationService {
return Server::get($class); return Server::get($class);
} }
/**
* Deck's assignment/ACL entries are internal, undocumented value
* objects whose exact accessor shape has changed across versions, so
* we probe the common accessor names defensively instead of relying
* on one fixed method signature.
*/
private function extractParticipantUid(mixed $entry): ?string {
$uid = $this->unwrapUid($entry);
if ($uid !== null) {
return $uid;
}
if (!is_object($entry)) {
return null;
}
foreach (['getParticipant', 'getUid', 'getParticipantUid', 'getUserId'] as $method) {
if (method_exists($entry, $method)) {
$uid = $this->unwrapUid($entry->$method());
if ($uid !== null) {
return $uid;
}
}
}
return null;
}
/** /**
* Turns whatever Deck hands out for a "participant"/"owner" field into * Turns whatever Deck hands out for a "participant"/"owner" field into
* a plain uid. * a plain uid.
+51 -114
View File
@@ -55,7 +55,9 @@ class WorkflowRunner {
} }
$byUser = []; $byUser = [];
$owners = [];
foreach ($workflows as $workflow) { foreach ($workflows as $workflow) {
$this->followBoardOwner($workflow, $owners);
$byUser[$workflow->getUserId()][] = $workflow; $byUser[$workflow->getUserId()][] = $workflow;
} }
@@ -78,6 +80,55 @@ class WorkflowRunner {
} }
} }
/**
* A workflow belongs to its board's owner, not to whoever created it: if
* Deck transferred the board, the workflow moves along to the new owner —
* it then runs as them, and they get its mails.
*
* Only a known owner rewrites `user_id`. A board that is gone keeps its
* last owner, so findBrokenTarget() can disable the workflow and mail
* them; a Deck error keeps it too, and the run just goes ahead as before.
*
* @param array<int, ?string> $owners per-run cache, board id => owner
*/
private function followBoardOwner(Workflow $workflow, array &$owners): void {
$boardId = $workflow->getBoardId();
if (!array_key_exists($boardId, $owners)) {
try {
$owners[$boardId] = $this->deckService->findBoardOwner($boardId);
} catch (Throwable $e) {
$this->logger->warning('Could not determine the owner of board {board}: ' . $e->getMessage(), [
'app' => 'workflow_deck_automation',
'board' => $boardId,
]);
$owners[$boardId] = null;
}
}
$owner = $owners[$boardId];
if ($owner === null || $owner === $workflow->getUserId()) {
return;
}
$this->logger->info('Workflow {id} follows board {board} to its new owner {owner}.', [
'app' => 'workflow_deck_automation',
'id' => $workflow->getId(),
'board' => $boardId,
'owner' => $owner,
]);
$workflow->setUserId($owner);
try {
$this->workflowMapper->update($workflow);
} catch (Throwable $e) {
// Not persisted, but this run still goes to the right user; the
// next one tries again.
$this->logger->warning('Could not store the new owner of workflow {id}: ' . $e->getMessage(), [
'app' => 'workflow_deck_automation',
'id' => $workflow->getId(),
]);
}
}
/** /**
* @param Workflow[] $workflows * @param Workflow[] $workflows
*/ */
@@ -158,10 +209,6 @@ class WorkflowRunner {
return; return;
} }
$filterUserIds = $workflow->getFilterUserIdsArray();
$filterLabelIds = $workflow->getFilterLabelIdsArray();
$this->warnAboutDeadFilters($workflow, $filterUserIds, $filterLabelIds);
// Resolved at most once per run, and only if a card actually moves // Resolved at most once per run, and only if a card actually moves
// and the workflow wants a mail — this is decoration, not a check. // and the workflow wants a mail — this is decoration, not a check.
$targets = null; $targets = null;
@@ -173,12 +220,6 @@ class WorkflowRunner {
continue; continue;
} }
$assignedUserIds = $this->deckService->getCardAssignedUserIds($card);
$labelIds = $this->deckService->getCardLabelIds($card);
if (!self::cardMatchesFilters($assignedUserIds, $labelIds, $filterUserIds, $filterLabelIds)) {
continue;
}
$this->logger->info('Card {card} ("{title}") matches workflow {id}; moving to stack {target}.', [ $this->logger->info('Card {card} ("{title}") matches workflow {id}; moving to stack {target}.', [
'app' => 'workflow_deck_automation', 'app' => 'workflow_deck_automation',
'card' => $card->getId(), 'card' => $card->getId(),
@@ -276,52 +317,6 @@ class WorkflowRunner {
return true; return true;
} }
/**
* A filter whose every entry has been deleted from the board is not an
* error — the workflow still runs, it just cannot match a single card any
* more, forever, without anything in the UI or the log saying so. That is
* the one failure mode of this app that is completely invisible, so it
* gets a log line on every run.
*
* Explicitly *not* a reason to disable the workflow or mail the user: a
* filter with three labels of which one was deleted still works as
* intended, and even a fully dead filter may be one board edit away from
* being live again. The settings page shows the same condition in red.
*
* @param string[] $filterUserIds
* @param int[] $filterLabelIds
*/
private function warnAboutDeadFilters(Workflow $workflow, array $filterUserIds, array $filterLabelIds): void {
if ($filterUserIds === [] && $filterLabelIds === []) {
return;
}
try {
$options = $this->deckService->findFilterOptions($workflow->getBoardId());
} catch (DeckUnavailableException $e) {
// Same rule as everywhere else: no answer is not a bad answer.
$this->logger->debug('Could not check the filters of workflow {id}: ' . $e->getMessage(), [
'app' => 'workflow_deck_automation',
'id' => $workflow->getId(),
]);
return;
}
$dead = self::findDeadFilters($filterUserIds, $filterLabelIds, $options['participantUids'], $options['labelIds']);
if ($dead !== []) {
$this->logger->warning(
'Workflow {id} can no longer match any card: none of its ' . implode('/', $dead)
. ' filter entries exists on board {board} any more',
[
'app' => 'workflow_deck_automation',
'id' => $workflow->getId(),
'board' => $workflow->getBoardId(),
],
);
}
}
/** /**
* Compares the card's actual due timestamp against $now instead of Deck's own * Compares the card's actual due timestamp against $now instead of Deck's own
* Card::getDaysUntilDue(), which truncates both sides to midnight before diffing * Card::getDaysUntilDue(), which truncates both sides to midnight before diffing
@@ -335,64 +330,6 @@ class WorkflowRunner {
return $duedate !== null && $duedate < $now; return $duedate !== null && $duedate < $now;
} }
/**
* Which filters cannot match anything any more, because not one of their
* entries is still offered by the board. An empty filter is not dead, it
* is "no restriction on this dimension" — the same reading as in
* cardMatchesFilters(), and getting it backwards would report every
* unfiltered workflow as broken.
*
* Static and side-effect free for the same reason as the matching logic:
* testable without a Deck installation.
*
* @param string[] $filterUserIds
* @param int[] $filterLabelIds
* @param string[] $boardUserIds everyone who can hold a card on the board
* @param int[] $boardLabelIds the board's remaining labels
* @return string[] any of 'label', 'user', in that order
*/
public static function findDeadFilters(
array $filterUserIds,
array $filterLabelIds,
array $boardUserIds,
array $boardLabelIds,
): array {
$dead = [];
if ($filterLabelIds !== [] && array_intersect($filterLabelIds, $boardLabelIds) === []) {
$dead[] = 'label';
}
if ($filterUserIds !== [] && array_intersect($filterUserIds, $boardUserIds) === []) {
$dead[] = 'user';
}
return $dead;
}
/**
* Pure filter-matching logic (kept static/side-effect free so it can
* be unit tested without real Deck objects). Both filters are OR
* inside themselves and AND between each other: an empty filter list
* means "no restriction on this dimension".
*
* @param string[] $cardAssignedUserIds
* @param int[] $cardLabelIds
* @param string[] $filterUserIds
* @param int[] $filterLabelIds
*/
public static function cardMatchesFilters(
array $cardAssignedUserIds,
array $cardLabelIds,
array $filterUserIds,
array $filterLabelIds,
): bool {
if ($filterUserIds !== [] && array_intersect($filterUserIds, $cardAssignedUserIds) === []) {
return false;
}
if ($filterLabelIds !== [] && array_intersect($filterLabelIds, $cardLabelIds) === []) {
return false;
}
return true;
}
/** /**
* @throws DeckUnavailableException if Deck cannot be pinned to $user * @throws DeckUnavailableException if Deck cannot be pinned to $user
*/ */
+1 -1
View File
@@ -29,6 +29,6 @@ class PersonalSection implements IIconSection {
} }
public function getIcon(): string { public function getIcon(): string {
return $this->urlGenerator->imagePath(Application::APP_ID, 'app-dark.svg'); return $this->urlGenerator->imagePath(Application::APP_ID, 'app.svg');
} }
} }
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "workflow_deck_automation", "name": "workflow_deck_automation",
"version": "34.0.2", "version": "35.1.0",
"private": true, "private": true,
"type": "module", "type": "module",
"description": "Automates moving overdue Deck cards between stacks, configurable per user.", "description": "Automates moving overdue Deck cards between stacks, configurable per user.",
+62 -119
View File
@@ -14,17 +14,18 @@
<table v-if="workflows.length" class="wfda-table"> <table v-if="workflows.length" class="wfda-table">
<thead> <thead>
<tr> <tr>
<th>Board</th>
<th>Titel</th> <th>Titel</th>
<th>Von Stapel</th> <th>Von Stapel</th>
<th>Nach Stapel</th> <th>Nach Stapel</th>
<th>Filter</th>
<th>E-Mail</th> <th>E-Mail</th>
<th>Aktiv</th> <th>Aktiv</th>
<th /> <th />
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<tr v-for="workflow in workflows" :key="workflow.id"> <tr v-for="workflow in sortedWorkflows" :key="workflow.id">
<td>{{ boardLabel(workflow.boardId) }}</td>
<td> <td>
{{ workflow.title }} {{ workflow.title }}
<span v-if="workflowIssues[workflow.id]" class="wfda-issue"> <span v-if="workflowIssues[workflow.id]" class="wfda-issue">
@@ -33,16 +34,8 @@
</td> </td>
<td>{{ stackLabel(workflow.boardId, workflow.sourceStackId) }}</td> <td>{{ stackLabel(workflow.boardId, workflow.sourceStackId) }}</td>
<td>{{ stackLabel(workflow.boardId, workflow.targetStackId) }}</td> <td>{{ stackLabel(workflow.boardId, workflow.targetStackId) }}</td>
<td> <td>{{ yesNo(workflow.notifyEmail) }}</td>
<span v-if="!workflow.filterUserIds.length && !workflow.filterLabelIds.length">–</span> <td>{{ yesNo(workflow.enabled) }}</td>
<span v-else>
<span v-if="workflow.filterUserIds.length">{{ workflow.filterUserIds.length }} Benutzer</span>
<span v-if="workflow.filterUserIds.length && workflow.filterLabelIds.length">, </span>
<span v-if="workflow.filterLabelIds.length">{{ workflow.filterLabelIds.length }} Label</span>
</span>
</td>
<td>{{ workflow.notifyEmail ? 'Ja' : 'Nein' }}</td>
<td>{{ workflow.enabled ? 'Ja' : 'Nein' }}</td>
<td class="wfda-actions"> <td class="wfda-actions">
<NcButton variant="tertiary" @click="editWorkflow(workflow)"> <NcButton variant="tertiary" @click="editWorkflow(workflow)">
Bearbeiten Bearbeiten
@@ -75,6 +68,9 @@
:reduce="option => option.value" :reduce="option => option.value"
placeholder="Board wählen" placeholder="Board wählen"
@update:model-value="onBoardChange" /> @update:model-value="onBoardChange" />
<NcNoteCard v-if="!boardOptions.length" type="info">
Workflows können nur für Boards angelegt werden, deren Eigentümer du bist.
</NcNoteCard>
<NcSelect <NcSelect
v-model="form.sourceStackId" v-model="form.sourceStackId"
@@ -92,24 +88,6 @@
:disabled="!form.boardId" :disabled="!form.boardId"
placeholder="Ziel-Stapel wählen" /> placeholder="Ziel-Stapel wählen" />
<NcSelect
v-model="form.filterUserIds"
input-label="Nur für zugewiesene Benutzer (optional)"
:options="participantOptions"
:reduce="option => option.value"
:disabled="!form.boardId"
multiple
placeholder="Alle Benutzer" />
<NcSelect
v-model="form.filterLabelIds"
input-label="Nur mit Label (optional)"
:options="labelOptions"
:reduce="option => option.value"
:disabled="!form.boardId"
multiple
placeholder="Alle Labels" />
<NcCheckboxRadioSwitch v-model="form.notifyEmail"> <NcCheckboxRadioSwitch v-model="form.notifyEmail">
Benachrichtigungs-E-Mail an mich senden Benachrichtigungs-E-Mail an mich senden
</NcCheckboxRadioSwitch> </NcCheckboxRadioSwitch>
@@ -148,8 +126,6 @@ import {
createWorkflow, createWorkflow,
deleteWorkflow, deleteWorkflow,
fetchBoards, fetchBoards,
fetchLabels,
fetchParticipants,
fetchStacks, fetchStacks,
fetchWorkflows, fetchWorkflows,
updateWorkflow, updateWorkflow,
@@ -161,8 +137,6 @@ const workflows = ref([])
const boards = ref([]) const boards = ref([])
// Per board, and `null` whenever the request failed — see loadStacksFor(). // Per board, and `null` whenever the request failed — see loadStacksFor().
const stacksByBoard = reactive({}) const stacksByBoard = reactive({})
const labelsByBoard = reactive({})
const participantsByBoard = reactive({})
const showForm = ref(false) const showForm = ref(false)
const saving = ref(false) const saving = ref(false)
@@ -170,12 +144,44 @@ const formError = ref('')
const editingId = ref(null) const editingId = ref(null)
const stackOptions = ref([]) const stackOptions = ref([])
const labelOptions = ref([]) // Which board the list above currently belongs to.
const participantOptions = ref([])
// Which board the three lists above currently belong to.
const loadedBoardId = ref(null) const loadedBoardId = ref(null)
const boardOptions = computed(() => boards.value.map((board) => ({ value: board.id, label: board.title }))) const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' })
// The backend only returns boards the user owns. Archived ones are in there
// so their workflows keep a board name, but are no target for new ones.
const boardOptions = computed(() => boards.value
.filter((board) => !board.archived || board.id === form.boardId)
.map((board) => ({ value: board.id, label: board.title }))
.sort((a, b) => collator.compare(a.label, b.label)))
/**
* Alphabetical by the columns as displayed, left to right: board, title,
* source stack, target stack, e-mail, active.
*/
const sortedWorkflows = computed(() => {
const sortKeys = (workflow) => [
boardLabel(workflow.boardId),
workflow.title,
stackLabel(workflow.boardId, workflow.sourceStackId),
stackLabel(workflow.boardId, workflow.targetStackId),
yesNo(workflow.notifyEmail),
yesNo(workflow.enabled),
]
return workflows.value
.map((workflow) => ({ workflow, keys: sortKeys(workflow) }))
.sort((a, b) => {
for (let i = 0; i < a.keys.length; i++) {
const result = collator.compare(a.keys[i], b.keys[i])
if (result !== 0) {
return result
}
}
return a.workflow.id - b.workflow.id
})
.map((entry) => entry.workflow)
})
// Source and target must differ, so each dropdown hides what the other one // Source and target must differ, so each dropdown hides what the other one
// already holds — the error message on save stays as the backstop for // already holds — the error message on save stays as the backstop for
@@ -184,15 +190,9 @@ const sourceStackOptions = computed(() => stackOptions.value.filter((option) =>
const targetStackOptions = computed(() => stackOptions.value.filter((option) => option.value !== form.sourceStackId)) const targetStackOptions = computed(() => stackOptions.value.filter((option) => option.value !== form.sourceStackId))
/** /**
* Workflows that stopped working, keyed by id. Two different kinds: * Workflows whose board or stacks were deleted in Deck, keyed by id. The
* * background job switches these off by itself, but a row that just stopped
* - Board or stacks deleted in Deck. The background job switches these off * working needs to say so instead of looking healthy.
* by itself, but a row that just stopped working needs to say so instead
* of looking healthy.
* - Every entry of a filter deleted from the board. Nothing switches those
* off — deliberately, since one deleted label out of three is harmless —
* yet a filter that cannot match a single card any more is otherwise
* completely invisible: the workflow keeps running and moves nothing.
*/ */
const workflowIssues = computed(() => { const workflowIssues = computed(() => {
const issues = {} const issues = {}
@@ -214,39 +214,13 @@ const workflowIssues = computed(() => {
} }
if (missing.length) { if (missing.length) {
issues[workflow.id] = `${missing.join(' und ')} nicht mehr vorhanden` issues[workflow.id] = `${missing.join(' und ')} nicht mehr vorhanden`
continue
} }
} }
const dead = []
if (isDeadFilter(workflow.filterLabelIds, labelsByBoard[workflow.boardId], 'id')) {
dead.push('Label-Filter')
}
if (isDeadFilter(workflow.filterUserIds, participantsByBoard[workflow.boardId], 'uid')) {
dead.push('Benutzer-Filter')
}
if (dead.length > 1) {
issues[workflow.id] = `${dead.join(' und ')} treffen keine Karte mehr`
} else if (dead.length) {
issues[workflow.id] = `${dead[0]} trifft keine Karte mehr`
}
} }
return issues return issues
}) })
/**
* True only on positive knowledge: the filter has entries, the board's list
* was actually loaded, and not one entry is still on it. A failed request
* (null) says nothing and must not turn a healthy row red.
*/
function isDeadFilter(selected, available, key) {
if (!selected.length || !available) {
return false
}
return !selected.some((value) => available.some((entry) => entry[key] === value))
}
const form = reactive(emptyForm()) const form = reactive(emptyForm())
function emptyForm() { function emptyForm() {
@@ -255,13 +229,20 @@ function emptyForm() {
boardId: null, boardId: null,
sourceStackId: null, sourceStackId: null,
targetStackId: null, targetStackId: null,
filterUserIds: [],
filterLabelIds: [],
notifyEmail: false, notifyEmail: false,
enabled: true, enabled: true,
} }
} }
function boardLabel(boardId) {
const board = boards.value.find((entry) => entry.id === boardId)
return board ? board.title : `#${boardId}`
}
function yesNo(value) {
return value ? 'Ja' : 'Nein'
}
function stackLabel(boardId, stackId) { function stackLabel(boardId, stackId) {
const stacks = stacksByBoard[boardId] const stacks = stacksByBoard[boardId]
if (!stacks) { if (!stacks) {
@@ -281,23 +262,6 @@ async function loadStacksFor(boardId) {
stacksByBoard[boardId] = await fetchStacks(boardId).catch(() => null) stacksByBoard[boardId] = await fetchStacks(boardId).catch(() => null)
} }
/**
* Labels and participants of a board — needed only to judge whether a stored
* filter can still match anything, so this is fetched just for the boards of
* workflows that actually use filters.
*/
async function loadFiltersFor(boardId) {
if (!boardId || labelsByBoard[boardId]) {
return
}
const [labels, participants] = await Promise.all([
fetchLabels(boardId).catch(() => null),
fetchParticipants(boardId).catch(() => null),
])
labelsByBoard[boardId] = labels
participantsByBoard[boardId] = participants
}
async function loadAll() { async function loadAll() {
loading.value = true loading.value = true
loadError.value = '' loadError.value = ''
@@ -305,13 +269,7 @@ async function loadAll() {
const [loadedWorkflows, loadedBoards] = await Promise.all([fetchWorkflows(), fetchBoards()]) const [loadedWorkflows, loadedBoards] = await Promise.all([fetchWorkflows(), fetchBoards()])
workflows.value = loadedWorkflows workflows.value = loadedWorkflows
boards.value = loadedBoards boards.value = loadedBoards
await Promise.all(loadedWorkflows.flatMap((workflow) => { await Promise.all(loadedWorkflows.map((workflow) => loadStacksFor(workflow.boardId)))
const pending = [loadStacksFor(workflow.boardId)]
if (workflow.filterLabelIds.length || workflow.filterUserIds.length) {
pending.push(loadFiltersFor(workflow.boardId))
}
return pending
}))
} catch (e) { } catch (e) {
loadError.value = 'Konnte Workflows oder Deck-Boards nicht laden. Ist die Deck-App aktiviert?' loadError.value = 'Konnte Workflows oder Deck-Boards nicht laden. Ist die Deck-App aktiviert?'
} finally { } finally {
@@ -320,36 +278,25 @@ async function loadAll() {
} }
/** /**
* Fills the stack/label/user dropdowns for a board without touching the * Fills the stack dropdowns for a board without touching the current
* current selection — that separation matters: editing a workflow has to * selection — that separation matters: editing a workflow has to load the
* load the same options but must keep the stored stacks and filters. * same options but must keep the stored stacks.
*/ */
async function loadBoardOptions(boardId) { async function loadBoardOptions(boardId) {
stackOptions.value = [] stackOptions.value = []
labelOptions.value = []
participantOptions.value = []
loadedBoardId.value = boardId ?? null loadedBoardId.value = boardId ?? null
if (!boardId) { if (!boardId) {
return return
} }
// One failing endpoint must not take the other two dropdowns down with it. const stacks = await fetchStacks(boardId).catch(() => null)
const [stacks, labels, participants] = await Promise.all([
fetchStacks(boardId).catch(() => null),
fetchLabels(boardId).catch(() => null),
fetchParticipants(boardId).catch(() => null),
])
// Feed the overview's caches too, so its red markers agree with what the // Feed the overview's cache too, so its red markers agree with what the
// form just loaded. `null` propagates on purpose: it means "unknown". // form just loaded. `null` propagates on purpose: it means "unknown".
stacksByBoard[boardId] = stacks stacksByBoard[boardId] = stacks
labelsByBoard[boardId] = labels
participantsByBoard[boardId] = participants
stackOptions.value = (stacks ?? []).map((stack) => ({ value: stack.id, label: stack.title })) stackOptions.value = (stacks ?? []).map((stack) => ({ value: stack.id, label: stack.title }))
labelOptions.value = (labels ?? []).map((label) => ({ value: label.id, label: label.title }))
participantOptions.value = (participants ?? []).map((participant) => ({ value: participant.uid, label: participant.displayName }))
} }
/** /**
@@ -364,8 +311,6 @@ async function onBoardChange(boardId) {
form.sourceStackId = null form.sourceStackId = null
form.targetStackId = null form.targetStackId = null
form.filterUserIds = []
form.filterLabelIds = []
await loadBoardOptions(boardId) await loadBoardOptions(boardId)
} }
@@ -384,8 +329,6 @@ async function editWorkflow(workflow) {
boardId: workflow.boardId, boardId: workflow.boardId,
sourceStackId: workflow.sourceStackId, sourceStackId: workflow.sourceStackId,
targetStackId: workflow.targetStackId, targetStackId: workflow.targetStackId,
filterUserIds: [...workflow.filterUserIds],
filterLabelIds: [...workflow.filterLabelIds],
notifyEmail: workflow.notifyEmail, notifyEmail: workflow.notifyEmail,
enabled: workflow.enabled, enabled: workflow.enabled,
}) })
-10
View File
@@ -33,13 +33,3 @@ export async function fetchStacks(boardId) {
const { data } = await axios.get(ocsUrl(`/boards/${boardId}/stacks`)) const { data } = await axios.get(ocsUrl(`/boards/${boardId}/stacks`))
return data.ocs.data return data.ocs.data
} }
export async function fetchLabels(boardId) {
const { data } = await axios.get(ocsUrl(`/boards/${boardId}/labels`))
return data.ocs.data
}
export async function fetchParticipants(boardId) {
const { data } = await axios.get(ocsUrl(`/boards/${boardId}/participants`))
return data.ocs.data
}
@@ -1,83 +0,0 @@
<?php
declare(strict_types=1);
namespace OCA\WorkflowDeckAutomation\Tests\Unit\Service;
use DateTimeImmutable;
use OCA\WorkflowDeckAutomation\Service\WorkflowRunner;
use PHPUnit\Framework\TestCase;
class WorkflowRunnerFilterTest extends TestCase {
public function testIsOverdueReturnsFalseWithoutDueDate(): void {
$this->assertFalse(WorkflowRunner::isOverdue(null, new DateTimeImmutable('2026-01-15 12:00:00')));
}
public function testIsOverdueReturnsFalseForFutureDueDate(): void {
$now = new DateTimeImmutable('2026-01-15 12:00:00');
$this->assertFalse(WorkflowRunner::isOverdue($now->modify('+1 hour'), $now));
$this->assertFalse(WorkflowRunner::isOverdue($now->modify('+3 days'), $now));
}
public function testIsOverdueReturnsTrueForPastDueDate(): void {
$now = new DateTimeImmutable('2026-01-15 12:00:00');
$this->assertTrue(WorkflowRunner::isOverdue($now->modify('-1 hour'), $now));
$this->assertTrue(WorkflowRunner::isOverdue($now->modify('-30 days'), $now));
}
public function testIsOverdueReturnsTrueForADueTimeEarlierTheSameDay(): void {
// Regression: comparing whole calendar days (as Deck's own
// Card::getDaysUntilDue() does) reports a card due earlier today as
// "0 days until due", not overdue, until the calendar date rolls
// over - holding every card back for up to 24h after it actually
// fell due. isOverdue() must compare the real timestamps instead.
$now = new DateTimeImmutable('2026-01-15 12:00:00');
$this->assertTrue(WorkflowRunner::isOverdue(new DateTimeImmutable('2026-01-15 06:00:00'), $now));
}
public function testNoFiltersMatchesAnyCard(): void {
$this->assertTrue(WorkflowRunner::cardMatchesFilters(['alice'], [1, 2], [], []));
$this->assertTrue(WorkflowRunner::cardMatchesFilters([], [], [], []));
}
public function testUserFilterIsOrAgainstAssignedUsers(): void {
$this->assertTrue(WorkflowRunner::cardMatchesFilters(['alice', 'bob'], [], ['bob', 'carol'], []));
$this->assertFalse(WorkflowRunner::cardMatchesFilters(['alice'], [], ['bob', 'carol'], []));
}
public function testLabelFilterIsOrAgainstCardLabels(): void {
$this->assertTrue(WorkflowRunner::cardMatchesFilters([], [1, 2], [], [2, 3]));
$this->assertFalse(WorkflowRunner::cardMatchesFilters([], [1], [], [2, 3]));
}
public function testUserAndLabelFiltersAreCombinedWithAnd(): void {
// user matches, label does not -> overall false
$this->assertFalse(WorkflowRunner::cardMatchesFilters(['alice'], [1], ['alice'], [99]));
// both match -> true
$this->assertTrue(WorkflowRunner::cardMatchesFilters(['alice'], [1], ['alice'], [1]));
}
public function testEmptyFiltersAreNeverDead(): void {
// "no restriction" must not be reported as a broken filter, however
// little the board has left to offer.
$this->assertSame([], WorkflowRunner::findDeadFilters([], [], [], []));
$this->assertSame([], WorkflowRunner::findDeadFilters([], [], ['alice'], [1]));
}
public function testFilterSurvivesAsLongAsOneEntryRemains(): void {
$this->assertSame([], WorkflowRunner::findDeadFilters(['alice', 'bob'], [1, 2], ['bob'], [2]));
}
public function testFilterIsDeadWhenEveryEntryIsGone(): void {
$this->assertSame(['label'], WorkflowRunner::findDeadFilters([], [1, 2], [], [3]));
$this->assertSame(['user'], WorkflowRunner::findDeadFilters(['alice'], [], ['bob'], []));
$this->assertSame(
['label', 'user'],
WorkflowRunner::findDeadFilters(['alice'], [1], ['bob'], [2]),
);
}
public function testAnEmptyBoardKillsOnlyTheFiltersThatAreSet(): void {
$this->assertSame(['label'], WorkflowRunner::findDeadFilters([], [1], [], []));
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace OCA\WorkflowDeckAutomation\Tests\Unit\Service;
use DateTimeImmutable;
use OCA\WorkflowDeckAutomation\Service\WorkflowRunner;
use PHPUnit\Framework\TestCase;
class WorkflowRunnerTest extends TestCase {
public function testIsOverdueReturnsFalseWithoutDueDate(): void {
$this->assertFalse(WorkflowRunner::isOverdue(null, new DateTimeImmutable('2026-01-15 12:00:00')));
}
public function testIsOverdueReturnsFalseForFutureDueDate(): void {
$now = new DateTimeImmutable('2026-01-15 12:00:00');
$this->assertFalse(WorkflowRunner::isOverdue($now->modify('+1 hour'), $now));
$this->assertFalse(WorkflowRunner::isOverdue($now->modify('+3 days'), $now));
}
public function testIsOverdueReturnsTrueForPastDueDate(): void {
$now = new DateTimeImmutable('2026-01-15 12:00:00');
$this->assertTrue(WorkflowRunner::isOverdue($now->modify('-1 hour'), $now));
$this->assertTrue(WorkflowRunner::isOverdue($now->modify('-30 days'), $now));
}
public function testIsOverdueReturnsTrueForADueTimeEarlierTheSameDay(): void {
// Regression: comparing whole calendar days (as Deck's own
// Card::getDaysUntilDue() does) reports a card due earlier today as
// "0 days until due", not overdue, until the calendar date rolls
// over - holding every card back for up to 24h after it actually
// fell due. isOverdue() must compare the real timestamps instead.
$now = new DateTimeImmutable('2026-01-15 12:00:00');
$this->assertTrue(WorkflowRunner::isOverdue(new DateTimeImmutable('2026-01-15 06:00:00'), $now));
}
}