Compare commits
16
Commits
80371d48fb
...
v35.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dfec88d396 | ||
|
|
28b4edc811 | ||
|
|
0e66319a06 | ||
|
|
43648f3728 | ||
|
|
ce749e63a4 | ||
|
|
b203ba35f8 | ||
|
|
ef973af4b5 | ||
|
|
a95d5e2d8a | ||
|
|
2d2f3ca19c | ||
|
|
a6dde35249 | ||
|
|
7ca728e79c | ||
|
|
be6faa7b42 | ||
|
|
131ef2e938 | ||
|
|
b4057809ed | ||
|
|
0eff367268 | ||
|
|
ee72d6fcf9 |
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 Summer 26 (server 35.x)** on this branch (`main` tracks Hub 26 Spring / server 34.x). It lets each user configure, from their personal settings, automation "workflows" that move overdue [Deck](https://github.com/nextcloud/deck) cards from one stack to another, with optional assigned-user/label filters and an email notification. A background `Job` evaluates all enabled workflows on every cron pass.
|
||||
|
||||
## Non-negotiable architectural constraint
|
||||
|
||||
@@ -14,17 +14,54 @@ All Deck access is funneled through `lib/Service/DeckIntegrationService.php` —
|
||||
|
||||
## 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.
|
||||
|
||||
## Job interval comes from config.php
|
||||
Both are undone in a `finally` (`WorkflowRunner::clearImpersonation()`).
|
||||
|
||||
`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.
|
||||
**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.
|
||||
|
||||
**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.
|
||||
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).
|
||||
|
||||
**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:
|
||||
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()`, `::isOverdue()`, `::findDeadFilters()`) is deliberately `static` and side-effect-free so it's unit-testable without a real Deck installation — see `tests/Unit/Service/WorkflowRunnerFilterTest.php`. Keep new pure logic in that shape; it is the only part of this app that has tests at all.
|
||||
|
||||
## 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 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.
|
||||
|
||||
## Dead filters are surfaced, never disabled
|
||||
|
||||
`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 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.
|
||||
|
||||
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()) {
|
||||
@@ -32,7 +69,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
|
||||
@@ -41,7 +80,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
|
||||
|
||||
@@ -70,6 +109,10 @@ 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 .../>` (on this branch `min-version="35" max-version="35"`), not this app's own feature history - so it only changes when the supported Nextcloud major changes, and resets `minor`/`patch` to `0.0` at that point. Ordinary fixes/features within the same supported NC major bump `minor`/`patch` as usual (semver-ish, without a leading `0.`). Versions before `34.0.0` (`0.1.x`/`0.2.x`) predate this scheme.
|
||||
|
||||
This branch (`nextcloud-35`) is a permanent, separately maintained version line for Nextcloud 35, started at `35.0.0` alongside the `34.x.x` line on `main`. Backport fixes between the two lines manually where relevant; they are not merged into each other.
|
||||
|
||||
1. Bump `<version>` in `appinfo/info.xml` and `version` in `package.json` (keep them in sync).
|
||||
2. Commit, push to `main`, confirm the run of `.gitea/workflows/build-main.yml` is green.
|
||||
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.
|
||||
@@ -105,7 +148,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,6 @@
|
||||
# Deck Workflow-Automatisierung
|
||||
|
||||
Nextcloud-App für **Nextcloud Hub 26 Spring (Server 34.x)**, die überfällige Karten der [Deck](https://github.com/nextcloud/deck)-App automatisch von einem Stapel in einen anderen verschiebt und optional eine E-Mail-Benachrichtigung verschickt.
|
||||
Nextcloud-App für **Nextcloud Hub Summer 26 (Server 35.x)**, die überfällige Karten der [Deck](https://github.com/nextcloud/deck)-App automatisch von einem Stapel in einen anderen verschiebt und optional eine E-Mail-Benachrichtigung verschickt.
|
||||
|
||||
Ersetzt das früher genutzte eigenständige PHP-Cron-Skript durch eine vollwertige App mit Oberfläche in den **persönlichen Einstellungen** — jeder Nutzer kann dort seine eigenen Regeln ("Workflows") anlegen, ohne Admin-Rechte oder Server-Zugriff zu benötigen.
|
||||
|
||||
@@ -19,8 +19,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
|
||||
@@ -38,23 +38,38 @@ Ein Nutzer kann beliebig viele Workflows anlegen, bearbeiten, deaktivieren oder
|
||||
|
||||
Jeder Nutzer findet die Einstellungen unter **Persönliche Einstellungen → Deck Workflow-Automatisierung**. Dort können neue Workflows angelegt, bestehende bearbeitet oder gelöscht werden. Die Dropdowns für Board/Stapel/Label/Benutzer werden live aus Deck geladen. Zur Auswahl stehen nur aktive Boards — archivierte und im Papierkorb liegende Boards sowie gelöschte Stapel blendet Deck bzw. die App aus.
|
||||
|
||||
## Konfiguration
|
||||
### Gelöschte Boards und Stapel
|
||||
|
||||
Das Prüfintervall des Hintergrundjobs lässt sich in der `config.php` setzen (Wert in **Sekunden**):
|
||||
Ein Workflow verweist per ID auf ein Board und zwei Stapel. Wird eines davon in Deck gelöscht, passiert Folgendes:
|
||||
|
||||
```php
|
||||
'workflow_deck_automation.interval' => 300,
|
||||
```
|
||||
- **Beim Speichern** werden Board und Stapel geprüft; ein Workflow auf nicht mehr existierende Ziele lässt sich gar nicht erst anlegen.
|
||||
- **In der Übersicht** wird ein betroffener Workflow rot markiert („Board nicht mehr vorhanden", „Quell-Stapel nicht mehr vorhanden" …).
|
||||
- **Im Hintergrundjob** wird der Workflow automatisch deaktiviert und der Besitzer einmalig per E-Mail informiert — unabhängig davon, ob für den Workflow „E-Mail senden" aktiviert ist, denn hier geht es nicht um verschobene Karten, sondern darum, dass die Automatisierung nicht mehr läuft. Danach bleibt es still: Ein deaktivierter Workflow wird nicht erneut ausgewertet.
|
||||
|
||||
- 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.
|
||||
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.
|
||||
|
||||
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.
|
||||
### Gelöschte Labels und entfernte Benutzer
|
||||
|
||||
Filter sind ein anderer Fall: Sie werden **nicht** deaktiviert. Wird eines von drei ausgewählten Labels gelöscht, greifen die anderen beiden weiter — das abzuschalten wäre falsch.
|
||||
|
||||
Problematisch ist nur der Grenzfall, dass **alle** Einträge eines Filters verschwunden sind. Der Workflow läuft dann weiter, kann aber keine einzige Karte mehr treffen. Das passiert bei gelöschten Labels und ebenso, wenn ein gefilterter Benutzer die Board-Freigabe verliert — Deck entfernt dabei alle seine Kartenzuweisungen auf diesem Board.
|
||||
|
||||
Damit dieser Zustand nicht unsichtbar bleibt:
|
||||
|
||||
- **In der Übersicht** wird der Workflow rot markiert („Label-Filter trifft keine Karte mehr", „Benutzer-Filter trifft keine Karte mehr").
|
||||
- **Im Hintergrundjob** landet bei jedem Lauf eine Warnung im `nextcloud.log`.
|
||||
|
||||
Keine E-Mail und keine Deaktivierung: Ein einziger Board-Klick kann den Filter wieder lebendig machen. Und wie bei Board und Stapel gilt auch hier — lässt sich das Board gerade nicht abfragen, wird nichts gemeldet statt etwas Falsches.
|
||||
|
||||
## Ausführungstakt
|
||||
|
||||
Der Hintergrundjob hat **kein eigenes Intervall** und ist auch nicht konfigurierbar: Er läuft bei **jedem** Cron-Durchlauf von Nextcloud. Der Takt ist damit exakt der des System-Crons — üblicherweise alle 5 Minuten, bei einem häufiger eingerichteten Cron entsprechend öfter.
|
||||
|
||||
> 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.
|
||||
|
||||
@@ -101,7 +116,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)
|
||||
|
||||
+3
-3
@@ -28,7 +28,7 @@ This app lets every user configure their own Deck automation workflows from Pers
|
||||
|
||||
A background job periodically evaluates all enabled workflows and moves cards whose due date has passed, using Deck's own internal PHP classes only (no HTTP/OCS calls).
|
||||
]]></description>
|
||||
<version>0.1.0</version>
|
||||
<version>35.0.0</version>
|
||||
<licence>agpl</licence>
|
||||
<author mail="patrick@niebel.ing">Patrick Niebeling</author>
|
||||
<namespace>WorkflowDeckAutomation</namespace>
|
||||
@@ -36,11 +36,11 @@ 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>
|
||||
<nextcloud min-version="34" max-version="34"/>
|
||||
<nextcloud min-version="35" max-version="35"/>
|
||||
</dependencies>
|
||||
<background-jobs>
|
||||
<job>OCA\WorkflowDeckAutomation\BackgroundJob\RunWorkflowsJob</job>
|
||||
|
||||
@@ -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;
|
||||
use OCP\BackgroundJob\Job;
|
||||
|
||||
class RunWorkflowsJob extends TimedJob {
|
||||
/**
|
||||
* config.php key holding how often (in seconds) workflows are checked.
|
||||
/**
|
||||
* 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 INTERVAL_CONFIG_KEY = 'workflow_deck_automation.interval';
|
||||
|
||||
public const DEFAULT_INTERVAL = 5 * 60;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ class WorkflowController extends OCSController {
|
||||
bool $notifyEmail = false,
|
||||
bool $enabled = true,
|
||||
): DataResponse {
|
||||
$this->validate($title, $sourceStackId, $targetStackId);
|
||||
$this->validate($title, $boardId, $sourceStackId, $targetStackId);
|
||||
|
||||
$workflow = new Workflow();
|
||||
$workflow->setUserId($this->currentUserId());
|
||||
@@ -85,7 +85,7 @@ class WorkflowController extends OCSController {
|
||||
bool $notifyEmail = false,
|
||||
bool $enabled = true,
|
||||
): DataResponse {
|
||||
$this->validate($title, $sourceStackId, $targetStackId);
|
||||
$this->validate($title, $boardId, $sourceStackId, $targetStackId);
|
||||
|
||||
try {
|
||||
$workflow = $this->workflowMapper->findForUser($id, $this->currentUserId());
|
||||
@@ -147,13 +147,35 @@ class WorkflowController extends OCSController {
|
||||
}
|
||||
}
|
||||
|
||||
private function validate(string $title, int $sourceStackId, int $targetStackId): void {
|
||||
private function validate(string $title, int $boardId, int $sourceStackId, int $targetStackId): void {
|
||||
if (trim($title) === '') {
|
||||
throw new OCSBadRequestException('Title must not be empty');
|
||||
}
|
||||
if ($sourceStackId === $targetStackId) {
|
||||
throw new OCSBadRequestException('Source and target stack must differ');
|
||||
}
|
||||
|
||||
// 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.
|
||||
// assertDeck() ran first, so an empty list here means "not there",
|
||||
// not "Deck is unreachable".
|
||||
$this->assertDeck();
|
||||
|
||||
$boardIds = array_map(
|
||||
static fn (array $board) => (int)$board['id'],
|
||||
$this->deckService->listBoardsForCurrentUser(),
|
||||
);
|
||||
if (!in_array($boardId, $boardIds, true)) {
|
||||
throw new OCSBadRequestException('The selected board does not exist or is not accessible');
|
||||
}
|
||||
|
||||
$stackIds = array_map(
|
||||
static fn (array $stack) => (int)$stack['id'],
|
||||
$this->deckService->listStacks($boardId),
|
||||
);
|
||||
if (!in_array($sourceStackId, $stackIds, true) || !in_array($targetStackId, $stackIds, true)) {
|
||||
throw new OCSBadRequestException('The selected stack does not exist on this board');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,17 +4,22 @@ declare(strict_types=1);
|
||||
|
||||
namespace OCA\WorkflowDeckAutomation\Service;
|
||||
|
||||
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;
|
||||
use OCP\IGroupManager;
|
||||
use OCP\IUser;
|
||||
use OCP\IUserManager;
|
||||
use OCP\Server;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use ReflectionProperty;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
@@ -38,6 +43,36 @@ 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',
|
||||
];
|
||||
|
||||
/**
|
||||
* @var list<array{ReflectionProperty, object, ?string}>
|
||||
*/
|
||||
private array $identityRestore = [];
|
||||
|
||||
public function __construct(
|
||||
private IAppManager $appManager,
|
||||
private IUserManager $userManager,
|
||||
@@ -46,6 +81,87 @@ 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());
|
||||
@@ -57,6 +173,12 @@ class DeckIntegrationService {
|
||||
|
||||
/**
|
||||
* @return array<int, array{id: int, title: string}>
|
||||
*
|
||||
* 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 () {
|
||||
@@ -110,26 +232,163 @@ class DeckIntegrationService {
|
||||
}, []);
|
||||
|
||||
return array_map(
|
||||
static fn ($stack) => ['id' => $stack->getId(), 'title' => $stack->getTitle()],
|
||||
static fn ($stack) => ['id' => (int)$stack->getId(), 'title' => $stack->getTitle()],
|
||||
$stacks,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ids of the board's stacks, for deciding whether a stored workflow still
|
||||
* points at anything real.
|
||||
*
|
||||
* 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" — 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, string $userId): ?array {
|
||||
try {
|
||||
$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->isMissing($e)) {
|
||||
return null;
|
||||
}
|
||||
$this->logger->error('Could not list stacks of board ' . $boardId . ': ' . $e->getMessage(), [
|
||||
'app' => 'workflow_deck_automation',
|
||||
'exception' => $e,
|
||||
]);
|
||||
throw new DeckUnavailableException('Deck call failed: ' . $e->getMessage(), 0, $e);
|
||||
}
|
||||
|
||||
return array_map(static fn ($stack) => (int)$stack->getId(), $stacks);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 isMissing(Throwable $e): bool {
|
||||
if ($e instanceof DoesNotExistException) {
|
||||
return true;
|
||||
}
|
||||
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
|
||||
@@ -138,9 +397,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) {
|
||||
@@ -163,20 +452,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -191,8 +466,14 @@ class DeckIntegrationService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Cards in the given stack that are neither archived nor marked done,
|
||||
* enriched so getAssignedUsers()/getLabels() are populated.
|
||||
* Cards in the given stack that are neither archived, deleted nor marked
|
||||
* done, enriched so getAssignedUsers()/getLabels() are populated.
|
||||
*
|
||||
* The `deletedAt` check is not redundant: Deck's
|
||||
* `CardMapper::findAllByStack()` filters on `stack_id` and
|
||||
* `archived = false` only, so cards sitting in the trash come back too —
|
||||
* they are kept until Deck's own DeleteCron purges them. Without this we
|
||||
* would move cards the user already deleted.
|
||||
*
|
||||
* @return Card[]
|
||||
*/
|
||||
@@ -202,9 +483,18 @@ 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 isOverdue() was always false and no workflow ever matched a card.
|
||||
// Keep using the original, now-enriched $cards instead.
|
||||
$cardService->enrichCards($cards);
|
||||
|
||||
return array_values(array_filter($cards, static function (Card $card) {
|
||||
if (method_exists($card, 'getDeletedAt') && (int)$card->getDeletedAt() > 0) {
|
||||
return false;
|
||||
}
|
||||
return !$card->getArchived() && $card->getDone() === null;
|
||||
}));
|
||||
}, []);
|
||||
|
||||
@@ -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', [
|
||||
@@ -55,6 +59,13 @@ class NotificationMailer {
|
||||
'The card "%1$s" was moved because it is overdue (workflow "%2$s").',
|
||||
[$card->getTitle(), $workflow->getTitle()],
|
||||
));
|
||||
// Single-argument addBodyText() runs htmlspecialchars() itself, so
|
||||
// these board- and stack-titles (user input) are safe as-is —
|
||||
// unlike the description below, which passes both parts.
|
||||
$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);
|
||||
$template->addFooter();
|
||||
@@ -78,6 +89,65 @@ class NotificationMailer {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One-off notice that a workflow was switched off because the board or
|
||||
* stack it points at is gone.
|
||||
*
|
||||
* @param WorkflowRunner::TARGET_* $brokenTarget
|
||||
*/
|
||||
public function sendWorkflowDisabledNotification(IUser $user, Workflow $workflow, string $brokenTarget): void {
|
||||
$email = $user->getEMailAddress();
|
||||
if ($email === null || $email === '') {
|
||||
$this->logger->info('Cannot notify about disabled workflow ' . $workflow->getId() . ': user ' . $user->getUID() . ' has no email address', [
|
||||
'app' => 'workflow_deck_automation',
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
$reason = match ($brokenTarget) {
|
||||
WorkflowRunner::TARGET_SOURCE_STACK => $this->l10n->t('its source stack no longer exists'),
|
||||
WorkflowRunner::TARGET_TARGET_STACK => $this->l10n->t('its target stack no longer exists'),
|
||||
default => $this->l10n->t('its board no longer exists or is no longer available to you'),
|
||||
};
|
||||
|
||||
try {
|
||||
$settingsLink = $this->urlGenerator->getAbsoluteURL('/settings/user/workflow_deck_automation');
|
||||
|
||||
$template = $this->mailer->createEMailTemplate('workflow_deck_automation.WorkflowDisabled', [
|
||||
'workflowTitle' => $workflow->getTitle(),
|
||||
]);
|
||||
$template->setSubject($this->l10n->t('Deck workflow deactivated: %s', [$workflow->getTitle()]));
|
||||
$template->addHeader();
|
||||
$template->addHeading($this->l10n->t('A workflow was deactivated'), false);
|
||||
$template->addBodyText($this->l10n->t(
|
||||
'The workflow "%1$s" was switched off automatically because %2$s. No cards are being moved by it any more.',
|
||||
[$workflow->getTitle(), $reason],
|
||||
));
|
||||
$template->addBodyText($this->l10n->t(
|
||||
'Delete the workflow or point it at an existing board and stack to reactivate it. You will not be reminded about this workflow again.',
|
||||
));
|
||||
$template->addBodyButton($this->l10n->t('Open settings'), $settingsLink);
|
||||
$template->addFooter();
|
||||
|
||||
$message = $this->mailer->createMessage();
|
||||
$message->setTo([$email => $user->getDisplayName()]);
|
||||
$message->setFrom([Util::getDefaultEmailAddress('noreply') => $this->l10n->t('Deck Workflow Automation')]);
|
||||
$message->useTemplate($template);
|
||||
|
||||
$failedRecipients = $this->mailer->send($message);
|
||||
if (!empty($failedRecipients)) {
|
||||
$this->logger->error('Deactivation mail for workflow ' . $workflow->getId() . ' failed for: ' . implode(', ', $failedRecipients), [
|
||||
'app' => 'workflow_deck_automation',
|
||||
]);
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
$this->logger->error('Could not send deactivation mail for workflow ' . $workflow->getId() . ': ' . $e->getMessage(), [
|
||||
'app' => 'workflow_deck_automation',
|
||||
'exception' => $e,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends the card's description, if it has one.
|
||||
*
|
||||
|
||||
+232
-13
@@ -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;
|
||||
@@ -18,14 +19,21 @@ use Throwable;
|
||||
/**
|
||||
* Evaluates all enabled workflows and moves overdue cards.
|
||||
*
|
||||
* 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';
|
||||
public const TARGET_SOURCE_STACK = 'sourceStack';
|
||||
public const TARGET_TARGET_STACK = 'targetStack';
|
||||
|
||||
private ?IUser $impersonationRestore = null;
|
||||
|
||||
public function __construct(
|
||||
@@ -89,7 +97,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
|
||||
@@ -110,6 +131,23 @@ class WorkflowRunner {
|
||||
}
|
||||
|
||||
private function runWorkflow(IUser $user, Workflow $workflow): void {
|
||||
try {
|
||||
$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.
|
||||
$this->logger->warning('Could not verify targets of workflow {id}: ' . $e->getMessage(), [
|
||||
'app' => 'workflow_deck_automation',
|
||||
'id' => $workflow->getId(),
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
if ($brokenTarget !== null) {
|
||||
$this->disableBrokenWorkflow($user, $workflow, $brokenTarget);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$cards = $this->deckService->getActiveCardsInStack($workflow->getSourceStackId());
|
||||
} catch (DeckUnavailableException $e) {
|
||||
@@ -122,9 +160,16 @@ 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();
|
||||
|
||||
foreach ($cards as $card) {
|
||||
if (!self::isOverdue($card->getDaysUntilDue())) {
|
||||
if (!self::isOverdue($card->getDuedate(), $now)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -134,14 +179,81 @@ class WorkflowRunner {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->moveAndNotify($user, $workflow, $card);
|
||||
$this->logger->info('Card {card} ("{title}") matches workflow {id}; moving to stack {target}.', [
|
||||
'app' => 'workflow_deck_automation',
|
||||
'card' => $card->getId(),
|
||||
'title' => $card->getTitle(),
|
||||
'id' => $workflow->getId(),
|
||||
'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());
|
||||
$this->workflowMapper->update($workflow);
|
||||
}
|
||||
|
||||
private function moveAndNotify(IUser $user, Workflow $workflow, Card $card): void {
|
||||
/**
|
||||
* Which of the workflow's Deck references no longer exists, if any.
|
||||
*
|
||||
* Deleting a board or stack leaves the workflow row untouched — there is
|
||||
* no foreign key — and Deck keeps the orphaned cards readable until its
|
||||
* own DeleteCron purges them, so the workflow would otherwise keep
|
||||
* failing on every single run.
|
||||
*
|
||||
* @return self::TARGET_*|null
|
||||
* @throws DeckUnavailableException if Deck could not be asked
|
||||
*/
|
||||
private function findBrokenTarget(IUser $user, Workflow $workflow): ?string {
|
||||
$stackIds = $this->deckService->findStackIds($workflow->getBoardId(), $user->getUID());
|
||||
if ($stackIds === null) {
|
||||
return self::TARGET_BOARD;
|
||||
}
|
||||
|
||||
if (!in_array($workflow->getSourceStackId(), $stackIds, true)) {
|
||||
return self::TARGET_SOURCE_STACK;
|
||||
}
|
||||
if (!in_array($workflow->getTargetStackId(), $stackIds, true)) {
|
||||
return self::TARGET_TARGET_STACK;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param self::TARGET_* $brokenTarget
|
||||
*/
|
||||
private function disableBrokenWorkflow(IUser $user, Workflow $workflow, string $brokenTarget): void {
|
||||
$workflow->setEnabled(false);
|
||||
$workflow->setLastRun($this->timeFactory->getDateTime());
|
||||
$this->workflowMapper->update($workflow);
|
||||
|
||||
$this->logger->warning('Disabled workflow {id}: its {target} no longer exists', [
|
||||
'app' => 'workflow_deck_automation',
|
||||
'id' => $workflow->getId(),
|
||||
'target' => $brokenTarget,
|
||||
]);
|
||||
|
||||
// Sent regardless of the workflow's notifyEmail setting: that flag is
|
||||
// about moved cards, this is a one-off notice that the automation the
|
||||
// user configured has been switched off. It stays one-off because a
|
||||
// disabled workflow is not picked up again.
|
||||
$this->mailer->sendWorkflowDisabledNotification($user, $workflow, $brokenTarget);
|
||||
}
|
||||
|
||||
private function moveCard(Workflow $workflow, Card $card): bool {
|
||||
try {
|
||||
$this->deckService->moveCard($card->getId(), $workflow->getTargetStackId());
|
||||
} catch (Throwable $e) {
|
||||
@@ -150,16 +262,109 @@ 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;
|
||||
/**
|
||||
* Compares the card's actual due timestamp against $now instead of Deck's own
|
||||
* Card::getDaysUntilDue(), which truncates both sides to midnight before diffing
|
||||
* (DateInterval's %a is a whole-day count) and therefore reports 0 - not overdue -
|
||||
* for any card whose due time has already passed today. That silently held back
|
||||
* every card for up to 24h after it actually fell due; comparing the raw datetime
|
||||
* instead matches what Deck's own UI shows (e.g. "vor 2 Stunden") and has no
|
||||
* day-rounding step to get wrong.
|
||||
*/
|
||||
public static function isOverdue(?DateTimeInterface $duedate, DateTimeInterface $now): bool {
|
||||
return $duedate !== null && $duedate < $now;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which filters cannot match anything any more, because not one of their
|
||||
* entries is still offered by the board. An empty filter is not dead, it
|
||||
* is "no restriction on this dimension" — the same reading as in
|
||||
* cardMatchesFilters(), and getting it backwards would report every
|
||||
* unfiltered workflow as broken.
|
||||
*
|
||||
* Static and side-effect free for the same reason as the matching logic:
|
||||
* testable without a Deck installation.
|
||||
*
|
||||
* @param string[] $filterUserIds
|
||||
* @param int[] $filterLabelIds
|
||||
* @param string[] $boardUserIds everyone who can hold a card on the board
|
||||
* @param int[] $boardLabelIds the board's remaining labels
|
||||
* @return string[] any of 'label', 'user', in that order
|
||||
*/
|
||||
public static function findDeadFilters(
|
||||
array $filterUserIds,
|
||||
array $filterLabelIds,
|
||||
array $boardUserIds,
|
||||
array $boardLabelIds,
|
||||
): array {
|
||||
$dead = [];
|
||||
if ($filterLabelIds !== [] && array_intersect($filterLabelIds, $boardLabelIds) === []) {
|
||||
$dead[] = 'label';
|
||||
}
|
||||
if ($filterUserIds !== [] && array_intersect($filterUserIds, $boardUserIds) === []) {
|
||||
$dead[] = 'user';
|
||||
}
|
||||
return $dead;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -188,6 +393,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);
|
||||
@@ -200,9 +408,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": "35.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Automates moving overdue Deck cards between stacks, configurable per user.",
|
||||
|
||||
+117
-12
@@ -25,7 +25,12 @@
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="workflow in workflows" :key="workflow.id">
|
||||
<td>{{ workflow.title }}</td>
|
||||
<td>
|
||||
{{ workflow.title }}
|
||||
<span v-if="workflowIssues[workflow.id]" class="wfda-issue">
|
||||
{{ workflowIssues[workflow.id] }}
|
||||
</span>
|
||||
</td>
|
||||
<td>{{ stackLabel(workflow.boardId, workflow.sourceStackId) }}</td>
|
||||
<td>{{ stackLabel(workflow.boardId, workflow.targetStackId) }}</td>
|
||||
<td>
|
||||
@@ -154,7 +159,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)
|
||||
@@ -175,6 +183,70 @@ const boardOptions = computed(() => boards.value.map((board) => ({ value: board.
|
||||
const sourceStackOptions = computed(() => stackOptions.value.filter((option) => option.value !== form.targetStackId))
|
||||
const targetStackOptions = computed(() => stackOptions.value.filter((option) => option.value !== form.sourceStackId))
|
||||
|
||||
/**
|
||||
* Workflows that stopped working, keyed by id. Two different kinds:
|
||||
*
|
||||
* - Board or stacks deleted in Deck. The background job switches these off
|
||||
* by itself, but a row that just stopped working needs to say so instead
|
||||
* of looking healthy.
|
||||
* - Every entry of a filter deleted from the board. Nothing switches those
|
||||
* off — deliberately, since one deleted label out of three is harmless —
|
||||
* yet a filter that cannot match a single card any more is otherwise
|
||||
* completely invisible: the workflow keeps running and moves nothing.
|
||||
*/
|
||||
const workflowIssues = computed(() => {
|
||||
const issues = {}
|
||||
|
||||
for (const workflow of workflows.value) {
|
||||
if (!boards.value.some((board) => board.id === workflow.boardId)) {
|
||||
issues[workflow.id] = 'Board nicht mehr vorhanden'
|
||||
continue
|
||||
}
|
||||
|
||||
const stacks = stacksByBoard[workflow.boardId]
|
||||
if (stacks) {
|
||||
const missing = []
|
||||
if (!stacks.some((stack) => stack.id === workflow.sourceStackId)) {
|
||||
missing.push('Quell-Stapel')
|
||||
}
|
||||
if (!stacks.some((stack) => stack.id === workflow.targetStackId)) {
|
||||
missing.push('Ziel-Stapel')
|
||||
}
|
||||
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() {
|
||||
@@ -203,11 +275,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() {
|
||||
@@ -217,7 +305,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 {
|
||||
@@ -242,15 +336,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 }))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -370,6 +469,12 @@ onMounted(loadAll)
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.wfda-issue {
|
||||
display: block;
|
||||
color: var(--color-error);
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
.wfda-empty {
|
||||
color: var(--color-text-maxcontrast);
|
||||
margin-bottom: 16px;
|
||||
|
||||
@@ -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));
|
||||
$this->assertFalse(WorkflowRunner::isOverdue(null, new DateTimeImmutable('2026-01-15 12:00:00')));
|
||||
}
|
||||
|
||||
public function testIsOverdueReturnsFalseForFutureDueDate(): void {
|
||||
$this->assertFalse(WorkflowRunner::isOverdue(0));
|
||||
$this->assertFalse(WorkflowRunner::isOverdue(3));
|
||||
$now = new DateTimeImmutable('2026-01-15 12:00:00');
|
||||
$this->assertFalse(WorkflowRunner::isOverdue($now->modify('+1 hour'), $now));
|
||||
$this->assertFalse(WorkflowRunner::isOverdue($now->modify('+3 days'), $now));
|
||||
}
|
||||
|
||||
public function testIsOverdueReturnsTrueForPastDueDate(): void {
|
||||
$this->assertTrue(WorkflowRunner::isOverdue(-1));
|
||||
$this->assertTrue(WorkflowRunner::isOverdue(-30));
|
||||
$now = new DateTimeImmutable('2026-01-15 12:00:00');
|
||||
$this->assertTrue(WorkflowRunner::isOverdue($now->modify('-1 hour'), $now));
|
||||
$this->assertTrue(WorkflowRunner::isOverdue($now->modify('-30 days'), $now));
|
||||
}
|
||||
|
||||
public function testIsOverdueReturnsTrueForADueTimeEarlierTheSameDay(): void {
|
||||
// Regression: comparing whole calendar days (as Deck's own
|
||||
// Card::getDaysUntilDue() does) reports a card due earlier today as
|
||||
// "0 days until due", not overdue, until the calendar date rolls
|
||||
// over - holding every card back for up to 24h after it actually
|
||||
// fell due. isOverdue() must compare the real timestamps instead.
|
||||
$now = new DateTimeImmutable('2026-01-15 12:00:00');
|
||||
$this->assertTrue(WorkflowRunner::isOverdue(new DateTimeImmutable('2026-01-15 06:00:00'), $now));
|
||||
}
|
||||
|
||||
public function testNoFiltersMatchesAnyCard(): void {
|
||||
@@ -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