Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0e66319a06 | ||
|
|
43648f3728 | ||
|
|
ce749e63a4 | ||
|
|
b203ba35f8 | ||
|
|
ef973af4b5 | ||
|
|
a95d5e2d8a | ||
|
|
2d2f3ca19c | ||
|
|
a6dde35249 | ||
|
|
7ca728e79c | ||
|
|
be6faa7b42 | ||
|
|
131ef2e938 | ||
|
|
b4057809ed |
No files matched your search
@@ -15,7 +15,7 @@ jobs:
|
||||
runs-on: gitea-runner-server03
|
||||
strategy:
|
||||
matrix:
|
||||
php-version: ['8.2', '8.3', '8.4']
|
||||
php-version: ['8.4', '8.5']
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
@@ -51,7 +51,7 @@ jobs:
|
||||
|
||||
- uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: '8.3'
|
||||
php-version: '8.4'
|
||||
extensions: sqlite, pdo_sqlite
|
||||
coverage: none
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ 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 overdue [Deck](https://github.com/nextcloud/deck) cards from one stack to another, with optional assigned-user/label filters and an email notification. A background `TimedJob` evaluates all enabled workflows every 5 minutes.
|
||||
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.
|
||||
|
||||
## Non-negotiable architectural constraint
|
||||
|
||||
@@ -12,30 +12,89 @@ A Nextcloud app (`workflow_deck_automation`, namespace `WorkflowDeckAutomation`)
|
||||
|
||||
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
|
||||
|
||||
Deck's ACL/permission checks read the *live* `IUserSession`, not a value frozen at construction. `RunWorkflowsJob` (a `TimedJob`) 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, per owner, temporarily impersonates them (`IUserSession::setUser()`, restored in a `finally`) before touching Deck. Don't remove this — without it, Deck's permission checks inside the cron run would be evaluated against no user (or the wrong user).
|
||||
`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:**
|
||||
|
||||
The filter-matching logic (`WorkflowRunner::cardMatchesFilters()`, `::isOverdue()`) is deliberately `static` and side-effect-free so it's unit-testable without a real Deck installation — see `tests/Unit/Service/WorkflowRunnerFilterTest.php`.
|
||||
1. `IUserSession::setUser()` — for the handful of Nextcloud services that do read the live session, plus `IRootFolder::getUserFolder()` for Deck helpers that expect an initialised user FS.
|
||||
2. `DeckIntegrationService::beginUserContext()` — pins **Deck itself** to that user. This is the load-bearing half.
|
||||
|
||||
**Not everything in Deck reads the live session, though.** `BoardService` takes the current user as `private ?string $userId` — a plain string frozen when the container builds it. `getUserBoards()` uses exactly that, so in the background job (one process, many users, a container-cached `BoardService`) it answers for whoever happened to be impersonated at first resolution, or for `null`. `listBoardsForCurrentUser()` is therefore **request-only**; the job asks `findStackIds()` instead, which goes through `StackService::findAll()` → `PermissionService` → live session. Before using any other `OCA\Deck\*` service from the runner, check which of the two kinds it is — the failure mode is silent and user-crossing, not an error.
|
||||
Both are undone in a `finally` (`WorkflowRunner::clearImpersonation()`).
|
||||
|
||||
**Deck does not read the session for permissions. At all.** `PermissionService` — the class behind every permission check, including the ones inside `CardService::reorder()` — takes the current user as `private ?string $userId`, and so do `CardService`, `BoardService` and `ActivityManager`. That string comes from the app container's `userId` service, which is `ISession::get('user_id')` registered via `registerService()`, i.e. **shared**: Pimple resolves it once and caches it for the whole process, and `ServerContainer` caches Deck's app container just as long. Whoever was active when Deck's container first built `PermissionService` is who every later check is evaluated against.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
## Workflows are auto-disabled when their Deck targets vanish
|
||||
|
||||
`WorkflowRunner::findBrokenTarget()` checks board and stacks before every run and, if something is gone, switches the workflow off (`enabled = false`) and sends a one-off mail. Two invariants hold this together and must survive refactors:
|
||||
|
||||
- **Only positive knowledge disables.** `DeckIntegrationService::findStackIds()` returns `null` only for "board missing/not readable" (`DoesNotExistException`, Deck's `NoPermissionException`/`NotFoundException`) and *throws* for everything else. The runner skips the workflow on a throw. If you make that method degrade to `[]`/`null` on generic errors, a Deck outage will disable every workflow on the instance and mail every user about it.
|
||||
- **Only positive knowledge disables.** `DeckIntegrationService::findStackIds()` returns `null` only for "board row gone" (`DoesNotExistException`, Deck's `NotFoundException`), "board in the trash" (`deleted_at > 0`), or "this uid has no read permission" — and *throws* for everything else. The runner skips the workflow on a throw. If you make that method degrade to `[]`/`null` on generic errors, a Deck outage will disable every workflow on the instance and mail every user about it.
|
||||
- **`findStackIds()` must never ask a Deck service to figure out *who* is asking.** It takes the uid as an argument and is assembled from pieces that cannot answer for the wrong user: `BoardMapper`/`StackMapper` are plain QBMappers with no user state, and `PermissionService::getPermissions($boardId, $userId)` is handed the uid explicitly instead of falling back to the frozen field. Do not "simplify" it back to a single `StackService::findAll($boardId)` — that is precisely what broke. `StackService::findAll()` runs `checkPermission()` with no uid, which falls through to the construction-time `$userId`; with that frozen to `null` in cron, Deck threw `NoPermissionException` for an untouched board, the old code read that as "board is gone", and users got "your workflow was deactivated" mails for boards sitting right in front of them. This layer stays correct even if `beginUserContext()` silently degrades.
|
||||
- **`NoPermissionException` is not evidence of anything.** It is deliberately *not* in `isMissing()`. Deck raises it for every failed check regardless of cause.
|
||||
- **The mail ignores the `notifyEmail` flag** — that flag is about moved cards; this is a notice that the user's configuration stopped working. It stays a one-off simply because a disabled workflow is not picked up by `findAllEnabled()` again.
|
||||
|
||||
Archived boards deliberately do *not* trigger this (they stay readable, so `findStackIds()` succeeds), even though they're filtered out of the settings dropdowns.
|
||||
|
||||
## Job interval comes from config.php
|
||||
## Dead filters are surfaced, never disabled
|
||||
|
||||
`RunWorkflowsJob` reads `workflow_deck_automation.interval` (seconds, default 300, clamped to a 60s minimum) via `IConfig::getSystemValueInt()` in its constructor. That works *because* `TimedJob` re-reads `$this->interval` on every cron pass from the freshly constructed job — so editing `config.php` takes effect immediately, with no `occ` command and no re-registration. Don't move this into `appinfo/info.xml` or a stored app config; the constants (`INTERVAL_CONFIG_KEY`, `DEFAULT_INTERVAL`, `MINIMUM_INTERVAL`) on the job are the single source of truth and are referenced from the README.
|
||||
`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 job must stay `IJob::TIME_SENSITIVE`.** It was `TIME_INSENSITIVE` at first, which looked harmless and was not: `OC\Core\Service\CronService::runCli()` reads `maintenance_window_start` (default `100`, i.e. unset) and, whenever the current UTC hour is outside `[start, start+4]`, calls `jobList->getNext($onlyTimeSensitive = true)` — time-insensitive jobs are then skipped for the other 20 hours of the day. On an instance with a maintenance window configured (Nextcloud's admin overview nags admins into setting one) the job simply never ran, showing `last_run = 1970-01-01` in `occ background-job:list` indefinitely. Note this gate only exists in `runCli()`, so it doesn't apply to ajax/webcron mode, and passing job classes explicitly (`occ background-job:worker '<class>'`) bypasses it — which is exactly why manual testing can look fine while cron does nothing.
|
||||
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.
|
||||
|
||||
**Changing the sensitivity in code does not fix an already-registered job.** `getNext()` filters on the `time_sensitive` *column* of `oc_jobs`, and `JobList::setLastRun()` is a one-way ratchet:
|
||||
Two low-stakes signals, no state and no migration:
|
||||
|
||||
- `WorkflowRunner::warnAboutDeadFilters()` logs a warning on every run.
|
||||
- `workflowIssues` in `src/PersonalSettings.vue` marks the row red.
|
||||
|
||||
Both obey the same rule as the disable path: **only positive knowledge**. `DeckIntegrationService::findFilterOptions()` therefore *throws* instead of degrading to `[]` — unlike its siblings `listLabels()`/`listParticipants()`, which are wrapped in `call(…, [])` for the dropdowns, where an empty list is harmless. On the JS side the per-board caches store `null` for a failed request, and `isDeadFilter()` returns false for `null`; storing `[]` there would report every stack and filter of the board as deleted the moment one request fails. Don't collapse those two states back together.
|
||||
|
||||
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).
|
||||
|
||||
## The job has no interval — one run per cron pass
|
||||
|
||||
`RunWorkflowsJob` extends `OCP\BackgroundJob\Job`, **not** `TimedJob`, so it runs every time cron picks it up. There is no interval and no knob: the cadence *is* the instance's cron cadence. Don't reintroduce one — an earlier version read `workflow_deck_automation.interval` from `config.php` (default 300, 60s floor), and that config key is gone as of v0.2.0. `TimedJob` with `setInterval(0)` would behave nearly identically but keeps an interval concept nothing uses.
|
||||
|
||||
**Time sensitivity is what actually decides whether the job runs at all.** `OC\Core\Service\CronService::runCli()` reads `maintenance_window_start` (default `100`, i.e. unset) and, whenever the current UTC hour is outside `[start, start+4]`, calls `jobList->getNext($onlyTimeSensitive = true)` — time-insensitive jobs are then skipped for the other 20 hours of the day. This app shipped `TIME_INSENSITIVE` once: on an instance with a maintenance window configured (Nextcloud's admin overview nags admins into setting one) the job simply never ran, showing `last_run = 1970-01-01` in `occ background-job:list` indefinitely. Note this gate only exists in `runCli()`, so it doesn't apply to ajax/webcron mode, and passing job classes explicitly (`occ background-job:worker '<class>'`) bypasses it — which is exactly why manual testing can look fine while cron does nothing.
|
||||
|
||||
Being a plain `Job` makes that unreachable rather than merely declared. `getNext()` filters on the `time_sensitive` *column* of `oc_jobs`; `JobList::add()` doesn't write the column at all (it takes the `TIME_SENSITIVE` default), and the only place that ever lowers it is a one-way ratchet in `JobList::setLastRun()`:
|
||||
|
||||
```php
|
||||
if ($job instanceof TimedJob && !$job->isTimeSensitive()) {
|
||||
@@ -43,7 +102,9 @@ if ($job instanceof TimedJob && !$job->isTimeSensitive()) {
|
||||
}
|
||||
```
|
||||
|
||||
There is no `else`. Once a job has run while declaring itself insensitive, the row is stamped `TIME_INSENSITIVE` for good — and nothing resets it: `JobList::add()` only writes the column in its *insert* branch, and re-registering an existing job (app update, `app:enable`) takes the *update* branch, which leaves it alone. So after deploying the `TIME_SENSITIVE` change, an existing instance still needs its row fixed once:
|
||||
There is no `else`, and a non-`TimedJob` never enters it. Note `setTimeSensitivity()`/`isTimeSensitive()` live on `TimedJob`, not on `Job` — so there is nothing to declare here, and nothing that can go wrong.
|
||||
|
||||
**Rows written by an older version keep their stamp.** Once stamped `TIME_INSENSITIVE` it stays that way: re-registering an existing job (app update, `app:enable`) takes `add()`'s update branch, which leaves the column alone. An instance that ran the pre-v0.1.0-fix build still needs its row fixed once:
|
||||
|
||||
```sql
|
||||
UPDATE oc_jobs SET time_sensitive = 0
|
||||
@@ -52,7 +113,7 @@ UPDATE oc_jobs SET time_sensitive = 0
|
||||
|
||||
or, without DB access, `occ background-job:delete <id>` followed by `occ app:disable workflow_deck_automation && occ app:enable workflow_deck_automation` to get a freshly inserted row. Fresh installs are unaffected.
|
||||
|
||||
To debug this job on a server: `occ background-job:list --class '<class>'` for its id and last run, then `occ background-job:execute <id> --force-execute` to run it right now regardless of the interval. `occ background-job:worker` takes **job classes**, not an app id.
|
||||
To debug this job on a server: `occ background-job:list --class '<class>'` for its id and last run, then `occ background-job:execute <id> --force-execute` to run it right now without waiting for cron. `occ background-job:worker` takes **job classes**, not an app id.
|
||||
|
||||
## Registration is declarative, not Bootstrap-based
|
||||
|
||||
@@ -81,6 +142,8 @@ There is no meaningful way to test the Deck integration itself outside a real Ne
|
||||
|
||||
### 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.
|
||||
|
||||
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.
|
||||
3. `git tag vX.Y.Z && git push origin vX.Y.Z` — this triggers the tag branch of the same workflow, which re-runs the checks, builds the frontend, runs `make appstore`, and attaches `workflow_deck_automation.tar.gz` as the asset on a normal (non-pre-) release for that tag.
|
||||
@@ -116,7 +179,7 @@ This replaced an earlier hand-made `RELEASE_TOKEN` repo secret. If the publish s
|
||||
|
||||
- **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` (5 min `TimedJob`) → `lib/Service/WorkflowRunner.php` (per-user impersonation + filtering, both filters OR-within-themselves and AND-between-each-other) → `lib/Service/DeckIntegrationService.php` (all actual Deck class calls) and `lib/Service/NotificationMailer.php` (email via `OCP\Mail\IMailer` to the workflow owner's account address, never a manually-entered address).
|
||||
- **Automation**: `lib/BackgroundJob/RunWorkflowsJob.php` (plain `Job`, one run per cron pass) → `lib/Service/WorkflowRunner.php` (per-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.
|
||||
|
||||
## Composer/npm lockfiles are intentionally not committed
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
# Deck Workflow-Automatisierung
|
||||
|
||||
Nextcloud-App für **Nextcloud Hub 26 Spring (Server 34.x)**, die überfällige Karten der [Deck](https://github.com/nextcloud/deck)-App automatisch von einem Stapel in einen anderen verschiebt und optional eine E-Mail-Benachrichtigung verschickt.
|
||||
Nextcloud-App für **Nextcloud Hub 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.
|
||||
|
||||
Ersetzt das früher genutzte eigenständige PHP-Cron-Skript durch eine vollwertige App mit Oberfläche in den **persönlichen Einstellungen** — jeder Nutzer kann dort seine eigenen Regeln ("Workflows") anlegen, ohne Admin-Rechte oder Server-Zugriff zu benötigen.
|
||||
|
||||
@@ -9,7 +11,8 @@ 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 überfällige Karten verschoben werden
|
||||
- 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)
|
||||
- Checkbox: E-Mail-Benachrichtigung an den Workflow-Besitzer, sobald eine Karte verschoben wurde
|
||||
@@ -19,8 +22,8 @@ Ein Nutzer kann beliebig viele Workflows anlegen, bearbeiten, deaktivieren oder
|
||||
## 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.
|
||||
- **Hintergrundjob statt Seitenaufruf.** [`lib/BackgroundJob/RunWorkflowsJob.php`](lib/BackgroundJob/RunWorkflowsJob.php) ist ein `TimedJob`, der standardmäßig alle 5 Minuten läuft (abhängig vom Nextcloud-Cron-Intervall) und [`lib/Service/WorkflowRunner.php`](lib/Service/WorkflowRunner.php) aufruft. Das Intervall ist über die `config.php` einstellbar, siehe unten.
|
||||
- **Rechte-Kontext je Nutzer.** Da Decks Berechtigungsprüfungen die aktuell eingeloggte Session lesen, ein Hintergrundjob aber standardmäßig keinen eingeloggten Nutzer hat und Regeln mehrerer Nutzer in einem einzigen Lauf auswerten muss, "verkörpert" der `WorkflowRunner` für die Dauer der jeweiligen Workflows kurzzeitig den entsprechenden Besitzer (`IUserSession::setUser()`), bevor die Deck-Klassen aufgerufen werden.
|
||||
- **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.
|
||||
|
||||
### Wichtiger Hinweis zu Decks internen Klassen
|
||||
@@ -48,23 +51,28 @@ 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.
|
||||
|
||||
## Konfiguration
|
||||
### Gelöschte Labels und entfernte Benutzer
|
||||
|
||||
Das Prüfintervall des Hintergrundjobs lässt sich in der `config.php` setzen (Wert in **Sekunden**):
|
||||
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.
|
||||
|
||||
```php
|
||||
'workflow_deck_automation.interval' => 300,
|
||||
```
|
||||
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.
|
||||
|
||||
- Standard ohne Eintrag: `300` (5 Minuten).
|
||||
- Minimum: `60` — kleinere Werte werden auf 60 Sekunden angehoben.
|
||||
- Die Änderung greift beim nächsten Cron-Durchlauf; ein `occ`-Befehl oder eine Neuinstallation der App ist nicht nötig.
|
||||
Damit dieser Zustand nicht unsichtbar bleibt:
|
||||
|
||||
Zu beachten: Das ist eine *Untergrenze* für den Abstand zwischen zwei Läufen, keine Garantie. Nextclouds Cron selbst läuft üblicherweise nur alle 5 Minuten — ein Intervall von 60 Sekunden führt also nur dann zu minütlichen Läufen, wenn der System-Cron entsprechend häufig ausgeführt wird.
|
||||
- **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.
|
||||
|
||||
> Bis einschließlich v0.1.0 gab es dafür die `config.php`-Option `workflow_deck_automation.interval`. Sie ist entfallen und wird ignoriert; ein vorhandener Eintrag kann aus der `config.php` entfernt werden.
|
||||
|
||||
### Der Job läuft nur nachts bzw. gar nicht
|
||||
|
||||
Der Job ist als `TIME_SENSITIVE` deklariert und läuft damit rund um die Uhr. Nextcloud merkt sich die Zeitsensitivität aber zusätzlich in der Spalte `time_sensitive` der Tabelle `oc_jobs`, und `JobList::setLastRun()` setzt sie nur in eine Richtung — von „zeitkritisch" auf „unkritisch", nie zurück. Wer eine ältere Version dieser App installiert hatte (bis einschließlich v0.1.0 war der Job `TIME_INSENSITIVE`), hat diesen Stempel noch in der Datenbank. Er wird weder durch ein App-Update noch durch `app:enable` zurückgesetzt.
|
||||
Nextcloud merkt sich in der Spalte `time_sensitive` der Tabelle `oc_jobs`, ob ein Job zeitkritisch ist, und überspringt „unkritische" Jobs außerhalb des Wartungsfensters. `JobList::setLastRun()` setzt diese Spalte nur in eine Richtung — von „zeitkritisch" auf „unkritisch", nie zurück. Wer eine ältere Version dieser App installiert hatte (bis einschließlich v0.1.0 war der Job `TIME_INSENSITIVE`), hat diesen Stempel noch in der Datenbank. Er wird weder durch ein App-Update noch durch `app:enable` zurückgesetzt.
|
||||
|
||||
Symptom: Ist in der `config.php` ein `maintenance_window_start` gesetzt, läuft der Job nur in diesem 4-Stunden-Fenster und den Rest des Tages gar nicht.
|
||||
|
||||
@@ -111,7 +119,7 @@ Ein echter End-to-End-Test (Karte anlegen, Workflow konfigurieren, Hintergrundjo
|
||||
# Job-ID und letzten Lauf anzeigen
|
||||
php occ background-job:list --class 'OCA\WorkflowDeckAutomation\BackgroundJob\RunWorkflowsJob'
|
||||
|
||||
# Sofort ausführen, unabhängig vom Intervall
|
||||
# Sofort ausführen, ohne auf den nächsten Cron-Durchlauf zu warten
|
||||
php occ background-job:execute <id> --force-execute
|
||||
|
||||
# Oder dauerhaft als Worker laufen lassen (Argument ist die Job-Klasse, keine App-ID)
|
||||
|
||||
+14
-8
@@ -4,31 +4,37 @@
|
||||
<id>workflow_deck_automation</id>
|
||||
<name lang="de">Deck Workflow-Automatisierung</name>
|
||||
<name lang="en">Deck Workflow Automation</name>
|
||||
<summary lang="de">Verschiebt überfällige Deck-Karten automatisch anhand konfigurierbarer Regeln</summary>
|
||||
<summary lang="en">Automatically moves overdue Deck cards based on configurable rules</summary>
|
||||
<summary lang="de">Verschiebt Deck-Karten automatisch anhand konfigurierbarer Regeln</summary>
|
||||
<summary lang="en">Automatically moves 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:
|
||||
|
||||
* Quell-Board und Quell-Stapel wählen
|
||||
* Ziel-Stapel wählen, in den überfällige Karten verschoben werden
|
||||
* 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
|
||||
* optional eine E-Mail-Benachrichtigung an sich selbst aktivieren
|
||||
|
||||
Ein Hintergrundjob prüft regelmäßig alle aktiven Workflows und verschiebt Karten, deren Fälligkeitsdatum überschritten wurde, ausschließlich über die internen PHP-Klassen der Deck-App (keine HTTP/OCS-Aufrufe).
|
||||
Ein Hintergrundjob prüft regelmäßig alle aktiven Workflows und verschiebt Karten, deren 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.
|
||||
]]></description>
|
||||
<description lang="en"><![CDATA[
|
||||
This app lets every user configure their own Deck automation workflows from Personal settings:
|
||||
|
||||
* pick a source board and source stack
|
||||
* pick a destination stack overdue cards get moved to
|
||||
* 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
|
||||
* optionally enable an email notification to themselves
|
||||
|
||||
A background job periodically evaluates all enabled workflows and moves cards whose due date has passed, using Deck's own internal PHP classes only (no HTTP/OCS calls).
|
||||
A background job periodically evaluates all enabled workflows and moves cards whose 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.
|
||||
]]></description>
|
||||
<version>0.1.0</version>
|
||||
<version>34.1.0</version>
|
||||
<licence>agpl</licence>
|
||||
<author mail="patrick@niebel.ing">Patrick Niebeling</author>
|
||||
<namespace>WorkflowDeckAutomation</namespace>
|
||||
@@ -36,7 +42,7 @@ A background job periodically evaluates all enabled workflows and moves cards wh
|
||||
<category>tools</category>
|
||||
<bugs>https://github.com/pniebeling/workflow_deck_automation/issues</bugs>
|
||||
<dependencies>
|
||||
<php min-version="8.2" max-version="8.4"/>
|
||||
<php min-version="8.4" max-version="8.5"/>
|
||||
<database min-version="9.4">pgsql</database>
|
||||
<database>sqlite</database>
|
||||
<database min-version="8.0">mysql</database>
|
||||
|
||||
@@ -6,51 +6,47 @@ namespace OCA\WorkflowDeckAutomation\BackgroundJob;
|
||||
|
||||
use OCA\WorkflowDeckAutomation\Service\WorkflowRunner;
|
||||
use OCP\AppFramework\Utility\ITimeFactory;
|
||||
use OCP\BackgroundJob\IJob;
|
||||
use OCP\BackgroundJob\TimedJob;
|
||||
use OCP\IConfig;
|
||||
|
||||
class RunWorkflowsJob extends TimedJob {
|
||||
/**
|
||||
* config.php key holding how often (in seconds) workflows are checked.
|
||||
*/
|
||||
public const INTERVAL_CONFIG_KEY = 'workflow_deck_automation.interval';
|
||||
|
||||
public const DEFAULT_INTERVAL = 5 * 60;
|
||||
use OCP\BackgroundJob\Job;
|
||||
|
||||
/**
|
||||
* Nextcloud's cron itself only ticks every 5 minutes by default, so
|
||||
* anything below a minute would only add load without running more
|
||||
* often. Values under this are clamped rather than rejected.
|
||||
* Evaluates all enabled workflows, once per cron pass.
|
||||
*
|
||||
* Deliberately a plain `Job`, not a `TimedJob`: there is no interval to
|
||||
* configure and none to compare against, so the cadence is exactly
|
||||
* Nextcloud's cron cadence — every pass, no matter how often cron is set
|
||||
* up to run. `TimedJob` with `setInterval(0)` would behave almost the
|
||||
* same, but it keeps an interval concept around that nothing uses.
|
||||
*
|
||||
* **Time sensitivity still matters, and it comes for free here.**
|
||||
* `OC\Core\Service\CronService::runCli()` reads `maintenance_window_start`
|
||||
* (default `100`, i.e. unset) and, whenever the current UTC hour is outside
|
||||
* `[start, start+4]`, asks `JobList::getNext($onlyTimeSensitive = true)`,
|
||||
* which filters on the `time_sensitive` *column* of `oc_jobs`. A job stamped
|
||||
* insensitive is then skipped for the other 20 hours of the day — this app
|
||||
* shipped that way once and the job looked completely dead, showing
|
||||
* `last_run = 1970-01-01` in `occ background-job:list` indefinitely. Note
|
||||
* the gate only exists in `runCli()`, so ajax/webcron are unaffected and
|
||||
* `occ background-job:worker '<class>'` bypasses it, which is why manual
|
||||
* testing can look fine while cron does nothing.
|
||||
*
|
||||
* A plain `Job` can never acquire that stamp: `JobList::add()` leaves the
|
||||
* column at its `TIME_SENSITIVE` default, and the one place that ever
|
||||
* downgrades it, `JobList::setLastRun()`, is guarded by
|
||||
* `$job instanceof TimedJob && !$job->isTimeSensitive()` — with no `else`.
|
||||
* Rows written by an older version of this app keep whatever they were
|
||||
* stamped with, though, so an instance that ran the `TIME_INSENSITIVE`
|
||||
* version still needs the one-off `UPDATE oc_jobs SET time_sensitive = 0`
|
||||
* documented in the README.
|
||||
*/
|
||||
public const MINIMUM_INTERVAL = 60;
|
||||
|
||||
class RunWorkflowsJob extends Job {
|
||||
public function __construct(
|
||||
ITimeFactory $time,
|
||||
IConfig $config,
|
||||
private WorkflowRunner $runner,
|
||||
) {
|
||||
parent::__construct($time);
|
||||
// TimedJob compares against this value on every cron pass, so a
|
||||
// changed config.php takes effect on the next pass — no occ command
|
||||
// and no re-registration of the job needed.
|
||||
$this->setInterval(self::resolveInterval($config));
|
||||
// Must stay TIME_SENSITIVE. If `maintenance_window_start` is set in
|
||||
// config.php — and Nextcloud's admin overview actively nags admins
|
||||
// to set it — CronService only picks up TIME_INSENSITIVE jobs during
|
||||
// those 4 hours and skips them for the rest of the day. A job whose
|
||||
// whole point is a 5-minute (configurable down to 60s) reaction time
|
||||
// would then run a handful of times per night and look completely
|
||||
// dead in between.
|
||||
$this->setTimeSensitivity(IJob::TIME_SENSITIVE);
|
||||
$this->setAllowParallelRuns(false);
|
||||
}
|
||||
|
||||
private static function resolveInterval(IConfig $config): int {
|
||||
$interval = $config->getSystemValueInt(self::INTERVAL_CONFIG_KEY, self::DEFAULT_INTERVAL);
|
||||
return max(self::MINIMUM_INTERVAL, $interval);
|
||||
}
|
||||
|
||||
protected function run($argument): void {
|
||||
$this->runner->run();
|
||||
}
|
||||
|
||||
@@ -56,14 +56,15 @@ class WorkflowController extends OCSController {
|
||||
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);
|
||||
$this->validate($title, $boardId, $sourceStackId, $targetStackId, $dateField);
|
||||
|
||||
$workflow = new Workflow();
|
||||
$workflow->setUserId($this->currentUserId());
|
||||
$this->applyFields($workflow, $title, $boardId, $sourceStackId, $targetStackId, $filterUserIds, $filterLabelIds, $notifyEmail, $enabled);
|
||||
$this->applyFields($workflow, $title, $boardId, $sourceStackId, $targetStackId, $filterUserIds, $filterLabelIds, $dateField, $notifyEmail, $enabled);
|
||||
|
||||
$workflow = $this->workflowMapper->insert($workflow);
|
||||
return new DataResponse($workflow->jsonSerialize(), Http::STATUS_CREATED);
|
||||
@@ -82,10 +83,11 @@ class WorkflowController extends OCSController {
|
||||
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);
|
||||
$this->validate($title, $boardId, $sourceStackId, $targetStackId, $dateField);
|
||||
|
||||
try {
|
||||
$workflow = $this->workflowMapper->findForUser($id, $this->currentUserId());
|
||||
@@ -93,7 +95,7 @@ class WorkflowController extends OCSController {
|
||||
throw new OCSNotFoundException('Workflow not found');
|
||||
}
|
||||
|
||||
$this->applyFields($workflow, $title, $boardId, $sourceStackId, $targetStackId, $filterUserIds, $filterLabelIds, $notifyEmail, $enabled);
|
||||
$this->applyFields($workflow, $title, $boardId, $sourceStackId, $targetStackId, $filterUserIds, $filterLabelIds, $dateField, $notifyEmail, $enabled);
|
||||
$workflow = $this->workflowMapper->update($workflow);
|
||||
|
||||
return new DataResponse($workflow->jsonSerialize());
|
||||
@@ -147,13 +149,19 @@ class WorkflowController extends OCSController {
|
||||
}
|
||||
}
|
||||
|
||||
private function validate(string $title, int $boardId, int $sourceStackId, int $targetStackId): void {
|
||||
private function validate(string $title, int $boardId, int $sourceStackId, int $targetStackId, string $dateField): 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.
|
||||
@@ -190,6 +198,7 @@ class WorkflowController extends OCSController {
|
||||
int $targetStackId,
|
||||
array $filterUserIds,
|
||||
array $filterLabelIds,
|
||||
string $dateField,
|
||||
bool $notifyEmail,
|
||||
bool $enabled,
|
||||
): void {
|
||||
@@ -199,6 +208,7 @@ class WorkflowController extends OCSController {
|
||||
$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);
|
||||
}
|
||||
|
||||
@@ -22,6 +22,8 @@ use OCP\DB\Types;
|
||||
* @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()
|
||||
@@ -30,6 +32,14 @@ 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;
|
||||
@@ -37,6 +47,7 @@ class Workflow extends Entity implements \JsonSerializable {
|
||||
protected $targetStackId;
|
||||
protected $filterUserIds;
|
||||
protected $filterLabelIds;
|
||||
protected $dateField;
|
||||
protected $notifyEmail;
|
||||
protected $enabled;
|
||||
protected $lastRun;
|
||||
@@ -50,11 +61,29 @@ class Workflow extends Entity implements \JsonSerializable {
|
||||
$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[]
|
||||
*/
|
||||
@@ -90,6 +119,7 @@ class Workflow extends Entity implements \JsonSerializable {
|
||||
'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),
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,14 @@ 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;
|
||||
use OCA\Deck\Db\StackMapper;
|
||||
use OCA\Deck\Service\BoardService;
|
||||
use OCA\Deck\Service\CardService;
|
||||
use OCA\Deck\Service\PermissionService;
|
||||
use OCA\Deck\Service\StackService;
|
||||
use OCP\App\IAppManager;
|
||||
use OCP\AppFramework\Db\DoesNotExistException;
|
||||
@@ -16,6 +20,7 @@ use OCP\IUser;
|
||||
use OCP\IUserManager;
|
||||
use OCP\Server;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use ReflectionProperty;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
@@ -31,6 +36,25 @@ use Throwable;
|
||||
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
|
||||
@@ -39,6 +63,56 @@ class DeckIntegrationService {
|
||||
private const ACL_TYPE_USER = 0;
|
||||
private const ACL_TYPE_GROUP = 1;
|
||||
|
||||
/**
|
||||
* Deck's Acl::PERMISSION_READ, inlined for the same reason. It is the key
|
||||
* under which PermissionService::getPermissions() reports read access.
|
||||
*/
|
||||
private const ACL_PERMISSION_READ = 0;
|
||||
|
||||
/**
|
||||
* The property through which Deck carries "the current user" — a plain
|
||||
* string frozen at construction rather than a session lookup. See
|
||||
* beginUserContext().
|
||||
*/
|
||||
private const IDENTITY_PROPERTY = 'userId';
|
||||
|
||||
/**
|
||||
* Further Deck classes holding that same frozen uid. Unlike
|
||||
* PermissionService these do not decide access, only whose name ends up
|
||||
* on an activity entry or whose unread-comment counts are computed, so
|
||||
* failing to pin them is logged and shrugged off.
|
||||
*/
|
||||
private const OPTIONAL_IDENTITY_CLASSES = [
|
||||
CardService::class,
|
||||
BoardService::class,
|
||||
'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,
|
||||
@@ -47,10 +121,101 @@ class DeckIntegrationService {
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Pins Deck to $user until endUserContext() — mandatory before any Deck
|
||||
* call made on behalf of someone who is not the logged-in web user.
|
||||
*
|
||||
* IUserSession::setUser() alone is not enough, and that is not obvious:
|
||||
* Deck's PermissionService — the class behind *every* permission check,
|
||||
* including the ones inside CardService::reorder() — receives the current
|
||||
* user as `private ?string $userId`. The app container fills that from
|
||||
* `ISession::get('user_id')` through a **shared** service, so Pimple
|
||||
* computes it once and caches it for the rest of the process, and
|
||||
* ServerContainer keeps the app container just as long. Whoever was
|
||||
* active when Deck's container first built PermissionService is therefore
|
||||
* the user every later check is evaluated against.
|
||||
*
|
||||
* In the background job that is never the user we are impersonating: it
|
||||
* is `null` whenever a Deck-owned job ran earlier in the same cron pass
|
||||
* (cron.php works through many jobs in one process), and otherwise the
|
||||
* first workflow owner we happened to touch. `null` fails every check,
|
||||
* which is how intact boards started reporting NoPermissionException and
|
||||
* got their workflows switched off.
|
||||
*
|
||||
* Deck exposes no API for this, so the frozen value is swapped directly
|
||||
* and put back in endUserContext(). PermissionService is required: if it
|
||||
* cannot be pinned this throws, and the caller has to skip the user
|
||||
* rather than run them under someone else's permissions.
|
||||
*
|
||||
* @throws DeckUnavailableException
|
||||
*/
|
||||
public function beginUserContext(IUser $user): void {
|
||||
if ($this->identityRestore !== []) {
|
||||
throw new DeckUnavailableException('A Deck user context is already active');
|
||||
}
|
||||
|
||||
$uid = $user->getUID();
|
||||
|
||||
try {
|
||||
$this->pinDeckIdentity($this->resolve(PermissionService::class), $uid);
|
||||
} catch (Throwable $e) {
|
||||
$this->endUserContext();
|
||||
throw new DeckUnavailableException(
|
||||
'Could not run Deck as ' . $uid . ': ' . $e->getMessage(),
|
||||
0,
|
||||
$e,
|
||||
);
|
||||
}
|
||||
|
||||
foreach (self::OPTIONAL_IDENTITY_CLASSES as $class) {
|
||||
try {
|
||||
$this->pinDeckIdentity($this->resolve($class), $uid);
|
||||
} catch (Throwable $e) {
|
||||
$this->logger->debug('Could not pin ' . $class . ' to ' . $uid . ': ' . $e->getMessage(), [
|
||||
'app' => 'workflow_deck_automation',
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Restores what beginUserContext() replaced. Idempotent, so it can be
|
||||
* called unconditionally from a finally block.
|
||||
*/
|
||||
public function endUserContext(): void {
|
||||
foreach (array_reverse($this->identityRestore) as [$property, $service, $previous]) {
|
||||
try {
|
||||
$property->setValue($service, $previous);
|
||||
} catch (Throwable $e) {
|
||||
$this->logger->warning('Could not restore Deck identity on ' . $service::class . ': ' . $e->getMessage(), [
|
||||
'app' => 'workflow_deck_automation',
|
||||
]);
|
||||
}
|
||||
}
|
||||
$this->identityRestore = [];
|
||||
}
|
||||
|
||||
private function pinDeckIdentity(object $service, string $uid): void {
|
||||
$property = new ReflectionProperty($service, self::IDENTITY_PROPERTY);
|
||||
$previous = $property->isInitialized($service) ? $property->getValue($service) : null;
|
||||
$property->setValue($service, $uid);
|
||||
$this->identityRestore[] = [$property, $service, is_string($previous) ? $previous : null];
|
||||
}
|
||||
|
||||
public function assertDeckAvailable(IUser $user): void {
|
||||
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');
|
||||
}
|
||||
@@ -59,12 +224,11 @@ class DeckIntegrationService {
|
||||
/**
|
||||
* @return array<int, array{id: int, title: string}>
|
||||
*
|
||||
* Only ever call this from a *request*: Deck injects the current user id
|
||||
* into BoardService as a plain string frozen at construction time, so in
|
||||
* the background job (one process, many users, a container-cached
|
||||
* BoardService) this would answer for the wrong user — or for none at
|
||||
* all. The job uses findStackIds() instead, which goes through Deck's
|
||||
* PermissionService and therefore reads the live session.
|
||||
* 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.
|
||||
*/
|
||||
public function listBoardsForCurrentUser(): array {
|
||||
$boards = $this->call(function () {
|
||||
@@ -127,23 +291,46 @@ class DeckIntegrationService {
|
||||
* Ids of the board's stacks, for deciding whether a stored workflow still
|
||||
* points at anything real.
|
||||
*
|
||||
* Returns `null` when the board itself is gone or not readable for the
|
||||
* current user — `StackService::findAll()` runs a Deck permission check
|
||||
* first, and that one reads the *live* session, which is what makes this
|
||||
* usable from the impersonating background job. Any other failure throws,
|
||||
* Returns `null` only on positive knowledge that the board is gone, in the
|
||||
* trash, or no longer readable for `$userId`. Every other failure throws,
|
||||
* because "Deck is broken right now" must never be mistaken for "the user
|
||||
* deleted this board".
|
||||
* deleted this board" — the caller reacts by switching the workflow off
|
||||
* and mailing its owner.
|
||||
*
|
||||
* Deliberately assembled from pieces that cannot answer for the wrong
|
||||
* user. BoardMapper and StackMapper are plain QBMappers with no user
|
||||
* state (StackMapper::findAll() filters `deleted_at = 0` itself), and
|
||||
* getPermissions() is handed the uid explicitly instead of falling back
|
||||
* to PermissionService's construction-time `$userId`. Leaning on that
|
||||
* frozen value — which is exactly what `StackService::findAll()` does
|
||||
* internally — is what disabled workflows whose board was perfectly
|
||||
* intact, so this must not be "simplified" back to one service call even
|
||||
* once beginUserContext() has pinned the identity.
|
||||
*
|
||||
* @return int[]|null
|
||||
* @throws DeckUnavailableException
|
||||
*/
|
||||
public function findStackIds(int $boardId): ?array {
|
||||
public function findStackIds(int $boardId, string $userId): ?array {
|
||||
try {
|
||||
$stacks = $this->resolve(StackService::class)->findAll($boardId);
|
||||
$board = $this->resolve(BoardMapper::class)->find($boardId);
|
||||
if (method_exists($board, 'getDeletedAt') && (int)$board->getDeletedAt() > 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$permissions = $this->resolve(PermissionService::class)->getPermissions($boardId, $userId);
|
||||
if (!array_key_exists(self::ACL_PERMISSION_READ, $permissions)) {
|
||||
// Unknown shape: say nothing rather than something wrong.
|
||||
throw new DeckUnavailableException('Deck reported no read permission for board ' . $boardId);
|
||||
}
|
||||
if ($permissions[self::ACL_PERMISSION_READ] !== true) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$stacks = $this->resolve(StackMapper::class)->findAll($boardId);
|
||||
} catch (DeckUnavailableException $e) {
|
||||
throw $e;
|
||||
} catch (Throwable $e) {
|
||||
if ($this->isMissingOrForbidden($e)) {
|
||||
if ($this->isMissing($e)) {
|
||||
return null;
|
||||
}
|
||||
$this->logger->error('Could not list stacks of board ' . $boardId . ': ' . $e->getMessage(), [
|
||||
@@ -160,34 +347,98 @@ class DeckIntegrationService {
|
||||
* 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
|
||||
* or renamed Deck degrades to "unknown error" instead of fataling.
|
||||
*
|
||||
* `OCA\Deck\NoPermissionException` is deliberately *not* treated as "the
|
||||
* board is gone" here. It used to be, and that is what switched intact
|
||||
* workflows off: Deck raises it for any check that fails, including every
|
||||
* check evaluated against the wrong frozen uid — which says nothing at
|
||||
* all about whether the board still exists.
|
||||
*/
|
||||
private function isMissingOrForbidden(Throwable $e): bool {
|
||||
private function isMissing(Throwable $e): bool {
|
||||
if ($e instanceof DoesNotExistException) {
|
||||
return true;
|
||||
}
|
||||
foreach (['OCA\Deck\NoPermissionException', 'OCA\Deck\NotFoundException'] as $class) {
|
||||
if (is_a($e, $class)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
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(function () use ($boardId) {
|
||||
$board = $this->resolve(BoardService::class)->find($boardId, true);
|
||||
return $board->getLabels() ?? [];
|
||||
}, []);
|
||||
$labels = $this->call(fn () => $this->readLabels($boardId), []);
|
||||
|
||||
return array_map(
|
||||
static fn ($label) => ['id' => $label->getId(), 'title' => $label->getTitle(), 'color' => $label->getColor()],
|
||||
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.
|
||||
*
|
||||
* Best effort by design: this only decorates a mail that is being sent
|
||||
* because a card *was* already moved, so anything unreadable degrades to
|
||||
* `#<id>` rather than costing the user their notification.
|
||||
*
|
||||
* @return array{board: string, sourceStack: string, targetStack: string}
|
||||
*/
|
||||
public function describeTargets(int $boardId, int $sourceStackId, int $targetStackId): array {
|
||||
$titles = $this->call(function () use ($boardId) {
|
||||
$stackTitles = [];
|
||||
foreach ($this->resolve(StackMapper::class)->findAll($boardId) as $stack) {
|
||||
$stackTitles[(int)$stack->getId()] = (string)$stack->getTitle();
|
||||
}
|
||||
|
||||
return [
|
||||
'board' => (string)$this->resolve(BoardMapper::class)->find($boardId)->getTitle(),
|
||||
'stacks' => $stackTitles,
|
||||
];
|
||||
}, ['board' => '', 'stacks' => []]);
|
||||
|
||||
return [
|
||||
'board' => self::titleOr($titles['board'], $boardId),
|
||||
'sourceStack' => self::titleOr($titles['stacks'][$sourceStackId] ?? '', $sourceStackId),
|
||||
'targetStack' => self::titleOr($titles['stacks'][$targetStackId] ?? '', $targetStackId),
|
||||
];
|
||||
}
|
||||
|
||||
private static function titleOr(string $title, int $id): string {
|
||||
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
|
||||
@@ -196,9 +447,39 @@ class DeckIntegrationService {
|
||||
* @return array<int, array{uid: string, displayName: string}>
|
||||
*/
|
||||
public function listParticipants(int $boardId): array {
|
||||
$uids = $this->call(function () use ($boardId) {
|
||||
$board = $this->resolve(BoardService::class)->find($boardId, true);
|
||||
$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) {
|
||||
@@ -221,20 +502,6 @@ class DeckIntegrationService {
|
||||
}
|
||||
|
||||
return $uids;
|
||||
}, []);
|
||||
|
||||
$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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -266,7 +533,13 @@ class DeckIntegrationService {
|
||||
$cardService = $this->resolve(CardService::class);
|
||||
|
||||
$cards = $cardMapper->findAllByStack($stackId);
|
||||
$cards = $cardService->enrichCards($cards);
|
||||
// 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);
|
||||
|
||||
return array_values(array_filter($cards, static function (Card $card) {
|
||||
if (method_exists($card, 'getDeletedAt') && (int)$card->getDeletedAt() > 0) {
|
||||
@@ -277,6 +550,45 @@ 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[]
|
||||
*/
|
||||
|
||||
@@ -30,7 +30,11 @@ class NotificationMailer {
|
||||
) {
|
||||
}
|
||||
|
||||
public function sendCardMovedNotification(IUser $user, Workflow $workflow, Card $card): void {
|
||||
/**
|
||||
* @param array{board: string, sourceStack: string, targetStack: string} $targets
|
||||
* titles resolved by DeckIntegrationService::describeTargets()
|
||||
*/
|
||||
public function sendCardMovedNotification(IUser $user, Workflow $workflow, Card $card, array $targets): void {
|
||||
$email = $user->getEMailAddress();
|
||||
if ($email === null || $email === '') {
|
||||
$this->logger->info('Skipping notification for workflow ' . $workflow->getId() . ': user ' . $user->getUID() . ' has no email address', [
|
||||
@@ -51,9 +55,25 @@ 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);
|
||||
$template->addBodyText($this->l10n->t(
|
||||
// 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);
|
||||
// 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.
|
||||
$template->addBodyText($this->l10n->t(
|
||||
'Board "%1$s": moved from "%2$s" to "%3$s".',
|
||||
[$targets['board'], $targets['sourceStack'], $targets['targetStack']],
|
||||
));
|
||||
$this->addCardDescription($template, $card);
|
||||
$template->addBodyButton($this->l10n->t('Open card'), $cardLink);
|
||||
|
||||
+175
-17
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace OCA\WorkflowDeckAutomation\Service;
|
||||
|
||||
use DateTimeInterface;
|
||||
use OCA\Deck\Db\Card;
|
||||
use OCA\WorkflowDeckAutomation\Db\Workflow;
|
||||
use OCA\WorkflowDeckAutomation\Db\WorkflowMapper;
|
||||
@@ -16,14 +17,18 @@ use Psr\Log\LoggerInterface;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Evaluates all enabled workflows and moves overdue cards.
|
||||
* Evaluates all enabled workflows and moves the cards whose watched date -
|
||||
* Deck's due date or its start date, per workflow - has passed.
|
||||
*
|
||||
* Deck's permission checks read the *live* user session, not a value
|
||||
* frozen at construction, and this runner has to evaluate rules for many
|
||||
* different users within a single background-job process. So workflows
|
||||
* are grouped by owner and, for each owner, we temporarily impersonate
|
||||
* that user (push their IUser onto the session, restore afterwards) —
|
||||
* the standard Nextcloud pattern for multi-user cron jobs.
|
||||
* This runner has to evaluate rules for many different users within a
|
||||
* single background-job process, so workflows are grouped by owner and
|
||||
* each owner is impersonated in turn. Impersonation here means two
|
||||
* things, and the second one is the load-bearing half: pushing the IUser
|
||||
* onto the session (the standard Nextcloud cron pattern), *and* pinning
|
||||
* Deck itself to that user via
|
||||
* DeckIntegrationService::beginUserContext(), because Deck's permission
|
||||
* checks never consult the session — they read a uid frozen once per
|
||||
* process. Both are undone in a finally.
|
||||
*/
|
||||
class WorkflowRunner {
|
||||
public const TARGET_BOARD = 'board';
|
||||
@@ -93,7 +98,20 @@ class WorkflowRunner {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->impersonate($user);
|
||||
} catch (DeckUnavailableException $e) {
|
||||
// Deck could not be pinned to this user, so every permission
|
||||
// check would be answered for somebody else. Skipping costs one
|
||||
// run; continuing would move the wrong cards or, worse, read a
|
||||
// denial as "the board is gone" and disable a working workflow.
|
||||
$this->logger->error('Could not impersonate {user} towards Deck: ' . $e->getMessage(), [
|
||||
'app' => 'workflow_deck_automation',
|
||||
'user' => $userId,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
foreach ($workflows as $workflow) {
|
||||
// Same reasoning as in run(): one broken workflow must not
|
||||
@@ -115,7 +133,7 @@ class WorkflowRunner {
|
||||
|
||||
private function runWorkflow(IUser $user, Workflow $workflow): void {
|
||||
try {
|
||||
$brokenTarget = $this->findBrokenTarget($workflow);
|
||||
$brokenTarget = $this->findBrokenTarget($user, $workflow);
|
||||
} catch (DeckUnavailableException $e) {
|
||||
// Could not determine it either way — leave the workflow alone
|
||||
// rather than disabling it over a temporary Deck problem.
|
||||
@@ -143,9 +161,17 @@ class WorkflowRunner {
|
||||
|
||||
$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::isOverdue($card->getDaysUntilDue())) {
|
||||
if (!self::hasPassed($this->deckService->getCardDate($card, $dateField), $now)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -155,7 +181,27 @@ class WorkflowRunner {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->moveAndNotify($user, $workflow, $card);
|
||||
$this->logger->info('Card {card} ("{title}") matches workflow {id} on its {dateField} date; moving to stack {target}.', [
|
||||
'app' => 'workflow_deck_automation',
|
||||
'card' => $card->getId(),
|
||||
'title' => $card->getTitle(),
|
||||
'id' => $workflow->getId(),
|
||||
'dateField' => $dateField,
|
||||
'target' => $workflow->getTargetStackId(),
|
||||
]);
|
||||
|
||||
if (!$this->moveCard($workflow, $card)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($workflow->getNotifyEmail()) {
|
||||
$targets ??= $this->deckService->describeTargets(
|
||||
$workflow->getBoardId(),
|
||||
$workflow->getSourceStackId(),
|
||||
$workflow->getTargetStackId(),
|
||||
);
|
||||
$this->mailer->sendCardMovedNotification($user, $workflow, $card, $targets);
|
||||
}
|
||||
}
|
||||
|
||||
$workflow->setLastRun($this->timeFactory->getDateTime());
|
||||
@@ -173,8 +219,8 @@ class WorkflowRunner {
|
||||
* @return self::TARGET_*|null
|
||||
* @throws DeckUnavailableException if Deck could not be asked
|
||||
*/
|
||||
private function findBrokenTarget(Workflow $workflow): ?string {
|
||||
$stackIds = $this->deckService->findStackIds($workflow->getBoardId());
|
||||
private function findBrokenTarget(IUser $user, Workflow $workflow): ?string {
|
||||
$stackIds = $this->deckService->findStackIds($workflow->getBoardId(), $user->getUID());
|
||||
if ($stackIds === null) {
|
||||
return self::TARGET_BOARD;
|
||||
}
|
||||
@@ -210,7 +256,7 @@ class WorkflowRunner {
|
||||
$this->mailer->sendWorkflowDisabledNotification($user, $workflow, $brokenTarget);
|
||||
}
|
||||
|
||||
private function moveAndNotify(IUser $user, Workflow $workflow, Card $card): void {
|
||||
private function moveCard(Workflow $workflow, Card $card): bool {
|
||||
try {
|
||||
$this->deckService->moveCard($card->getId(), $workflow->getTargetStackId());
|
||||
} catch (Throwable $e) {
|
||||
@@ -219,16 +265,114 @@ class WorkflowRunner {
|
||||
'card' => $card->getId(),
|
||||
'id' => $workflow->getId(),
|
||||
]);
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->logger->info('Moved card {card} ("{title}") to stack {target} for workflow {id}.', [
|
||||
'app' => 'workflow_deck_automation',
|
||||
'card' => $card->getId(),
|
||||
'title' => $card->getTitle(),
|
||||
'target' => $workflow->getTargetStackId(),
|
||||
'id' => $workflow->getId(),
|
||||
]);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* A filter whose every entry has been deleted from the board is not an
|
||||
* error — the workflow still runs, it just cannot match a single card any
|
||||
* more, forever, without anything in the UI or the log saying so. That is
|
||||
* the one failure mode of this app that is completely invisible, so it
|
||||
* gets a log line on every run.
|
||||
*
|
||||
* Explicitly *not* a reason to disable the workflow or mail the user: a
|
||||
* filter with three labels of which one was deleted still works as
|
||||
* intended, and even a fully dead filter may be one board edit away from
|
||||
* being live again. The settings page shows the same condition in red.
|
||||
*
|
||||
* @param string[] $filterUserIds
|
||||
* @param int[] $filterLabelIds
|
||||
*/
|
||||
private function warnAboutDeadFilters(Workflow $workflow, array $filterUserIds, array $filterLabelIds): void {
|
||||
if ($filterUserIds === [] && $filterLabelIds === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($workflow->getNotifyEmail()) {
|
||||
$this->mailer->sendCardMovedNotification($user, $workflow, $card);
|
||||
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(),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public static function isOverdue(?int $daysUntilDue): bool {
|
||||
return $daysUntilDue !== null && $daysUntilDue < 0;
|
||||
/**
|
||||
* 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
|
||||
* 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.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -257,6 +401,9 @@ class WorkflowRunner {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws DeckUnavailableException if Deck cannot be pinned to $user
|
||||
*/
|
||||
private function impersonate(IUser $user): void {
|
||||
$this->impersonationRestore = $this->userSession->getUser();
|
||||
$this->userSession->setUser($user);
|
||||
@@ -269,9 +416,20 @@ class WorkflowRunner {
|
||||
'app' => 'workflow_deck_automation',
|
||||
]);
|
||||
}
|
||||
|
||||
try {
|
||||
// The session switch above is necessary but nowhere near
|
||||
// sufficient — Deck's permission checks never look at it. See
|
||||
// DeckIntegrationService::beginUserContext().
|
||||
$this->deckService->beginUserContext($user);
|
||||
} catch (DeckUnavailableException $e) {
|
||||
$this->clearImpersonation();
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
private function clearImpersonation(): void {
|
||||
$this->deckService->endUserContext();
|
||||
$this->userSession->setUser($this->impersonationRestore);
|
||||
$this->impersonationRestore = null;
|
||||
}
|
||||
|
||||
@@ -29,6 +29,6 @@ class PersonalSection implements IIconSection {
|
||||
}
|
||||
|
||||
public function getIcon(): string {
|
||||
return $this->urlGenerator->imagePath(Application::APP_ID, 'app-dark.svg');
|
||||
return $this->urlGenerator->imagePath(Application::APP_ID, 'app.svg');
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "workflow_deck_automation",
|
||||
"version": "0.1.0",
|
||||
"version": "34.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Automates moving overdue Deck cards between stacks, configurable per user.",
|
||||
|
||||
+150
-19
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<NcSettingsSection
|
||||
name="Deck Workflow-Automatisierung"
|
||||
description="Verschiebt überfällige Karten aus einem Deck-Stapel automatisch in einen anderen Stapel. Ein Hintergrundjob prüft die Regeln alle paar Minuten.">
|
||||
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.">
|
||||
<NcNoteCard v-if="loadError" type="error">
|
||||
{{ loadError }}
|
||||
</NcNoteCard>
|
||||
@@ -17,6 +17,7 @@
|
||||
<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>
|
||||
@@ -33,6 +34,7 @@
|
||||
</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>
|
||||
@@ -92,6 +94,34 @@
|
||||
: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)"
|
||||
@@ -159,7 +189,10 @@ const loading = ref(true)
|
||||
const loadError = ref('')
|
||||
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)
|
||||
@@ -181,9 +214,15 @@ const sourceStackOptions = computed(() => stackOptions.value.filter((option) =>
|
||||
const targetStackOptions = computed(() => stackOptions.value.filter((option) => option.value !== form.sourceStackId))
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
const workflowIssues = computed(() => {
|
||||
const issues = {}
|
||||
@@ -195,10 +234,7 @@ const workflowIssues = computed(() => {
|
||||
}
|
||||
|
||||
const stacks = stacksByBoard[workflow.boardId]
|
||||
if (!stacks) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (stacks) {
|
||||
const missing = []
|
||||
if (!stacks.some((stack) => stack.id === workflow.sourceStackId)) {
|
||||
missing.push('Quell-Stapel')
|
||||
@@ -208,12 +244,39 @@ 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() {
|
||||
@@ -224,11 +287,16 @@ function emptyForm() {
|
||||
targetStackId: null,
|
||||
filterUserIds: [],
|
||||
filterLabelIds: [],
|
||||
dateField: 'due',
|
||||
notifyEmail: false,
|
||||
enabled: true,
|
||||
}
|
||||
}
|
||||
|
||||
function dateFieldLabel(dateField) {
|
||||
return dateField === 'start' ? 'Startdatum' : 'Fälligkeit'
|
||||
}
|
||||
|
||||
function stackLabel(boardId, stackId) {
|
||||
const stacks = stacksByBoard[boardId]
|
||||
if (!stacks) {
|
||||
@@ -242,11 +310,27 @@ async function loadStacksFor(boardId) {
|
||||
if (!boardId || stacksByBoard[boardId]) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
stacksByBoard[boardId] = await fetchStacks(boardId)
|
||||
} catch (e) {
|
||||
stacksByBoard[boardId] = []
|
||||
// `null`, not `[]` — "could not ask Deck" has to stay distinguishable
|
||||
// from "this board has none", or a single failed request reports every
|
||||
// stack of the board as deleted.
|
||||
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() {
|
||||
@@ -256,7 +340,13 @@ async function loadAll() {
|
||||
const [loadedWorkflows, loadedBoards] = await Promise.all([fetchWorkflows(), fetchBoards()])
|
||||
workflows.value = loadedWorkflows
|
||||
boards.value = loadedBoards
|
||||
await Promise.all(loadedWorkflows.map((workflow) => loadStacksFor(workflow.boardId)))
|
||||
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
|
||||
}))
|
||||
} catch (e) {
|
||||
loadError.value = 'Konnte Workflows oder Deck-Boards nicht laden. Ist die Deck-App aktiviert?'
|
||||
} finally {
|
||||
@@ -281,15 +371,20 @@ async function loadBoardOptions(boardId) {
|
||||
|
||||
// One failing endpoint must not take the other two dropdowns down with it.
|
||||
const [stacks, labels, participants] = await Promise.all([
|
||||
fetchStacks(boardId).catch(() => []),
|
||||
fetchLabels(boardId).catch(() => []),
|
||||
fetchParticipants(boardId).catch(() => []),
|
||||
fetchStacks(boardId).catch(() => null),
|
||||
fetchLabels(boardId).catch(() => null),
|
||||
fetchParticipants(boardId).catch(() => null),
|
||||
])
|
||||
|
||||
// Feed the overview's caches too, so its red markers agree with what the
|
||||
// form just loaded. `null` propagates on purpose: it means "unknown".
|
||||
stacksByBoard[boardId] = stacks
|
||||
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 }))
|
||||
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 }))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -326,6 +421,8 @@ async function editWorkflow(workflow) {
|
||||
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,
|
||||
})
|
||||
@@ -438,4 +535,38 @@ 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>
|
||||
@@ -0,0 +1,43 @@
|
||||
<?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']);
|
||||
}
|
||||
}
|
||||
@@ -4,22 +4,35 @@ declare(strict_types=1);
|
||||
|
||||
namespace OCA\WorkflowDeckAutomation\Tests\Unit\Service;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use OCA\WorkflowDeckAutomation\Service\WorkflowRunner;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class WorkflowRunnerFilterTest extends TestCase {
|
||||
public function testIsOverdueReturnsFalseWithoutDueDate(): void {
|
||||
$this->assertFalse(WorkflowRunner::isOverdue(null));
|
||||
public function testHasPassedReturnsFalseWithoutADate(): void {
|
||||
$this->assertFalse(WorkflowRunner::hasPassed(null, new DateTimeImmutable('2026-01-15 12:00:00')));
|
||||
}
|
||||
|
||||
public function testIsOverdueReturnsFalseForFutureDueDate(): void {
|
||||
$this->assertFalse(WorkflowRunner::isOverdue(0));
|
||||
$this->assertFalse(WorkflowRunner::isOverdue(3));
|
||||
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 testIsOverdueReturnsTrueForPastDueDate(): void {
|
||||
$this->assertTrue(WorkflowRunner::isOverdue(-1));
|
||||
$this->assertTrue(WorkflowRunner::isOverdue(-30));
|
||||
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 {
|
||||
@@ -43,4 +56,28 @@ class WorkflowRunnerFilterTest extends TestCase {
|
||||
// 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], [], []));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user