6 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
18 changed files with 374 additions and 1074 deletions

No files matched your search

+25 -54
View File
@@ -4,35 +4,14 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## 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 [Deck](https://github.com/nextcloud/deck) cards from one stack to another once their due date or start date has passed, 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
**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.
## `method_exists()` cannot see Deck's getters — use `property_exists()`
`Card`, `Board`, `Label`, `Acl` and `Assignment` declare **no getters as real code**. `getStartdate()`, `getDuedate()`, `getDeletedAt()`, `getArchived()`, even `getId()` are `@method` docblocks resolved by `OCP\AppFramework\Db\Entity::__call()` (`Entity` itself declares neither `getId()` nor `setId()`). `method_exists()` ignores `__call()` by definition, so **every `method_exists($deckEntity, 'getSomething')` probe in this app is permanently false**, on every Deck version, and the guarded branch is dead code that fails open or closed without a sound.
`DeckIntegrationService::getCardDate()` therefore probes `property_exists($card, 'startdate')` — the protected property declaration is visible, and it is exactly what `Entity::getter()` checks before throwing `BadFunctionCallException`. Use that shape for any new optional Deck field.
**Known dead probes still in the tree** (each one a separate fix, none of them yet made — verify against a live instance before touching, since the symptoms are silent):
- `getCardLabelIds()` / `extractParticipantUid()` — always return `[]`/`null`, so **label and assigned-user filters cannot match any card**, and ACL participants never reach the settings dropdown. Only the board owner survives, because `RelationalObject::getPrimaryKey()` *is* real code — which is why the bug is invisible on a private board (empty ACL, owner = the user themselves) and looks fixed.
- `getActiveCardsInStack()`'s `getDeletedAt` check — trashed cards are moved.
- `findStackIds()`'s `getDeletedAt` check — a board in the trash is not recognised as gone.
- `isBoardHidden()` — dead, but masked by `getUserBoards(null, false)` doing the filtering server-side.
## The Deck version floor lives in code, because info.xml cannot express it
`DeckIntegrationService::MIN_DECK_VERSION` (`1.18.0`) plus the `version_compare()` in `assertDeckAvailable()` is the *only* enforcement point for "this app needs a recent Deck". Neither the server's `resources/app-info.xsd` nor the app store's `info.xsd` has an app-to-app dependency element — `<dependencies>` takes only `php`, `database`, `command`, `lib`, `owncloud`, `nextcloud`, `architecture`, `backend`. Don't go looking for a `<app min-version=…>`; it does not exist in either schema.
`<nextcloud min-version="34" max-version="34"/>` already does most of the work and is the strictest pin available: **Deck 1.18.x is the only Deck release line declaring `>=34.0.0,<35.0.0`**, and 1.18.0 is exactly the release that added the card start date (`Card::$startdate`, PR #7749). So on any Nextcloud this app installs on, Deck already has that field, and 1.17.x cannot be enabled at all (its own `max-version` is 33, so a server upgrade to 34 disables it). What the version check still covers is a Deck dropped in by hand or checked out from git.
`version_compare()` sorts `1.18.0-beta.x` *below* `1.18.0`. That is intended — pre-releases of that line may predate the field. Since `assertDeckAvailable()` is called from both the controller (→ `OCSPreconditionFailedException`, visible as an error on the settings page) and the runner (→ skip + info log), a too-old Deck degrades in both places instead of failing halfway through a card move.
## Per-user impersonation in the background job
`RunWorkflowsJob` has no logged-in user by default and must evaluate workflows belonging to many different users within one PHP process. `lib/Service/WorkflowRunner.php` therefore groups workflows by owner and impersonates each owner in turn. **Impersonation here is two steps, and `IUserSession::setUser()` is the one that barely matters:**
@@ -46,21 +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).
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()`, `::hasPassed()`, `::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.
## Due date or start date, per workflow
Each workflow carries a `date_field` (`'due'` | `'start'`, `Workflow::DATE_FIELD_*`) deciding which Deck card date it watches. `WorkflowRunner::hasPassed()` (formerly `isOverdue()`) is one function for both, because the comparison is identical — the raw timestamp against `$now` — and the whole argument against Deck's day-truncating `getDaysUntilDue()` applies unchanged to the start date. What differs is only the wording, in the UI and in `NotificationMailer`.
Three places keep an unknown value from becoming a surprise trigger, and all three resolve **towards the due date**, because that is what every workflow meant before the choice existed:
- the column default `'due'`, which is also the entire migration for existing rows (`Version1001Date20260825120000`, a separate step because `Version1000…` is wrapped in `hasTable()` and would never reach an existing install),
- `Workflow::getDateFieldOrDue()`, for entities that were never near the database and for hand-edited rows,
- `DeckIntegrationService::CARD_DATE_PROPERTIES`'s `?? DEFAULT_CARD_DATE`.
The controller is the exception: it *rejects* an unknown `dateField` instead of normalising it, since a client asking for a rule it would not get should hear about it.
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
@@ -73,20 +40,22 @@ The controller is the exception: it *rejects* an unknown `dateField` instead of
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.
- `workflowIssues` in `src/PersonalSettings.vue` marks the row red.
## Card filters were removed — don't bring them back casually
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
@@ -136,13 +105,15 @@ npm run build # production build
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
**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).
2. Commit, push to `main`, confirm the run of `.gitea/workflows/build-main.yml` is green.
@@ -178,9 +149,9 @@ This replaced an earlier hand-made `RELEASE_TOKEN` repo secret. If the publish s
## 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/...`).
- **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.
- **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).
- 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.
- **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-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 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
@@ -209,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'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
+7 -25
View File
@@ -1,8 +1,6 @@
# Deck Workflow-Automatisierung
Nextcloud-App für **Nextcloud Hub 26 Spring (Server 34.x)**, die Karten der [Deck](https://github.com/nextcloud/deck)-App automatisch von einem Stapel in einen anderen verschiebt, sobald ihr Fälligkeits- oder Startdatum erreicht ist, und optional eine E-Mail-Benachrichtigung verschickt.
Setzt **Deck ab 1.18.0** voraus (die Version, die das Startdatum eingeführt hat) — auf Nextcloud 34 ist das automatisch erfüllt, da 1.18.x die einzige dort freigegebene Deck-Reihe ist.
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.
@@ -11,17 +9,14 @@ Ersetzt das früher genutzte eigenständige PHP-Cron-Skript durch eine vollwerti
Pro Workflow lässt sich konfigurieren:
- Quell-Board und Quell-Stapel
- Ziel-Stapel, in den die Karten verschoben werden
- **auslösendes Datum: Fälligkeitsdatum oder Startdatum der Karte** (Karten ohne das gewählte Datum werden nie verschoben; Regeln aus älteren Versionen laufen unverändert auf dem Fälligkeitsdatum)
- 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)
- Ziel-Stapel, in den **alle** überfälligen Karten des Quell-Stapels verschoben werden
- 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
- **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.
- **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.
@@ -39,7 +34,7 @@ Ein Nutzer kann beliebig viele Workflows anlegen, bearbeiten, deaktivieren oder
## 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
@@ -51,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.
### 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
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.
@@ -110,7 +92,7 @@ npm run watch # Entwicklung mit automatischem Rebuild
```bash
composer run lint # php -l über lib/ und tests/
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:
@@ -147,7 +129,7 @@ In [`.gitea/workflows/`](.gitea/workflows/):
## 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
+10 -20
View File
@@ -4,37 +4,27 @@
<id>workflow_deck_automation</id>
<name lang="de">Deck Workflow-Automatisierung</name>
<name lang="en">Deck Workflow Automation</name>
<summary lang="de">Verschiebt Deck-Karten automatisch anhand konfigurierbarer Regeln</summary>
<summary lang="en">Automatically moves Deck cards based on configurable rules</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>
<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
* Ziel-Stapel wählen, in den die Karten verschoben werden
* je Regel wählen, ob das Fälligkeits- oder das Startdatum der Karte ausgewertet wird
* optional nach zugewiesenen Benutzern filtern
* optional nach Labels/Tags filtern
* Ziel-Stapel wählen, in den überfällige Karten verschoben werden
* optional eine E-Mail-Benachrichtigung an sich selbst aktivieren
Ein Hintergrundjob prüft regelmäßig alle aktiven Workflows und verschiebt Karten, deren gewähltes Datum in der Vergangenheit liegt, ausschließlich über die internen PHP-Klassen der Deck-App (keine HTTP/OCS-Aufrufe).
Voraussetzung: Nextcloud 34 und die Deck-App ab Version 1.18.0 – die einzige Deck-Reihe, die für Nextcloud 34 freigegeben ist.
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 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 destination stack the cards get moved to
* pick, per rule, whether the card's due date or its start date is evaluated
* optionally filter by assigned users
* optionally filter by labels/tags
* pick a destination stack overdue cards get moved to
* optionally enable an email notification to themselves
A background job periodically evaluates all enabled workflows and moves cards whose chosen date lies in the past, using Deck's own internal PHP classes only (no HTTP/OCS calls).
Requires Nextcloud 34 and Deck 1.18.0 or newer - the only Deck release line supported on Nextcloud 34.
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>
<version>34.1.0</version>
<version>35.1.0</version>
<licence>agpl</licence>
<author mail="patrick@niebel.ing">Patrick Niebeling</author>
<namespace>WorkflowDeckAutomation</namespace>
@@ -46,7 +36,7 @@ Requires Nextcloud 34 and Deck 1.18.0 or newer - the only Deck release line supp
<database min-version="9.4">pgsql</database>
<database>sqlite</database>
<database min-version="8.0">mysql</database>
<nextcloud min-version="34" max-version="34"/>
<nextcloud min-version="35" max-version="35"/>
</dependencies>
<background-jobs>
<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#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'],
],
];
+58 -62
View File
@@ -38,42 +38,36 @@ class WorkflowController extends OCSController {
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]
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));
}
/**
* @param string[] $filterUserIds
* @param int[] $filterLabelIds
*/
#[NoAdminRequired]
public function create(
string $title,
int $boardId,
int $sourceStackId,
int $targetStackId,
array $filterUserIds = [],
array $filterLabelIds = [],
string $dateField = Workflow::DATE_FIELD_DUE,
bool $notifyEmail = false,
bool $enabled = true,
): DataResponse {
$this->validate($title, $boardId, $sourceStackId, $targetStackId, $dateField);
$this->validate($title, $boardId, $sourceStackId, $targetStackId);
$workflow = new Workflow();
$workflow->setUserId($this->currentUserId());
$this->applyFields($workflow, $title, $boardId, $sourceStackId, $targetStackId, $filterUserIds, $filterLabelIds, $dateField, $notifyEmail, $enabled);
$this->applyFields($workflow, $title, $boardId, $sourceStackId, $targetStackId, $notifyEmail, $enabled);
$workflow = $this->workflowMapper->insert($workflow);
return new DataResponse($workflow->jsonSerialize(), Http::STATUS_CREATED);
}
/**
* @param string[] $filterUserIds
* @param int[] $filterLabelIds
*/
#[NoAdminRequired]
public function update(
int $id,
@@ -81,21 +75,16 @@ class WorkflowController extends OCSController {
int $boardId,
int $sourceStackId,
int $targetStackId,
array $filterUserIds = [],
array $filterLabelIds = [],
string $dateField = Workflow::DATE_FIELD_DUE,
bool $notifyEmail = false,
bool $enabled = true,
): DataResponse {
$this->validate($title, $boardId, $sourceStackId, $targetStackId, $dateField);
$workflow = $this->findOwnWorkflow($id);
$this->validate($title, $boardId, $sourceStackId, $targetStackId);
try {
$workflow = $this->workflowMapper->findForUser($id, $this->currentUserId());
} catch (DoesNotExistException $e) {
throw new OCSNotFoundException('Workflow not found');
}
$this->applyFields($workflow, $title, $boardId, $sourceStackId, $targetStackId, $filterUserIds, $filterLabelIds, $dateField, $notifyEmail, $enabled);
// Kept in step with the board owner so the job runs as, and mails,
// the right user; validate() made sure the editor owns the board.
$workflow->setUserId($this->currentUserId());
$this->applyFields($workflow, $title, $boardId, $sourceStackId, $targetStackId, $notifyEmail, $enabled);
$workflow = $this->workflowMapper->update($workflow);
return new DataResponse($workflow->jsonSerialize());
@@ -103,12 +92,7 @@ class WorkflowController extends OCSController {
#[NoAdminRequired]
public function destroy(int $id): DataResponse {
try {
$workflow = $this->workflowMapper->findForUser($id, $this->currentUserId());
} catch (DoesNotExistException $e) {
throw new OCSNotFoundException('Workflow not found');
}
$workflow = $this->findOwnWorkflow($id);
$this->workflowMapper->delete($workflow);
return new DataResponse([]);
}
@@ -116,7 +100,7 @@ class WorkflowController extends OCSController {
#[NoAdminRequired]
public function boards(): DataResponse {
$this->assertDeck();
return new DataResponse($this->deckService->listBoardsForCurrentUser());
return new DataResponse($this->ownedBoards());
}
#[NoAdminRequired]
@@ -125,16 +109,38 @@ class WorkflowController extends OCSController {
return new DataResponse($this->deckService->listStacks($boardId));
}
#[NoAdminRequired]
public function labels(int $boardId): DataResponse {
$this->assertDeck();
return new DataResponse($this->deckService->listLabels($boardId));
private function findOwnWorkflow(int $id): Workflow {
try {
$workflow = $this->workflowMapper->findById($id);
} 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();
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 {
@@ -149,19 +155,13 @@ class WorkflowController extends OCSController {
}
}
private function validate(string $title, int $boardId, int $sourceStackId, int $targetStackId, string $dateField): void {
private function validate(string $title, int $boardId, int $sourceStackId, int $targetStackId): void {
if (trim($title) === '') {
throw new OCSBadRequestException('Title must not be empty');
}
if ($sourceStackId === $targetStackId) {
throw new OCSBadRequestException('Source and target stack must differ');
}
// Rejected rather than silently normalised to 'due': a client sending
// something else is asking for a rule it would not get, and the runner
// falls back to the due date without a word.
if (!in_array($dateField, Workflow::DATE_FIELDS, true)) {
throw new OCSBadRequestException('Unknown date field: ' . $dateField);
}
// Reject references to boards or stacks that are gone (or were never
// the user's) instead of storing a workflow that can only fail later.
@@ -169,12 +169,18 @@ class WorkflowController extends OCSController {
// not "Deck is unreachable".
$this->assertDeck();
$boardIds = array_map(
static fn (array $board) => (int)$board['id'],
$this->deckService->listBoardsForCurrentUser(),
);
if (!in_array($boardId, $boardIds, true)) {
throw new OCSBadRequestException('The selected board does not exist or is not accessible');
// Only boards the user owns are listed, so this also enforces the
// owner rule. Archived boards stay listed (their workflows must stay
// visible) but are no target for a new or changed workflow.
$board = null;
foreach ($this->ownedBoards() as $candidate) {
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(
@@ -186,19 +192,12 @@ class WorkflowController extends OCSController {
}
}
/**
* @param string[] $filterUserIds
* @param int[] $filterLabelIds
*/
private function applyFields(
Workflow $workflow,
string $title,
int $boardId,
int $sourceStackId,
int $targetStackId,
array $filterUserIds,
array $filterLabelIds,
string $dateField,
bool $notifyEmail,
bool $enabled,
): void {
@@ -206,9 +205,6 @@ class WorkflowController extends OCSController {
$workflow->setBoardId($boardId);
$workflow->setSourceStackId($sourceStackId);
$workflow->setTargetStackId($targetStackId);
$workflow->setFilterUserIds($filterUserIds === [] ? null : json_encode(array_values($filterUserIds)));
$workflow->setFilterLabelIds($filterLabelIds === [] ? null : json_encode(array_values($filterLabelIds)));
$workflow->setDateField($dateField);
$workflow->setNotifyEmail($notifyEmail);
$workflow->setEnabled($enabled);
}
-65
View File
@@ -18,12 +18,6 @@ use OCP\DB\Types;
* @method void setSourceStackId(int $sourceStackId)
* @method int getTargetStackId()
* @method void setTargetStackId(int $targetStackId)
* @method string|null getFilterUserIds()
* @method void setFilterUserIds(?string $filterUserIds)
* @method string|null getFilterLabelIds()
* @method void setFilterLabelIds(?string $filterLabelIds)
* @method string|null getDateField()
* @method void setDateField(string $dateField)
* @method bool getNotifyEmail()
* @method void setNotifyEmail(bool $notifyEmail)
* @method bool getEnabled()
@@ -32,22 +26,11 @@ use OCP\DB\Types;
* @method void setLastRun(?\DateTime $lastRun)
*/
class Workflow extends Entity implements \JsonSerializable {
/** Deck's `Card::$duedate` — the card is picked up once it is overdue. */
public const DATE_FIELD_DUE = 'due';
/** Deck's `Card::$startdate` — the card is picked up once its start date has been reached. */
public const DATE_FIELD_START = 'start';
public const DATE_FIELDS = [self::DATE_FIELD_DUE, self::DATE_FIELD_START];
protected $userId;
protected $title;
protected $boardId;
protected $sourceStackId;
protected $targetStackId;
protected $filterUserIds;
protected $filterLabelIds;
protected $dateField;
protected $notifyEmail;
protected $enabled;
protected $lastRun;
@@ -59,56 +42,11 @@ class Workflow extends Entity implements \JsonSerializable {
$this->addType('boardId', Types::INTEGER);
$this->addType('sourceStackId', Types::INTEGER);
$this->addType('targetStackId', Types::INTEGER);
$this->addType('filterUserIds', Types::STRING);
$this->addType('filterLabelIds', Types::STRING);
$this->addType('dateField', Types::STRING);
$this->addType('notifyEmail', Types::BOOLEAN);
$this->addType('enabled', Types::BOOLEAN);
$this->addType('lastRun', Types::DATETIME);
}
/**
* The date field to evaluate, never anything else.
*
* Rows written before the column existed carry 'due' from the schema
* default, but a freshly constructed entity holds `null` and a hand-edited
* row could hold anything. Falling back to the due date keeps the old
* behaviour for every value that is not explicitly the start date — the
* safe direction, since 'due' is what every workflow meant before this
* choice existed.
*
* @return self::DATE_FIELD_*
*/
public function getDateFieldOrDue(): string {
$field = $this->getDateField();
return in_array($field, self::DATE_FIELDS, true) ? $field : self::DATE_FIELD_DUE;
}
/**
* @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 {
return [
'id' => $this->getId(),
@@ -117,9 +55,6 @@ class Workflow extends Entity implements \JsonSerializable {
'boardId' => $this->getBoardId(),
'sourceStackId' => $this->getSourceStackId(),
'targetStackId' => $this->getTargetStackId(),
'filterUserIds' => $this->getFilterUserIdsArray(),
'filterLabelIds' => $this->getFilterLabelIdsArray(),
'dateField' => $this->getDateFieldOrDue(),
'notifyEmail' => (bool)$this->getNotifyEmail(),
'enabled' => (bool)$this->getEnabled(),
'lastRun' => $this->getLastRun()?->format(\DateTimeInterface::ATOM),
+8 -5
View File
@@ -22,24 +22,27 @@ class WorkflowMapper extends QBMapper {
* @throws DoesNotExistException
* @throws MultipleObjectsReturnedException
*/
public function findForUser(int $id, string $userId): Workflow {
public function findById(int $id): Workflow {
$qb = $this->db->getQueryBuilder();
$qb->select('*')
->from($this->getTableName())
->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)))
->andWhere($qb->expr()->eq('user_id', $qb->createNamedParameter($userId)));
->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
return $this->findEntity($qb);
}
/**
* @param int[] $boardIds
* @return Workflow[]
*/
public function findAllForUser(string $userId): array {
public function findAllForBoards(array $boardIds): array {
if ($boardIds === []) {
return [];
}
$qb = $this->db->getQueryBuilder();
$qb->select('*')
->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');
return $this->findEntities($qb);
@@ -1,47 +0,0 @@
<?php
declare(strict_types=1);
namespace OCA\WorkflowDeckAutomation\Migration;
use Closure;
use OCA\WorkflowDeckAutomation\Db\Workflow;
use OCP\DB\ISchemaWrapper;
use OCP\DB\Types;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;
/**
* Adds the per-workflow choice between Deck's due date and its start date.
*
* A separate migration rather than an edit to Version1000...: that one is
* wrapped in `if (!$schema->hasTable(...))`, so changing it would only ever
* reach fresh installs.
*
* The `default` is what migrates the existing rows — every workflow written
* before this release was evaluated against the due date, and the column
* default gives exactly that without a backfill step.
*/
class Version1001Date20260825120000 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');
if ($table->hasColumn('date_field')) {
return null;
}
$table->addColumn('date_field', Types::STRING, [
'notnull' => true,
'length' => 16,
'default' => Workflow::DATE_FIELD_DUE,
]);
return $schema;
}
}
@@ -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 -326
View File
@@ -4,7 +4,6 @@ declare(strict_types=1);
namespace OCA\WorkflowDeckAutomation\Service;
use DateTimeInterface;
use OCA\Deck\Db\BoardMapper;
use OCA\Deck\Db\Card;
use OCA\Deck\Db\CardMapper;
@@ -15,9 +14,7 @@ use OCA\Deck\Service\PermissionService;
use OCA\Deck\Service\StackService;
use OCP\App\IAppManager;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\IGroupManager;
use OCP\IUser;
use OCP\IUserManager;
use OCP\Server;
use Psr\Log\LoggerInterface;
use ReflectionProperty;
@@ -37,35 +34,9 @@ class DeckIntegrationService {
private const DECK_APP_ID = 'deck';
/**
* Oldest Deck this app will talk to.
*
* Deck 1.18.0 is the release that added the card start date
* (`Card::$startdate`, PR #7749), which the start-date workflows read.
* The floor cannot live in appinfo/info.xml: neither the server's
* app-info.xsd nor the app store's info.xsd has an app-to-app dependency
* element, only <nextcloud>.
*
* That pin does most of the work anyway — Deck 1.18.x is the only release
* line declaring `>=34.0.0,<35.0.0`, so on the Nextcloud 34 this app
* requires, every installable Deck already carries the field. What is left
* for this check is a Deck put in place by hand or from git.
*
* version_compare() sorts `1.18.0-beta.x` *below* `1.18.0`, and that is
* intended: the betas of that line may predate the field.
*/
private const MIN_DECK_VERSION = '1.18.0';
/**
* Deck's Acl::PERMISSION_TYPE_* values, inlined so this class keeps
* working (degrading to "treat it as a user") if Deck ever moves or
* renames the constants.
*/
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.
* Deck's Acl::PERMISSION_READ, inlined so a moved or renamed constant
* cannot fatal this class. It is the key under which
* PermissionService::getPermissions() reports read access.
*/
private const ACL_PERMISSION_READ = 0;
@@ -88,35 +59,13 @@ class DeckIntegrationService {
'OCA\Deck\Activity\ActivityManager',
];
/**
* `Workflow::DATE_FIELD_*` mapped to the property on Deck's Card entity.
* Kept here rather than on the Workflow so this class stays the only one
* that has to know what Deck calls its columns.
*/
private const CARD_DATE_PROPERTIES = [
'due' => 'duedate',
'start' => 'startdate',
];
private const DEFAULT_CARD_DATE = 'due';
/**
* @var list<array{ReflectionProperty, object, ?string}>
*/
private array $identityRestore = [];
/**
* Card properties already reported as missing, so the warning in
* getCardDate() is one line per process instead of one per card.
*
* @var array<string, true>
*/
private array $reportedMissingCardProperties = [];
public function __construct(
private IAppManager $appManager,
private IUserManager $userManager,
private IGroupManager $groupManager,
private LoggerInterface $logger,
) {
}
@@ -206,71 +155,50 @@ class DeckIntegrationService {
if (!$this->appManager->isEnabledForUser(self::DECK_APP_ID, $user)) {
throw new DeckUnavailableException('Deck is not enabled for user ' . $user->getUID());
}
$version = $this->appManager->getAppVersion(self::DECK_APP_ID);
if ($version === '' || version_compare($version, self::MIN_DECK_VERSION, '<')) {
throw new DeckUnavailableException(sprintf(
'Deck %s is installed, but %s or newer is required',
$version !== '' ? $version : '(unknown version)',
self::MIN_DECK_VERSION,
));
}
if (!class_exists(CardService::class) || !class_exists(BoardService::class) || !class_exists(StackService::class)) {
throw new DeckUnavailableException('Deck internal classes are not available');
}
}
/**
* @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
* BoardService froze at construction time, and beginUserContext() cannot
* help here — it repoints that field, but Deck may already have cached
* board lists behind it, and the job has no use for a board *list*
* anyway. It asks findStackIds() about one known board id instead.
* One query: BoardMapper::findAllByOwner() is `WHERE owner = :uid`, so
* shared boards never come back, and as a plain QBMapper it has none of
* the frozen-uid state of BoardService::getUserBoards(). It does return
* archived and trashed boards; trashed ones are dropped here, archived
* 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 {
$boards = $this->call(function () {
$boardService = $this->resolve(BoardService::class);
try {
// getUserBoards(?int $since, bool $includeArchived, …): with
// 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();
}
}, []);
public function listOwnedBoards(string $userId): array {
$boards = $this->call(
fn () => $this->resolve(BoardMapper::class)->findAllByOwner($userId),
[],
true,
);
// 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 = [];
foreach ($boards as $board) {
$id = (int)$board->getId();
if (isset($result[$id]) || $this->isBoardHidden($board)) {
if (method_exists($board, 'getDeletedAt') && (int)$board->getDeletedAt() > 0) {
continue;
}
$id = (int)$board->getId();
$title = $board->getTitle();
$result[$id] = [
$result[] = [
'id' => $id,
'title' => (is_string($title) && $title !== '') ? $title : ('#' . $id),
'archived' => method_exists($board, 'getArchived') && (bool)$board->getArchived(),
];
}
return array_values($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;
return $result;
}
/**
@@ -343,6 +271,37 @@ class DeckIntegrationService {
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
* string simply returns false when the class does not exist, so a missing
@@ -361,51 +320,6 @@ class DeckIntegrationService {
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.
*
@@ -439,85 +353,9 @@ class DeckIntegrationService {
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
* done, enriched so getAssignedUsers()/getLabels() are populated.
* done.
*
* The `deletedAt` check is not redundant: Deck's
* `CardMapper::findAllByStack()` filters on `stack_id` and
@@ -529,17 +367,11 @@ class DeckIntegrationService {
*/
public function getActiveCardsInStack(int $stackId): array {
return $this->call(function () use ($stackId) {
$cardMapper = $this->resolve(CardMapper::class);
$cardService = $this->resolve(CardService::class);
$cards = $cardMapper->findAllByStack($stackId);
// enrichCards() mutates each $cards entry in place (labels, assigned users, ...) but
// *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 hasPassed() was always false and no workflow ever matched a card.
// Keep using the original, now-enriched $cards instead.
$cardService->enrichCards($cards);
// Deliberately not enriched: CardService::enrichCards() only adds
// labels, assignees and comment counts — none of which is used —
// and runs BoardService::find(), a permission check against
// Deck's frozen uid (see beginUserContext()).
$cards = $this->resolve(CardMapper::class)->findAllByStack($stackId);
return array_values(array_filter($cards, static function (Card $card) {
if (method_exists($card, 'getDeletedAt') && (int)$card->getDeletedAt() > 0) {
@@ -550,74 +382,6 @@ class DeckIntegrationService {
}, []);
}
/**
* The card date a workflow is evaluated against: Deck's due date or its
* start date, per `Workflow::DATE_FIELD_*`. Anything unrecognised reads the
* due date, which is what every workflow meant before the choice existed.
*
* The guard is `property_exists()`, deliberately, and this is the one thing
* to get right here: **`method_exists()` cannot see Deck's getters.**
* `Card`, `Board`, `Label`, `Acl` and `Assignment` declare none of them as
* real code — `getStartdate()`, `getDuedate()`, even `getId()` all go
* through `OCP\AppFramework\Db\Entity::__call()`, and `method_exists()`
* ignores `__call()` by definition. A `method_exists($card, 'getStartdate')`
* probe would therefore be false on *every* Deck version and silently turn
* every start-date workflow into a no-op. `property_exists()` sees the
* protected `$startdate` declaration and is exactly what `Entity::getter()`
* checks internally before throwing.
*
* In practice the property is always there — `assertDeckAvailable()`
* enforces Deck >= MIN_DECK_VERSION, which is the release that added it —
* so this branch is a backstop for a hand-installed Deck, loud enough to be
* found in the log rather than silently matching nothing.
*/
public function getCardDate(Card $card, string $dateField): ?DateTimeInterface {
$property = self::CARD_DATE_PROPERTIES[$dateField] ?? self::CARD_DATE_PROPERTIES[self::DEFAULT_CARD_DATE];
if (!property_exists($card, $property)) {
if (!isset($this->reportedMissingCardProperties[$property])) {
$this->reportedMissingCardProperties[$property] = true;
$this->logger->warning(
'This Deck version has no Card::$' . $property . '; workflows using it cannot match any card',
['app' => 'workflow_deck_automation'],
);
}
return null;
}
$value = $property === 'startdate' ? $card->getStartdate() : $card->getDuedate();
return $value instanceof DateTimeInterface ? $value : null;
}
/**
* @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
* (the exact same code path behind Deck's "move card" action).
@@ -664,31 +428,6 @@ class DeckIntegrationService {
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
* a plain uid.
+4 -13
View File
@@ -55,19 +55,10 @@ class NotificationMailer {
$template->setSubject($this->l10n->t('Deck card moved: %s', [$card->getTitle()]));
$template->addHeader();
$template->addHeading($this->l10n->t('A card was moved automatically'), false);
// Two whole strings rather than one sentence with an interpolated
// reason: the trigger is the point of the mail, and a translator
// needs to see it in the sentence to get the grammar right.
$reason = $workflow->getDateFieldOrDue() === Workflow::DATE_FIELD_START
? $this->l10n->t(
'The card "%1$s" was moved because its start date has been reached (workflow "%2$s").',
[$card->getTitle(), $workflow->getTitle()],
)
: $this->l10n->t(
'The card "%1$s" was moved because it is overdue (workflow "%2$s").',
[$card->getTitle(), $workflow->getTitle()],
);
$template->addBodyText($reason);
$template->addBodyText($this->l10n->t(
'The card "%1$s" was moved because it is overdue (workflow "%2$s").',
[$card->getTitle(), $workflow->getTitle()],
));
// Single-argument addBodyText() runs htmlspecialchars() itself, so
// these board- and stack-titles (user input) are safe as-is —
// unlike the description below, which passes both parts.
+58 -129
View File
@@ -17,8 +17,7 @@ use Psr\Log\LoggerInterface;
use Throwable;
/**
* Evaluates all enabled workflows and moves the cards whose watched date -
* Deck's due date or its start date, per workflow - has passed.
* Evaluates all enabled workflows and moves overdue cards.
*
* This runner has to evaluate rules for many different users within a
* single background-job process, so workflows are grouped by owner and
@@ -56,7 +55,9 @@ class WorkflowRunner {
}
$byUser = [];
$owners = [];
foreach ($workflows as $workflow) {
$this->followBoardOwner($workflow, $owners);
$byUser[$workflow->getUserId()][] = $workflow;
}
@@ -79,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
*/
@@ -159,34 +209,22 @@ class WorkflowRunner {
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
// and the workflow wants a mail — this is decoration, not a check.
$targets = null;
$now = $this->timeFactory->getDateTime();
$dateField = $workflow->getDateFieldOrDue();
foreach ($cards as $card) {
if (!self::hasPassed($this->deckService->getCardDate($card, $dateField), $now)) {
if (!self::isOverdue($card->getDuedate(), $now)) {
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} on its {dateField} date; moving to stack {target}.', [
$this->logger->info('Card {card} ("{title}") matches workflow {id}; moving to stack {target}.', [
'app' => 'workflow_deck_automation',
'card' => $card->getId(),
'title' => $card->getTitle(),
'id' => $workflow->getId(),
'dateField' => $dateField,
'target' => $workflow->getTargetStackId(),
]);
@@ -280,125 +318,16 @@ class WorkflowRunner {
}
/**
* 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(),
],
);
}
}
/**
* Whether the card date a workflow watches - its due date or its start date,
* see Workflow::DATE_FIELD_* - lies in the past. A card without that date set
* is never picked up.
*
* Compares the card's actual 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
* (DateInterval's %a is a whole-day count) and therefore reports 0 - not overdue -
* for any card whose due time has already passed today. That silently held back
* every card for up to 24h after it actually fell due; comparing the raw datetime
* instead matches what Deck's own UI shows (e.g. "vor 2 Stunden") and has no
* day-rounding step to get wrong. The same reasoning applies unchanged to the
* start date, which is why this is one function and not two.
* day-rounding step to get wrong.
*/
public static function hasPassed(?DateTimeInterface $cardDate, DateTimeInterface $now): bool {
return $cardDate !== null && $cardDate < $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;
public static function isOverdue(?DateTimeInterface $duedate, DateTimeInterface $now): bool {
return $duedate !== null && $duedate < $now;
}
/**
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "workflow_deck_automation",
"version": "34.1.0",
"version": "35.1.0",
"private": true,
"type": "module",
"description": "Automates moving overdue Deck cards between stacks, configurable per user.",
+61 -189
View File
@@ -1,7 +1,7 @@
<template>
<NcSettingsSection
name="Deck Workflow-Automatisierung"
description="Verschiebt Karten automatisch aus einem Deck-Stapel in einen anderen, sobald ihr Fälligkeits- oder Startdatum erreicht ist. Ein Hintergrundjob prüft die Regeln alle paar Minuten.">
description="Verschiebt überfällige Karten aus einem Deck-Stapel automatisch in einen anderen Stapel. Ein Hintergrundjob prüft die Regeln alle paar Minuten.">
<NcNoteCard v-if="loadError" type="error">
{{ loadError }}
</NcNoteCard>
@@ -14,18 +14,18 @@
<table v-if="workflows.length" class="wfda-table">
<thead>
<tr>
<th>Board</th>
<th>Titel</th>
<th>Von Stapel</th>
<th>Nach Stapel</th>
<th>Auslöser</th>
<th>Filter</th>
<th>E-Mail</th>
<th>Aktiv</th>
<th />
</tr>
</thead>
<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>
{{ workflow.title }}
<span v-if="workflowIssues[workflow.id]" class="wfda-issue">
@@ -34,17 +34,8 @@
</td>
<td>{{ stackLabel(workflow.boardId, workflow.sourceStackId) }}</td>
<td>{{ stackLabel(workflow.boardId, workflow.targetStackId) }}</td>
<td>{{ dateFieldLabel(workflow.dateField) }}</td>
<td>
<span v-if="!workflow.filterUserIds.length && !workflow.filterLabelIds.length">–</span>
<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>{{ yesNo(workflow.notifyEmail) }}</td>
<td>{{ yesNo(workflow.enabled) }}</td>
<td class="wfda-actions">
<NcButton variant="tertiary" @click="editWorkflow(workflow)">
Bearbeiten
@@ -77,6 +68,9 @@
:reduce="option => option.value"
placeholder="Board wählen"
@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
v-model="form.sourceStackId"
@@ -94,52 +88,6 @@
:disabled="!form.boardId"
placeholder="Ziel-Stapel wählen" />
<fieldset class="wfda-fieldset">
<legend>Auslösendes Datum</legend>
<!--
v-model + value + type="radio" + a shared name is the
@nextcloud/vue 9 radio API: v-model carries the group's
current value, value the one this button stands for. Do
not reach for :checked.sync here - Vue 3 dropped .sync,
and it would silently never update.
-->
<NcCheckboxRadioSwitch
v-model="form.dateField"
value="due"
name="wfda-date-field"
type="radio">
Fälligkeitsdatum überschritten
</NcCheckboxRadioSwitch>
<NcCheckboxRadioSwitch
v-model="form.dateField"
value="start"
name="wfda-date-field"
type="radio">
Startdatum erreicht
</NcCheckboxRadioSwitch>
<p class="wfda-hint">
Karten ohne das gewählte Datum werden nie verschoben.
</p>
</fieldset>
<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">
Benachrichtigungs-E-Mail an mich senden
</NcCheckboxRadioSwitch>
@@ -178,8 +126,6 @@ import {
createWorkflow,
deleteWorkflow,
fetchBoards,
fetchLabels,
fetchParticipants,
fetchStacks,
fetchWorkflows,
updateWorkflow,
@@ -191,8 +137,6 @@ const workflows = ref([])
const boards = ref([])
// Per board, and `null` whenever the request failed — see loadStacksFor().
const stacksByBoard = reactive({})
const labelsByBoard = reactive({})
const participantsByBoard = reactive({})
const showForm = ref(false)
const saving = ref(false)
@@ -200,12 +144,44 @@ const formError = ref('')
const editingId = ref(null)
const stackOptions = ref([])
const labelOptions = ref([])
const participantOptions = ref([])
// Which board the three lists above currently belong to.
// Which board the list above currently belongs to.
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
// already holds — the error message on save stays as the backstop for
@@ -214,15 +190,9 @@ const sourceStackOptions = computed(() => stackOptions.value.filter((option) =>
const targetStackOptions = computed(() => stackOptions.value.filter((option) => option.value !== form.sourceStackId))
/**
* Workflows that stopped working, keyed by id. Two different kinds:
*
* - Board or stacks deleted in Deck. The background job switches these off
* 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.
* 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
* working needs to say so instead of looking healthy.
*/
const workflowIssues = computed(() => {
const issues = {}
@@ -244,39 +214,13 @@ const workflowIssues = computed(() => {
}
if (missing.length) {
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
})
/**
* 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())
function emptyForm() {
@@ -285,16 +229,18 @@ function emptyForm() {
boardId: null,
sourceStackId: null,
targetStackId: null,
filterUserIds: [],
filterLabelIds: [],
dateField: 'due',
notifyEmail: false,
enabled: true,
}
}
function dateFieldLabel(dateField) {
return dateField === 'start' ? 'Startdatum' : 'Fälligkeit'
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) {
@@ -316,23 +262,6 @@ async function loadStacksFor(boardId) {
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() {
loading.value = true
loadError.value = ''
@@ -340,13 +269,7 @@ async function loadAll() {
const [loadedWorkflows, loadedBoards] = await Promise.all([fetchWorkflows(), fetchBoards()])
workflows.value = loadedWorkflows
boards.value = loadedBoards
await Promise.all(loadedWorkflows.flatMap((workflow) => {
const pending = [loadStacksFor(workflow.boardId)]
if (workflow.filterLabelIds.length || workflow.filterUserIds.length) {
pending.push(loadFiltersFor(workflow.boardId))
}
return pending
}))
await Promise.all(loadedWorkflows.map((workflow) => loadStacksFor(workflow.boardId)))
} catch (e) {
loadError.value = 'Konnte Workflows oder Deck-Boards nicht laden. Ist die Deck-App aktiviert?'
} finally {
@@ -355,36 +278,25 @@ async function loadAll() {
}
/**
* Fills the stack/label/user dropdowns for a board without touching the
* current selection — that separation matters: editing a workflow has to
* load the same options but must keep the stored stacks and filters.
* Fills the stack dropdowns for a board without touching the current
* selection — that separation matters: editing a workflow has to load the
* same options but must keep the stored stacks.
*/
async function loadBoardOptions(boardId) {
stackOptions.value = []
labelOptions.value = []
participantOptions.value = []
loadedBoardId.value = boardId ?? null
if (!boardId) {
return
}
// One failing endpoint must not take the other two dropdowns down with it.
const [stacks, labels, participants] = await Promise.all([
fetchStacks(boardId).catch(() => null),
fetchLabels(boardId).catch(() => null),
fetchParticipants(boardId).catch(() => null),
])
const stacks = await fetchStacks(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".
stacksByBoard[boardId] = stacks
labelsByBoard[boardId] = labels
participantsByBoard[boardId] = participants
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 }))
}
/**
@@ -399,8 +311,6 @@ async function onBoardChange(boardId) {
form.sourceStackId = null
form.targetStackId = null
form.filterUserIds = []
form.filterLabelIds = []
await loadBoardOptions(boardId)
}
@@ -419,10 +329,6 @@ async function editWorkflow(workflow) {
boardId: workflow.boardId,
sourceStackId: workflow.sourceStackId,
targetStackId: workflow.targetStackId,
filterUserIds: [...workflow.filterUserIds],
filterLabelIds: [...workflow.filterLabelIds],
// Workflows stored before this field existed come back without it.
dateField: workflow.dateField || 'due',
notifyEmail: workflow.notifyEmail,
enabled: workflow.enabled,
})
@@ -535,38 +441,4 @@ onMounted(loadAll)
display: flex;
gap: 8px;
}
.wfda-fieldset {
display: flex;
flex-direction: column;
gap: 4px;
/* The form already draws its own frame; the browser default would put a
second box around just this group. */
border: none;
padding: 0;
margin: 0;
}
.wfda-fieldset legend {
font-weight: bold;
margin-bottom: 4px;
}
.wfda-hint {
color: var(--color-text-maxcontrast);
font-size: 0.9em;
}
/*
* NcSelect positions the clear/open icons (.vs__actions) absolutely relative
* to the outer .v-select wrapper, while the dropdown menu itself opens
* relative to .vs__dropdown-toggle (its $refs.toggle) — normally the same
* box, but any width mismatch between the two (e.g. from global Nextcloud
* input styles bleeding into the scoped component) shifts the icons off the
* visible border of single-value selects like Board/Quell-/Ziel-Stapel.
* Anchoring both to .vs__dropdown-toggle keeps them in sync.
*/
:deep(.v-select.select:not(.vs--multiple) .vs__dropdown-toggle) {
position: relative;
}
</style>
-10
View File
@@ -33,13 +33,3 @@ export async function fetchStacks(boardId) {
const { data } = await axios.get(ocsUrl(`/boards/${boardId}/stacks`))
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
}
-43
View File
@@ -1,43 +0,0 @@
<?php
declare(strict_types=1);
namespace OCA\WorkflowDeckAutomation\Tests\Unit\Db;
use OCA\WorkflowDeckAutomation\Db\Workflow;
use PHPUnit\Framework\TestCase;
class WorkflowTest extends TestCase {
public function testDateFieldDefaultsToDueWhenUnset(): void {
// The column default covers rows written before date_field existed,
// but an entity built in PHP has never been near the database.
$this->assertSame(Workflow::DATE_FIELD_DUE, (new Workflow())->getDateFieldOrDue());
}
public function testDateFieldIsKeptWhenKnown(): void {
$workflow = new Workflow();
$workflow->setDateField(Workflow::DATE_FIELD_START);
$this->assertSame(Workflow::DATE_FIELD_START, $workflow->getDateFieldOrDue());
$workflow->setDateField(Workflow::DATE_FIELD_DUE);
$this->assertSame(Workflow::DATE_FIELD_DUE, $workflow->getDateFieldOrDue());
}
public function testUnknownDateFieldFallsBackToDue(): void {
// A hand-edited row must not silently switch a workflow to a trigger
// nobody configured; the due date is what every workflow meant before
// this choice existed.
$workflow = new Workflow();
$workflow->setDateField('whenever');
$this->assertSame(Workflow::DATE_FIELD_DUE, $workflow->getDateFieldOrDue());
}
public function testDateFieldIsSerialisedForTheSettingsUi(): void {
$workflow = new Workflow();
$workflow->setDateField(Workflow::DATE_FIELD_START);
$this->assertSame(Workflow::DATE_FIELD_START, $workflow->jsonSerialize()['dateField']);
}
}
@@ -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 testHasPassedReturnsFalseWithoutADate(): void {
$this->assertFalse(WorkflowRunner::hasPassed(null, new DateTimeImmutable('2026-01-15 12:00:00')));
}
public function testHasPassedReturnsFalseForAFutureDate(): void {
$now = new DateTimeImmutable('2026-01-15 12:00:00');
$this->assertFalse(WorkflowRunner::hasPassed($now->modify('+1 hour'), $now));
$this->assertFalse(WorkflowRunner::hasPassed($now->modify('+3 days'), $now));
}
public function testHasPassedReturnsTrueForAPastDate(): void {
$now = new DateTimeImmutable('2026-01-15 12:00:00');
$this->assertTrue(WorkflowRunner::hasPassed($now->modify('-1 hour'), $now));
$this->assertTrue(WorkflowRunner::hasPassed($now->modify('-30 days'), $now));
}
public function testHasPassedReturnsTrueForATimeEarlierTheSameDay(): 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. hasPassed() must compare the real timestamps instead.
$now = new DateTimeImmutable('2026-01-15 12:00:00');
$this->assertTrue(WorkflowRunner::hasPassed(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));
}
}