Compare commits
89
Commits
8a31c42578
..
main
No files matched your search
@@ -0,0 +1,7 @@
|
||||
# Shell scripts must keep LF line endings, also on Windows checkouts with
|
||||
# core.autocrlf, or bash fails on the carriage returns.
|
||||
*.sh text eol=lf
|
||||
|
||||
# The Whisper word list is generated (npm run export:voice-vocabulary) and
|
||||
# copied into the image; keep LF so the file stays byte-identical everywhere.
|
||||
ApiCore-Whisper/vocabulary.txt text eol=lf
|
||||
@@ -0,0 +1,112 @@
|
||||
name: Backend E2E
|
||||
|
||||
# Fuehrt `npm run test:e2e` (Jest, maxWorkers 4, siehe test/jest-e2e.json)
|
||||
# gegen einen frischen Postgres-Service-Container aus. Das Backend-Image
|
||||
# (backend-image.yml) fuehrt nur Lint, Typecheck und Unit-Tests aus, weil der
|
||||
# Docker-Build keine Datenbank hat; diese Pipeline schliesst die Luecke.
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- "ApiCore-Backend/**"
|
||||
- ".gitea/workflows/backend-e2e.yml"
|
||||
workflow_dispatch:
|
||||
|
||||
# Ein neuer Push auf denselben Ref ersetzt den laufenden Lauf.
|
||||
concurrency:
|
||||
group: backend-e2e-${{ gitea.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
e2e:
|
||||
runs-on: docker-builder
|
||||
timeout-minutes: 30
|
||||
# Gitea act_runner unterstuetzt `services:`. Annahme (beim ersten Lauf
|
||||
# pruefen): der Job-Container teilt das Netz der Services und erreicht
|
||||
# Postgres unter dem Service-Namen `postgres`. Laeuft der Runner
|
||||
# stattdessen im Host-Modus, ist der Port auf localhost veroeffentlicht;
|
||||
# der Schritt "Datenbank-Host ermitteln" probiert beide Wege.
|
||||
services:
|
||||
postgres:
|
||||
# Gleiche Major-Version wie Produktion (deploy/k8s/base/postgres).
|
||||
# Per Digest gepinnt (Index-Digest von 18.6-alpine, nachgeschlagen
|
||||
# 2026-10-16); die k8s-Manifeste pinnen Postgres bisher nur per Tag.
|
||||
image: postgres:18.6-alpine@sha256:77f585114c32fbca283dc835b0596f4e52b51b4c6662d7810b2f4084f60a1873
|
||||
env:
|
||||
# Wegwerf-Datenbank im Service-Container, nur im Job-Netz erreichbar
|
||||
# und nach dem Lauf verworfen: kein echtes Secret.
|
||||
POSTGRES_USER: apicore
|
||||
POSTGRES_PASSWORD: apicore-ci-only
|
||||
POSTGRES_DB: apicore_test
|
||||
ports:
|
||||
- 5432:5432
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U apicore -d apicore_test"
|
||||
--health-interval 5s
|
||||
--health-timeout 5s
|
||||
--health-retries 20
|
||||
env:
|
||||
NODE_ENV: test
|
||||
# Das Wetter-e2e ruft die echte Open-Meteo-API; in CI ueberspringen.
|
||||
SKIP_EXTERNAL: "1"
|
||||
JWT_ACCESS_EXPIRES_IN: 15m
|
||||
JWT_REFRESH_EXPIRES_IN: 7d
|
||||
PORT: "3001"
|
||||
FRONTEND_ORIGIN: http://localhost:3000
|
||||
DOCUMENTS_STORAGE_PATH: ./test-uploads
|
||||
defaults:
|
||||
run:
|
||||
working-directory: ApiCore-Backend
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- name: Node einrichten
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: 22
|
||||
|
||||
- name: Datenbank-Host ermitteln und Testumgebung erzeugen
|
||||
# jest-e2e.json laedt .env.test per dotenv, das vorhandene Variablen
|
||||
# nicht ueberschreibt: alles kommt aus der Job-Umgebung, .env.test
|
||||
# existiert in CI nicht (gitignored). Die JWT-Secrets sind frisch
|
||||
# erzeugte Wegwerfwerte (mind. 32 Zeichen, voneinander verschieden),
|
||||
# nie echte Secrets.
|
||||
run: |
|
||||
set -eu
|
||||
host=""
|
||||
for candidate in postgres localhost; do
|
||||
if node -e "const s=require('net').connect(5432,process.argv[1]);s.on('connect',()=>process.exit(0));s.on('error',()=>process.exit(1));setTimeout(()=>process.exit(1),3000)" "$candidate"; then
|
||||
host="$candidate"
|
||||
break
|
||||
fi
|
||||
done
|
||||
if [ -z "$host" ]; then
|
||||
echo "Postgres weder unter 'postgres' noch unter 'localhost' erreichbar" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Postgres-Host: $host"
|
||||
access="$(openssl rand -hex 32)"
|
||||
refresh="$(openssl rand -hex 32)"
|
||||
echo "::add-mask::$access"
|
||||
echo "::add-mask::$refresh"
|
||||
{
|
||||
echo "DATABASE_URL=postgresql://apicore:apicore-ci-only@${host}:5432/apicore_test?schema=public"
|
||||
echo "JWT_ACCESS_SECRET=$access"
|
||||
echo "JWT_REFRESH_SECRET=$refresh"
|
||||
} >> "$GITEA_ENV"
|
||||
|
||||
- name: Abhaengigkeiten installieren
|
||||
run: npm ci
|
||||
|
||||
- name: Prisma-Client erzeugen
|
||||
run: npx prisma generate
|
||||
|
||||
- name: Migrationen anwenden
|
||||
# Die Rollen (z. B. BEEKEEPER) kommen aus den Migrationen, ein Seed
|
||||
# ist fuer die e2e-Tests nicht noetig.
|
||||
run: npx prisma migrate deploy
|
||||
|
||||
- name: E2E-Tests
|
||||
# Auf dem geteilten Runner brauchten App-Start plus bcrypt-Logins in
|
||||
# beforeAll mehr als die lokalen 20 s (Laeufe 826, 836); hier 60 s.
|
||||
run: npm run test:e2e -- --ci --testTimeout=60000
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
REGISTRY_PUSH: gitea:80
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- name: Image-Namen in Kleinbuchstaben ermitteln
|
||||
# OCI-Registries erlauben nur Kleinbuchstaben im Repository-Pfad;
|
||||
@@ -31,7 +31,7 @@ jobs:
|
||||
run: echo "name=$(echo '${{ gitea.repository_owner }}/apicore-backend' | tr '[:upper:]' '[:lower:]')" >> "$GITEA_OUTPUT"
|
||||
|
||||
- name: Docker Buildx einrichten
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
|
||||
with:
|
||||
# REGISTRY_PUSH ist Klartext-HTTP (Gitea-Service intern ohne TLS)
|
||||
# statt HTTPS — BuildKit lehnt das ohne diese Freigabe ab.
|
||||
@@ -40,7 +40,7 @@ jobs:
|
||||
http = true
|
||||
|
||||
- name: Bei der Gitea-Container-Registry anmelden
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY_PUSH }}
|
||||
username: ${{ gitea.actor }}
|
||||
@@ -50,7 +50,7 @@ jobs:
|
||||
|
||||
- name: Metadaten (Tags/Labels) ermitteln
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY_PUSH }}/${{ steps.image.outputs.name }}
|
||||
tags: |
|
||||
@@ -58,7 +58,7 @@ jobs:
|
||||
type=semver,pattern={{version}}
|
||||
|
||||
- name: Image bauen und pushen
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
|
||||
with:
|
||||
context: ./ApiCore-Backend
|
||||
push: true
|
||||
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
REGISTRY_PUSH: gitea:80
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- name: Image-Namen in Kleinbuchstaben ermitteln
|
||||
# OCI-Registries erlauben nur Kleinbuchstaben im Repository-Pfad;
|
||||
@@ -31,7 +31,7 @@ jobs:
|
||||
run: echo "name=$(echo '${{ gitea.repository_owner }}/apicore-frontend' | tr '[:upper:]' '[:lower:]')" >> "$GITEA_OUTPUT"
|
||||
|
||||
- name: Docker Buildx einrichten
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
|
||||
with:
|
||||
# REGISTRY_PUSH ist Klartext-HTTP (Gitea-Service intern ohne TLS)
|
||||
# statt HTTPS — BuildKit lehnt das ohne diese Freigabe ab.
|
||||
@@ -40,7 +40,7 @@ jobs:
|
||||
http = true
|
||||
|
||||
- name: Bei der Gitea-Container-Registry anmelden
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY_PUSH }}
|
||||
username: ${{ gitea.actor }}
|
||||
@@ -50,7 +50,7 @@ jobs:
|
||||
|
||||
- name: Metadaten (Tags/Labels) ermitteln
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY_PUSH }}/${{ steps.image.outputs.name }}
|
||||
tags: |
|
||||
@@ -58,7 +58,7 @@ jobs:
|
||||
type=semver,pattern={{version}}
|
||||
|
||||
- name: Image bauen und pushen
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
|
||||
with:
|
||||
context: ./ApiCore-Frontend
|
||||
push: true
|
||||
|
||||
@@ -32,10 +32,10 @@ jobs:
|
||||
YQ_SHA256: c5f056448f973ae7d39b5401949648a78f2dc1947d6a8eb65be60d5c504b9385
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- name: Node einrichten
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: 22
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
name: Whisper Image
|
||||
|
||||
# Nur bei Aenderungen am Abschreib-Image (Spec T7 11.1): das Image ist rund
|
||||
# 1,2 GB gross (Modell + Python-Abhaengigkeiten) und aendert sich selten.
|
||||
# Tag sha-<commit>; das Overlay setzt danach den Digest.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ['ApiCore-Whisper/**', '.gitea/workflows/whisper-image.yml']
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
runs-on: docker-builder
|
||||
env:
|
||||
# Nur fuer Doku/OCI-Labels, siehe REGISTRY_PUSH fuer den eigentlichen Push.
|
||||
REGISTRY: git.encry.de
|
||||
# Cluster-interner Service-Name statt git.encry.de: Registry-Blob-
|
||||
# Uploads (PUT) vertragen sich nicht mit dem Cloudflare-Proxy vor
|
||||
# git.encry.de ("413 Payload Too Large" unabhaengig von der Groesse).
|
||||
# Der Runner-Pod erreicht den Gitea-Service direkt ueber Kubernetes-DNS.
|
||||
# Push und Pull landen im selben Registry-Pfad (Owner/Repo:Tag), der
|
||||
# Hostname ist nur die Verbindung, daher bleibt der Pull in den
|
||||
# k8s-Manifesten unveraendert ueber git.encry.de.
|
||||
REGISTRY_PUSH: gitea:80
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- name: Image-Namen in Kleinbuchstaben ermitteln
|
||||
# OCI-Registries erlauben nur Kleinbuchstaben im Repository-Pfad;
|
||||
# der Gitea-Owner-Name behaelt Gross-/Kleinschreibung bei.
|
||||
id: image
|
||||
run: echo "name=$(echo '${{ gitea.repository_owner }}/apicore-whisper' | tr '[:upper:]' '[:lower:]')" >> "$GITEA_OUTPUT"
|
||||
|
||||
- name: Docker Buildx einrichten
|
||||
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
|
||||
with:
|
||||
# REGISTRY_PUSH ist Klartext-HTTP (Gitea-Service intern ohne TLS)
|
||||
# statt HTTPS — BuildKit lehnt das ohne diese Freigabe ab.
|
||||
config-inline: |
|
||||
[registry."gitea:80"]
|
||||
http = true
|
||||
|
||||
- name: Bei der Gitea-Container-Registry anmelden
|
||||
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY_PUSH }}
|
||||
username: ${{ gitea.actor }}
|
||||
# GITEA_TOKEN hat kein Package-Write-Recht — separates Personal
|
||||
# Access Token (Scope "package") als Secret REGISTRY_TOKEN anlegen.
|
||||
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||
|
||||
- name: Metadaten (Tags/Labels) ermitteln
|
||||
id: meta
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY_PUSH }}/${{ steps.image.outputs.name }}
|
||||
tags: |
|
||||
type=sha,format=short
|
||||
|
||||
- name: Image bauen und pushen
|
||||
uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
|
||||
with:
|
||||
context: ./ApiCore-Whisper
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha,scope=apicore-whisper
|
||||
cache-to: type=gha,scope=apicore-whisper,mode=max
|
||||
|
||||
- name: Schwachstellen-Scan (nur wenn trivy im Runner vorhanden ist)
|
||||
# Hinweisend (exit-code 0): die Ausgabe gehoert ins Runbook, ein Fund
|
||||
# blockiert den Push nicht, weil das Image dann schon in der Registry
|
||||
# liegt. Der Build selbst ist die harte Sperre (Hashes, Modell-SHA,
|
||||
# pytest in der Test-Stufe).
|
||||
run: |
|
||||
if command -v trivy >/dev/null 2>&1; then
|
||||
first_tag="$(echo '${{ steps.meta.outputs.tags }}' | head -n1)"
|
||||
trivy image --insecure --severity HIGH,CRITICAL --exit-code 0 "$first_tag"
|
||||
else
|
||||
echo "trivy ist im Runner nicht installiert, Scan uebersprungen"
|
||||
fi
|
||||
@@ -0,0 +1,9 @@
|
||||
# Root-level artefacts only; each project has its own .gitignore.
|
||||
|
||||
# Tool caches created when tests or scripts run from the repo root.
|
||||
/node_modules/
|
||||
|
||||
# Working notes of the SDD orchestration (ledgers, briefs, review reports)
|
||||
# and design mockups/screenshots (~90 MB). Decisions that matter are in
|
||||
# ARCHITECTURE.md, the specs/plans under docs/ and the Gitea issues.
|
||||
/.superpowers/
|
||||
+469
-18
@@ -23,6 +23,9 @@ Ein NestJS-Modul pro fachlichem Bereich, Reihenfolge entspricht Baureihenfolge i
|
||||
| `ExtractionsModule` | Schleuderungen | Harvests |
|
||||
| `HoneyBatchesModule` | Honigchargen, Honigmessungen | Extractions |
|
||||
| `StorageModule` | Lagerbehälter, einfache Lagerverwaltung (StockItem/StockMovement) | HoneyBatches |
|
||||
| `VeterinaryMedicinesModule` | Tierarzneimittel-Katalog, Packungen, Bewegungsbuch (T6, Abschnitt 12.2); exportiert `VeterinaryMedicinesService` und `VeterinaryMedicineLotsService`; die Behandlung bucht direkt über ihr `tx` und importiert das Modul nicht (12.2) | – |
|
||||
| `ComplianceModule` | Compliance-Einstellungen, Bestandsbild und Behördenanzeigen (T6, Abschnitt 12.8); `restricted-zone.ts` für den Sperrbezirk (12.7); ohne Provider an `PermissionResolverService` | – |
|
||||
| `ApiaryRestrictionsModule` | Sperrbezirke je Stand (T6, Abschnitt 12.7); von `ColoniesModule` importiert | – |
|
||||
| `DashboardModule` | Aggregations-Endpunkte | alle o.g. |
|
||||
| `SearchModule` | globale Suche, Filter-Bausteine | alle o.g. |
|
||||
| `ExportModule` | CSV/JSON/PDF-Export | alle o.g. |
|
||||
@@ -73,7 +76,9 @@ Zentrale Schnellaktion "+ Neu" (Abschnitt 22): permanent sichtbarer Floating-But
|
||||
|
||||
**Offline-Seiten:** Ohne Netz zeigen `/offline` (Start: geladene Stände), `/offline/apiary?id=…` und `/offline/colony?id=…` die Daten aus den Offline-Paketen (IndexedDB). QR- und NFC-Deep-Links (`/apiaries/<id>`, `/colonies/<id>`) weicht der Service Worker ohne Netz auf diese Seiten aus; der Weg zurück („Mit Netz öffnen“) übernimmt `from` nur bei gleicher Herkunft (same-origin). Formulare lesen Völker und Königinnen aus dem Paket, wenn die API nicht antwortet (`withPackFallback`, `networkMode: "always"`).
|
||||
|
||||
**API-Client und Service Worker.** `apiFetch` und `apiFetchFormData` nehmen die Option `refreshOn401: false`: Ein 401 wird dann weder erneuert noch wiederholt, die deutsche Meldung des Servers kommt unverändert an. Alle Nachweis-Aufrufe (Step-up, Abschnitt 11.13) setzen sie (Annahme 56). Der Service Worker legt `/api/v1/profile/telegram`, `/api/v1/profile/notification-settings` und `/api/v1/system` nie im Cache ab (`NEVER_CACHED_API_PATHS` in `public/sw-routes.js`; eine Änderung hebt `SW_ROUTES_VERSION` in `public/sw.js`).
|
||||
**Beute offline (Abschnitt 13.1):** Das Paket (`offline-pack`) trägt optional `hives` (Aufbau je Volk) und `hiveCatalog` (aktive Systeme plus die von den Aufbauten genutzten); ein älteres Paket ohne diese Felder sagt „unbekannt“, nicht „kein Aufbau“ (`hiveFromPacks`, `lib/hive/pack.ts`). Änderungen ohne Netz landen im IndexedDB-Speicher `pending-hive-changes` (DB-Version 5, `queueHiveChange`). `drainTimeline` (`lib/offline/sync.ts`) sendet diese Einträge und die Durchsichten, die eine `hiveChange` tragen, gemeinsam nach `queuedAt`, nacheinander. Netzfehler und 5xx stoppen den Lauf; jede andere Ablehnung (`HIVE_CONFLICT`, 403, 400) wird am Eintrag gespeichert, der Eintrag bleibt in der Warteschlange und hält die späteren Einträge desselben Volks zurück, andere Völker laufen weiter. **Überholschutz:** Solange für ein Volk eine Beute-Änderung wartet (auch eine abgelehnte), reiht `useHiveMutation` jede neue Kartenänderung hinter sie ein, statt online zu senden (`hasQueuedHiveChange`). Die Karte zeigt die wartenden Operationen auf dem geladenen Stand; eine abgelehnte Änderung zeigt `HivePendingNote` als Hinweis mit Weg in die Warteschlange (Annahme 102).
|
||||
|
||||
**API-Client und Service Worker.** `apiFetch` und `apiFetchFormData` nehmen die Option `refreshOn401: false`: Ein 401 wird dann weder erneuert noch wiederholt, die deutsche Meldung des Servers kommt unverändert an. Alle Nachweis-Aufrufe (Step-up, Abschnitt 11.13) setzen sie (Annahme 56). Der Service Worker legt `/api/v1/profile/telegram`, `/api/v1/profile/notification-settings` und `/api/v1/system` nie im Cache ab (`NEVER_CACHED_API_PATHS` in `public/sw-routes.js`; eine Änderung hebt `SW_ROUTES_VERSION` in `public/sw.js`, aktuell der Hash `215afb9f84e9`; ein Spec prüft, dass die Version zum Inhalt von `sw-routes.js` passt, jede Änderung an der Datei braucht also eine neue Version). Seit T6 kommen dazu: `/api/v1/compliance` (Prüfbereitschaft, Anzeigen-Einstellungen), `authority-notices`, `apiary-restrictions`, `apiaries/:id/restrictions`, `veterinary-medicines`, `veterinary-medicine-lots`, die Etikett-Prüfung und der Druck (`label-templates/check`, `label-templates/:id/check…`, `label-templates/:id/print…`; sie tragen die Anschrift des Lebensmittelunternehmers), das Einzeldokument `documents/:id` (die Art steht nicht im Pfad) und die Dokumentlisten der drei eingeschränkten Arten `MEDICINE_LOT`, `AUTHORITY_NOTICE` und `APIARY_RESTRICTION` (die Art steht in der Query `/documents?entityType=…`, daher prüft `isCacheableApiUrl` die URL samt Query; Listen der Durchsicht-Fotos und `documents/:id/download` bleiben offline verfügbar, das Präfix `/api/v1/documents` wird nicht als Ganzes gesperrt). **Der globale Header `Cache-Control: no-store` des Backends ist bewusst kein Signal für den Worker:** Jede API-Antwort trägt ihn (Abschnitt 9, `noStoreMiddleware`), ein Header-Check würde das gesamte Offline-Verhalten abschalten. `isKeepableApiAnswer` prüft nur Erfolg und JSON; ob etwas behalten wird, entscheidet allein der Pfad (Annahme 87). Ebenfalls nie gespeichert wird `/api/v1/colonies/:id/hive` (`/\/api\/v1\/colonies\/[^/]+\/hive\/?$/i`): das Paket antwortet dort, eine alte Kopie würde einen neueren Stand verdecken. `…/hive/changes` und der Katalog (`/hive-systems`) bleiben cachebar.
|
||||
|
||||
**Stand-Seite und Standrunde:** `apiaries/[id]` zeigt die lebenden Völker mit Ampel und „Runde starten“; nach dem Speichern führt „Weiter mit …“ zum nächsten Volk. Der Rundenzustand liegt je Benutzer lokal und wird beim Abmelden gelöscht.
|
||||
|
||||
@@ -119,7 +124,7 @@ Fachliche Annahmen, getroffen weil das Lastenheft an der Stelle keine eindeutige
|
||||
4. **API-Client-Rolle im MVP**: kein vollwertiger OAuth2/Client-Credentials-Server. Ein API-Client ist ein `User` mit Rolle `API_CLIENT` und einem langlebigen Service-Refresh-Token; vollwertiges Scopes-/Client-Management ist SOLL/KANN.
|
||||
5. **Backup-fähige Struktur**: reproduzierbare Prisma-Migrationen (kein manuelles Schema-Drift), anwendungsseitiges Backup (`BackupModule`, Abschnitt 8) und der CronJob `apicore-db-backup` mit `pg_dump` (Abschnitt 7), `/health`-Endpoint für Betriebsüberwachung.
|
||||
6. **Deviations vom Leitentscheidungs-Rahmen**: bisher keine. Wird ergänzt, falls während der Umsetzung ein konkreter Grund für eine Abweichung von NestJS/Prisma/Next.js/Tailwind/shadcn/TanStack Query auftritt.
|
||||
7. **Dokumentenspeicher als lokales Volume (Modul 29)**: `DocumentsModule` speichert Uploads unterhalb von `DOCUMENTS_STORAGE_PATH` auf dem lokalen Dateisystem des Backend-Pods, keine Objektspeicher-Anbindung (S3-kompatibel o.ä.) im MVP/v1.x. Der Pfad ist über die ConfigMap austauschbar, wie in Abschnitt 27 des Lastenhefts vorgesehen. Wichtig für den Betrieb: das aktuelle `deploy/k8s`-Deployment läuft mit `replicas: 2` ohne geteiltes Volume – für konsistente Uploads über beide Pods hinweg muss vor Produktivbetrieb mit Dokumenten-Feature ein `ReadWriteMany`-PVC (z.B. NFS- oder EFS-basiert) gemountet und `DOCUMENTS_STORAGE_PATH` darauf gesetzt werden, sonst sieht nur der Pod, der die Datei entgegengenommen hat, sie auch beim Download wieder.
|
||||
7. **Dokumentenspeicher als lokales Volume (Modul 29)**: `DocumentsModule` speichert Uploads unterhalb von `DOCUMENTS_STORAGE_PATH` auf dem lokalen Dateisystem des Backend-Pods, keine Objektspeicher-Anbindung (S3-kompatibel o.ä.) im MVP/v1.x. Der Pfad ist über die ConfigMap austauschbar, wie in Abschnitt 27 des Lastenhefts vorgesehen. Wichtig für den Betrieb: das aktuelle `deploy/k8s`-Deployment läuft mit `replicas: 2` ohne geteiltes Volume – für konsistente Uploads über beide Pods hinweg muss vor Produktivbetrieb mit Dokumenten-Feature ein `ReadWriteMany`-PVC (z.B. NFS- oder EFS-basiert) gemountet und `DOCUMENTS_STORAGE_PATH` darauf gesetzt werden, sonst sieht nur der Pod, der die Datei entgegengenommen hat, sie auch beim Download wieder. Seit T6 gilt für die Arten `MEDICINE_LOT`, `AUTHORITY_NOTICE` und `APIARY_RESTRICTION` zusätzlich zum Dokumentenrecht das Fachrecht des Datensatzes (Abschnitt 12.3, Annahmen 69 und 70).
|
||||
8. **Entra ID SSO ohne Auto-Provisioning**: `POST/GET /api/v1/auth/sso/*` implementiert Authorization Code + PKCE gegen Entra ID über `openid-client`. Der E-Mail-Claim aus dem ID-Token wird ausschließlich gegen einen bereits existierenden, aktiven `User`-Datensatz gematcht – es wird kein neuer Benutzer automatisch angelegt (Just-in-Time-Provisioning), passend zum bestehenden Modell, dass Admins Benutzer manuell anlegen. Eine erfolgreiche SSO-Anmeldung überspringt die App-eigene TOTP-MFA-Abfrage, da der Identity Provider bereits eine eigene (typischerweise stärkere) Authentifizierung durchgesetzt hat. Der PKCE-`code_verifier` wird kurzlebig (5 min) in einem httpOnly-`SameSite=Lax`-Cookie zwischengespeichert statt serverseitig, damit der Flow ohne Sticky-Sessions über mehrere Backend-Replicas hinweg funktioniert; der Rückweg vom Callback zum Frontend nutzt ein kurzlebiges (60 s), zweckgebundenes JWT statt des echten Access-Tokens in der Redirect-URL. `OIDC_ISSUER_URL`/`OIDC_CLIENT_ID`/`OIDC_CLIENT_SECRET`/`OIDC_REDIRECT_URI` kommen ausschließlich aus Environment-Variablen; fehlen sie, meldet `GET /api/v1/auth/sso/status` `enabled: false` und die Login-Seite blendet den "Mit Microsoft anmelden"-Button aus, statt beim Start zu scheitern.
|
||||
9. **M365-Kalender-Synchronisation als einseitiger, asynchroner Push**: Abschnitt 4.25 verlangt nur einen internen Betriebskalender, keine externe Anbindung – diese Funktion ist eine reine Erweiterung ohne Lastenheft-Vorgabe. Umgesetzt als `CalendarSyncModule` (`ApiCore-Backend/src/calendar-sync/`): App-only Graph-API-Zugriff per Client-Credentials-Flow (`GraphClientService`) statt delegierter Anmeldung, da die Synchronisation unbeaufsichtigt im Hintergrund laufen muss und nicht an eine interaktive Benutzersitzung gebunden sein darf. Nutzt bewusst dieselbe Entra-App-Registrierung wie das SSO-Login (`OIDC_ISSUER_URL`/`OIDC_CLIENT_ID`/`OIDC_CLIENT_SECRET`, ausschließlich Env-Variablen) statt einer zweiten, separaten App-Registrierung – ein Enterprise-App-Objekt im Tenant genügt, sofern es zusätzlich zu den delegierten Login-Scopes auch die Application-Permission „Calendars.ReadWrite“ (Admin-Consent) erhält; die Tenant-ID wird dafür aus dem Pfad von `OIDC_ISSUER_URL` abgeleitet, statt eine weitere Konfigurationsvariable zu benötigen. Die Übertragung ist bewusst nur einseitig (ApiCore → M365-Gruppenkalender, adressiert über `groupId`); Änderungen, die direkt im M365-Kalender vorgenommen werden, fließen nicht zurück. Statt eines synchronen Push im Request-Pfad nutzt `CalendarSyncOutboxEntry` ein Outbox-Muster, das die Worker-Schleife `calendar-outbox` abarbeitet (alle 60 s und auf `pg_notify('calendar_sync', '')`, siehe Abschnitt 10): Graph-API-Aufrufe sind zu langsam/fehleranfällig (Token-Refresh, Drosselung, transiente 5xx), um eine Durchsicht-/Aufgaben-Erstellung darauf warten zu lassen; fehlgeschlagene Versuche werden bis zu 5-mal wiederholt, danach bleibt der Eintrag `FAILED` bis zu einem manuellen "Jetzt synchronisieren" oder einer erneuten Änderung des Quelldatensatzes. Die Outbox ist sicher bei mehreren Replicas: Jeder Eintrag wird vor der Arbeit per bedingtem Update (`claimedAt`) reserviert, ein Claim älter als 5 min gilt als verwaist und wird übernommen, Graph-Requests haben ein 30-s-Timeout. `revision` sorgt dafür, dass eine Änderung während des Syncs nicht verloren geht (Eintrag bleibt PENDING, dasselbe Event wird beim nächsten Lauf aktualisiert); ein Abbruch während des Syncs löscht das gerade geschriebene Event. Abmelden eines Eintrags aus dem Kalender geschieht durch erneutes Einreihen: Wird eine Quelle (z. B. eine Aufgabe, die erledigt oder storniert wird oder ihr Fälligkeitsdatum verliert, oder ein gelöschter Datensatz) erneut in die Kalender-Outbox eingereiht, findet der Worker in `buildEventInput` nichts mehr anzuzeigen. Hat der Eintrag eine `graphEventId`, löscht der Worker das Graph-Event (404/410 gelten als bereits gelöscht, jeder andere Fehler zählt als fehlgeschlagener Versuch) und setzt den Eintrag auf `SKIPPED` mit `graphEventId = null`. Die API ruft Graph dafür nie auf; die Einreihung selbst erfolgt in der Handler-Transaktion der Domain-Events (`calendar-sync.*`-Handler über `CalendarSyncService.enqueueIn(tx, …)`). Auch die Königin-Zuordnung (`QueenAssigned` → `calendar-sync.queen-assignment`) und die Wartezeit (`calendar-sync.withdrawal`, Abschnitt 11.8) laufen so; `CalendarSyncService.enqueue` und das Einreihen nach dem Commit gibt es nicht mehr, nur `enqueueIn`. Ein neues Graph-Event entsteht beim Aktualisieren nur, wenn das alte nicht mehr existiert (404/410); andere Fehler gelten als fehlgeschlagener Versuch. Jedes Anlegen schickt eine `transactionId` (aus Eintrag, Revision und ersetztem Event), damit Graph eine Wiederholung nach einem Timeout nicht doppelt anlegt; „Jetzt synchronisieren“ startet den Lauf im Hintergrund (202, `running` im Status) und setzt FAILED-Einträge auf PENDING zurück. `groupId` muss eine Entra-Objekt-ID (GUID) sein; `""` oder `null` löscht sie; sie wird in Graph-URLs kodiert. Fehler aus Prisma werden nur mit Name, Code und Modell geloggt (`src/common/loggable-error.ts`), nie mit Abfragewerten. **Offene Entscheidung (2026-10-12):** Laut Microsoft-Doku (`group-post-events`) unterstützt `POST /groups/{id}/events` keine Application-Permission, nur delegiertes `Group.ReadWrite.All`. Mit dem App-only-Token oben kann das Anlegen im Gruppenkalender deshalb in Produktion scheitern (nicht gegen einen echten Tenant geprüft). Auswege: Zielkalender auf ein Ressourcen- oder Benutzerpostfach umstellen (`/users/{upn}/calendar/events`, App-only erlaubt, per Application Access Policy begrenzt) oder delegierter Zugriff über ein Dienstkonto. Pro Quelltyp (Aufgabe/Durchsicht/Behandlung/Fütterung/Ernte/Königinnen-Zuordnung/Wartezeit) ist die Synchronisation einzeln über die GUI (Verwaltung > Automatisierung > Kalender-Sync) abschaltbar; Kalendereinträge werden als ganztägige Graph-Events (`isAllDay: true`) angelegt, um Zeitzonen-/Uhrzeit-Mehrdeutigkeiten zu vermeiden, da die zugrundeliegenden Fachdaten selbst keine Uhrzeit führen.
|
||||
10. **Wartezeit manuell statt aus Wirkstoff-Datenbank abgeleitet**: `Treatment.withdrawalPeriodDays` wird pro Behandlung von Hand eingetragen (laut Packungsbeilage des verwendeten Mittels), statt automatisch aus Produktname/Wirkstoff hergeleitet zu werden. Eine hartkodierte Zuordnung Produkt→Wartezeit wäre eine faktische, rechtlich relevante Behauptung über Tierarzneimittel-Zulassungen, die im Code weder aktuell gehalten noch verlässlich verifiziert werden kann; die Verantwortung für den korrekten Wert bleibt beim Imker. Die App warnt in der Ernte-Erfassung nur, wenn ein Wert hinterlegt wurde und dessen Fenster (`endDate ?? date` + `withdrawalPeriodDays`) noch nicht abgelaufen ist – bezogen auf das Erntedatum (`GET /treatments/withdrawal-status?colonyIds=…&at=JJJJ-MM-TT`, ohne `at` gilt jetzt; Behandlungen, die erst nach diesem Datum beginnen, zählen nicht) – sie blockiert die Ernte nicht hart, da Ernte-Datensätze auch nachträglich für bereits erfolgte, reale Ernten erfasst werden. Warnungen sperren nie; einzige Ausnahme ist der Wassergehalt (Bestätigung, T4b). Ein einziger Fenster-Helfer (`src/treatments/withdrawal-window.ts`) bestimmt die Wartezeit; Warnung bei Ernte und Abfüllung, Meldung, Kalender und `getWithdrawalStatus` rechnen alle darüber, in Berliner Kalendertagen (Annahme 41). Die Kette beschreibt Abschnitt 11.8. Auch bei der Schleuderung warnt die App (`WITHDRAWAL_ACTIVE`, Abschnitt 11.12). Diese Warnung sieht jeder, der eine Schleuderung erfasst, auch ohne `treatments:read`: Lebensmittelsicherheit geht vor der Lese-Trennung.
|
||||
@@ -128,7 +133,7 @@ Fachliche Annahmen, getroffen weil das Lastenheft an der Stelle keine eindeutige
|
||||
12. **Automatische Hinweise sind Vorschläge, keine Aufgaben**: Automatisierungsregeln legen keine Aufgaben mehr an, sondern schreiben Vorschläge (`Suggestion`, Abschnitt 11.1). Erst „Übernehmen“ erzeugt die Aufgabe (Quelle „Aus Vorschlag“: `Task.sourceSuggestionId`, `sourceAutomationTrigger` = Regel); bestehende Automatik-Aufgaben bleiben Aufgaben. Je Regel und Objekt existiert höchstens eine offene Sache (Vorschlag oder Aufgabe). Geprüft wird unter der Volkssperre und der Zeilensperre der Regel (`SELECT … FOR UPDATE`, Reihenfolge Volk, dann Regel), die bis zum Commit gilt. Keine voreingestellte Frist (fachlich nicht belastbar ableitbar); optional `config.dueInDays` je Regel, gerechnet ab dem Berliner Tag. Ohne sie ist die Aufgabe beim Übernehmen heute fällig. Anker je Regel (ein verworfener Anker kommt nie wieder): `QUEENLESS_NO_EGGS` und `FEED_STATUS_CRITICAL` die Durchsicht-ID; `VARROA_THRESHOLD` die Mess-ID (nur rot, nicht im Behandlungseffekt, Abschnitt 11.4); `SWARM_MOOD_HIGH` die Kontroll-ID; `COLONY_HEALTH_CRITICAL` die Ereignis-ID; `STOCK_ITEM_LOW` die jüngste IN-Bewegung (sonst `none`); `RAW_MATERIAL_LOW` die jüngste Charge der Sorte (sonst `none`); `TREATMENT_FOLLOW_UP` und `FEEDING_FOLLOW_UP` die Behandlungs- bzw. Fütterungs-ID. Die Tagesrate des natürlichen Milbenfalls wird bei jeder Korrektur einer Eingangsgröße (Methode, Anzahl, Dauer) neu berechnet; ein mitgesendeter, vom gespeicherten abweichender Wert gilt als manuell gesetzt und gewinnt. Vorschlag, Meldung und der Audit-Eintrag der Regel (`AutomationRule CREATE`, mit `suggestionId`) entstehen in einer Transaktion: Scheitert ein Teil, entsteht nichts davon. Eine Meldung (Kategorie `SUGGESTION`, WARNUNG, bei `URGENT` KRITISCH) schreibt ein Vorschlag nur, wenn die Regel `config.notify` hat. Empfänger sind Inhaber von `tasks:read` und des Leserechts des Bereichs; der Text lautet „<Volkscode>: <Titel>“ (bewusste Abweichung vom Spec-Wortlaut, bei dem das Präfix der Regelcode war; ohne Volk nur der Titel). Der Kalendereintrag (`calendar-sync.task`) und der Webhook `task.created` (`webhooks.forward`) folgen erst aus `TaskCreated` beim Übernehmen; die Regel ruft `WebhooksService` nicht selbst auf. Eine neuere Durchsicht führt die offenen Vorschläge von `QUEENLESS_NO_EGGS` und `FEED_STATUS_CRITICAL` nach: Zeigt die tatsächlich jüngste Durchsicht des Volkes den Befund nicht mehr, wird der Vorschlag `RESOLVED` („Bedingung entfällt“); besteht der Befund, bleibt es bei einem Vorschlag mit aktuellem Beleg (der Anker bleibt der alte); eine rückdatierte Durchsicht ändert nichts, eine Korrektur schlägt nie neu vor, führt aber Offenes nach. Dasselbe gilt für `VARROA_THRESHOLD` bei `VarroaCorrected`. Eine abgeschaltete Regel lässt offene Vorschläge unberührt. Ausgewertet wird in den Handlern `automation.*` (`src/automation/automation.handlers.ts`) in der Zustell-Transaktion, bei Fehler mit Wiederholung; sie rufen `evaluate…In(tx, …)`, überspringen beendete Völker und prüfen unter der Volkssperre erneut. Nur `SWARM_MOOD_HIGH` und `STOCK_ITEM_LOW` laufen dauerhaft über `runAfterCommit` in eigener Transaktion (Annahme 11); sie rufen dieselben `evaluate…In`, werfen aber nie.
|
||||
14. **API-Schlüssel für Maschinen-Zugriffe**: Integrationen (Wabenhain-Shop, ERPNext) nutzen einen Schlüssel `ack_…` im `Authorization: Bearer`-Header statt eines Service-Kontos mit Passwort. Gespeichert wird nur der SHA-256-Hash (32 Zufallsbytes, daher kein langsamer KDF nötig); die Suche läuft über den Hash, Geheimnisse werden nie verglichen; der Klartext erscheint einmal bei der Erstellung. Ein Schlüssel ist kein Benutzer: `JwtAuthGuard` setzt `request.apiKey` statt `request.user`, `PermissionsGuard` lässt ihn nur auf Routen, deren Berechtigung in seinen Scopes steht – `@AnyAuthenticatedUser`-Routen nie. Erlaubte Scopes sind eine kurze Allowlist (`api-keys/api-key-scopes.ts`, `shop-sync:read`, `shop-sync:write`, `erp-inventory:read`); je angebundenem System ein eigener Schlüssel. Verwaltung mit `api-keys:manage`. Schlüssel sind bewusst nicht Teil des Backups: nach einer Wiederherstellung wird ein neuer Schlüssel ausgestellt. Lesen und Buchen sind getrennte API-Schlüssel (`shop-sync:read` bzw. `shop-sync:write`; `erp-inventory:read` zählt als Lesen, Buchungsrecht ist nur `shop-sync:write`, Liste `API_KEY_WRITE_SCOPES`): Ein neuer Schlüssel trägt genau ein Recht: einer mit mehreren Rechten wird beim Anlegen mit 400 abgelehnt (mit Lese- und Buchungsrecht eigens begründet); bereits ausgestellte Schlüssel mit mehreren Rechten bleiben gültig, die Oberfläche markiert sie und empfiehlt getrennte Schlüssel (neue anlegen, im angebundenen System – Wabenhain bzw. ERPNext – eintragen, alten widerrufen). Ein geleakter Lese-Schlüssel kann so nicht buchen, ein Buchungs-Schlüssel nicht lesen. Die Oberfläche bietet nur Rechte an, die der Anlegende selbst hat (alles andere lehnt der Server ohnehin ab). Ungültige Schlüssel werden je Client-Netz gezählt und nach 20 Fehlversuchen in 15 min gesperrt: Annahme 30.
|
||||
13. **Lebende vs. beendete Völker**: Nur `DISSOLVED`, `SOLD`, `DECEASED`, `MERGED` sperren Umsetzen/Teilen/Vereinigen/Königinzuweisung (`colonies/colony-status.ts`). `WEAK`, `CONSPICUOUS`, `QUEENLESS` bleiben bearbeitbar.
|
||||
15. **Bestandsbuch aus Behandlungen, nicht als eigenes Register**: Das Bestandsbuch nach Art. 108 VO (EU) 2019/6 wird aus `Treatment` erzeugt (`export/treatment-log.ts`); Lieferant, Erwerbsbeleg und verschreibender Tierarzt sind Freitextfelder der Behandlung, Name/Anschrift des Halters liegen in `SiteSettings`. Der Stand am Behandlungstag wird beim Anlegen als `Treatment.apiaryId` festgehalten (Umsetzen ändert ihn nicht nachträglich); für Altbestand wird er aus `ColonyApiaryHistory` abgeleitet und im PDF bei Unsicherheit markiert. Fehlende Pflichtangaben werden als „FEHLT“ gedruckt statt still weggelassen. Keine Wartezeit-Automatik (siehe 10).
|
||||
15. **Bestandsbuch aus Behandlungen, nicht als eigenes Register**: Das Bestandsbuch nach Art. 108 VO (EU) 2019/6 wird aus `Treatment` erzeugt (`export/treatment-log.ts`); Lieferant, Erwerbsbeleg und verschreibender Tierarzt sind Freitextfelder der Behandlung, Name/Anschrift des Halters liegen in `SiteSettings`. Der Stand am Behandlungstag wird beim Anlegen als `Treatment.apiaryId` festgehalten (Umsetzen ändert ihn nicht nachträglich); für Altbestand wird er aus `ColonyApiaryHistory` abgeleitet und im PDF bei Unsicherheit markiert. Fehlende Pflichtangaben werden als „FEHLT“ gedruckt statt still weggelassen. Keine Wartezeit-Automatik (siehe 10). Ergänzung T6: Wird eine Behandlung aus einer Packung erfasst, kommen Lieferant, Beleg, Ch.-B. und Tierarzt live aus der Packung und stehen nie als Kopie auf der Behandlung (Abschnitt 12.2).
|
||||
16. **Überwinterung als eigene Einträge statt Volksstatus**: `WinterCheck` (eindeutig je Volk, `winterYear`, Saison) hält Ein- und Auswinterung; ab Juli gehört ein Datum zum Winter desselben Jahres. Verlustursachen sind bewusst nur die COLOSS-Kategorien, keine Diagnosen. Die Übersicht gruppiert nach dem aktuellen Stand des Volkes. Ein Verlust ändert den Volksstatus nur auf ausdrücklichen Wunsch (`markColonyDeceased`). Neue Rechte vergibt die Migration an Nicht-System-Rollen, weil der Katalog-Sync nur System-Rollen berechtigt. Ein Verlust mit `markColonyDeceased` beendet auch die Königin-Zuordnung und schreibt `ColonyEnded` mit `via: WINTER_CHECK` (Abschnitt 11.7).
|
||||
|
||||
17. **Schutz gegen Rechteausweitung in der Benutzerverwaltung**: Wer Benutzer pflegt, darf nur Konten verwalten (Passwort/MFA zurücksetzen, E-Mail ändern, (de)aktivieren) und Rollen vergeben, deren Rechte er selbst vollständig hat (`UsersService.assertWithinCallerPermissions`), analog zur Rollenbearbeitung.
|
||||
@@ -136,7 +141,7 @@ Fachliche Annahmen, getroffen weil das Lastenheft an der Stelle keine eindeutige
|
||||
19. **Backups versiegelt**: AES-256-GCM über das gzip-Bundle, Schlüssel aus dem Schlüsselbund `BACKUP_ENCRYPTION_KEY` (+ `BACKUP_ENCRYPTION_KEY_PREVIOUS`, in Produktion Pflicht, siehe Annahme 22); Dateien von vor dem Schlüsselbund (Schlüssel per HKDF aus `JWT_ACCESS_SECRET`) bleiben lesbar, solange `JWT_ACCESS_SECRET` unverändert ist. Nur versiegelte Dateien stellen vollständig wieder her (und überschreiben). Eine unversiegelte (alte v2-)Datei darf nur die 27 Stamm- und Feldtabellen der Erlaubt-Liste `LEGACY_UNSEALED_TABLES` ergänzen – fehlende Zeilen anlegen, bestehende nie ändern. Alles andere (Benutzer, Rollen, Webhooks, Audit-Log, Kalender-Sync, Backup- und Website-Einstellungen, Nummernkreise, Bestands- und Chargenbewegungen, Shop-Anfragen, Rohstoffe/Herstellung, Dokumente, Benachrichtigungen samt Einstellungen, Vorschläge, Pflanzenentwicklungs-Meldungen und jede künftige Tabelle) kommt nur aus versiegelten Dateien; die Oberfläche listet übersprungene Tabellen auf; Import verlangt Passwort (+ TOTP). MFA- und Webhook-Secrets liegen mit eigenen Schlüsseln (`MFA_ENCRYPTION_KEY`, `WEBHOOK_ENCRYPTION_KEY`) verschlüsselt in der DB und damit auch im Backup – für eine Wiederherstellung in einem anderen Deployment dort dieselben Schlüssel setzen (oder als `*_PREVIOUS`), sonst müssen Webhook-Secrets und MFA neu eingerichtet werden.
|
||||
20. **Bearbeiten-Regel für `null`** (Grundsatz „alles bearbeitbar“): In jeder Bearbeiten-Anfrage bleibt ein weggelassenes Feld unverändert, `null` leert ein Feld, das leer sein darf, und `null` auf einem Pflichtfeld wird mit 400 abgelehnt (statt still ignoriert oder als 500). Umgesetzt über `PartialType(..., { skipNullProperties: false })` in den Update-DTOs, `@IsOptionalNotNull()` (`src/common/validation/is-optional-not-null.ts`) für weglassbare, aber nicht leerbare Felder und `optionalDate()` (`src/common/patch-values.ts`) für leerbare Datumsfelder; `update-dto-null-handling.spec.ts` hält den Vertrag je DTO fest. Das Frontend sendet geleerte optionale Felder über `emptyToNull` (`ApiCore-Frontend/src/lib/forms/empty-to-null.ts`) als `null`. Für Regel-Configs gilt dasselbe Muster: `null` löscht einen optionalen Schlüssel (z. B. `dueInDays`, `windowDays`, `minGrams`, einzelne GTS-Schwellen), ein Pflichtschlüssel (z. B. `queenMaxAgeYears`, `notify`, die Gruppe `swarmSeason`) lehnt `null` mit 400 ab (Abschnitt 11.2). Neu leerbar sind `Colony.occupiedFrames`, `VarroaMeasurement.sampleBees` und `Inspection.feedStatus`.
|
||||
21. **Lebende Völker**: „Lebend“ heißt jeder Status außer `DISSOLVED`, `SOLD`, `DECEASED`, `MERGED` – also auch `WEAK`, `CONSPICUOUS`, `QUEENLESS`. Backend-Abfragen filtern über `LIVING_COLONY_WHERE` (`colonies/colony-status.ts`), das Frontend über `isLivingColony` (`lib/colonies/status.ts`); `status = ACTIVE` steht nur dort, wo wirklich genau dieser Status gemeint ist.
|
||||
22. **Schlüsselbund**: Jeder Zweck hat einen eigenen Schlüssel, nie ein JWT-Secret: `MFA_ENCRYPTION_KEY` (TOTP-Secrets), `WEBHOOK_ENCRYPTION_KEY` (Webhook-Signaturschlüssel), `BACKUP_ENCRYPTION_KEY` (Backup-Dateien). In Produktion Pflicht: je ≥ 32 Zeichen, paarweise verschieden und verschieden von `JWT_ACCESS_SECRET`/`JWT_REFRESH_SECRET` – sonst startet kein Prozess (`src/runtime/startup-checks.ts`). Außerhalb der Produktion fällt ein fehlender Schlüssel je Zweck auf eine Ableitung aus `JWT_ACCESS_SECRET` zurück. Format `k<8 hex>:<iv>.<tag>.<data>` (Base64-Teile, AES-256-GCM, 128-Bit-Tag Pflicht); AES-Schlüssel = HKDF-SHA256(Secret, Salt `apicore-key-ring`, Info `apicore-<zweck>-v1`), Schlüssel-ID = `k` + die ersten 8 Hex-Zeichen von sha256(Schlüssel). Backups behalten Dateiformat v3 und ihre bisherige Ableitung (`keyId` 12 Hex), folgen aber denselben Ring-Regeln. Code: `src/common/crypto/key-ring.ts`. In Produktion lehnt der Start außerdem Platzhalterwerte ab (`change-me…`, ohne Groß-/Kleinschreibung) – für beide JWT-Secrets, die drei Schlüssel und ihre `*_PREVIOUS`, ein gesetztes `OIDC_CLIENT_SECRET` und das Passwort in `DATABASE_URL`; auch `*_PREVIOUS` muss von den JWT-Secrets verschieden sein. Außerhalb der Produktion meldet jeder Prozess einmal je Variable, dass ein aus `JWT_ACCESS_SECRET` abgeleiteter Entwicklungsschlüssel einspringt.
|
||||
22. **Schlüsselbund**: Jeder Zweck hat einen eigenen Schlüssel, nie ein JWT-Secret: `MFA_ENCRYPTION_KEY` (TOTP-Secrets), `WEBHOOK_ENCRYPTION_KEY` (Webhook-Signaturschlüssel), `BACKUP_ENCRYPTION_KEY` (Backup-Dateien), `VOICE_ENCRYPTION_KEY` (Sprachnotizen: Transkript, Vorschlag, Aufnahme; seit T7, AAD `capture:<id>:<art>`). In Produktion Pflicht: je ≥ 32 Zeichen, paarweise verschieden und verschieden von `JWT_ACCESS_SECRET`/`JWT_REFRESH_SECRET` – sonst startet kein Prozess (`src/runtime/startup-checks.ts`). Außerhalb der Produktion fällt ein fehlender Schlüssel je Zweck auf eine Ableitung aus `JWT_ACCESS_SECRET` zurück. Format `k<8 hex>:<iv>.<tag>.<data>` (Base64-Teile, AES-256-GCM, 128-Bit-Tag Pflicht); AES-Schlüssel = HKDF-SHA256(Secret, Salt `apicore-key-ring`, Info `apicore-<zweck>-v1`), Schlüssel-ID = `k` + die ersten 8 Hex-Zeichen von sha256(Schlüssel). Backups behalten Dateiformat v3 und ihre bisherige Ableitung (`keyId` 12 Hex), folgen aber denselben Ring-Regeln. Code: `src/common/crypto/key-ring.ts`. In Produktion lehnt der Start außerdem Platzhalterwerte ab (`change-me…`, ohne Groß-/Kleinschreibung) – für beide JWT-Secrets, die vier Schlüssel und ihre `*_PREVIOUS`, ein gesetztes `OIDC_CLIENT_SECRET` und das Passwort in `DATABASE_URL`; auch `*_PREVIOUS` muss von den JWT-Secrets verschieden sein. Außerhalb der Produktion meldet jeder Prozess einmal je Variable, dass ein aus `JWT_ACCESS_SECRET` abgeleiteter Entwicklungsschlüssel einspringt. Der Job `rekey` versiegelt beim Schlüsseltausch nur offene Sprachnotizen neu (bestätigte, verworfene und abgelaufene haben keinen Inhalt mehr). **Rollout:** Ein Image mit T7 startet in Produktion in keiner Rolle ohne `VOICE_ENCRYPTION_KEY` in `apicore-backend-secret`; vorher `deploy/k8s/scripts/ensure-secrets.sh` ausführen und den Schlüssel wie die anderen sichern.
|
||||
23. **Öffentliche Herkunftsseite ohne Standort**: Sie nennt nur `Apiary.publicLocationLabel` (je Stand, z. B. „Nordhessen“) und `SiteSettings.originCountry`. Name, Ort, Adresse und Koordinaten eines Stands werden nie öffentlich ausgeliefert (Diebstahlschutz). Ohne Label erscheint nur das Land. Eine Label-Änderung kann am Edge bis zu 1 h verzögert sichtbar werden.
|
||||
**Rotation über `*_PREVIOUS`:** alten Wert nach `<NAME>_PREVIOUS` (öffnet weiter, versiegelt nie), neuen `<NAME>` setzen, api und worker neu starten (sonst versiegeln sie weiter mit dem alten Schlüssel), Job `rekey` laufen lassen; danach muss `rekey --dry-run` bei `rekeyed`, `plaintextSealed`, `changedMeanwhile` und `failed` 0 melden, erst dann `*_PREVIOUS` entfernen. Backup-Dateien werden nicht umgeschlüsselt: `BACKUP_ENCRYPTION_KEY_PREVIOUS` bleibt gesetzt, solange ältere Dateien einspielbar sein sollen.
|
||||
**Altchiffrate sind nur lesbar** (nie geschrieben), **und nur, solange `JWT_ACCESS_SECRET` unverändert ist**: MFA-Secrets ohne Präfix und Webhook-Secrets mit `enc:v1:` (beide AES-Schlüssel sha256(`JWT_ACCESS_SECRET`)), Webhook-Secrets im Klartext, Backup-Dateien mit JWT-abgeleiteter `keyId`. Liest ein Prozess ein solches MFA- oder Webhook-Secret, warnt er einmal je Zweck „legacy ciphertext read – run the rekey job“ (ohne Werte). Reihenfolge darum: Schlüssel setzen → `rekey` → neues Backup ziehen → erst dann die JWT-Secrets rotieren (alle Sitzungen enden einmal; JWT-versiegelte Backup-Dateien sind danach nicht mehr einspielbar).
|
||||
@@ -156,7 +161,7 @@ Fachliche Annahmen, getroffen weil das Lastenheft an der Stelle keine eindeutige
|
||||
36. **Saison aus Pflanzenentwicklung**: Die Saison (Abschnitte `WINTERRUHE`, `FRUEHJAHR`, `SCHWARMZEIT`, `SOMMER`, `SPAETSOMMER`, `HERBST`) leitet sich aus der Pflanzenentwicklung ab (Abschnitt 11.3). Der Kalender-Rückfall (`PHENOLOGY.calendarFallback`, Standard `SALWEIDE` 20.03., `KIRSCHE` 15.04., `APFEL` 28.04., `HOLUNDER` 30.05., `LINDE` 20.06., `TRACHTENDE` 01.08., `HERBST` 15.09., `WINTER` 15.11.). Die Tage sind eine Annahme für Schwaben und per Regel anpassbar. Ohne gespeicherte Zeile für das laufende Jahr gilt der reine Kalenderzustand (Verhalten von T4a); dort steht vor `SALWEIDE` noch `WINTER` des Vorjahres. Seit T4b kommen gemeldete Phasen und die Grünlandtemperatursumme (GTS, Wetter) dazu; sie wirken über `SeasonService.statesFor`, die Aufrufer bleiben gleich. Der Zustand eines Stands steht in `ApiaryPhenology (apiaryId, year)`; der Job-Schritt `phenology` und jede Meldung oder Rücknahme berechnen ihn neu (`PhenologyStateService.recomputeIn`, unter Zeilensperre auf `Apiary`). Die Phase ist das Maximum aus eigener Meldung (Meldungen für alle Stände zählen für jeden Stand), GTS-Schätzung und Kalender. Sie läuft im Jahr nur vorwärts, außer nach einer Korrektur oder Rücknahme einer Meldung (`allowBackward`, gesetzt nur vom Handler bei `PhenologyCorrected`; eine neue Meldung schiebt die Phase nie zurück). GTS = Summe der positiven Tagesmittel ab 1. Januar bis gestern, Januar × 0,5, Februar × 0,75, ab März × 1 (nach DWD). Annahme: 200 °C gelten als `SALWEIDE` (Standardschwelle `PHENOLOGY.gtsThresholds`). Weitere Schwellen werden nie erfunden, sondern als Median der GTS am ersten Meldetag der letzten bis zu 3 Vorjahre kalibriert (Standard `KIRSCHE` und `APFEL`); ein einzelnes Vorjahr genügt und ist dann der Median. Ohne Vorjahresmeldung gilt für diese Phasen der Kalender. Fehlen mehr als `maxGapShare` (10 %) der Tage, steht „Wetterdaten lückenhaft“; ist der letzte Wettertag älter als 3 Tage, „Wetterdaten veraltet“; ohne Koordinaten „Keine Koordinaten“. In allen drei Fällen wird die GTS nicht benutzt und der Kalender entscheidet. Vor der ersten Phase des Jahres ist die gespeicherte Phase leer (Quelle Kalender), der Abschnitt `WINTERRUHE`. Ist die gespeicherte Zeile älter als 2 Tage (Job ausgefallen), gilt wieder der Kalenderzustand. `springSince` ist nicht gespeichert, sondern genähert: im Abschnitt `FRUEHJAHR` der Abschnittsbeginn, später im Jahr das Kalenderdatum von `SALWEIDE` (höchstens der Abschnittsbeginn). Weicht der GTS-Tag von `SALWEIDE` stark vom Kalender ab, verschiebt sich die Frist „Erste Durchsicht im Jahr“ um diese Differenz. Die Rückfall-Daten für Schwaben und die 200-°C-Schwelle sind Annahmen und noch nicht an regionalen Daten geprüft. Die Wetterquelle beschreibt Abschnitt 11.11. Meldungen und Rücknahmen stoßen die Neuberechnung über Ereignisse an, Saisonwechsel erscheinen nur in der Morgenübersicht (Annahme 47).
|
||||
37. **Alter der Königin**: Eine Königin gilt als gealtert, wenn aktuelles Jahr minus Schlupfjahr ≥ `queenMaxAgeYears` (Regel `SEASON_AUTOPILOT`, Standard 2). Die frühere getrennte Schwelle (3 im Dashboard, 2 im Ereignis) ist aufgehoben; `isQueenAged` (`src/season/queen-age.ts`) ist die einzige Stelle, ein Wächter-Test (`queen-age-threshold.spec.ts`) hält das fest. Das Dashboard-Fenster „alte Königinnen“ beginnt daher bei 2 Jahren und folgt der Regel. Der Wert 2 ist eine Annahme (Imkerpraxis).
|
||||
38. **Autopilot: Annahmen zu Ablauf und Alter**: Ein Vorschlag läuft `max(Fälligkeit, heute) + suggestionTtlDays` (Standard 30 Tage) ab, nicht schlicht Fälligkeit + 30: Sonst würde eine schon über 30 Tage überfällige Bedingung beim Anlegen abgelaufen, ihr Schlüssel freigegeben und sie täglich neu vorgeschlagen, ohne je sichtbar zu sein. Das Auffrischen behält `expiresAt`; besteht die Bedingung weiter, läuft der Vorschlag nach etwa 30 Tagen ab und kommt mit frischer Frist wieder. A3 beobachtet nur Behandlungen, die vor höchstens 60 Tagen endeten (`RECHECK_MAX_AGE_DAYS`); ältere Historie ohne spätere Messung erzeugt keinen Vorschlag. Beim Abgleich werden entfallene Vorschläge vor neuen Kandidaten aufgelöst (gleicher Endzustand, aber einen Abgleich früher, weil `proposeIn` Kandidaten bei offenem Vorschlag derselben Absicht verwirft).
|
||||
39. **Benachrichtigungen je Nutzer**: Jede Meldung gehört genau einem Empfänger (`Notification.userId` Pflicht). Rundmeldungen gibt es nicht mehr: `NotificationsService.recordForPermission` und `recordForUsers` schreiben beim Anlegen je einen Eintrag für jeden aktiven Nutzer mit aktiver Rolle, der alle nötigen Rechte hält (Fan-out mit Rechteprüfung beim Schreiben, bewusste Abweichung von der Rückgrat-Spec §4). Lesen und Gelesen-Markieren ist so pro Person, und wer das Recht nicht hat, sieht den Inhalt nie. Dasselbe Recht gilt beim Lesen: `requiredPermissions` (Vereinigung aus Empfänger- und Inhaltsrechten) muss der Nutzer zum Lesezeitpunkt vollständig halten, sonst ist die Zeile für ihn unsichtbar (`GET /notifications`, `POST /notifications/:id/read` → 404, `read-all` markiert nur sichtbare). `dedupeKey = "<Präfix>:<userId>"` verhindert Doppelungen (`createManyAndReturn` mit `skipDuplicates`); `link` ist ein relativer App-Pfad (`assertAppLink`). Die Migration hat vorhandene Rundmeldungen für alle aktiven Nutzer kopiert (gleiche Sichtbarkeit wie zuvor; ohne aktiven Nutzer entfallen sie). `Notification.userId` und `NotificationPreference.userId` hängen mit `ON DELETE CASCADE` am Benutzer (Benutzer werden produktiv nur deaktiviert, `RESTRICT` schützte nichts und blockierte Aufräumen). Wächter: `no-broadcast-notifications.spec.ts`.
|
||||
39. **Benachrichtigungen je Nutzer**: Jede Meldung gehört genau einem Empfänger (`Notification.userId` Pflicht). Rundmeldungen gibt es nicht mehr: `NotificationsService.recordForPermission` und `recordForUsers` schreiben beim Anlegen je einen Eintrag für jeden aktiven Nutzer mit aktiver Rolle, der alle nötigen Rechte hält (Fan-out mit Rechteprüfung beim Schreiben, bewusste Abweichung von der Rückgrat-Spec §4). Lesen und Gelesen-Markieren ist so pro Person, und wer das Recht nicht hat, sieht den Inhalt nie. Dasselbe Recht gilt beim Lesen: `requiredPermissions` (Vereinigung aus Empfänger- und Inhaltsrechten) muss der Nutzer zum Lesezeitpunkt vollständig halten, sonst ist die Zeile für ihn unsichtbar (`GET /notifications`, `POST /notifications/:id/read` → 404, `read-all` markiert nur sichtbare). `dedupeKey = "<Präfix>:<userId>"` verhindert Doppelungen (`createManyAndReturn` mit `skipDuplicates`); `link` ist ein relativer App-Pfad (`assertAppLink`). Die Migration hat vorhandene Rundmeldungen für alle aktiven Nutzer kopiert (gleiche Sichtbarkeit wie zuvor; ohne aktiven Nutzer entfallen sie). `Notification.userId` und `NotificationPreference.userId` hängen mit `ON DELETE CASCADE` am Benutzer (Benutzer werden produktiv nur deaktiviert, `RESTRICT` schützte nichts und blockierte Aufräumen). Wächter: `no-broadcast-notifications.spec.ts`. `NotificationsService` liest die Empfänger und schreibt die Meldungen in einer Transaktion und sperrt die Nutzerzeilen dabei mit `FOR KEY SHARE`; ein gleichzeitiges Löschen eines Empfängers wartet, statt einen Fremdschlüsselfehler (P2003) im Handler auszulösen.
|
||||
40. **Erinnerungen in der App und Morgenübersicht**: Siehe Abschnitt 11.9. In der App steuern die Morgenzeit (05:00–12:00), die Ruhezeit und die Umstellung Sommer-/Winterzeit nichts; die Übersicht entsteht immer um 04:30 mit dem Stand dieser Stunde. Sie wirken auf die Telegram-Zustellung (Annahme 49). Die Saison-Zeile der Übersicht nennt die Abschnittswechsel seit dem Zeitfenster der letzten Übersicht, nicht als Einzelmeldung (Annahme 47).
|
||||
41. **Berliner Kalendertage**: Tagesrechnung steckt in `src/common/dates.ts` (`berlinToday`, `berlinDayOf`, `dayToDate`, `addDays`, `daysBetween`; unmögliche Tage wie 30.02. werfen). Fachliche Tage sind Berliner Kalendertage, gespeichert als Mitternacht UTC dieses Tages: Varroa-Ampel, Behandlungs- und Wartezeitfenster, Erntetag, Fälligkeiten der Vorschläge, „heute“ im Job und im Autopilot. Für Werte um Mitternacht UTC ändert das nichts; ein Behandlungszeitpunkt am Abend (UTC) kann so auf den nächsten Berliner Tag fallen.
|
||||
42. **Wetterquelle Open-Meteo (Entscheidung des Inhabers)**: Die Pflanzenentwicklung nutzt die freie Open-Meteo-API (Forecast-Endpunkt für die letzten 90 Tage, Archiv für ältere Lücken). Die nicht-kommerziellen Bedingungen und das damit verbundene Lizenzrisiko hat der Inhaber bewusst übernommen. Es wird kein API-Schlüssel verwendet (`OPEN_METEO_API_KEY` bleibt leer). Die Quelle liegt hinter der Schnittstelle `WeatherHistorySource` (`src/weather/history`); ein Wechsel geht über `WEATHER_HISTORY_SOURCE` und einen neuen Adapter. Koordinaten werden auf 0,01° gerundet. URL und Schlüssel erscheinen nie in Logs oder Fehlermeldungen. Details: Abschnitt 11.11.
|
||||
@@ -167,7 +172,7 @@ Fachliche Annahmen, getroffen weil das Lastenheft an der Stelle keine eindeutige
|
||||
47. **Pflanzen-Meldungen, Neuberechnung und Saisonwechsel**: Rechte: `phenology:read` (Liste), `phenology:create` (Melden), `phenology:update` (Bearbeiten und Zurückziehen); `GET /phenology/state` braucht `apiaries:read` und enthält nie Koordinaten (Abschnitt 11.11). Das Datum muss ein echter Kalendertag sein und darf nicht nach dem Berliner Tag von heute liegen (400). Ein unbekannter Stand ergibt 404 (in der Transaktion geprüft, Stand vor Meldung in der Sperrreihenfolge); `apiaryId` leer (`""`) ergibt 400, `null` heißt „alle Stände“. Wer `phenology:update` hält, darf auch fremde Meldungen bearbeiten und zurückziehen (kleines Team, bewusst); eine zurückgezogene Meldung lässt sich nicht mehr bearbeiten (409), erneutes Zurückziehen ebenso (409). Eine Änderung ohne tatsächliche Abweichung schreibt weder Datensatz noch Audit-Eintrag noch Ereignis. `PhenologyReported` und `PhenologyCorrected` (auch beim Zurückziehen) entstehen in der Schreib-Transaktion. `PhenologyCorrected` trägt `previousApiaryId` (beim Zurückziehen gleich `apiaryId`): Eine Verschiebung von Stand A nach B berechnet nur A und B neu; ist eine Seite `null` (Meldung erweitert oder eingeengt), gilt „alle Stände“. Der Handler `phenology.recompute` rechnet für den späteren von Berliner Tag des Ereignisses (`occurredAt`) und heute, damit eine verzögerte Zustellung keinen älteren Tag (GTS-Stand, Abschnittsbeginn) zurückschreibt; bei einem oder zwei Ständen direkt, in Id-Reihenfolge. Gilt „alle Stände“, schreibt er je aktivem Stand ein internes Ereignis `PhenologyRecomputeRequested { apiaryId, allowBackward, day }` (kein Schlüssel), und `phenology.recompute-apiary` rechnet einen Stand je Zustellung (übersprungen, wenn er nicht mehr aktiv ist). So läuft eine Meldung für alle Stände nicht in einer einzigen Zustell-Transaktion. **Bewusste Abweichung von der Spec:** Saisonwechsel erscheinen nur in der Morgenübersicht (Abschnitt 11.9), nie als Einzelmeldung: Meldungen für alle Stände ergäben sonst Stände × Nutzer Meldungen. `SeasonPhaseChanged` bleibt für den Autopiloten.
|
||||
48. **Autopilot A4–A10: Annahmen**: A4 (Sommerbehandlung planen) und A8 (Umweiseln planen) sind `PLAN`-Vorschläge ohne gespeicherten Plan: Übernehmen legt genau eine Aufgabe an, heute fällig (Spec 8.2). Der gespeicherte Saisonzustand kennt nur den Beginn des aktuellen Abschnitts. Im Abschnitt `HERBST` ist der Beginn von `SPAETSOMMER` daher genähert: der Kalendertag von `TRACHTENDE` (`PHENOLOGY.calendarFallback`), höchstens der Beginn von `HERBST` (`lateSummerStart`). Wurde die Phase viel früher oder später gemeldet als der Kalender sagt, zählt eine Fütterung zwischen beiden Tagen für A5 falsch (nur A5 betrifft das). Der genaue Weg ist eine Spalte `lateSummerSince` an `ApiaryPhenology` (Migration, späteres Schema-Fenster; im Code als TODO vermerkt). A6 ohne Durchsicht zählt Fütterungen seit dem späteren von Anlagetag des Volkes und heute minus 60 Tage; A7 nutzt nur eine Durchsicht ab `springSince` des laufenden Jahres (sonst ab 1. Januar). „Gemeldet am TT.MM.“ im Grund von A4 steht nur, wenn `reportedOn` vorliegt (bei gespeicherten Zeilen nie), sonst „Tracht vorbei (gemeldet)“, bei Schätzung oder Kalender „(geschätzt)“ bzw. „(Kalender)“. `syncApiaryIn` gleicht alle Völker eines Stands in einer Transaktion ab (etwa 10 Abfragen je Volk); für sehr große Stände wäre eine Aufteilung nötig. Ein Wächter (`src/suggestions/suggesting-triggers.spec.ts`) verlangt für jeden vorschlagenden Trigger eine Textvorlage und für jeden im Quelltext gefundenen `reasonCode` einen Registereintrag; ein neuer Trigger fällt durch, bis er eine Vorlage hat oder bewusst ausgenommen wird.
|
||||
49. **Telegram-Zustellung: Zustellzeit, Zeitumstellung, Prüfung beim Senden**: Zeiten rechnen auf der Berliner Wanduhr (Europe/Berlin, `src/notifications/delivery-time.ts`). Verfügbar ab dem späteren von jetzt und der Kategorie-Zeit (`TASK_DUE`: eine Minute nach der Morgenzeit, `DIGEST`: die Morgenzeit, jeweils heute); liegt das Ergebnis in der Ruhezeit (Standard 21:00 bis 06:30, über Mitternacht, Ende ausgeschlossen; fehlende oder gleiche Grenzen = keine Ruhezeit), rückt es an deren Ende. Eine Uhrzeit, die im Herbst doppelt vorkommt (Doppelstunde 02:xx), gilt als das erste Vorkommen (Sommerzeit); eine Uhrzeit in der Frühjahrslücke (02:30 existiert nicht) als der Zeitpunkt eine Stunde später (03:30 Sommerzeit). Antworten des Bots (`templateCode`) umgehen Ruhezeit und Prüfungen. Beim Senden gilt der Stand dieses Moments, nicht der der Planung: Nutzer und Rolle aktiv, Telegram an, Verbindung, Kategorie, jedes Recht aus `requiredPermissions` (frisch gelesen, nicht aus dem 30-s-Cache) und Frische. `TASK_DUE` und `DIGEST` sind nur am selben Berliner Tag frisch, alle anderen höchstens 24 Stunden; eine `TASK_DUE`-Zustellung braucht die Aufgabe noch offen. Sonst `SKIPPED` mit Grund. Der Batch ist auf 120 s begrenzt; der Rest geht ohne Fehlversuch zurück. Abschnitt 11.13.
|
||||
50. **Sperrreihenfolge: Stand vor Volk**: Die Karte `LOCKABLE_TABLES` (`LOCK_ORDER`, `src/prisma/row-lock.ts`) gilt für jede Transaktion, die Zeilen mehrerer Tabellen sperrt (Tabellen in dieser Reihenfolge, innerhalb einer Tabelle Id aufsteigend), mit einer Ausnahme (Entscheidung zu Task 27): `Apiary` wird vor `Colony` gesperrt. Der Abgleich je Stand (`AutopilotService.syncApiaryIn`) sperrt die Standzeile, liest danach die Völker, sperrt alle in einer Anweisung (`lockRowsForUpdate`, Id aufsteigend) und erst dann Vorschläge und Regeln; der Handler `autopilot.colony-sync` sperrt die Völker eines Ereignisses ebenso in einer Anweisung. Kein Pfad sperrt ein Volk und danach einen Stand (die Neuberechnung der Pflanzenentwicklung sperrt nur den Stand); ein künftiger Pfad Volk → Stand würde mit dem Abgleich je Stand verklemmen. Die Karte im Code führt `Apiary` weiterhin weiter hinten (Stand dieses Dokuments): Die Ausnahme steht als Regel hier, nicht in der Karte.
|
||||
50. **Sperrreihenfolge: Stand vor Volk**: Die Karte `LOCKABLE_TABLES` (`LOCK_ORDER`, `src/prisma/row-lock.ts`) gilt für jede Transaktion, die Zeilen mehrerer Tabellen sperrt (Tabellen in dieser Reihenfolge, innerhalb einer Tabelle Id aufsteigend), `Apiary` steht seit T6 an erster Stelle der Karte, also vor `Colony` (Entscheidung zu Task 27, in T6 Task 1 in die Karte übernommen). Hinter `NotificationDelivery` stehen die T6-Tabellen `LabelTemplate`, `SiteSettings`, `VeterinaryMedicine`, `VeterinaryMedicineLot`, `ComplianceSettings`, `AuthorityNotice`, `ApiaryRestriction`, `ComplianceAcknowledgement` (Schlüssel jeweils `id`, `Product` stand schon in der Karte). Pfade, die Stand und Volk zusammen sperren, nehmen zuerst die Stände (aufsteigend), dann das Volk; `row-lock.spec.ts` hält die Reihenfolge und die Einmaligkeit jeder Tabelle fest. Der Abgleich je Stand (`AutopilotService.syncApiaryIn`) sperrt die Standzeile, liest danach die Völker, sperrt alle in einer Anweisung (`lockRowsForUpdate`, Id aufsteigend) und erst dann Vorschläge und Regeln; der Handler `autopilot.colony-sync` sperrt die Völker eines Ereignisses ebenso in einer Anweisung. Kein Pfad sperrt ein Volk und danach einen Stand (die Neuberechnung der Pflanzenentwicklung sperrt nur den Stand); ein künftiger Pfad Volk → Stand würde mit dem Abgleich je Stand verklemmen. Die Aufrufer (`ColoniesService.create/update/move/merge`, `ImportService`, `ApiariesService`, `ApiaryRestrictionsService`) sind umgebaut (Abschnitt 12.7); ein Umsetzen, das zwischen Lesen und Sperren den Stand wechselt, endet mit 409 „Der Stand wurde gerade geändert. Bitte neu laden.“ ohne automatischen Neuversuch (Abschnitt 12.1).
|
||||
51. **Telegram: fehlerhaftes Update wird übersprungen (Annahme der Umsetzung)**: Ein Update, dessen Verarbeitung scheitert, wird bis zu 5 Mal oder höchstens 10 Minuten wiederholt (Zähler und erste Fehlzeit je `update_id` im Speicher des Pods; `MAX_UPDATE_ATTEMPTS`, `MAX_UPDATE_RETRY_MS`). Danach überspringt es eine eigene Transaktion: Offset weiter, `lastError` = „Telegram-Nachricht übersprungen“, eine Warnung ohne IDs und Text im Log, der Rest des Batches läuft weiter. Ohne diese Grenze würde ein dauerhaft scheiternder Befehl alle späteren Befehle (etwa jedes `/start`) sperren. Kosten bei falscher Annahme: ein verlorenes `/start`, der Nutzer erzeugt den Link neu. Eine verlorene Lease zählt nie als Fehlversuch, Verbindungsfehler ebenso wenig; die Zähler werden nach jedem Batch bereinigt. Abschnitt 11.13.
|
||||
52. **Wassergehalt: Bestätigung gilt für den gemessenen Wert**: Die Bestätigung über der gesetzlichen Grenze (`acknowledgedWarnings: ['WATER_CONTENT_ABOVE_LEGAL']`) trägt zusätzlich `acknowledgedWaterContent` mit dem Wert aus der 409-Antwort. Sie gilt nur, wenn der unter der Sperre geprüfte Wert genau gleich ist; sonst folgt eine frische 409. Wer bestätigt hat, hat also diesen Wert gesehen, und eine zwischenzeitlich neue Messung entwertet die Bestätigung (Lebensmittelsicherheit; Kosten bei falscher Annahme: ein zusätzliches Feld). Streng größer als die Grenze löst die Bestätigung aus, genau 20,0 % warnt nur. Abschnitt 11.12.
|
||||
53. **Vorbelegungs-Hinweise: Speichern bleibt erlaubt**: Laden die Hinweise einer Vorbelegung (Warnungen, etwa die Wartezeit) nicht, sperrt die Oberfläche das Speichern nicht; eine dauerhafte Zeile weist darauf hin, das Backend prüft beim Speichern. Kosten bei falscher Annahme: Ein Nutzer speichert, ohne die Wartezeitwarnung gesehen zu haben; die Antwort des Speicherns trägt die Warnung trotzdem. Abschnitt 11.12.
|
||||
@@ -176,6 +181,66 @@ Fachliche Annahmen, getroffen weil das Lastenheft an der Stelle keine eindeutige
|
||||
56. **Step-up: ein 401 wird nie mit Refresh wiederholt**: Bei Aufrufen mit Nachweis (Telegram verbinden, Backup-Import, Passwort ändern, Konto deaktivieren, MFA bestätigen und abschalten) bedeutet ein 401 „Nachweis falsch“. Der Client erneuert dort das Token nicht und wiederholt nicht (`refreshOn401: false`), weil ein zweiter Versuch den Sperrzähler verdoppeln würde. Ist die Sitzung wirklich abgelaufen, erscheint statt Stille der deutsche Hinweis „Sitzung abgelaufen. Bitte die Seite neu laden und erneut anmelden.“ (der Client kennt den Ablauf des Tokens nicht und erneuert nicht vorab). Kosten bei falscher Annahme: Eine abgelaufene Sitzung zeigt bei einem Step-up einmal einen Fehler statt einer stillen Erneuerung. Abschnitt 11.13.
|
||||
57. **Abfüllung: Produktwechsel setzt Artikelwerte zurück**: Wechselt das Produkt, verwirft die Maske von Hand geänderte Glasgröße und MHD und nimmt die Werte des neuen Artikels; ein Datumswechsel lässt eigene Eingaben stehen. Sonst bliebe die Glasgröße eines anderen Artikels unbemerkt im Formular. Kosten bei falscher Annahme: Wer erst tippt und dann das Produkt wählt, muss neu eintragen. Abschnitt 11.12.
|
||||
58. **„Alle fehlgeschlagenen erneut versuchen“: die Zahl kann zu niedrig sein**: Die API liefert keine Gesamtzahl der `FAILED`-Zeilen, die Rückfrage nennt daher nur „Mindestens N“ (größerer Wert aus `failed24h` und den `FAILED`-Zeilen der Liste) und immer die Grenze „höchstens 100, neueste zuerst“. Kosten bei falscher Annahme: Es gehen mehr (bis 100) Nachrichten erneut hinaus als angezeigt. Abschnitt 10, System-Seite.
|
||||
59. **T6-Schema: Prüfungen in der Datenbank, Rechtswerte als Einstellung**: CHECK-Constraints sichern `VeterinaryMedicineLot.quantity > 0`, `VeterinaryMedicineMovement.quantity <> 0` und `(type = 'TREATMENT') = ("treatmentId" IS NOT NULL)`, `ApiaryRestriction.endsOn >= startsOn` sowie `LabelTemplate.minXHeightMm` zwischen 0,5 und 5. Katalog, Packung, Behandlung und Stand hängen mit `ON DELETE RESTRICT` aneinander. `AuthorityNotice.openKey` ist nullbar-eindeutig (höchstens ein offener Entwurf je Art und Jahr). Die Vorgabe `ComplianceSettings.netQuantityDigitRules` (bis 50 g: 2 mm, bis 200 g: 3 mm, bis 1000 g: 4 mm, darüber 6 mm) und `minXHeightMm` 1,2 mm sind Annahme – vom Inhaber zu prüfen; im Code stehen keine Rechtswerte. Abschnitt 12.1.
|
||||
60. **Tierarzneimittel: eigener Katalog und eigenes Bewegungsbuch**: Ergänzung zu Annahme 10. Mittel (`VeterinaryMedicine`), Packungen (`VeterinaryMedicineLot`) und Bewegungen (`VeterinaryMedicineMovement`) sind nicht `StockItem`/`BatchMovement`. Bewegungen werden nie geändert oder gelöscht, Fehler werden gegengebucht (es gibt keine Route dafür). Der Rest einer Packung ist `quantity` plus Summe der Bewegungen, auf Tausendstel gerundet, immer berechnet und nie gespeichert; ein negativer Rest ist erlaubt (die Behandlung hat stattgefunden) und erscheint in der Prüfbereitschaft. Der Katalog startet leer, der Seed legt nichts an. Kosten bei falscher Annahme: Wer einen Buchungsfehler erwartet zu löschen, muss gegenbuchen. Abschnitt 12.2.
|
||||
61. **Ein inaktives Mittel nimmt keinen neuen Bestand**: Eine Packung lässt sich weder zu einem inaktiven Mittel anlegen noch auf ein solches umhängen (400 „Das Mittel ist deaktiviert.“, `active` wird unter der Mittelsperre gelesen). Kosten bei falscher Annahme: Wer eine Lieferung eines stillgelegten Mittels buchen will, muss es erst wieder aktivieren.
|
||||
62. **Packung und Mittel müssen dieselbe Einheit haben**: Beim Anlegen und beim Umhängen einer Packung auf ein anderes Mittel gilt 400 „Die Einheit des Mittels passt nicht zur Packung.“; die Einheit eines Mittels ist nur änderbar, solange keine Packung existiert, das Mittel einer Packung nur, solange keine Bewegung existiert (jeweils 409).
|
||||
63. **Wiederherstellung ersetzt das Packungsbuch**: Eine versiegelte Datei überschreibt Mittel, Packungen und Bewegungen nach Id; sie führt das Buch nicht mit dem vorhandenen zusammen. Aus unversiegelten Dateien entsteht kein Packungsbezug einer Behandlung (Abschnitt 8). Kosten bei falscher Annahme: Buchungen, die nach der Sicherung entstanden sind, fehlen nach dem Einspielen und müssen nachgetragen werden.
|
||||
64. **Beim Wiederherstellen gewinnt der offene Entwurf im Zielsystem**: Hält dort ein Entwurf (`openKey`, etwa der vom Tagesjob angelegte TSK-Entwurf) den Schlüssel unter anderer Id, entfällt die Anzeige der Datei mit ihren Dokumenten; der Restore scheitert nicht am Unique-Constraint. Kosten bei falscher Annahme: Der Entwurf aus der Datei fehlt und muss neu erfasst werden (die Ids stehen in `summary.skippedNoticeIds`).
|
||||
65. **Etikett-Pflichtangaben prüft eine reine Funktion am aufgelösten Inhalt**: `checkLabel` (`src/label-templates/label-particulars.ts`) bewertet alle Text-Elemente mit eingesetzten Platzhaltern, normalisiert mit NFKC, Kleinschreibung und „alles außer Buchstaben und Ziffern wird zum Leerzeichen“. Ein Text, der nicht in sein Feld passt (gemessene Höhe größer als Feldhöhe plus 0,5 pt), zählt nicht und löst `TEXT_CLIPPED` aus. Nicht geprüft werden die „gleiches Sichtfeld“-Regel und die Nährwertdeklaration (für Honig befreit – Annahme, vom Inhaber zu prüfen). Das Datum auf dem Etikett und das erwartete MHD der Prüfung kommen beide aus `labelDayOf` (Berliner Kalendertag, unabhängig von der Prozess-Zeitzone; ein Quelltext-Wächter sichert das). Eine Zahl direkt vor der Menge („1,250 g“) gilt nicht als Treffer für 250 g; der Ziffern-Wächter gilt je Element, nie im verbundenen Text. Eine Anschrift wird auch erkannt, wenn sie auf mehrere Elemente verteilt ist (Annahme 75), weil eine unerkannte Anschrift den Druck sperrt. Abschnitt 12.4.
|
||||
66. **Füllmengen-Höhe: jede Nennung zählt**: `NET_QUANTITY_HEIGHT` ist erfüllt, wenn irgendeine Nennung der Füllmenge hoch genug ist (größte Versalhöhe aller Träger); eine zusätzliche kleine Nennung warnt nicht. Die Warnung sperrt nie. Kosten bei falscher Annahme: Eine große Nennung neben einer zu kleinen wird nicht bemängelt.
|
||||
67. **Verkehrsbezeichnung: „honig“ in einem beliebigen Wort genügt**: Für `LEGAL_NAME` reicht ein Wort mit „honig“ („Blütenhonig“, auch „Honigtau“); ob die Bezeichnung inhaltlich stimmt, prüft die Software nicht. Kosten bei falscher Annahme: Ein falsch benannter Honig sperrt den Druck nicht.
|
||||
68. **Losnummer mit „L“ am Anfang erfüllt die Präfix-Regel**: Beginnt die Losnummer schon mit „L“ („L-001“), stellt der Platzhalter `lotLine` kein weiteres „L“ voran und `LOT_PREFIX` warnt nicht. Die Warnung sperrt nie.
|
||||
69. **`compliance:manage` schließt `compliance:read` nicht ein**: Die Rechte sind getrennt; die Rollenvergabe koppelt sie (nur ADMIN und BEEKEEPER haben `manage`, und diese haben auch `read`). Ein Nutzer mit nur `manage` darf bei Dokumenten hochladen, aber die Liste nicht lesen (403). Kosten bei falscher Annahme: Eine handgebaute Rolle mit nur `manage` sieht nichts, was sie angelegt hat.
|
||||
70. **Dokumente gelöschter Datensätze bleiben bestehen**: Sie bleiben durch das Recht der Art geschützt und werden nicht mitgelöscht; bisher löscht kein Pfad einen Datensatz mit Dokumenten (Behandlungen, Sperrbezirke und Behördenanzeigen haben keine Löschroute; Sperrbezirke enden über das Enddatum, Entwürfe werden verworfen, Annahme 76). Ein künftiger Löschpfad entfernt die Dokumente seines Datensatzes selbst. Kosten bei falscher Annahme: Dateien ohne Datensatz bleiben im Speicher.
|
||||
71. **Der CSV-Import befolgt den Sperrbezirk ohne Ausnahme**: Der Import legt in einem Stand mit aktivem Sperrbezirk kein Volk an; die Zeile wird als Fehlerzeile gemeldet (Text des Sperrbezirks), nichts wird für sie geschrieben. Der Import kennt keine Ausnahmebegründung. Kosten bei falscher Annahme: Wer Altbestand in einen gesperrten Stand importieren muss, legt die Völker einzeln mit Begründung an. Abschnitt 12.7.
|
||||
72. **Eine Ausnahmebegründung ohne `compliance:manage` ist immer 403**: Wer `restrictionOverrideReason` sendet, ohne `compliance:manage` zu halten, bekommt 403, bevor gelesen oder gesperrt wird, auch ohne aktive Sperre. Mit dem Recht wird eine Begründung ohne aktive Sperre ignoriert. Kosten bei falscher Annahme: Ein Client, der die Begründung immer mitsendet, braucht das Recht. Abschnitt 12.7.
|
||||
73. **Der Bestandsbuch-Export braucht zusätzlich `veterinary-medicines:read`**: `GET /export/treatment-log.pdf` verlangt `export:read` und `veterinary-medicines:read`, weil es Lieferant, Beleg und Tierarzt aus der Packung zeigt (die Prüfung steckt im `ExportController`, nur für diesen Bericht). Kosten bei falscher Annahme: Ein Nutzer mit nur `export:read` verliert das Bestandsbuch; das Frontend (Task 15) blendet den Export ohne das Recht aus. Abschnitt 12.2.
|
||||
74. **„500“ und „g“ in zwei Elementen zählen nur als anliegendes Paar**: Die Füllmenge gilt in zwei Elementen nur, wenn sich die Boxen senkrecht überlappen, die Einheit rechts der Zahl liegt (`x` nicht kleiner) und der waagerechte Abstand höchstens 10 mm beträgt; vor der Zahl darf keine Ziffer stehen. Sonst ist es eine Lücke (sperrt den Druck, der Probedruck bleibt möglich). Abschnitt 12.4.
|
||||
75. **Eine verteilte Anschrift zählt nur mit höchstens 10 mm Abstand**: Name und Anschrift des Lebensmittelunternehmers dürfen über mehrere Elemente verteilt sein, wenn der senkrechte Abstand jedes Elements zur bisherigen Gruppe höchstens 10 mm beträgt (symmetrisch, gegen die laufende Ober- und Unterkante der Gruppe; die Lesereihenfolge kommt allein aus den Positionen). Der waagerechte Abstand zählt dort nicht. Kosten bei falscher Annahme: Eine sehr weit auseinandergezogene Anschrift gilt als Lücke; zwei nahe, fremde Elemente mit der passenden Wortfolge gelten als Anschrift. Abschnitt 12.4.
|
||||
76. **Verwerfen einer Behördenanzeige behält die Dokumente**: `cancel` setzt den Entwurf auf `CANCELLED` und gibt den `openKey` frei; es gibt keine Löschroute (Spec 7), angehängte Dokumente (`AUTHORITY_NOTICE`) bleiben bestehen und durch das Recht der Art geschützt (Annahme 70). Kosten bei falscher Annahme: Wer einen Entwurf „löschen“ erwartet, findet ihn als verworfen in der Liste. Abschnitt 12.8.
|
||||
77. **Etikett-Rechte: derzeit nur ADMIN (Frage an den Inhaber offen)**: `label-templates:read|create|update|deactivate|print` vergibt keine Migration, nur die Katalog-Synchronisation an die damaligen Systemrollen; in der Test-Datenbank halten sie nur ADMIN. Prüfen und Drucken brauchen zusätzlich `bottling:read`. Offen ist, ob BEEKEEPER (und für `read` STAFF und READONLY) Etiketten ansehen und drucken dürfen; vor dem Rollout die tatsächliche Rollenvergabe in Produktion prüfen. Abschnitt 12.6.
|
||||
78. **Eine Bestandsänderung meldet nur, sie legt keine Anzeige an**: `compliance.herd-change` schreibt eine Meldung (`HINWEIS`, `COMPLIANCE`) an jeden aktiven Nutzer mit `compliance:manage`, nie einen Entwurf (Spec 5.5). Kosten bei falscher Annahme: Wer einen Entwurf erwartet, legt die Änderungsanzeige selbst an. Abschnitt 12.9.
|
||||
79. **Die TSK-Erinnerung geht auch bei einem offenen Entwurf**: Existiert für das Jahr nur ein Entwurf, geht die Meldung weiter (Link auf den Entwurf, höchstens eine ungelesene je Nutzer); nur eine gesendete Anzeige hält sie still. Kosten bei falscher Annahme: Eine Erinnerung zu viel, solange der Entwurf nicht gesendet ist. Abschnitt 12.9.
|
||||
80. **Ein Umschalter der Benachrichtigung wirkt erst beim nächsten Ereignis**: Wer `noticeOnColonyCountChange` oder `noticeOnApiaryChange` einschaltet, bekommt eine bereits bestehende Abweichung erst beim nächsten Herd-Ereignis gemeldet. Kosten bei falscher Annahme: Die Meldung kommt später; die Prüfbereitschaft (12.10) zeigt die Abweichung sofort. Abschnitt 12.9.
|
||||
81. **Maskierte Aufrufer der Prüfbereitschaft sehen die Zählungen**: Ohne `subjectPermission` bleiben `subjects` leer, `more` und Sätze wie „N Stände liegen im Sperrbezirk“ bleiben sichtbar; Namen, Anschriften und Aktenzeichen stehen nie in Titel und Detail. Kosten bei falscher Annahme: Die Anzahl ist für alle mit `compliance:read` sichtbar. Abschnitt 12.10.
|
||||
82. **Das TSK-PDF ist A4 quer**: Der Zählnachweis hat viele Spalten (eine je Völkerart plus Summe); im Hochformat blieben der Lage-Spalte etwa 49 pt. Erst- und Änderungsanzeige bleiben Hochformat. Kosten bei falscher Annahme: Das Blatt muss gedreht abgelegt werden. Abschnitt 12.8.
|
||||
83. **Der Ort im Briefkopf kommt aus der Postleitzahl-Zeile**: Aus „…, 34117 Kassel“ wird „Kassel“; ohne Treffer steht nur das Datum, der Ort bleibt leer (kein `FEHLT`). Kosten bei falscher Annahme: Der Ort fehlt neben dem Datum. Abschnitt 12.8.
|
||||
84. **Die Summe im Anzeigen-PDF ist das gespeicherte `totalColonies`**: Weicht es von der Summe der Stände ab, steht „Gesamtzahl berichtigt (Summe der Stände: n)“; es wird nicht live neu gezählt. Kosten bei falscher Annahme: Ein veraltetes `totalColonies` erscheint im Ausdruck, bis `recount` im Entwurf läuft. Abschnitt 12.8.
|
||||
85. **Keine der ersten sieben Prüfregeln ist quittierbar**: Weder Pflicht- noch Prüfen-Punkte dieser Stufe lassen sich wegquittieren (Spec 5.7); die Quittung ist Mechanik für spätere weiche Regeln (Task 13). Kosten bei falscher Annahme: Der Inhaber muss die Ursache beheben statt zu quittieren. Abschnitt 12.10.
|
||||
86. **Die Kurzfassung der Prüfbereitschaft kann bis zu 60 s veraltet sein**: `GET /compliance/readiness/summary` (Dashboard-Zeile) wird je Prozess 60 s aus dem Speicher bedient und nach Quittieren oder Zurücknehmen im selben Prozess sofort verworfen. Änderungen an den Daten und Quittungen eines anderen Prozesses erscheinen dort bis zu 60 s später; Liste, PDF-Bericht und Quittierpfad rechnen immer live. Kosten bei falscher Annahme: Die Dashboard-Zeile zeigt kurz einen alten Stand. Abschnitt 12.10.
|
||||
87. **Der Service Worker entscheidet über das Zwischenspeichern nach dem Pfad, nicht nach `Cache-Control`**: Das Backend sendet `Cache-Control: no-store` an jede API-Antwort (Abschnitt 9); würde der Worker den Header als Signal lesen, verwürfe er das gesamte Offline-Verhalten. Nie gespeichert wird, was `NEVER_CACHED_API_PATHS` und die Dokumentarten-Regel benennen; ein neuer schutzwürdiger Pfad muss dort eingetragen werden und hebt `SW_ROUTES_VERSION`. Kosten bei falscher Annahme: Ein vergessener Pfad kann offline gespeichert werden, obwohl der Server `no-store` sendet. Abschnitt 2 und 12.3.
|
||||
88. **„1.000“ wird als mehrdeutig abgelehnt**: Die Mengenfelder der Tierarzneimittel-Oberfläche lesen das Komma als Dezimalzeichen und lehnen einen einzelnen Punkt mit genau drei Nachkommastellen („1.000“, „12.345“) sowie jeden Text mit mehreren Trennzeichen ab, weil er Tausender oder Dezimalstelle meinen könnte. Kosten bei falscher Annahme: Wer „1.000“ als eins meint, muss „1“ oder „1,0“ schreiben. Abschnitt 12.11.
|
||||
89. **Eine neue, ungespeicherte Etikettvorlage prüft nichts, bis sie einen Wert hat**: Der Check-Endpunkt verlangt die Mindest-x-Höhe; das Frontend kennt keinen eigenen Vorgabewert (kein Rechtswert im Code). Eine neue Vorlage startet mit leerem Feld, sendet beim Anlegen keinen Wert (der Server setzt seinen Standard) und zeigt das Panel erst nach Eingabe oder nach dem ersten Speichern. Kosten bei falscher Annahme: Im Designer fehlt bei einer ganz neuen Vorlage die Prüfung, bis der Wert gesetzt ist. Abschnitt 12.11.
|
||||
90. **Das Prüfbericht-PDF druckt Zählungen, keine Namen**: Es nennt je Punkt nur die Zahl der betroffenen Objekte, nie Stände, Völker, Mittel, Packungen oder Aktenzeichen, damit der Bericht ohne Rechteprüfung der Namen weitergegeben werden kann. Kosten bei falscher Annahme: Wer die Objekte braucht, öffnet die Seite `/compliance` mit den Rechten. Abschnitt 12.10.
|
||||
91. **Eine Sperre, die heute endet, gilt bis Tagesende; ein Aufheben am selben Tag gibt es nicht**: `endsOn` ist inklusive (aktiv bei `startsOn` ≤ Berliner Tag ≤ `endsOn`), das Backend lehnt `endsOn` vor `startsOn` ab. Die Oberfläche schlägt „gestern“ als Endtag vor; wer heute oder später wählt, bekommt „Die Sperre gilt noch bis einschließlich …“. Kosten bei falscher Annahme: Wer eine Sperre heute am Vormittag aufheben will, hat sie bis Mitternacht Berliner Zeit weiter am Stand. Abschnitt 12.11.
|
||||
92. **Beim Bearbeiten einer Behandlung wählt die Oberfläche nie selbst eine Packung vor**: Nur das Anlegen schlägt die Packung mit dem frühesten Verfall vor; im Bearbeiten-Dialog steht nach einem Mittelwechsel „Ohne Packung“, bis der Nutzer wählt. Kosten bei falscher Annahme: Wer eine Abbuchung erwartet, muss die Packung ausdrücklich wählen. Abschnitt 12.11.
|
||||
93. **Die Glocke zeigt für `COMPLIANCE` das Kurz-Etikett „Behörden“**: Die Badges der Glocke sind Einwort-Etiketten („Aufgabe“, „Vorschlag“); „Behörden & Prüfung“ würde die Zeile umbrechen und steht darum nur in `lib/notifications/labels.ts` und der Telegram-Kategorienauswahl. Kosten bei falscher Annahme: Zwei Bezeichnungen für dieselbe Kategorie. Abschnitt 12.11.
|
||||
94. **Die Dosis ist auf drei Nachkommastellen begrenzt**: Das Eingabefeld lehnt mehr als drei Nachkommastellen mit „Höchstens 3 Nachkommastellen.“ ab (Packungsmengen rechnen auf Tausendstel, `roundToThousandths`). Kosten bei falscher Annahme: Eine feinere Dosis lässt sich nicht erfassen. Abschnitt 12.11.
|
||||
95. **Die Liebig-Zander-Zarge misst außen 525 × 430 mm**: Der Wert stammt aus dem Innenmaß des Edelstahldeckels und steht im Katalog (Migration `20261017100100_hive_catalog_zander_liebig`, `test/fixtures/hive-ops/catalog.json`). Kosten bei falscher Annahme: Die 3D-Maße stimmen nicht; der Inhaber misst nach, der Katalogwert wird mit `hive-systems:manage` geändert. Abschnitt 13.
|
||||
96. **Die Styropor-Einlage misst 465 × 365 × 20 mm**: Der Inhaber misst nach. Kosten bei falscher Annahme: Die Dämmung sitzt im Modell zu groß oder zu klein; Katalogwert ändern, kein Code. Abschnitt 13.
|
||||
97. **Der Nassenheider Professional liegt in einer Leerzarge auf den Rähmchen der Zarge darunter**: Im Modell ist er ein Einsatz der Leerzarge (`EVAPORATOR` in einer `BOX` mit 0 Plätzen). Kosten bei falscher Annahme: Die Lage im Aufbau weicht vom Stock ab; der Inhaber bestätigt mit Foto, die Regel steht in `hive-validate.ts`. Abschnitt 13.
|
||||
98. **Rähmchen-Plätze zählen von links, mit Blick auf das Flugloch**: Platz 1 ist links, Platz `frameSlots` rechts. Kosten bei falscher Annahme: Alle gespeicherten Platznummern sind gespiegelt; das lässt sich nur mit einer Datenmigration über alle Aufbauten beheben. Abschnitt 13.
|
||||
99. **Den Aufbau ändert nur, wer `colonies:update` hat; den Katalog pflegt nur `hive-systems:manage` (ADMIN)**: STAFF hat `colonies:update` nicht und kann die Beute daher nicht ändern, auch nicht in der Durchsicht (403 `HIVE_FORBIDDEN`). `hive-systems:manage` kommt nur über die Katalog-Synchronisierung zur Rolle ADMIN, ohne Rechte-Migration. Kosten bei falscher Annahme: Mitarbeiter müssen den Aufbau über einen Administrator ändern lassen; der Inhaber vergibt `colonies:update` in der Rollenverwaltung, das ist kein Code. Abschnitt 13.
|
||||
100. **Die Bausperre ist eine Einlage ohne Zustand; „Winter“ ist kein eigener Modus**: Die Bausperre (`FLOOR_INSERT`) hat kein Zustandsfeld, Einlegen und Entfernen sind die Operationen `addInsert` und `removePart`. Kosten bei falscher Annahme: Wer einen Winter-Modus erwartet, muss Einlagen einzeln setzen; ein Modus wäre eine spätere Erweiterung des Katalogs. Abschnitt 13.
|
||||
101. **Die Futtertasche misst 477 × 70 × 220 mm und fasst 2 l**: Der Hersteller (Holtermann) nennt Anschlussmaße, kein Volumen; Maße und `max: 2` im Zustandsfeld `syrupLiters` sind Annahmen der Startdaten (Migration `20261018100100_hive_catalog_frame_feeder`) und im Katalog editierbar (Einstellungen > Beutensysteme). Kosten bei falscher Annahme: Die Tasche sitzt im 3D-Modell zu groß oder zu klein und die Füllstandsgrenze stimmt nicht; der Inhaber misst nach, der Katalogwert wird mit `hive-systems:manage` geändert, kein Code. Abschnitt 13.
|
||||
102. **Eine wartende Beute-Änderung wird nie überholt, auch eine abgelehnte nicht**: Ohne Netz oder mit offener Warteschlange reiht die Karte jede weitere Änderung desselben Volks hinten ein, statt sie online zu senden; ein abgelehnter Eintrag hält die späteren desselben Volks zurück, bis der Nutzer ihn in der Warteschlange klärt (Abschnitt 2). Kosten bei falscher Annahme: Nach einer abgelehnten Änderung sind neue Änderungen am Volk vorerst blockiert, bis der Nutzer entscheidet; die Alternative (überholen) könnte einen Aufbau erzeugen, den die Reihenfolge nie hatte. Abschnitt 13.1.
|
||||
103. **Die Historienzeilen haben keine Folgeknöpfe**: Eine Zeile der Beute-Historie zeigt die Änderung und den Stand an diesem Tag, bietet aber keine Vorschläge wie „Futter nachlegen“ an, weil ein Eintrag den Zustand davor nicht trägt; die Vorschläge erscheinen nur als Hinweis (Toast) direkt nach dem Speichern. Kosten bei falscher Annahme: Ein weggewischter Hinweis ist aus der Historie nicht wiederzufinden; Abhilfe wäre, `stateBefore` im Protokoll zu speichern (Migration). Abschnitt 13.1.
|
||||
104. **Der Editor hält den Stand fest, auf dem der Entwurf begann**: Beim ersten Schritt merkt sich `useHiveDraft` den geladenen Aufbau (`snapshot`) und zeigt die Vorschau darauf; ändert sich der Aufbau auf dem Server inzwischen, erscheint ein Hinweis, und beim Speichern wendet der Server die Operationen auf den aktuellen Stand an. Passen sie nicht mehr, öffnet sich das Konflikt-Sheet, es wird nichts gespeichert. Kosten bei falscher Annahme: Die Vorschau im Editor weicht nach einer gleichzeitigen Änderung vom gespeicherten Ergebnis ab; der Konflikt-Weg fängt Unverträgliches ab. Abschnitt 13.1.
|
||||
105. **Der Zoom der 3D-Szene (0,6 bis 2,5) kommt mit dem Ziehen und Ablegen**: Die Szene hat Drehen und Fokus auf ein Teil, aber noch keinen frei wählbaren Zoom; der Bereich ist der Aufgabe für Ziehen und Ablegen zugeordnet (Task 18). Kosten bei falscher Annahme: Auf kleinen Bildschirmen fehlt zunächst ein Zoom; der Browser-Zoom und die Listenansicht (Gliederung) bleiben als Weg. Abschnitt 13.1.
|
||||
106. **Restrisiko im Abschreib-Pod wird getragen**: Der Container `whisper` (CronJob `voice-transcribe`, Komponente `deploy/k8s/components/voice`) dekodiert nicht vertrauenswürdige Audiodateien mit libav/PyAV und CTranslate2. Er teilt das Pod-Netz; die NetworkPolicy `apicore-jobs` erlaubt nur Postgres (5432) und DNS. Ein kompromittierter Decoder könnte über DNS-Anfragen langsam Daten nach außen tragen und Postgres erreichen, hat aber keine Zugangsdaten (kein `envFrom`, kein `secretKeyRef`, kein Service-Account-Token, eigenes `/tmp`, damit er `ingest` mit den Secrets nichts unterschieben kann). Er sieht Ton und Abschriften seines Laufs (höchstens 5 Aufnahmen, 600 s) und könnte deren Ergebnisse verfälschen; `/work/in` ist für ihn nur lesbar, und `ingest` übernimmt nur Ergebnisse zu Aufnahmen des eigenen Manifests mit passendem `claimToken`, prüft jedes Ergebnis streng, und nichts geht ohne Klick in ein Formular. Akzeptiert nach Spec 9.2: ein Betrieb mit eigenen Nutzern, keine Geheimnisse im Decoder, kein Internet, Schaden auf einen Lauf begrenzt. Das CronJob-Objekt trägt bewusst `app: apicore-voice-job` (nur das Pod-Template `app: apicore-job`), damit der gemeinsame Job-Patch keinen weiteren Container einsetzt; `av` ist wegen faster-whisper 1.2.1 auf 18.1.0 festgelegt. Kosten bei falscher Annahme: Abschriften eines Laufs könnten bei einer Lücke im Decoder abfließen oder vertauscht werden. Stärkere Optionen später: eigener Pod für den Decoder mit deny-all-NetworkPolicy (auch ohne DNS) und Übergabe-Volume, oder ein Subprozess je Aufnahme mit eigener Sandbox.
|
||||
107. **Speichern der Durchsicht bestätigt eine Sprachnotiz in jedem offenen Zustand**: Auch eine Notiz, die noch abgeschrieben oder ausgewertet wird, wird mit dem Speichern `CONFIRMED` und ihr Inhalt in derselben Transaktion gelöscht; ein laufender Job verliert seinen Anspruch. Grund: Wer speichert, hat entschieden, und Inhalte sollen nie liegen bleiben. Kosten bei falscher Annahme: Eine noch laufende Abschrift oder Auswertung geht verloren, wenn der Nutzer vorher speichert; die Notiz lässt sich nicht mehr nutzen und muss neu aufgenommen werden. Abschnitt 14.2.
|
||||
108. **Eine Dezimalzahl bleibt beim Zitatabgleich ein Wort**: `4,5` und `4.5` gelten als dieselbe Zahl und werden nicht an Komma oder Punkt zerlegt, sonst ließe sich ein Zitat aus Zahlenresten zusammensetzen, das nie gesagt wurde. Kosten bei falscher Annahme: Ein Zitat mit anderer Schreibweise der Dezimalzahl trifft die Abschrift nicht, ein gültiger Vorschlag wird verworfen (der Nutzer trägt von Hand ein). Abschnitt 14.4.
|
||||
109. **Wiederholen wird über Grenzen gebremst, nicht über eine Zahl je Notiz**: Jedes Wiederholen reiht die Notiz neu ein und kann einen bezahlten Aufruf auslösen. Gebremst wird es durch die Sperre je Nutzer, die Grenze von 10 offenen Notizen und höchstens 5 Anfragen je Minute und Netz; eine Obergrenze je Notiz gibt es nicht (sie bräuchte eine Schemaänderung). Kosten bei falscher Annahme: Ein Nutzer mit einer dauerhaft kaputten Notiz kann sie wiederholt neu starten und Tagesbudget verbrauchen; Abhilfe wäre ein Zähler für manuelle Wiederholungen mit Migration. Abschnitt 14.1.
|
||||
110. **Das Tagesbudget zählt bezahlte Aufrufe im Protokoll, nicht Notizen**: `VoiceExtractionCall` hält jeden Aufruf mit Ausgang; `AUTH` und `ABORTED` zählen nicht, abgelehnte, abgeschnittene, ungültige und wiederholte Aufrufe schon, weil sie Geld kosten. Die Tabelle ist nicht im Backup und wird nach 90 Tagen gelöscht. Kosten bei falscher Annahme: Bei vielen Fehlversuchen ist das Budget früher erschöpft, als die Zahl der Notizen vermuten lässt, und Notizen warten bis zum nächsten Tag; eine weitere Tabelle ist zu pflegen. Abschnitt 14.4.
|
||||
111. **Das Tagesbudget wechselt um 00:00 UTC**: Die Grenze ist der UTC-Tag der Datenbankuhr (wie die 30 neuen Notizen je Tag), also 01:00 oder 02:00 Uhr in Berlin. Kosten bei falscher Annahme: Wer in der Nacht arbeitet, sieht das Limit nicht zum Berliner Tageswechsel zurückgesetzt; für einen Betrieb mit Tagesarbeit ohne Folgen, sonst ein Wechsel der Grenze auf den Berliner Tag. Abschnitt 14.4.
|
||||
112. **Eine von selbst beendete Aufnahme wird sofort gespeichert**: Erreicht die Aufnahme 180 s, geht sie ohne Rückfrage in die Geräte-Warteschlange; ein Verlassen der Seite verwirft sie nicht. Kosten bei falscher Annahme: Eine Aufnahme, die der Nutzer nicht wollte, liegt in der Warteschlange und wird hochgeladen, bis er sie verwirft; sie kostet Speicher und Abschreibzeit, aber keine Auswertung, solange er sie nicht öffnet. Abschnitt 14.6.
|
||||
113. **Der Schalter wirkt auch im Server**: Bei `VOICE_RECORDING_ENABLED=false` lehnen Upload und Text-Weg mit 403 `VOICE_RECORDING_DISABLED` ab, nicht nur die Oberfläche. Lesen, Wiederholen und Verwerfen bleiben. Kosten bei falscher Annahme: Notizen, die offline vor dem Ausschalten aufgenommen wurden, werden beim Sync abgelehnt und bleiben mit Fehler in der Warteschlange (der Nutzer verwirft sie); der Rückweg ist damit sauber, aber nicht verlustfrei. Abschnitt 14.1.
|
||||
114. **Kosten werden für die letzten 7 Tage gezeigt, zum Preis des eingestellten Modells**: Die Zähler der Systemseite kennen nur ein 7-Tage-Fenster, und die Preistabelle liegt in zwei Dateien (`lib/voice/prices.ts`, `src/voice/eval/voice-prices.ts`, ein Paritätstest). Kosten bei falscher Annahme: Der Inhaber liest eine Wochen-, keine Monatssumme; die echte Abrechnung steht in der Anthropic-Konsole. Abschnitt 14.5.
|
||||
115. **Eine abgelehnte Anfrage darf serverseitig auf einem anderen Modell laufen**: Mit `VOICE_SERVER_FALLBACK=default` (Voreinstellung) setzt der Adapter für Sonnet und Opus den Ausweichweg von Anthropic; gebucht wird das tatsächlich antwortende Modell. Kosten bei falscher Annahme: Eine Notiz wird auf einem anderen, womöglich teureren Modell beantwortet als eingestellt, und das Tagesbudget zählt Aufrufe, nicht Euro; abschaltbar mit `off`, dann endet die Notiz bei einer Ablehnung `FAILED/REFUSED`. Abschnitt 14.4.
|
||||
116. **Der Text einer Sprachnotiz darf zu Anthropic (Drittland)**: Der Inhaber hat den API-Schlüssel angelegt (2026-10-16); das gilt als Freigabe von Spec-Frage 3. Modell `claude-sonnet-5-5` mit `effort: low` (Frage 1); die Cloud-Erkennung des Browsers bleibt ohne Einwilligung aus (Frage 2). Eine Region ist nicht gesetzt (`inference_geo` bleibt aus), es gilt die Voreinstellung des Anthropic-Arbeitsbereichs. Kosten bei falscher Annahme: Fehlt die Freigabe, bleibt der Worker ohne das Secret `apicore-anthropic`, die Notizen bleiben `TRANSCRIBED` und sind als Text nutzbar; Datenschutzerklärung und Verzeichnis müssen die Übermittlung vor dem Einschalten nennen. Abschnitt 14.7.
|
||||
117. **Die Grenzen der Vorschläge folgen dem Formular, nicht der Spec**: Volksstärke bis 40 und fünf Futterstufen, wie `CreateInspectionDto` und das Formular; für `broodFrames` ohne Obergrenze im Formular gilt im Sprachweg 40. Kosten bei falscher Annahme: Die Auswertung schlägt Werte vor, die der Autor der Spec nicht erwartet hat, oder verwirft zulässige (sie landen als Zahl in `dropped`); die Grenzen stehen an einer Stelle (`core/inspection-field-specs.ts`). Abschnitt 14.4.
|
||||
118. **Meldungen zu Sprachnotizen gehören in die Kategorie „Vorschläge“**: „Sprachnotiz ist fertig“ und „konnte nicht ausgewertet werden“ haben die Kategorie `SUGGESTION`, weil sie zu Vorschlägen führen. Kosten bei falscher Annahme: Wer die Kategorie „Vorschläge“ in Telegram oder der App abschaltet, bekommt auch diese Meldungen nicht mehr; die Notiz bleibt unter `/voice` sichtbar. Abschnitt 14.5.
|
||||
|
||||
## 7. Kubernetes
|
||||
|
||||
@@ -188,7 +253,8 @@ Fachliche Annahmen, getroffen weil das Lastenheft an der Stelle keine eindeutige
|
||||
- `pod-hardening`: Frontend mit `readOnlyRootFilesystem`, `emptyDir` auf `/tmp` und `/app/.next/cache`, ohne Service-Account-Token, Ressourcen laut Spec §7.
|
||||
- `backend-roles`: `APICORE_ROLE=api` samt initContainern `migrate` und `seed` im Deployment `apicore-backend`, Deployment `apicore-worker`, CronJobs `apicore-job-<name>`. Das neue Backend-Image (CMD nur `node dist/main.js`) geht nur zusammen mit dieser Komponente live. Ohne `APICORE_ROLE` bricht es den Start in Produktion ab, und ohne die initContainer liefe keine Migration.
|
||||
- `api-hpa`: HPA `apicore-backend` (`autoscaling/v2`, 1–2 Pods bei 70 % CPU); entfernt `replicas` aus dem Deployment.
|
||||
- `overlays/encry/`: Namespace `apicore`, ConfigMaps, Ingresses (Traefik, Middleware `apicore-cloudflare-only@kubernetescrd`, cert-manager `letsencrypt-prod` mit HTTP-01), Image-Digests. Hosts, ConfigMap-Werte und Digests sind bis zum Rollout Platzhalter (`example.com`, `sha256:000…`).
|
||||
- `overlays/encry/`: Namespace `apicore`, ConfigMaps, Ingresses (Traefik, Middleware `apicore-cloudflare-only@kubernetescrd`, cert-manager `letsencrypt-prod` mit HTTP-01), Image-Digests. Die ConfigMap-Werte sind seit 2026-10-15 die Live-Werte aus dem Cluster (Runbook Schritt 1, Commit `6e3e9ae`). Hosts und TLS in `ingress-*.yaml` und die Image-Digests sind bis zum Rollout noch Platzhalter (`example.com`, `sha256:000…`).
|
||||
- `scripts/ensure-secrets.sh`: ergänzt fehlende Schlüssel in `apicore-backend-secret` und `apicore-telegram`, ohne vorhandene Werte zu ändern, und gibt nur Schlüsselnamen aus (`--dry-run` zeigt nur an). Die Secrets selbst legt der Inhaber an.
|
||||
- `tests/`: `manifest-policy.test.mjs` prüft das gerenderte Overlay (NetworkPolicies nach Kubernetes-Semantik, Pod-Härtung, Ressourcen, CronJobs, Migration, Digests, Live-Selektoren) und jeden Rollout-Schritt (DNS, Ingress, api → Postgres und alle DB-Clients bleiben erreichbar). `render-stages.mjs` rendert die Schritte 1, 2, 3 und 5 aus dem Overlay. Die CI (`.gitea/workflows/manifests.yml`, nur `push` und `workflow_dispatch`, kein `pull_request`, weil der Runner im Cluster läuft) rendert mit `kubectl kustomize`, validiert mit `kubeconform -strict` und führt den Test aus; kubectl, kubeconform und yq mit festen Versionen und SHA-256.
|
||||
- **Telegram-Secret.** `apicore-telegram` (Schlüssel `TELEGRAM_BOT_TOKEN`) bindet nur `apicore-worker` ein: als einzelne `secretKeyRef`-Variable mit `optional: true` am Haupt-Container, ohne `envFrom`, ohne Volume, nicht im initContainer. Die api bekommt das Secret nie. Fehlt es, startet der Worker normal, nur die Telegram-Schleifen laufen nicht. `TELEGRAM_BOT_USERNAME` steht in der ConfigMap `apicore-backend-config` (api und Worker lesen sie per `envFrom`; leerer Platzhalter, bis der Bot angelegt ist); das Token steht nie in einer ConfigMap. `manifest-policy.test.mjs` prüft für den Zielstand und jede Rollout-Stufe mit Worker: genau ein Worker-Pod, genau eine Token-Variable ohne Klartextwert, kein anderer Pod mit `TELEGRAM_BOT_TOKEN`. Einrichtung bei BotFather: je Umgebung ein eigener Bot, Gruppen aus (`/setjoingroups` → Disable), kein Webhook (der Worker ruft `getUpdates`). Der Worker läuft mit `replicas: 1`, weil der Versand das annimmt (Annahme 46); Claims und Empfangs-Lease bleiben auch mit mehr Pods korrekt.
|
||||
|
||||
@@ -234,7 +300,7 @@ initContainer haben die Ressourcen der CronJob-Pods. Alle App-Pods laufen ohne S
|
||||
|
||||
**Images:** Das Base-Image `node:22-alpine` ist in beiden Dockerfiles per Digest gepinnt; ein Update ist ein bewusster Commit mit neuem Digest. Die CI taggt nur noch `sha-<commit>` und Versionen, kein `latest`. Das Overlay setzt die Digests der gebauten Images. Bis Schritt 3 bleibt beim Backend der Digest des laufenden Images.
|
||||
|
||||
**Rollout:** nur nach dem Runbook im Plan `docs/superpowers/plans/2026-10-13-plattform-rueckgrat.md`, jeder Schritt mit Freigabe des Inhabers: 0 Digests, 1 Overlay auf den Ist-Stand (Diff leer), 2 NetworkPolicies, 3 Rollen und Pod-Härtung, 4 Schlüssel trennen, 5 HPA.
|
||||
**Rollout:** nur nach dem Runbook im Plan `docs/superpowers/plans/2026-10-13-plattform-rueckgrat.md`, jeder Schritt mit Freigabe des Inhabers: 0 Digests, 1 Overlay auf den Ist-Stand (Diff leer), 2 NetworkPolicies, 3 Rollen und Pod-Härtung, 4 Schlüssel trennen, 5 HPA. Stand 2026-10-16: Im Cluster wurde noch kein Schritt angewendet; vorbereitet sind nur die ConfigMap-Werte aus Schritt 1. Live laufen das Backend-Image `sha-f5b1964` und ein Frontend-Image vom 2026-10-12, im Namespace gelten nur die drei Policies aus `rke2-cluster`. Fortschritt: Gitea-Issue „Rollout in den Cluster“ (#28).
|
||||
|
||||
## 8. Backup & Restore
|
||||
|
||||
@@ -248,11 +314,11 @@ Der Seed (`node dist/seed.js`) läuft als zweiter initContainer `seed` nur im `a
|
||||
|
||||
Scheitert die Migration, scheitert der initContainer und der neue Pod startet nicht. Wegen `maxSurge: 1` und `maxUnavailable: 0` läuft der alte Pod weiter. Die Hauptprozesse starten ohne Prisma-CLI. Die `startupProbe` der api (bis 5 Minuten) bleibt für das alte Image, das die Migration noch im `CMD` ausführt.
|
||||
|
||||
**Erster Admin-Zugang:** `prisma/seed.ts` legt beim allerersten Start (leere `User`-Tabelle) einen Administrator an (`SEED_ADMIN_EMAIL`/`SEED_ADMIN_PASSWORD`, Default `[email protected]`/`ChangeMe123!`) und gibt URL (`FRONTEND_ORIGIN`), Benutzername und Passwort einmalig im Container-Log aus. Existiert der User schon (auch deaktiviert), passiert nichts – kein erneutes Log, kein erneutes Anlegen, damit spätere Passwortänderungen nicht durch veraltete Logs verwirrend überschrieben wirken und Zugangsdaten nicht bei jedem Neustart in die Logs wandern. Ersetzen: neuen Admin über `/settings/users` anlegen, dann den alten deaktivieren (Löschen gibt es nicht, siehe "Historie statt Löschen") – die Lockout-Sperre in `UsersService.assertNotLastSystemRoleUser` verhindert ohnehin, den letzten aktiven Admin zu deaktivieren.
|
||||
**Erster Admin-Zugang:** `prisma/seed.ts` (`seedAdmin`) legt nur an, solange die `User`-Tabelle leer ist, also beim allerersten Start. Adresse aus `SEED_ADMIN_EMAIL` (Standard `[email protected]`), Passwort aus `SEED_ADMIN_PASSWORD`; fehlt es, erzeugt der Seed ein zufälliges. Ins Container-Log kommen einmalig URL (`FRONTEND_ORIGIN`), Benutzername und nur das erzeugte Passwort; ein vom Betrieb gesetztes Passwort erscheint nie im Log. Sobald irgendein Benutzer existiert, passiert nichts – auch nicht, wenn der Administrator seine Adresse geändert hat (früher entstand dann bei jedem Start ein weiterer ADMIN, #45). Ersetzen: neuen Admin über `/settings/users` anlegen, dann den alten deaktivieren (Löschen gibt es nicht, siehe "Historie statt Löschen") – die Lockout-Sperre in `UsersService.assertNotLastSystemRoleUser` verhindert ohnehin, den letzten aktiven Admin zu deaktivieren.
|
||||
|
||||
**Datensicherung:** Seit der Entscheidung, PostgreSQL selbst im Cluster zu betreiben (siehe CLAUDE.md), liegt die Backup-Verantwortung bei diesem Projekt, nicht mehr bei einem externen Cluster-/DBA-Betrieb. Umgesetzt als anwendungsseitiges `BackupModule` (`ApiCore-Backend/src/backup/`) statt der ursprünglich hier vorgesehenen reinen `pg_dump`/PITR-Strategie:
|
||||
|
||||
- **Export/Import:** `BackupService.exportAll()`/`.importAll()` sichert alle fachlichen und Konfigurationsmodelle (Betriebsdaten inkl. Herstellung, Rohstoffe, Bewegungsbuch und Shop-Anfragen, Nummernkreise, Benutzer/Rollen/Rechte, Audit-Log, Website-/Backup-/Kalender-Einstellungen samt Kalender-Outbox, hochgeladene Dokumente inkl. Dateiinhalt als Base64) als eine versionierte JSON-Datei (Bundle-Version 3; ältere Bundles bleiben einspielbar). Neu im Bundle: `Suggestion` (Import nach `colony`, vor `task`, weil `Task.sourceSuggestionId` darauf zeigt; `decidedByUserId` wie andere Benutzer-IDs, `null` bleibt `null`; nur aus versiegelten Dateien, sonst kämen verworfene oder übernommene Vorschläge nach einem Restore als neue zurück) und `NotificationPreference`. Seit T4b zusätzlich `PhenologyReport` (eigene Beobachtungen; Import nach `winterCheck`, Benutzer-IDs wie bei anderen Pflicht-Benutzern umgesetzt; nur aus versiegelten Dateien). `ApiaryPhenology` (abgeleiteter Saisonzustand, der Job `daily-evaluation` berechnet ihn neu) und `ApiaryWeatherDay` (Wetter-Cache, der Worker holt ihn neu) sind ausgenommen. Alte Bundles, deren `HoneyBatch`-Zeilen kein `initialAmount` tragen, werden beim Import wie in Migration `t4_honey_ledger` zurückgerechnet (Annahme 44, `src/backup/legacy-honey-ledger.ts`): `initialAmount` wird gesetzt; die `BOTTLING`-Buchungen mit der stabilen ID `legacy-bottling:<Abfüllung>` entstehen nur aus versiegelten Dateien, nach dem Abschnitt `batchMovement`, und werden bei einem erneuten Import nie überschrieben. Eine unversiegelte Datei setzt nur `initialAmount` bei Chargen, die es noch nicht gibt. Nach dem Honig-Teil des Imports prüft eine SQL-Abfrage die Invariante der importierten Chargen (`honeyLedgerViolations`) in der Import-Transaktion: bei Treffern Warnung im Log mit den IDs und `imported.honeyLedgerViolations = <Anzahl>` (Schlüssel nur bei > 0); der Import scheitert deshalb nicht. Meldungen: Ein Eintrag eines im Zielsystem unbekannten Nutzers oder mit einem `dedupeKey`, der dort unter anderer ID existiert, wird übersprungen und in `imported.notificationSkipped` gezählt (nie umgehängt); Einträge alter Bundles ohne `userId` werden je aktivem Nutzer kopiert (abgeleitete ID `<id>:<userId>`, wiederholbar), ohne `category` nach der Regel von Migration `100800` (`relatedType 'JobRun'` oder leer → `SYSTEM`, sonst `SUGGESTION`). Ein alter Bundle-Wert für `Inspection.feedStatus` wird auf das Futter-Vokabular abgebildet (Annahme 33). Bewusst ausgenommen sind nur Permission (Katalog aus dem Code), RefreshToken, ConsumedToken, ApiKey (Annahme 14), IdempotencyRecord (Annahme 11) sowie die Betriebsmodelle des Plattform-Rückgrats DomainEvent und DomainEventDelivery (Outbox – Seiteneffekte dürfen nach einem Restore nicht erneut ausgelöst werden), WebhookDelivery (Zustellprotokoll und Wiederholungs-Warteschlange – sonst gingen alte Ereignisse erneut an Empfänger), JobRun (Laufhistorie der CronJobs dieses Deployments) und ThrottlerHit (UNLOGGED-Zähler des Rate-Limits). Die Telegram-Tabellen werden nie exportiert: `TelegramLink` (Chat-Bindung an den Bot dieses Deployments; Nutzer verknüpfen nach einem Restore neu, wie bei ApiKey), `TelegramLinkToken` (Einmal-Tokens, nur Minuten gültig), `NotificationDelivery` (Zustell-Warteschlange; ein Restore schickte alte Nachrichten erneut) und `TelegramPollState` (Update-Offset und Abfrage-Lease dieses Deployments). Die Liste mit Begründung steht in `MODELS_EXCLUDED_FROM_BACKUP`, ein Test erzwingt sie für jedes neue Prisma-Modell. Import ist upsert-basiert (Rollen/Berechtigungen über `key`/`resource+action` statt roher `id`, damit ein Restore auch in ein anderes Deployment funktioniert) und läuft in einer einzigen `$transaction`.
|
||||
- **Export/Import:** `BackupService.exportAll()`/`.importAll()` sichert alle fachlichen und Konfigurationsmodelle (Betriebsdaten inkl. Herstellung, Rohstoffe, Bewegungsbuch und Shop-Anfragen, Nummernkreise, Benutzer/Rollen/Rechte, Audit-Log, Website-/Backup-/Kalender-Einstellungen samt Kalender-Outbox, hochgeladene Dokumente inkl. Dateiinhalt als Base64) als eine versionierte JSON-Datei (Bundle-Version 3; ältere Bundles bleiben einspielbar). Neu im Bundle: `Suggestion` (Import nach `colony`, vor `task`, weil `Task.sourceSuggestionId` darauf zeigt; `decidedByUserId` wie andere Benutzer-IDs, `null` bleibt `null`; nur aus versiegelten Dateien, sonst kämen verworfene oder übernommene Vorschläge nach einem Restore als neue zurück) und `NotificationPreference`. Seit T4b zusätzlich `PhenologyReport` (eigene Beobachtungen; Import nach `winterCheck`, Benutzer-IDs wie bei anderen Pflicht-Benutzern umgesetzt; nur aus versiegelten Dateien). `ApiaryPhenology` (abgeleiteter Saisonzustand, der Job `daily-evaluation` berechnet ihn neu) und `ApiaryWeatherDay` (Wetter-Cache, der Worker holt ihn neu) sind ausgenommen. Alte Bundles, deren `HoneyBatch`-Zeilen kein `initialAmount` tragen, werden beim Import wie in Migration `t4_honey_ledger` zurückgerechnet (Annahme 44, `src/backup/legacy-honey-ledger.ts`): `initialAmount` wird gesetzt; die `BOTTLING`-Buchungen mit der stabilen ID `legacy-bottling:<Abfüllung>` entstehen nur aus versiegelten Dateien, nach dem Abschnitt `batchMovement`, und werden bei einem erneuten Import nie überschrieben. Eine unversiegelte Datei setzt nur `initialAmount` bei Chargen, die es noch nicht gibt. Nach dem Honig-Teil des Imports prüft eine SQL-Abfrage die Invariante der importierten Chargen (`honeyLedgerViolations`) in der Import-Transaktion: bei Treffern Warnung im Log mit den IDs und `imported.honeyLedgerViolations = <Anzahl>` (Schlüssel nur bei > 0); der Import scheitert deshalb nicht. Meldungen: Ein Eintrag eines im Zielsystem unbekannten Nutzers oder mit einem `dedupeKey`, der dort unter anderer ID existiert, wird übersprungen und in `imported.notificationSkipped` gezählt (nie umgehängt); Einträge alter Bundles ohne `userId` werden je aktivem Nutzer kopiert (abgeleitete ID `<id>:<userId>`, wiederholbar), ohne `category` nach der Regel von Migration `100800` (`relatedType 'JobRun'` oder leer → `SYSTEM`, sonst `SUGGESTION`). Ein alter Bundle-Wert für `Inspection.feedStatus` wird auf das Futter-Vokabular abgebildet (Annahme 33). Seit T6 (Abschnitt 12) gehören `VeterinaryMedicine`, `VeterinaryMedicineLot`, `VeterinaryMedicineMovement`, `ComplianceSettings`, `AuthorityNotice`, `ApiaryRestriction` und `ComplianceAcknowledgement` zum versiegelten Bundle; keine dieser Tabellen steht in `MODELS_EXCLUDED_FROM_BACKUP` oder `LEGACY_UNSEALED_TABLES`, eine unversiegelte Altdatei überspringt sie und meldet sie unter `skipped`. Beim Einspielen stehen Mittel und Packung vor den Behandlungen, die Buchungen der Packung danach, Sperrbezirke folgen den Ständen. Behandlungen einer unversiegelten Datei verlieren `medicineId`, `medicineLotId` und `doseQuantity` (ohne Bewegungsbuch gäbe es eine Behandlung mit Packung, aber ohne Buchung, also eine Fälschung des Bestands); die Zahl steht als `imported.treatmentMedicineLinksDropped` in der Zusammenfassung, dazu eine Log-Warnung. Eine versiegelte Wiederherstellung ersetzt das Packungsbuch (Annahme 63). Hält im Zielsystem ein Entwurf den `openKey` einer Behördenanzeige unter anderer Id, gewinnt dieser Entwurf: Die Anzeige der Datei wird samt ihren Dokumenten (`AUTHORITY_NOTICE`) übersprungen und als `imported.authorityNoticeSkipped` bzw. `imported.authorityNoticeDocumentsSkipped` gezählt, die Ids stehen in `summary.skippedNoticeIds` (Annahme 64). Die Wiederherstellung schreibt keine Domänenereignisse, also auch kein `ColonyCreated` (Abschnitt 12.5). Bewusst ausgenommen sind nur Permission (Katalog aus dem Code), RefreshToken, ConsumedToken, ApiKey (Annahme 14), IdempotencyRecord (Annahme 11) sowie die Betriebsmodelle des Plattform-Rückgrats DomainEvent und DomainEventDelivery (Outbox – Seiteneffekte dürfen nach einem Restore nicht erneut ausgelöst werden), WebhookDelivery (Zustellprotokoll und Wiederholungs-Warteschlange – sonst gingen alte Ereignisse erneut an Empfänger), JobRun (Laufhistorie der CronJobs dieses Deployments) und ThrottlerHit (UNLOGGED-Zähler des Rate-Limits). Die Telegram-Tabellen werden nie exportiert: `TelegramLink` (Chat-Bindung an den Bot dieses Deployments; Nutzer verknüpfen nach einem Restore neu, wie bei ApiKey), `TelegramLinkToken` (Einmal-Tokens, nur Minuten gültig), `NotificationDelivery` (Zustell-Warteschlange; ein Restore schickte alte Nachrichten erneut) und `TelegramPollState` (Update-Offset und Abfrage-Lease dieses Deployments). Die Liste mit Begründung steht in `MODELS_EXCLUDED_FROM_BACKUP`, ein Test erzwingt sie für jedes neue Prisma-Modell. Import ist upsert-basiert (Rollen/Berechtigungen über `keLine truncated
|
||||
- **Automatischer Zeitplan:** Kein Timer im API-Prozess. Der CronJob `apicore-job-app-backup` (`0 * * * *`, Europe/Berlin, `concurrencyPolicy: Forbid`) startet stündlich `node dist/cli.js app-backup` (`BackupSchedulerService.runIfDue`). Der Job liest Pfad (`BACKUP_STORAGE_PATH`), Cron-Ausdruck und Aufbewahrung (`BACKUP_RETENTION_COUNT`) frisch – Env-Variable vor GUI-Wert (Verwaltung > Backup) –, vergleicht den nächsten Termin nach der mtime der neuesten Backup-Datei (`isBackupDue`, Zeitzone Europe/Berlin, „jetzt“ = DB-Uhr) und schreibt nur, wenn er erreicht ist; alte Stände rotiert er nach der Aufbewahrung. Prüfung und Schreiben laufen unter einem DB-Advisory-Lock, zwei Job-Pods schreiben nie doppelt. Ohne Pfad endet der Lauf erfolgreich mit `{ written: false, reason: 'no-path' }`; ein Fehler lässt den `JobRun` fehlschlagen (Benachrichtigung an die Inhaber von `backup:configure`). GUI-Änderungen und Importe gelten ab der nächsten stündlichen Prüfung. „Jetzt sichern“ bleibt in der API und schreibt immer. `GET /backup/schedule` liefert zusätzlich `lastJobRun` (Status, Start, Ende, Fehler); die Seite zeigt „Wird stündlich geprüft · letzter Lauf …“. Die Lock-Transaktion der Fälligkeitsprüfung hält eine Verbindung bis zum Ende des Schreibens (Timeout 1 h = `activeDeadlineSeconds`; der Export nutzt andere Verbindungen, der Pool braucht mindestens zwei). Sie braucht weder `idle_in_transaction_session_timeout` noch einen Transaction-Mode-PgBouncer: Postgres wird direkt angesprochen, und der Lock hängt an der Transaktion. Scheitert der Commit, nachdem die Datei schon geschrieben wurde, bleibt die Datei bestehen, der Lauf steht aber kosmetisch auf `FAILED`; der nächste Lauf sieht die Datei an ihrer mtime. Das Aufräumen von Idempotenz-Einträgen (90 Tage) und verbrauchten Einmal-Tokens läuft einmal täglich im CronJob `apicore-job-cleanup` (Abschnitt 10, „Jobs“).
|
||||
- **Restore:** Über `POST /backup/import` (bzw. den Import-Dialog unter Verwaltung > Backup) eine zuvor exportierte Bundle-Datei einspielen. Import-Limit `BACKUP_MAX_IMPORT_BYTES` (Standard 50 MB, höchstens 256 MB, weil der Upload vollständig im RAM des 512-Mi-Pods verarbeitet wird); Export und Zeitplan prüfen jede Sicherung dagegen und warnen in Log und UI (Verwaltung > Backup), bevor eine Datei entsteht, die sich im Notfall nicht mehr einspielen ließe.
|
||||
|
||||
@@ -273,6 +339,7 @@ Grundlage: OWASP API Security Top 10 (2023) und OWASP ASVS Level 2. Umsetzung un
|
||||
| Ausgehende Aufrufe | Webhooks: nie aus der Anfrage heraus gesendet, sondern über die Zustelltabelle `WebhookDelivery` (Warteschlange und Zustellprotokoll), die der Worker abarbeitet; Ziel-IP beim Verbindungsaufbau geprüft (kein DNS-Rebinding), nur Port 80/443, https in Produktion, keine Weiterleitungen, 5 s Leerlauf-Timeout und 10 s Frist je Versuch (danach wird die Verbindung abgebrochen); nur eine `2xx`-Antwort gilt als zugestellt, sonst Wiederholung nach der Outbox-Regel (30 s bis 6 h, nach 8 Versuchen `FAILED`); stabile Delivery-ID (`X-ApiCore-Delivery` = `WebhookDelivery.id`, mit gleichem Body über alle Wiederholungen); Signatur über Zeitstempel+ID+Body; Antwortkörper wird nie gelesen, `lastError` nur über `loggableError()` |
|
||||
| Wetter und Telegram | Wetter (Open-Meteo) nur aus der Worker-Schleife `phenology-weather` und der Wetter-Anzeige, über `src/weather/`: nur https-URLs aus der Konfiguration, keine Weiterleitungen (`redirect: 'error'`), 8 s Frist, Antwort höchstens 1 000 000 Byte, Fehlertexte fest (kein URL, keine Ursache, kein Schlüssel). Telegram (`api.telegram.org`) nur aus Worker-Schleifen über `TelegramClient` (`src/telegram/`): Klartext ohne `parse_mode`, Linkvorschau aus, Text höchstens 600 Zeichen ohne Steuer- und Richtungszeichen, keine Weiterleitungen, Antwort höchstens 256 kB; der Token steht nie in Logs oder Fehlern (`TelegramApiError` trägt Methode, Status, bereinigte Beschreibung, `retry_after` 1–3600 s, keine URL). Wächter `src/common/no-network-outside-loops.spec.ts`: Wetter-Hosts nur in `src/weather/`, `api.telegram.org` nur in `src/telegram/`, `fetch(` und Netzwerkpakete nur in den erlaubten Dateien (Graph-Client, Passwort-Prüfung, Webhook-Zustellung, Worker-Health, Wetter, Telegram), nie in Handlern oder Jobs; `handler-contract.spec.ts` verbietet den Import von `telegram-client` in Handlern |
|
||||
| Transport/Antworten | Alle API-Antworten tragen `Cache-Control: no-store` und `Pragma: no-cache`; einzige Ausnahme ist die erfolgreiche (200) öffentliche Herkunftsantwort `GET /public/batches/:lot` mit `Cache-Control: public, max-age=300, s-maxage=3600` (ohne Pragma, am Cloudflare-Edge cachebar), Fehlerantworten bleiben `no-store`; `Cache-Control: no-store` (außer öffentliche Chargen-Seite), CSP `default-src 'none'`, `frame-ancestors 'none'`, keine ETags; Produktion startet nur mit https-`FRONTEND_ORIGIN` und sicheren Cookies |
|
||||
| Frontend-CSP | `src/proxy.ts` setzt für die Oberfläche `script-src 'self' 'unsafe-inline'` und `style-src 'self' 'unsafe-inline'` (dazu u. a. `media-src 'self' blob:` für die eigene Aufnahme). `'unsafe-inline'` ist ein getragenes Risiko: Next.js liefert eigene Inline-Bootstrap-Skripte, und sobald `script-src` einen Hash oder Nonce enthält, ignorieren Browser `'unsafe-inline'` und blockieren diese; ein Nonce würde jede Seite dynamisch rendern. Das Darstellungs-Skript im `<head>` (T5 A2) ist eine Konstante ohne Nutzerdaten. Wird die CSP verschärft, Hash für `appearanceScript()` ergänzen. |
|
||||
| Rate-Limits | Throttler vor der Authentifizierung, Zähler in der UNLOGGED-Tabelle `ThrottlerHit` und damit über alle Pods geteilt (eine Upsert-Anweisung, ausschließlich DB-Uhr `now()`; 100/min, Login/MFA/Refresh/Logout 10/min, öffentliche Chargen 30/min); Client-IP über `TRUST_PROXY` (IPv6 je /64); bei DB-Fehler schlägt die Anfrage fehl (fail-closed) – nur die Liveness `GET /health` ist ausgenommen, damit ein DB-Ausfall nicht alle Pods neu startet; abgelaufene Zeilen räumt der Job `cleanup` auf |
|
||||
| Daten | Backups verschlüsselt und signiert, Dateien 0600; CSV-Export ohne Formel-Injection; Logs ohne Query-Strings |
|
||||
|
||||
@@ -321,7 +388,7 @@ Die Wirkung des Handlers und `DONE` werden gemeinsam committet. Die Exklusivitä
|
||||
|
||||
**Behandlungen, Fütterungen und Ernten.** Anlegen schreibt Datensatz, Audit-Eintrag und `TreatmentRecorded`, `FeedingRecorded` bzw. `HarvestRecorded` in einer Transaktion, Ändern `TreatmentCorrected`, `FeedingCorrected` bzw. `HarvestCorrected`. Kalendereintrag (`calendar-sync.*`), Webhook (`treatment.created`, `feeding.created`, `harvest.created`) und Folgekontrolle (`automation.treatment-follow-up`, `automation.feeding-follow-up`) entstehen ausschließlich in den Handlern; Korrekturen lösen nur den Kalender-Handler aus, keine Folgekontrolle und keinen Webhook. Die Fälligkeit der Folgekontrolle gilt ab dem Datum der Maßnahme. `update` sperrt die Zeile und liest „vorher“ danach über `tx`; die Behandlung sperrt beim Anlegen das Volk und liest es über `tx`, bei Ernten läuft die Gewichtsprüfung unter der Sperre.
|
||||
|
||||
**Völker.** `ColoniesService` und `WinterChecksService` schreiben Audit, Datenänderung und Ereignis in einer Transaktion. Ändert sich `status` oder `healthStatus` (update, merge je vereinigtem Volk, dissolve, reactivate, Auswinterungsverlust mit `markColonyDeceased`), entsteht `ColonyStatusChanged { from, to }`; beim Übergang von lebend nach beendet (`DISSOLVED`, `SOLD`, `DECEASED`, `MERGED`) zusätzlich `ColonyEnded { status, endedOn, releasedQueenId, via }` (Abschnitt 11.7). `automation.colony-health` hört auf `ColonyStatusChanged`. Die Operationen sperren das Volk (`lockColony`: Sperre, dann Neulesen über `tx`) und prüfen darunter, ob es noch lebt; `merge` sperrt alle vereinigten Völker mit einer Anweisung (`lockRowsForUpdate`). `colony.created` bleibt im Altpfad `WebhooksService.dispatch` (Annahme 11). Das Teilen schreibt `ColonySplit`, die Königin-Zuordnung `QueenAssigned` in ihrer Transaktion (Handler-Übersicht unten); Kalender, Webhook und Ketten folgen aus diesen Ereignissen.
|
||||
**Völker.** `ColoniesService` und `WinterChecksService` schreiben Audit, Datenänderung und Ereignis in einer Transaktion. Ändert sich `status` oder `healthStatus` (update, merge je vereinigtem Volk, dissolve, reactivate, Auswinterungsverlust mit `markColonyDeceased`), entsteht `ColonyStatusChanged { from, to }`; beim Übergang von lebend nach beendet (`DISSOLVED`, `SOLD`, `DECEASED`, `MERGED`) zusätzlich `ColonyEnded { status, endedOn, releasedQueenId, via }` (Abschnitt 11.7). `automation.colony-health` hört auf `ColonyStatusChanged`. Die Operationen sperren das Volk (`lockColony`: Sperre, dann Neulesen über `tx`) und prüfen darunter, ob es noch lebt; `merge` sperrt alle vereinigten Völker mit einer Anweisung (`lockRowsForUpdate`). `colony.created` bleibt im Altpfad `WebhooksService.dispatch` (Annahme 11). Neu sind seit T6 `ColonyCreated`, `ColonyMoved`, `ApiaryChanged` und `TskReferenceDayReached` (Abschnitt 12.5); `ColonyCreated` schreiben auch Teilen und CSV-Import. Das Teilen schreibt `ColonySplit`, die Königin-Zuordnung `QueenAssigned` in ihrer Transaktion (Handler-Übersicht unten); Kalender, Webhook und Ketten folgen aus diesen Ereignissen.
|
||||
|
||||
**Bestand und Abfüllung.** Bestandsbuchungen kündigen sich über `StockChanged { bottlingBatchIds, productIds, rawMaterialKinds }` an. Das Ereignis entsteht in derselben Transaktion wie Bewegung, Audit-Eintrag und Datenänderung, über `StockService.recordChange(tx, change, actingUserId, aggregate)`. Eine leere Änderung erzeugt kein Ereignis, jede ID und jede Sorte steht nur einmal darin.
|
||||
- Entnahme und Inventur hängen das Ereignis an die Bewegung (`BatchMovement`). Bei einer Rohstoff-Charge steht deren Sorte in `rawMaterialKinds`.
|
||||
@@ -333,7 +400,7 @@ Daraus folgen die Webhooks `batch.updated` und `stock.changed` (`webhooks.forwar
|
||||
|
||||
**Sammelerfassung am Stand.** `POST /treatments/bulk`, `/feedings/bulk` und `/varroa-measurements/bulk` legen in einer Transaktion (`runBulk`, `src/common/bulk/run-bulk.ts`) je Volk einen eigenen Datensatz an: höchstens `BULK_MAX_COLONIES` = 100 Völker, Timeout `BULK_TRANSACTION_TIMEOUT_MS` = 15 s. Es gilt alles oder nichts: `assertLivingColonies` sperrt die Völker per `lockRowsForShare` (`SELECT … FOR SHARE`, aufsteigend nach id) und liest sie neu. Ist ein Volk unbekannt oder beendet, wird nichts gespeichert, und die Antwort 400 nennt die Völker in `invalidColonyIds`; der Client kann ohne sie erneut senden. Jeder Datensatz bekommt seinen eigenen Audit-Eintrag und sein eigenes `TreatmentRecorded`, `FeedingRecorded` bzw. `VarroaMeasured`; diese Ereignisse tragen optional `bulkId` (`RecordedForColony`), bei Einzelanlage fehlt das Feld. Kalender, Folgekontrolle, Varroa-Schwelle und Webhooks folgen daher je Volk unverändert aus den Ereignissen. Einzel- und Sammelanlage nutzen dieselbe Datenaufbereitung; bei Behandlungen kommt der Stand je Volk aus der gesperrten Zeile (Bestandsbuch). Die Chargennummer ist die Arzneimittel-Charge der Packung: einmal eingegeben, für alle Datensätze gleich, nie erzeugt. Die Gruppierung leistet `bulkId`. Varroa nimmt `entries` mit Milbenzahl je Volk (keine gemeinsame Milbenzahl), die Tagesrate wird je Eintrag wie bei der Einzelmessung abgeleitet. Die Einzel-Endpunkte akzeptieren weiter beendete Völker, nur die Sammelerfassung prüft auf lebende.
|
||||
|
||||
**Zeilensperren.** `src/prisma/row-lock.ts` bietet `lockRowForUpdate` (eine Zeile, liefert, ob sie existiert), `lockRowsForUpdate` und `lockRowsForShare` (mehrere Zeilen mit einer Anweisung, aufsteigend nach id, damit sich überlappende Mengen nicht gegenseitig blockieren). Sie laufen nur mit einem Transaktions-Client, Tabellennamen kommen aus einer festen Liste (nie aus Eingaben). Muster für jedes Ändern: sperren, dann „vorher“ über `tx` neu lesen, nie die Vorab-Lesung verwenden. Die Reihenfolge der Sperr-Karte (`LOCK_ORDER`) gilt für alle Tabellen mit einer Ausnahme: `Apiary` kommt vor `Colony` (Annahme 50).
|
||||
**Zeilensperren.** `src/prisma/row-lock.ts` bietet `lockRowForUpdate` (eine Zeile, liefert, ob sie existiert), `lockRowsForUpdate` und `lockRowsForShare` (mehrere Zeilen mit einer Anweisung, aufsteigend nach id, damit sich überlappende Mengen nicht gegenseitig blockieren). Sie laufen nur mit einem Transaktions-Client, Tabellennamen kommen aus einer festen Liste (nie aus Eingaben). Muster für jedes Ändern: sperren, dann „vorher“ über `tx` neu lesen, nie die Vorab-Lesung verwenden. Die Reihenfolge der Sperr-Karte (`LOCK_ORDER`) gilt für alle Tabellen; `Apiary` steht seit T6 an erster Stelle, also vor `Colony` (Annahme 50).
|
||||
|
||||
**Tests.** e2e-Tests haben keinen Worker. Sie rufen nach der Anfrage `drainDomainEvents(app, [aggregateId])` aus `test/utils/domain-events.ts` auf. Das arbeitet nur die Ereignisse dieser Korrelationen ab, sodass parallele e2e-Dateien sich nicht stören.
|
||||
|
||||
@@ -346,7 +413,7 @@ Daraus folgen die Webhooks `batch.updated` und `stock.changed` (`webhooks.forwar
|
||||
- `SeasonPhaseChanged` (Aggregat `Apiary`, Payload `apiaryId`, `phase`, `segment`, `previousPhase`, `previousSegment`, `source`) schreibt `PhenologyStateService`, wenn sich Phase oder Abschnitt eines Stands ändern: höchstens eines je Stand und Tag über `dailyDedupeKey`. Beim ersten Zustand eines Jahres wird gegen den Kalenderzustand verglichen; ein unveränderter Zustand erzeugt kein Ereignis. Der Handler `autopilot.apiary-sync` hört darauf; eine Einzelmeldung je Saisonwechsel gibt es bewusst nicht (Annahme 47).
|
||||
- `PhenologyRecomputeRequested { apiaryId, allowBackward, day }` (Aggregat `Apiary`, ohne Schlüssel) schreibt der Handler `phenology.recompute` je aktivem Stand, wenn eine Meldung für alle Stände gilt; `phenology.recompute-apiary` rechnet damit einen Stand je Zustellung.
|
||||
- `WinterCheckRecorded { colonyId }` (Aggregat `WinterCheck`) schreiben `WinterChecksService.create` und `update` in ihrer Transaktion (ein Verschieben auf ein anderes Volk meldet auch das alte); `autopilot.colony-sync` löst damit A9/A10 sofort auf.
|
||||
`Apiary`, `PhenologyReport`, `Extraction` und `HoneyBatch` stehen am Ende der Sperr-Karte (`LOCKABLE_TABLES`, Schlüssel `id`); `NotificationDelivery` steht ganz zuletzt (Abschnitt 11.13).
|
||||
`PhenologyReport`, `Extraction` und `HoneyBatch` stehen hinter `NotificationPreference` am Ende der Sperr-Karte (`LOCKABLE_TABLES`, Schlüssel `id`); `Apiary` steht seit T6 an erster Stelle (Annahme 50). `NotificationDelivery` folgt danach, ihr schließen sich die T6-Tabellen an (Abschnitte 11.13 und 12.1).
|
||||
|
||||
**Handler-Übersicht (T4).** Alle Handler laufen nach dem Vertrag oben (eigene Transaktion, nur über `tx` schreiben, kein Netzwerk). Die Handler der Ketten, des Autopilots und der Wartezeit prüfen zuerst das Volk: Zeile sperren (`lockRowForUpdate`; fehlt es, ist nichts zu tun), Status über `tx` neu lesen (beendet: nichts), Regel über `readRule(tx, …)` lesen (abgeschaltet: nichts vorschlagen).
|
||||
|
||||
@@ -373,6 +440,8 @@ Daraus folgen die Webhooks `batch.updated` und `stock.changed` (`webhooks.forwar
|
||||
| `calendar-sync.queen-assignment` | `QueenAssigned` | `enqueueIn(tx, 'QUEEN_ASSIGNMENT', historyId)`. |
|
||||
| `calendar-sync.withdrawal` | `TreatmentRecorded`, `TreatmentCorrected` | `enqueueIn(tx, 'WITHDRAWAL', treatmentId)` (Abschnitt 11.8). |
|
||||
| `webhooks.forward` | erweitert um `QueenAssigned`, `HoneyBatchRecorded` | `queen.replaced`, `batch.created` (siehe „Webhook-Zustellung“). `HoneyBatchCorrected` sendet nichts. |
|
||||
| `compliance.herd-change` | `ColonyCreated`, `ColonyMoved`, `ColonyStatusChanged` (lebend ↔ beendet), `ApiaryChanged` | HINWEIS „Bestand geändert …“ (Kategorie `COMPLIANCE`, höchstens eine ungelesene je Nutzer), legt nie eine Anzeige an (Abschnitt 12.9). |
|
||||
| `compliance.tsk-reference-day` | `TskReferenceDayReached` | TSK-Entwurf (falls keiner offen) und WARNUNG „TSK-Stichtag …“; still bei gesendeter Meldung (Abschnitt 12.9). |
|
||||
|
||||
**Worker-Schleife `phenology-weather`** (T4b). Takt 3 600 000 ms, kein Weckkanal (keine Outbox); der erste Durchlauf folgt 10 s nach dem Start des Workers (`WEATHER_FIRST_TICK_DELAY_MS`). Ein Takt ruft `WeatherHistoryService.syncOnce(berlinToday(), signal)` auf und holt die fehlenden Tagesmittel der aktiven Stände mit Koordinaten (Ablauf und Regeln: Abschnitt 11.11). Die Schleife schreibt nur `ApiaryWeatherDay`: kein Ereignis, keine Meldung. Die Loops liegen in einer Karte nach Namen; `WorkerLoop.channel` ist optional. Zu den LISTEN-Kanälen kommt `notification_delivery` (Abschnitt 11.13). Der Test `test/worker-runtime.e2e-spec.ts` ersetzt `WEATHER_HISTORY_SOURCE` durch eine Attrappe, weil die Schleife sonst für jeden Stand der geteilten Test-DB den echten Dienst aufriefe.
|
||||
|
||||
@@ -432,6 +501,8 @@ Das Ergebnis zählt jede Kategorie (`idempotencyRecords`, `consumedTokens`, `thr
|
||||
|
||||
**`rekey`** (nur von Hand, CronJobs `apicore-job-rekey` und `apicore-job-rekey-dry-run` mit `suspend: true`): siehe Annahme 22.
|
||||
|
||||
**`voice-transcribe`** (CronJob alle 2 Minuten, Phasen `--phase=fetch` und `--phase=ingest` um den Whisper-Container): Abschnitt 14.3.
|
||||
|
||||
**Tests.** `test/jobs.e2e-spec.ts` ruft `runCli([...])` mit dem echten `JobsModule` auf, wie `node dist/cli.js`. `test/daily-evaluation.e2e-spec.ts` ruft `TimeEventsStep.run(Tag)` mit Tagen in den Jahren 2001 und 2002 auf: Der Schritt wertet die ganze geteilte Test-DB aus, so bleiben die Ereignisse paralleler e2e-Dateien unberührt (und es entstehen keine `JobRun`-Zeilen, die `jobs.e2e-spec.ts` zählt). `test/rekey.e2e-spec.ts` setzt nur `*_PREVIOUS`, weil der Job jede Zeile der geteilten Test-DB besucht und die anderen e2e-Prozesse mit denselben aktuellen Schlüsseln weiterlesen müssen.
|
||||
|
||||
### System-Seite
|
||||
@@ -444,7 +515,7 @@ Die Seite „Verwaltung > System“ (Rechte `system:read` zum Ansehen, `system:m
|
||||
|
||||
## 11. Logik-Ketten und Saison-Autopilot (T4a bis T4c)
|
||||
|
||||
Regeln, Ketten und der Autopilot schreiben Vorschläge statt Aufgaben; ein Mensch übernimmt oder verwirft. Alles hängt am Ereignis-Rückgrat (Abschnitt 10, Handler-Übersicht) und am Job `daily-evaluation`. Entwurf: Spec `docs/superpowers/specs/2026-10-13-t4-logik-ketten-design.md`. T4b und T4c ergänzen Pflanzenentwicklung und Wetter (11.11), Honig-Kette und Bewegungsbuch (11.12) sowie Telegram (11.13). Noch offen sind die Bestätigung beim Wassergehalt (Regel `HONEY_WATER_CONTENT`) und das Verknüpfen und Abfragen von Telegram (Task 36).
|
||||
Regeln, Ketten und der Autopilot schreiben Vorschläge statt Aufgaben; ein Mensch übernimmt oder verwirft. Alles hängt am Ereignis-Rückgrat (Abschnitt 10, Handler-Übersicht) und am Job `daily-evaluation`. Entwurf: Spec `docs/superpowers/specs/2026-10-13-t4-logik-ketten-design.md`. T4b und T4c ergänzen Pflanzenentwicklung und Wetter (11.11), Honig-Kette und Bewegungsbuch (11.12) sowie Telegram (11.13); T4 ist vollständig (Stand 2026-10-15).
|
||||
|
||||
### 11.1 Vorschläge
|
||||
|
||||
@@ -452,7 +523,7 @@ Regeln, Ketten und der Autopilot schreiben Vorschläge statt Aufgaben; ein Mensc
|
||||
|
||||
**PLAN und DO.** `PLAN` hat mehrere Termine oder ist heute fällig; Übernehmen legt je Schritt eine Aufgabe an (Basisdatum aus dem Beleg plus Versatz, Titel aus `PLAN_STEP_TITLES`, ein Fensterschritt trägt „Zeitfenster bis TT.MM.“). Ein gewähltes Datum verschiebt den ganzen Plan, sodass Schritt 1 darauf liegt; ohne Plan und Datum ist die Aufgabe heute (Berliner Tag) fällig. `DO` ist genau eine Aufgabe und braucht ein Datum (eigenes oder `dueDate` des Vorschlags), sonst 400 „Bitte ein Datum wählen.“. „Als Aufgabe planen“ ist Übernehmen mit Datum. Titel und Beschreibung kommen aus `renderSuggestion` mit dem `actionTemplate` der Regel. Die Aufgabe entsteht über `TasksService.createInTx` (Audit, `TaskCreated`, danach Kalender und Webhook). `sourceInspectionId` wird nur gesetzt, wenn die Durchsicht aus dem Beleg noch existiert (unter `FOR SHARE` geprüft). Übernehmen für ein beendetes oder unbekanntes Volk: 409 „Das Volk ist nicht mehr aktiv.“; ein `assignedUserId`, der nicht existiert oder inaktiv ist: 400 mit `issues`.
|
||||
|
||||
**Übergänge.** Jede Entscheidung sperrt die Zeile `Suggestion` (Sammelrouten in id-Reihenfolge), liest „vorher“ danach, prüft den Status (409 `{ message: 'Der Vorschlag ist nicht mehr offen.', status }`) und setzt ihn per Compare-and-Set in SQL gegen `now()`; der Audit-Eintrag (`Suggestion UPDATE`) steht in derselben Transaktion. Entscheidungen sperren nie das Volk; `proposeIn` sperrt zuerst die Volkszeile, dann die Regelzeile (`LOCK_ORDER` in `row-lock.ts`: Colony, Suggestion, Task, Queen, AutomationRule, …, NotificationPreference; Ausnahme: `Apiary` vor `Colony`, Annahme 50).
|
||||
**Übergänge.** Jede Entscheidung sperrt die Zeile `Suggestion` (Sammelrouten in id-Reihenfolge), liest „vorher“ danach, prüft den Status (409 `{ message: 'Der Vorschlag ist nicht mehr offen.', status }`) und setzt ihn per Compare-and-Set in SQL gegen `now()`; der Audit-Eintrag (`Suggestion UPDATE`) steht in derselben Transaktion. Entscheidungen sperren nie das Volk; `proposeIn` sperrt zuerst die Volkszeile, dann die Regelzeile (`LOCK_ORDER` in `row-lock.ts`: Colony, Suggestion, Task, Queen, AutomationRule, …, NotificationPreference; davor seit T6 `Apiary`, Annahme 50).
|
||||
|
||||
| von | nach | Auslöser |
|
||||
|---|---|---|
|
||||
@@ -566,7 +637,7 @@ Ein einziger Fenster-Helfer (`src/treatments/withdrawal-window.ts`, Annahme 10)
|
||||
|
||||
### 11.9 Meldungen je Nutzer, Erinnerungen und Morgenübersicht
|
||||
|
||||
**Meldungen.** Annahme 39. `GET /notifications` (eigene, nach aktuellen Rechten gefiltert, höchstens 100), `POST /notifications/read-all` (vor `:id/read` deklariert), `POST /notifications/:id/read` (404 für fremde, unbekannte oder verborgene). Kategorien (`NotificationCategory`) u. a. `SUGGESTION`, `SYSTEM`, `WITHDRAWAL`, `TASK_DUE`, `DIGEST`; die Glocke zeigt das Kategoriewort, „Alle gelesen“ und öffnet interne `link`-Pfade (nur mit führendem `/`, nie `//` oder `/\`). Einstellungen je Nutzer in `NotificationPreference`: `GET/PATCH /profile/notification-settings` (`@AnyAuthenticatedUser`, API-Schlüssel erhalten 403): `taskDueEnabled`, `digestEnabled`, `digestTime` (05:00–12:00 einschließlich), Ruhezeit nur als Paar (beide leer oder beide gesetzt); `telegramEnabled` schreibt dieser Endpunkt nie (nur der Telegram-Sender setzt es auf aus, Abschnitt 11.13). Profil > Benachrichtigungen bietet „Erinnerung je Aufgabe“, „Morgenübersicht“ (Uhrzeit, Standard 06:30) und „Ruhezeit von/bis“; gesendet wird nur Geändertes.
|
||||
**Meldungen.** Annahme 39. `GET /notifications` (eigene, nach aktuellen Rechten gefiltert, höchstens 100), `POST /notifications/read-all` (vor `:id/read` deklariert), `POST /notifications/:id/read` (404 für fremde, unbekannte oder verborgene). Kategorien (`NotificationCategory`) u. a. `SUGGESTION`, `SYSTEM`, `WITHDRAWAL`, `TASK_DUE`, `DIGEST`, `SEASON` und seit T6 `COMPLIANCE` („Behörden & Prüfung“, für die Hinweise „Bestand geändert“ und „TSK-Stichtag“, Abschnitt 12.1); die Glocke zeigt das Kategoriewort, „Alle gelesen“ und öffnet interne `link`-Pfade (nur mit führendem `/`, nie `//` oder `/\`). Einstellungen je Nutzer in `NotificationPreference`: `GET/PATCH /profile/notification-settings` (`@AnyAuthenticatedUser`, API-Schlüssel erhalten 403): `taskDueEnabled`, `digestEnabled`, `digestTime` (05:00–12:00 einschließlich), Ruhezeit nur als Paar (beide leer oder beide gesetzt); `telegramEnabled` schreibt dieser Endpunkt nie (nur der Telegram-Sender setzt es auf aus, Abschnitt 11.13). Profil > Benachrichtigungen bietet „Erinnerung je Aufgabe“, „Morgenübersicht“ (Uhrzeit, Standard 06:30) und „Ruhezeit von/bis“; gesendet wird nur Geändertes.
|
||||
|
||||
**Erinnerung je Aufgabe.** Handler `notifications.task-due` (`RemindersModule`, von `AppModule`, `WorkerModule` und `JobsModule` importiert) schreibt zu `TaskDue` je Empfänger eine Meldung (HINWEIS, `TASK_DUE`, Link `/tasks`, Schlüssel `task-due:<Aufgabe>:<dueOn>:<userId>`): „Heute fällig: <Titel>“, bei einem Nachhol-Ereignis „Fällig seit TT.MM.: <Titel>“. Empfänger ist der Zuständige, sonst alle aktiven Nutzer mit `tasks:complete`; immer nur mit `tasks:read` und eingeschaltetem `taskDueEnabled` (fehlende Einstellung = an). Nur offene Aufgaben (`OPEN`, `IN_PROGRESS`); eine inzwischen verschobene oder fällig-lose Aufgabe wird übersprungen.
|
||||
|
||||
@@ -668,7 +739,7 @@ Stand: Schema, Client, Prüfung beim Start, Planung, Senden, Verbinden, Empfange
|
||||
- `TELEGRAM_BOT_USERNAME` verliert ein führendes `@` und muss `^[A-Za-z][A-Za-z0-9_]{4,31}$` erfüllen, sonst gilt er als nicht gesetzt (`telegramBotAvailable()` falsch) mit Warnung.
|
||||
- Der Wächter `no-network-outside-loops.spec.ts` hält fest, dass das Netzwerk nur in den erlaubten Dateien und nur aus Schleifen genutzt wird (Abschnitt 9).
|
||||
|
||||
**Planung.** `NotificationDeliveryPlanner.planIn(db, notifications)` (Abschnitt 10, „Zustellplanung“) liest in einer Abfrage die Einstellungen (`telegramEnabled`, Verbindung, `telegramCategories`) und die DB-Uhr, legt per `createMany({ skipDuplicates })` (eindeutig je Meldung und Kanal) die Zustellungen an und weckt den Worker nur, wenn Zeilen entstanden. Standardkategorien `TASK_DUE` und `DIGEST`; `SUGGESTION`, `WITHDRAWAL`, `SEASON` und `SYSTEM` schaltet der Nutzer zu. Der Text wird nicht gespeichert, sondern beim Senden aus der Meldung gerendert. Die Zustellzeit (`availableAt`) folgt Annahme 49 (Morgenzeit, Ruhezeit, Zeitumstellung).
|
||||
**Planung.** `NotificationDeliveryPlanner.planIn(db, notifications)` (Abschnitt 10, „Zustellplanung“) liest in einer Abfrage die Einstellungen (`telegramEnabled`, Verbindung, `telegramCategories`) und die DB-Uhr, legt per `createMany({ skipDuplicates })` (eindeutig je Meldung und Kanal) die Zustellungen an und weckt den Worker nur, wenn Zeilen entstanden. Standardkategorien `TASK_DUE`, `DIGEST` und seit T6 `COMPLIANCE` (Migration `20261016100400_t6_notification_compliance_default`, Abschnitt 12.1); `SUGGESTION`, `WITHDRAWAL`, `SEASON` und `SYSTEM` schaltet der Nutzer zu. `COMPLIANCE` hat wie `SYSTEM` keine Tageszeit (nur die Ruhezeit) und ist 24 Stunden frisch. Der Text wird nicht gespeichert, sondern beim Senden aus der Meldung gerendert. Die Zustellzeit (`availableAt`) folgt Annahme 49 (Morgenzeit, Ruhezeit, Zeitumstellung).
|
||||
|
||||
**Texte** (`src/telegram/telegram-texts.ts`). `TELEGRAM_TEMPLATES` hält die festen Texte, `renderTelegramText` baut daraus den Klartext: ohne Details nur „Neue Meldung in ApiCore.“ und Link, Standardlink `/dashboard`, ein Schrägstrich am Ende von `FRONTEND_ORIGIN` wird toleriert. Höchstens 600 Zeichen nach Codepunkten; die Meldung wird mit Auslassungspunkten gekürzt, der Link bleibt ganz, Steuer- und unsichtbare Zeichen entfallen. Ohne `FRONTEND_ORIGIN` entfällt der Link (Annahme 46).
|
||||
|
||||
@@ -689,8 +760,388 @@ Stand: Schema, Client, Prüfung beim Start, Planung, Senden, Verbinden, Empfange
|
||||
|
||||
**Betrieb.** Die Karte „Telegram“ unter Verwaltung > System (Abschnitt 10) zeigt Empfänger (Lease, Alter des letzten Abrufs, `lastError`) und Sender (wartend, überfällig, fehlgeschlagen in 24 h, letzte Fehler) und erlaubt das Wiederholen fehlgeschlagener Zustellungen. Die Einstellungsansicht (`GET /profile/notification-settings`) nennt das Feld `telegram.botNameSet` (Bot-Name gesetzt; das Token kennt die api nicht), derselbe Begriff wie am System-Endpunkt. Verdrahtung des Secrets und Einrichtung des Bots: Abschnitt 7.
|
||||
|
||||
**Oberfläche: Profil > Telegram** (`TelegramLinkCard`). Der Zustand steht in einer Statuszeile (`role="status"`): „Telegram ist nicht eingerichtet.“ (ohne `botNameSet`, dann ohne Knopf), „Nicht verbunden“ oder „Verbunden mit „{Vorname}“ seit {TT.MM.JJJJ}“. „Telegram verbinden“ öffnet den `StepUpDialog`; danach erscheint der große Knopf „In Telegram öffnen“ (`target="_blank"`, `rel="noopener noreferrer"`) mit „Gültig bis {HH:MM}“ (Berliner Zeit), und der Fokus springt auf diesen Knopf; nach „Trennen“ (`ConfirmDialog`) springt er auf „Telegram verbinden“. Der Deep Link ist ein Geheimnis: Er wird nur gezeigt, wenn er mit `https://t.me/` beginnt (sonst „Der Telegram-Link ist ungültig. …“), liegt nur im Zustand der Komponente (nie im React-Query-Cache, in `localStorage`/IndexedDB oder im Log) und verschwindet bei Ablauf oder sobald der Status „verbunden“ meldet. Solange ein Link gültig und noch nicht verbunden ist, lädt die Karte den Status alle 5 Sekunden neu. Verbundene Nutzer wählen die sechs Kategorien (`ToggleChip`, während des Speicherns und offline aus) und den Schalter „Mit Details“ mit dem Hinweis „Nachrichten laufen über Server von Telegram und sind dort nicht Ende-zu-Ende verschlüsselt.“; jede Änderung geht einzeln per `PATCH`. Verbinden, Trennen und Speichern sind offline gesperrt („Nur mit Verbindung“).
|
||||
**Oberfläche: Profil > Telegram** (`TelegramLinkCard`). Der Zustand steht in einer Statuszeile (`role="status"`): „Telegram ist nicht eingerichtet.“ (ohne `botNameSet`, dann ohne Knopf), „Nicht verbunden“ oder „Verbunden mit „{Vorname}“ seit {TT.MM.JJJJ}“. „Telegram verbinden“ öffnet den `StepUpDialog`; danach erscheint der große Knopf „In Telegram öffnen“ (`target="_blank"`, `rel="noopener noreferrer"`) mit „Gültig bis {HH:MM}“ (Berliner Zeit), und der Fokus springt auf diesen Knopf; nach „Trennen“ (`ConfirmDialog`) springt er auf „Telegram verbinden“. Der Deep Link ist ein Geheimnis: Er wird nur gezeigt, wenn er mit `https://t.me/` beginnt (sonst „Der Telegram-Link ist ungültig. …“), liegt nur im Zustand der Komponente (nie im React-Query-Cache, in `localStorage`/IndexedDB oder im Log) und verschwindet bei Ablauf oder sobald der Status „verbunden“ meldet. Solange ein Link gültig und noch nicht verbunden ist, lädt die Karte den Status alle 5 Sekunden neu. Verbundene Nutzer wählen die sechs Kategorien (Stand T4c; `COMPLIANCE` liefert das Backend schon, die Karte zeigt sie mit T6 Task 18; `ToggleChip`, während des Speicherns und offline aus) und den Schalter „Mit Details“ mit dem Hinweis „Nachrichten laufen über Server von Telegram und sind dort nicht Ende-zu-Ende verschlüsselt.“; jede Änderung geht einzeln per `PATCH`. Verbinden, Trennen und Speichern sind offline gesperrt („Nur mit Verbindung“).
|
||||
|
||||
**Step-up** (`src/components/auth/step-up-dialog.tsx`, geteilt mit dem Backup-Import; `pendingLabel`, beim Import „Wird eingespielt…“). Der Dialog fragt das aktuelle Passwort und bei MFA den 6-stelligen Code; `onConfirm(proof)` darf werfen, dann bleibt er offen, leert die Felder, fokussiert das Passwortfeld und zeigt den deutschen Grund in einer dauerhaften Live-Region. Während der Ausführung sind die Eingaben `readOnly`, Esc, Hintergrund und Schließen-Knopf wirkungslos. Die Felder leben nur, solange der Dialog offen ist. Ein fehlgeschlagener Import erscheint im Dialog statt als Toast. Alle Step-up-Aufrufe senden mit `refreshOn401: false` (Annahme 56): `createTelegramLinkToken`, `importBackup`, `changePassword`, `deactivateAccount`, `confirmMfaEnrollment` und `disableMfa`. `stepUpErrorText` (`src/lib/auth/step-up-error.ts`, auch im Passwortformular des Profils) liefert: 429 „Zu viele Versuche. Bitte in einer Minute noch einmal.“, ein 401 ohne eigene Meldung „Sitzung abgelaufen. Bitte die Seite neu laden und erneut anmelden.“, deutsche Server-Meldungen unverändert. Der Client kennt den Ablauf des Tokens nicht und erneuert vor Step-up-Aufrufen nicht vorab.
|
||||
|
||||
Logs nennen nur Zustellungs-IDs, nie Token, Chat-ID oder Text.
|
||||
|
||||
## 12. Compliance (T6)
|
||||
|
||||
Prüfbereitschaft für Tierarzneimittel, Etiketten und Behörden. Rechtswerte (Fristen, Paragraphen, Ziffernhöhen, x-Höhe, Landesrecht Bayern) stehen nie im Code, sondern sind Einstellungen mit dem Vermerk „Annahme – vom Inhaber zu prüfen“; sie sind vor dem Rollout gegen gesetze-im-internet.de und EUR-Lex abzugleichen. Belege, Rechnungsnummern, Anschriften, Koordinaten und Aktenzeichen sehen nur Inhaber von `compliance:read` bzw. `veterinary-medicines:read`; sie erscheinen nie in öffentlichen Endpunkten, im Shop-Feed, in Webhooks oder in Ereignis-Payloads. Entscheidungen des Inhabers vom 2026-10-15: eigene Meldungs-Kategorie `COMPLIANCE`, Stand vor Volk beim Sperren, kein Step-up für die Ausnahme vom Sperrbezirk.
|
||||
|
||||
**Stand:** Umgesetzt sind Task 1 (Schema, Rechte, Sperren, Backup), 2 (Tierarzneimittel), 3 (Behandlung aus Packung), 4 (Dokumente), 5 (Etikett-Pflichtangaben), 6 (Druck-Sperre und Probedruck), 7 (Ereignisse), 8 (Sperrbezirk und Sperr-Umbau der Völker) und 9 (Behördenpaket I), 10 (Anzeigen-PDFs), 11 (Hinweise und Tagesauswertung) und 12 (Prüfbereitschaft I), 13 (Prüfbereitschaft II), 14 (Oberfläche Prüfbereitschaft), 15 (Oberfläche Tierarzneimittel) 17 (Oberfläche Etikett), 16 (Behandlungsmaske), 18 (Anzeigen und Einstellungen) und 19 (Oberfläche Sperrbezirk). Task 1 bis 19 sind erledigt (T6a Backend: Task 1 bis 13; T6b Frontend: Task 14 bis 19). Offen sind die Browserprüfung aller T6-Seiten, die Rechtswerte-Prüfung durch den Inhaber und das Ausrollen (TASKS.md).
|
||||
|
||||
### 12.1 Schema und Rechte
|
||||
|
||||
**Migrationen** (alle additiv, nach `20261015110000_t4_telegram`): `20261016100000_t6_veterinary_medicines` (Enums `MedicineUnit`, `VeterinaryMedicineMovementType`; drei Tabellen; `Treatment.medicineId`, `medicineLotId`, `doseQuantity` mit Fremdschlüsseln `ON DELETE RESTRICT`, Indizes `Treatment_medicineId_idx` und `medicineLotId`; `DocumentEntityType` + `MEDICINE_LOT`; Rechte), `…100100_t6_label_particulars` (`SiteSettings.foodBusinessName`/`foodBusinessAddress`, `Product.legalName`, `LabelTemplate.minXHeightMm` Vorgabe 1,2, `AuditAction` + `PRINT`), `…100200_t6_authority_compliance` (`ComplianceSettings`, `AuthorityNotice`, `ApiaryRestriction`, `ComplianceAcknowledgement`; `DocumentEntityType` + `AUTHORITY_NOTICE`, `APIARY_RESTRICTION`; Rechte), `…100300_t6_notification_category_compliance` (nur `ALTER TYPE … ADD VALUE 'COMPLIANCE'`; der Wert wird in derselben Migration nicht benutzt) und `…100400_t6_notification_compliance_default` und `…100500_t6_compliance_settings_row` (Datenmigration: legt die Zeile `ComplianceSettings` mit der Id `singleton` an). Prüfungen und Annahmen zum Schema: Annahme 59. `netQuantityDigitRules` ist ein Prisma-`@default`, damit die SQL-Vorgabe keinen Drift gegen das Schema erzeugt; die Singleton-Zeile `ComplianceSettings` legt die Migration `…100500` an; `ComplianceSettingsService` und `herdStatusIn` behalten einen idempotenten `upsert` nur als Rückfall, der Etikettendruck dagegen schließt ohne Zeile (12.6). Es gibt keine Löschroute für Behandlungen; die RESTRICT-Schlüssel schützen eine Behandlung mit Buchung weiter. Ein künftiger Löschpfad müsste `P2003` auf 409 „Diese Behandlung hat eine Buchung aus einer Packung und kann nicht gelöscht werden.“ abbilden oder gegenbuchen.
|
||||
|
||||
**Rechte** (Katalog `permission-catalog.ts`; die Migrationen vergeben, der Katalog-Sync berechtigt nur System-Rollen):
|
||||
|
||||
| Recht | Gruppe (Sortierung) | ADMIN | BEEKEEPER | STAFF | READONLY | API_CLIENT |
|
||||
|---|---|---|---|---|---|---|
|
||||
| `veterinary-medicines:read` | Tierarzneimittel (3700) | ✓ | ✓ | ✓ | ✓ | – |
|
||||
| `veterinary-medicines:create`, `:update` | Tierarzneimittel | ✓ | ✓ | ✓ | – | – |
|
||||
| `compliance:read` | Prüfbereitschaft & Behörden (3800) | ✓ | ✓ | ✓ | ✓ | – |
|
||||
| `compliance:manage` | Prüfbereitschaft & Behörden (3801) | ✓ | ✓ | – | – | – |
|
||||
|
||||
Eine Behandlung aus einer Packung bucht mit `treatments:create` ab, es gibt kein eigenes Recht. Sperrbezirke lesen mit `apiaries:read` (Einzelheiten nur mit `compliance:read`, 12.7) und schreiben mit `compliance:manage`. `AuditAction` kennt `PRINT` (Etikettendruck, 12.6).
|
||||
|
||||
**Sperr-Reihenfolge.** `Apiary` steht an erster Stelle von `LOCKABLE_TABLES`, danach `Colony` und die übrigen Tabellen wie bisher; die acht neuen Tabellen stehen hinter `NotificationDelivery` (Annahme 50). Die Völker-Pfade, die Stand und Volk zusammen sperren, nehmen zuerst die Stände mit `lockRowsForShare(tx, 'Apiary', ids)` (aufsteigend), dann das Volk; `ApiaryRestrictionsService` sperrt die betroffenen Stände mit `lockRowsForUpdate`, damit sich eine Sperre und ein laufendes Umsetzen hintereinander einreihen. Wechselt der Stand eines Volkes zwischen Lesen und Sperren, endet die Anfrage mit 409 „Der Stand wurde gerade geändert. Bitte neu laden.“, ohne automatischen Neuversuch. Die Umbauten der Aufrufer stehen in 12.7. Services, die T6 anfasst und `before` bisher außerhalb lasen (`SiteSettingsService.update`, `ProductsService.update`, `LabelTemplatesService.update`), lesen es seit Task 5 nach der Zeilensperre.
|
||||
|
||||
**Backup.** Die sieben neuen Tabellen gehören zum versiegelten Bundle; Reihenfolge, Verlust des Packungsbezugs in unversiegelten Dateien und die Regel für Behördenanzeigen stehen in Abschnitt 8 (Annahmen 63 und 64).
|
||||
|
||||
**Meldungs-Kategorie `COMPLIANCE`** („Behörden & Prüfung“). Sie trägt die Hinweise „Bestand geändert“ und „TSK-Stichtag“ (Task 11) und ist anders als `SYSTEM` für Telegram vorgewählt: Die Vorgabe `telegramCategories` ist `[TASK_DUE, DIGEST, COMPLIANCE]`, und die Daten-Migration hängt `COMPLIANCE` an jede bestehende, nichtleere Liste an. Eine leere Liste (der Nutzer hat bewusst alles abgewählt, Opt-out) bleibt leer; Kosten bei falscher Annahme: ein Nutzer mit Opt-out bekäme sonst Behördenhinweise. `IsEnum(NotificationCategory)` und die Längengrenze übernehmen den Wert aus dem Enum, es gibt keine zweite Kategorienliste im Code. Das Frontend (Task 18) ergänzt Label und Auswahl; bis dahin zeigt es den Wert als unbekannte Kategorie.
|
||||
|
||||
**Null-Verträge.** `describeNullContracts` (`src/common/validation/null-contract.spec-helper.ts`, per `tsconfig.build.json` aus dem Build ausgeschlossen) registriert je Update-DTO die drei Prüfungen der Null-Regel (Annahme 20); jede T6-Task legt ihre Verträge in eine eigene Spec-Datei.
|
||||
|
||||
### 12.2 Tierarzneimittel: Katalog, Packungen, Bewegungsbuch
|
||||
|
||||
`VeterinaryMedicinesModule` (`src/veterinary-medicines/`, in `AppModule`, nicht im `WorkerModule`: es hat keine Handler) trennt drei Ebenen: das Mittel (`VeterinaryMedicine`, Handelsname, Wirkstoff, Einheit, Wartezeit, Lagerhinweise), die Packung (`VeterinaryMedicineLot`, Beleg, Verfall) und die Bewegung (`VeterinaryMedicineMovement`: `TREATMENT` nur aus einer Behandlung, `CORRECTION` für die Inventur, `DISPOSAL` mit Pflichtgrund). Grundsätze: Annahmen 60 bis 62. Der Rest ist `roundToThousandths(lot.quantity + Σ movement.quantity)` (`src/common/quantity.ts`, die einzige Rundung auf Tausendstel; `roundKg` in `honey-plausibility.ts` ist ein Alias, `bottling.service.ts` ruft sie direkt auf, `-0` wird zu `0`). Die reinen Helfer stehen in `medicine-ledger.ts` (`summarizeLot`, `treatmentBookingDelta` für die Gegenbuchung bei geänderter Packung oder Dosis, Task 3), die Sichten in `medicine-views.ts` (eine `groupBy`-Abfrage je Liste, kein N+1).
|
||||
|
||||
**API** (Rechte `veterinary-medicines:read|create|update`, Datumsfelder der Antworten als Tagestexte `JJJJ-MM-TT`):
|
||||
- `GET /veterinary-medicines?active=`, `GET /veterinary-medicines/suggestions` (eigene, noch nicht katalogisierte Handelsnamen aus `Treatment.product` ohne Beachtung der Groß-/Kleinschreibung, höchstens 50, mit den Werten der jüngsten Behandlung; legt nichts an), `GET/PATCH /veterinary-medicines/:id`, `POST /veterinary-medicines`, `POST …/:id/deactivate|reactivate` (ohne Änderung keine Schreibzeile und kein Audit).
|
||||
- `GET /veterinary-medicine-lots?medicineId=&selectable=true&includeLotId=` (wählbar: Rest > 0 und Mittel aktiv, älteste Haltbarkeit zuerst; `includeLotId` hält die Packung einer bearbeiteten Behandlung zusätzlich wählbar), `GET/PATCH /veterinary-medicine-lots/:id` (mit Bewegungsbuch), `POST /veterinary-medicine-lots`, `POST …/:id/movements` mit `{ type: 'CORRECTION', actualRemaining }` oder `{ type: 'DISPOSAL', quantity, reason }`.
|
||||
- Die Anlege-Endpunkte und `:id/movements` tragen `@Idempotent()`. Die Listen sind noch nicht paginiert; mit wachsendem Buch ist ein Limit zu ergänzen.
|
||||
|
||||
**Schreiben.** Mittel und Packungen lesen `before` nach der Zeilensperre und schreiben das Audit in derselben Transaktion; die Sperrfolge ist Mittel, dann Packung. Eine Inventur bucht die Differenz zwischen Buchrest und gezähltem Rest unter der Packungssperre (Delta 0 bucht nichts und schreibt kein Audit), zwei gleichzeitige Inventuren laufen nacheinander. Eine Entsorgung, die auf 0 rundet (unter 0,0005), ist 400. `name` und `reason` dürfen nicht nur aus Leerzeichen bestehen. `minTemperatureC <= maxTemperatureC` prüft der Dienst gegen den zusammengeführten Stand (400). Der Seed legt keine Mittel an; `seed-no-medicines.spec.ts` sichert das (nur die fünf bekannten Seed-Module, keine weitere `.ts` unter `prisma/`).
|
||||
|
||||
**Behandlung aus Packung (Task 3).** `POST /treatments`, `POST /treatments/bulk` und `PATCH /treatments/:id` nehmen zusätzlich `medicineId`, `medicineLotId` und `doseQuantity` (`null` leert); `product` entfällt, wenn Mittel oder Packung gewählt sind, `PATCH` kennt außerdem `apiaryId` (Stand am Behandlungstag, 404 bei unbekanntem Stand). Die Logik steckt in `treatment-medicine.ts` (freie Funktionen mit `tx`); `TreatmentsModule` importiert `VeterinaryMedicinesModule` nicht, die Buchung braucht nur `treatments:create`.
|
||||
- **Prüfung** (`resolveMedicineIn`, am zusammengeführten Zustand): Eine Packung schließt `supplier`, `purchaseProof`, `batchNumber` und `prescribingVet` auf der Behandlung aus (400 „Diese Angabe kommt aus der Packung“); `medicineId: null` bei gesetzter Packung, eine Packung eines anderen Mittels, ein abweichendes `product` (ohne Groß-/Kleinschreibung, getrimmt) und ein inaktives Mittel beim Anlegen sind 400, ein unbekanntes Mittel oder eine unbekannte Packung 404. Die Dosis wird auf Tausendstel gerundet, unter 0,001 ist 400. Das Mittel wird `FOR SHARE` gesperrt. `activeIngredient`, `withdrawalPeriodDays` und `method` füllt der Server nie aus dem Katalog nach; `product` wird zum Handelsnamen und folgt dem Katalog nur, wenn der Patch `product`, `medicineId` oder `medicineLotId` anfasst. `update` prüft und bucht nur, wenn der Patch Mittel, Packung, Dosis, `product` oder eines der vier Packungs-Textfelder berührt; eine reine Notizänderung gelingt auch, wenn das Mittel der Packung inzwischen gewechselt hat.
|
||||
- **Delta-Buchung** (`bookTreatmentIn`): Eine Behandlung mit Packung und Dosis bucht `TREATMENT` mit −Dosis in derselben Transaktion wie Behandlung, Audit und `TreatmentRecorded` (Sammelerfassung: je Volk eine Bewegung, alles oder nichts). Beim Bearbeiten bucht der Server nur das Delta je Packung aus `treatmentBookingDelta` über die Summe der bisherigen Bewegungen dieser Behandlung (Gegenbuchung auf der alten, neue Buchung auf der neuen Packung; Bewegungen werden nie geändert). Ein Umhängen auf ein anderes Volk lässt den Bestand unberührt. Eine Dosis ohne Packung wird gespeichert und bucht nichts; eine später gesetzte Packung bucht die volle Dosis nach. Leere oder abgelaufene Packungen blockieren nicht (der Rest wird negativ, die Prüfbereitschaft meldet es).
|
||||
- **Sperr-Reihenfolge:** Volk (wenn `colonyId` im Patch steht) → Behandlung → Mittel (`FOR SHARE`) → Packungen aufsteigend in einer Anweisung (`lockRowsForUpdate`), also Colony vor Treatment wie in der Karte `LOCKABLE_TABLES`. Nach der Packungssperre prüft die Buchung, dass die Packung noch zum Mittel der Behandlung gehört (sonst 409 „Die Packung wurde gerade geändert. Bitte neu laden.“). Eine Inventur auf derselben Packung wartet auf dieselbe Sperre.
|
||||
- **Bestandsbuch** (`export/treatment-log.ts`, `GET /export/treatment-log.pdf`): `resolveSourceValues` liest die Spalten aus genau einer Quelle (Packung, wenn gesetzt, sonst die Behandlung). Die Menge ist der Text der Behandlung, sonst die Dosis mit Einheit des Mittels („30 ml“, auch ohne Packung, sobald ein Katalogmittel da ist). `treatmentLogGaps` (`SUPPLIER`, `PROOF`, `AMOUNT`, `WITHDRAWAL` mit 0 Tagen als erfasst, `VET` nur bei verschreibungspflichtigem Mittel) ist die **einzige Quelle**: `treatmentLogCells` druckt „FEHLT“ genau an diesen Stellen (die Tierarzt-Lücke in der Spalte „a) Lieferant …“ als „; Tierarzt: FEHLT“), und die Prüfbereitschaft nutzt dieselbe Funktion; FEHLT und Lücken sind also gleich. Zeilen mit gleichen aufgelösten Werten gruppiert das Buch nur bei gleicher Packung und gleichem `prescriptionOnly`. Fußnote: „Lieferant, Beleg und Ch.-B. stammen aus der erfassten Packung.“ **Der Export braucht `export:read` und zusätzlich `veterinary-medicines:read`** (Annahme 73); ohne dieses Recht 403, die Stammkarte bleibt mit `export:read` erreichbar.
|
||||
|
||||
### 12.3 Dokumente mit Rechten je Art
|
||||
|
||||
Für `MEDICINE_LOT`, `AUTHORITY_NOTICE` und `APIARY_RESTRICTION` gilt zusätzlich zum Dokumentenrecht das Fachrecht des Datensatzes. Die Zuordnung steht in `DOCUMENT_ENTITY_PERMISSIONS` (`documents.service.ts`): Packung lesen `veterinary-medicines:read`, schreiben `veterinary-medicines:update`; Behördenanzeige und Sperrbezirk lesen `compliance:read`, schreiben `compliance:manage`. „Schreiben“ umfasst Hochladen, Umhängen, Umbenennen und Löschen; beim Umhängen zählen die alte und die neue Art. `DocumentsService.assertEntityAccess(userId, entityType, mode)` wirft 403 ohne das Recht; Arten ohne Eintrag (Stand, Volk, Königin, Durchsicht, Honigcharge) prüfen nichts zusätzlich. Die Prüfung kommt vor jeder Datenbankabfrage (`findAll`, `create`) bzw. nach dem Laden des Dokuments und vor dem Lesen der Datei (`readFile`, `update`, `delete`), daher 403 vor 404 und kein Existenz-Orakel für Unberechtigte. Wer nur `documents:read` hat, sieht Belege, Anzeigen und Sperrbescheide weder in der Liste noch per Download-ID. `compliance:manage` schließt `compliance:read` nicht ein (Annahme 69). Speicherordner sind `medicine_lot`, `authority_notice` und `apiary_restriction`; MIME-Allowlist und Signaturprüfung gelten unverändert. Ein Fehler beim Löschen der Datei wird mit Dokument-Id und `loggableError()` protokolliert, Zeile, Audit und Antwort bleiben. Dokumente gelöschter Datensätze bleiben bestehen (Annahme 70). Das Recht wirkt über den 30-s-Cache des Resolvers verzögert, wie überall.
|
||||
|
||||
**Zwischenspeicher.** Alle API-Antworten tragen `Cache-Control: no-store` (Abschnitt 9, `noStoreMiddleware`); die e2e-Tests halten das für Liste und Download fest. Der Service Worker beachtet `no-store` bewusst **nicht**, weil es jede Antwort trägt (Abschnitt 2, Annahme 87). Stattdessen schließen Pfadregeln die Listen der drei Arten (`/documents?entityType=…`) und `documents/:id` aus; das Präfix `/api/v1/documents` wird nicht ganz gesperrt, sonst fehlten die Durchsichtsfotos offline. Nie gecacht werden auch die Compliance-, Arzneimittel- und Sperrbezirk-Pfade (`NEVER_CACHED_API_PATHS`, seit Task 14).
|
||||
|
||||
### 12.4 Etikett-Pflichtangaben
|
||||
|
||||
`checkLabel` (`src/label-templates/label-particulars.ts`) ist rein und ohne Datenbank; Regeln und Grenzen: Annahmen 65 bis 68. **Pflichtangaben** (sperren den Druck: 409 `LABEL_PARTICULARS_MISSING` mit `{ gaps }`, Abschnitt 12.6): `LEGAL_NAME` (ein Wort mit „honig“), `NET_QUANTITY` (Füllmenge der Abfüllung, „250,5 g“ wie „250.5 g“, „1 kg“ nur bei vollen Kilogramm; als ganze Wörter), `BEST_BEFORE` („Mindestens haltbar bis“ mit dem Datum), `LOT`, `ORIGIN` und `FOOD_BUSINESS` (Name und Anschrift). **Warnungen** (sperren nie): `LOT_PREFIX`, `X_HEIGHT` (unter `LabelTemplate.minXHeightMm`), `NET_QUANTITY_HEIGHT` (Ziffernhöhe unter der Regel aus `ComplianceSettings.netQuantityDigitRules`), `TEXT_CLIPPED`. Das Ergebnis trägt `requirements` (`minXHeightMm`, `netQuantityMinCapHeightMm`) und je Befund `elementIds` (bei Lücken die abgeschnittenen Elemente, die die Angabe getragen hätten). **Verfeinerungen (Runden 2 bis 4 der Task 5).**
|
||||
- **Ziffern-Wächter je Element.** „Zahl direkt vor der Menge“ („1,250 g“ ist kein Treffer für 250 g) gilt nur im Text eines Elements, nie im verbundenen Text: Eine Losnummer oder ein Datum in einem Nachbarelement macht „500 g“ nicht ungültig. „250g“ gilt als „250 g“, „L2026“ bleibt.
|
||||
- **Lesereihenfolge** kommt allein aus den Positionen (nach y, Zeilen mit 1 mm Toleranz gegen die erste Oberkante, je Zeile von links nach rechts), nie aus der Reihenfolge der Elemente in der Vorlage.
|
||||
- **Verteilte Angaben** (Name und Anschrift): Zeilen, Blöcke in Lesereihenfolge oder Ketten wortgleicher Elemente, jeweils mit **symmetrischem** senkrechtem Abstand von höchstens 10 mm (`max(0, y − Unterkante, Oberkante − (y + h))`, gemessen an der laufenden Ober- und Unterkante der ganzen Gruppe, nicht am Vorgänger, `groupByDistance`). Elemente mit leerem normalisiertem Text werden ignoriert und überbrücken nichts; eine hohe Textbox überbrückt Zeilen um ihre Boxhöhe. Nur sichtbare (nicht abgeschnittene) Teile zählen (Annahme 75).
|
||||
- **Zahl | Einheit** („500“ | „g“): zwei Elemente gelten als Paar, wenn sich die Boxen senkrecht überlappen, die Einheit rechts liegt und der waagerechte Abstand höchstens 10 mm beträgt (Annahme 74). Beide Teile zählen für `X_HEIGHT` und `NET_QUANTITY_HEIGHT`.
|
||||
- **Träger** einer verteilten Angabe sind nur die Elemente, die sich mit dem Treffer im verbundenen Text überlappen (`matchParts`), nicht jedes Element mit einem gemeinsamen Wort; abgeschnittene Träger erscheinen über dieselbe Überlappung in `elementIds` der Lücke und von `TEXT_CLIPPED` (`clippedHolders`).
|
||||
- **Zeitzonen-Unabhängigkeit.** Der Datumstag kommt aus `labelDayOf` (Berliner Kalendertag). Ein Quelltext-Wächter liest `label-templates.service.ts`, `label-particulars.ts`, `label-text.ts`, `font-metrics.ts`, `src/common/dates.ts` und `format-day.ts` und scheitert bei zeitzonenabhängigen Aufrufen (`getDate`, `getHours`, `toLocaleDateString` ohne `timeZone`, `Intl.DateTimeFormat(` mit oder ohne `new` ohne `timeZone`, mehrargumentiges `new Date(y, m, …)` u. a.); ein Selbsttest prüft die Muster an schlechten und guten Beispielen. Die Spec setzt keine Prozess-Zeitzone, sondern prüft wörtliche Berliner Tage.
|
||||
- **Dokumentierte Grenzen:** Ein fremdes Element mit einem gemeinsamen Wort kann in eine Kette geraten; der waagerechte Abstand zählt bei Anschriften nicht; „honig“ in einem Wort genügt (Annahme 67); `NET_QUANTITY_HEIGHT` zählt die größte Nennung (Annahme 66). Eine Füllmenge, die auf drei oder mehr Elemente verteilt ist oder deren Einheit links steht, ist eine Lücke.
|
||||
|
||||
**Höhen.** mm = Schriftgröße in pt × AFM-Metrik / 1000 × 25,4 / 72 (Helvetica: x-Höhe 523, Versalhöhe 718). Der Zugriff auf das private pdfkit-Feld steckt allein in `font-metrics.ts` (`fontMetricsOf`, je Schnitt gecacht, Fehler bei fehlenden Werten, durch einen Spec-Test gesichert); `pdfFontName` und `MM_TO_PT` wohnen dort. Beispiel: 6 pt ergibt 1,11 mm (Warnung), 7 pt 1,29 mm (in Ordnung). Die Rechtswerte sind Eingaben, die Beispielregeln stehen nur in den Tests.
|
||||
|
||||
**Stammdaten und Platzhalter.** `SiteSettings.foodBusinessName` (200) und `foodBusinessAddress` (300), `Product.legalName` (200) und `LabelTemplate.minXHeightMm` (0,5 bis 5) bleiben leer bzw. bei der Vorgabe, bis der Inhaber sie pflegt; leer ist eine Lücke, kein Standardwert. Neue Platzhalter: `legalName`, `originCountry`, `foodBusinessName`, `foodBusinessAddress`, `bestBeforeLine` („Mindestens haltbar bis TT.MM.JJJJ“), `lotLine` („L <Losnummer>“); die Liste liegt als `test/fixtures/placeholder-keys.json` vor (Wächter `placeholder-keys.spec.ts`, das Frontend vergleicht seine Liste damit). `buildPlaceholderValues(bottlingBatch, settings)` setzt unbesetzte Stammdaten auf `''`. Die öffentliche Herkunftsseite und der Shop-Feed zeigen weder Anschrift noch Verkehrsbezeichnung (e2e belegt, auch mit gesetztem `legalName`). `holderName`/`holderAddress` laufen über denselben `trimmedOrNull`-Helfer (`null` löscht). Der Druck (12.6) ruft `labelDayOf(bottling.bestBeforeDate)` für `expected.bestBefore` und nutzt einen gemeinsamen Messer je Druck (`pdfTextMeasurer()`); `labelDayOf` wohnt in `label-text.ts` (vermeidet einen Importzyklus) und wird vom Service weiter exportiert.
|
||||
|
||||
### 12.5 Ereignisse für Völker und Stände
|
||||
|
||||
Vier neue Typen im Katalog (`domain-event-types.ts`, 38 Typen), Aggregattyp `Compliance` neu (`'Apiary'` gab es schon). Alle tragen nur Ids, Codes, Jahr und Tag, nie Adresse, Koordinaten oder Namen, und sind nicht in `DOMAIN_EVENT_WEBHOOKS`; der Testhelfer `herd-payload.spec-helper.ts` prüft die wirklich geschriebenen Payloads gegen eine Allow-Liste.
|
||||
- `ColonyCreated { apiaryId }` (Aggregat `Colony`): `ColoniesService.create` und für den Ableger in `split` (zusätzlich zu `ColonySplit`), jeweils in der Transaktion des Schreibens. Auch der CSV-Import schreibt es je angelegtem Volk in derselben Transaktion mit Datensatz und Audit (`Colony` CREATE), damit die Bestandsänderung die importierten Völker sieht (gemeinsamer Erzeuger `colonyCreatedEvent`, `src/colonies/colony-created-event.ts`). Der Import sendet weiterhin keinen Webhook `colony.created`; der Webhook bleibt im Altpfad (Annahme 11). Fehlerzeilen, Überspringen und Zähler des Imports sind unverändert. Eine Wiederherstellung aus dem Backup schreibt bewusst kein `ColonyCreated`.
|
||||
- `ColonyMoved { fromApiaryId, toApiaryId }` (Aggregat `Colony`): `move` und `update` mit geändertem Stand. Ein Umsetzen in denselben Stand schreibt Historie und Audit, aber kein Ereignis.
|
||||
- `ApiaryChanged { change }` (Aggregat `Apiary`), `change` = `CREATED` | `DEACTIVATED` | `REACTIVATED` | `LOCATION_CHANGED`. `LOCATION_CHANGED` nur, wenn Adresse, Ort, Breite oder Länge sich gegenüber dem gesperrten `before` ändern. Je Schreibvorgang ein Ereignis, ohne `dedupeKey`.
|
||||
- `TskReferenceDayReached { year, referenceDay }` (Aggregat `Compliance`, `referenceDay` als `JJJJ-MM-TT`, tagesbezogen über `dailyDedupeKey`): nur im Katalog; der Erzeuger ist die Tagesauswertung (Task 11).
|
||||
|
||||
`ApiariesService` schreibt Datensatz, Audit und Ereignis seit Task 7 in **einer** Transaktion; `update`, `deactivate` und `reactivate` sperren zuerst die Standzeile (`lockRowForUpdate`) und lesen `before` danach, `deactivate` zählt lebende Völker erst danach über `tx`; `reactivate` behält die Audit-Aktion `UPDATE`. Die Handler (`compliance.herd-change`, `compliance.tsk-reference-day`) liegen im künftigen `ComplianceModule` (von `AppModule` und `WorkerModule` importiert, ohne `PermissionsModule`, Task 11); die Erzeuger laufen nur in der API. Frontend: `DOMAIN_EVENT_LABELS` kennt die vier Typen („Volk angelegt“, „Volk umgesetzt“, „Stand geändert“, „TSK-Stichtag erreicht“); Task 14 trägt sie nicht noch einmal ein.
|
||||
|
||||
### 12.6 Etikettendruck: Sperre, Probedruck, Audit
|
||||
|
||||
`LabelTemplatesService.renderLabelsPdf(templateId, bottlingBatchId, options, actingUserId)` mit `options = { startPosition?, proof? }` ersetzt die alte Signatur mit `startPosition`. Der Druck ruft vor dem Rendern dieselbe Prüfung `checkLabel` wie die Prüf-Endpunkte (eine private Methode `check`, dieselbe Aufbereitung der Platzhalter, dieselbe Füllmenge, derselbe MHD-Tag aus `labelDayOf`, dieselben Ziffernregeln).
|
||||
- **Sperre.** Fehlt eine Pflichtangabe und ist `proof` nicht gesetzt, antwortet der Druck mit 409 `{ code: 'LABEL_PARTICULARS_MISSING', message, gaps }` und erzeugt kein PDF. Warnungen sperren nie, sie landen im Audit. `?proof=false` mit Lücke ist 409, `?proof=maybe` und `?proof=0` sind 400 (`ParseBoolPipe`).
|
||||
- **Probedruck** (`?proof=true`): immer möglich; jedes Etikett trägt den Stempel „MUSTER – nicht verkaufsfähig“ (`label-proof-watermark.ts`: diagonal, 50 % Grau, halbtransparent, 80 % der Diagonale, höchstens 50 % der Etikettenhöhe; im gedrehten Bogen mit den Etikettenmaßen), damit ein Probeabzug nie als verkaufsfähig umläuft.
|
||||
- **Audit vor dem PDF.** Jeder Druck, auch der Probedruck, schreibt vor der Auslieferung `PRINT` am `BottlingBatch` mit `{ templateId, copies, proof, gapCodes, warningCodes }`; `copies` ist immer `jarCount` der Abfüllung, unabhängig von `startPosition`. Schlägt das Audit fehl, schlägt der Druck fehl (fail closed; das Audit steht außerhalb einer Transaktion, es gibt keinen zu schützenden Datensatz).
|
||||
- **Prüf-Endpunkte.** `GET /label-templates/:id/check/:bottlingBatchId` prüft eine gespeicherte Vorlage gegen eine Abfüllung, `POST /label-templates/check` (200, vor `:id` registriert) einen **ungespeicherten Entwurf**: nur Text-Elemente (`@Equals('text')`, andere Arten 400), höchstens 100, Element-Ids eindeutig, Breite und Höhe 0,1 bis 1000 mm, `x`/`y` −1000 bis 1000, `fontSize` höchstens 500, `minXHeightMm` 0,5 bis 5; ohne `bottlingBatchId` mit Beispielwerten (`sample: true`). `widthMm`/`heightMm` des Entwurfs werden nur auf Grenzen geprüft (10 bis 1000), maßgeblich sind die Feldgrößen der Elemente. `startPosition` liegt zwischen 1 und 1000, sonst 400.
|
||||
- **Rechte.** Prüfen: `label-templates:read`, Drucken: `label-templates:print`; **zusätzlich `bottling:read`** bei `GET check`, `GET print` und bei `POST check` mit `bottlingBatchId` (sonst 403; der Controller prüft das über `PermissionResolverService.hasAny`, weil `@RequirePermission` nur „oder“ kennt). Der Entwurfs-Check mit Beispielwerten braucht nur `label-templates:read`. Zur Vergabe der Etikett-Rechte: Annahme 77.
|
||||
- **Ziffernregeln nur aus `ComplianceSettings`.** Der Code kennt keine Rechtswerte und keine Rückfall-Vorgabe. `loadDigitRules` liest `ComplianceSettings.netQuantityDigitRules` der Zeile `singleton` (Migration `20261016100500`); fehlt die Zeile oder sind die Regeln unbrauchbar (`parseDigitRules`: leer, Höhe nicht größer als 0, nicht endlich, nicht genau eine Regel ohne Obergrenze), antworten Druck **und** Prüfung mit 409 `{ code: 'COMPLIANCE_SETTINGS_INVALID', message: 'Compliance-Einstellungen fehlen oder sind ungültig.' }` (fail closed; geloggt über `loggableError`, ohne Werte). Auch dann entsteht kein Audit.
|
||||
- Alle Antworten (Prüfung wie PDF) sind `no-store` (die globale Middleware, Abschnitt 9); die Prüfantworten enthalten die Anschrift des Lebensmittelunternehmers. Das Frontend (Task 17) liest `GET`/`POST check` und die Lückenliste `gaps` des 409.
|
||||
|
||||
### 12.7 Sperrbezirk
|
||||
|
||||
`ApiaryRestriction` (Seuche, Behörde, Aktenzeichen, Beginn, Ende, Notiz) sperrt Bewegungen von Völkern in und aus einem Stand. **Aktiv** ist eine Sperre vom Beginn bis einschließlich Endtag, ohne Endtag bis auf Weiteres. Maßgeblich ist der **Berliner Kalendertag** (`berlinToday()` der Anwendung, nicht der UTC-Tag und kein Datenbank-`now()`; Entscheidung des Inhabers 2026-10-15). Eine Sperre wird nie gelöscht, sie endet über das Enddatum. Paragraphen und Fristen (BienSeuchV) sind Hinweise und vor dem Rollout gegen die Quelle zu prüfen.
|
||||
- **Geschützte Pfade:** `ColoniesService.create` (Volk im Stand anlegen), `update` mit Standwechsel (alter oder neuer Stand; eine reine Namensänderung prüft nichts und sperrt keinen Stand), `move` (Quell- oder Zielstand), `merge` über verschiedene Stände und der **CSV-Import** (`ImportService.importColonyRow` sperrt den Stand `FOR SHARE`, prüft `ACTIVE` über `tx` und die Sperre ohne Ausnahme; Treffer sind Fehlerzeilen, Annahme 71).
|
||||
- **Freie Pfade:** Ableger (`split`, im selben Stand), Auflösen (`dissolve`), Ernte (warnt nur, Task 13) und die Wiederherstellung aus dem Backup (prüft bewusst nichts); ebenso ein Umsetzen in den eigenen Stand und ein Vereinigen innerhalb eines Standes.
|
||||
- **Antwort:** 409 `{ code: 'RESTRICTED_ZONE', message, restrictionIds, restrictions: [{ id, apiaryId, apiaryName, disease, startsOn }] }`; die Meldung nennt Stand, Seuche und Beginn `TT.MM.JJJJ`.
|
||||
- **Ausnahme.** `restrictionOverrideReason` (getrimmt 10 bis 500 Zeichen) bei Anlegen, Bearbeiten, Umsetzen und Vereinigen. Ohne `compliance:manage` ist jede Begründung 403, **vorab** (vor Lesen und Sperren, auch ohne aktive Sperre; Annahme 72). Kein Step-up (Entscheidung des Inhabers). Mit dem Recht und aktiver Sperre landet die Begründung im Audit (`afterData.restrictionOverride = { reason, restrictionIds }`) und in `ColonyApiaryHistory.notes` („Ausnahme Sperrbezirk: …“, vor einer vorhandenen Notiz; bei Anlegen und Vereinigen gibt es keine Historienzeile, dort nur das Audit). Die Begründung steht **nie am Volk**: sie wird vor jedem Prisma-Aufruf abgetrennt. Ohne aktive Sperre wird sie (mit dem Recht) ignoriert, `null` zählt wie weggelassen.
|
||||
- **Sperrmuster und 409 „neu laden“.** Die Pfade lesen die Stand-Ids ungesperrt, sperren die Stände `FOR SHARE` aufsteigend, dann die Völker (beim Vereinigen Überlebendes und Aufgelöstes in einer Anweisung), vergleichen unter der Sperre den Stand des Volkes mit dem gelesenen (sonst 409 „Der Stand wurde gerade geändert. Bitte neu laden.“, kein automatischer Neuversuch; ein verschwundenes Volk ist 404), lesen `assertApiaryActive` über `tx` und prüfen erst dann die Sperre. `ApiaryRestrictionsService` (`POST`, `PATCH`) sperrt die Stände `FOR UPDATE`: Ein laufendes Umsetzen und eine neu beginnende Sperre reihen sich hintereinander ein, eine Sperrenänderung wartet auf laufende Umsetzungen. `updateIn` nimmt selbst keinen Standlock; ein Patch mit Standwechsel ohne den Wächter aus `update()` wirft (Programmierfehler). Die Durchsicht-Übernahme (ohne `apiaryId`) sperrt nur das Volk.
|
||||
- **Endpunkte.** `POST /apiary-restrictions` (`compliance:manage`, `@Idempotent`, 1 bis 50 verschiedene Stände, je Stand eine Zeile und ein Audit, eine Transaktion, unbekannter Stand 404 mit Rollback, `endsOn >= startsOn` sonst 400), `PATCH /apiary-restrictions/:id` (Stand `FOR UPDATE`, dann Sperre, `before` danach, `endsOn: null` öffnet wieder), `GET /apiary-restrictions?active=true|false`, `GET /apiaries/:id/restrictions` (`apiaries:read`).
|
||||
- **Einzelheiten nur mit `compliance:read`:** Behörde, Aktenzeichen, Notiz und Ersteller liefern beide GET-Pfade nur dann; mit nur `apiaries:read` besteht eine Zeile aus `id`, `apiaryId`, `disease`, `startsOn`, `endsOn`. `active=true` liefert für alle die schlanke `ActiveRestrictionInfo` (ohne diese Felder). Öffentliche Seiten und der Shop-Feed nennen weder Seuche noch Sperre (e2e mit echter öffentlicher Charge).
|
||||
- Das Frontend (Task 19, Abschnitt 12.11) bietet den Ausnahmedialog nur mit `compliance:manage` an und sendet `restrictionOverrideReason`.
|
||||
|
||||
### 12.8 Behördenpaket I: Einstellungen, Bestandsbild, Anzeigen
|
||||
|
||||
`ComplianceModule` (`src/compliance/`, in `AppModule` und seit Task 11 auch in `WorkerModule`, Abschnitt 12.9) enthält `ComplianceSettingsService`, `AuthorityNoticesService` und die reinen Helfer `tsk-day.ts`, `herd-snapshot.ts`, `herd-status.ts`. Kein Provider hängt am `PermissionResolverService`; das Modul exportiert beide Services.
|
||||
- **Einstellungen.** `GET`/`PATCH /compliance/settings` (`compliance:read` / `compliance:manage`). `update` upsertet, sperrt `ComplianceSettings`, liest `before` danach und schreibt das Audit in derselben Transaktion. Prüfungen (400): `tskReferenceDay` und `tskReportDueDay` als `MM-TT` (02-29 und „1-1“ abgelehnt), `tskExcludedColonyTypes` ohne Doppelte, `netQuantityDigitRules` mit 1 bis 10 Regeln, Obergrenzen streng aufsteigend, nur die letzte ohne Grenze, `minMm` 0,5 bis 20; ein fehlender `maxGrams` wird vor der Prüfung zu `null` normalisiert und so gespeichert. Alle Rechts- und Fristwerte sind Einstellungen mit dem Vermerk „Annahme – vom Inhaber zu prüfen“.
|
||||
- **Bestandsbild** (`herdStatusIn(db, now)`): lebende Völker (`LIVING_COLONY_WHERE`) an aktiven Ständen, bei der TSK-Zählung ohne `tskExcludedColonyTypes`; zwei ungesperrte Abfragen genügen für eine Anzeige. `herdDeviation` vergleicht `baseline.totalColonies` mit der aktuellen Zahl und erkennt neue, aufgegebene und verlegte Stände (Adresse, Ort, Koordinaten); ein Umsetzen zwischen Ständen löst nichts aus. `noticeOnColonyCountChange` und `noticeOnApiaryChange` schalten nur `triggered`, die Tatsachen stehen immer da.
|
||||
- **Bezugsstand-Regeln.** Bezugsstand ist die jüngste `SENT`-Anzeige der Art `REGISTRATION` oder `HERD_CHANGE`, sortiert nach `sentOn`, dann `createdAt`, `id`; TSK-Zählnachweise zählen nicht. Ohne Bezugsstand ist `deviation = null` (Punkt „Erstanzeige fehlt“). `REGISTRATION` entsteht nur ohne Bezugsstand, `HERD_CHANGE` nur mit („Erst die Erstanzeige erfassen.“, 409); `TSK_REPORT` braucht `year`, andere Arten dürfen keines haben (400). Eine wiedergeöffnete Erstanzeige lässt sich erneut senden.
|
||||
- **Lebenszyklus.** `DRAFT` → `SENT` (`mark-sent`) → `DRAFT` (`reopen`); `DRAFT` → `CANCELLED` (`cancel`). `recount` nur im Entwurf. `createDraftIn(tx, { kind, year?, referenceDate }, userId | null)` ist der gemeinsame Kern von `create` und dem des Tagesjobs (Task 11); `referenceDate` und `sentOn` beim Senden sind standardmäßig `berlinToday()`. Jeder Wechsel sperrt die Anzeige, liest `before` danach, prüft den Übergang (409, deutsche Meldung) und schreibt Audit `UPDATE` mit `beforeData`/`afterData` in derselben Transaktion. Die POST-Wechsel antworten wie die übrigen POST-Aktionen mit 201.
|
||||
- **`openKey` und Mutex.** Anlegen, `mark-sent` und `reopen` sperren zuerst `ComplianceSettings` (`singleton`), dann die Anzeige (Reihenfolge der Karte). `openKey` (`REGISTRATION` | `HERD_CHANGE` | `TSK_REPORT:<Jahr>`, nur bei `DRAFT`, nullbar eindeutig) lässt höchstens einen offenen Entwurf je Art und Jahr zu; ein zweiter, auch im Rennen, antwortet 409 `{ code: 'DRAFT_EXISTS', existingId }`. Ein `P2002` ohne erklärenden Entwurf wird unverändert weitergeworfen. Die Prüfung auf einen offenen Entwurf entfällt, wenn die Anzeige mit `sentOn` angelegt wird.
|
||||
- **`sentOn`-Regeln.** Mit `sentOn` beim Anlegen entsteht die Anzeige gleich als `SENT` ohne `openKey` (Weg „bereits angezeigt am …“ für Altbestand). `reopen` setzt `sentOn = null` und `openKey`, scheitert aber bei vorhandenem Entwurf (409 `DRAFT_EXISTS`). `PATCH` (`totalColonies`, `referenceDate`, `sentOn`, `sentVia`, `reference`, `notes`): `sentOn` auf einem Entwurf ist 400 „Ein Entwurf hat kein Sendedatum.“, das Sendedatum einer `SENT`-Anzeige ist nicht löschbar (400), eine `CANCELLED`-Anzeige nicht änderbar (409); fasst ein Patch `sentOn` an, nimmt `update` zuerst den Settings-Mutex.
|
||||
- **Verwerfen statt Löschen.** `cancel` verwirft nur einen Entwurf (`CANCELLED`, `openKey` frei); es gibt keine Löschroute (Spec 7), angehängte Dokumente bleiben (Annahme 76). `GET /authority-notices?kind=&year=` liefert höchstens die 200 neuesten Einträge (`take: 200`), eine Seitenaufteilung fehlt noch.
|
||||
- **Endpunkte.** `GET /authority-notices`, `GET …/:id`, `POST /authority-notices` (`@Idempotent`), `PATCH …/:id`, `POST …/:id/recount|mark-sent|reopen|cancel`; Lesen mit `compliance:read`, Schreiben mit `compliance:manage` (Nutzer ohne die Rechte: 403 auf Liste, Einzelanzeige und Einstellungen). Der PDF-Endpunkt `…/:id/pdf` steht im Absatz „PDFs (Task 10)“ am Ende dieses Abschnitts.
|
||||
|
||||
**PDFs (Task 10).** Aufbau: reines Modell `pdf/authority-notice-model.ts` (`buildNoticePdfModel`) getrennt vom Renderer `pdf/authority-notice-pdf.ts` (pdfkit, `PDF_MARGIN`, `drawTable`); `noticeHeaderLines` ist rein und einzeln testbar.
|
||||
- **Endpunkt.** `GET /authority-notices/:id/pdf` (`compliance:read`) liefert `application/pdf`, `Cache-Control: no-store` und `Content-Disposition: attachment; filename="anzeige-<id>.pdf"` (Dateiname nur mit der Id, auch für TSK-Nachweise). `AuthorityNoticesService.pdf(id)` gibt `{ buffer, fileName }`; eine unbekannte Id ist 404.
|
||||
- **Inhalt.** Erstanzeige „Anzeige der Bienenhaltung (§ 1a BienSeuchV)“ ohne Spalte „vorher“; Änderungsanzeige „Änderungsanzeige Bienenhaltung (§ 1a BienSeuchV)“ mit „vorher“ je Stand, Summenzeile und der Liste „Änderungen seit der Anzeige vom {Datum}“ (Stand neu, aufgegeben, Lage geändert, Zahl der Völker). Lage = Adresse, sonst Koordinaten mit fünf Nachkommastellen, sonst Ort, sonst `FEHLT`.
|
||||
- **TSK-Zählnachweis in A4 quer.** Titel „Zählnachweis Bienenvölker zum Stichtag {Datum}“, eine Spalte je gezählter Völkerart (feste Reihenfolge) plus „Summe“, Zahlenspalten rechtsbündig, Spaltenbreite aus dem breitesten Wortteil (Mindestbreite 40 pt, Umbruch am Bindestrich), „Lage“ bekommt den Rest. Hinweis „Gezählt am {Tag}“, bei Zählung nach dem Stichtag „…, nicht am Stichtag. Bitte prüfen.“; Fußsatz „Ersetzt nicht die Meldung an die Tierseuchenkasse.“; kein Empfängerblock. Erst- und Änderungsanzeige bleiben Hochformat (Annahme 82). Rutscht die Unterschrift bei vielen Ständen auf Seite 2, ist das gewollt (kein Abschneiden).
|
||||
- **`FEHLT` statt Weglassen.** Halter, Veterinäramt, TSK-Nummer und die Lage eines Standes druckt der Renderer als `FEHLT`; die Registriernummer als „–“ (Spec 8.1). Fehlt beim Halter nur die Anschrift (oder nur der Name), steht `FEHLT` an dieser Stelle („Imkerei Muster, FEHLT“); nur wenn beides leer ist, ist `holder = null` und der Renderer druckt `FEHLT`.
|
||||
- **Summen aus dem gespeicherten `totalColonies`.** `totals.current` und `totals.previous` sind beide das gespeicherte `totalColonies` (der Anzeige bzw. der Bezugsanzeige); die Zeilen kommen weiter aus dem Bestandsbild. Weicht die Zahl von der Summe der Stände ab, steht vor den Änderungen „Gesamtzahl berichtigt (Summe der Stände: n)“; die Zeile „Zahl der Völker: a auf b“ nutzt dasselbe `totalColonies`. Das PDF druckt, was in der Anzeige gespeichert ist, keinen Live-Stand (Annahme 84).
|
||||
- **Richtiger Bezugsstand.** Entwurf: jüngste `SENT`-Anzeige (`findBaselineIn`). Gesendete Anzeige: die davor gesendete (`sentOn` kleiner, bei Gleichstand `createdAt` kleiner, andere Id), damit ein altes PDF nicht gegen einen später gesendeten Stand verglichen wird. Halter aus `SiteSettings`, Empfänger und Nummern aus `ComplianceSettings`. Fußzeile „Stand der Daten {updatedAt} · erstellt mit ApiCore“ (Berliner Tag). Das Briefdatum ist der Berliner Tag von `now`; der Ort daneben kommt aus der Postleitzahl-Zeile der Halteranschrift und bleibt leer, wenn keine gefunden wird (Annahme 83).
|
||||
- **Geteilter Tabellenhelfer.** `src/export/pdf-table.ts` hat zwei additive Optionen: `PdfColumn.align` (rechtsbündige Zahlenspalten) und `drawTable(…, { boldLastRow })` (fette Summenzeile). Standardverhalten und Kopfwiederholung beim Seitenumbruch bleiben unverändert. Nach `drawTable` setzt der Renderer `doc.x = PDF_MARGIN`, sonst liefen Notizen und Fußzeile im rechten Randstreifen.
|
||||
- Layout-Tests: 15 Stände mit langen Adressen ergeben eine Hochformat-Seite, Notizen und Fußzeile beginnen bei `PDF_MARGIN`, der TSK-Nachweis hat eine Querformat-MediaBox. Beispiel-PDFs wurden gerendert und angesehen (lesbar, Umlaute korrekt).
|
||||
|
||||
### 12.9 Hinweise und Tagesauswertung
|
||||
|
||||
Task 11 verbindet die Anzeigen mit dem Ereignis-Rückgrat (Abschnitt 10). `ComplianceModule` samt `ComplianceEventHandlers` ist in `AppModule` **und** `WorkerModule`; `worker-runtime.e2e-spec.ts` und `authority-notices-herd.e2e-spec.ts` prüfen, dass `compliance.herd-change` und `compliance.tsk-reference-day` in beiden Registern stehen.
|
||||
- **`recordForPermissionOnce`.** `NotificationsService.recordForPermissionOnce(permission, input, tx)` schreibt je Thema (`relatedType` + `relatedId`) und Nutzer höchstens eine **ungelesene** Meldung. Ein Advisory-Lock je Thema (`pg_advisory_xact_lock(hashtextextended('notify-once:<Typ>:<Id>', 0))`) ordnet Prüfung und Schreiben gleichzeitiger Transaktionen hintereinander (e2e: zwei parallele Transaktionen schreiben genau eine Zeile je Nutzer). Bewusst kein `dedupeKey`: Das Thema kommt wieder, sobald die Meldung gelesen ist. Empfänger sind aktive Nutzer mit aktiver Rolle und allen Rechten; `planIn` plant die Telegram-Zustellung in derselben Transaktion (Kategorie `COMPLIANCE`, Vorgabe-Kategorie). Texte unter 600 Zeichen, ohne Anschrift; der Link steht in `link`. Themen: `ComplianceItem` / `herd-change` und `ComplianceItem` / `tsk-report:<Jahr>`.
|
||||
- **`compliance.herd-change`.** Ereignisse: `ColonyCreated`, `ColonyMoved`, `ColonyEnded`, `ColonyStatusChanged` (nur Wechsel zwischen lebend und beendet) und `ApiaryChanged`. Der Handler berechnet über `herdStatusIn` die Abweichung vom Bezugsstand (außerhalb der Sperre, READ COMMITTED: schlimmstenfalls zu früh oder zu spät gemeldet, nie doppelt). Löst sie aus (`noticeOnColonyCountChange`, `noticeOnApiaryChange`), erhält jeder aktive Nutzer mit `compliance:manage` höchstens eine ungelesene Meldung „Bestand geändert: …“ (Priorität `HINWEIS`, Kategorie `COMPLIANCE`, Link `/compliance`). **Er sendet nur eine Meldung und legt nie eine Anzeige an**, auch keinen Entwurf (Spec 5.5, Annahme 78). Ein Stand-Umzug (`ApiaryChanged` mit Ortswechsel) zählt, ein Umbenennen nicht, ein Umsetzen zwischen Ständen löst nichts aus. Der CSV-Import emittiert `ColonyCreated` (Task 7), damit auch importierte Völker die Meldung auslösen.
|
||||
- **`compliance.tsk-reference-day`.** Ereignis `TskReferenceDayReached`. Unter der Sperre der Zeile `ComplianceSettings` legt der Handler einen TSK-Entwurf für das Jahr an (`createDraftIn`, 12.8), außer es gibt für das Jahr schon eine gesendete Anzeige oder einen offenen Entwurf. Dazu die Meldung „TSK-Stichtag TT.MM.JJJJ: n Völker gezählt. Bitte prüfen und melden.“ (`WARNUNG`, Kategorie `COMPLIANCE`, Link `/compliance/notices/<id>`). **Die Erinnerung geht auch, wenn nur ein Entwurf existiert** (kein neuer Entwurf, Link auf den vorhandenen, höchstens eine ungelesene je Nutzer); **bei einer gesendeten Anzeige bleibt der Handler still** (Annahme 79).
|
||||
- **Tagesregel `TskReferenceDayReached`.** Aggregat `Compliance`, `aggregateId tsk:<Jahr>`, Payload `{ year, referenceDay }`, Schlüssel `TskReferenceDayReached:tsk:<Jahr>:<Tag>`. Die Regel prüft den Stichtag des **Jahres des Berliner Laufs und des Vorjahres** mit einem **Nachholfenster von 7 Tagen**: Ein verpasster Lauf wird nachgeholt (Lauf am 05.03. nach verpasstem 03.03. ergibt ein Ereignis, einen Entwurf und eine Meldung je Nutzer). Der Tag ist der Berliner Kalendertag; den Stichtag liest die Regel aus der Zeile `ComplianceSettings` (`tskReferenceDay`). Im Code steht kein Vorgabewert: Fehlt die Zeile, legt `complianceSettingsIn(db)` sie mit dem Schema-Vorgabewert (`01-01`) an; die Migration `20261016100500` sät sie. Zweimal am Stichtag gelaufen heißt: ein Ereignis, ein Entwurf.
|
||||
- **Umschalter wirkt erst beim nächsten Ereignis.** Schaltet der Inhaber `noticeOnColonyCountChange` oder `noticeOnApiaryChange` von aus auf an und besteht bereits eine Abweichung, kommt die Meldung erst beim nächsten Herd-Ereignis; die Einstellung löst selbst kein Ereignis aus und kein Handler hört auf Einstellungsänderungen (Annahme 80).
|
||||
- Die e2e-Dateien der Stufe sichern und stellen die geseedete Zeile `ComplianceSettings` wieder her (nie `deleteMany` auf der Tabelle) und räumen nur selbst angelegte Anzeigen ab.
|
||||
|
||||
### 12.10 Prüfbereitschaft I
|
||||
|
||||
Task 12 liefert den Rahmen der Prüfbereitschaft mit den ersten sieben Regeln, Task 13 ergänzt die übrigen elf (zusammen die 18 der Spec, Ergänzungen am Ende dieses Abschnitts).
|
||||
- **Modul und Worker-Schutz.** `ReadinessModule` (`src/compliance/readiness/`) ist **nur in `AppModule`**. Der Controller hängt am `PermissionResolverService` und darf nicht in den Worker-Graphen. `readiness-worker-graph.spec.ts` läuft über die `imports` des `WorkerModule` und prüft, dass weder `ReadinessModule` noch `ReadinessController` darin liegen.
|
||||
- **`READINESS_RULES_TOKEN`.** Die Regelliste (`READINESS_RULES` in `rules/index.ts`) wird unter dem Token bereitgestellt; `ReadinessService` und `AcknowledgementsService` bekommen sie per Konstruktor. Unit-Specs übergeben Fake-Regeln direkt, die e2e überschreibt den Provider (`[...READINESS_RULES, softRule]`), ohne die geteilte Liste zu verändern. `rules/index.spec.ts` prüft eindeutige Schlüssel und eindeutige `subjectId` je Regel.
|
||||
- **Sieben reine Regeln.** Jede Regel ist eine pure Funktion `evaluate(ctx)`: `holder-data`, `food-business-data` (Pflicht), `vet-office` (Prüfen), `registration` (keine `SENT`-Erstanzeige), `herd-change` (Abweichung zum Bezugsstand laut Einstellung, nie ohne Bezugsstand), `tsk-report` (Stichtag erreicht ohne `SENT`-Zählung, „überfällig“ nach `tskReportDueDay`; das Vorjahr bleibt offen, solange sein Entwurf existiert) und `restriction-active` (ein Punkt mit allen gesperrten Ständen). Eine Regel ohne Befund ergibt genau einen erledigten Punkt (`DONE`, `subjectId` `global`). **Keine dieser sieben Regeln ist quittierbar** (Spec 5.7, Annahme 85); die Quittierung ist als Mechanik gebaut (`acknowledgeable`) und wird erst von den weichen Regeln aus Task 13 genutzt (vier quittierbare Regeln, siehe unten).
|
||||
- **Live-Auswertung, nur Quittungen gespeichert.** `GET /compliance/readiness` lädt einen Kontext (Stammdaten, Einstellungen, Bestandsstatus, Anzeigen, aktive Sperren, jeweils begrenzt) und führt jede Regel aus; gespeichert wird allein `ComplianceAcknowledgement`. Tage (`today`, Stichtag, „überfällig“) sind Berliner Kalendertage; die Sperre zählt über `isRestrictionActive`, dieselbe Funktion wie der Wächter an den Völker-Pfaden (12.7), damit Anzeige und Sperre nie auseinanderlaufen.
|
||||
- **Fingerabdruck.** sha256 über kanonisches JSON der für den Befund maßgeblichen Werte; Listen (z. B. `apiariesAdded/Removed/Relocated` bei `herd-change`) werden vorher **sortiert**, damit dieselben Daten in anderer Reihenfolge denselben Abdruck ergeben (Test).
|
||||
- **Quittung, Rücknahme, veraltet.** Quittiert wird mit Notiz (10 bis 2000 Zeichen); der Fingerabdruck muss zum jetzt berechneten Punkt passen (sonst 409). Eine Quittung gilt nur, solange sie nicht zurückgenommen ist **und** ihr Fingerabdruck noch passt: Eine **zurückgenommene oder veraltete Quittung öffnet den Punkt wieder**. Quittieren und Zurücknehmen schreiben Audit (`CREATE`/`UPDATE` an `ComplianceAcknowledgement`); das Zurücknehmen sperrt die Zeile und setzt `revokedAt` in SQL.
|
||||
- **Rot und Schwere.** Jeder offene Punkt ist rot; die Schwere steht als Wort („Pflicht“ oder „Prüfen“) daneben. Gesamtstatus `READY`, wenn kein Punkt offen ist, sonst `OPEN`.
|
||||
- **Höchstens 50 Subjekte.** Betroffene Objekte stehen in `subjects` (höchstens 50), der Rest wird in `more` gezählt.
|
||||
- **Maskierung je `subjectPermission`.** Titel und Detailtexte enthalten nie Namen, Anschriften, Aktenzeichen oder Notizen. Hat der Aufrufer das Recht der Regel (`subjectPermission`, hier `apiaries:read`) nicht, bleiben `subjects` leer und `more` zählt sie; `summary` wertet ohne Subjekte aus. Der Stammdaten-Punkt nennt nur die Lücke („Name“, „Anschrift“), nie den Wert. **Die Zählungen bleiben sichtbar** („N Stände liegen im Sperrbezirk“), auch maskiert; die Seite verlangt ohnehin `compliance:read`, nur die Namen hängen am Recht (Annahme 81). Die Arzneimittel-Regeln aus Task 13 halten Mittel, Packung, Lieferant und Tierarzt aus `detail` und `title` heraus; welches Recht die Namen freigibt, steht je Regel in der Tabelle unten.
|
||||
- **Lesepfade schreiben nicht.** `loadReadinessContext` liest `SiteSettings` per `findUnique`; fehlt die Zeile, gilt ein leerer In-Memory-Standard (alle Felder `null`, `holder-data` meldet die Lücken), kein Upsert. `ComplianceSettings` kommt aus `herdStatusIn` (12.8), das nur anlegt, wenn die von der Migration gesäte Zeile fehlt.
|
||||
- **Registrierungs-Bezug separat.** Die jüngste `SENT`-Erstanzeige (nach `sentOn`, `createdAt`, `id`) und der jüngste `DRAFT` werden in **eigenen Abfragen** gelesen, nicht aus einer begrenzten Gesamtliste; nur der TSK-Teil ist auf 100 begrenzt. Der Bezugsstand für `herd-change` kommt unverändert aus `herdStatusIn` (`findBaselineIn`).
|
||||
- **Endpunkte.** `GET /compliance/readiness`, `GET /compliance/readiness/summary` (`compliance:read`); `POST /compliance/acknowledgements` (`@Idempotent`) und `POST /compliance/acknowledgements/:id/revoke` (`compliance:manage`). BEEKEEPER und ADMIN alles, STAFF und READONLY nur Lesen, API_CLIENT nichts.
|
||||
- Oberfläche: Die Zuordnung „Schwere → Wort“ und „`OPEN` → rot mit Symbol und Wort“ hat seit Task 14 einen eigenen Test (`labels.spec.ts`, Abschnitt 12.11).
|
||||
|
||||
**Task 13: die 18 Prüfpunkte.** Die Liste `READINESS_RULES` hat jetzt 18 Regeln in fünf Bereichen; `rules/index.spec.ts` prüft Bereich, Schwere, `acknowledgeable` und `subjectPermission` aller 18. Alle Regeln sind weiter reine Funktionen auf dem Kontext (`loadReadinessContext(db, now, { withdrawal })` mit den Feldern `treatments`, `moves`, `lots`, `medicines`, `templates`, `harvests`; `ReadinessModule` importiert dafür `WithdrawalModule`).
|
||||
|
||||
| Bereich | Regel (Schlüssel) | Schwere | quittierbar | Namen frei mit |
|
||||
|---|---|---|---|---|
|
||||
| Stammdaten | `holder-data`, `food-business-data` | Pflicht | – | – |
|
||||
| Stammdaten | `vet-office` | Prüfen | – | – |
|
||||
| Behörden | `registration`, `herd-change`, `tsk-report`, `restriction-active` | Pflicht | – | `apiaries:read` bei `herd-change`, `restriction-active` |
|
||||
| Tierarzneimittel | `treatment-log-gaps` (ein Punkt je Kalenderjahr) | Pflicht | – | `treatments:read` |
|
||||
| Tierarzneimittel | `lot-gaps`, `lot-prescription` | Pflicht | – | `veterinary-medicines:read` |
|
||||
| Tierarzneimittel | `treatment-location-uncertain` | Prüfen | – | `treatments:read` |
|
||||
| Tierarzneimittel | `medicine-withdrawal-missing`, `lot-negative` | Prüfen | – | `veterinary-medicines:read` |
|
||||
| Tierarzneimittel | `lot-expired-stock` (je Packung), `treatment-expired-lot` (je Behandlung) | Prüfen | ja | `veterinary-medicines:read` |
|
||||
| Etiketten | `label-template-gaps` | Pflicht | – | – |
|
||||
| Etiketten | `label-template-form` | Prüfen | ja | – |
|
||||
| Ernte | `harvest-withdrawal` (je Ernte) | Prüfen | ja | `treatments:read` |
|
||||
|
||||
- **Gleiche Funktionen wie das PDF.** `treatment-log-gaps` nutzt `resolveSourceValues`, `treatmentLogGaps` und `groupTreatmentLog` des Bestandsbuchs (12.2): Rückblick sind das laufende und fünf vorige Kalenderjahre (Jahr der UTC-Zeit wie im PDF; ein Eintrag um Mitternacht zum Jahreswechsel kann im Nachbarjahr stehen). Eine lückenhafte Packung steht einmal als Subjekt `LOT` (Label „Packung der Behandlungen“), Behandlungen ohne Packung als Subjekt `TREATMENT` mit dem Volk als `parentId`; Mengen- und Wartezeitlücken bleiben auf der Behandlung, die Tierarzt-Lücke gibt es nur bei verschreibungspflichtigem Mittel. `treatment-location-uncertain` meldet die `*`-Zeilen (`apiaryOnDate(...).uncertain`). `medicine-withdrawal-missing` zählt 0 Tage als erfasst. `lot-expired-stock` nimmt den Rest in den Fingerabdruck auf: Ändert sich der Rest, öffnet sich die Quittung wieder.
|
||||
- **Etiketten.** `label-template-gaps` und `label-template-form` prüfen jede aktive Vorlage mit demselben `checkLabel` wie der Druck (12.4, 12.6; `buildPlaceholderValues`, `expectedParticulars`, Ziffernregeln nur aus `ComplianceSettings`), je Vorlage einmal gemessen (`label-checks.ts`). `label-template-form` meldet nur Warnungen, sein Fingerabdruck sind die Warn-Codes. **Das Ziel der Prüfung ist die jüngste Abfüllung mit Restbestand**: Der Lader liest die Abfüllungen seitenweise (200, neueste zuerst) und hört bei der ersten mit Restbestand (`summarizeStock`) auf; gibt es keine, gilt die jüngste, sonst `SAMPLE_BOTTLING` (Beispielwerte). Ungültige `netQuantityDigitRules` ergeben in der Prüfbereitschaft „keine Regel“ (die Höhe der Füllmenge wird nicht beurteilt), der Druck lehnt sie dagegen mit 409 ab.
|
||||
- **Ernte.** `harvest-withdrawal` rechnet keine Fenster selbst: Der Lader ruft `WithdrawalCheckService.conflictsForHarvests` für die Ernten der letzten 24 Monate auf, der Text kommt aus `withdrawalRangeText` (längstes Fenster).
|
||||
- **Arzneimittel-Namen maskiert.** Regeln mit `subjectPermission: 'veterinary-medicines:read'` zeigen Packungen und Behandlungen ohne dieses Recht nur gezählt (`subjects` leer, `more` zählt). Titel, Text und Subjekt-Labels enthalten **nie Produktnamen** oder Mittelnamen; ein Label heißt allgemein („Packung der Behandlungen“), die Zuordnung zum Mittel steht erst hinter dem Beheben-Link. Die Namen der Lücken (`missing`) sind deutsche Feldnamen (Lieferant, Beleg, Menge, Wartezeit, Tierarzt) bzw. die Titel der Etikett-Befunde. Neue Subjekt-Typen: `TREATMENT`, `LOT`, `MEDICINE`, `LABEL_TEMPLATE`, `HARVEST`.
|
||||
- **Prüfbericht als PDF.** `GET /compliance/readiness/report.pdf` (`compliance:read`) liefert `pruefbericht.pdf` (A4 hoch, `no-store`, `renderReadinessReportPdf` in `readiness-report.ts`). Inhalt: Kopf mit Halter (`FEHLT`, wenn leer), Datum, Gesamtstatus und dem Satz „Jeder offene Punkt ist zu behandeln.“, je Bereich eine Tabelle mit Status (Offen, Erledigt, Quittiert), Schwere als Wort, Titel, Text, Norm (130 pt breit, „Fertigpackungsverordnung“ in einer Zeile) und bei Quittungen Notiz, Nutzer und Datum. **Gedruckt werden nur Zählungen** („n Objekte“), nie Namen von Objekten (Annahme 90); Quittungsnotizen werden nach 600 Zeichen mit „…“ gekürzt. Die Auswertung läuft mit den Rechten des Aufrufers. Ein Aufrufer mit `compliance:read` ohne `veterinary-medicines:read` bekommt 200, und das PDF enthält weder Mittelnamen noch Behandlungsprodukte (e2e).
|
||||
- **Kurzfassung gecacht.** `ReadinessService.summary(now)` hält das Ergebnis je Prozess 60 Sekunden (`SUMMARY_TTL_MS`, Zeitbasis ist das übergebene `now`). `AcknowledgementsService.create` (nach Erfolg) und `revoke` rufen `invalidateSummary()` auf; ein abgelehntes Quittieren lässt den Cache stehen. Liste (`GET /compliance/readiness`), PDF-Bericht und Quittierpfad rechnen immer live. Änderungen an den Daten und Quittungen anderer Prozesse zeigen sich in der Kurzfassung bis zu 60 Sekunden später (Annahme 86).
|
||||
- **409-Codes beim Quittieren.** Die Antwort hat den Körper `{ code, message }` (Meldungen unverändert): `READINESS_FINGERPRINT_STALE` (Fingerabdruck passt nicht mehr; „Der Punkt hat sich geändert. Bitte neu laden.“), `READINESS_ITEM_NOT_OPEN` (Punkt weg oder erledigt; gleiche Meldung) bei `POST /compliance/acknowledgements`, und `READINESS_ACK_REVOKED` („Die Quittung ist schon zurückgenommen.“) bei `…/:id/revoke`. Die Konstanten stehen in `acknowledgements.service.ts`; die Oberfläche wertet die Codes aus (12.11), der Text ist nur Rückfall.
|
||||
- **Lastgrenze.** Eine Auswertung lädt alle Packungen, sechs Jahre Behandlungen und die Ernte-Konflikte (`windowsOf` liest alle Behandlungen der beteiligten Völker). Das ist für den Betrieb unkritisch und der Grund für den 60-s-Cache der Kurzfassung (Dashboard); bei sehr vielen Daten sind Index oder weitere Zwischenspeicher zu prüfen. Einzelpunkte je Behandlung oder Ernte können lang werden, die Oberfläche klappt sie ein.
|
||||
|
||||
### 12.11 Oberfläche (Frontend)
|
||||
|
||||
Die Oberfläche des Compliance-Blocks entstand in Task 14 bis 19: Prüfbereitschaft (14), Tierarzneimittel (15), Behandlungsmaske (16), Etikett (17), Anzeigen und Einstellungen (18) und Sperrbezirk (19). Alle Aktionen sind online-only: Auslöser sind offline deaktiviert und nennen den sichtbaren Grund „Nur mit Verbindung“ (`aria-describedby`). Der Service-Worker-Ausschluss steht in Abschnitt 2.
|
||||
|
||||
**Prüfbereitschaft (Task 14).** Code in `lib/compliance/` (`types`, `api`, `fix-links`, `errors`, `labels`, `use-readiness`; Query-Schlüssel `['compliance', …]`) und `app/(app)/compliance/`.
|
||||
- **Seite `/compliance`** zeigt `GET /compliance/readiness`. Oben der Status: „Prüfbereit“ (grün) oder „n offen“ (rot), jeweils mit Symbol und Wort. **Jeder offene Punkt ist rot** (Token `destructive`) und trägt Symbol, das Wort „Offen“, die **Schwere als Wort „Pflicht“ oder „Prüfen“** und den Titel; dazu ein Satz Detail und klein die Norm. Betroffene Objekte stehen eingeklappt mit einem „Beheben“-Link je Objekt, „und n weitere“ für den Rest; fehlt das Recht auf die Namen, steht nur „n betroffen“. Erledigte Punkte stehen eingeklappt unter „Erledigt (n)“, Quittierte ruhig mit Nutzer, Datum und Notiz. Die Zuordnung Schwere → Wort und offen → rot liegt allein in `labels.ts` und hat einen eigenen Test. Hauptaktion ist „Nächsten Punkt lösen“ (erster offener Pflicht-Punkt); ist dessen Ziel noch nicht gebaut, heißt sie „Nächsten Punkt ansehen“ und springt auf die Karte (`#item-<Schlüssel>-<Subjekt>`). Bei grünem Status steht dort „Bestandsbuch {Jahr} drucken“. Hinter „Mehr“ liegen der Bericht (PDF über `downloadReadinessReport`, als Blob mit Bearer-Header, Dateiname `pruefbericht.pdf`), das Bestandsbuch, Anzeigen, Sperrbezirke und Einstellungen. Downloads sind offline aus.
|
||||
- **Beheben-Links aus einer Stelle:** `fixLinkFor(itemKey, subject)` in `fix-links.ts` bildet Subjekte auf Seiten ab (Typen ohne Beachtung der Groß-/Kleinschreibung). Die Ziele `/compliance/notices(/[id])`, `/compliance/restrictions` und `/compliance/settings` schaltet `ROUTE_AVAILABLE` seit Task 18 und 19 ein (vorher blendete die Menge solche Links aus, `available: false`). Eine Behandlung verlinkt auf `/colonies/{parentId}`, Stammdaten auf `/settings/automation?tab=social-media` (Reiter „Stammdaten & Web“). `herd-change` führt zur Anzeige (`/compliance/notices`), nicht zur Sperrenliste; `restriction-active` ohne Subjekt zur Sperrenliste.
|
||||
- **Quittieren und Zurücknehmen** (`acknowledge-dialog.tsx`): nur bei `acknowledgeable` und offenem Punkt bzw. quittiertem Punkt, nur mit `compliance:manage`. Notiz 10 bis 2000 Zeichen, vor dem Senden geprüft; Zurücknehmen über `ConfirmDialog`. Fehler laufen über `readinessConflictText`, der die drei Codes `READINESS_FINGERPRINT_STALE`, `READINESS_ITEM_NOT_OPEN` und `READINESS_ACK_REVOKED` mit je eigenem deutschem Text auswertet (der Servertext ist nur Rückfall); bei jedem 409 laden alle `compliance`-Queries neu. Nach Erfolg und Neuladen geht der Fokus auf die Kartenüberschrift (`tabIndex=-1`), eine `role="status"`-Region sagt „Punkt quittiert“ bzw. „Quittung zurückgenommen“. `lib/compliance/errors.ts` liest außerdem `DRAFT_EXISTS` und `RESTRICTED_ZONE`, alles andere läuft über `saveErrorText`; es gibt keine zweite Fehlerlogik.
|
||||
- **Dashboard-Zeile** (`components/today/compliance-line.tsx`): „n Punkte offen in der Prüfbereitschaft“, nur mit `compliance:read` und `openCount > 0`, aus `GET /compliance/readiness/summary` (60 s gecacht, Annahme 86). Schlägt das Laden fehl (kein Netzfehler; offline bleibt es still), steht eine **Fehlerzeile** „Prüfbereitschaft nicht geladen.“ mit „Erneut versuchen“.
|
||||
- **Navigation:** `nav-config.ts` hat „Prüfbereitschaft“ (Symbol `ShieldCheck`, Gruppe „Betrieb“, Recht `compliance:read`).
|
||||
|
||||
**Tierarzneimittel (Task 15).** Seiten unter `app/(app)/medicines/`, Daten aus `lib/medicines/api.ts`; kein eigener Nav-Eintrag, der Einstieg ist die Karte „Tierarzneimittel“ auf `/storage` (nur mit `veterinary-medicines:read`).
|
||||
- **Seiten.** `/medicines` (Katalog mit Rest und nächstem Verfall, Reiter Aktiv/Deaktiviert; bei leerem Katalog „Aus deinen Behandlungen übernehmen?“ mit `GET …/suggestions`: „Übernehmen“ öffnet nur das Formular, gespeichert wird erst beim Absenden), `/medicines/[id]` (Angaben, Packungen, Hauptknopf „Packung erfassen“) und `/medicines/lots/[id]` (Rest, Angaben, Bewegungsbuch, Beleg, Hauptknopf „Inventur“). Hauptknöpfe: „Mittel anlegen“ (`create`), „Packung erfassen“ (`create`), „Inventur“ (`update`); Entsorgung, Bearbeiten und (De-)Aktivieren sind Nebenaktionen mit `update`. Ist das Mittel inaktiv, ist „Packung erfassen“ mit sichtbarem Grund „Das Mittel ist deaktiviert.“ gesperrt (Annahme 61). Mit Packungen entfällt das Einheitsfeld (Annahme 62), `unit` wird nie gesendet; geleerte Felder gehen als `null` hinaus.
|
||||
- **Dialoge.** Mittel, Packung, Inventur (zeigt die Differenz live in einem `aria-live`-Bereich, Buchen bei Differenz 0 gesperrt) und Entsorgung (Menge, Pflichtgrund; über den Rest hinaus erlaubt, mit roter Warnung samt Symbol und Wort „Negativ“). Server-Meldungen („Das Mittel ist deaktiviert.“, „Die Einheit des Mittels passt nicht zur Packung.“) erscheinen im Dialog. Ein negativer Rest erscheint überall rot mit Warnsymbol und Wort (`RestText`).
|
||||
- **`use-attempt-key`** (`lib/medicines/use-attempt-key.ts`, Ansatz der Abfüllung): Jeder Anlege- und Buchungsaufruf trägt einen `Idempotency-Key`. Der Schlüssel bleibt nur, wenn der Body unverändert ist und der letzte Versuch am Netzwerk scheiterte; jede Serverantwort ohne Erfolg und jede Änderung des Bodys erneuert ihn (sonst würde der Server mit dem Schlüssel einen alten Body wiedergeben). Er gilt in allen vier Dialogen.
|
||||
- **`parseDecimal`: Tausenderpunkt-Regel.** Das Komma ist immer das deutsche Dezimalzeichen („1,000“ ist 1). Ein Punkt gilt nur als Dezimalpunkt, wenn er das einzige Trennzeichen ist und nicht wie ein Tausenderpunkt aussieht (`^\d*[1-9]\d*\.\d{3}$`). „1,5“, „1.5“ und „0.001“ gehen; **„1.000“**, „12.345“ und jeder Text mit mehr als einem Trenner (auch „1.234,5“) sind ungültig mit „Bitte ohne Tausenderpunkt eingeben, z. B. 1000 oder 1,5“ (Annahme 88). Gilt in allen Mengenfeldern; sie sind Textfelder mit `inputMode="decimal"`.
|
||||
- **Bewegungsbuch** (`lib/medicines/book.ts`): Eingang als erste Zeile, laufender Stand auf Tausendstel gerundet, neueste zuerst, Datum ist der Berliner Tag der Buchung. **Hinweis bei Abweichung:** Weicht der letzte rechnerische Stand von `lot.remaining` des Servers ab, steht unter der Tabelle „Stand weicht vom Server ab – bitte neu laden“.
|
||||
- **Seite ohne Leserecht.** Die drei Seiten laden ohne `veterinary-medicines:read` nichts (`enabled: false`) und zeigen „Dazu fehlt dir das Recht.“ ohne Erneut-Knopf (`components/medicines/no-read-access.tsx`, Link zurück zum Lager).
|
||||
- **Belege.** `DocumentUploadCard` (Art `MEDICINE_LOT`, Titel „Beleg“) hat die Eigenschaft `canWrite` (Vorgabe `true`); die Packungsseite übergibt `canWrite={canUpdate}`. Ohne sie entfallen Hochladen, Umbenennen und Löschen, Herunterladen bleibt. `DocumentEntityType` kommt aus `DOCUMENT_ENTITY_TYPES` und kennt `MEDICINE_LOT`, `AUTHORITY_NOTICE`, `APIARY_RESTRICTION`.
|
||||
- **Hinweis Bestandsbuch (Annahme 73).** Auf der Standseite ist der Menüeintrag „Bestandsbuch (PDF)“ ohne `veterinary-medicines:read` deaktiviert (und nicht fokussierbar, weil die Menükomponente `aria-disabled` nicht zulässt); dauerhaft steht darunter die Zeile „Das Bestandsbuch braucht das Recht „Tierarzneimittel lesen“.“. Für Task 16: `fetchSelectableLots(medicineId, includeLotId?)` liefert nur Packungen aktiver Mittel mit Rest > 0.
|
||||
|
||||
**Etikett (Task 17).** Das Frontend entscheidet nichts über Pflichtangaben; es zeigt, was das Backend (12.4, 12.6) prüft.
|
||||
- **Prüfpanel im Designer** (`components/labels/label-compliance-panel.tsx`): Der Designer sendet 500 ms nach der letzten Änderung nur die Text-Elemente an `POST /label-templates/check` (Hook `useDebouncedLabelCheck` in `lib/label-templates/check.ts`; nur Text-Änderungen lösen aus, Eingaben außerhalb des technischen Bereichs lösen keinen Aufruf aus). Ein neuer Entwurf und das Aushängen **brechen den laufenden Aufruf ab** (`AbortSignal`); bei einem ungültigen Entwurf bleibt das letzte Ergebnis stehen, ist aber als „Veraltet: …“ markiert (`stale`). Das Panel zeigt die sechs Pflichtangaben mit Symbol und „Erfüllt“/„Fehlt“, Hinweise getrennt und mit „Hinweis:“ beginnend; die Live-Region (`aria-live="polite"`) enthält nur die Summenzeile.
|
||||
- **Keine Rechtszahlen im Frontend.** Mindest-x-Höhe und Ziffernhöhen kommen ausschließlich aus `requirements` der Prüfantwort („Die Prüfung verlangt aktuell mindestens X mm“); der Hinweistext am Feld „Mindest-x-Höhe (mm)“ nennt keine Zahl, `DEFAULT_MIN_X_HEIGHT_MM` gibt es nicht. Der Pflichtangaben-Block (`compliance-block.ts`, „Pflichtangaben-Block einfügen“, mit Rückgängig) rechnet die Schriftgrößen aus `requirements`. Die Schranken 0,5 bis 5 mm des Feldes sind der technische Bereich des DTO, kein Rechtswert. Eine neue Vorlage startet mit leerem Feld und sendet kein `minXHeightMm` (der Server setzt seinen Standard); bis ein Wert da ist, läuft keine Prüfung (Annahme 89).
|
||||
- **Druckkarte der Abfüllung** (`bottling/[id]/print-labels-card.tsx`): Vor dem Anzeigen läuft `GET /label-templates/:id/check/:bottlingBatchId` (`gcTime: 0`, keine Persistenz, `cache: "no-store"`). Bei Lücken zeigt sie die **rote Lückenliste** (Region, Symbol und „Fehlt:“) mit Links zu Stammdaten, Produkt und Designer (der Produktlink entfällt ohne Produkt an der Abfüllung); „Etiketten als PDF“ ist dann `aria-disabled` (fokussierbar, Grund per `aria-describedby`). Der **Probedruck** („Probedruck (MUSTER)“, `proof=true`) bleibt immer möglich; sein Dateiname enthält „muster“, der des echten Drucks nicht. Antwortet der Druck mit 409 `LABEL_PARTICULARS_MISSING`, zeigt die Karte die Liste `gaps` des Servers und **setzt den Fokus darauf**. 409 `COMPLIANCE_SETTINGS_INVALID` und 403 erscheinen als deutsche Meldung (`labelCheckErrorText`). Ein zweiter Klick während der Wartezeit löst keinen zweiten Aufruf aus. Ohne `label-templates:read` steht nur ein Hinweis, ohne `:print` gibt es keine Druckknöpfe, ohne Netz „Nur mit Verbindung“. Prüf- und Druckaufrufe laufen mit `cache: "no-store"` (`apiFetchBlob` reicht `init` durch).
|
||||
- **Stammdaten.** Im Reiter „Stammdaten & Web“ (Verwaltung > Automatisierung) stehen `foodBusinessName` (200) und `foodBusinessAddress` (300); **leere oder nur aus Leerzeichen bestehende Felder werden als `null` gesendet** (`value.trim() || null`), damit sie serverseitig löschen. „Vom Bienenhalter übernehmen“ füllt nur die Felder, ohne zu speichern. Der Text nennt, dass sie weder im Shop noch auf der Herkunftsseite erscheinen.
|
||||
- **Produkt `legalName`.** Das Feld „Bezeichnung auf dem Etikett (z. B. Blütenhonig)“ steht im Typ `Product`, im Neu-Formular, im Bearbeiten-Dialog und auf der Detailseite; Platzhalter-Schlüssel und deutsche Labels liegen in `lib/label-templates/placeholder-keys.ts` (Wächter-Spec gegen `test/fixtures/placeholder-keys.json`).
|
||||
|
||||
**Behandlung mit Mittel, Packung und Dosis (Task 16).** Formular „Neue Behandlung“, Dialog „Behandlung bearbeiten“ und Sammelerfassung.
|
||||
- **Mittel.** „Aus dem Katalog wählen“ bietet die aktiven Mittel (nur mit `veterinary-medicines:read`; ohne das Recht gibt es nur „Anderes Mittel“, ohne Fehler); „Anderes Mittel“ ist die letzte Option mit dem Freitextfeld wie bisher. Ein Katalogmittel füllt Wirkstoff, Wartezeit, Methode und Dosis als sichtbaren, bearbeitbaren Vorschlag mit dem Vermerk „aus Katalog“. Er gewinnt gegen die Vorbelegung aus der letzten Behandlung, überschreibt aber nie, was der Nutzer getippt hat; der Server füllt nichts nach. Lade- und Fehlerzustand des Katalogs zeigt `PrefillStatus`, Speichern bleibt möglich.
|
||||
- **Packung.** Beim Anlegen wird die Packung mit dem frühesten Verfall vorgewählt (mit Hinweis); „Ohne Packung“ bucht nichts und wird nicht wieder überschrieben. **Beim Bearbeiten wählt die Oberfläche nie selbst eine Packung vor** (nach einem Mittelwechsel steht „Ohne Packung“, der Nutzer wählt; Annahme 92). Ist eine Packung gesetzt, stammen Chargennummer, Lieferant, Beleg und Tierarzt aus der Packung (Zeile „aus Packung: …“); die Nutzlast lässt diese Felder weg (der Server lehnt Text daneben mit 400 ab), `product` entfällt mit Katalogmittel. Über „Speichern“ steht die Buchungszeile („Bucht 30 ml je Volk ab (× 6 = 180 ml).“, in der Sammelerfassung mal Anzahl der Völker). Abgelaufene oder zu kleine Packungen warnen, blockieren nie. Der Temperaturhinweis („Heute 9–17 °C. Laut Katalog 12–25 °C.“) kommt aus `GET /apiaries/:id/weather` (`apiaries:read`) und entfällt still, wenn das Wetter fehlt.
|
||||
- **Dosis.** Dezimalfeld, kein `NumberStepper` (der kennt nur ganze Zahlen): Komma als Dezimalzeichen, mindestens 0,001, **höchstens 3 Nachkommastellen** („Höchstens 3 Nachkommastellen.“, Annahme 94), „1.000“ wird als mehrdeutig abgelehnt (Annahme 88).
|
||||
- **Mittelwechsel beim Bearbeiten.** Der Dialog nutzt dieselbe Katalog-Vorbelegung wie das Anlegen; was die Behandlung schon enthält, gehört dem Nutzer, nur leere Felder füllt der Katalog. Eine vorhandene Wartezeit wird beim Wechsel nie still ersetzt: Weicht sie vom Katalogwert des neuen Mittels ab (oder kennt der Katalog keinen), steht am Feld „Wartezeit stammt vom vorherigen Mittel – bitte prüfen.“, dazu der Knopf „aus Katalog übernehmen“ (nur mit Katalogwert) als ausdrückliche Übernahme. Eine Eingabe im Feld entfernt die Warnung.
|
||||
- **Patch.** `medicinePatch` sendet die Mittel-Gruppe (`product`, `medicineId`, `medicineLotId`, `doseQuantity`, vier Packungstexte) nur, wenn sich in ihr etwas geändert hat; eine reine Notiz-Änderung bleibt so immer möglich.
|
||||
- **Fehler und Deep-Link.** Anlegen und Dialog lesen Fehler über **einen** Leser, `saveErrorText` (kennt auch Feldfehler-Listen des Servers). `?editTreatment=<id>` an der Volksseite öffnet den Dialog dieser Behandlung; findet die geladene Liste die ID nicht, sagt eine Live-Region „Behandlung nicht gefunden.“.
|
||||
- **Entwurf wiederherstellen** (`treatments/new`): Ist das Mittel des Entwurfs nicht mehr im Katalog, nicht aktiv oder fehlt das Leserecht, fallen `medicineId` und `medicineLotId` weg, `product` bleibt als Freitext, und eine Statuszeile sagt „Das Mittel aus dem Entwurf ist im Katalog nicht mehr aktiv. Bitte wähle es neu.“ Ist die Katalogliste noch nicht geladen, wird nichts verworfen.
|
||||
|
||||
**Anzeigen und Einstellungen (Task 18).** Seiten unter `app/(app)/compliance/`, Fehlertexte über `complianceErrorText` (`lib/compliance/errors.ts`).
|
||||
- **Liste `/compliance/notices`:** Anzeigen ans Veterinäramt (Art, Jahr, Status mit Symbol und Wort, Völkerzahl, Stichtag), Filter nach Art und **Jahresfilter** (vier Ziffern, sonst Hinweis am Feld; Server-Query `year`). Ab 200 Einträgen steht der Hinweis „Es werden die neuesten 200 angezeigt.“ (Obergrenze der Liste).
|
||||
- **Anlegen:** „Anzeige anlegen“ (nur `compliance:manage`) öffnet einen Dialog (Erstanzeige, Bestandsänderung, TSK-Zählung mit Jahr; „Bereits angezeigt“ mit Datum legt direkt eine gesendete an). Der Aufruf trägt einen `Idempotency-Key`. Gibt es schon einen Entwurf, antwortet der Server 409 `DRAFT_EXISTS` mit `existingId`; der Dialog verlinkt auf den vorhandenen Entwurf.
|
||||
- **Detail `/compliance/notices/[id]`** mit drei sichtbaren Schritten (1. PDF öffnen, 2. ans Amt schicken, 3. hier bestätigen; je Symbol und Wort Jetzt/Danach/Erledigt). Der **PDF-Download** (authentifiziert, kein Token im Link) meldet in der `aria-live`-Region „PDF heruntergeladen. Schick es jetzt ans Amt.“ und setzt den Fokus auf die neue Hauptaktion. **„Als gesendet markieren“ ist im Entwurf immer erreichbar**: als zweite Aktion (Umrissknopf neben „Neu zählen“), nach dem PDF als Hauptaktion; so geht es auch nach einem Neuladen ohne erneutes PDF. Das Sendedatum und „Gesendet am“ nutzen den **Berliner Kalendertag** (`berlinCalendarDay`); ein geleertes Datum zeigt „Das Datum kann nicht entfernt werden.“ „Neu zählen“ und „Anzeige stornieren“ gibt es nur im Entwurf, „Wieder öffnen“ nur bei gesendeter Anzeige; Kopie und Eingangsbestätigung sind Dokumente der Art `AUTHORITY_NOTICE`. Mit nur `compliance:read` fehlen die Aktionsknöpfe. `complianceErrorText` übersetzt 403 („Dazu fehlt dir das Recht.“) und 5xx („Der Server hat einen Fehler gemeldet. Versuch es gleich noch einmal.“) und fügt eine 400-Antwort mit `message: string[]` zusammen; Nests Englisch erscheint nie.
|
||||
- **Einstellungen `/compliance/settings`:** Veterinäramt, Erinnerungs-Schalter (Völkerzahl, Stand), TSK-Stichtag und Meldefrist, Mitgliedsnummer. Jeder Rechts- und Fristwert trägt am Feld „Annahme – bitte prüfen“. Stichtag und Meldefrist (leer erlaubt) prüft der Client vor dem Senden auf `MM-TT` (`isValidMonthDay`, Tage je Monat im Nichtschaltjahr, „02-29“ ungültig; Hinweis „Bitte einen Tag im Format MM-TT eingeben, zum Beispiel 03-31. Den 29. Februar gibt es hier nicht.“, `aria-describedby`, kein Request). Unter „Erweitert“ stehen die gezählten Völkerarten und der **Editor der Ziffernregeln** (1 bis 10 Regeln; „Regel hinzufügen“ fügt vor der letzten ein, „Entfernen, Regel n“; Höhe 0,5 bis 20 mm, Obergrenzen > 0 und aufsteigend, die letzte Regel hat keine Grenze und geht als `null` hinaus). Die Schranken sind die Grenzen des Backends (`assertDigitRules`, Konstanten in `compliance-settings.service.ts`), keine Rechtswerte; Fehler stehen an der Zeile (`role="alert"`) und als Satz „Bitte die Ziffernhöhen unter „Erweitert“ prüfen.“, weil der Abschnitt eingeklappt sein kann. Ohne `compliance:manage` sind die Felder nur lesbar.
|
||||
- **Formular-Schutz:** Ein Hintergrund-Refetch setzt eine Eingabe nie zurück. Ohne Eingabe werden neue Serverdaten still übernommen; mit ungespeicherter Eingabe bleibt sie stehen, und „Daten wurden geändert – neu laden?“ mit „Neu laden“ erscheint. Nach eigenem Speichern wird der Zustand direkt übernommen.
|
||||
- **Meldungskategorie `COMPLIANCE`** („Behörden & Prüfung“) steht in `lib/notifications/labels.ts` und damit in der Kategorienauswahl der Telegram-Karte. Die Glocke zeigt dafür das Kurz-Etikett „Behörden“ (Annahme 93).
|
||||
|
||||
**Sperrbezirk (Task 19).** Aktive Sperren lädt jede Seite einmal (`useActiveRestrictions`, Schlüssel `['compliance','restrictions','active']`, `staleTime` 30 s, Neuladen beim Fokus; Umsetzen- und Vereinigen-Dialog laden beim Öffnen neu). Der Server entscheidet endgültig, der Browser blendet nur früh aus.
|
||||
- **Seite `/compliance/restrictions`** (Recht `compliance:read`, Pflege mit `compliance:manage`; ohne Leserecht `NoComplianceAccess` „Dazu fehlt dir das Recht.“ und keine Abfragen) mit drei Abschnitten **Aktiv / Geplant / Beendet** (Symbol und Wort; `restrictionState` rechnet nach dem Berliner Kalendertag, eine Sperre mit Beginn in der Zukunft steht unter „Geplant“, nie unter „Beendet“). Die Live-Region sagt nur Laden und Fehler. Die Verfügung hängt als Dokument (`APIARY_RESTRICTION`, `DocumentUploadCard`, schreibend nur mit `compliance:manage`; ohne Leserecht entfällt die Zeile „Verfügung“).
|
||||
- **Anlegen:** „Sperrbezirk anlegen“ legt je gewähltem Stand (1 bis 50) einen Eintrag an (Seuche: Amerikanische Faulbrut, Kleiner Beutenkäfer oder Andere mit Freitext; Beginn, optional Ende, Behörde, Aktenzeichen, Notizen) mit `Idempotency-Key`.
|
||||
- **Beenden:** Der Dialog setzt nur `endsOn` (der Eintrag wird nie gelöscht). **Vorgabe ist „gestern“** (nicht vor dem Beginn); `endsOn` gilt **einschließlich**. Ist der gewählte Endtag heute oder später, zeigen Hinweis und Toast „Die Sperre gilt noch bis einschließlich TT.MM.JJJJ.“. **Ein Aufheben am selben Tag ist nicht möglich** (Annahme 91): Ist die Sperre heute aufgehoben, trägt man gestern ein, außer sie begann heute, dann gilt sie bis einschließlich heute.
|
||||
- **Rotes Band** am Stand, solange eine Sperre aktiv ist, mit dem Link „Sperrbezirke ansehen“ (Link nur mit `compliance:read`).
|
||||
- **Wächter** bei Umsetzen (Quell- und Zielstand), Vereinigen über verschiedene Stände, Standkorrektur am Volk und neuem Volk: rote Meldung („Stand {Name} liegt im Sperrbezirk ({Krankheit}, seit {Datum}). … ist gesperrt.“; ohne Servertext der Rückfall „Der Stand liegt im Sperrbezirk.“) mit Symbol und Wort in einer persistenten `aria-live`-Region. Der Hauptknopf ist `aria-disabled` mit `aria-describedby` auf den Grund (bleibt fokussierbar, Klick und Submit sind gesperrt; `ConfirmDialog` hat dafür die additive Eigenschaft `triggerAriaDisabled`). Ableger (`split`) bleiben frei. Der Umsetzen-Dialog trägt den festen Hinweis zu BienSeuchV § 5 (Gesundheitsbescheinigung, im Zweifel beim Veterinäramt nachfragen) und keine Rechtswerte.
|
||||
- **Ausnahme.** Nur mit `compliance:manage` erscheint der aufklappbare Abschnitt „Ausnahme mit Begründung“ (10 bis 500 Zeichen; Leerzeichen allein genügen nicht); die Begründung gilt erst nach der Rückfrage im `ConfirmDialog`, ohne Passwort-Abfrage (Inhaber-Entscheidung 2026-10-15). `restrictionOverrideReason` wird nur gesendet, wenn die Ausnahme genutzt wird; ändern sich die Sperren, verfällt sie. Ohne das Recht wäre die Antwort immer 403, darum wird das Feld nicht angeboten.
|
||||
- **Ernte:** nur die Warnung „Im Sperrbezirk gelten Auflagen auch für Honig und Waben. Verfügung prüfen.“; sie speichert immer.
|
||||
- **409.** `RESTRICTED_ZONE` und „Der Stand wurde gerade geändert. Bitte neu laden.“ erscheinen mit dem Servertext über dem Knopf, der Fokus springt auf die Meldung, die aktiven Sperren laden neu, und ein Knopf „Neu laden“ (Umsetzen, Vereinigen, Standkorrektur) lädt Volk und Stände neu und löscht die Meldung. Kein automatischer Neuversuch.
|
||||
- **Service Worker.** Die Sperrbezirk-Pfade sind seit Task 14 nie zwischengespeichert; offline fehlt die frühe Sperre, der Server entscheidet.
|
||||
|
||||
## 13. Beute (3D-Aufbau)
|
||||
|
||||
Der Aufbau einer Beute (Boden, Zargen, Rähmchen, Einlagen, Dach) je Volk. Spec: `docs/superpowers/specs/2026-10-15-beute-3d-design.md`. L1 ist das Backend (dieser Abschnitt), L2–L5 die Oberfläche (Abschnitt 13.1); Ziehen und Ablegen in 3D (Task 18) folgt.
|
||||
|
||||
**Modul.** `src/hive` (`HiveModule`): `hive.service.ts` (Aufbau je Volk), `hive-catalog.service.ts` (Katalog), `hive-ops.ts` (`applyHiveOps`), `hive-validate.ts` (Validator), `hive-facts.ts` (abgeleitete Fakten), `hive-state-schema.ts` (Zustandsfelder der Teile). Hive-Fakten schreiben nie in `Colony` oder `Inspection`; `Colony.occupiedFrames` bleibt die Volksstärke.
|
||||
|
||||
**Speicherform.**
|
||||
- `HiveSystem` (Maße, `template`) und `HivePartType` (Art, Maße, `frameSlots`, `stateSchema`, `active`) bilden den Katalog. Die Startdaten (Zander nach Liebig, 10 Rähmchen, 14 Teile) kommen per Migration `20261017100100_hive_catalog_zander_liebig` mit festen Ids; `test/fixtures/hive-ops/catalog.json` ist dieselbe Quelle für das Frontend, ein e2e vergleicht beide. Die Futtertasche (`FRAME_FEEDER`, Migration `20261018100100_hive_catalog_frame_feeder`) ist ein Einsatz einer Zarge mit `slot` (erster belegter Rähmchenplatz) und der Katalogspalte `slotWidth` (Zahl belegter Plätze); die von ihr bedeckten Rähmchen sind `NONE`, Überschneidungen melden `RULE_FEEDER_SLOT` (Annahme 101).
|
||||
- `HiveSetup` hält den aktuellen Aufbau eines Volks als JSON (Stand und `version`), `HiveChange` das Protokoll: je Änderung `occurredOn` (Berliner Tag), `source`, die Operationen und `stateAfter`. Der Stand an einem Tag kommt aus dem letzten `stateAfter` bis zu diesem Tag. Nachträge sind möglich, aber nie vor dem `INIT`-Tag und nie in der Zukunft.
|
||||
- Katalogteile werden nie gelöscht, nur `active: false`. Bestehende Aufbauten mit einer inaktiven Art bleiben gültig.
|
||||
|
||||
**Operationen.** `addPart`, `addInsert`, `removePart`, `movePart`, `setState`, `setFrame`, `setFrames`, `setLabel`; höchstens 100 pro Anfrage, höchstens 30 Teile im Stapel, Beschriftungen und Rähmchen-Namen höchstens 40 Zeichen. Die Regeln und die Gründe (`reason`-Codes wie `RULE_FLOOR_BOTTOM`, `STATE_OUT_OF_RANGE`, `UNKNOWN_FIELD`, `LIMIT_PARTS`) stehen im Kopf von `hive-validate.ts`; die Prüfreihenfolge entscheidet, welcher Grund zuerst gemeldet wird, und das Frontend muss sie übernehmen: Wurzelform (`schemaVersion` 1, unbekannte Schlüssel), `LIMIT_PARTS`, dann je Stapelteil Id, unbekannte Felder, Art, Beschriftung, Zustand, Rähmchen und Einsätze (`RULE_INSERT_HOST`, `RULE_FEEDER_SLOT`), danach Boden (`RULE_FLOOR_BOTTOM`), zuletzt Dach (`RULE_ROOF_TOP`); Textlängen zählen UTF-16-Einheiten. `applyHiveOps` und `validateHiveState` sind reine Funktionen ohne Prisma; `applyHiveOps` prüft den Zustand nach jeder Operation, ein Fehler trägt Index und Grund. Scheitert eine Operation am aktuellen Stand, wird die ganze Änderung abgelehnt (409 `HIVE_CONFLICT`).
|
||||
|
||||
**Endpunkte** (`/colonies/:id/hive`): `GET` (Stand und Fakten), `POST` (Aufbau anlegen), `POST changes` (Änderung mit `Idempotency-Key`: dieselbe Wiederholung liefert dieselbe Antwort ohne zweite Änderung), `GET changes` (Historie mit Cursor), `GET at` (Stand an einem Tag). Katalog: `GET /hive-systems`, `GET /hive-systems/:id/template` (Vorlage mit frischen Ids je Aufruf), `POST` und `PATCH /hive-systems`, `POST /hive-systems/:id/part-types`, `PATCH /hive-part-types/:id`.
|
||||
|
||||
**Sperrreihenfolge.** `Colony` FOR UPDATE, dann `HiveSetup` FOR UPDATE, dann `HivePartType` (`LOCKABLE_TABLES` in `src/prisma/row-lock.ts`: `HiveSetup` direkt nach `Colony`). Die Version steigt je Änderung um 1; zwei gleichzeitige Änderungen laufen nacheinander, die zweite sieht den Stand der ersten.
|
||||
|
||||
**Rechte.** Lesen `colonies:read`, Aufbau anlegen und ändern `colonies:update`, Katalog ändern `hive-systems:manage` (Gruppe „Beutensysteme“). `hive-systems:manage` kommt nur über die Katalog-Synchronisierung (`PermissionCatalogSyncService`) zur Rolle ADMIN, ohne Rechte-Migration. STAFF hat `colonies:update` nicht und kann die Beute nicht ändern (Annahme 99).
|
||||
|
||||
**Ereignis.** `HiveChanged` (Outbox, in derselben Transaktion wie die Änderung; Nutzlast `colonyId`, `version`, `source`, `inspectionId`). Ein nicht lebendes Volk ist schreibgeschützt: 409 wie `assertActive`.
|
||||
|
||||
**Durchsicht.** `POST /inspections` nimmt optional `hiveChange` (`ops`). Durchsicht und Beute-Änderung werden in einer Transaktion gespeichert und gemeinsam abgelehnt. Ohne `colonies:update` antwortet der Server 403 `HIVE_FORBIDDEN` und schreibt nichts. Der Tag der Änderung ist der Tag der Durchsicht (nicht in der Zukunft, nicht vor dem `INIT`-Tag); die Änderung hat `source` `INSPECTION` und verweist auf die Durchsicht.
|
||||
|
||||
**Backup.** Export und Import enthalten `HiveSystem`, `HivePartType`, `HiveSetup` und `HiveChange`. Katalogzeilen werden nach Id eingespielt (auch in eine frische Installation mit Startdaten). Je Volk gewinnt die Sicherung: Aufbau und Protokoll eines wiederhergestellten Volks ersetzen die vorhandenen. Nicht versiegelte Altdateien ohne diese Tabellen werden gemeldet und übersprungen (Abschnitt 8).
|
||||
|
||||
**Fehlercodes.**
|
||||
|
||||
| Code | Status | Bedeutung |
|
||||
|---|---|---|
|
||||
| `HIVE_CONFLICT` | 409 | Operation passt nicht zum aktuellen Stand; mit `opIndex`, `reason`, `current` (Version und Stand) |
|
||||
| `HIVE_EXISTS` | 409 | Das Volk hat schon einen Aufbau |
|
||||
| `HIVE_NOT_FOUND` | 404 | Das Volk hat noch keinen Aufbau |
|
||||
| `HIVE_FORBIDDEN` | 403 | Durchsicht mit `hiveChange` ohne `colonies:update` |
|
||||
| `TEMPLATE_NOT_SET` | 409 | Das System hat noch keine Vorlage |
|
||||
| `SCHEMA_NOT_ADDITIVE` | 400 | Zustandsfelder dürfen nur angehängt werden |
|
||||
| `TEMPLATE_INVALID` | 400 | Die Vorlage besteht den Validator nicht |
|
||||
|
||||
Formfehler (Form der Anfrage, zukünftiger Tag, Tag vor `INIT`, mehr als 100 Operationen) sind 400. Ein neues System beginnt mit leerer Vorlage; sie wird per `PATCH` gesetzt, sobald die Teile existieren.
|
||||
|
||||
### 13.1 Frontend (Karte, Editor, Durchsicht, 3D)
|
||||
|
||||
- **Port von Regeln und Fixtures.** `src/lib/hive` spiegelt das Backend: `ops.ts` (`applyHiveOps`), `validate.ts`, `facts.ts`, `types.ts`. Ob beide Seiten gleich rechnen, sichern gemeinsame Fixtures: `ApiCore-Backend/test/fixtures/hive-ops/*.json` liest das Backend-Spec und das Frontend-Spec (`lib/hive/test-utils.ts`, `FIXTURE_DIR`); dazu `catalog.json` für den Katalog. Wer eine Regel ändert, ändert Backend, Frontend und Fixtures zusammen; die Prüfreihenfolge aus Abschnitt 13 gilt auch hier, `reason-text.ts` übersetzt die Gründe in Sätze.
|
||||
- **Karte.** `components/hive/hive-card.tsx` auf der Volksseite (`mode` `view` oder `inspection`). Die Bühne (`HiveVisualSlot`) zeigt immer das SVG (`HiveSvg`, aus `lib/hive/layout.ts`), die 3D-Szene liegt darüber. Daneben stehen die Gliederung (`HiveOutline`, Baum aller Teile, per Tastatur bedienbar), Fakten und Fokusleiste. Teile und Rähmchen öffnen Sheets (`part-sheet`, `frame-sheet`); jede Änderung geht über `useHiveMutation` als `POST changes` mit eigenem `Idempotency-Key` je Versuch, einen Versand nach dem anderen, optimistisch auf dem Cache. Das Sheet zeigt bei `HIVE_CONFLICT` den aktuellen Stand aus der Antwort (`HiveConflictSheet`). Die Historie (`HiveHistory`) zeigt Änderungen und den Stand eines Tages (`GET at`).
|
||||
- **Editor** `/colonies/[id]/hive` („Umbauen“): Mehrere Schritte werden lokal als Entwurf gesammelt (`useHiveDraft`: Schritte, Rückgängig und Wiederholen, `snapshot` des Ausgangsstands, Annahme 104) und mit einer Änderung gespeichert. Bis dahin berührt der Entwurf den Server nicht; Verlassen der Seite mit offenen Schritten fragt nach. Der Editor lädt den Aufbau neu, sobald das Fenster den Fokus bekommt, und alle 30 s, solange ein Entwurf besteht (`REFRESH_INTERVAL_MS`). Umbauen geht nur mit Netz.
|
||||
- **Durchsicht.** `inspections/new` hat den Abschnitt „Beute“ (`hive-section.tsx`): die Karte im Modus `inspection` sammelt Operationen als Entwurf, sie gehen als `hiveChange` mit der Durchsicht in `POST /inspections` und in der Warteschlange mit dem Eintrag (Abschnitt 2). Die Sheets stoppen das `submit` an ihrem Formular (`stopPropagation`; sie liegen in einem Portal, doch React reicht Ereignisse im Komponentenbaum weiter), sonst würde „Speichern“ im Sheet die Durchsicht speichern; neue Formulare in Sheets müssen dasselbe tun. Zusätzlich stoppt der Abschnitt selbst `submit` an seinem Wrapper (`hive-section.tsx`).
|
||||
- **3D-Szene.** `components/hive/hive-scene` (three, react-three-fiber, drei, postprocessing) wird nur über `next/dynamic` mit `ssr: false` geladen, sobald die Karte sichtbar wird (`IntersectionObserver`); andere Seiten laden nichts davon. Budget für den Chunk: höchstens 320 kB gzip (Spec 9.7); gemessen zuletzt etwa 296 kB. Die Szene misst die Bildrate (`quality.ts`): unter 45 fps fällt sie auf die Stufe `low` (kein Spiegelboden, kein MSAA, keine Tiefenunschärfe, keine Partikel), die Tiefenunschärfe läuft erst ab 55 fps. Bewegung folgt der Stufe `full`, `subtle` oder `off` (`useEffectiveMotionLevel`: Flüge, Überblendung 400, 150 oder 0 ms). **Rückfall auf das SVG** (`shouldUse3D`, `lib/hive/webgl.ts`): kein WebGL, erzwungene Farben, oder Bewegung `off` bei höchstens 2 Prozessorkernen; ein verlorener WebGL-Kontext baut die Szene einmal neu auf, der zweite lässt es beim SVG. Das SVG ist darunter immer gerendert und bleibt bedienbar, bis das erste 3D-Bild steht; im Druck entfällt die 3D-Ebene.
|
||||
|
||||
## 14. Sprache (T7 „Freihand“)
|
||||
|
||||
Spracheingabe für die Durchsicht am Stand, in drei Stufen, die einzeln abschaltbar sind. Spec: `docs/superpowers/specs/2026-10-14-t7-sprache-design.md`, Plan: `docs/superpowers/plans/2026-10-16-t7-sprache.md`. Eine Sprachnotiz füllt nie etwas selbst aus: Vorschläge landen erst nach einem Tipp im Formular (Abschnitt 14.6). Inhalte (Ton, Abschrift, Vorschlag) sind personenbezogen und leben nur verschlüsselt und nur kurz; Protokolle, Audit-Einträge und Ereignisse tragen nie Inhalt, nur Ids, Zähler und feste Codes.
|
||||
|
||||
**Stufen.**
|
||||
1. **Diktat im Browser.** Die Spracherkennung des Browsers (`components/voice/use-dictation.ts`) schreibt in Textfelder der Durchsicht. Die Cloud-Erkennung mancher Browser ist ohne Einwilligung aus (`lib/voice/consent.ts`, nur `localStorage`). Kein Server beteiligt.
|
||||
2. **Sprachnotiz mit Abschrift im Cluster.** Das Gerät nimmt bis zu 180 s auf, lädt die Aufnahme hoch, und der CronJob `apicore-job-voice-transcribe` schreibt sie mit Whisper ab (Abschnitt 14.3). Das Ergebnis ist ein Text (Status `TRANSCRIBED`), der im Formular nutzbar ist, auch ohne Stufe 3.
|
||||
3. **Auswertung mit Claude.** Die Worker-Schleife `voice-extractions` ruft Claude, prüft die Antwort gegen die Abschrift und legt Vorschläge ab (Status `READY`, Abschnitt 14.4). Ohne Schlüssel bleibt die Notiz bei `TRANSCRIBED`.
|
||||
|
||||
**Datenmodell** (Migration `20261019100000_t7_voice_captures`).
|
||||
- `VoiceCapture`: Besitzer, Volk, Berliner Tag der Durchsicht (`inspectionDate`), `source` (`AUDIO` oder `TEXT`), `status`, `attempts`, `availableAt`, `claimedAt`, `claimToken`, `lastErrorCode`, Spalten `transcriptEnc` und `suggestionEnc` (Chiffrat), Modell und Tokens, `contentExpiresAt` (Anlage + 7 Tage), `contentDeletedAt`, `inspectionId` (ohne Fremdschlüssel; ein CHECK bindet `CONFIRMED` an eine gesetzte `inspectionId`). `VoiceCaptureAudio` hält den Ton getrennt (`dataEnc`, höchstens 2 MB Klartext), damit Löschen ein `DELETE` ist und Listen den Ton nie laden.
|
||||
- `VoiceExtractionCall`: Protokoll bezahlter Modellaufrufe (Modell, Token, `outcome`, optional `captureId`), ohne Inhalt und ohne Fremdschlüssel. Das Tagesbudget und die Kostenkarte lesen es, nicht die Notizen.
|
||||
- Status: `QUEUED` → `TRANSCRIBING` → `TRANSCRIBED` → `EXTRACTING` → `READY` → `CONFIRMED`; dazu `DISCARDED`, `FAILED` (Code in `lastErrorCode`) und `EXPIRED`. Der Text-Weg beginnt bei `TRANSCRIBED`. Feste Fehlercodes: `src/voice/voice-error-codes.ts`; deutsche Texte: `voice-error-texts.ts`.
|
||||
- `VoiceCapture`, `VoiceCaptureAudio` und `VoiceExtractionCall` stehen im Backup auf der Ausschlussliste (flüchtig, personenbezogen, nach einer Wiederherstellung nicht zustellbar). In der Sperrreihenfolge ist `VoiceCapture` die letzte Tabelle (`row-lock.ts`).
|
||||
|
||||
**Verschlüsselung.** Alles Inhaltliche liegt mit dem Schlüssel `VOICE_ENCRYPTION_KEY` (Zweck `voice`, Annahme 22) versiegelt. Die GCM-AAD bindet jeden Wert an seine Zeile und Art: `capture:<id>:transcript`, `capture:<id>:suggestion`, `capture:<id>:audio` (`voiceAad` in `core/voice-crypto.ts`). Ein in eine andere Notiz oder Art kopiertes Chiffrat öffnet sich nicht. Text hat das Format der anderen Zwecke; Ton ist `[Version][Schlüssel-Id][IV][Tag][Daten]`. Der Job `rekey` versiegelt nur offene Notizen neu.
|
||||
|
||||
**Aufbewahrung und Löschen.**
|
||||
- Ton: gelöscht, sobald die Abschrift gespeichert ist, spätestens nach 24 h; eine Notiz, die dann noch auf ihre Abschrift wartet, endet `FAILED` mit `AUDIO_EXPIRED`.
|
||||
- Inhalte (Abschrift, Vorschlag): spätestens 7 Tage (`contentExpiresAt`), dann `EXPIRED`. Inhalte deaktivierter Nutzer gehen mit derselben Regel.
|
||||
- Zeilen und Protokoll: 90 Tage (`deleteOldVoiceRows`, `deleteOldVoiceCalls`); leere Läufe des Abschreib-Jobs räumt `deleteIdleVoiceRuns` nach einem Tag aus `JobRun`.
|
||||
- Die reinen SQL-Regeln (`expireVoiceContent`, Datenbankuhr, kein Schlüssel nötig) laufen in jedem Lauf der Phase `fetch`, also alle 2 Minuten, und zusätzlich im täglichen `cleanup`, das jede Kategorie zählt (`voice.audioExpired`, `voice.contentExpired`, `voice.inactiveOwnersWiped`, `voice.rowsDeleted`, `voice.callsDeleted`).
|
||||
- Sofort gelöscht: bei Übernahme (Durchsicht gespeichert, Abschnitt 14.2), bei „Verwerfen“, bei „Alle löschen“ (`POST /voice-captures/discard-all`) und, auf dem Gerät, beim Abmelden (Abschnitt 14.6).
|
||||
|
||||
### 14.1 Rechte, Routen und Grenzen
|
||||
|
||||
**Rechte.** Alle Routen außer den Zählern brauchen `voice-captures:use` (Gruppe „Sprache“; die Migration vergibt es an ADMIN, BEEKEEPER und STAFF, nicht an READONLY und API_CLIENT) und zusätzlich `inspections:create` (`InspectionCreateGuard`): wer keine Durchsicht anlegen darf, bekommt keine Sprachnotizen. `GET /voice-captures/stats` verlangt `system:manage`. Jede Abfrage filtert auf den Besitzer; eine fremde Id ist 404. Antworten tragen `Cache-Control: no-store`.
|
||||
|
||||
**Routen** (`src/voice/captures/voice-captures.controller.ts`; statische Pfade vor `:id`).
|
||||
- `POST /voice-captures`: Aufnahme hochladen (multipart `audio`, `colonyId`, `inspectionDate`, `durationSec` 1 bis 240), `@Idempotent()`, Antwort `{ id, status: 'QUEUED' }`. Multer hält die Datei im RAM (`fileSize` 2 MB, ein Teil); der Typ kommt aus den ersten Bytes (WebM, Ogg, MP4), nie aus dem `Content-Type` (415 `UNSUPPORTED_AUDIO`, 413 `TOO_LARGE`).
|
||||
- `POST /voice-captures/text`: Text zur Auswertung (`colonyId`, `inspectionDate`, `text`, nach NFKC und ohne Steuerzeichen 20 bis 4000 Zeichen), `@Idempotent()`, Status `TRANSCRIBED`.
|
||||
- `GET /voice-captures?status=` (eigene Notizen ohne Inhalt, höchstens 200), `GET /voice-captures/:id` (bei `READY`, `TRANSCRIBED` und `FAILED` mit Abschrift und Vorschlägen; ändert nichts), `GET /voice-captures/config`, `GET /voice-captures/stats`.
|
||||
- `POST /voice-captures/:id/retry`: nur bei `FAILED` mit vorhandenem Text oder frischem Ton (unter 24 h) und `contentExpiresAt` in der Zukunft; zurück auf `TRANSCRIBED` oder `QUEUED`, `attempts = 0`; sonst 409 `VOICE_CAPTURE_GONE`. `POST /voice-captures/:id/discard` (204, idempotent) und `POST /voice-captures/discard-all`.
|
||||
- `POST /inspections` nimmt `voiceCaptureId`; `VoiceConfirmationService.confirmIn` läuft als Letztes in der Anlege-Transaktion (Annahme 107). Eine fremde, fehlende oder abgeschlossene Notiz ist 409 `VOICE_CAPTURE_GONE`, eine Notiz eines anderen Volks 409 `VOICE_CAPTURE_COLONY_MISMATCH`; eine Wiederholung mit demselben `Idempotency-Key` ändert nichts.
|
||||
|
||||
**Grenzen.** Je Nutzer höchstens 10 offene Notizen (`QUEUED` bis `READY`), 30 neue je UTC-Tag und 10 neue je Minute, unter einer Advisory-Sperre je Nutzer (sonst 429 `TOO_MANY_OPEN`, Text „Zu viele offene Sprachnotizen. Erst auswerten oder verwerfen.“); ein Wiederholen zählt wie eine neue Notiz. Dazu Throttle je Netz: 10/min für Upload, 5/min für Wiederholen (Annahme 109). Das Volk muss leben (400), der Tag der Durchsicht höchstens 7 Tage zurück und nicht in der Zukunft.
|
||||
|
||||
**Schalter.** `VOICE_RECORDING_ENABLED` (ConfigMap `apicore-backend-config`, Voreinstellung `false`) steuert die Aufnahme. Aus: Upload und Text-Weg antworten 403 `VOICE_RECORDING_DISABLED`, die Oberfläche blendet die Einstiege aus; Liste, Lesen, Wiederholen und Verwerfen bleiben (Annahme 113). `GET /voice-captures/config` meldet `recordingEnabled`, `extractionEnabled` (der API-Pod kennt den Schlüssel nicht und schließt „aus“ daraus, dass der Worker in der letzten Stunde eine Notiz mit `EXTRACT_DISABLED` geparkt hat), das Modell und die Fristen (24 h, 7 Tage, 90 Tage). Weitere Einstellungen: `VOICE_MODEL` (`claude-sonnet-5-5`, `claude-haiku-5-5`, `claude-opus-5-5`; die Modell-Ids stehen nur in `voice-config.ts`), `VOICE_DAILY_EXTRACTIONS` (60, erlaubt 1 bis 10000), `WHISPER_MODEL` (`small` oder `medium`), `VOICE_SERVER_FALLBACK` (`default` oder `off`). Ungültige Werte verhindern den Start.
|
||||
|
||||
**Ansprüche, Wiederholungen, Verfallsfenster.** Beide Phasen teilen sich die Hilfen in `claims/voice-claims.ts` und die Regeln in `claims/voice-phases.ts`. Ein Lauf beansprucht eine Notiz atomar (`claimToken`); Abschluss, Fehlversuch und Verschieben prüfen den Token (Compare-and-Set), sodass ein Prozess, der den Anspruch verloren hat, nichts mehr schreibt. Ein Abschluss der Phase `transcribe` setzt `attempts` auf 0, damit `extract` seine eigenen 3 Versuche hat.
|
||||
|
||||
| Phase | Von → in Arbeit → fertig | Versuche | Wartezeit nach Fehlversuch | Anspruch veraltet nach | Endcode |
|
||||
|---|---|---|---|---|---|
|
||||
| `transcribe` | `QUEUED` → `TRANSCRIBING` → `TRANSCRIBED` | 3 | 5 min, 15 min | 30 min | `TRANSCRIBE_FAILED` |
|
||||
| `extract` | `TRANSCRIBED` → `EXTRACTING` → `READY` | 3 | 30 s, 2 min | 5 min | `EXTRACT_FAILED` |
|
||||
|
||||
Ein veralteter Anspruch geht beim nächsten Lauf zurück und zählt einen Versuch; ist der letzte verbraucht, endet die Notiz `FAILED` und `VoiceCaptureFailed` wird geschrieben.
|
||||
|
||||
### 14.2 Übernahme
|
||||
|
||||
Das Speichern der Durchsicht bestätigt die Notiz in jedem offenen Zustand: Status `CONFIRMED`, `inspectionId` gesetzt, Ton, Abschrift und Vorschlag gelöscht, alles in der Transaktion der Durchsicht. Ein laufender Job verliert seinen Anspruch und kann nicht mehr abschließen. Scheitert die Bestätigung, scheitert das ganze Speichern.
|
||||
|
||||
### 14.3 Abschreiben im Cluster
|
||||
|
||||
**Job.** `voice-transcribe` (`src/jobs/voice-transcribe.job.ts`, Argumente `--phase=fetch` und `--phase=ingest`) ist die Node-Hälfte um den Whisper-Container; Komponente `deploy/k8s/components/voice`, CronJob `apicore-job-voice-transcribe`: `*/2 * * * *`, `Europe/Berlin`, `concurrencyPolicy: Forbid`, `backoffLimit: 0`, `activeDeadlineSeconds: 1500`. Drei Container laufen nacheinander mit derselben uid 1000 und fsGroup 1000:
|
||||
1. `fetch` (initContainer, Backend-Image, Rolle `job`): wendet die Aufbewahrungsregeln an, gibt veraltete Ansprüche frei, beansprucht bis zu 5 Notizen mit zusammen höchstens 600 s Ton, entschlüsselt in den Speicher und legt Ton und Manifest nach `/work/in`.
|
||||
2. `whisper` (initContainer, Image `apicore-whisper` aus `ApiCore-Whisper/`, faster-whisper auf CPU, `int8`, Deutsch, `beam_size` 1, VAD-Filter, 2 Threads): liest `/work/in` (nur lesbar), schreibt je Notiz ein Ergebnis nach `/work/out`. Kein `envFrom`, kein `secretKeyRef`, kein Service-Account-Token, kein Datenbankzugang; zusätzlich sperrt das Skript `socket.socket`. Das Modell steckt mit Prüfsummen im Image; `av` ist auf 18.1.0 festgelegt (Annahme 106).
|
||||
3. `ingest` (Hauptcontainer, Backend-Image): übernimmt nur Ergebnisse zu Notizen des eigenen Manifests mit passendem `claimToken`, prüft sie streng, versiegelt den Text, löscht den Ton, setzt `TRANSCRIBED` und weckt den Worker (`pg_notify('voice_extraction')`), je Notiz in einer eigenen Transaktion. Zu kurzer Text (unter 5 Zeichen) ist `NO_SPEECH`, mehr als 240 s `TOO_LONG`; beide enden die Notiz sofort `FAILED`. Ein nicht dekodierbarer Ton zählt als Fehlversuch (`TRANSCRIBE_FAILED`).
|
||||
|
||||
**Härtung.** `/work` ist ein `emptyDir` mit `medium: Memory` (32Mi): entschlüsselter Ton und Abschriften berühren nie eine Platte; die Verzeichnisse sind 0700, die Dateien 0600. `fetch` und `ingest` teilen ein `/tmp` (64Mi), `whisper` hat ein eigenes im RAM (16Mi), damit ein kompromittierter Decoder `ingest` (das alle Secrets lädt) keinen Code unterschieben kann. Das Pod-Template trägt `app: apicore-job` und `db-client: "true"`; die NetworkPolicy `apicore-jobs` erlaubt nur Postgres (5432) und DNS. Das CronJob-Objekt selbst trägt `app: apicore-voice-job`, damit der gemeinsame Job-Patch keinen weiteren Container `job` einsetzt. Whisper: Request und Limit je 1280Mi Speicher (Messung vor der Freigabe, Abschnitt 14.7). Das Restrisiko eines gemeinsamen Pod-Netzes steht in Annahme 106.
|
||||
|
||||
### 14.4 Auswertung mit Claude
|
||||
|
||||
**Schleife.** `VoiceExtractionService` (`src/voice/extraction/`) läuft als Worker-Schleife `voice-extractions` (15 s Sicherheitsabfrage, sofort bei `voice_extraction`, ein Lauf zur Zeit, höchstens 20 Notizen je Lauf). Der Anspruch, das Ergebnis und das Ereignis einer Notiz committen zusammen.
|
||||
|
||||
**Aufruf.** Der Adapter `AnthropicStructuredModel` ist die einzige Stelle, die das SDK einbindet (`@anthropic-ai/sdk` 0.131.0, exakt festgelegt; eine Netz-Wächterprüfung sichert das). Der Endpunkt ist fest `https://api.anthropic.com`; `ANTHROPIC_BASE_URL` und `ANTHROPIC_CUSTOM_HEADERS` aus der Umgebung werden mit Warnung ignoriert. Je Aufruf `max_tokens` 2000, Timeout 60 s, 2 SDK-Wiederholungen, insgesamt höchstens 240 s, `effort: low`. Der Schlüssel `ANTHROPIC_API_KEY` kommt nur im Worker an (Secret `apicore-anthropic`, optional, einzelne Variable per `patch-worker-voice.yaml`); API- und Job-Pods warnen beim Start, wenn sie ihn trotzdem sehen.
|
||||
|
||||
**Prompt als Daten.** Der Systemprompt ist fester Text ohne Datum, Volk, Nutzer oder Modell-Id (`voice-prompt.ts`, `VOICE_PROMPT_VERSION`): Feldliste mit Wertebereichen aus dem Formular, die vier Skalen mit Ankerwörtern, die Futtercodes, neun Regeln (nur Ausdrückliches, Verneinung ist ein Wert, wörtliches Zitat, keine Namen, kein Wetter, Korrektur gewinnt) und die Fachwortliste. Die Abschrift steht in `<transkript>…</transkript>` und gilt als Datenmaterial, nie als Anweisung; `<` und `>` im Text werden zu ‹ und ›, damit sie den Rahmen weder schließen noch öffnen.
|
||||
|
||||
**Schema und Prüfung.** Strukturierte Ausgabe `{ findings: [{ field, value, quote, corrected }], unclear: [] }` (`voice-schema.ts`, ohne Grenzen wie `maxItems`, die das Schema nicht zulässt). Der Server prüft jede Antwort (`validate-suggestions.ts`, rein und deterministisch): höchstens 20 Einträge und 5 Unklarheiten (je 300 Zeichen); Feld und Wert gegen die Regeln des Formulars (`core/inspection-field-specs.ts`: Bereiche, Skalen 1 bis 5, Futtercodes, gekürzte Texte); das Zitat (höchstens 120 Zeichen) muss wörtlich in der Abschrift stehen, wobei eine Dezimalzahl ein Wort bleibt (Annahme 108); je Feld bleibt ein Wert (eine Korrektur schlägt eine Nichtkorrektur, dann das spätere Zitat), der stärkste andere Wert wird als `previous` mitgegeben. Verworfene Einträge zählen nur als Zahl (`dropped`, `truncated`). Das Ergebnis `{ suggestions, unclear, dropped, truncated }` liegt versiegelt in `suggestionEnc`.
|
||||
|
||||
**Budget und Ausgänge.** Das Tagesbudget zählt bezahlte Aufrufe aus `VoiceExtractionCall` auf dem UTC-Tag der Datenbankuhr, alle Ausgänge außer `AUTH` und `ABORTED` (Annahmen 110 und 111). Ist es erreicht, wartet die Notiz bis zum Tagesende (`DAILY_LIMIT`, kein Fehlversuch). Ein Aufruf wird vor dem Abschluss der Notiz gebucht, damit ein verlorener Anspruch ihn nicht kostenlos macht.
|
||||
- Kein brauchbarer Schlüssel oder Ablehnung des Schlüssels (401, 403): die Notiz wartet eine Stunde mit `EXTRACT_DISABLED` (kein Fehlversuch); je Periode entsteht ein Ereignis für `system:manage`.
|
||||
- Modell lehnt ab (`refusal`): sofort `FAILED` mit `REFUSED`. Abgeschnitten, ungültige Antwort oder `BAD_REQUEST`: Fehlversuch mit `EXTRACT_INVALID`. Netz, Zeitüberschreitung, 408, 409, 429, 5xx: Fehlversuch mit `EXTRACT_RETRY`, nach dem dritten `EXTRACT_FAILED`.
|
||||
- Abbruch beim Herunterfahren: nicht gezählt, die Notiz wird sofort wieder frei (`ABORTED`).
|
||||
- Serverseitiger Ausweichweg: für Sonnet und Opus setzt der Adapter bei `VOICE_SERVER_FALLBACK=default` die Beta-Kennung `server-side-fallback-2026-07-01` und `fallbacks: "default"`; eine abgelehnte Anfrage läuft dann bei Anthropic auf dem empfohlenen Modell neu. Gebucht wird das tatsächlich antwortende Modell (Annahme 115). Haiku hat keinen Ausweichweg.
|
||||
|
||||
**Messung.** `npm run eval:voice` (Gold-Menge `test/fixtures/voice/gold/g01` bis `g30`, Schwellen: Genauigkeit ≥ 98 %, Trefferquote ≥ 85 %) läuft ohne Zusatz offline gegen eine Attrappe; `-- --live --yes` ruft Claude auf und kostet etwa 0,21 $ für 30 Fälle (Sonnet). Es läuft nie in der CI.
|
||||
|
||||
### 14.5 Ereignisse und Meldungen
|
||||
|
||||
`VoiceCaptureReady` und `VoiceCaptureFailed` (Outbox, in derselben Transaktion wie der Zustandswechsel; Nutzlast Ids und Code). Handler (`voice.handlers.ts`, über `VoiceHandlersModule` im Worker): `voice.notify-ready` legt dem Besitzer eine Meldung `HINWEIS` der Kategorie `SUGGESTION` an („Sprachnotiz für {Volk} ist fertig“, Link `/inspections/new?colonyId=…&voice=<id>`, einmal je Notiz), `voice.notify-failed` eine `WARNUNG` mit dem deutschen Hinweistext des Codes und Link `/voice`, nur wenn die Notiz `FAILED` ist. `EXTRACT_DISABLED` erzeugt zusätzlich einen Hinweis ohne Nutzer-, Volk- und Notizbezug an `system:manage`. Beide Meldungen verlangen `voice-captures:use` beim Empfänger. Ein Fehlschlag des Jobs meldet wie bei allen Jobs an `system:manage`; die Systemkarte zeigt Zähler je Status und Fehlercode der letzten 7 Tage sowie Tokens je Modell und die daraus geschätzten Kosten (`lib/voice/prices.ts`, dieselbe Preistabelle wie `src/voice/eval/voice-prices.ts`; Annahme 114).
|
||||
|
||||
### 14.6 Frontend
|
||||
|
||||
- **Aufnahme.** `components/voice/voice-recorder.tsx` mit `lib/voice/recorder.ts`: höchstens 180 s (`MAX_RECORDING_SEC`, Warnung ab 150 s), Bildschirm bleibt wach; nach einer Mikrofonverweigerung hilft `microphone-help.tsx`. Der Server nimmt bis 240 s an, damit eine Messabweichung die Notiz nicht verwirft. Ein Hinweis zur Aufnahme erscheint einmal je Gerät (`recording-notice-dialog.tsx`). Endet die Aufnahme von selbst, geht sie sofort in die Geräte-Warteschlange (Annahme 112).
|
||||
- **Geräte-Warteschlange.** IndexedDB, Version 6, Store `pending-voice` (Index `ownerUserId`, `lib/voice/pending-voice.ts`, Typen in `lib/offline/db.ts`). Der Upload hängt am Synclauf (`uploadPendingVoice` nach Datensätzen und Fotos): ältester zuerst, mit einem festen `uploadIdempotencyKey` je Notiz, damit ein verlorener Antwortweg nichts doppelt anlegt. 2xx löscht den lokalen Ton sofort; eine endgültige Ablehnung (4xx) bleibt mit Fehler an der Notiz und wartet auf den Nutzer; Netzfehler, 5xx, 408 und 429 beenden den Lauf, `TOO_MANY_OPEN` sperrt den Eintrag, bis Platz ist. Notizen eines anderen Kontos werden gezählt, nie gesendet. Beim Abmelden löscht `clearQueueOf` die Sprachnotizen des Kontos; die Abmeldefrage nennt vorher die Zahl der noch nicht gesendeten Notizen.
|
||||
- **Seiten.** `/voice` (Liste: Notizen vom Server und vom Gerät, Verwerfen, Wiederholen), `/voice/new` (aufnehmen, Volk und Tag wählen), Einstiege per `VoiceEntryLink` in Schnell-Anlegen, Navigation, Volksseite und Durchsicht; sie erscheinen nur, wenn der Schalter `on` oder `unknown` (offline) ist (`useVoiceRecordingSwitch`: `loading`, `on`, `off`, `unknown`). `/settings/voice` („Sprache & Datenschutz“): Info- und Datenschutztext, Einwilligung zur Browser-Cloud-Erkennung (aus), „Alle löschen“ für Server und Gerät.
|
||||
- **Durchsicht.** `inspections/new?voice=<id>` zeigt oben die Notiz (`VoiceReviewBox`, `useVoiceReview`: fragt alle 5 s, höchstens 10 min) und je Feld einen Vorschlag mit Zitat (`VoiceFieldRow`, „Übernehmen“, „Alle übernehmen“, Ignorieren). Nichts wird ohne Tipp übernommen; die Abschrift lässt sich einsehen und in die Zwischenablage kopieren, auch wenn die Auswertung aus ist (`TRANSCRIBED`). Beim Speichern geht `voiceCaptureId` mit.
|
||||
- **Weg bei Konflikt.** 409 `VOICE_CAPTURE_GONE` beim Speichern: `createInspection` versucht es genau einmal ohne `voiceCaptureId` und mit demselben `Idempotency-Key` erneut (der Interceptor gibt den Schlüssel bei Handlerfehler frei und prüft den Rumpf nicht; ein neuer Schlüssel könnte doppelt anlegen). 409 `VOICE_CAPTURE_COLONY_MISMATCH` wird nie wiederholt; in der Warteschlange erscheint „Ohne Sprachnotiz senden“ (`retryInspectionWithoutVoice`), und der Nutzer entscheidet.
|
||||
- **Textweg.** „Ganze Durchsicht auswerten“ (`EvaluateDictationButton`, unter den Textfeldern) sendet den noch in den vier Freitextfeldern stehenden diktierten Text (20 bis 4000 Zeichen, so normalisiert wie auf dem Server) an `POST /voice-captures/text` mit einem `Idempotency-Key` je Inhalt. Daneben steht „Der Text geht zur Auswertung an Anthropic.“. Offline ist der Knopf gesperrt (nichts wird eingereiht); mit `?voice=` fehlt er; die Antwort kommt als Sprachnotiz oben im Formular, und nach 2 min Warten ohne Ergebnis verweist ein Hinweis auf die Meldung.
|
||||
- **Service-Worker.** `public/sw-routes.js` cacht `/api/v1/voice-captures` nie (Abschrift und Vorschläge sind Inhalt) und hält nur die Hüllen `/voice` und `/voice/new` vor.
|
||||
|
||||
### 14.7 Rollout
|
||||
|
||||
Reihenfolge, jeder Schritt mit Freigabe:
|
||||
1. **Schlüssel vor dem Image.** `deploy/k8s/scripts/ensure-secrets.sh` legt `VOICE_ENCRYPTION_KEY` in `apicore-backend-secret` an (48 Zufallsbytes, Base64URL); er muss existieren und gesichert sein, bevor das Backend-Image mit T7 startet, denn in Produktion startet sonst keine Rolle (Annahme 22). Dann Image mit Migration. Die Auswertung bleibt ohne Anthropic-Schlüssel aus (`EXTRACT_DISABLED`).
|
||||
2. **Whisper-Image.** `.gitea/workflows/whisper-image.yml` baut es; der Digest ersetzt den Platzhalter im Overlay `deploy/k8s/overlays/encry/kustomization.yaml` (Eintrag `apicore-whisper`).
|
||||
3. **Komponente `voice`** (im Overlay eingebunden, erst nach Schritt 1 und 2 anwenden): CronJob und Worker-Patch. Erster Lauf von Hand (`kubectl create job --from=cronjob/apicore-job-voice-transcribe`); das Log darf keinen Inhalt enthalten.
|
||||
4. **Anthropic.** Der Inhaber legt das Secret `apicore-anthropic` (Schlüssel `ANTHROPIC_API_KEY`) an und verschiebt den Schlüssel aus `apicore-backend-secret`, wo er über `envFrom` auch API- und Job-Pods erreichte; er setzt in der Anthropic-Konsole ein Ausgabenlimit (Vorschlag 10 $ im Monat). Mit 60 Aufrufen am Tag (`VOICE_DAILY_EXTRACTIONS`) bleibt der Verbrauch dahinter.
|
||||
5. **Messung (Task 24)** auf dem Zielknoten: Speicherspitze des Whisper-Containers gegen 1280Mi (inklusive der Speicher-Volumes), Zeit und CPU-Drosselung, Trefferquote der Fachwörter (Ziel ≥ 90 %, sonst `medium` oder längere Fachwortliste), einmal `npm run eval:voice -- --live --yes`.
|
||||
6. **Freigabe (Task 25).** `VOICE_RECORDING_ENABLED` auf `"true"` und Frontend ausrollen. Rückweg: Schalter auf `"false"` und die Komponente `voice` abschalten; offene Notizen laufen über die Fristen ab, es gehen nur flüchtige Daten verloren.
|
||||
@@ -56,6 +56,16 @@ BACKUP_CRON_SCHEDULE="0 3 * * *"
|
||||
# Wie viele der neuesten Backup-Dateien behalten werden, aeltere werden nach
|
||||
# jedem Lauf geloescht (Standard: 14).
|
||||
BACKUP_RETENTION_COUNT=14
|
||||
# Obergrenze fuer eine einzuspielende Backup-Datei in Bytes (Standard 50 MB,
|
||||
# hoechstens 256 MB, weil der Upload komplett im RAM verarbeitet wird).
|
||||
# Export und Zeitplan warnen, wenn eine Sicherung groesser wird.
|
||||
# BACKUP_MAX_IMPORT_BYTES=52428800
|
||||
|
||||
# Erster Administrator (prisma/seed.ts): wird angelegt, wenn es noch keinen
|
||||
# Benutzer mit dieser Adresse gibt. Ohne Passwort erzeugt der Seed ein
|
||||
# zufaelliges und gibt es einmalig im Log aus.
|
||||
# [email protected]
|
||||
# SEED_ADMIN_PASSWORD=
|
||||
|
||||
# Encryption keys, one per purpose (AES-256-GCM, key derived per purpose with
|
||||
# HKDF): TOTP secrets, webhook signing secrets, backup files. Required in
|
||||
@@ -72,9 +82,12 @@ BACKUP_RETENTION_COUNT=14
|
||||
# MFA_ENCRYPTION_KEY=""
|
||||
# WEBHOOK_ENCRYPTION_KEY=""
|
||||
# BACKUP_ENCRYPTION_KEY=""
|
||||
# Seals voice notes (audio, transcripts, suggestions); required in production.
|
||||
# VOICE_ENCRYPTION_KEY=""
|
||||
# MFA_ENCRYPTION_KEY_PREVIOUS=""
|
||||
# WEBHOOK_ENCRYPTION_KEY_PREVIOUS=""
|
||||
# BACKUP_ENCRYPTION_KEY_PREVIOUS=""
|
||||
# VOICE_ENCRYPTION_KEY_PREVIOUS=""
|
||||
|
||||
# Entra ID SSO. Ohne alle vier Werte bleibt SSO deaktiviert
|
||||
# (GET /api/v1/auth/sso/status meldet enabled: false, kein Fehler beim Start).
|
||||
|
||||
+32
-86
@@ -1,98 +1,44 @@
|
||||
<p align="center">
|
||||
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
||||
</p>
|
||||
# ApiCore-Backend
|
||||
|
||||
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||
NestJS-API von ApiCore (TypeScript, Prisma, PostgreSQL). Alle fachlichen Funktionen liegen unter `/api/v1/...`. Überblick über das ganze Projekt: [`../README.md`](../README.md), Architektur: [`../ARCHITECTURE.md`](../ARCHITECTURE.md).
|
||||
|
||||
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||
<p align="center">
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
|
||||
</p>
|
||||
<!--[](https://opencollective.com/nest#backer)
|
||||
[](https://opencollective.com/nest#sponsor)-->
|
||||
|
||||
## Description
|
||||
|
||||
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||
|
||||
## Project setup
|
||||
## Einrichten
|
||||
|
||||
```bash
|
||||
$ npm install
|
||||
npm install
|
||||
cp .env.example .env # DATABASE_URL, JWT- und Verschlüsselungs-Schlüssel setzen
|
||||
npx prisma migrate dev # Schema anwenden (nur lokal; gegen Produktion nur migrate deploy)
|
||||
npm run start:dev # http://localhost:3001
|
||||
```
|
||||
|
||||
## Compile and run the project
|
||||
Alle Variablen mit Bedeutung stehen in [`.env.example`](.env.example). Swagger unter `/api/v1/docs` ist nur mit `ENABLE_SWAGGER=true` erreichbar.
|
||||
|
||||
## Laufrollen
|
||||
|
||||
Ein Build, drei Einstiegspunkte (`ARCHITECTURE.md` Abschnitt 10):
|
||||
|
||||
| Befehl | Rolle | Zweck |
|
||||
|---|---|---|
|
||||
| `npm run start:dev` / `node dist/main.js` | `api` (lokal ohne `APICORE_ROLE`: `all`) | HTTP-API; mit `all` laufen API und Worker in einem Prozess, nur für Entwicklung und Tests |
|
||||
| `npm run worker` (`node dist/worker.js`) | `worker` | Zustellung der Outbox `DomainEvent`, Webhooks, Kalender-Sync, Wetter, Telegram; Health auf Port 3002 |
|
||||
| `npm run job -- <name>` (`node dist/cli.js <name>`) | `job` | `cleanup`, `daily-evaluation`, `task-templates`, `app-backup`, `rekey` (auch `rekey --dry-run`); im Cluster als CronJobs |
|
||||
|
||||
In Produktion ist `APICORE_ROLE` Pflicht und `all` verboten. Migrationen laufen im Cluster als initContainer `migrate` (`prisma migrate deploy`), der Seed als initContainer `seed` (`node dist/seed.js`).
|
||||
|
||||
## Prüfen
|
||||
|
||||
```bash
|
||||
# development
|
||||
$ npm run start
|
||||
|
||||
# watch mode
|
||||
$ npm run start:dev
|
||||
|
||||
# production mode
|
||||
$ npm run start:prod
|
||||
npm run lint # eslint mit --fix
|
||||
npm run typecheck # tsc --noEmit
|
||||
npm test # Jest-Unit-Tests
|
||||
npm run test:e2e # Jest-e2e gegen die Datenbank aus .env.test (vorher migrieren)
|
||||
npm run build # dist/main.js, dist/worker.js, dist/cli.js, dist/seed.js
|
||||
```
|
||||
|
||||
## Run tests
|
||||
Die e2e-Suites laufen parallel (`maxWorkers: 4` in `test/jest-e2e.json`) und scheitern dabei derzeit sporadisch; mit `npm run test:e2e -- --runInBand` sind sie grün ([Issue #32](https://git.encry.de/Nick.Rosenloecher/ApiCore/issues/32)). Der Image-Build (`Dockerfile`) führt Lint, Typecheck und Unit-Tests aus und bricht bei Fehlern ab; die e2e-Tests laufen dort nicht.
|
||||
|
||||
```bash
|
||||
# unit tests
|
||||
$ npm run test
|
||||
## Aufbau
|
||||
|
||||
# e2e tests
|
||||
$ npm run test:e2e
|
||||
|
||||
# test coverage
|
||||
$ npm run test:cov
|
||||
```
|
||||
|
||||
## Deployment
|
||||
|
||||
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
|
||||
|
||||
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
|
||||
|
||||
```bash
|
||||
$ npm install -g @nestjs/mau
|
||||
$ mau deploy
|
||||
```
|
||||
|
||||
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
|
||||
|
||||
## Resources
|
||||
|
||||
Check out a few resources that may come in handy when working with NestJS:
|
||||
|
||||
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
|
||||
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
|
||||
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
|
||||
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
|
||||
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
|
||||
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
|
||||
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
|
||||
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
|
||||
|
||||
## Support
|
||||
|
||||
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
|
||||
|
||||
## Stay in touch
|
||||
|
||||
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
|
||||
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||
|
||||
## License
|
||||
|
||||
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
|
||||
- `src/<modul>/`: ein NestJS-Modul je Fachbereich (z. B. `colonies`, `inspections`, `treatments`, `honey-batches`, `compliance`, `hive`), dazu Querschnitt in `common`, `prisma`, `domain-events`, `worker`, `jobs`, `runtime`.
|
||||
- `prisma/schema.prisma` und `prisma/migrations/` sind die einzige Quelle des Schemas; `prisma db push` wird nirgends verwendet.
|
||||
- `test/`: e2e-Specs und gemeinsame Fixtures (u. a. `test/fixtures/hive-ops/`, die auch das Frontend nutzt).
|
||||
Generated
+72
@@ -9,6 +9,7 @@
|
||||
"version": "0.0.1",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "0.131.0",
|
||||
"@nestjs/common": "^11.0.1",
|
||||
"@nestjs/config": "^4.0.4",
|
||||
"@nestjs/core": "^11.0.1",
|
||||
@@ -213,6 +214,27 @@
|
||||
"tslib": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@anthropic-ai/sdk": {
|
||||
"version": "0.131.0",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.131.0.tgz",
|
||||
"integrity": "sha512-9+PepoU7qVMmM70jSahdnfcMHAvAnzhMOLv2W9WjRLO+OG/MAiBETkwKZqv7KIJ1Cj5h8eZ019bHzZaq+Mbepw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"json-schema-to-ts": "^3.1.1",
|
||||
"standardwebhooks": "^1.0.0"
|
||||
},
|
||||
"bin": {
|
||||
"anthropic-ai-sdk": "bin/cli"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"zod": "^3.25.0 || ^4.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"zod": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/code-frame": {
|
||||
"version": "7.29.7",
|
||||
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
|
||||
@@ -674,6 +696,15 @@
|
||||
"@babel/core": "^7.0.0-0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/runtime": {
|
||||
"version": "7.29.10",
|
||||
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.10.tgz",
|
||||
"integrity": "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/template": {
|
||||
"version": "7.29.7",
|
||||
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz",
|
||||
@@ -3213,6 +3244,12 @@
|
||||
"@sinonjs/commons": "^3.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@stablelib/base64": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz",
|
||||
"integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@standard-schema/spec": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
|
||||
@@ -6925,6 +6962,12 @@
|
||||
"integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-sha256": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz",
|
||||
"integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==",
|
||||
"license": "Unlicense"
|
||||
},
|
||||
"node_modules/fast-uri": {
|
||||
"version": "3.1.5",
|
||||
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz",
|
||||
@@ -8780,6 +8823,19 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/json-schema-to-ts": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",
|
||||
"integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.18.3",
|
||||
"ts-algebra": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/json-schema-traverse": {
|
||||
"version": "0.4.1",
|
||||
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
|
||||
@@ -11249,6 +11305,16 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/standardwebhooks": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.1.1.tgz",
|
||||
"integrity": "sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@stablelib/base64": "^1.0.0",
|
||||
"fast-sha256": "^1.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/statuses": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
|
||||
@@ -11785,6 +11851,12 @@
|
||||
"url": "https://github.com/sponsors/Borewit"
|
||||
}
|
||||
},
|
||||
"node_modules/ts-algebra": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",
|
||||
"integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/ts-api-utils": {
|
||||
"version": "2.5.0",
|
||||
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz",
|
||||
|
||||
@@ -22,9 +22,12 @@
|
||||
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||
"test:e2e": "jest --config ./test/jest-e2e.json",
|
||||
"migrate:deploy": "prisma migrate deploy",
|
||||
"seed": "node dist/seed.js"
|
||||
"seed": "node dist/seed.js",
|
||||
"export:voice-vocabulary": "ts-node scripts/export-voice-vocabulary.ts",
|
||||
"eval:voice": "ts-node scripts/eval-voice.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "0.131.0",
|
||||
"@nestjs/common": "^11.0.1",
|
||||
"@nestjs/config": "^4.0.4",
|
||||
"@nestjs/core": "^11.0.1",
|
||||
@@ -102,6 +105,7 @@
|
||||
"**/*.(t|j)s"
|
||||
],
|
||||
"coverageDirectory": "../coverage",
|
||||
"testEnvironment": "node"
|
||||
"testEnvironment": "node",
|
||||
"testTimeout": 20000
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
-- T6 migration 6/6: the ComplianceSettings singleton row exists from the
|
||||
-- start. The label check reads the net-quantity digit rules from it and fails
|
||||
-- closed when the row is missing, so no legal value lives in the code. The
|
||||
-- column defaults (digit rules, notice switches) fill the row; the owner has
|
||||
-- to check them (ARCHITECTURE).
|
||||
|
||||
INSERT INTO "ComplianceSettings" ("id", "updatedAt")
|
||||
VALUES ('singleton', now())
|
||||
ON CONFLICT ("id") DO NOTHING;
|
||||
@@ -0,0 +1,109 @@
|
||||
-- Beute in 3D: hive systems, part types, per-colony setup and its change
|
||||
-- history (spec 2026-10-15, section 5.1).
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "HivePartKind" AS ENUM ('FLOOR', 'BOX', 'DIVIDER_BOARD', 'QUEEN_EXCLUDER', 'FEEDER', 'COVER_SHEET', 'PROPOLIS_SCREEN', 'INNER_LID', 'INSULATION', 'ROOF', 'FLOOR_INSERT', 'EVAPORATOR');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "HiveBoxDepth" AS ENUM ('FULL', 'SHALLOW');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "HiveChangeSource" AS ENUM ('INIT', 'CARD', 'EDITOR', 'INSPECTION', 'AI_SUGGESTION');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "HiveSystem" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"frameWidthMm" INTEGER NOT NULL,
|
||||
"frameHeightMm" INTEGER NOT NULL,
|
||||
"footprintLMm" INTEGER NOT NULL,
|
||||
"footprintWMm" INTEGER NOT NULL,
|
||||
"template" JSONB NOT NULL,
|
||||
"active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "HiveSystem_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "HivePartType" (
|
||||
"id" TEXT NOT NULL,
|
||||
"systemId" TEXT NOT NULL,
|
||||
"kind" "HivePartKind" NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"articleRef" TEXT,
|
||||
"lengthMm" INTEGER NOT NULL,
|
||||
"widthMm" INTEGER NOT NULL,
|
||||
"heightMm" INTEGER NOT NULL,
|
||||
"boxDepth" "HiveBoxDepth",
|
||||
"frameSlots" INTEGER,
|
||||
"stateSchema" JSONB NOT NULL,
|
||||
"active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "HivePartType_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "HiveSetup" (
|
||||
"colonyId" TEXT NOT NULL,
|
||||
"systemId" TEXT NOT NULL,
|
||||
"version" INTEGER NOT NULL DEFAULT 1,
|
||||
"state" JSONB NOT NULL,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "HiveSetup_pkey" PRIMARY KEY ("colonyId")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "HiveChange" (
|
||||
"id" TEXT NOT NULL,
|
||||
"colonyId" TEXT NOT NULL,
|
||||
"version" INTEGER NOT NULL,
|
||||
"occurredOn" TIMESTAMP(3) NOT NULL,
|
||||
"source" "HiveChangeSource" NOT NULL,
|
||||
"inspectionId" TEXT,
|
||||
"userId" TEXT NOT NULL,
|
||||
"ops" JSONB NOT NULL,
|
||||
"stateAfter" JSONB NOT NULL,
|
||||
"note" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "HiveChange_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "HiveSystem_name_key" ON "HiveSystem"("name");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "HivePartType_systemId_name_key" ON "HivePartType"("systemId", "name");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "HiveChange_inspectionId_key" ON "HiveChange"("inspectionId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "HiveChange_colonyId_occurredOn_idx" ON "HiveChange"("colonyId", "occurredOn");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "HiveChange_colonyId_version_key" ON "HiveChange"("colonyId", "version");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "HivePartType" ADD CONSTRAINT "HivePartType_systemId_fkey" FOREIGN KEY ("systemId") REFERENCES "HiveSystem"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "HiveSetup" ADD CONSTRAINT "HiveSetup_colonyId_fkey" FOREIGN KEY ("colonyId") REFERENCES "Colony"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "HiveSetup" ADD CONSTRAINT "HiveSetup_systemId_fkey" FOREIGN KEY ("systemId") REFERENCES "HiveSystem"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "HiveChange" ADD CONSTRAINT "HiveChange_colonyId_fkey" FOREIGN KEY ("colonyId") REFERENCES "HiveSetup"("colonyId") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "HiveChange" ADD CONSTRAINT "HiveChange_inspectionId_fkey" FOREIGN KEY ("inspectionId") REFERENCES "Inspection"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "HiveChange" ADD CONSTRAINT "HiveChange_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
-- Beute in 3D: start catalog for the Liebig-Zander equipment (spec 2026-10-15,
|
||||
-- sections 4.3 and 4.4) under fixed ids, so the system template has stable
|
||||
-- references and a restore into a fresh install creates no duplicate names.
|
||||
-- Dimensions are catalog data and editable in the settings.
|
||||
|
||||
-- Hive system
|
||||
INSERT INTO "HiveSystem" ("id", "name", "frameWidthMm", "frameHeightMm", "footprintLMm", "footprintWMm", "template", "active", "updatedAt")
|
||||
VALUES (
|
||||
'hive-system-zander-liebig-10',
|
||||
'Zander nach Dr. Liebig, 10 Rähmchen',
|
||||
477,
|
||||
220,
|
||||
525,
|
||||
430,
|
||||
'{"schemaVersion":1,"stack":[{"partTypeId":"hive-part-zl10-floor","state":{}},{"partTypeId":"hive-part-zl10-box-10","state":{},"frames":[{"slot":1,"type":"FOUNDATION"},{"slot":2,"type":"FOUNDATION"},{"slot":3,"type":"FOUNDATION"},{"slot":4,"type":"FOUNDATION"},{"slot":5,"type":"FOUNDATION"},{"slot":6,"type":"FOUNDATION"},{"slot":7,"type":"FOUNDATION"},{"slot":8,"type":"FOUNDATION"},{"slot":9,"type":"FOUNDATION"},{"slot":10,"type":"FOUNDATION"}]},{"partTypeId":"hive-part-zl10-cover-abdeckfix","state":{}},{"partTypeId":"hive-part-zl10-inner-lid","state":{}},{"partTypeId":"hive-part-zl10-insulation","state":{}},{"partTypeId":"hive-part-zl10-roof","state":{}}]}'::jsonb,
|
||||
true,
|
||||
CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Part types
|
||||
INSERT INTO "HivePartType" ("id", "systemId", "kind", "name", "lengthMm", "widthMm", "heightMm", "boxDepth", "frameSlots", "stateSchema", "active", "updatedAt")
|
||||
VALUES
|
||||
('hive-part-zl10-floor', 'hive-system-zander-liebig-10', 'FLOOR', 'Liebig Wanderboden', 525, 430, 120, NULL, NULL, '[{"key":"entrance","label":"Flugloch","kind":"choice","options":["OPEN","NARROW","CLOSED"],"optionLabels":["offen","eng","zu"]},{"key":"varroaTray","label":"Varroa-Schublade","kind":"choice","options":["IN","OUT"],"optionLabels":["drin","draußen"]}]'::jsonb, true, CURRENT_TIMESTAMP),
|
||||
('hive-part-zl10-floor-insert', 'hive-system-zander-liebig-10', 'FLOOR_INSERT', 'Liebig Bausperre', 475, 375, 5, NULL, NULL, '[]'::jsonb, true, CURRENT_TIMESTAMP),
|
||||
('hive-part-zl10-box-10', 'hive-system-zander-liebig-10', 'BOX', 'Liebig Zander Ganzzarge, 10 Rähmchen', 525, 430, 230, 'FULL', 10, '[]'::jsonb, true, CURRENT_TIMESTAMP),
|
||||
('hive-part-zl10-box-empty', 'hive-system-zander-liebig-10', 'BOX', 'Leerzarge (Liebig Zander Ganzzarge ohne Rähmchen)', 525, 430, 230, 'FULL', 0, '[]'::jsonb, true, CURRENT_TIMESTAMP),
|
||||
('hive-part-zl10-divider-board', 'hive-system-zander-liebig-10', 'DIVIDER_BOARD', 'Liebig Zwischenboden', 525, 430, 50, NULL, NULL, '[{"key":"bungHoles","label":"Spundlöcher","kind":"choice","options":["OPEN","CLOSED","BEE_ESCAPE"],"optionLabels":["offen","zu","Bienenflucht"]}]'::jsonb, true, CURRENT_TIMESTAMP),
|
||||
('hive-part-zl10-queen-excluder', 'hive-system-zander-liebig-10', 'QUEEN_EXCLUDER', 'Niro-Absperrgitter Zander Liebig', 478, 376, 2, NULL, NULL, '[]'::jsonb, true, CURRENT_TIMESTAMP),
|
||||
('hive-part-zl10-feeder', 'hive-system-zander-liebig-10', 'FEEDER', 'Liebig Zweikammer-Futterzarge', 520, 420, 70, NULL, NULL, '[{"key":"syrupLiters","label":"Flüssigfutter","kind":"level","unit":"l","max":3,"step":0.5,"feedType":"SUGAR_WATER"},{"key":"fondantKg","label":"Futterteig","kind":"level","unit":"kg","max":2.5,"step":0.5,"feedType":"FEED_PASTE"}]'::jsonb, true, CURRENT_TIMESTAMP),
|
||||
('hive-part-zl10-cover-abdeckfix', 'hive-system-zander-liebig-10', 'COVER_SHEET', 'Abdeck-Fix (Folie, klar, 0,4 mm)', 478, 378, 1, NULL, NULL, '[]'::jsonb, true, CURRENT_TIMESTAMP),
|
||||
('hive-part-zl10-cover-lotus', 'hive-system-zander-liebig-10', 'COVER_SHEET', 'Imgut Lotus-Abdeckung (0,5 mm)', 478, 378, 1, NULL, NULL, '[]'::jsonb, true, CURRENT_TIMESTAMP),
|
||||
('hive-part-zl10-propolis-screen', 'hive-system-zander-liebig-10', 'PROPOLIS_SCREEN', 'Imgut Propolisgitter', 478, 378, 3, NULL, NULL, '[]'::jsonb, true, CURRENT_TIMESTAMP),
|
||||
('hive-part-zl10-inner-lid', 'hive-system-zander-liebig-10', 'INNER_LID', 'Liebig Holzdeckel', 525, 430, 35, NULL, NULL, '[{"key":"feedHole","label":"Futterloch","kind":"choice","options":["OPEN","CLOSED"],"optionLabels":["offen","zu"]}]'::jsonb, true, CURRENT_TIMESTAMP),
|
||||
('hive-part-zl10-insulation', 'hive-system-zander-liebig-10', 'INSULATION', 'Styropor-Einlage (selbst gebaut)', 465, 365, 20, NULL, NULL, '[]'::jsonb, true, CURRENT_TIMESTAMP),
|
||||
('hive-part-zl10-roof', 'hive-system-zander-liebig-10', 'ROOF', 'Edelstahldeckel konisch Liebig', 525, 430, 60, NULL, NULL, '[]'::jsonb, true, CURRENT_TIMESTAMP),
|
||||
('hive-part-zl10-evaporator', 'hive-system-zander-liebig-10', 'EVAPORATOR', 'Nassenheider Verdunster Professional', 200, 140, 120, NULL, NULL, '[{"key":"acidMl","label":"Ameisensäure","kind":"level","unit":"ml","max":290,"step":10}]'::jsonb, true, CURRENT_TIMESTAMP);
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Beute in 3D: Futtertasche (FRAME_FEEDER, spec 2026-10-15 sections 4.1, 4.3,
|
||||
-- 5.1). A frame feeder hangs in a box in place of frames and covers
|
||||
-- `slotWidth` frame slots. The enum value cannot be used in the migration that
|
||||
-- adds it, so the catalog row comes in 20261018100100.
|
||||
|
||||
-- AlterEnum
|
||||
ALTER TYPE "HivePartKind" ADD VALUE 'FRAME_FEEDER';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "HivePartType" ADD COLUMN "slotWidth" INTEGER;
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
-- Beute in 3D: start catalog row for the Futtertasche (owner wish 2026-10-16,
|
||||
-- spec sections 4.3 and 4.1). Fixed id like the other start data; dimensions and
|
||||
-- the 2 l capacity are assumptions the owner confirms (catalog data, editable).
|
||||
|
||||
INSERT INTO "HivePartType" ("id", "systemId", "kind", "name", "lengthMm", "widthMm", "heightMm", "boxDepth", "frameSlots", "slotWidth", "stateSchema", "active", "updatedAt")
|
||||
VALUES (
|
||||
'hive-part-zl10-frame-feeder',
|
||||
'hive-system-zander-liebig-10',
|
||||
'FRAME_FEEDER',
|
||||
'Holz-Futtertasche Zander, doppelte Wabenbreite',
|
||||
477,
|
||||
70,
|
||||
220,
|
||||
NULL,
|
||||
NULL,
|
||||
2,
|
||||
'[{"key":"syrupLiters","label":"Flüssigfutter","kind":"level","unit":"l","max":2,"step":0.25,"feedType":"SUGAR_WATER"}]'::jsonb,
|
||||
true,
|
||||
CURRENT_TIMESTAMP
|
||||
);
|
||||
@@ -0,0 +1,96 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "VoiceCaptureSource" AS ENUM ('AUDIO', 'TEXT');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "VoiceCaptureStatus" AS ENUM ('QUEUED', 'TRANSCRIBING', 'TRANSCRIBED', 'EXTRACTING', 'READY', 'CONFIRMED', 'DISCARDED', 'FAILED', 'EXPIRED');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "VoiceCapture" (
|
||||
"id" TEXT NOT NULL,
|
||||
"ownerUserId" TEXT NOT NULL,
|
||||
"colonyId" TEXT NOT NULL,
|
||||
"inspectionDate" DATE NOT NULL,
|
||||
"source" "VoiceCaptureSource" NOT NULL,
|
||||
"status" "VoiceCaptureStatus" NOT NULL DEFAULT 'QUEUED',
|
||||
"audioMime" TEXT,
|
||||
"audioBytes" INTEGER,
|
||||
"durationSec" INTEGER,
|
||||
"transcriptEnc" TEXT,
|
||||
"suggestionEnc" TEXT,
|
||||
"attempts" INTEGER NOT NULL DEFAULT 0,
|
||||
"availableAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"claimedAt" TIMESTAMP(3),
|
||||
"claimToken" TEXT,
|
||||
"lastErrorCode" TEXT,
|
||||
"model" TEXT,
|
||||
"inputTokens" INTEGER,
|
||||
"outputTokens" INTEGER,
|
||||
"inspectionId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"readyAt" TIMESTAMP(3),
|
||||
"contentExpiresAt" TIMESTAMP(3) NOT NULL,
|
||||
"contentDeletedAt" TIMESTAMP(3),
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "VoiceCapture_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "VoiceCaptureAudio" (
|
||||
"captureId" TEXT NOT NULL,
|
||||
"dataEnc" BYTEA NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "VoiceCaptureAudio_pkey" PRIMARY KEY ("captureId")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "VoiceCapture_status_availableAt_idx" ON "VoiceCapture"("status", "availableAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "VoiceCapture_ownerUserId_status_idx" ON "VoiceCapture"("ownerUserId", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "VoiceCapture_contentExpiresAt_idx" ON "VoiceCapture"("contentExpiresAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "VoiceCapture" ADD CONSTRAINT "VoiceCapture_ownerUserId_fkey" FOREIGN KEY ("ownerUserId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "VoiceCapture" ADD CONSTRAINT "VoiceCapture_colonyId_fkey" FOREIGN KEY ("colonyId") REFERENCES "Colony"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "VoiceCaptureAudio" ADD CONSTRAINT "VoiceCaptureAudio_captureId_fkey" FOREIGN KEY ("captureId") REFERENCES "VoiceCapture"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
|
||||
-- Constraints Prisma cannot express.
|
||||
ALTER TABLE "VoiceCapture"
|
||||
ADD CONSTRAINT "VoiceCapture_audioBytes_range"
|
||||
CHECK ("audioBytes" IS NULL OR "audioBytes" BETWEEN 1 AND 2097152);
|
||||
|
||||
ALTER TABLE "VoiceCapture"
|
||||
ADD CONSTRAINT "VoiceCapture_durationSec_range"
|
||||
CHECK ("durationSec" IS NULL OR "durationSec" BETWEEN 1 AND 240);
|
||||
|
||||
ALTER TABLE "VoiceCapture"
|
||||
ADD CONSTRAINT "VoiceCapture_confirmed_matches_inspection"
|
||||
CHECK (("status" = 'CONFIRMED') = ("inspectionId" IS NOT NULL));
|
||||
|
||||
ALTER TABLE "VoiceCapture"
|
||||
ADD CONSTRAINT "VoiceCapture_audioMime_only_for_audio"
|
||||
CHECK ("source" = 'AUDIO' OR "audioMime" IS NULL);
|
||||
|
||||
-- Permission: the boot-time catalog sync only grants new permissions to
|
||||
-- system roles (ADMIN), so the grants are made here (same as T6). READONLY
|
||||
-- and API_CLIENT get nothing: voice notes are for people who inspect.
|
||||
INSERT INTO "Permission" (id, key, resource, action, "labelDe", "groupDe", "sortOrder")
|
||||
VALUES
|
||||
(gen_random_uuid()::text, 'voice-captures:use', 'voice-captures', 'use', 'Benutzen', 'Sprache', 4000)
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
|
||||
INSERT INTO "RolePermission" ("roleId", "permissionId", "grantedAt")
|
||||
SELECT r.id, p.id, now()
|
||||
FROM "Role" r, "Permission" p
|
||||
WHERE p.key = 'voice-captures:use'
|
||||
AND r.key IN ('ADMIN', 'BEEKEEPER', 'STAFF')
|
||||
ON CONFLICT DO NOTHING;
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "VoiceExtractionOutcome" AS ENUM ('OK', 'REFUSED', 'TRUNCATED', 'INVALID', 'RETRY', 'BAD_REQUEST', 'AUTH', 'ABORTED');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "VoiceExtractionCall" (
|
||||
"id" TEXT NOT NULL,
|
||||
"at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"model" TEXT NOT NULL,
|
||||
"inputTokens" INTEGER NOT NULL DEFAULT 0,
|
||||
"outputTokens" INTEGER NOT NULL DEFAULT 0,
|
||||
"outcome" "VoiceExtractionOutcome" NOT NULL,
|
||||
"captureId" TEXT,
|
||||
|
||||
CONSTRAINT "VoiceExtractionCall_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "VoiceExtractionCall_at_idx" ON "VoiceExtractionCall"("at");
|
||||
@@ -104,6 +104,8 @@ model User {
|
||||
refreshTokens RefreshToken[]
|
||||
|
||||
inspections Inspection[]
|
||||
voiceCaptures VoiceCapture[]
|
||||
hiveChanges HiveChange[]
|
||||
varroaMeasurements VarroaMeasurement[]
|
||||
swarmControlChecks SwarmControlCheck[]
|
||||
winterChecks WinterCheck[]
|
||||
@@ -331,6 +333,8 @@ model Colony {
|
||||
harvests HarvestColony[]
|
||||
queenEvaluations QueenEvaluation[]
|
||||
suggestions Suggestion[]
|
||||
hiveSetup HiveSetup?
|
||||
voiceCaptures VoiceCapture[]
|
||||
|
||||
@@index([apiaryId])
|
||||
@@index([status])
|
||||
@@ -501,7 +505,8 @@ model Inspection {
|
||||
notes String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
tasks Task[]
|
||||
tasks Task[]
|
||||
hiveChange HiveChange?
|
||||
|
||||
@@index([colonyId, date])
|
||||
}
|
||||
@@ -2182,3 +2187,202 @@ model ComplianceAcknowledgement {
|
||||
|
||||
@@index([itemKey, subjectId])
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Beute in 3D: Beutensysteme, Teile-Arten, Aufbau je Volk (Spec 2026-10-15)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
model HiveSystem {
|
||||
id String @id @default(cuid())
|
||||
name String @unique
|
||||
frameWidthMm Int // Oberträger
|
||||
frameHeightMm Int
|
||||
footprintLMm Int
|
||||
footprintWMm Int
|
||||
template Json // Aufbau-JSON ohne Ids, Schema 5.2
|
||||
active Boolean @default(true)
|
||||
partTypes HivePartType[]
|
||||
setups HiveSetup[]
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
model HivePartType {
|
||||
id String @id @default(cuid())
|
||||
systemId String
|
||||
system HiveSystem @relation(fields: [systemId], references: [id])
|
||||
kind HivePartKind
|
||||
name String
|
||||
articleRef String? // z. B. Holtermann-Art.-Nr.
|
||||
lengthMm Int
|
||||
widthMm Int
|
||||
heightMm Int
|
||||
boxDepth HiveBoxDepth?
|
||||
frameSlots Int? // nur BOX
|
||||
slotWidth Int? // nur FRAME_FEEDER: belegte Rähmchen-Plätze
|
||||
stateSchema Json // Abschnitt 4.2
|
||||
active Boolean @default(true)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([systemId, name])
|
||||
}
|
||||
|
||||
model HiveSetup {
|
||||
colonyId String @id
|
||||
colony Colony @relation(fields: [colonyId], references: [id])
|
||||
systemId String
|
||||
system HiveSystem @relation(fields: [systemId], references: [id])
|
||||
version Int @default(1)
|
||||
state Json // Abschnitt 5.2, immer vollständig
|
||||
updatedAt DateTime @updatedAt
|
||||
changes HiveChange[]
|
||||
}
|
||||
|
||||
model HiveChange {
|
||||
id String @id @default(cuid())
|
||||
colonyId String
|
||||
setup HiveSetup @relation(fields: [colonyId], references: [colonyId])
|
||||
version Int // Version nach der Änderung
|
||||
occurredOn DateTime // fachlicher Tag (Durchsicht oder Eingabe)
|
||||
source HiveChangeSource
|
||||
inspectionId String? @unique
|
||||
inspection Inspection? @relation(fields: [inspectionId], references: [id])
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id])
|
||||
ops Json // angewandte Operationen, Abschnitt 6
|
||||
stateAfter Json
|
||||
note String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@unique([colonyId, version])
|
||||
@@index([colonyId, occurredOn])
|
||||
}
|
||||
|
||||
enum HivePartKind {
|
||||
FLOOR
|
||||
BOX
|
||||
DIVIDER_BOARD
|
||||
QUEEN_EXCLUDER
|
||||
FEEDER
|
||||
COVER_SHEET
|
||||
PROPOLIS_SCREEN
|
||||
INNER_LID
|
||||
INSULATION
|
||||
ROOF
|
||||
FLOOR_INSERT
|
||||
EVAPORATOR
|
||||
FRAME_FEEDER
|
||||
}
|
||||
|
||||
enum HiveBoxDepth {
|
||||
FULL
|
||||
SHALLOW
|
||||
}
|
||||
|
||||
enum HiveChangeSource {
|
||||
INIT
|
||||
CARD
|
||||
EDITOR
|
||||
INSPECTION
|
||||
AI_SUGGESTION
|
||||
}
|
||||
|
||||
enum VoiceCaptureSource {
|
||||
AUDIO
|
||||
TEXT
|
||||
}
|
||||
|
||||
enum VoiceCaptureStatus {
|
||||
QUEUED // audio uploaded, waits for Whisper
|
||||
TRANSCRIBING // claimed by the CronJob
|
||||
TRANSCRIBED // text present, waits for Claude (also source TEXT)
|
||||
EXTRACTING // claimed by the worker
|
||||
READY // suggestions present, waits for the user
|
||||
CONFIRMED // inspection saved, content deleted
|
||||
DISCARDED // discarded by the user, content deleted
|
||||
FAILED // finally failed, code in lastErrorCode
|
||||
EXPIRED // deadline passed, content deleted
|
||||
}
|
||||
|
||||
// A voice note. Audio and text are personal data: content lives here only
|
||||
// encrypted and only until it is taken over, at most 7 days. The row itself
|
||||
// holds no content and stays 90 days for the error and cost overview.
|
||||
model VoiceCapture {
|
||||
id String @id @default(cuid())
|
||||
ownerUserId String
|
||||
owner User @relation(fields: [ownerUserId], references: [id])
|
||||
colonyId String
|
||||
colony Colony @relation(fields: [colonyId], references: [id])
|
||||
inspectionDate DateTime @db.Date // date of the inspection per the form
|
||||
source VoiceCaptureSource
|
||||
status VoiceCaptureStatus @default(QUEUED)
|
||||
|
||||
audioMime String? // audio/webm, audio/ogg, audio/mp4
|
||||
audioBytes Int?
|
||||
durationSec Int? // reported by the device; Whisper measures again
|
||||
|
||||
transcriptEnc String? // key-ring ciphertext
|
||||
suggestionEnc String? // key-ring ciphertext of the checked suggestion
|
||||
|
||||
attempts Int @default(0)
|
||||
availableAt DateTime @default(now())
|
||||
claimedAt DateTime?
|
||||
claimToken String? // guards against completion by a process that lost the claim
|
||||
lastErrorCode String? // fixed code, never content
|
||||
|
||||
model String? // e.g. "claude-sonnet-5-5"
|
||||
inputTokens Int?
|
||||
outputTokens Int?
|
||||
|
||||
inspectionId String? // set when CONFIRMED
|
||||
createdAt DateTime @default(now())
|
||||
readyAt DateTime?
|
||||
contentExpiresAt DateTime // createdAt + 7 days
|
||||
contentDeletedAt DateTime? // when audio/text/suggestion were deleted
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
audio VoiceCaptureAudio?
|
||||
|
||||
@@index([status, availableAt])
|
||||
@@index([ownerUserId, status])
|
||||
@@index([contentExpiresAt])
|
||||
}
|
||||
|
||||
// The audio lives in its own table: deleting is a DELETE of the row (not
|
||||
// nulling a big column), and the row is never loaded into lists.
|
||||
model VoiceCaptureAudio {
|
||||
captureId String @id
|
||||
capture VoiceCapture @relation(fields: [captureId], references: [id], onDelete: Cascade)
|
||||
dataEnc Bytes // key-ring ciphertext of the audio, at most 2 MB plaintext
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
// What a call to the language model counts as. The daily budget counts every
|
||||
// outcome except AUTH and ABORTED (those never reached the model).
|
||||
enum VoiceExtractionOutcome {
|
||||
OK
|
||||
REFUSED
|
||||
TRUNCATED
|
||||
INVALID
|
||||
RETRY
|
||||
BAD_REQUEST
|
||||
AUTH
|
||||
ABORTED
|
||||
}
|
||||
|
||||
// Ledger of paid model calls for voice extraction: the daily budget and the
|
||||
// cost card read it, not the notes (a retry or a refused call costs money
|
||||
// too). Ids and numbers only - no content, no foreign key (a note may be
|
||||
// deleted while the call stays counted). Rows go after 90 days (cleanup).
|
||||
model VoiceExtractionCall {
|
||||
id String @id @default(cuid())
|
||||
at DateTime @default(now())
|
||||
model String
|
||||
inputTokens Int @default(0)
|
||||
outputTokens Int @default(0)
|
||||
outcome VoiceExtractionOutcome
|
||||
captureId String?
|
||||
|
||||
@@index([at])
|
||||
}
|
||||
@@ -16,18 +16,28 @@ function generateRandomPassword(): string {
|
||||
}
|
||||
|
||||
// Only printed the moment the account is actually created (first deploy on
|
||||
// an empty database), never on later restarts: by then the real admin may
|
||||
// an empty user table), never on later restarts: by then the real admin may
|
||||
// have changed the password via /profile, so repeating it would just be
|
||||
// stale and would leak credentials into logs indefinitely for no reason.
|
||||
function printLoginBanner(email: string, password: string): void {
|
||||
// An operator-supplied password is never printed: the operator already has
|
||||
// it, and the log would only be one more place it leaks to.
|
||||
function printLoginBanner(
|
||||
email: string,
|
||||
password: string | null,
|
||||
log: (line: string) => void,
|
||||
): void {
|
||||
const url = process.env.FRONTEND_ORIGIN ?? 'http://localhost:3000';
|
||||
const line = '='.repeat(60);
|
||||
console.log(line);
|
||||
console.log('Seed: Admin-Zugang eingerichtet.');
|
||||
console.log(` URL: ${url}`);
|
||||
console.log(` Benutzer: ${email}`);
|
||||
console.log(` Passwort: ${password}`);
|
||||
console.log(line);
|
||||
log(line);
|
||||
log('Seed: Admin-Zugang eingerichtet.');
|
||||
log(` URL: ${url}`);
|
||||
log(` Benutzer: ${email}`);
|
||||
log(
|
||||
password === null
|
||||
? ' Passwort: wie in SEED_ADMIN_PASSWORD gesetzt'
|
||||
: ` Passwort: ${password}`,
|
||||
);
|
||||
log(line);
|
||||
}
|
||||
|
||||
// Duplicated from src/task-templates/recurrence.ts rather than imported:
|
||||
@@ -189,22 +199,26 @@ async function seedDefaultTaskTemplates(prisma: PrismaClient): Promise<void> {
|
||||
);
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const prisma = new PrismaClient({
|
||||
adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
|
||||
});
|
||||
type AdminSeedClient = Pick<PrismaClient, 'user' | 'role'>;
|
||||
|
||||
await seedDefaultTaskTemplates(prisma);
|
||||
|
||||
const email = process.env.SEED_ADMIN_EMAIL ?? DEFAULT_ADMIN_EMAIL;
|
||||
const password = process.env.SEED_ADMIN_PASSWORD ?? generateRandomPassword();
|
||||
const existing = await prisma.user.findUnique({ where: { email } });
|
||||
if (existing) {
|
||||
console.log(`Seed: admin user ${email} already exists, skipping.`);
|
||||
await prisma.$disconnect();
|
||||
return;
|
||||
/**
|
||||
* Creates the first administrator, but only while the user table is still
|
||||
* empty. Checking SEED_ADMIN_EMAIL instead would add a second ADMIN (and log
|
||||
* its password) on every start after the real admin changed their address.
|
||||
*/
|
||||
export async function seedAdmin(
|
||||
prisma: AdminSeedClient,
|
||||
env: NodeJS.ProcessEnv,
|
||||
log: (line: string) => void,
|
||||
): Promise<'created' | 'skipped'> {
|
||||
if ((await prisma.user.count()) > 0) {
|
||||
log('Seed: Es gibt bereits Benutzer, kein Admin angelegt.');
|
||||
return 'skipped';
|
||||
}
|
||||
|
||||
const email = env.SEED_ADMIN_EMAIL ?? DEFAULT_ADMIN_EMAIL;
|
||||
const suppliedPassword = env.SEED_ADMIN_PASSWORD;
|
||||
const password = suppliedPassword ?? generateRandomPassword();
|
||||
const passwordHash = await bcrypt.hash(password, BCRYPT_SALT_ROUNDS);
|
||||
const adminRole = await prisma.role.findUniqueOrThrow({
|
||||
where: { key: 'ADMIN' },
|
||||
@@ -218,27 +232,42 @@ async function main(): Promise<void> {
|
||||
roleId: adminRole.id,
|
||||
},
|
||||
});
|
||||
printLoginBanner(email, password);
|
||||
} catch (error: unknown) {
|
||||
// P2002 = unique constraint violation on email: another replica's
|
||||
// startup won this race between the existence check above and this
|
||||
// create() call. The user now exists either way, so this is a no-op,
|
||||
// not a failure - container startup must not crash on it.
|
||||
// startup won this race between the count above and this create()
|
||||
// call. The user now exists either way, so this is a no-op, not a
|
||||
// failure - container startup must not crash on it.
|
||||
if (
|
||||
error instanceof Prisma.PrismaClientKnownRequestError &&
|
||||
error.code === 'P2002'
|
||||
) {
|
||||
console.log(
|
||||
`Seed: admin user ${email} was created concurrently, skipping.`,
|
||||
);
|
||||
} else {
|
||||
throw error;
|
||||
log(`Seed: admin user ${email} was created concurrently, skipping.`);
|
||||
return 'skipped';
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
printLoginBanner(
|
||||
email,
|
||||
suppliedPassword === undefined ? password : null,
|
||||
log,
|
||||
);
|
||||
return 'created';
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const prisma = new PrismaClient({
|
||||
adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
|
||||
});
|
||||
|
||||
await seedDefaultTaskTemplates(prisma);
|
||||
await seedAdmin(prisma, process.env, (line) => console.log(line));
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
|
||||
main().catch((error: unknown) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
// Only when run as `node dist/seed.js`, not when a test imports seedAdmin.
|
||||
if (require.main === module) {
|
||||
main().catch((error: unknown) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
/**
|
||||
* Evaluates voice extraction against the gold set (test/fixtures/voice/gold).
|
||||
*
|
||||
* npm run eval:voice offline, replays the expected answers, no network, free
|
||||
* npm run eval:voice -- --live --yes real Claude calls, costs money
|
||||
* npm run eval:voice -- --live --yes --model=claude-haiku-5-5
|
||||
*
|
||||
* Live mode needs ANTHROPIC_API_KEY in the environment AND both --live and
|
||||
* --yes; it is never the default and never runs in CI (no workflow calls
|
||||
* this script). This is an operator tool, not a request path: it lives
|
||||
* outside src/, so the network guard (src/common/no-network-outside-loops)
|
||||
* does not scan it, and it talks to the adapter only through the
|
||||
* StructuredModel port.
|
||||
*
|
||||
* Exit code: 0 pass, 1 below the thresholds (precision < 98 % or recall <
|
||||
* 85 %, see EVAL_THRESHOLDS), 2 usage or setup error.
|
||||
*/
|
||||
import { join } from 'node:path';
|
||||
import { anthropicApiKey } from '../src/voice/anthropic-config';
|
||||
import { formatReport } from '../src/voice/eval/eval-report';
|
||||
import { loadGoldCases } from '../src/voice/eval/gold-case';
|
||||
import { estimateCostUsd } from '../src/voice/eval/voice-prices';
|
||||
import {
|
||||
offlineModelFor,
|
||||
runEval,
|
||||
summarize,
|
||||
} from '../src/voice/eval/voice-eval';
|
||||
import { AnthropicStructuredModel } from '../src/voice/extraction/anthropic-structured-model';
|
||||
import { FAKE_USAGE } from '../src/voice/extraction/fake-structured-model';
|
||||
import { DEFAULT_VOICE_MODEL, VOICE_MODELS } from '../src/voice/voice-config';
|
||||
|
||||
const GOLD_DIR = join(__dirname, '..', 'test', 'fixtures', 'voice', 'gold');
|
||||
const EXIT_PASS = 0;
|
||||
const EXIT_BELOW_THRESHOLD = 1;
|
||||
const EXIT_USAGE = 2;
|
||||
|
||||
interface Options {
|
||||
live: boolean;
|
||||
yes: boolean;
|
||||
model: string;
|
||||
}
|
||||
|
||||
function parseArgs(args: readonly string[]): Options | string {
|
||||
let live = false;
|
||||
let yes = false;
|
||||
let model: string = DEFAULT_VOICE_MODEL;
|
||||
for (const arg of args) {
|
||||
if (arg === '--live') {
|
||||
live = true;
|
||||
} else if (arg === '--yes') {
|
||||
yes = true;
|
||||
} else if (arg.startsWith('--model=')) {
|
||||
model = arg.slice('--model='.length);
|
||||
} else {
|
||||
return `Unknown argument: ${arg}`;
|
||||
}
|
||||
}
|
||||
if (!(VOICE_MODELS as readonly string[]).includes(model)) {
|
||||
return `--model must be one of ${VOICE_MODELS.join(', ')}`;
|
||||
}
|
||||
return { live, yes, model };
|
||||
}
|
||||
|
||||
function fail(message: string): never {
|
||||
console.error(message);
|
||||
process.exit(EXIT_USAGE);
|
||||
}
|
||||
|
||||
async function main(): Promise<number> {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
if (typeof options === 'string') {
|
||||
return fail(options);
|
||||
}
|
||||
const cases = loadGoldCases(GOLD_DIR);
|
||||
if (!options.live) {
|
||||
const results = await runEval(
|
||||
cases,
|
||||
offlineModelFor(options.model),
|
||||
options.model,
|
||||
);
|
||||
console.log(
|
||||
formatReport(results, summarize(results), {
|
||||
mode: 'offline',
|
||||
model: options.model,
|
||||
}),
|
||||
);
|
||||
return summarizeExit(results);
|
||||
}
|
||||
const key = anthropicApiKey(process.env);
|
||||
if (key === null) {
|
||||
return fail('--live needs a valid ANTHROPIC_API_KEY in the environment.');
|
||||
}
|
||||
const estimate = estimateCostUsd(options.model, {
|
||||
input: FAKE_USAGE.input * cases.length,
|
||||
output: FAKE_USAGE.output * cases.length,
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
});
|
||||
console.warn(
|
||||
`WARNING: ${cases.length} real Claude calls on ${options.model}, roughly ${
|
||||
estimate === null ? 'an unknown amount' : `$${estimate.toFixed(2)}`
|
||||
} of API cost.`,
|
||||
);
|
||||
if (!options.yes) {
|
||||
return fail('Add --yes to confirm and run the live evaluation.');
|
||||
}
|
||||
const live = new AnthropicStructuredModel(key);
|
||||
const results = await runEval(cases, () => live, options.model);
|
||||
console.log(
|
||||
formatReport(results, summarize(results), {
|
||||
mode: 'live',
|
||||
model: options.model,
|
||||
}),
|
||||
);
|
||||
return summarizeExit(results);
|
||||
}
|
||||
|
||||
function summarizeExit(results: Parameters<typeof summarize>[0]): number {
|
||||
return summarize(results).failures.length === 0
|
||||
? EXIT_PASS
|
||||
: EXIT_BELOW_THRESHOLD;
|
||||
}
|
||||
|
||||
main().then(
|
||||
(code) => process.exit(code),
|
||||
(error: unknown) => {
|
||||
console.error(error instanceof Error ? error.message : 'eval failed');
|
||||
process.exit(EXIT_USAGE);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Writes the Whisper initial prompt to ApiCore-Whisper/vocabulary.txt, so the
|
||||
* Python image uses the same word list as the backend (one source:
|
||||
* src/voice/core/voice-vocabulary.ts). Run `npm run export:voice-vocabulary`
|
||||
* after changing the list; voice-vocabulary-export.spec.ts fails until you do.
|
||||
*/
|
||||
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { whisperInitialPrompt } from '../src/voice/core/voice-vocabulary';
|
||||
|
||||
const target = join(__dirname, '..', '..', 'ApiCore-Whisper', 'vocabulary.txt');
|
||||
|
||||
mkdirSync(dirname(target), { recursive: true });
|
||||
writeFileSync(target, `${whisperInitialPrompt()}\n`, 'utf8');
|
||||
console.log(`Wrote ${target}`);
|
||||
@@ -1,11 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AutopilotModule } from '../autopilot/autopilot.module';
|
||||
import { DomainEventsModule } from '../domain-events/domain-events.module';
|
||||
import { HiveModule } from '../hive/hive.module';
|
||||
import { ApiariesController } from './apiaries.controller';
|
||||
import { ApiariesService } from './apiaries.service';
|
||||
import { ApiaryFieldService } from './apiary-field.service';
|
||||
|
||||
@Module({
|
||||
imports: [AutopilotModule],
|
||||
imports: [AutopilotModule, DomainEventsModule, HiveModule],
|
||||
controllers: [ApiariesController],
|
||||
providers: [ApiariesService, ApiaryFieldService],
|
||||
exports: [ApiariesService],
|
||||
|
||||
@@ -2,44 +2,78 @@ import { ConflictException, NotFoundException } from '@nestjs/common';
|
||||
import { ApiariesService } from './apiaries.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { AuditLogService } from '../audit/audit-log.service';
|
||||
import { DomainEventsService } from '../domain-events/domain-events.service';
|
||||
import { expectOnlyIdPayloads } from '../domain-events/herd-payload.spec-helper';
|
||||
|
||||
describe('ApiariesService', () => {
|
||||
let service: ApiariesService;
|
||||
let prisma: {
|
||||
apiary: {
|
||||
findMany: jest.Mock;
|
||||
findUnique: jest.Mock;
|
||||
create: jest.Mock;
|
||||
update: jest.Mock;
|
||||
};
|
||||
let order: string[];
|
||||
let tx: {
|
||||
$queryRaw: jest.Mock;
|
||||
apiary: { findUnique: jest.Mock; create: jest.Mock; update: jest.Mock };
|
||||
colony: { count: jest.Mock };
|
||||
};
|
||||
let prisma: {
|
||||
apiary: { findMany: jest.Mock; findUnique: jest.Mock };
|
||||
$transaction: jest.Mock;
|
||||
};
|
||||
let auditLog: { record: jest.Mock };
|
||||
let events: { record: jest.Mock };
|
||||
|
||||
const existingApiary = {
|
||||
id: 'apiary-1',
|
||||
name: 'Heimstand',
|
||||
status: 'ACTIVE',
|
||||
deactivatedAt: null,
|
||||
address: 'Weg 1',
|
||||
location: 'Garten',
|
||||
latitude: 48.1,
|
||||
longitude: 11.5,
|
||||
notes: null,
|
||||
};
|
||||
|
||||
const changes = (): string[] =>
|
||||
(
|
||||
events.record.mock.calls as [unknown, { payload: { change: string } }][]
|
||||
).map(([, event]) => event.payload.change);
|
||||
|
||||
beforeEach(() => {
|
||||
prisma = {
|
||||
order = [];
|
||||
tx = {
|
||||
$queryRaw: jest.fn().mockImplementation(() => {
|
||||
order.push('lock');
|
||||
return Promise.resolve([{ id: 'apiary-1' }]);
|
||||
}),
|
||||
apiary: {
|
||||
findMany: jest.fn(),
|
||||
findUnique: jest.fn(),
|
||||
findUnique: jest.fn().mockImplementation(() => {
|
||||
order.push('read');
|
||||
return Promise.resolve(existingApiary);
|
||||
}),
|
||||
create: jest.fn(),
|
||||
update: jest.fn(),
|
||||
},
|
||||
colony: { count: jest.fn().mockResolvedValue(0) },
|
||||
};
|
||||
prisma = {
|
||||
apiary: { findMany: jest.fn(), findUnique: jest.fn() },
|
||||
$transaction: jest.fn((callback: (txArg: typeof tx) => unknown) =>
|
||||
callback(tx),
|
||||
),
|
||||
};
|
||||
auditLog = { record: jest.fn().mockResolvedValue(undefined) };
|
||||
events = { record: jest.fn().mockResolvedValue(undefined) };
|
||||
service = new ApiariesService(
|
||||
prisma as unknown as PrismaService,
|
||||
auditLog as unknown as AuditLogService,
|
||||
events as unknown as DomainEventsService,
|
||||
);
|
||||
});
|
||||
|
||||
// Whatever a test recorded, the herd payloads carry only ids.
|
||||
afterEach(() => {
|
||||
expectOnlyIdPayloads(events.record.mock.calls);
|
||||
});
|
||||
|
||||
it('findById throws NotFoundException when missing', async () => {
|
||||
prisma.apiary.findUnique.mockResolvedValue(null);
|
||||
await expect(service.findById('missing')).rejects.toBeInstanceOf(
|
||||
@@ -47,89 +81,152 @@ describe('ApiariesService', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('create persists the apiary and records an audit entry', async () => {
|
||||
prisma.apiary.create.mockResolvedValue(existingApiary);
|
||||
it('create writes record, audit and ApiaryChanged CREATED in one transaction', async () => {
|
||||
tx.apiary.create.mockResolvedValue(existingApiary);
|
||||
|
||||
const result = await service.create({ name: 'Heimstand' }, 'user-1');
|
||||
|
||||
expect(result).toEqual(existingApiary);
|
||||
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
|
||||
expect(auditLog.record).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
entityType: 'Apiary',
|
||||
action: 'CREATE',
|
||||
userId: 'user-1',
|
||||
}),
|
||||
tx,
|
||||
);
|
||||
expect(events.record).toHaveBeenCalledWith(tx, {
|
||||
type: 'ApiaryChanged',
|
||||
aggregateType: 'Apiary',
|
||||
aggregateId: 'apiary-1',
|
||||
actorUserId: 'user-1',
|
||||
payload: { change: 'CREATED' },
|
||||
});
|
||||
});
|
||||
|
||||
it('a failing audit write rolls back the apiary change', async () => {
|
||||
tx.apiary.create.mockResolvedValue(existingApiary);
|
||||
auditLog.record.mockRejectedValue(new Error('audit down'));
|
||||
|
||||
await expect(
|
||||
service.create({ name: 'Heimstand' }, 'user-1'),
|
||||
).rejects.toThrow('audit down');
|
||||
// Record, audit and event share one transaction callback: its rejection
|
||||
// is what rolls the record back.
|
||||
expect(events.record).not.toHaveBeenCalled();
|
||||
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('update reads before after locking the Apiary row', async () => {
|
||||
tx.apiary.update.mockResolvedValue(existingApiary);
|
||||
|
||||
await service.update('apiary-1', { notes: 'neu' }, 'user-1');
|
||||
|
||||
expect(order).toEqual(['lock', 'read']);
|
||||
expect(auditLog.record).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: 'UPDATE',
|
||||
beforeData: existingApiary,
|
||||
}),
|
||||
tx,
|
||||
);
|
||||
});
|
||||
|
||||
it('deactivate sets status to INACTIVE and records an audit entry', async () => {
|
||||
prisma.apiary.findUnique.mockResolvedValue(existingApiary);
|
||||
prisma.apiary.update.mockResolvedValue({
|
||||
it('update of a missing apiary answers 404', async () => {
|
||||
tx.apiary.findUnique.mockResolvedValue(null);
|
||||
await expect(
|
||||
service.update('missing', { notes: 'x' }, 'user-1'),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
expect(tx.apiary.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ address: 'Neuer Weg 2' }],
|
||||
[{ location: 'Wiese' }],
|
||||
[{ latitude: 50 }],
|
||||
[{ longitude: 12 }],
|
||||
])('update records LOCATION_CHANGED for %j', async (dto) => {
|
||||
tx.apiary.update.mockResolvedValue({ ...existingApiary, ...dto });
|
||||
|
||||
await service.update('apiary-1', dto, 'user-1');
|
||||
|
||||
expect(changes()).toEqual(['LOCATION_CHANGED']);
|
||||
});
|
||||
|
||||
it('update records LOCATION_CHANGED only when address, location, latitude or longitude changed', async () => {
|
||||
tx.apiary.update.mockResolvedValue({ ...existingApiary, notes: 'neu' });
|
||||
await service.update(
|
||||
'apiary-1',
|
||||
{ name: 'Anders', notes: 'neu' },
|
||||
'user-1',
|
||||
);
|
||||
// The same value sent again is no change either.
|
||||
tx.apiary.update.mockResolvedValue(existingApiary);
|
||||
await service.update('apiary-1', { address: 'Weg 1' }, 'user-1');
|
||||
|
||||
expect(events.record).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('deactivate counts living colonies inside the transaction and records DEACTIVATED', async () => {
|
||||
tx.apiary.update.mockResolvedValue({
|
||||
...existingApiary,
|
||||
status: 'INACTIVE',
|
||||
deactivatedAt: new Date(),
|
||||
});
|
||||
|
||||
const result = await service.deactivate('apiary-1', 'user-1');
|
||||
|
||||
expect(result.status).toBe('INACTIVE');
|
||||
expect(auditLog.record).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ entityType: 'Apiary', action: 'DEACTIVATE' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('deactivate counts every living colony, weak and queenless ones included', async () => {
|
||||
prisma.apiary.findUnique.mockResolvedValue(existingApiary);
|
||||
prisma.apiary.update.mockResolvedValue(existingApiary);
|
||||
|
||||
await service.deactivate('apiary-1', 'user-1');
|
||||
|
||||
expect(prisma.colony.count).toHaveBeenCalledWith({
|
||||
expect(order).toEqual(['lock', 'read']);
|
||||
expect(tx.colony.count).toHaveBeenCalledWith({
|
||||
where: {
|
||||
apiaryId: 'apiary-1',
|
||||
status: { notIn: ['DISSOLVED', 'SOLD', 'DECEASED', 'MERGED'] },
|
||||
},
|
||||
});
|
||||
expect(auditLog.record).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ entityType: 'Apiary', action: 'DEACTIVATE' }),
|
||||
tx,
|
||||
);
|
||||
expect(changes()).toEqual(['DEACTIVATED']);
|
||||
});
|
||||
|
||||
it('deactivate throws ConflictException when active colonies remain', async () => {
|
||||
prisma.apiary.findUnique.mockResolvedValue(existingApiary);
|
||||
prisma.colony.count.mockResolvedValue(2);
|
||||
tx.colony.count.mockResolvedValue(2);
|
||||
|
||||
await expect(
|
||||
service.deactivate('apiary-1', 'user-1'),
|
||||
).rejects.toBeInstanceOf(ConflictException);
|
||||
expect(prisma.apiary.update).not.toHaveBeenCalled();
|
||||
expect(tx.apiary.update).not.toHaveBeenCalled();
|
||||
expect(events.record).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reactivate throws ConflictException when already active', async () => {
|
||||
prisma.apiary.findUnique.mockResolvedValue(existingApiary);
|
||||
await expect(
|
||||
service.reactivate('apiary-1', 'user-1'),
|
||||
).rejects.toBeInstanceOf(ConflictException);
|
||||
expect(events.record).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reactivate sets status to ACTIVE and clears deactivatedAt', async () => {
|
||||
prisma.apiary.findUnique.mockResolvedValue({
|
||||
it('reactivate records REACTIVATED and clears deactivatedAt', async () => {
|
||||
tx.apiary.findUnique.mockResolvedValue({
|
||||
...existingApiary,
|
||||
status: 'INACTIVE',
|
||||
deactivatedAt: new Date(),
|
||||
});
|
||||
prisma.apiary.update.mockResolvedValue({
|
||||
...existingApiary,
|
||||
status: 'ACTIVE',
|
||||
deactivatedAt: null,
|
||||
});
|
||||
tx.apiary.update.mockResolvedValue(existingApiary);
|
||||
|
||||
const result = await service.reactivate('apiary-1', 'user-1');
|
||||
|
||||
expect(result.status).toBe('ACTIVE');
|
||||
expect(prisma.apiary.update).toHaveBeenCalledWith({
|
||||
expect(tx.apiary.update).toHaveBeenCalledWith({
|
||||
where: { id: 'apiary-1' },
|
||||
data: { status: 'ACTIVE', deactivatedAt: null },
|
||||
});
|
||||
expect(auditLog.record).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ entityType: 'Apiary', action: 'UPDATE' }),
|
||||
tx,
|
||||
);
|
||||
expect(changes()).toEqual(['REACTIVATED']);
|
||||
});
|
||||
});
|
||||
@@ -5,8 +5,11 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { AuditLogService } from '../audit/audit-log.service';
|
||||
import { DomainEventsService } from '../domain-events/domain-events.service';
|
||||
import type { DomainEventPayloads } from '../domain-events/domain-event-types';
|
||||
import { lockRowForUpdate } from '../prisma/row-lock';
|
||||
import { LIVING_COLONY_WHERE } from '../colonies/colony-status';
|
||||
import { Apiary, ApiaryStatus } from '../../generated/prisma';
|
||||
import { Apiary, ApiaryStatus, Prisma } from '../../generated/prisma';
|
||||
import { CreateApiaryDto } from './dto/create-apiary.dto';
|
||||
import { UpdateApiaryDto } from './dto/update-apiary.dto';
|
||||
|
||||
@@ -15,11 +18,22 @@ export interface ApiaryFilter {
|
||||
location?: string;
|
||||
}
|
||||
|
||||
type ApiaryChange = DomainEventPayloads['ApiaryChanged']['change'];
|
||||
|
||||
// The fields a change of which counts as a new location of the apiary.
|
||||
const LOCATION_FIELDS = [
|
||||
'address',
|
||||
'location',
|
||||
'latitude',
|
||||
'longitude',
|
||||
] as const;
|
||||
|
||||
@Injectable()
|
||||
export class ApiariesService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly auditLog: AuditLogService,
|
||||
private readonly events: DomainEventsService,
|
||||
) {}
|
||||
|
||||
async findAll(filter: ApiaryFilter = {}): Promise<Apiary[]> {
|
||||
@@ -43,15 +57,21 @@ export class ApiariesService {
|
||||
}
|
||||
|
||||
async create(dto: CreateApiaryDto, actingUserId: string): Promise<Apiary> {
|
||||
const apiary = await this.prisma.apiary.create({ data: { ...dto } });
|
||||
await this.auditLog.record({
|
||||
entityType: 'Apiary',
|
||||
entityId: apiary.id,
|
||||
action: 'CREATE',
|
||||
userId: actingUserId,
|
||||
afterData: apiary,
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const apiary = await tx.apiary.create({ data: { ...dto } });
|
||||
await this.auditLog.record(
|
||||
{
|
||||
entityType: 'Apiary',
|
||||
entityId: apiary.id,
|
||||
action: 'CREATE',
|
||||
userId: actingUserId,
|
||||
afterData: apiary,
|
||||
},
|
||||
tx,
|
||||
);
|
||||
await this.recordChange(tx, apiary.id, 'CREATED', actingUserId);
|
||||
return apiary;
|
||||
});
|
||||
return apiary;
|
||||
}
|
||||
|
||||
async update(
|
||||
@@ -59,69 +79,120 @@ export class ApiariesService {
|
||||
dto: UpdateApiaryDto,
|
||||
actingUserId: string,
|
||||
): Promise<Apiary> {
|
||||
const before = await this.findById(id);
|
||||
const apiary = await this.prisma.apiary.update({
|
||||
where: { id },
|
||||
data: { ...dto },
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const before = await this.lockApiary(tx, id);
|
||||
const apiary = await tx.apiary.update({
|
||||
where: { id },
|
||||
data: { ...dto },
|
||||
});
|
||||
await this.auditLog.record(
|
||||
{
|
||||
entityType: 'Apiary',
|
||||
entityId: id,
|
||||
action: 'UPDATE',
|
||||
userId: actingUserId,
|
||||
beforeData: before,
|
||||
afterData: apiary,
|
||||
},
|
||||
tx,
|
||||
);
|
||||
if (LOCATION_FIELDS.some((field) => before[field] !== apiary[field])) {
|
||||
await this.recordChange(tx, id, 'LOCATION_CHANGED', actingUserId);
|
||||
}
|
||||
return apiary;
|
||||
});
|
||||
await this.auditLog.record({
|
||||
entityType: 'Apiary',
|
||||
entityId: id,
|
||||
action: 'UPDATE',
|
||||
userId: actingUserId,
|
||||
beforeData: before,
|
||||
afterData: apiary,
|
||||
});
|
||||
return apiary;
|
||||
}
|
||||
|
||||
async deactivate(id: string, actingUserId: string): Promise<Apiary> {
|
||||
const before = await this.findById(id);
|
||||
// Colony.apiaryId is a plain FK, not enforced against apiary status -
|
||||
// without this guard a colony can silently keep pointing at an
|
||||
// inactive apiary (still shows ACTIVE, still countable, but its
|
||||
// "location" has vanished from the active apiary list). Move the
|
||||
// colonies elsewhere or dissolve them first instead.
|
||||
const activeColonyCount = await this.prisma.colony.count({
|
||||
where: { apiaryId: id, ...LIVING_COLONY_WHERE },
|
||||
});
|
||||
if (activeColonyCount > 0) {
|
||||
throw new ConflictException(
|
||||
`Der Bienenstand hat noch ${activeColonyCount} aktive(s) Volk/Völker - zuerst verlegen oder auflösen`,
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const before = await this.lockApiary(tx, id);
|
||||
// Colony.apiaryId is a plain FK, not enforced against apiary status -
|
||||
// without this guard a colony can silently keep pointing at an
|
||||
// inactive apiary (still shows ACTIVE, still countable, but its
|
||||
// "location" has vanished from the active apiary list). Move the
|
||||
// colonies elsewhere or dissolve them first instead. Counted under the
|
||||
// apiary lock: the colony paths hold the apiary FOR SHARE, so a move
|
||||
// into it that is still running finishes first.
|
||||
const activeColonyCount = await tx.colony.count({
|
||||
where: { apiaryId: id, ...LIVING_COLONY_WHERE },
|
||||
});
|
||||
if (activeColonyCount > 0) {
|
||||
throw new ConflictException(
|
||||
`Der Bienenstand hat noch ${activeColonyCount} aktive(s) Volk/Völker - zuerst verlegen oder auflösen`,
|
||||
);
|
||||
}
|
||||
const apiary = await tx.apiary.update({
|
||||
where: { id },
|
||||
data: { status: 'INACTIVE', deactivatedAt: new Date() },
|
||||
});
|
||||
await this.auditLog.record(
|
||||
{
|
||||
entityType: 'Apiary',
|
||||
entityId: id,
|
||||
action: 'DEACTIVATE',
|
||||
userId: actingUserId,
|
||||
beforeData: before,
|
||||
afterData: apiary,
|
||||
},
|
||||
tx,
|
||||
);
|
||||
}
|
||||
const apiary = await this.prisma.apiary.update({
|
||||
where: { id },
|
||||
data: { status: 'INACTIVE', deactivatedAt: new Date() },
|
||||
await this.recordChange(tx, id, 'DEACTIVATED', actingUserId);
|
||||
return apiary;
|
||||
});
|
||||
await this.auditLog.record({
|
||||
entityType: 'Apiary',
|
||||
entityId: id,
|
||||
action: 'DEACTIVATE',
|
||||
userId: actingUserId,
|
||||
beforeData: before,
|
||||
afterData: apiary,
|
||||
});
|
||||
return apiary;
|
||||
}
|
||||
|
||||
async reactivate(id: string, actingUserId: string): Promise<Apiary> {
|
||||
const before = await this.findById(id);
|
||||
if (before.status === 'ACTIVE') {
|
||||
throw new ConflictException('Apiary is already active');
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const before = await this.lockApiary(tx, id);
|
||||
if (before.status === 'ACTIVE') {
|
||||
throw new ConflictException('Apiary is already active');
|
||||
}
|
||||
const apiary = await tx.apiary.update({
|
||||
where: { id },
|
||||
data: { status: 'ACTIVE', deactivatedAt: null },
|
||||
});
|
||||
await this.auditLog.record(
|
||||
{
|
||||
entityType: 'Apiary',
|
||||
entityId: id,
|
||||
action: 'UPDATE',
|
||||
userId: actingUserId,
|
||||
beforeData: before,
|
||||
afterData: apiary,
|
||||
},
|
||||
tx,
|
||||
);
|
||||
await this.recordChange(tx, id, 'REACTIVATED', actingUserId);
|
||||
return apiary;
|
||||
});
|
||||
}
|
||||
|
||||
// Locks the apiary row and reads it afterwards: the result - not an earlier
|
||||
// read - is "before" for the comparison, the audit and the event.
|
||||
private async lockApiary(
|
||||
tx: Prisma.TransactionClient,
|
||||
id: string,
|
||||
): Promise<Apiary> {
|
||||
await lockRowForUpdate(tx, 'Apiary', id);
|
||||
const apiary = await tx.apiary.findUnique({ where: { id } });
|
||||
if (!apiary) {
|
||||
throw new NotFoundException('Apiary not found');
|
||||
}
|
||||
const apiary = await this.prisma.apiary.update({
|
||||
where: { id },
|
||||
data: { status: 'ACTIVE', deactivatedAt: null },
|
||||
});
|
||||
await this.auditLog.record({
|
||||
entityType: 'Apiary',
|
||||
entityId: id,
|
||||
action: 'UPDATE',
|
||||
userId: actingUserId,
|
||||
beforeData: before,
|
||||
afterData: apiary,
|
||||
});
|
||||
return apiary;
|
||||
}
|
||||
|
||||
private recordChange(
|
||||
tx: Prisma.TransactionClient,
|
||||
apiaryId: string,
|
||||
change: ApiaryChange,
|
||||
actorUserId: string,
|
||||
): Promise<void> {
|
||||
return this.events.record(tx, {
|
||||
type: 'ApiaryChanged',
|
||||
aggregateType: 'Apiary',
|
||||
aggregateId: apiaryId,
|
||||
actorUserId,
|
||||
payload: { change },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import { PrismaService } from '../prisma/prisma.service';
|
||||
import { PermissionResolverService } from '../auth/permissions/permission-resolver.service';
|
||||
import type { ColonyNextSteps } from '../autopilot/next-step-ranking';
|
||||
import { NextStepsService } from '../autopilot/next-steps.service';
|
||||
import { HiveService } from '../hive/hive.service';
|
||||
import { HiveCatalogService } from '../hive/hive-catalog.service';
|
||||
|
||||
describe('ApiaryFieldService', () => {
|
||||
let service: ApiaryFieldService;
|
||||
@@ -17,6 +19,8 @@ describe('ApiaryFieldService', () => {
|
||||
};
|
||||
let permissionResolver: { getPermissions: jest.Mock };
|
||||
let nextSteps: { forColonies: jest.Mock; warningCounts: jest.Mock };
|
||||
let hives: { getMany: jest.Mock };
|
||||
let hiveCatalogs: { listSystems: jest.Mock };
|
||||
|
||||
const stepsOf = (
|
||||
colonyId: string,
|
||||
@@ -87,10 +91,14 @@ describe('ApiaryFieldService', () => {
|
||||
),
|
||||
warningCounts: jest.fn().mockResolvedValue(new Map()),
|
||||
};
|
||||
hives = { getMany: jest.fn().mockResolvedValue({}) };
|
||||
hiveCatalogs = { listSystems: jest.fn().mockResolvedValue([]) };
|
||||
service = new ApiaryFieldService(
|
||||
prisma as unknown as PrismaService,
|
||||
permissionResolver as unknown as PermissionResolverService,
|
||||
nextSteps as unknown as NextStepsService,
|
||||
hives as unknown as HiveService,
|
||||
hiveCatalogs as unknown as HiveCatalogService,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -129,6 +137,40 @@ describe('ApiaryFieldService', () => {
|
||||
expect(prisma.task.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('carries the hives of the apiary colonies and the hive catalog', async () => {
|
||||
grant('colonies:read');
|
||||
const view = { colonyId: 'c2', systemId: 's1', version: 3 };
|
||||
hives.getMany.mockResolvedValue({ c2: view });
|
||||
const systems = [{ id: 's1', name: 'Zander', active: true, partTypes: [] }];
|
||||
hiveCatalogs.listSystems.mockResolvedValue(systems);
|
||||
|
||||
const pack = await service.offlinePack('apiary-1', 'u1');
|
||||
|
||||
expect(hives.getMany).toHaveBeenCalledWith(['c2', 'c10']);
|
||||
expect(pack.hives).toEqual({ c2: view });
|
||||
expect(pack.hiveCatalog).toEqual(systems);
|
||||
});
|
||||
|
||||
it('limits the hive catalog to active systems and those the hives use', async () => {
|
||||
grant('colonies:read');
|
||||
hives.getMany.mockResolvedValue({ c2: { colonyId: 'c2', systemId: 's2' } });
|
||||
hiveCatalogs.listSystems.mockResolvedValue([
|
||||
{ id: 's1', active: true },
|
||||
{ id: 's2', active: false },
|
||||
{ id: 's3', active: false },
|
||||
]);
|
||||
|
||||
const pack = await service.offlinePack('apiary-1', 'u1');
|
||||
|
||||
expect(pack.hiveCatalog?.map((system) => system.id)).toEqual(['s1', 's2']);
|
||||
});
|
||||
|
||||
it('keeps colonies without a hive setup out of the hives', async () => {
|
||||
grant('colonies:read');
|
||||
const pack = await service.offlinePack('apiary-1', 'u1');
|
||||
expect(pack.hives).toEqual({});
|
||||
});
|
||||
|
||||
it('fills the permitted sections and the last inspection date', async () => {
|
||||
grant('colonies:read', 'inspections:read', 'queens:read', 'tasks:read');
|
||||
const date = new Date('2026-05-01T10:00:00.000Z');
|
||||
|
||||
@@ -2,6 +2,8 @@ import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { PermissionResolverService } from '../auth/permissions/permission-resolver.service';
|
||||
import type { ColonyNextSteps } from '../autopilot/next-step-ranking';
|
||||
import { NextStepsService } from '../autopilot/next-steps.service';
|
||||
import { HiveCatalogService } from '../hive/hive-catalog.service';
|
||||
import { HiveService } from '../hive/hive.service';
|
||||
import { LIVING_COLONY_WHERE } from '../colonies/colony-status';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type {
|
||||
@@ -12,6 +14,15 @@ import type {
|
||||
|
||||
const INSPECTIONS_PER_COLONY = 3;
|
||||
|
||||
/** Active systems plus the ones the pack's hives use (a hidden system still builds an old hive). */
|
||||
function activeOrUsed<S extends { id: string; active: boolean }>(
|
||||
systems: S[],
|
||||
hives: Record<string, { systemId: string }>,
|
||||
): S[] {
|
||||
const used = new Set(Object.values(hives).map((hive) => hive.systemId));
|
||||
return systems.filter((system) => system.active || used.has(system.id));
|
||||
}
|
||||
|
||||
type PackColony = OfflinePackV1['colonies'][number];
|
||||
|
||||
interface FieldData {
|
||||
@@ -33,6 +44,8 @@ export class ApiaryFieldService {
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly permissionResolver: PermissionResolverService,
|
||||
private readonly nextSteps: NextStepsService,
|
||||
private readonly hives: HiveService,
|
||||
private readonly hiveCatalogs: HiveCatalogService,
|
||||
) {}
|
||||
|
||||
async colonyOverview(
|
||||
@@ -45,12 +58,14 @@ export class ApiaryFieldService {
|
||||
async offlinePack(apiaryId: string, userId: string): Promise<OfflinePackV1> {
|
||||
const { apiary, colonies, permissions, overview, nextSteps } =
|
||||
await this.load(apiaryId, userId);
|
||||
const [queens, inspections, tasks] = await Promise.all([
|
||||
const [queens, inspections, tasks, hives, hiveCatalog] = await Promise.all([
|
||||
permissions.has('queens:read') ? this.loadQueens(colonies) : null,
|
||||
permissions.has('inspections:read')
|
||||
? this.loadInspections(colonies)
|
||||
: null,
|
||||
permissions.has('tasks:read') ? this.loadTasks(apiaryId, colonies) : null,
|
||||
this.hives.getMany(colonies.map((colony) => colony.id)),
|
||||
this.hiveCatalogs.listSystems(),
|
||||
]);
|
||||
return {
|
||||
version: 1,
|
||||
@@ -61,6 +76,8 @@ export class ApiaryFieldService {
|
||||
queens,
|
||||
inspections,
|
||||
tasks,
|
||||
hives,
|
||||
hiveCatalog: activeOrUsed(hiveCatalog, hives),
|
||||
nextSteps: Object.fromEntries(
|
||||
colonies.map((colony) => [
|
||||
colony.id,
|
||||
|
||||
@@ -7,6 +7,8 @@ import type {
|
||||
Queen,
|
||||
Task,
|
||||
} from '../../generated/prisma';
|
||||
import type { HiveSystemDto } from '../hive/hive-catalog.service';
|
||||
import type { HiveSetupView } from '../hive/hive.service';
|
||||
import type { NextStep } from '../autopilot/next-step-ranking';
|
||||
import type { SeasonSegmentKey } from '../season/season-types';
|
||||
|
||||
@@ -106,4 +108,11 @@ export interface OfflinePackV1 {
|
||||
* returns as `steps`). Absent in packs cached before T4.
|
||||
*/
|
||||
nextSteps?: Record<string, NextStep[]>;
|
||||
/**
|
||||
* The hive setup per colony id, only for colonies of this apiary that have
|
||||
* one. Absent in packs cached before the hive card.
|
||||
*/
|
||||
hives?: Record<string, HiveSetupView>;
|
||||
/** The hive systems with their part types. Absent in older packs. */
|
||||
hiveCatalog?: HiveSystemDto[];
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import {
|
||||
describeNullContracts,
|
||||
NullContract,
|
||||
} from '../common/validation/null-contract.spec-helper';
|
||||
import { UpdateColonyDto } from '../colonies/dto/update-colony.dto';
|
||||
import { UpdateApiaryRestrictionDto } from './dto/update-apiary-restriction.dto';
|
||||
|
||||
const contracts: Record<string, NullContract> = {
|
||||
UpdateApiaryRestrictionDto: {
|
||||
dto: UpdateApiaryRestrictionDto,
|
||||
notNull: ['disease', 'startsOn'],
|
||||
clearable: ['endsOn', 'authority', 'reference', 'notes'],
|
||||
},
|
||||
// The reason is only read, never stored: null means "no override".
|
||||
UpdateColonyDto: {
|
||||
dto: UpdateColonyDto,
|
||||
notNull: ['status'],
|
||||
clearable: ['restrictionOverrideReason'],
|
||||
},
|
||||
};
|
||||
|
||||
describeNullContracts('Apiary restriction DTOs', contracts);
|
||||
@@ -0,0 +1,82 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
import { RequirePermission } from '../auth/decorators/require-permission.decorator';
|
||||
import type { AuthenticatedUser } from '../auth/types/authenticated-user';
|
||||
import { PermissionResolverService } from '../auth/permissions/permission-resolver.service';
|
||||
import { Idempotent } from '../common/idempotency/idempotent.decorator';
|
||||
import { ApiaryRestrictionsService } from './apiary-restrictions.service';
|
||||
import { CreateApiaryRestrictionDto } from './dto/create-apiary-restriction.dto';
|
||||
import { RestrictionListQuery } from './dto/restriction-list-query.dto';
|
||||
import { UpdateApiaryRestrictionDto } from './dto/update-apiary-restriction.dto';
|
||||
|
||||
// Full paths on an empty prefix: the list lives under /apiary-restrictions,
|
||||
// the per-apiary read under /apiaries/:id/restrictions.
|
||||
@ApiTags('apiary-restrictions')
|
||||
@ApiBearerAuth()
|
||||
@Controller()
|
||||
export class ApiaryRestrictionsController {
|
||||
constructor(
|
||||
private readonly restrictions: ApiaryRestrictionsService,
|
||||
private readonly permissions: PermissionResolverService,
|
||||
) {}
|
||||
|
||||
// Authority, file reference and notes are for compliance:read only.
|
||||
private async mayReadDetails(actor: AuthenticatedUser): Promise<boolean> {
|
||||
return (await this.permissions.getPermissions(actor.id)).has(
|
||||
'compliance:read',
|
||||
);
|
||||
}
|
||||
|
||||
@RequirePermission('apiaries:read')
|
||||
@Get('apiary-restrictions')
|
||||
async findAll(
|
||||
@Query() query: RestrictionListQuery,
|
||||
@CurrentUser() actor: AuthenticatedUser,
|
||||
) {
|
||||
return this.restrictions.list(
|
||||
query.active,
|
||||
await this.mayReadDetails(actor),
|
||||
);
|
||||
}
|
||||
|
||||
@RequirePermission('apiaries:read')
|
||||
@Get('apiaries/:id/restrictions')
|
||||
async findForApiary(
|
||||
@Param('id') id: string,
|
||||
@CurrentUser() actor: AuthenticatedUser,
|
||||
) {
|
||||
return this.restrictions.findForApiary(
|
||||
id,
|
||||
await this.mayReadDetails(actor),
|
||||
);
|
||||
}
|
||||
|
||||
@RequirePermission('compliance:manage')
|
||||
@Idempotent()
|
||||
@Post('apiary-restrictions')
|
||||
create(
|
||||
@Body() dto: CreateApiaryRestrictionDto,
|
||||
@CurrentUser() actor: AuthenticatedUser,
|
||||
) {
|
||||
return this.restrictions.create(dto, actor.id);
|
||||
}
|
||||
|
||||
@RequirePermission('compliance:manage')
|
||||
@Patch('apiary-restrictions/:id')
|
||||
update(
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateApiaryRestrictionDto,
|
||||
@CurrentUser() actor: AuthenticatedUser,
|
||||
) {
|
||||
return this.restrictions.update(id, dto, actor.id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ApiaryRestrictionsController } from './apiary-restrictions.controller';
|
||||
import { ApiaryRestrictionsService } from './apiary-restrictions.service';
|
||||
|
||||
/**
|
||||
* Not needed in WorkerModule: the service injects no permission resolver and
|
||||
* the guard helper (compliance/restricted-zone.ts) is a plain function.
|
||||
*/
|
||||
@Module({
|
||||
controllers: [ApiaryRestrictionsController],
|
||||
providers: [ApiaryRestrictionsService],
|
||||
exports: [ApiaryRestrictionsService],
|
||||
})
|
||||
export class ApiaryRestrictionsModule {}
|
||||
@@ -0,0 +1,295 @@
|
||||
import { Prisma } from '../../generated/prisma';
|
||||
import { AuditLogService } from '../audit/audit-log.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { ApiaryRestrictionsService } from './apiary-restrictions.service';
|
||||
|
||||
const day = (value: string): Date => new Date(`${value}T00:00:00.000Z`);
|
||||
|
||||
describe('ApiaryRestrictionsService', () => {
|
||||
let service: ApiaryRestrictionsService;
|
||||
let tx: {
|
||||
$queryRaw: jest.Mock;
|
||||
apiary: { findMany: jest.Mock };
|
||||
apiaryRestriction: {
|
||||
create: jest.Mock;
|
||||
update: jest.Mock;
|
||||
findUnique: jest.Mock;
|
||||
};
|
||||
};
|
||||
let prisma: {
|
||||
apiary: { findUnique: jest.Mock };
|
||||
apiaryRestriction: { findMany: jest.Mock; findUnique: jest.Mock };
|
||||
$transaction: jest.Mock;
|
||||
};
|
||||
let auditLog: { record: jest.Mock };
|
||||
|
||||
beforeEach(() => {
|
||||
tx = {
|
||||
$queryRaw: jest.fn().mockResolvedValue([]),
|
||||
apiary: { findMany: jest.fn() },
|
||||
apiaryRestriction: {
|
||||
create: jest.fn(),
|
||||
update: jest.fn(),
|
||||
findUnique: jest.fn(),
|
||||
},
|
||||
};
|
||||
prisma = {
|
||||
apiary: { findUnique: jest.fn() },
|
||||
apiaryRestriction: { findMany: jest.fn(), findUnique: jest.fn() },
|
||||
$transaction: jest.fn((callback: (txArg: typeof tx) => unknown) =>
|
||||
callback(tx),
|
||||
),
|
||||
};
|
||||
auditLog = { record: jest.fn().mockResolvedValue(undefined) };
|
||||
service = new ApiaryRestrictionsService(
|
||||
prisma as unknown as PrismaService,
|
||||
auditLog as unknown as AuditLogService,
|
||||
);
|
||||
});
|
||||
|
||||
function lockStatements(): string[] {
|
||||
return (tx.$queryRaw.mock.calls as [Prisma.Sql][]).map(
|
||||
([query]) => query.sql,
|
||||
);
|
||||
}
|
||||
|
||||
describe('create', () => {
|
||||
const dto = {
|
||||
apiaryIds: ['a2', 'a1'],
|
||||
disease: 'Faulbrut',
|
||||
startsOn: '2026-10-01',
|
||||
};
|
||||
|
||||
it('creates one row per apiary in one transaction, audits each, locks the apiaries first', async () => {
|
||||
tx.apiary.findMany.mockResolvedValue([{ id: 'a1' }, { id: 'a2' }]);
|
||||
tx.apiaryRestriction.create.mockImplementation(
|
||||
({ data }: { data: { apiaryId: string } }) =>
|
||||
Promise.resolve({ id: `r-${data.apiaryId}`, ...data }),
|
||||
);
|
||||
|
||||
const created = await service.create(dto, 'user-1');
|
||||
|
||||
expect(created.map((row) => row.apiaryId)).toEqual(['a1', 'a2']);
|
||||
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
|
||||
expect(lockStatements()).toEqual([
|
||||
'SELECT id FROM "Apiary" WHERE id = ANY(?) ORDER BY id FOR UPDATE',
|
||||
]);
|
||||
const [[firstRow]] = tx.apiaryRestriction.create.mock.calls as [
|
||||
[{ data: Record<string, unknown> }],
|
||||
];
|
||||
expect(firstRow.data).toMatchObject({
|
||||
apiaryId: 'a1',
|
||||
disease: 'Faulbrut',
|
||||
startsOn: day('2026-10-01'),
|
||||
createdByUserId: 'user-1',
|
||||
});
|
||||
expect(auditLog.record).toHaveBeenCalledTimes(2);
|
||||
expect(auditLog.record).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
entityType: 'ApiaryRestriction',
|
||||
action: 'CREATE',
|
||||
userId: 'user-1',
|
||||
}),
|
||||
tx,
|
||||
);
|
||||
expect(tx.$queryRaw.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
tx.apiaryRestriction.create.mock.invocationCallOrder[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('rolls all back when one apiary is unknown (404 after the lock, nothing written)', async () => {
|
||||
tx.apiary.findMany.mockResolvedValue([{ id: 'a1' }]);
|
||||
|
||||
await expect(service.create(dto, 'user-1')).rejects.toMatchObject({
|
||||
status: 404,
|
||||
});
|
||||
expect(tx.$queryRaw).toHaveBeenCalledTimes(1);
|
||||
expect(tx.apiaryRestriction.create).not.toHaveBeenCalled();
|
||||
expect(auditLog.record).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects an endsOn before startsOn with 400 before any lock', async () => {
|
||||
await expect(
|
||||
service.create({ ...dto, endsOn: '2026-09-30' }, 'user-1'),
|
||||
).rejects.toMatchObject({ status: 400 });
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects no apiary and more than 50 apiaries with 400', async () => {
|
||||
const ids = Array.from({ length: 51 }, (_, index) => `a${index}`);
|
||||
|
||||
await expect(
|
||||
service.create({ ...dto, apiaryIds: ids }, 'user-1'),
|
||||
).rejects.toMatchObject({ status: 400 });
|
||||
await expect(
|
||||
service.create({ ...dto, apiaryIds: [] }, 'user-1'),
|
||||
).rejects.toMatchObject({ status: 400 });
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
const stored = {
|
||||
id: 'r1',
|
||||
apiaryId: 'a1',
|
||||
disease: 'Faulbrut',
|
||||
startsOn: day('2026-10-01'),
|
||||
endsOn: null as Date | null,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
prisma.apiaryRestriction.findUnique.mockResolvedValue(stored);
|
||||
tx.apiaryRestriction.findUnique.mockResolvedValue(stored);
|
||||
tx.apiaryRestriction.update.mockImplementation(
|
||||
({ data }: { data: object }) => Promise.resolve({ ...stored, ...data }),
|
||||
);
|
||||
});
|
||||
|
||||
it('locks the apiary FOR UPDATE, then the restriction, then reads before', async () => {
|
||||
await service.update('r1', { endsOn: '2026-10-20' }, 'user-1');
|
||||
|
||||
expect(lockStatements()).toEqual([
|
||||
'SELECT id FROM "Apiary" WHERE id = ANY(?) ORDER BY id FOR UPDATE',
|
||||
'SELECT id FROM "ApiaryRestriction" WHERE id = ? FOR UPDATE',
|
||||
]);
|
||||
expect(tx.$queryRaw.mock.invocationCallOrder[1]).toBeLessThan(
|
||||
tx.apiaryRestriction.findUnique.mock.invocationCallOrder[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('ending a restriction is an update of endsOn, nothing is deleted', async () => {
|
||||
const result = await service.update(
|
||||
'r1',
|
||||
{ endsOn: '2026-10-20' },
|
||||
'user-1',
|
||||
);
|
||||
|
||||
expect(tx.apiaryRestriction.update).toHaveBeenCalledWith({
|
||||
where: { id: 'r1' },
|
||||
data: { endsOn: day('2026-10-20') },
|
||||
});
|
||||
expect(result.endsOn).toEqual(day('2026-10-20'));
|
||||
expect(auditLog.record).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
entityType: 'ApiaryRestriction',
|
||||
entityId: 'r1',
|
||||
action: 'UPDATE',
|
||||
beforeData: stored,
|
||||
}),
|
||||
tx,
|
||||
);
|
||||
});
|
||||
|
||||
it('null clears endsOn', async () => {
|
||||
tx.apiaryRestriction.findUnique.mockResolvedValue({
|
||||
...stored,
|
||||
endsOn: day('2026-10-20'),
|
||||
});
|
||||
|
||||
await service.update('r1', { endsOn: null }, 'user-1');
|
||||
|
||||
expect(tx.apiaryRestriction.update).toHaveBeenCalledWith({
|
||||
where: { id: 'r1' },
|
||||
data: { endsOn: null },
|
||||
});
|
||||
});
|
||||
|
||||
it('checks endsOn >= startsOn on the merged state (400)', async () => {
|
||||
await expect(
|
||||
service.update('r1', { endsOn: '2026-09-30' }, 'user-1'),
|
||||
).rejects.toMatchObject({ status: 400 });
|
||||
await expect(
|
||||
service.update('r1', { startsOn: '2026-11-01' }, 'user-1'),
|
||||
).resolves.toBeDefined();
|
||||
tx.apiaryRestriction.findUnique.mockResolvedValue({
|
||||
...stored,
|
||||
endsOn: day('2026-10-20'),
|
||||
});
|
||||
await expect(
|
||||
service.update('r1', { startsOn: '2026-11-01' }, 'user-1'),
|
||||
).rejects.toMatchObject({ status: 400 });
|
||||
expect(tx.apiaryRestriction.update).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('answers 404 for an unknown restriction without locking', async () => {
|
||||
prisma.apiaryRestriction.findUnique.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
service.update('missing', { notes: 'x' }, 'user-1'),
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
expect(tx.$queryRaw).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('reads', () => {
|
||||
it('findActive lists only restrictions active today, with the apiary name', async () => {
|
||||
prisma.apiaryRestriction.findMany.mockResolvedValue([
|
||||
{
|
||||
id: 'r1',
|
||||
apiaryId: 'a1',
|
||||
apiary: { name: 'Nord' },
|
||||
disease: 'Faulbrut',
|
||||
startsOn: day('2000-01-01'),
|
||||
endsOn: null,
|
||||
},
|
||||
{
|
||||
id: 'r2',
|
||||
apiaryId: 'a2',
|
||||
apiary: { name: 'Sued' },
|
||||
disease: 'Faulbrut',
|
||||
startsOn: day('2000-01-01'),
|
||||
endsOn: day('2000-01-02'),
|
||||
},
|
||||
]);
|
||||
|
||||
await expect(service.findActive()).resolves.toEqual([
|
||||
{
|
||||
id: 'r1',
|
||||
apiaryId: 'a1',
|
||||
apiaryName: 'Nord',
|
||||
disease: 'Faulbrut',
|
||||
startsOn: '2000-01-01',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('without compliance:read the lists carry no authority, reference, notes or creator', async () => {
|
||||
const row = {
|
||||
id: 'r1',
|
||||
apiaryId: 'a1',
|
||||
disease: 'Faulbrut',
|
||||
authority: 'Veterinaeramt',
|
||||
reference: 'AZ 12/3',
|
||||
notes: 'intern',
|
||||
createdByUserId: 'u1',
|
||||
startsOn: day('2026-10-01'),
|
||||
endsOn: null,
|
||||
};
|
||||
prisma.apiaryRestriction.findMany.mockResolvedValue([row]);
|
||||
prisma.apiary.findUnique.mockResolvedValue({ id: 'a1' });
|
||||
const expected = [
|
||||
{
|
||||
id: 'r1',
|
||||
apiaryId: 'a1',
|
||||
disease: 'Faulbrut',
|
||||
startsOn: '2026-10-01',
|
||||
endsOn: null,
|
||||
},
|
||||
];
|
||||
|
||||
await expect(service.list(undefined, false)).resolves.toEqual(expected);
|
||||
await expect(service.findForApiary('a1', false)).resolves.toEqual(
|
||||
expected,
|
||||
);
|
||||
await expect(service.list(undefined, true)).resolves.toEqual([row]);
|
||||
});
|
||||
|
||||
it('findForApiary answers 404 for an unknown apiary', async () => {
|
||||
prisma.apiary.findUnique.mockResolvedValue(null);
|
||||
|
||||
await expect(service.findForApiary('missing')).rejects.toMatchObject({
|
||||
status: 404,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,224 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { ApiaryRestriction } from '../../generated/prisma';
|
||||
import { AuditLogService } from '../audit/audit-log.service';
|
||||
import { berlinToday, dayToDate } from '../common/dates';
|
||||
import { optionalDate } from '../common/patch-values';
|
||||
import {
|
||||
ActiveRestrictionInfo,
|
||||
isRestrictionActive,
|
||||
startedRestrictions,
|
||||
toActiveRestrictionInfo,
|
||||
} from '../compliance/restricted-zone';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { lockRowForUpdate, lockRowsForUpdate } from '../prisma/row-lock';
|
||||
import {
|
||||
CreateApiaryRestrictionDto,
|
||||
MAX_RESTRICTION_APIARIES,
|
||||
} from './dto/create-apiary-restriction.dto';
|
||||
import { UpdateApiaryRestrictionDto } from './dto/update-apiary-restriction.dto';
|
||||
|
||||
const AUDIT_ENTITY = 'ApiaryRestriction';
|
||||
|
||||
/** What a reader without compliance:read sees: no authority, reference, notes or creator. */
|
||||
export interface RestrictionSummary {
|
||||
id: string;
|
||||
apiaryId: string;
|
||||
disease: string;
|
||||
startsOn: string;
|
||||
endsOn: string | null;
|
||||
}
|
||||
|
||||
function toSummary(row: ApiaryRestriction): RestrictionSummary {
|
||||
return {
|
||||
id: row.id,
|
||||
apiaryId: row.apiaryId,
|
||||
disease: row.disease,
|
||||
startsOn: row.startsOn.toISOString().slice(0, 10),
|
||||
endsOn: row.endsOn ? row.endsOn.toISOString().slice(0, 10) : null,
|
||||
};
|
||||
}
|
||||
|
||||
function assertEndNotBeforeStart(startsOn: Date, endsOn: Date | null): void {
|
||||
if (endsOn !== null && endsOn < startsOn) {
|
||||
throw new BadRequestException(
|
||||
'Das Ende der Sperre darf nicht vor ihrem Beginn liegen',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Restricted zones (Sperrbezirke) of apiaries. A restriction is never deleted:
|
||||
* it ends by an endsOn date, so the colony history stays explainable.
|
||||
*
|
||||
* Lock order (Task 1): the apiary rows FOR UPDATE first, then the restriction
|
||||
* row. A colony path holds its apiaries FOR SHARE until it commits, so a
|
||||
* restriction and a move into that apiary queue up behind each other.
|
||||
*/
|
||||
@Injectable()
|
||||
export class ApiaryRestrictionsService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly auditLog: AuditLogService,
|
||||
) {}
|
||||
|
||||
/** One row per apiary, all in one transaction; an unknown apiary rolls all back. */
|
||||
async create(
|
||||
dto: CreateApiaryRestrictionDto,
|
||||
actingUserId: string,
|
||||
): Promise<ApiaryRestriction[]> {
|
||||
const apiaryIds = [...new Set(dto.apiaryIds)].sort();
|
||||
if (apiaryIds.length < 1 || apiaryIds.length > MAX_RESTRICTION_APIARIES) {
|
||||
throw new BadRequestException(
|
||||
`Es sind 1 bis ${MAX_RESTRICTION_APIARIES} Stände möglich`,
|
||||
);
|
||||
}
|
||||
const startsOn = dayToDate(dto.startsOn);
|
||||
const endsOn = dto.endsOn ? dayToDate(dto.endsOn) : null;
|
||||
assertEndNotBeforeStart(startsOn, endsOn);
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
await lockRowsForUpdate(tx, 'Apiary', apiaryIds);
|
||||
const known = await tx.apiary.findMany({
|
||||
where: { id: { in: apiaryIds } },
|
||||
select: { id: true },
|
||||
});
|
||||
if (known.length !== apiaryIds.length) {
|
||||
throw new NotFoundException('Bienenstand nicht gefunden');
|
||||
}
|
||||
const created: ApiaryRestriction[] = [];
|
||||
for (const apiaryId of apiaryIds) {
|
||||
const restriction = await tx.apiaryRestriction.create({
|
||||
data: {
|
||||
apiaryId,
|
||||
disease: dto.disease,
|
||||
authority: dto.authority,
|
||||
reference: dto.reference,
|
||||
startsOn,
|
||||
endsOn,
|
||||
notes: dto.notes,
|
||||
createdByUserId: actingUserId,
|
||||
},
|
||||
});
|
||||
await this.auditLog.record(
|
||||
{
|
||||
entityType: AUDIT_ENTITY,
|
||||
entityId: restriction.id,
|
||||
action: 'CREATE',
|
||||
userId: actingUserId,
|
||||
afterData: restriction,
|
||||
},
|
||||
tx,
|
||||
);
|
||||
created.push(restriction);
|
||||
}
|
||||
return created;
|
||||
});
|
||||
}
|
||||
|
||||
async update(
|
||||
id: string,
|
||||
dto: UpdateApiaryRestrictionDto,
|
||||
actingUserId: string,
|
||||
): Promise<ApiaryRestriction> {
|
||||
const seen = await this.prisma.apiaryRestriction.findUnique({
|
||||
where: { id },
|
||||
select: { apiaryId: true },
|
||||
});
|
||||
if (!seen) {
|
||||
throw new NotFoundException('Sperrbezirk nicht gefunden');
|
||||
}
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
await lockRowsForUpdate(tx, 'Apiary', [seen.apiaryId]);
|
||||
await lockRowForUpdate(tx, 'ApiaryRestriction', id);
|
||||
const before = await tx.apiaryRestriction.findUnique({ where: { id } });
|
||||
if (!before) {
|
||||
throw new NotFoundException('Sperrbezirk nicht gefunden');
|
||||
}
|
||||
const startsOnPatch =
|
||||
dto.startsOn === undefined ? undefined : dayToDate(dto.startsOn);
|
||||
const startsOn = startsOnPatch ?? before.startsOn;
|
||||
const endsOn = optionalDate(dto.endsOn);
|
||||
assertEndNotBeforeStart(
|
||||
startsOn,
|
||||
endsOn === undefined ? before.endsOn : endsOn,
|
||||
);
|
||||
const updated = await tx.apiaryRestriction.update({
|
||||
where: { id },
|
||||
data: {
|
||||
disease: dto.disease,
|
||||
authority: dto.authority,
|
||||
reference: dto.reference,
|
||||
startsOn: startsOnPatch,
|
||||
endsOn,
|
||||
notes: dto.notes,
|
||||
},
|
||||
});
|
||||
await this.auditLog.record(
|
||||
{
|
||||
entityType: AUDIT_ENTITY,
|
||||
entityId: id,
|
||||
action: 'UPDATE',
|
||||
userId: actingUserId,
|
||||
beforeData: before,
|
||||
afterData: updated,
|
||||
},
|
||||
tx,
|
||||
);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
/** The restrictions in force today (Berlin day), with the apiary name. */
|
||||
async findActive(): Promise<ActiveRestrictionInfo[]> {
|
||||
const today = berlinToday();
|
||||
const started = await startedRestrictions(this.prisma, undefined, today);
|
||||
return started
|
||||
.filter((row) => isRestrictionActive(row, today))
|
||||
.map(toActiveRestrictionInfo);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every restriction (newest first); `active` narrows to in force / ended.
|
||||
* Authority, file reference, notes and the creator are for callers with
|
||||
* compliance:read (`detailed`); everybody else gets the summary.
|
||||
*/
|
||||
async list(
|
||||
active?: boolean,
|
||||
detailed = true,
|
||||
): Promise<
|
||||
ApiaryRestriction[] | ActiveRestrictionInfo[] | RestrictionSummary[]
|
||||
> {
|
||||
if (active === true) {
|
||||
return this.findActive();
|
||||
}
|
||||
const rows = await this.prisma.apiaryRestriction.findMany({
|
||||
orderBy: [{ startsOn: 'desc' }, { id: 'asc' }],
|
||||
});
|
||||
const wanted =
|
||||
active === false
|
||||
? rows.filter((row) => !isRestrictionActive(row, berlinToday()))
|
||||
: rows;
|
||||
return detailed ? wanted : wanted.map(toSummary);
|
||||
}
|
||||
|
||||
async findForApiary(
|
||||
apiaryId: string,
|
||||
detailed = true,
|
||||
): Promise<ApiaryRestriction[] | RestrictionSummary[]> {
|
||||
const apiary = await this.prisma.apiary.findUnique({
|
||||
where: { id: apiaryId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!apiary) {
|
||||
throw new NotFoundException('Bienenstand nicht gefunden');
|
||||
}
|
||||
const rows = await this.prisma.apiaryRestriction.findMany({
|
||||
where: { apiaryId },
|
||||
orderBy: [{ startsOn: 'desc' }, { id: 'asc' }],
|
||||
});
|
||||
return detailed ? rows : rows.map(toSummary);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import {
|
||||
ArrayMaxSize,
|
||||
ArrayMinSize,
|
||||
ArrayUnique,
|
||||
IsArray,
|
||||
IsDateString,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Matches,
|
||||
MaxLength,
|
||||
} from 'class-validator';
|
||||
|
||||
export const MAX_RESTRICTION_APIARIES = 50;
|
||||
const MAX_ID_LENGTH = 64;
|
||||
const MAX_TEXT_LENGTH = 200;
|
||||
const MAX_NOTE_LENGTH = 2000;
|
||||
const ID_PATTERN = /^[A-Za-z0-9_-]+$/;
|
||||
const DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
||||
const DAY_MESSAGE = 'muss ein Datum im Format JJJJ-MM-TT sein';
|
||||
|
||||
/** A restricted zone declared by the authority, for one or several apiaries. */
|
||||
export class CreateApiaryRestrictionDto {
|
||||
@ApiProperty({
|
||||
type: [String],
|
||||
description: 'Ein Datensatz je Stand, 1 bis 50 Stände',
|
||||
})
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
@ArrayMaxSize(MAX_RESTRICTION_APIARIES)
|
||||
@ArrayUnique()
|
||||
@IsString({ each: true })
|
||||
@Matches(ID_PATTERN, { each: true })
|
||||
@MaxLength(MAX_ID_LENGTH, { each: true })
|
||||
apiaryIds!: string[];
|
||||
|
||||
@ApiProperty({ description: 'Seuche, z. B. Amerikanische Faulbrut' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@Matches(/\S/, { message: 'disease darf nicht nur aus Leerzeichen bestehen' })
|
||||
@MaxLength(MAX_TEXT_LENGTH)
|
||||
disease!: string;
|
||||
|
||||
@ApiPropertyOptional({ nullable: true, description: 'Anordnende Behörde' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(MAX_TEXT_LENGTH)
|
||||
authority?: string | null;
|
||||
|
||||
@ApiPropertyOptional({ nullable: true, description: 'Aktenzeichen' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(MAX_TEXT_LENGTH)
|
||||
reference?: string | null;
|
||||
|
||||
@ApiProperty({ example: '2026-10-01', description: 'Erster Tag der Sperre' })
|
||||
@Matches(DAY_PATTERN, { message: `startsOn ${DAY_MESSAGE}` })
|
||||
@IsDateString({ strict: true })
|
||||
startsOn!: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
nullable: true,
|
||||
example: '2026-12-01',
|
||||
description: 'Letzter Tag der Sperre; leer = bis auf Weiteres',
|
||||
})
|
||||
@IsOptional()
|
||||
@Matches(DAY_PATTERN, { message: `endsOn ${DAY_MESSAGE}` })
|
||||
@IsDateString({ strict: true })
|
||||
endsOn?: string | null;
|
||||
|
||||
@ApiPropertyOptional({ nullable: true })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(MAX_NOTE_LENGTH)
|
||||
notes?: string | null;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Transform } from 'class-transformer';
|
||||
import { IsBoolean, IsOptional } from 'class-validator';
|
||||
import { booleanQuery } from '../../veterinary-medicines/dto/medicine-list-query.dto';
|
||||
|
||||
export class RestrictionListQuery {
|
||||
@ApiPropertyOptional({
|
||||
description: 'true: nur heute geltende Sperren; false: nur beendete',
|
||||
})
|
||||
@IsOptional()
|
||||
@Transform(booleanQuery)
|
||||
@IsBoolean()
|
||||
active?: boolean;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { OmitType, PartialType } from '@nestjs/swagger';
|
||||
import { CreateApiaryRestrictionDto } from './create-apiary-restriction.dto';
|
||||
|
||||
/**
|
||||
* The apiary of a restriction is fixed: a restriction for another stand is a
|
||||
* new restriction. Omitted stays, null clears a nullable field (endsOn ends
|
||||
* the restriction as open again), null on disease or startsOn is a 400.
|
||||
*/
|
||||
export class UpdateApiaryRestrictionDto extends PartialType(
|
||||
OmitType(CreateApiaryRestrictionDto, ['apiaryIds'] as const),
|
||||
{ skipNullProperties: false },
|
||||
) {}
|
||||
@@ -60,6 +60,11 @@ import { SuggestionsModule } from './suggestions/suggestions.module';
|
||||
import { AutopilotModule } from './autopilot/autopilot.module';
|
||||
import { SystemModule } from './system/system.module';
|
||||
import { WithdrawalModule } from './withdrawal/withdrawal.module';
|
||||
import { HiveModule } from './hive/hive.module';
|
||||
import { VeterinaryMedicinesModule } from './veterinary-medicines/veterinary-medicines.module';
|
||||
import { ComplianceModule } from './compliance/compliance.module';
|
||||
import { ReadinessModule } from './compliance/readiness/readiness.module';
|
||||
import { VoiceModule } from './voice/voice.module';
|
||||
import { JwtAuthGuard } from './auth/guards/jwt-auth.guard';
|
||||
import { PermissionsGuard } from './auth/guards/permissions.guard';
|
||||
import { PermissionsModule } from './auth/permissions/permissions.module';
|
||||
@@ -132,6 +137,11 @@ import { IdempotencyInterceptor } from './common/idempotency/idempotency.interce
|
||||
ErpExportModule,
|
||||
ApiKeysModule,
|
||||
SystemModule,
|
||||
VeterinaryMedicinesModule,
|
||||
HiveModule,
|
||||
ComplianceModule,
|
||||
ReadinessModule,
|
||||
VoiceModule,
|
||||
],
|
||||
controllers: [],
|
||||
providers: [
|
||||
|
||||
@@ -412,6 +412,11 @@ export const PERMISSION_CATALOG = [
|
||||
],
|
||||
3800,
|
||||
),
|
||||
// Beute in 3D: hive systems and their part-type catalog. Reading the
|
||||
// catalog and writing a colony's setup use the colonies permissions.
|
||||
...group('Beutensysteme', 'hive-systems', [['manage', 'Pflegen']], 3900),
|
||||
// T7 Freihand: voice notes. Every endpoint also needs inspections:create.
|
||||
...group('Sprache', 'voice-captures', [['use', 'Benutzen']], 4000),
|
||||
] as const satisfies readonly PermissionCatalogEntry[];
|
||||
|
||||
export type PermissionKey = (typeof PERMISSION_CATALOG)[number]['key'];
|
||||
@@ -2,6 +2,7 @@ import { BadRequestException, Logger } from '@nestjs/common';
|
||||
import * as path from 'node:path';
|
||||
import { Prisma } from '../../generated/prisma';
|
||||
import {
|
||||
BackupBundle,
|
||||
BackupService,
|
||||
LEGACY_UNSEALED_TABLES,
|
||||
MODELS_EXCLUDED_FROM_BACKUP,
|
||||
@@ -113,7 +114,15 @@ describe('BackupService', () => {
|
||||
document: { findMany: jest.Mock; count: jest.Mock };
|
||||
$transaction: jest.Mock;
|
||||
};
|
||||
let tx: Record<string, { upsert: jest.Mock; update?: jest.Mock }> & {
|
||||
let tx: Record<
|
||||
string,
|
||||
{
|
||||
upsert: jest.Mock;
|
||||
update?: jest.Mock;
|
||||
create?: jest.Mock;
|
||||
deleteMany?: jest.Mock;
|
||||
}
|
||||
> & {
|
||||
permission: { findUnique: jest.Mock };
|
||||
user: { upsert: jest.Mock; findMany: jest.Mock };
|
||||
queen: { upsert: jest.Mock; update: jest.Mock; findMany: jest.Mock };
|
||||
@@ -139,6 +148,10 @@ describe('BackupService', () => {
|
||||
(tx as unknown as { $queryRaw: jest.Mock }).$queryRaw = jest
|
||||
.fn()
|
||||
.mockResolvedValue([]);
|
||||
for (const key of ['hiveChange', 'hiveSetup']) {
|
||||
tx[key].create = jest.fn().mockResolvedValue({});
|
||||
tx[key].deleteMany = jest.fn().mockResolvedValue({ count: 0 });
|
||||
}
|
||||
tx.queen.update = jest.fn().mockResolvedValue({});
|
||||
tx.queen.findMany = jest.fn().mockResolvedValue([]);
|
||||
tx.document.findUnique = jest.fn().mockResolvedValue(null);
|
||||
@@ -1523,6 +1536,29 @@ describe('BackupService', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('excludes VoiceCapture and VoiceCaptureAudio with a reason', async () => {
|
||||
const bundle = await service.exportAll();
|
||||
|
||||
for (const [model, key] of [
|
||||
['VoiceCapture', 'voiceCapture'],
|
||||
['VoiceCaptureAudio', 'voiceCaptureAudio'],
|
||||
] as const) {
|
||||
expect(bundle.data).not.toHaveProperty(key);
|
||||
expect(MODELS_EXCLUDED_FROM_BACKUP[model]).toMatch(
|
||||
/ephemeral, personal data, not deliverable after a restore/,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('excludes the VoiceExtractionCall ledger with a reason', async () => {
|
||||
const bundle = await service.exportAll();
|
||||
|
||||
expect(bundle.data).not.toHaveProperty('voiceExtractionCall');
|
||||
expect(MODELS_EXCLUDED_FROM_BACKUP.VoiceExtractionCall).toMatch(
|
||||
/Operational ledger/,
|
||||
);
|
||||
});
|
||||
|
||||
it('restores phenology reports after the apiaries, remapping a user that does not exist', async () => {
|
||||
await importData({
|
||||
apiary: [{ id: 'apiary-1' }],
|
||||
@@ -1948,6 +1984,80 @@ describe('BackupService', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('importAll hive models', () => {
|
||||
const hiveBundle = (): BackupBundle => ({
|
||||
version: 3,
|
||||
exportedAt: '2026-01-01T00:00:00.000Z',
|
||||
data: {
|
||||
hiveSystem: [{ id: 'hive-system-1', name: 'System' }],
|
||||
hivePartType: [{ id: 'hive-part-1', systemId: 'hive-system-1' }],
|
||||
colony: [{ id: 'colony-1' }, { id: 'colony-2' }],
|
||||
hiveSetup: [
|
||||
{ colonyId: 'colony-1', systemId: 'hive-system-1', version: 2 },
|
||||
{ colonyId: 'colony-other', systemId: 'hive-system-1', version: 1 },
|
||||
],
|
||||
hiveChange: [
|
||||
{ id: 'change-1', colonyId: 'colony-1', userId: 'known-user' },
|
||||
{ id: 'change-2', colonyId: 'colony-1', userId: 'gone-user' },
|
||||
{ id: 'change-3', colonyId: 'colony-other', userId: 'known-user' },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
it('upserts the catalog by id so seeded rows are neither duplicated nor rejected', async () => {
|
||||
await service.importAll(hiveBundle(), 'admin-1', TRUSTED);
|
||||
|
||||
expect(tx.hiveSystem.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ where: { id: 'hive-system-1' } }),
|
||||
);
|
||||
expect(tx.hivePartType.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ where: { id: 'hive-part-1' } }),
|
||||
);
|
||||
});
|
||||
|
||||
it('replaces setup and history of each restored colony, remapping the history user', async () => {
|
||||
const summary = await service.importAll(hiveBundle(), 'admin-1', TRUSTED);
|
||||
|
||||
expect(tx.hiveChange.deleteMany).toHaveBeenCalledWith({
|
||||
where: { colonyId: { in: ['colony-1'] } },
|
||||
});
|
||||
expect(tx.hiveSetup.deleteMany).toHaveBeenCalledWith({
|
||||
where: { colonyId: { in: ['colony-1'] } },
|
||||
});
|
||||
expect(tx.hiveSetup.create).toHaveBeenCalledTimes(1);
|
||||
const created = tx.hiveChange.create!.mock.calls.map(
|
||||
([arg]: [{ data: { id: string; userId: string } }]) => arg.data,
|
||||
);
|
||||
expect(created).toEqual([
|
||||
expect.objectContaining({ id: 'change-1', userId: 'known-user' }),
|
||||
expect.objectContaining({ id: 'change-2', userId: 'admin-1' }),
|
||||
]);
|
||||
expect(summary.imported).toMatchObject({
|
||||
hiveSystem: 1,
|
||||
hivePartType: 1,
|
||||
hiveSetup: 2,
|
||||
hiveChange: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it('takes no hive table from an unsealed file and reports them', async () => {
|
||||
const summary = await service.importAll(hiveBundle(), 'admin-1', {
|
||||
trusted: false,
|
||||
});
|
||||
|
||||
expect(tx.hiveSetup.create).not.toHaveBeenCalled();
|
||||
expect(tx.hiveSystem.upsert).not.toHaveBeenCalled();
|
||||
expect(summary.skipped).toEqual(
|
||||
expect.arrayContaining([
|
||||
'hiveSystem',
|
||||
'hivePartType',
|
||||
'hiveSetup',
|
||||
'hiveChange',
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// Drift guard: a model added to the schema has to be backed up or listed
|
||||
// in MODELS_EXCLUDED_FROM_BACKUP with its reason - never silently missing.
|
||||
describe('model coverage', () => {
|
||||
|
||||
@@ -158,6 +158,12 @@ export const MODELS_EXCLUDED_FROM_BACKUP: Readonly<
|
||||
NotificationDelivery:
|
||||
'Delivery queue - restoring it would resend old messages.',
|
||||
TelegramPollState: 'Update offset and poll lease of this deployment.',
|
||||
VoiceCapture:
|
||||
'Voice notes are ephemeral, personal data, not deliverable after a restore (content is deleted after at most 7 days).',
|
||||
VoiceCaptureAudio:
|
||||
'Encrypted audio of voice notes: ephemeral, personal data, not deliverable after a restore.',
|
||||
VoiceExtractionCall:
|
||||
'Operational ledger of paid model calls (daily budget, cost card), kept 90 days, meaningless after a restore.',
|
||||
};
|
||||
|
||||
const DOCUMENT_ENTITY_TYPES = new Set<string>(
|
||||
@@ -329,9 +335,13 @@ export class BackupService {
|
||||
data.colony = await this.prisma.colony.findMany();
|
||||
data.colonyApiaryHistory = await this.prisma.colonyApiaryHistory.findMany();
|
||||
data.colonyLineage = await this.prisma.colonyLineage.findMany();
|
||||
data.hiveSystem = await this.prisma.hiveSystem.findMany();
|
||||
data.hivePartType = await this.prisma.hivePartType.findMany();
|
||||
data.hiveSetup = await this.prisma.hiveSetup.findMany();
|
||||
data.queenEvaluation = await this.prisma.queenEvaluation.findMany();
|
||||
data.queenColonyHistory = await this.prisma.queenColonyHistory.findMany();
|
||||
data.inspection = await this.prisma.inspection.findMany();
|
||||
data.hiveChange = await this.prisma.hiveChange.findMany();
|
||||
data.taskTemplate = await this.prisma.taskTemplate.findMany();
|
||||
data.suggestion = await this.prisma.suggestion.findMany();
|
||||
data.task = await this.prisma.task.findMany();
|
||||
@@ -608,6 +618,27 @@ export class BackupService {
|
||||
}
|
||||
imported.queen = rowsOf('queen').length;
|
||||
|
||||
// Catalog first: a fresh install already carries the seeded rows with
|
||||
// the same fixed ids, so upsert by id neither fails nor duplicates.
|
||||
for (const row of rowsOf('hiveSystem')) {
|
||||
await tx.hiveSystem.upsert({
|
||||
where: { id: row.id as string },
|
||||
create: row as never,
|
||||
update: updateWith(row) as never,
|
||||
});
|
||||
}
|
||||
imported.hiveSystem = rowsOf('hiveSystem').length;
|
||||
|
||||
for (const row of rowsOf('hivePartType')) {
|
||||
await tx.hivePartType.upsert({
|
||||
where: { id: row.id as string },
|
||||
create: row as never,
|
||||
update: updateWith(row) as never,
|
||||
});
|
||||
}
|
||||
imported.hivePartType = rowsOf('hivePartType').length;
|
||||
|
||||
// Restore deliberately emits no ColonyCreated (no domain events).
|
||||
for (const row of rowsOf('colony')) {
|
||||
await tx.colony.upsert({
|
||||
where: { id: row.id as string },
|
||||
@@ -617,6 +648,33 @@ export class BackupService {
|
||||
}
|
||||
imported.colony = rowsOf('colony').length;
|
||||
|
||||
// A restore replaces, never merges: the backup's setup wins, so the
|
||||
// existing setup and history of each restored colony go first (the
|
||||
// history rows reference the setup). Their backup history follows
|
||||
// after the inspections.
|
||||
const hiveSetupRows = rowsOf('hiveSetup');
|
||||
const restoredColonyIds = new Set(
|
||||
rowsOf('colony').map((row) => row.id as string),
|
||||
);
|
||||
const setupsToReplace = hiveSetupRows.filter((row) =>
|
||||
restoredColonyIds.has(row.colonyId as string),
|
||||
);
|
||||
const replacedColonyIds = setupsToReplace.map(
|
||||
(row) => row.colonyId as string,
|
||||
);
|
||||
if (replacedColonyIds.length > 0) {
|
||||
await tx.hiveChange.deleteMany({
|
||||
where: { colonyId: { in: replacedColonyIds } },
|
||||
});
|
||||
await tx.hiveSetup.deleteMany({
|
||||
where: { colonyId: { in: replacedColonyIds } },
|
||||
});
|
||||
}
|
||||
for (const row of setupsToReplace) {
|
||||
await tx.hiveSetup.create({ data: row as never });
|
||||
}
|
||||
imported.hiveSetup = hiveSetupRows.length;
|
||||
|
||||
for (const row of rowsOf('queen')) {
|
||||
if (row.motherQueenId && !preexistingQueenIds.has(row.id as string)) {
|
||||
await tx.queen.update({
|
||||
@@ -691,6 +749,21 @@ export class BackupService {
|
||||
}
|
||||
imported.inspection = rowsOf('inspection').length;
|
||||
|
||||
const replacedColonies = new Set(replacedColonyIds);
|
||||
const hiveChangeRows = rowsOf('hiveChange');
|
||||
for (const row of hiveChangeRows) {
|
||||
if (!replacedColonies.has(row.colonyId as string)) {
|
||||
continue;
|
||||
}
|
||||
await tx.hiveChange.create({
|
||||
data: {
|
||||
...row,
|
||||
userId: resolveUserId(asString(row, 'userId')),
|
||||
} as never,
|
||||
});
|
||||
}
|
||||
imported.hiveChange = hiveChangeRows.length;
|
||||
|
||||
for (const row of rowsOf('taskTemplate')) {
|
||||
await tx.taskTemplate.upsert({
|
||||
where: { id: row.id as string },
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { roundToThousandths } from '../common/quantity';
|
||||
import { DbClient } from '../prisma/db-client';
|
||||
import { lockRowForUpdate, lockRowsForUpdate } from '../prisma/row-lock';
|
||||
import { AuditLogService } from '../audit/audit-log.service';
|
||||
@@ -33,11 +34,6 @@ export interface BottlingBatchFilter {
|
||||
honeyBatchId?: string;
|
||||
}
|
||||
|
||||
/** Amounts are kept in kilograms with gram precision. */
|
||||
function roundKg(amount: number): number {
|
||||
return Math.round(amount * 1000) / 1000;
|
||||
}
|
||||
|
||||
type Tx = Prisma.TransactionClient;
|
||||
|
||||
const REMOVED_NOTE = 'Abfüllung entfernt';
|
||||
@@ -212,7 +208,9 @@ export class BottlingService {
|
||||
? await this.assertBottledProduct(dto.productId)
|
||||
: null;
|
||||
const resolved = resolveJarAndBestBefore(dto, article);
|
||||
const totalAmount = roundKg((resolved.jarSize * dto.jarCount) / 1000);
|
||||
const totalAmount = roundToThousandths(
|
||||
(resolved.jarSize * dto.jarCount) / 1000,
|
||||
);
|
||||
|
||||
const lotNumber =
|
||||
dto.lotNumber ??
|
||||
@@ -352,7 +350,7 @@ export class BottlingService {
|
||||
const movedToOtherHoneyBatch = honeyBatchId !== before.honeyBatchId;
|
||||
const jarSize = dto.jarSize ?? before.jarSize;
|
||||
const jarCount = dto.jarCount ?? before.jarCount;
|
||||
const totalAmount = roundKg((jarSize * jarCount) / 1000);
|
||||
const totalAmount = roundToThousandths((jarSize * jarCount) / 1000);
|
||||
|
||||
if (movedToOtherHoneyBatch) {
|
||||
// Both batches in one statement in ascending id order, so two
|
||||
@@ -392,7 +390,7 @@ export class BottlingService {
|
||||
await this.book(
|
||||
tx,
|
||||
honeyBatchId,
|
||||
roundKg(before.totalAmount - totalAmount),
|
||||
roundToThousandths(before.totalAmount - totalAmount),
|
||||
actingUserId,
|
||||
{ sourceBottlingBatchId: id },
|
||||
);
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ApiaryRestrictionsModule } from '../apiary-restrictions/apiary-restrictions.module';
|
||||
import { ColoniesController } from './colonies.controller';
|
||||
import { ColoniesService } from './colonies.service';
|
||||
|
||||
// ApiaryRestrictionsModule: the restricted-zone endpoints ride along with the
|
||||
// colony paths that enforce them (AppModule imports ColoniesModule).
|
||||
@Module({
|
||||
imports: [ApiaryRestrictionsModule],
|
||||
controllers: [ColoniesController],
|
||||
providers: [ColoniesService],
|
||||
exports: [ColoniesService],
|
||||
|
||||
@@ -4,7 +4,9 @@ import { PrismaService } from '../prisma/prisma.service';
|
||||
import { AuditLogService } from '../audit/audit-log.service';
|
||||
import { WebhooksService } from '../webhooks/webhooks.service';
|
||||
import { DomainEventsService } from '../domain-events/domain-events.service';
|
||||
import { PermissionResolverService } from '../auth/permissions/permission-resolver.service';
|
||||
import { berlinToday } from '../common/dates';
|
||||
import { expectOnlyIdPayloads } from '../domain-events/herd-payload.spec-helper';
|
||||
|
||||
describe('ColoniesService', () => {
|
||||
let service: ColoniesService;
|
||||
@@ -15,6 +17,8 @@ describe('ColoniesService', () => {
|
||||
colonyLineage: { create: jest.Mock };
|
||||
queenColonyHistory: { updateMany: jest.Mock };
|
||||
suggestion: { updateMany: jest.Mock };
|
||||
apiary: { findUnique: jest.Mock };
|
||||
apiaryRestriction: { findMany: jest.Mock };
|
||||
};
|
||||
let prisma: {
|
||||
colony: {
|
||||
@@ -31,6 +35,7 @@ describe('ColoniesService', () => {
|
||||
};
|
||||
let auditLog: { record: jest.Mock };
|
||||
let events: { record: jest.Mock; recordAll: jest.Mock };
|
||||
let resolver: { getPermissions: jest.Mock };
|
||||
|
||||
const parentColony = {
|
||||
id: 'colony-1',
|
||||
@@ -48,10 +53,12 @@ describe('ColoniesService', () => {
|
||||
colonyLineage: { create: jest.fn() },
|
||||
queenColonyHistory: { updateMany: jest.fn() },
|
||||
suggestion: { updateMany: jest.fn() },
|
||||
apiary: { findUnique: jest.fn() },
|
||||
apiaryRestriction: { findMany: jest.fn().mockResolvedValue([]) },
|
||||
};
|
||||
prisma = {
|
||||
colony: {
|
||||
findMany: jest.fn(),
|
||||
findMany: jest.fn().mockResolvedValue([]),
|
||||
findUnique: jest.fn(),
|
||||
create: jest.fn(),
|
||||
update: jest.fn(),
|
||||
@@ -68,6 +75,10 @@ describe('ColoniesService', () => {
|
||||
callback(tx),
|
||||
),
|
||||
};
|
||||
// The apiary is read inside the transaction now: same answers as before.
|
||||
tx.apiary.findUnique.mockImplementation(
|
||||
(args: unknown) => prisma.apiary.findUnique(args) as Promise<unknown>,
|
||||
);
|
||||
// The locked re-read sees what the pre-read saw unless a test says otherwise.
|
||||
tx.colony.findUnique.mockImplementation(
|
||||
(args: unknown) => prisma.colony.findUnique(args) as Promise<unknown>,
|
||||
@@ -78,11 +89,17 @@ describe('ColoniesService', () => {
|
||||
record: jest.fn().mockResolvedValue(undefined),
|
||||
recordAll: jest.fn().mockResolvedValue(0),
|
||||
};
|
||||
resolver = {
|
||||
getPermissions: jest
|
||||
.fn()
|
||||
.mockResolvedValue(new Set(['compliance:manage'])),
|
||||
};
|
||||
service = new ColoniesService(
|
||||
prisma as unknown as PrismaService,
|
||||
auditLog as unknown as AuditLogService,
|
||||
webhooks as unknown as WebhooksService,
|
||||
events as unknown as DomainEventsService,
|
||||
resolver as unknown as PermissionResolverService,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -194,9 +211,12 @@ describe('ColoniesService', () => {
|
||||
'user-1',
|
||||
);
|
||||
|
||||
const [[, event]] = events.record.mock.calls as [
|
||||
[unknown, { payload: { queenSource: unknown; splitOn: string } }],
|
||||
];
|
||||
const event = (
|
||||
events.record.mock.calls as [
|
||||
unknown,
|
||||
{ type: string; payload: { queenSource: unknown; splitOn: string } },
|
||||
][]
|
||||
).find(([, recorded]) => recorded.type === 'ColonySplit')![1];
|
||||
expect(event.payload.queenSource).toBeNull();
|
||||
expect(event.payload.splitOn).toBe(berlinToday());
|
||||
});
|
||||
@@ -233,17 +253,23 @@ describe('ColoniesService', () => {
|
||||
});
|
||||
|
||||
it('merge marks the merged colony as MERGED, releases its queen, and records a MERGE lineage entry', async () => {
|
||||
prisma.colony.findUnique
|
||||
.mockResolvedValueOnce(parentColony)
|
||||
.mockResolvedValueOnce({
|
||||
...parentColony,
|
||||
id: 'colony-1',
|
||||
});
|
||||
tx.colony.findUnique.mockResolvedValue({
|
||||
id: 'colony-3',
|
||||
status: 'ACTIVE',
|
||||
currentQueenId: 'queen-2',
|
||||
});
|
||||
prisma.colony.findUnique.mockResolvedValue(parentColony);
|
||||
prisma.colony.findMany.mockResolvedValue([
|
||||
{ id: 'colony-3', apiaryId: 'apiary-1' },
|
||||
]);
|
||||
tx.colony.findUnique.mockImplementation(
|
||||
({ where }: { where: { id: string } }) =>
|
||||
Promise.resolve(
|
||||
where.id === 'colony-1'
|
||||
? parentColony
|
||||
: {
|
||||
id: 'colony-3',
|
||||
apiaryId: 'apiary-1',
|
||||
status: 'ACTIVE',
|
||||
currentQueenId: 'queen-2',
|
||||
},
|
||||
),
|
||||
);
|
||||
tx.colony.update.mockResolvedValue({
|
||||
id: 'colony-3',
|
||||
status: 'MERGED',
|
||||
@@ -514,6 +540,110 @@ describe('ColoniesService', () => {
|
||||
expect(tx.colonyApiaryHistory.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe('herd events', () => {
|
||||
// Whatever a test recorded, the herd payloads carry only ids.
|
||||
afterEach(() => {
|
||||
expectOnlyIdPayloads(events.record.mock.calls);
|
||||
});
|
||||
|
||||
function recorded(type: string): unknown[] {
|
||||
return (events.record.mock.calls as [unknown, { type: string }][]).filter(
|
||||
([, event]) => event.type === type,
|
||||
);
|
||||
}
|
||||
|
||||
it('create records ColonyCreated with the apiary inside the transaction', async () => {
|
||||
tx.colony.create.mockResolvedValue({
|
||||
id: 'colony-9',
|
||||
apiaryId: 'apiary-1',
|
||||
});
|
||||
|
||||
await service.create(
|
||||
{ code: 'V-9', apiaryId: 'apiary-1', colonyType: 'PRODUCTION_COLONY' },
|
||||
'user-1',
|
||||
);
|
||||
|
||||
expect(events.record).toHaveBeenCalledWith(tx, {
|
||||
type: 'ColonyCreated',
|
||||
aggregateType: 'Colony',
|
||||
aggregateId: 'colony-9',
|
||||
actorUserId: 'user-1',
|
||||
payload: { apiaryId: 'apiary-1' },
|
||||
});
|
||||
});
|
||||
|
||||
it('split records ColonyCreated for the child next to ColonySplit', async () => {
|
||||
prisma.colony.findUnique.mockResolvedValue(parentColony);
|
||||
tx.colony.create.mockResolvedValue({
|
||||
id: 'colony-2',
|
||||
apiaryId: 'apiary-1',
|
||||
});
|
||||
tx.colonyLineage.create.mockResolvedValue({ id: 'lineage-1' });
|
||||
|
||||
await service.split(
|
||||
'colony-1',
|
||||
{ code: 'V-001-A', colonyType: 'NUCLEUS_COLONY' },
|
||||
'user-1',
|
||||
);
|
||||
|
||||
const types = (
|
||||
events.record.mock.calls as [unknown, { type: string }][]
|
||||
).map(([, event]) => event.type);
|
||||
expect(types).toEqual(
|
||||
expect.arrayContaining(['ColonySplit', 'ColonyCreated']),
|
||||
);
|
||||
expect(events.record).toHaveBeenCalledWith(tx, {
|
||||
type: 'ColonyCreated',
|
||||
aggregateType: 'Colony',
|
||||
aggregateId: 'colony-2',
|
||||
actorUserId: 'user-1',
|
||||
payload: { apiaryId: 'apiary-1' },
|
||||
});
|
||||
});
|
||||
|
||||
it('move records ColonyMoved with from and to', async () => {
|
||||
prisma.colony.findUnique.mockResolvedValue(parentColony);
|
||||
tx.colony.update.mockResolvedValue({
|
||||
...parentColony,
|
||||
apiaryId: 'apiary-2',
|
||||
});
|
||||
|
||||
await service.move('colony-1', { apiaryId: 'apiary-2' }, 'user-1');
|
||||
|
||||
expect(events.record).toHaveBeenCalledWith(tx, {
|
||||
type: 'ColonyMoved',
|
||||
aggregateType: 'Colony',
|
||||
aggregateId: 'colony-1',
|
||||
actorUserId: 'user-1',
|
||||
payload: { fromApiaryId: 'apiary-1', toApiaryId: 'apiary-2' },
|
||||
});
|
||||
});
|
||||
|
||||
it('update with a changed apiary records ColonyMoved and without one records none', async () => {
|
||||
prisma.colony.findUnique.mockResolvedValue(parentColony);
|
||||
tx.colony.update.mockResolvedValue({
|
||||
...parentColony,
|
||||
apiaryId: 'apiary-2',
|
||||
});
|
||||
|
||||
await service.update('colony-1', { apiaryId: 'apiary-2' }, 'user-1');
|
||||
expect(recorded('ColonyMoved')).toHaveLength(1);
|
||||
expect(events.record).toHaveBeenCalledWith(
|
||||
tx,
|
||||
expect.objectContaining({
|
||||
type: 'ColonyMoved',
|
||||
payload: { fromApiaryId: 'apiary-1', toApiaryId: 'apiary-2' },
|
||||
}),
|
||||
);
|
||||
|
||||
events.record.mockClear();
|
||||
tx.colony.update.mockResolvedValue(parentColony);
|
||||
await service.update('colony-1', { notes: 'x' }, 'user-1');
|
||||
await service.update('colony-1', { apiaryId: 'apiary-1' }, 'user-1');
|
||||
expect(recorded('ColonyMoved')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
it('update into CRITICAL health records ColonyStatusChanged with from/to snapshots', async () => {
|
||||
prisma.colony.findUnique.mockResolvedValue({
|
||||
...parentColony,
|
||||
@@ -617,10 +747,15 @@ describe('ColoniesService', () => {
|
||||
|
||||
it('merge records ColonyEnded "MERGED" for every merged colony', async () => {
|
||||
prisma.colony.findUnique.mockResolvedValue(parentColony);
|
||||
prisma.colony.findMany.mockResolvedValue([
|
||||
{ id: 'colony-3', apiaryId: 'apiary-1' },
|
||||
{ id: 'colony-4', apiaryId: 'apiary-1' },
|
||||
]);
|
||||
tx.colony.findUnique.mockImplementation(
|
||||
({ where }: { where: { id: string } }) =>
|
||||
Promise.resolve({
|
||||
id: where.id,
|
||||
apiaryId: 'apiary-1',
|
||||
status: 'ACTIVE',
|
||||
healthStatus: null,
|
||||
currentQueenId: null,
|
||||
@@ -701,7 +836,8 @@ describe('ColoniesService', () => {
|
||||
});
|
||||
await service.reactivate('colony-1', 'user-1');
|
||||
|
||||
expect(tx.$queryRaw).toHaveBeenCalledTimes(4);
|
||||
// update 1, move 2 (apiary share + colony), dissolve 1, reactivate 1.
|
||||
expect(tx.$queryRaw).toHaveBeenCalledTimes(5);
|
||||
});
|
||||
|
||||
it('uses the locked row, not the pre-read, as "before" for event and audit', async () => {
|
||||
@@ -752,9 +888,18 @@ describe('ColoniesService', () => {
|
||||
|
||||
it('locks every merged colony', async () => {
|
||||
prisma.colony.findUnique.mockResolvedValue(parentColony);
|
||||
prisma.colony.findMany.mockResolvedValue([
|
||||
{ id: 'colony-3', apiaryId: 'apiary-1' },
|
||||
{ id: 'colony-4', apiaryId: 'apiary-1' },
|
||||
]);
|
||||
tx.colony.findUnique.mockImplementation(
|
||||
({ where }: { where: { id: string } }) =>
|
||||
Promise.resolve({ id: where.id, status: 'ACTIVE', healthStatus: null }),
|
||||
Promise.resolve({
|
||||
id: where.id,
|
||||
apiaryId: 'apiary-1',
|
||||
status: 'ACTIVE',
|
||||
healthStatus: null,
|
||||
}),
|
||||
);
|
||||
tx.colony.update.mockImplementation(
|
||||
({ where }: { where: { id: string } }) =>
|
||||
@@ -767,10 +912,12 @@ describe('ColoniesService', () => {
|
||||
'user-1',
|
||||
);
|
||||
|
||||
// One multi-row statement, not one per colony.
|
||||
expect(tx.$queryRaw).toHaveBeenCalledTimes(1);
|
||||
const [[query]] = tx.$queryRaw.mock.calls as [[{ sql: string }]];
|
||||
expect(query.sql).toContain('ANY(?) ORDER BY id FOR UPDATE');
|
||||
// The apiary rows (share), then ONE multi-row statement for the colonies.
|
||||
expect(tx.$queryRaw).toHaveBeenCalledTimes(2);
|
||||
const [, [query]] = tx.$queryRaw.mock.calls as [unknown, [{ sql: string }]];
|
||||
expect(query.sql).toContain(
|
||||
'"Colony" WHERE id = ANY(?) ORDER BY id FOR UPDATE',
|
||||
);
|
||||
});
|
||||
|
||||
describe('a colony that ends through an edit', () => {
|
||||
@@ -824,4 +971,521 @@ describe('ColoniesService', () => {
|
||||
expect(tx.queenColonyHistory.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('restricted zone', () => {
|
||||
const reason = 'Amtstierarzt hat die Verbringung genehmigt';
|
||||
const reloadMessage = 'Der Stand wurde gerade geändert. Bitte neu laden.';
|
||||
const startedLongAgo = new Date('2000-01-01T00:00:00.000Z');
|
||||
|
||||
// An open restriction on each of the given apiaries.
|
||||
function restrict(...apiaryIds: string[]): void {
|
||||
tx.apiaryRestriction.findMany.mockImplementation(
|
||||
({ where }: { where: { apiaryId: { in: string[] } } }) =>
|
||||
Promise.resolve(
|
||||
apiaryIds
|
||||
.filter((apiaryId) => where.apiaryId.in.includes(apiaryId))
|
||||
.map((apiaryId) => ({
|
||||
id: `r-${apiaryId}`,
|
||||
apiaryId,
|
||||
apiary: { name: `Stand ${apiaryId}` },
|
||||
disease: 'Faulbrut',
|
||||
startsOn: startedLongAgo,
|
||||
endsOn: null,
|
||||
})),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function lockSql(): string[] {
|
||||
return (tx.$queryRaw.mock.calls as [{ sql: string }][]).map(
|
||||
([query]) => query.sql,
|
||||
);
|
||||
}
|
||||
|
||||
function setupMove(): void {
|
||||
prisma.colony.findUnique.mockResolvedValue(parentColony);
|
||||
tx.colony.update.mockResolvedValue({
|
||||
...parentColony,
|
||||
apiaryId: 'apiary-2',
|
||||
});
|
||||
}
|
||||
|
||||
function setupMerge(mergedApiaryId = 'apiary-2'): void {
|
||||
prisma.colony.findUnique.mockResolvedValue(parentColony);
|
||||
prisma.colony.findMany.mockResolvedValue([
|
||||
{ id: 'colony-3', apiaryId: mergedApiaryId },
|
||||
]);
|
||||
tx.colony.findUnique.mockImplementation(
|
||||
({ where }: { where: { id: string } }) =>
|
||||
Promise.resolve(
|
||||
where.id === 'colony-1'
|
||||
? parentColony
|
||||
: {
|
||||
id: 'colony-3',
|
||||
apiaryId: mergedApiaryId,
|
||||
status: 'ACTIVE',
|
||||
currentQueenId: null,
|
||||
},
|
||||
),
|
||||
);
|
||||
tx.colony.update.mockResolvedValue({
|
||||
id: 'colony-3',
|
||||
status: 'MERGED',
|
||||
healthStatus: null,
|
||||
});
|
||||
}
|
||||
|
||||
const createDto = {
|
||||
code: 'V-9',
|
||||
apiaryId: 'apiary-1',
|
||||
colonyType: 'PRODUCTION_COLONY' as const,
|
||||
};
|
||||
|
||||
it('split inside the apiary is allowed', async () => {
|
||||
restrict('apiary-1');
|
||||
prisma.colony.findUnique.mockResolvedValue(parentColony);
|
||||
tx.colony.create.mockResolvedValue({
|
||||
id: 'colony-2',
|
||||
apiaryId: 'apiary-1',
|
||||
});
|
||||
tx.colonyLineage.create.mockResolvedValue({ id: 'lineage-1' });
|
||||
|
||||
await expect(
|
||||
service.split(
|
||||
'colony-1',
|
||||
{ code: 'V-001-A', colonyType: 'NUCLEUS_COLONY' },
|
||||
'user-1',
|
||||
),
|
||||
).resolves.toBeDefined();
|
||||
expect(tx.apiaryRestriction.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('create in a restricted apiary is refused', async () => {
|
||||
restrict('apiary-1');
|
||||
|
||||
await expect(service.create(createDto, 'user-1')).rejects.toMatchObject({
|
||||
status: 409,
|
||||
response: { code: 'RESTRICTED_ZONE' },
|
||||
});
|
||||
expect(tx.colony.create).not.toHaveBeenCalled();
|
||||
expect(auditLog.record).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['into', 'apiary-2'],
|
||||
['out of', 'apiary-1'],
|
||||
])('move %s a restricted apiary is refused', async (_way, restricted) => {
|
||||
setupMove();
|
||||
restrict(restricted);
|
||||
|
||||
await expect(
|
||||
service.move('colony-1', { apiaryId: 'apiary-2' }, 'user-1'),
|
||||
).rejects.toMatchObject({
|
||||
status: 409,
|
||||
response: { code: 'RESTRICTED_ZONE' },
|
||||
});
|
||||
expect(tx.colony.update).not.toHaveBeenCalled();
|
||||
expect(tx.colonyApiaryHistory.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('move to the same apiary moves nothing and checks nothing', async () => {
|
||||
prisma.colony.findUnique.mockResolvedValue(parentColony);
|
||||
tx.colony.update.mockResolvedValue(parentColony);
|
||||
restrict('apiary-1');
|
||||
|
||||
await expect(
|
||||
service.move('colony-1', { apiaryId: 'apiary-1' }, 'user-1'),
|
||||
).resolves.toBeDefined();
|
||||
expect(tx.apiaryRestriction.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['the old apiary', 'apiary-1'],
|
||||
['the new apiary', 'apiary-2'],
|
||||
])('update with a changed apiary checks %s', async (_which, restricted) => {
|
||||
setupMove();
|
||||
restrict(restricted);
|
||||
|
||||
await expect(
|
||||
service.update('colony-1', { apiaryId: 'apiary-2' }, 'user-1'),
|
||||
).rejects.toMatchObject({
|
||||
status: 409,
|
||||
response: { code: 'RESTRICTED_ZONE' },
|
||||
});
|
||||
expect(tx.colony.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('a name change checks nothing and takes no apiary lock', async () => {
|
||||
prisma.colony.findUnique.mockResolvedValue(parentColony);
|
||||
tx.colony.update.mockResolvedValue(parentColony);
|
||||
restrict('apiary-1', 'apiary-2');
|
||||
|
||||
await service.update('colony-1', { code: 'V-neu' }, 'user-1');
|
||||
await service.update('colony-1', { apiaryId: 'apiary-1' }, 'user-1');
|
||||
|
||||
expect(tx.apiaryRestriction.findMany).not.toHaveBeenCalled();
|
||||
expect(lockSql().every((sql) => !sql.includes('"Apiary"'))).toBe(true);
|
||||
});
|
||||
|
||||
it('merge across apiaries is refused when one is restricted', async () => {
|
||||
setupMerge('apiary-2');
|
||||
restrict('apiary-2');
|
||||
|
||||
await expect(
|
||||
service.merge('colony-1', { mergedColonyIds: ['colony-3'] }, 'user-1'),
|
||||
).rejects.toMatchObject({
|
||||
status: 409,
|
||||
response: { code: 'RESTRICTED_ZONE' },
|
||||
});
|
||||
expect(tx.colony.update).not.toHaveBeenCalled();
|
||||
expect(tx.colonyLineage.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('merge within one apiary is allowed even in a restricted apiary', async () => {
|
||||
setupMerge('apiary-1');
|
||||
restrict('apiary-1');
|
||||
|
||||
await expect(
|
||||
service.merge('colony-1', { mergedColonyIds: ['colony-3'] }, 'user-1'),
|
||||
).resolves.toBeDefined();
|
||||
expect(tx.apiaryRestriction.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const scenarios: Record<
|
||||
string,
|
||||
{
|
||||
run: (restrictionOverrideReason: string) => Promise<unknown>;
|
||||
setup: () => void;
|
||||
restricted: string[];
|
||||
}
|
||||
> = {
|
||||
create: {
|
||||
setup: () => {
|
||||
tx.colony.create.mockResolvedValue({
|
||||
id: 'colony-9',
|
||||
apiaryId: 'apiary-1',
|
||||
});
|
||||
},
|
||||
restricted: ['apiary-1'],
|
||||
run: (restrictionOverrideReason) =>
|
||||
service.create({ ...createDto, restrictionOverrideReason }, 'user-1'),
|
||||
},
|
||||
update: {
|
||||
setup: setupMove,
|
||||
restricted: ['apiary-2'],
|
||||
run: (restrictionOverrideReason) =>
|
||||
service.update(
|
||||
'colony-1',
|
||||
{ apiaryId: 'apiary-2', restrictionOverrideReason },
|
||||
'user-1',
|
||||
),
|
||||
},
|
||||
move: {
|
||||
setup: setupMove,
|
||||
restricted: ['apiary-2'],
|
||||
run: (restrictionOverrideReason) =>
|
||||
service.move(
|
||||
'colony-1',
|
||||
{ apiaryId: 'apiary-2', restrictionOverrideReason },
|
||||
'user-1',
|
||||
),
|
||||
},
|
||||
merge: {
|
||||
setup: () => setupMerge('apiary-2'),
|
||||
restricted: ['apiary-2'],
|
||||
run: (restrictionOverrideReason) =>
|
||||
service.merge(
|
||||
'colony-1',
|
||||
{ mergedColonyIds: ['colony-3'], restrictionOverrideReason },
|
||||
'user-1',
|
||||
),
|
||||
},
|
||||
};
|
||||
|
||||
it.each(Object.keys(scenarios))(
|
||||
'the override reason is never part of the data written to the colony (%s)',
|
||||
async (name) => {
|
||||
const scenario = scenarios[name];
|
||||
scenario.setup();
|
||||
restrict(...scenario.restricted);
|
||||
|
||||
await scenario.run(reason);
|
||||
|
||||
const written = JSON.stringify([
|
||||
tx.colony.create.mock.calls,
|
||||
tx.colony.update.mock.calls,
|
||||
]);
|
||||
expect(written).not.toContain(reason);
|
||||
expect(written).not.toContain('restrictionOverrideReason');
|
||||
},
|
||||
);
|
||||
|
||||
it.each(Object.keys(scenarios))(
|
||||
'an override writes the reason and the restriction ids into the audit entry (%s)',
|
||||
async (name) => {
|
||||
const scenario = scenarios[name];
|
||||
scenario.setup();
|
||||
restrict(...scenario.restricted);
|
||||
|
||||
await scenario.run(reason);
|
||||
|
||||
const audits = (
|
||||
auditLog.record.mock.calls as [
|
||||
{ afterData: { restrictionOverride?: unknown } },
|
||||
][]
|
||||
).filter(([entry]) => entry.afterData.restrictionOverride);
|
||||
expect(audits).toHaveLength(1);
|
||||
expect(audits[0][0].afterData.restrictionOverride).toEqual({
|
||||
reason,
|
||||
restrictionIds: [`r-${scenario.restricted[0]}`],
|
||||
});
|
||||
expect(resolver.getPermissions).toHaveBeenCalledTimes(1);
|
||||
},
|
||||
);
|
||||
|
||||
it('an override writes the reason into ColonyApiaryHistory.notes, in front of an existing note', async () => {
|
||||
setupMove();
|
||||
restrict('apiary-2');
|
||||
|
||||
await service.move(
|
||||
'colony-1',
|
||||
{
|
||||
apiaryId: 'apiary-2',
|
||||
notes: 'Wanderung',
|
||||
restrictionOverrideReason: reason,
|
||||
},
|
||||
'user-1',
|
||||
);
|
||||
await service.update(
|
||||
'colony-1',
|
||||
{ apiaryId: 'apiary-2', restrictionOverrideReason: reason },
|
||||
'user-1',
|
||||
);
|
||||
|
||||
const notes = (
|
||||
tx.colonyApiaryHistory.create.mock.calls as [
|
||||
{ data: { notes: string } },
|
||||
][]
|
||||
).map(([call]) => call.data.notes);
|
||||
expect(notes).toEqual([
|
||||
`Ausnahme Sperrbezirk: ${reason}\nWanderung`,
|
||||
`Ausnahme Sperrbezirk: ${reason}\nKorrektur über Volk bearbeiten`,
|
||||
]);
|
||||
});
|
||||
|
||||
it('an override without compliance:manage answers 403 and writes nothing', async () => {
|
||||
setupMove();
|
||||
restrict('apiary-2');
|
||||
resolver.getPermissions.mockResolvedValue(new Set(['colonies:update']));
|
||||
|
||||
await expect(
|
||||
service.move(
|
||||
'colony-1',
|
||||
{ apiaryId: 'apiary-2', restrictionOverrideReason: reason },
|
||||
'user-1',
|
||||
),
|
||||
).rejects.toMatchObject({ status: 403 });
|
||||
expect(tx.colony.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('a reason without an active restriction is ignored for a user with the right: no note, no audit field', async () => {
|
||||
setupMove();
|
||||
|
||||
await service.move(
|
||||
'colony-1',
|
||||
{ apiaryId: 'apiary-2', restrictionOverrideReason: reason },
|
||||
'user-1',
|
||||
);
|
||||
|
||||
expect(
|
||||
JSON.stringify(tx.colonyApiaryHistory.create.mock.calls),
|
||||
).not.toContain('Ausnahme');
|
||||
expect(JSON.stringify(auditLog.record.mock.calls)).not.toContain(
|
||||
'restrictionOverride',
|
||||
);
|
||||
});
|
||||
|
||||
it.each(Object.keys(scenarios))(
|
||||
'a reason without compliance:manage answers 403 up front, even without any restriction (%s)',
|
||||
async (name) => {
|
||||
const scenario = scenarios[name];
|
||||
scenario.setup();
|
||||
resolver.getPermissions.mockResolvedValue(new Set());
|
||||
|
||||
await expect(scenario.run(reason)).rejects.toMatchObject({
|
||||
status: 403,
|
||||
});
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled();
|
||||
expect(tx.colony.update).not.toHaveBeenCalled();
|
||||
expect(tx.colony.create).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('merge answers 404, not "moved meanwhile", when a merged colony vanished between read and lock', async () => {
|
||||
setupMerge('apiary-2');
|
||||
tx.colony.findUnique.mockImplementation(
|
||||
({ where }: { where: { id: string } }) =>
|
||||
Promise.resolve(where.id === 'colony-1' ? parentColony : null),
|
||||
);
|
||||
|
||||
await expect(
|
||||
service.merge('colony-1', { mergedColonyIds: ['colony-3'] }, 'user-1'),
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
});
|
||||
|
||||
it('a null reason counts as omitted and asks for no permission', async () => {
|
||||
setupMove();
|
||||
restrict('apiary-2');
|
||||
|
||||
await expect(
|
||||
service.move(
|
||||
'colony-1',
|
||||
{ apiaryId: 'apiary-2', restrictionOverrideReason: null },
|
||||
'user-1',
|
||||
),
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
expect(resolver.getPermissions).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('the restriction check runs inside the transaction after the apiary rows (share, ascending) and then the colony row are locked', async () => {
|
||||
setupMove();
|
||||
|
||||
await service.move('colony-1', { apiaryId: 'apiary-2' }, 'user-1');
|
||||
|
||||
expect(lockSql()).toEqual([
|
||||
'SELECT id FROM "Apiary" WHERE id = ANY(?) ORDER BY id FOR SHARE',
|
||||
'SELECT id FROM "Colony" WHERE id = ? FOR UPDATE',
|
||||
]);
|
||||
const [[shareQuery]] = tx.$queryRaw.mock.calls as [
|
||||
[{ values: unknown[] }],
|
||||
];
|
||||
expect(shareQuery.values).toEqual([['apiary-1', 'apiary-2']]);
|
||||
const order = [
|
||||
tx.$queryRaw.mock.invocationCallOrder[0],
|
||||
tx.$queryRaw.mock.invocationCallOrder[1],
|
||||
tx.apiaryRestriction.findMany.mock.invocationCallOrder[0],
|
||||
tx.colony.update.mock.invocationCallOrder[0],
|
||||
];
|
||||
expect(order).toEqual([...order].sort((a, b) => a - b));
|
||||
expect(tx.apiary.findUnique.mock.invocationCallOrder[0]).toBeGreaterThan(
|
||||
tx.$queryRaw.mock.invocationCallOrder[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('create locks the apiary (share) before it checks and writes', async () => {
|
||||
tx.colony.create.mockResolvedValue({
|
||||
id: 'colony-9',
|
||||
apiaryId: 'apiary-1',
|
||||
});
|
||||
|
||||
await service.create(createDto, 'user-1');
|
||||
|
||||
expect(lockSql()).toEqual([
|
||||
'SELECT id FROM "Apiary" WHERE id = ANY(?) ORDER BY id FOR SHARE',
|
||||
]);
|
||||
expect(tx.$queryRaw.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
tx.apiaryRestriction.findMany.mock.invocationCallOrder[0],
|
||||
);
|
||||
expect(
|
||||
tx.apiaryRestriction.findMany.mock.invocationCallOrder[0],
|
||||
).toBeLessThan(tx.colony.create.mock.invocationCallOrder[0]);
|
||||
});
|
||||
|
||||
it('merge locks the apiaries (share), then survivor and merged colonies in one statement', async () => {
|
||||
setupMerge('apiary-2');
|
||||
|
||||
await service.merge(
|
||||
'colony-1',
|
||||
{ mergedColonyIds: ['colony-3'] },
|
||||
'user-1',
|
||||
);
|
||||
|
||||
expect(lockSql()).toEqual([
|
||||
'SELECT id FROM "Apiary" WHERE id = ANY(?) ORDER BY id FOR SHARE',
|
||||
'SELECT id FROM "Colony" WHERE id = ANY(?) ORDER BY id FOR UPDATE',
|
||||
]);
|
||||
expect(
|
||||
tx.apiaryRestriction.findMany.mock.invocationCallOrder[0],
|
||||
).toBeGreaterThan(tx.$queryRaw.mock.invocationCallOrder[1]);
|
||||
});
|
||||
|
||||
it('update, move and merge answer 409 when the colony changed its apiary between the unlocked read and the lock', async () => {
|
||||
const movedAway = { ...parentColony, apiaryId: 'apiary-3' };
|
||||
|
||||
prisma.colony.findUnique.mockResolvedValue(parentColony);
|
||||
tx.colony.findUnique.mockResolvedValue(movedAway);
|
||||
await expect(
|
||||
service.update('colony-1', { apiaryId: 'apiary-2' }, 'user-1'),
|
||||
).rejects.toMatchObject({ status: 409, message: reloadMessage });
|
||||
await expect(
|
||||
service.move('colony-1', { apiaryId: 'apiary-2' }, 'user-1'),
|
||||
).rejects.toMatchObject({ status: 409, message: reloadMessage });
|
||||
|
||||
setupMerge('apiary-2');
|
||||
tx.colony.findUnique.mockImplementation(
|
||||
({ where }: { where: { id: string } }) =>
|
||||
Promise.resolve(
|
||||
where.id === 'colony-1'
|
||||
? parentColony
|
||||
: { id: 'colony-3', apiaryId: 'apiary-3', status: 'ACTIVE' },
|
||||
),
|
||||
);
|
||||
await expect(
|
||||
service.merge('colony-1', { mergedColonyIds: ['colony-3'] }, 'user-1'),
|
||||
).rejects.toMatchObject({ status: 409, message: reloadMessage });
|
||||
tx.colony.findUnique.mockImplementation(
|
||||
({ where }: { where: { id: string } }) =>
|
||||
Promise.resolve(
|
||||
where.id === 'colony-1'
|
||||
? movedAway
|
||||
: { id: 'colony-3', apiaryId: 'apiary-2', status: 'ACTIVE' },
|
||||
),
|
||||
);
|
||||
await expect(
|
||||
service.merge('colony-1', { mergedColonyIds: ['colony-3'] }, 'user-1'),
|
||||
).rejects.toMatchObject({ status: 409, message: reloadMessage });
|
||||
|
||||
expect(tx.colony.update).not.toHaveBeenCalled();
|
||||
expect(tx.colonyApiaryHistory.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('an update without an apiary change still works when the colony was moved meanwhile', async () => {
|
||||
prisma.colony.findUnique.mockResolvedValue(parentColony);
|
||||
tx.colony.findUnique.mockResolvedValue({
|
||||
...parentColony,
|
||||
apiaryId: 'apiary-3',
|
||||
});
|
||||
tx.colony.update.mockResolvedValue(parentColony);
|
||||
|
||||
await expect(
|
||||
service.update('colony-1', { notes: 'x' }, 'user-1'),
|
||||
).resolves.toBeDefined();
|
||||
});
|
||||
|
||||
it('updateIn called from an inspection takeover locks no apiary', async () => {
|
||||
tx.colony.findUnique.mockResolvedValue(parentColony);
|
||||
tx.colony.update.mockResolvedValue(parentColony);
|
||||
|
||||
await service.updateIn(tx as never, 'colony-1', { notes: 'x' }, 'user-1');
|
||||
|
||||
expect(lockSql()).toEqual([
|
||||
'SELECT id FROM "Colony" WHERE id = ? FOR UPDATE',
|
||||
]);
|
||||
expect(tx.apiaryRestriction.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('updateIn refuses to move the apiary without the locks update() takes', async () => {
|
||||
tx.colony.findUnique.mockResolvedValue(parentColony);
|
||||
|
||||
await expect(
|
||||
service.updateIn(
|
||||
tx as never,
|
||||
'colony-1',
|
||||
{ apiaryId: 'apiary-2' },
|
||||
'user-1',
|
||||
),
|
||||
).rejects.toThrow('moving the apiary');
|
||||
expect(tx.colony.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
@@ -8,6 +9,8 @@ import { PrismaService } from '../prisma/prisma.service';
|
||||
import { AuditLogService } from '../audit/audit-log.service';
|
||||
import { WebhooksService } from '../webhooks/webhooks.service';
|
||||
import { DomainEventsService } from '../domain-events/domain-events.service';
|
||||
import type { AnyNewDomainEvent } from '../domain-events/domain-event-types';
|
||||
import { colonyCreatedEvent } from './colony-created-event';
|
||||
import { Colony, ColonyStatus, Prisma } from '../../generated/prisma';
|
||||
import { CreateColonyDto } from './dto/create-colony.dto';
|
||||
import { UpdateColonyDto } from './dto/update-colony.dto';
|
||||
@@ -19,9 +22,51 @@ import {
|
||||
isLivingColonyStatus,
|
||||
TERMINAL_COLONY_STATUSES,
|
||||
} from './colony-status';
|
||||
import { lockRowsForUpdate } from '../prisma/row-lock';
|
||||
import { lockRowsForShare, lockRowsForUpdate } from '../prisma/row-lock';
|
||||
import { colonyTransitionEvents, lockColony } from './colony-events';
|
||||
import { berlinToday, dayToDate } from '../common/dates';
|
||||
import { PermissionResolverService } from '../auth/permissions/permission-resolver.service';
|
||||
import {
|
||||
assertNoActiveRestriction,
|
||||
RestrictionCheck,
|
||||
RestrictionOverride,
|
||||
} from '../compliance/restricted-zone';
|
||||
import {
|
||||
apiaryChangedMeanwhile,
|
||||
NOT_OVERRIDDEN,
|
||||
overrideNote,
|
||||
overrideTrace,
|
||||
} from './restriction-override';
|
||||
|
||||
function colonyMovedEvent(
|
||||
colonyId: string,
|
||||
fromApiaryId: string,
|
||||
toApiaryId: string,
|
||||
actorUserId: string,
|
||||
): AnyNewDomainEvent<'ColonyMoved'> {
|
||||
return {
|
||||
type: 'ColonyMoved',
|
||||
aggregateType: 'Colony',
|
||||
aggregateId: colonyId,
|
||||
actorUserId,
|
||||
payload: { fromApiaryId, toApiaryId },
|
||||
};
|
||||
}
|
||||
|
||||
/** The fields update() writes: the override reason is read, never stored. */
|
||||
type ColonyPatch = Omit<UpdateColonyDto, 'restrictionOverrideReason'>;
|
||||
|
||||
/**
|
||||
* What update() hands to updateIn when it moves the colony to another apiary:
|
||||
* the apiary the unlocked read saw (the apiary rows were locked for it) and
|
||||
* the override the user may use.
|
||||
*/
|
||||
export interface ApiaryMoveGuard {
|
||||
seenApiaryId: string;
|
||||
override: RestrictionOverride;
|
||||
}
|
||||
|
||||
const OVERRIDE_PERMISSION = 'compliance:manage';
|
||||
|
||||
export interface ColonyFilter {
|
||||
status?: ColonyStatus;
|
||||
@@ -35,6 +80,7 @@ export class ColoniesService {
|
||||
private readonly auditLog: AuditLogService,
|
||||
private readonly webhooks: WebhooksService,
|
||||
private readonly events: DomainEventsService,
|
||||
private readonly permissions: PermissionResolverService,
|
||||
) {}
|
||||
|
||||
async findAll(filter: ColonyFilter = {}): Promise<Colony[]> {
|
||||
@@ -67,11 +113,14 @@ export class ColoniesService {
|
||||
// this, a colony could be created or moved into an apiary that either
|
||||
// doesn't exist (a raw Prisma FK-constraint error instead of a clean
|
||||
// 404) or is deactivated (silently orphaning the colony the same way an
|
||||
// apiary deactivated out from under an existing colony would).
|
||||
private async assertApiaryActive(apiaryId: string): Promise<void> {
|
||||
const apiary = await this.prisma.apiary.findUnique({
|
||||
where: { id: apiaryId },
|
||||
});
|
||||
// apiary deactivated out from under an existing colony would). Read inside
|
||||
// the transaction, after the apiary rows are locked (FOR SHARE): the
|
||||
// apiary cannot be deactivated before this colony path commits.
|
||||
private async assertApiaryActiveIn(
|
||||
tx: Prisma.TransactionClient,
|
||||
apiaryId: string,
|
||||
): Promise<void> {
|
||||
const apiary = await tx.apiary.findUnique({ where: { id: apiaryId } });
|
||||
if (!apiary) {
|
||||
throw new NotFoundException('Bienenstand nicht gefunden');
|
||||
}
|
||||
@@ -82,24 +131,56 @@ export class ColoniesService {
|
||||
}
|
||||
}
|
||||
|
||||
// Asked once per request, and only when a reason was sent (null counts as
|
||||
// omitted): the right to override is compliance:manage.
|
||||
private async overrideOf(
|
||||
reason: string | null | undefined,
|
||||
actingUserId: string,
|
||||
): Promise<RestrictionOverride> {
|
||||
if (!reason) {
|
||||
return { reason: null, canOverride: false };
|
||||
}
|
||||
const held = await this.permissions.getPermissions(actingUserId);
|
||||
// Spec 5.6: a reason without compliance:manage is a 403 - always, also
|
||||
// when no restriction is active. Checked before anything is read or locked.
|
||||
if (!held.has(OVERRIDE_PERMISSION)) {
|
||||
throw new ForbiddenException(
|
||||
'Eine Begründung für eine Ausnahme vom Sperrbezirk darf nur mit dem Recht Prüfbereitschaft verwalten (compliance:manage) angegeben werden.',
|
||||
);
|
||||
}
|
||||
return { reason, canOverride: true };
|
||||
}
|
||||
|
||||
async create(dto: CreateColonyDto, actingUserId: string): Promise<Colony> {
|
||||
await this.assertApiaryActive(dto.apiaryId);
|
||||
const { restrictionOverrideReason, ...data } = dto;
|
||||
const override = await this.overrideOf(
|
||||
restrictionOverrideReason,
|
||||
actingUserId,
|
||||
);
|
||||
const colony = await this.prisma.$transaction(async (tx) => {
|
||||
const created = await tx.colony.create({ data: { ...dto } });
|
||||
await lockRowsForShare(tx, 'Apiary', [data.apiaryId]);
|
||||
await this.assertApiaryActiveIn(tx, data.apiaryId);
|
||||
const check = await assertNoActiveRestriction(
|
||||
tx,
|
||||
[data.apiaryId],
|
||||
berlinToday(),
|
||||
override,
|
||||
);
|
||||
const created = await tx.colony.create({ data });
|
||||
await this.auditLog.record(
|
||||
{
|
||||
entityType: 'Colony',
|
||||
entityId: created.id,
|
||||
action: 'CREATE',
|
||||
userId: actingUserId,
|
||||
afterData: created,
|
||||
afterData: { ...created, ...overrideTrace(check, override.reason) },
|
||||
},
|
||||
tx,
|
||||
);
|
||||
await this.events.record(tx, colonyCreatedEvent(created, actingUserId));
|
||||
return created;
|
||||
});
|
||||
// No domain event for a new colony in this stage - the webhook stays on
|
||||
// the direct path.
|
||||
// The webhook stays on the direct path (the event is not forwarded).
|
||||
await this.webhooks.dispatch('colony.created', colony);
|
||||
return colony;
|
||||
}
|
||||
@@ -109,9 +190,25 @@ export class ColoniesService {
|
||||
dto: UpdateColonyDto,
|
||||
actingUserId: string,
|
||||
): Promise<Colony> {
|
||||
const { after } = await this.prisma.$transaction((tx) =>
|
||||
this.updateIn(tx, id, dto, actingUserId),
|
||||
const { restrictionOverrideReason, ...patch } = dto;
|
||||
const override = await this.overrideOf(
|
||||
restrictionOverrideReason,
|
||||
actingUserId,
|
||||
);
|
||||
const seen = await this.findById(id);
|
||||
// Only a change of the apiary involves apiaries: the old and the new one
|
||||
// are locked first (FOR SHARE, ascending), then the colony (Task 1 order).
|
||||
const movesApiary =
|
||||
patch.apiaryId !== undefined && patch.apiaryId !== seen.apiaryId;
|
||||
const { after } = await this.prisma.$transaction(async (tx) => {
|
||||
if (movesApiary) {
|
||||
await lockRowsForShare(tx, 'Apiary', [seen.apiaryId, patch.apiaryId!]);
|
||||
}
|
||||
return this.updateIn(tx, id, patch, actingUserId, {
|
||||
seenApiaryId: seen.apiaryId,
|
||||
override,
|
||||
});
|
||||
});
|
||||
return after;
|
||||
}
|
||||
|
||||
@@ -120,22 +217,44 @@ export class ColoniesService {
|
||||
* inspection handing values over to the colony card). Locks the colony row
|
||||
* and reads "before" only afterwards (404 when missing); writes the apiary
|
||||
* history, the status events and the audit entry with the change.
|
||||
*
|
||||
* It locks no apiary itself. A patch that moves the colony to another
|
||||
* apiary needs `guard`: update() has then locked both apiaries (FOR SHARE)
|
||||
* before the colony, so the restriction check and the write cannot be
|
||||
* overtaken by a restriction or a deactivation. The inspection takeover
|
||||
* passes no apiary and no guard.
|
||||
*/
|
||||
async updateIn(
|
||||
tx: Prisma.TransactionClient,
|
||||
id: string,
|
||||
dto: UpdateColonyDto,
|
||||
dto: ColonyPatch,
|
||||
actingUserId: string,
|
||||
guard?: ApiaryMoveGuard,
|
||||
): Promise<{ before: Colony; after: Colony }> {
|
||||
const before = await lockColony(tx, id);
|
||||
const today = berlinToday();
|
||||
const movesApiary =
|
||||
dto.apiaryId !== undefined && dto.apiaryId !== before.apiaryId;
|
||||
let check: RestrictionCheck = NOT_OVERRIDDEN;
|
||||
if (movesApiary) {
|
||||
await this.assertApiaryActive(dto.apiaryId!);
|
||||
if (!guard) {
|
||||
throw new Error(
|
||||
'ColoniesService.updateIn: moving the apiary needs update()',
|
||||
);
|
||||
}
|
||||
if (before.apiaryId !== guard.seenApiaryId) {
|
||||
throw apiaryChangedMeanwhile();
|
||||
}
|
||||
await this.assertApiaryActiveIn(tx, dto.apiaryId!);
|
||||
check = await assertNoActiveRestriction(
|
||||
tx,
|
||||
[before.apiaryId, dto.apiaryId!],
|
||||
today,
|
||||
guard.override,
|
||||
);
|
||||
}
|
||||
// An edit into an ended status ends the queen assignment like dissolve
|
||||
// does, before the status is written (the pointer is read under the lock).
|
||||
const today = berlinToday();
|
||||
const endsColony =
|
||||
dto.status !== undefined &&
|
||||
TERMINAL_COLONY_STATUSES.includes(dto.status) &&
|
||||
@@ -156,9 +275,17 @@ export class ColoniesService {
|
||||
colonyId: id,
|
||||
apiaryId: updated.apiaryId,
|
||||
movedByUserId: actingUserId,
|
||||
notes: 'Korrektur über Volk bearbeiten',
|
||||
notes: overrideNote(
|
||||
check,
|
||||
guard?.override.reason,
|
||||
'Korrektur über Volk bearbeiten',
|
||||
),
|
||||
},
|
||||
});
|
||||
await this.events.record(
|
||||
tx,
|
||||
colonyMovedEvent(id, before.apiaryId, updated.apiaryId, actingUserId),
|
||||
);
|
||||
}
|
||||
await this.events.recordAll(
|
||||
tx,
|
||||
@@ -175,7 +302,10 @@ export class ColoniesService {
|
||||
action: 'UPDATE',
|
||||
userId: actingUserId,
|
||||
beforeData: before,
|
||||
afterData: updated,
|
||||
afterData: {
|
||||
...updated,
|
||||
...overrideTrace(check, guard?.override.reason),
|
||||
},
|
||||
},
|
||||
tx,
|
||||
);
|
||||
@@ -187,23 +317,49 @@ export class ColoniesService {
|
||||
dto: MoveColonyDto,
|
||||
actingUserId: string,
|
||||
): Promise<Colony> {
|
||||
this.assertActive(await this.findById(id));
|
||||
await this.assertApiaryActive(dto.apiaryId);
|
||||
const { restrictionOverrideReason, ...data } = dto;
|
||||
const override = await this.overrideOf(
|
||||
restrictionOverrideReason,
|
||||
actingUserId,
|
||||
);
|
||||
const seen = await this.findById(id);
|
||||
this.assertActive(seen);
|
||||
const colony = await this.prisma.$transaction(async (tx) => {
|
||||
await lockRowsForShare(tx, 'Apiary', [seen.apiaryId, data.apiaryId]);
|
||||
const before = await lockColony(tx, id);
|
||||
this.assertActive(before);
|
||||
if (before.apiaryId !== seen.apiaryId) {
|
||||
throw apiaryChangedMeanwhile();
|
||||
}
|
||||
await this.assertApiaryActiveIn(tx, data.apiaryId);
|
||||
// A "move" within one apiary leaves the herd where it is.
|
||||
const check =
|
||||
before.apiaryId === data.apiaryId
|
||||
? NOT_OVERRIDDEN
|
||||
: await assertNoActiveRestriction(
|
||||
tx,
|
||||
[before.apiaryId, data.apiaryId],
|
||||
berlinToday(),
|
||||
override,
|
||||
);
|
||||
const updated = await tx.colony.update({
|
||||
where: { id },
|
||||
data: { apiaryId: dto.apiaryId },
|
||||
data: { apiaryId: data.apiaryId },
|
||||
});
|
||||
await tx.colonyApiaryHistory.create({
|
||||
data: {
|
||||
colonyId: id,
|
||||
apiaryId: dto.apiaryId,
|
||||
apiaryId: data.apiaryId,
|
||||
movedByUserId: actingUserId,
|
||||
notes: dto.notes,
|
||||
notes: overrideNote(check, override.reason, data.notes),
|
||||
},
|
||||
});
|
||||
if (before.apiaryId !== updated.apiaryId) {
|
||||
await this.events.record(
|
||||
tx,
|
||||
colonyMovedEvent(id, before.apiaryId, updated.apiaryId, actingUserId),
|
||||
);
|
||||
}
|
||||
await this.auditLog.record(
|
||||
{
|
||||
entityType: 'Colony',
|
||||
@@ -211,7 +367,7 @@ export class ColoniesService {
|
||||
action: 'UPDATE',
|
||||
userId: actingUserId,
|
||||
beforeData: before,
|
||||
afterData: updated,
|
||||
afterData: { ...updated, ...overrideTrace(check, override.reason) },
|
||||
},
|
||||
tx,
|
||||
);
|
||||
@@ -263,6 +419,7 @@ export class ColoniesService {
|
||||
},
|
||||
tx,
|
||||
);
|
||||
await this.events.record(tx, colonyCreatedEvent(created, actingUserId));
|
||||
await this.events.record(tx, {
|
||||
type: 'ColonySplit',
|
||||
aggregateType: 'Colony',
|
||||
@@ -285,24 +442,54 @@ export class ColoniesService {
|
||||
dto: MergeColonyDto,
|
||||
actingUserId: string,
|
||||
): Promise<Colony> {
|
||||
const { restrictionOverrideReason, ...data } = dto;
|
||||
const survivor = await this.findById(id);
|
||||
this.assertActive(survivor);
|
||||
if (dto.mergedColonyIds.includes(survivor.id)) {
|
||||
if (data.mergedColonyIds.includes(survivor.id)) {
|
||||
throw new BadRequestException(
|
||||
'Ein Volk kann nicht mit sich selbst vereinigt werden',
|
||||
);
|
||||
}
|
||||
if (new Set(dto.mergedColonyIds).size !== dto.mergedColonyIds.length) {
|
||||
if (new Set(data.mergedColonyIds).size !== data.mergedColonyIds.length) {
|
||||
throw new BadRequestException(
|
||||
'Jedes Volk darf nur einmal zur Vereinigung ausgewählt werden',
|
||||
);
|
||||
}
|
||||
const override = await this.overrideOf(
|
||||
restrictionOverrideReason,
|
||||
actingUserId,
|
||||
);
|
||||
const today = berlinToday();
|
||||
// The apiaries of the colonies as the unlocked read saw them: they are
|
||||
// locked first, and compared with the locked rows afterwards.
|
||||
const seenApiaries = new Map(
|
||||
(
|
||||
await this.prisma.colony.findMany({
|
||||
where: { id: { in: data.mergedColonyIds } },
|
||||
select: { id: true, apiaryId: true },
|
||||
})
|
||||
).map((colony) => [colony.id, colony.apiaryId]),
|
||||
);
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
await lockRowsForShare(tx, 'Apiary', [
|
||||
...new Set([survivor.apiaryId, ...seenApiaries.values()]),
|
||||
]);
|
||||
// One statement in id order, the same order bulk lockRowsForShare
|
||||
// uses: no deadlock with a concurrent bulk write.
|
||||
await lockRowsForUpdate(tx, 'Colony', dto.mergedColonyIds);
|
||||
for (const mergedColonyId of dto.mergedColonyIds) {
|
||||
await lockRowsForUpdate(tx, 'Colony', [
|
||||
survivor.id,
|
||||
...data.mergedColonyIds,
|
||||
]);
|
||||
const lockedSurvivor = await tx.colony.findUnique({ where: { id } });
|
||||
if (!lockedSurvivor) {
|
||||
throw new NotFoundException('Colony not found');
|
||||
}
|
||||
this.assertActive(lockedSurvivor);
|
||||
if (lockedSurvivor.apiaryId !== survivor.apiaryId) {
|
||||
throw apiaryChangedMeanwhile();
|
||||
}
|
||||
const mergedRows: Colony[] = [];
|
||||
for (const mergedColonyId of data.mergedColonyIds) {
|
||||
const merged = await tx.colony.findUnique({
|
||||
where: { id: mergedColonyId },
|
||||
});
|
||||
@@ -312,6 +499,22 @@ export class ColoniesService {
|
||||
);
|
||||
}
|
||||
this.assertActive(merged);
|
||||
if (seenApiaries.get(merged.id) !== merged.apiaryId) {
|
||||
throw apiaryChangedMeanwhile();
|
||||
}
|
||||
mergedRows.push(merged);
|
||||
}
|
||||
// Uniting colonies of different apiaries brings bees from one stand to
|
||||
// the other; within one apiary nothing leaves it.
|
||||
const apiaryIds = new Set([
|
||||
lockedSurvivor.apiaryId,
|
||||
...mergedRows.map((merged) => merged.apiaryId),
|
||||
]);
|
||||
const check =
|
||||
apiaryIds.size > 1
|
||||
? await assertNoActiveRestriction(tx, [...apiaryIds], today, override)
|
||||
: NOT_OVERRIDDEN;
|
||||
for (const merged of mergedRows) {
|
||||
// currentQueenId is unique across colonies - if it stayed set on
|
||||
// this now-dead colony, any later attempt to assign her queen to a
|
||||
// different colony would fail with a unique-constraint conflict.
|
||||
@@ -320,11 +523,11 @@ export class ColoniesService {
|
||||
// merge is a beekeeper decision, not one to guess here).
|
||||
const releasedQueenId = await releaseQueenIn(
|
||||
tx,
|
||||
mergedColonyId,
|
||||
merged.id,
|
||||
dayToDate(today),
|
||||
);
|
||||
const mergedAway = await tx.colony.update({
|
||||
where: { id: mergedColonyId },
|
||||
where: { id: merged.id },
|
||||
data: { status: 'MERGED', deactivatedAt: new Date() },
|
||||
});
|
||||
await this.events.recordAll(
|
||||
@@ -338,21 +541,25 @@ export class ColoniesService {
|
||||
await tx.colonyLineage.create({
|
||||
data: {
|
||||
type: 'MERGE',
|
||||
fromColonyId: mergedColonyId,
|
||||
toColonyId: survivor.id,
|
||||
fromColonyId: merged.id,
|
||||
toColonyId: lockedSurvivor.id,
|
||||
date: new Date(),
|
||||
notes: dto.notes,
|
||||
notes: data.notes,
|
||||
},
|
||||
});
|
||||
}
|
||||
await this.auditLog.record(
|
||||
{
|
||||
entityType: 'Colony',
|
||||
entityId: survivor.id,
|
||||
entityId: lockedSurvivor.id,
|
||||
action: 'UPDATE',
|
||||
userId: actingUserId,
|
||||
beforeData: survivor,
|
||||
afterData: { ...survivor, mergedColonyIds: dto.mergedColonyIds },
|
||||
beforeData: lockedSurvivor,
|
||||
afterData: {
|
||||
...lockedSurvivor,
|
||||
mergedColonyIds: data.mergedColonyIds,
|
||||
...overrideTrace(check, override.reason),
|
||||
},
|
||||
},
|
||||
tx,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { Colony } from '../../generated/prisma';
|
||||
import type { AnyNewDomainEvent } from '../domain-events/domain-event-types';
|
||||
|
||||
/**
|
||||
* The ColonyCreated event of a colony that was just written (create, split
|
||||
* child, CSV import). The caller records it in the transaction that wrote the
|
||||
* colony. Backup restore deliberately records none.
|
||||
*/
|
||||
export function colonyCreatedEvent(
|
||||
colony: Pick<Colony, 'id' | 'apiaryId'>,
|
||||
actorUserId: string,
|
||||
): AnyNewDomainEvent<'ColonyCreated'> {
|
||||
return {
|
||||
type: 'ColonyCreated',
|
||||
aggregateType: 'Colony',
|
||||
aggregateId: colony.id,
|
||||
actorUserId,
|
||||
payload: { apiaryId: colony.apiaryId },
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsEnum, IsInt, IsOptional, IsString, Max, Min } from 'class-validator';
|
||||
import { ColonyCondition, ColonyType } from '../../../generated/prisma';
|
||||
import { RestrictionOverrideReason } from './restriction-override-reason';
|
||||
|
||||
export class CreateColonyDto {
|
||||
@ApiProperty()
|
||||
@@ -67,4 +68,7 @@ export class CreateColonyDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
|
||||
@RestrictionOverrideReason()
|
||||
restrictionOverrideReason?: string | null;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { ArrayMinSize, IsArray, IsOptional, IsString } from 'class-validator';
|
||||
import { RestrictionOverrideReason } from './restriction-override-reason';
|
||||
|
||||
export class MergeColonyDto {
|
||||
@ApiProperty({ type: [String] })
|
||||
@@ -12,4 +13,7 @@ export class MergeColonyDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
|
||||
@RestrictionOverrideReason()
|
||||
restrictionOverrideReason?: string | null;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsOptional, IsString } from 'class-validator';
|
||||
import { RestrictionOverrideReason } from './restriction-override-reason';
|
||||
|
||||
export class MoveColonyDto {
|
||||
@ApiProperty()
|
||||
@@ -10,4 +11,7 @@ export class MoveColonyDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
|
||||
@RestrictionOverrideReason()
|
||||
restrictionOverrideReason?: string | null;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { applyDecorators } from '@nestjs/common';
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Transform } from 'class-transformer';
|
||||
import { IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
|
||||
|
||||
export const OVERRIDE_REASON_MIN = 10;
|
||||
export const OVERRIDE_REASON_MAX = 500;
|
||||
|
||||
/**
|
||||
* `restrictionOverrideReason`: why a colony may enter or leave an apiary in a
|
||||
* restricted zone. Only read by ColoniesService (needs compliance:manage) and
|
||||
* written to audit and apiary history - never to the colony. Trimmed before
|
||||
* the length check, so blanks do not count; null counts as omitted.
|
||||
*/
|
||||
export function RestrictionOverrideReason(): PropertyDecorator {
|
||||
return applyDecorators(
|
||||
ApiPropertyOptional({
|
||||
nullable: true,
|
||||
minLength: OVERRIDE_REASON_MIN,
|
||||
maxLength: OVERRIDE_REASON_MAX,
|
||||
description:
|
||||
'Begründung für eine Ausnahme vom Sperrbezirk (nur mit compliance:manage)',
|
||||
}),
|
||||
IsOptional(),
|
||||
Transform(({ value }: { value: unknown }) =>
|
||||
typeof value === 'string' ? value.trim() : value,
|
||||
),
|
||||
IsString(),
|
||||
MinLength(OVERRIDE_REASON_MIN),
|
||||
MaxLength(OVERRIDE_REASON_MAX),
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { IsEnum } from 'class-validator';
|
||||
import { ColonyStatus } from '../../../generated/prisma';
|
||||
import { CreateColonyDto } from './create-colony.dto';
|
||||
import { IsOptionalNotNull } from '../../common/validation/is-optional-not-null';
|
||||
import { RestrictionOverrideReason } from './restriction-override-reason';
|
||||
|
||||
/**
|
||||
* `apiaryId` is editable here too, not only through POST /colonies/:id/move:
|
||||
@@ -32,4 +33,7 @@ export class UpdateColonyDto extends UpdatableColonyFieldsDto {
|
||||
@IsOptionalNotNull()
|
||||
@IsEnum(ColonyStatus)
|
||||
status?: ColonyStatus;
|
||||
|
||||
@RestrictionOverrideReason()
|
||||
restrictionOverrideReason?: string | null;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { ConflictException } from '@nestjs/common';
|
||||
import type { RestrictionCheck } from '../compliance/restricted-zone';
|
||||
|
||||
/** 409 when the colony or an apiary changed between the unlocked read and the lock. */
|
||||
export function apiaryChangedMeanwhile(): ConflictException {
|
||||
return new ConflictException(
|
||||
'Der Stand wurde gerade geändert. Bitte neu laden.',
|
||||
);
|
||||
}
|
||||
|
||||
export const NOT_OVERRIDDEN: RestrictionCheck = {
|
||||
overridden: false,
|
||||
restrictionIds: [],
|
||||
};
|
||||
|
||||
/**
|
||||
* The audit trace of an override: only the reason and the restriction ids,
|
||||
* and only when an active restriction was really overridden. Spread into the
|
||||
* audit entry's afterData - never into data written to the colony.
|
||||
*/
|
||||
export function overrideTrace(
|
||||
check: RestrictionCheck,
|
||||
reason: string | null | undefined,
|
||||
): { restrictionOverride?: { reason: string; restrictionIds: string[] } } {
|
||||
return check.overridden && reason
|
||||
? { restrictionOverride: { reason, restrictionIds: check.restrictionIds } }
|
||||
: {};
|
||||
}
|
||||
|
||||
/** The apiary-history note: the override in front of an existing note. */
|
||||
export function overrideNote(
|
||||
check: RestrictionCheck,
|
||||
reason: string | null | undefined,
|
||||
note: string | undefined,
|
||||
): string | undefined {
|
||||
if (!check.overridden || !reason) {
|
||||
return note;
|
||||
}
|
||||
const prefix = `Ausnahme Sperrbezirk: ${reason}`;
|
||||
return note ? `${prefix}\n${note}` : prefix;
|
||||
}
|
||||
@@ -54,6 +54,18 @@ describe('legacy after-commit paths', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('apiaries.service.ts has no after-commit side effects', () => {
|
||||
for (const call of [
|
||||
'runAfterCommit(',
|
||||
'webhooks.dispatch(',
|
||||
'calendarSync.enqueue(',
|
||||
]) {
|
||||
expect(filesCalling(call)).not.toContain(
|
||||
'src/apiaries/apiaries.service.ts',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('no longer defines the removed post-commit automation wrappers (only SWARM_MOOD_HIGH and STOCK_ITEM_LOW keep one)', () => {
|
||||
const removed = [
|
||||
'evaluateInspection',
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
|
||||
/**
|
||||
* Secrets the server must read back (TOTP secrets, webhook signing secrets,
|
||||
* backup files) are encrypted with a key of their own per purpose, never
|
||||
* voice notes, backup files) are encrypted with a key of their own per purpose, never
|
||||
* with a JWT secret. Each purpose has a key ring: the current key from
|
||||
* `<VARIABLE>` seals, the previous one from `<VARIABLE>_PREVIOUS` still
|
||||
* opens, so a key can be rotated without losing data. A sealed value names
|
||||
@@ -33,13 +33,14 @@ export const ENCRYPTION_KEY_VARIABLES = {
|
||||
mfa: 'MFA_ENCRYPTION_KEY',
|
||||
webhook: 'WEBHOOK_ENCRYPTION_KEY',
|
||||
backup: 'BACKUP_ENCRYPTION_KEY',
|
||||
voice: 'VOICE_ENCRYPTION_KEY',
|
||||
} as const;
|
||||
|
||||
export type EncryptionKeyVariable =
|
||||
(typeof ENCRYPTION_KEY_VARIABLES)[keyof typeof ENCRYPTION_KEY_VARIABLES];
|
||||
|
||||
/** Purposes sealed in the `k…:` string format; backups have their own envelope (backup-crypto.ts). */
|
||||
export type SecretPurpose = 'mfa' | 'webhook';
|
||||
export type SecretPurpose = 'mfa' | 'webhook' | 'voice';
|
||||
|
||||
export interface RingKey {
|
||||
id: string;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { matchesFileSignature } from './file-signature';
|
||||
import { detectAudioType, matchesFileSignature } from './file-signature';
|
||||
|
||||
describe('matchesFileSignature', () => {
|
||||
it('accepts a buffer starting with the PNG signature', () => {
|
||||
@@ -47,3 +47,63 @@ describe('matchesFileSignature', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('detectAudioType', () => {
|
||||
it('knows EBML, OggS and ftyp and nothing else', () => {
|
||||
const webm = Buffer.from([0x1a, 0x45, 0xdf, 0xa3, 0x9f, 0x42]);
|
||||
const ogg = Buffer.concat([Buffer.from('OggS', 'ascii'), Buffer.alloc(8)]);
|
||||
const mp4 = Buffer.concat([
|
||||
Buffer.from([0x00, 0x00, 0x00, 0x20]),
|
||||
Buffer.from('ftypM4A ', 'ascii'),
|
||||
]);
|
||||
expect(detectAudioType(webm)).toBe('audio/webm');
|
||||
expect(detectAudioType(ogg)).toBe('audio/ogg');
|
||||
expect(detectAudioType(mp4)).toBe('audio/mp4');
|
||||
expect(
|
||||
detectAudioType(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a])),
|
||||
).toBeNull();
|
||||
expect(detectAudioType(Buffer.from('RIFF....WAVE', 'ascii'))).toBeNull();
|
||||
expect(detectAudioType(Buffer.from('%PDF-1.7', 'ascii'))).toBeNull();
|
||||
});
|
||||
|
||||
it.each(['heic', 'avif', 'mif1', 'qt ', '3gp4'])(
|
||||
'rejects an ftyp file with the brand %s',
|
||||
(brand) => {
|
||||
const file = Buffer.concat([
|
||||
Buffer.from([0, 0, 0, 0x20]),
|
||||
Buffer.from(`ftyp${brand}`, 'latin1'),
|
||||
]);
|
||||
expect(detectAudioType(file)).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(['M4A ', 'isom', 'iso2', 'iso6', 'mp41', 'mp42', 'dash'])(
|
||||
'accepts the audio brand %s',
|
||||
(brand) => {
|
||||
const file = Buffer.concat([
|
||||
Buffer.from([0, 0, 0, 0x20]),
|
||||
Buffer.from(`ftyp${brand}`, 'latin1'),
|
||||
]);
|
||||
expect(detectAudioType(file)).toBe('audio/mp4');
|
||||
},
|
||||
);
|
||||
|
||||
it('rejects buffers that are too short for any signature', () => {
|
||||
expect(detectAudioType(Buffer.alloc(0))).toBeNull();
|
||||
expect(detectAudioType(Buffer.from([0x1a, 0x45, 0xdf]))).toBeNull();
|
||||
expect(
|
||||
detectAudioType(Buffer.from('OggS', 'ascii').subarray(0, 3)),
|
||||
).toBeNull();
|
||||
expect(
|
||||
detectAudioType(Buffer.from([0, 0, 0, 0x20, 0x66, 0x74])),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('does not take a signature from the middle of the buffer', () => {
|
||||
const late = Buffer.concat([
|
||||
Buffer.alloc(16),
|
||||
Buffer.from('OggS', 'ascii'),
|
||||
]);
|
||||
expect(detectAudioType(late)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -33,3 +33,47 @@ export function matchesFileSignature(
|
||||
const check = SIGNATURE_CHECKS[declaredMimeType];
|
||||
return check ? check(buffer) : true;
|
||||
}
|
||||
|
||||
export type VoiceAudioMime = 'audio/webm' | 'audio/ogg' | 'audio/mp4';
|
||||
|
||||
// Major brands of MP4/M4A audio; HEIC, AVIF and other ISO-BMFF files are not.
|
||||
const MP4_AUDIO_BRANDS: ReadonlySet<string> = new Set([
|
||||
'M4A ',
|
||||
'isom',
|
||||
'iso2',
|
||||
'iso3',
|
||||
'iso4',
|
||||
'iso5',
|
||||
'iso6',
|
||||
'mp41',
|
||||
'mp42',
|
||||
'dash',
|
||||
]);
|
||||
|
||||
const EBML_MAGIC = Buffer.from([0x1a, 0x45, 0xdf, 0xa3]);
|
||||
|
||||
/**
|
||||
* Names the audio container by its first bytes - strict, unlike
|
||||
* matchesFileSignature: anything unknown is null, and the declared type of
|
||||
* the upload plays no part. EBML (WebM/Matroska), "OggS" and "ftyp" at byte 4
|
||||
* (MP4/M4A) are the containers MediaRecorder produces.
|
||||
*/
|
||||
export function detectAudioType(buffer: Buffer): VoiceAudioMime | null {
|
||||
if (buffer.length >= 4 && buffer.subarray(0, 4).equals(EBML_MAGIC)) {
|
||||
return 'audio/webm';
|
||||
}
|
||||
if (
|
||||
buffer.length >= 4 &&
|
||||
buffer.subarray(0, 4).toString('latin1') === 'OggS'
|
||||
) {
|
||||
return 'audio/ogg';
|
||||
}
|
||||
if (
|
||||
buffer.length >= 12 &&
|
||||
buffer.subarray(4, 8).toString('latin1') === 'ftyp' &&
|
||||
MP4_AUDIO_BRANDS.has(buffer.subarray(8, 12).toString('latin1'))
|
||||
) {
|
||||
return 'audio/mp4';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -12,7 +12,10 @@ import { dirname, join, resolve, sep } from 'node:path';
|
||||
* predate this guard,
|
||||
* - a *.handlers.ts file or a file under src/jobs/ imports no network
|
||||
* package and no module that itself reaches the network - checked on its
|
||||
* own, whatever the fetch rule says.
|
||||
* own, whatever the fetch rule says,
|
||||
* - the Anthropic SDK is imported by exactly one file, the voice adapter
|
||||
* (plan T7, contradiction 17); the worker reaches it only through the
|
||||
* StructuredModel port.
|
||||
*/
|
||||
const SRC = join(__dirname, '..');
|
||||
|
||||
@@ -23,7 +26,9 @@ interface SourceFile {
|
||||
|
||||
const WEATHER_HOSTS = /open-meteo\.com/i;
|
||||
const TELEGRAM_HOST = /api\.telegram\.org/i;
|
||||
const FETCH_USE = /(?<![\w$.])fetch\b(?!\s*:)|\bglobalThis\s*\.\s*fetch\b/;
|
||||
// `--phase=fetch` is the argument of the voice job, not a network call.
|
||||
const FETCH_USE =
|
||||
/(?<![\w$.])(?<!['"`]--phase=)fetch\b(?!\s*:)|\bglobalThis\s*\.\s*fetch\b/;
|
||||
const NETWORK_PACKAGES = new Set([
|
||||
'http',
|
||||
'https',
|
||||
@@ -32,14 +37,35 @@ const NETWORK_PACKAGES = new Set([
|
||||
'got',
|
||||
'node-fetch',
|
||||
]);
|
||||
const ANTHROPIC_SDK = '@anthropic-ai/sdk';
|
||||
const ANTHROPIC_ADAPTER = 'voice/extraction/anthropic-structured-model.ts';
|
||||
const IMPORT_SPECIFIER =
|
||||
/(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)['"]([^'"]+)['"]/g;
|
||||
/(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)(['"`])([^'"`]+)\1/g;
|
||||
// The files that may (transitively) import the Anthropic adapter.
|
||||
const ADAPTER_WIRING_FILES = [
|
||||
'voice/voice-worker.module.ts',
|
||||
'all-in-one.module.ts',
|
||||
'main.ts',
|
||||
'worker.ts',
|
||||
'runtime/root-module.ts',
|
||||
];
|
||||
const ADAPTER_WIRING_DIRECTORIES = ['worker/'];
|
||||
/**
|
||||
* Handlers that reach a network module only indirectly, through a service
|
||||
* whose network part runs elsewhere. A direct import of a network file is
|
||||
* never excused.
|
||||
*/
|
||||
const INDIRECT_NETWORK_EXCEPTIONS: Readonly<Record<string, string>> = {
|
||||
'calendar-sync/calendar-sync.handlers.ts':
|
||||
'calls only CalendarSyncService.enqueueIn(tx, ...); Graph calls run in the worker loop',
|
||||
};
|
||||
|
||||
const ALLOWED_DIRECTORIES = ['weather/', 'telegram/'];
|
||||
// Files that reach the network and predate the guard.
|
||||
const ALLOWED_FILES = [
|
||||
'calendar-sync/graph-client.service.ts',
|
||||
'common/password/password-policy.ts',
|
||||
ANTHROPIC_ADAPTER,
|
||||
'webhooks/webhook-delivery.ts',
|
||||
'worker/worker-health.ts',
|
||||
'worker/worker-health-server.service.ts',
|
||||
@@ -69,12 +95,21 @@ function sourceFiles(): SourceFile[] {
|
||||
});
|
||||
}
|
||||
|
||||
function isAnthropicSdk(specifier: string): boolean {
|
||||
return (
|
||||
specifier === ANTHROPIC_SDK || specifier.startsWith(`${ANTHROPIC_SDK}/`)
|
||||
);
|
||||
}
|
||||
|
||||
function isNetworkPackage(specifier: string): boolean {
|
||||
return NETWORK_PACKAGES.has(specifier.replace(/^node:/, ''));
|
||||
return (
|
||||
NETWORK_PACKAGES.has(specifier.replace(/^node:/, '')) ||
|
||||
isAnthropicSdk(specifier)
|
||||
);
|
||||
}
|
||||
|
||||
function importsOf(source: string): string[] {
|
||||
return [...source.matchAll(IMPORT_SPECIFIER)].map((match) => match[1]);
|
||||
return [...source.matchAll(IMPORT_SPECIFIER)].map((match) => match[2]);
|
||||
}
|
||||
|
||||
function inAllowedPlace(path: string): boolean {
|
||||
@@ -109,15 +144,60 @@ function resolveImport(
|
||||
.find((candidate) => known.has(candidate));
|
||||
}
|
||||
|
||||
/**
|
||||
* The seeds plus every file that reaches one of them through relative
|
||||
* imports, however many steps away.
|
||||
*/
|
||||
function reachingClosure(
|
||||
files: readonly SourceFile[],
|
||||
seeds: Iterable<string>,
|
||||
): Set<string> {
|
||||
const known = new Set(files.map((file) => file.path));
|
||||
const reaching = new Set(seeds);
|
||||
let grew = true;
|
||||
while (grew) {
|
||||
grew = false;
|
||||
for (const { path, source } of files) {
|
||||
if (reaching.has(path)) {
|
||||
continue;
|
||||
}
|
||||
const reachesSeed = importsOf(source).some((specifier) => {
|
||||
const target = resolveImport(path, specifier, known);
|
||||
return target !== undefined && reaching.has(target);
|
||||
});
|
||||
if (reachesSeed) {
|
||||
reaching.add(path);
|
||||
grew = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return reaching;
|
||||
}
|
||||
|
||||
function isAdapterWiring(path: string): boolean {
|
||||
return (
|
||||
path === ANTHROPIC_ADAPTER ||
|
||||
ADAPTER_WIRING_FILES.includes(path) ||
|
||||
ADAPTER_WIRING_DIRECTORIES.some((directory) => path.startsWith(directory))
|
||||
);
|
||||
}
|
||||
|
||||
/** Where the code breaks the rule; empty when it keeps it. */
|
||||
function violations(rawFiles: readonly SourceFile[]): string[] {
|
||||
const files = rawFiles.map(({ path, source }) => ({
|
||||
path,
|
||||
source: withoutComments(source),
|
||||
}));
|
||||
const networkFiles = new Set(
|
||||
const directNetworkFiles = new Set(
|
||||
files.filter(reachesNetwork).map((file) => file.path),
|
||||
);
|
||||
const networkFiles = reachingClosure(files, directNetworkFiles);
|
||||
const adapterReachers = reachingClosure(
|
||||
files,
|
||||
files.some((file) => file.path === ANTHROPIC_ADAPTER)
|
||||
? [ANTHROPIC_ADAPTER]
|
||||
: [],
|
||||
);
|
||||
return files.flatMap(({ path, source }) => {
|
||||
const found: string[] = [];
|
||||
if (WEATHER_HOSTS.test(source) && !path.startsWith('weather/')) {
|
||||
@@ -133,6 +213,16 @@ function violations(rawFiles: readonly SourceFile[]): string[] {
|
||||
if (specifiers.some(isNetworkPackage) && !inAllowedPlace(path)) {
|
||||
found.push(`${path}: network package import outside the allowed places`);
|
||||
}
|
||||
if (specifiers.some(isAnthropicSdk) && path !== ANTHROPIC_ADAPTER) {
|
||||
found.push(
|
||||
`${path}: ${ANTHROPIC_SDK} imported outside the voice adapter`,
|
||||
);
|
||||
}
|
||||
if (adapterReachers.has(path) && !isAdapterWiring(path)) {
|
||||
found.push(
|
||||
`${path}: reaches the Anthropic adapter outside the worker wiring`,
|
||||
);
|
||||
}
|
||||
if (isHandlerOrJob(path)) {
|
||||
if (FETCH_USE.test(source)) {
|
||||
found.push(`${path}: fetch in a handler or job`);
|
||||
@@ -140,11 +230,14 @@ function violations(rawFiles: readonly SourceFile[]): string[] {
|
||||
if (specifiers.some(isNetworkPackage)) {
|
||||
found.push(`${path}: network package imported by a handler or job`);
|
||||
}
|
||||
if (
|
||||
const importsAny = (targets: ReadonlySet<string>): boolean =>
|
||||
specifiers.some(
|
||||
(specifier) =>
|
||||
resolveImport(path, specifier, networkFiles) !== undefined,
|
||||
)
|
||||
(specifier) => resolveImport(path, specifier, targets) !== undefined,
|
||||
);
|
||||
if (
|
||||
importsAny(directNetworkFiles) ||
|
||||
(importsAny(networkFiles) &&
|
||||
!Object.hasOwn(INDIRECT_NETWORK_EXCEPTIONS, path))
|
||||
) {
|
||||
found.push(
|
||||
`${path}: handler or job imports a module that reaches the network`,
|
||||
@@ -177,9 +270,24 @@ describe('network calls stay inside their loop directories', () => {
|
||||
expect(existsSync(join(SRC, 'jobs'))).toBe(true);
|
||||
});
|
||||
|
||||
it('@anthropic-ai/sdk is imported only by anthropic-structured-model.ts', () => {
|
||||
const importers = sourceFiles()
|
||||
.filter(({ source }) =>
|
||||
importsOf(withoutComments(source)).some(isAnthropicSdk),
|
||||
)
|
||||
.map((file) => file.path);
|
||||
|
||||
expect(importers).toEqual([ANTHROPIC_ADAPTER]);
|
||||
});
|
||||
|
||||
describe('with planted violations', () => {
|
||||
it.each([
|
||||
['colonies/colonies.service.ts', 'await fetch(url);'],
|
||||
[
|
||||
'colonies/colonies.service.ts',
|
||||
"const a = '--phase=fetch'; await fetch(url);",
|
||||
],
|
||||
['colonies/colonies.service.ts', 'const a = --phase=fetch;'],
|
||||
['colonies/colonies.service.ts', 'const f = fetch;'],
|
||||
['colonies/colonies.service.ts', 'await globalThis.fetch(url);'],
|
||||
['colonies/colonies.service.ts', "import https from 'node:https';"],
|
||||
@@ -209,6 +317,26 @@ describe('network calls stay inside their loop directories', () => {
|
||||
'weather/weather.service.ts',
|
||||
"const u = 'https://api.telegram.org/bot';",
|
||||
],
|
||||
[
|
||||
'weather/weather.service.ts',
|
||||
"import Anthropic from '@anthropic-ai/sdk';",
|
||||
],
|
||||
[
|
||||
'voice/extraction/voice-extraction.service.ts',
|
||||
"import Anthropic from '@anthropic-ai/sdk';",
|
||||
],
|
||||
[
|
||||
'voice/extraction/voice-prompt.ts',
|
||||
"const m = require('@anthropic-ai/sdk/resources');",
|
||||
],
|
||||
[
|
||||
'voice/voice.handlers.ts',
|
||||
"import { APIError } from '@anthropic-ai/sdk';",
|
||||
],
|
||||
[
|
||||
'jobs/voice-transcribe.job.ts',
|
||||
"const s = await import('@anthropic-ai/sdk');",
|
||||
],
|
||||
])('flags %s: %s', (path, source) => {
|
||||
expect(violations([{ path, source }])).not.toEqual([]);
|
||||
});
|
||||
@@ -233,7 +361,160 @@ describe('network calls stay inside their loop directories', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('flags a handler or job importing the voice adapter', () => {
|
||||
const adapter = {
|
||||
path: ANTHROPIC_ADAPTER,
|
||||
source: "import Anthropic from '@anthropic-ai/sdk';",
|
||||
};
|
||||
const importers = [
|
||||
{
|
||||
path: 'voice/voice.handlers.ts',
|
||||
source:
|
||||
"import { AnthropicStructuredModel } from './extraction/anthropic-structured-model';",
|
||||
},
|
||||
{
|
||||
path: 'jobs/voice-transcribe.job.ts',
|
||||
source:
|
||||
"import { AnthropicStructuredModel } from '../voice/extraction/anthropic-structured-model';",
|
||||
},
|
||||
];
|
||||
expect(violations([adapter, ...importers])).toEqual(
|
||||
importers.flatMap(({ path }) => [
|
||||
`${path}: reaches the Anthropic adapter outside the worker wiring`,
|
||||
`${path}: handler or job imports a module that reaches the network`,
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it('flags a job reaching the adapter through the worker wiring', () => {
|
||||
const files = [
|
||||
{
|
||||
path: ANTHROPIC_ADAPTER,
|
||||
source: "import Anthropic from '@anthropic-ai/sdk';",
|
||||
},
|
||||
{
|
||||
path: 'voice/voice-worker.module.ts',
|
||||
source:
|
||||
"import { AnthropicStructuredModel } from './extraction/anthropic-structured-model';",
|
||||
},
|
||||
{
|
||||
path: 'jobs/voice-transcribe.job.ts',
|
||||
source:
|
||||
"import { VoiceWorkerModule } from '../voice/voice-worker.module';",
|
||||
},
|
||||
];
|
||||
|
||||
expect(violations(files)).toEqual([
|
||||
'jobs/voice-transcribe.job.ts: reaches the Anthropic adapter outside the worker wiring',
|
||||
'jobs/voice-transcribe.job.ts: handler or job imports a module that reaches the network',
|
||||
]);
|
||||
});
|
||||
|
||||
it('flags the API side reaching the adapter, but not the worker wiring', () => {
|
||||
const files = [
|
||||
{
|
||||
path: ANTHROPIC_ADAPTER,
|
||||
source: "import Anthropic from '@anthropic-ai/sdk';",
|
||||
},
|
||||
{
|
||||
path: 'voice/voice-worker.module.ts',
|
||||
source:
|
||||
"import { AnthropicStructuredModel } from './extraction/anthropic-structured-model';",
|
||||
},
|
||||
{
|
||||
path: 'worker/worker-runtime.module.ts',
|
||||
source:
|
||||
"import { VoiceWorkerModule } from '../voice/voice-worker.module';",
|
||||
},
|
||||
{
|
||||
path: 'voice/voice.module.ts',
|
||||
source: "import { VoiceWorkerModule } from './voice-worker.module';",
|
||||
},
|
||||
{
|
||||
path: 'app.module.ts',
|
||||
source: "import { VoiceModule } from './voice/voice.module';",
|
||||
},
|
||||
];
|
||||
|
||||
expect(violations(files)).toEqual([
|
||||
'voice/voice.module.ts: reaches the Anthropic adapter outside the worker wiring',
|
||||
'app.module.ts: reaches the Anthropic adapter outside the worker wiring',
|
||||
]);
|
||||
});
|
||||
|
||||
it('flags a handler reaching the network over several imports', () => {
|
||||
const files = [
|
||||
{ path: 'weather/weather.service.ts', source: 'await fetch(url);' },
|
||||
{
|
||||
path: 'colonies/colony-weather.ts',
|
||||
source:
|
||||
"import { WeatherService } from '../weather/weather.service';",
|
||||
},
|
||||
{
|
||||
path: 'colonies/colony-facts.ts',
|
||||
source: "export * from './colony-weather';",
|
||||
},
|
||||
{
|
||||
path: 'colonies/colonies.handlers.ts',
|
||||
source: "import { facts } from './colony-facts';",
|
||||
},
|
||||
];
|
||||
|
||||
expect(violations(files)).toEqual([
|
||||
'colonies/colonies.handlers.ts: handler or job imports a module that reaches the network',
|
||||
]);
|
||||
});
|
||||
|
||||
it('reads import specifiers in backticks', () => {
|
||||
const files = [
|
||||
{ path: 'weather/weather.service.ts', source: 'await fetch(url);' },
|
||||
{
|
||||
path: 'jobs/daily-evaluation.job.ts',
|
||||
source: 'const w = await import(`../weather/weather.service`);',
|
||||
},
|
||||
{
|
||||
path: 'colonies/colonies.service.ts',
|
||||
source: 'const h = require(`node:https`);',
|
||||
},
|
||||
];
|
||||
|
||||
expect(violations(files)).toEqual([
|
||||
'jobs/daily-evaluation.job.ts: handler or job imports a module that reaches the network',
|
||||
'colonies/colonies.service.ts: network package import outside the allowed places',
|
||||
]);
|
||||
});
|
||||
|
||||
it('excuses a listed handler only for an indirect path', () => {
|
||||
const graph = {
|
||||
path: 'calendar-sync/graph-client.service.ts',
|
||||
source: 'await fetch(url);',
|
||||
};
|
||||
const service = {
|
||||
path: 'calendar-sync/calendar-sync.service.ts',
|
||||
source: "import { GraphClient } from './graph-client.service';",
|
||||
};
|
||||
const indirect = {
|
||||
path: 'calendar-sync/calendar-sync.handlers.ts',
|
||||
source:
|
||||
"import { CalendarSyncService } from './calendar-sync.service';",
|
||||
};
|
||||
const direct = {
|
||||
...indirect,
|
||||
source: "import { GraphClient } from './graph-client.service';",
|
||||
};
|
||||
|
||||
expect(violations([graph, service, indirect])).toEqual([]);
|
||||
expect(violations([graph, service, direct])).toEqual([
|
||||
'calendar-sync/calendar-sync.handlers.ts: handler or job imports a module that reaches the network',
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[ANTHROPIC_ADAPTER, "import Anthropic from '@anthropic-ai/sdk';"],
|
||||
[
|
||||
'voice/extraction/voice-extraction.service.ts',
|
||||
"import { STRUCTURED_MODEL } from './structured-model.port';",
|
||||
],
|
||||
[
|
||||
'weather/weather.service.ts',
|
||||
"await fetch('https://api.open-meteo.com/v1');",
|
||||
@@ -248,6 +529,7 @@ describe('network calls stay inside their loop directories', () => {
|
||||
['colonies/colonies.service.ts', '// fetch the data later\nconst a = 1;'],
|
||||
['colonies/colonies.service.ts', "const scheme = 'https';"],
|
||||
['colonies/colonies.service.ts', 'const o = { fetch: 1 };'],
|
||||
['jobs/job-names.ts', "const a = ['--phase=fetch', '--phase=ingest'];"],
|
||||
])('lets %s pass: %s', (path, source) => {
|
||||
expect(violations([{ path, source }])).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { roundToThousandths } from './quantity';
|
||||
|
||||
describe('roundToThousandths', () => {
|
||||
it('rounds to thousandths', () => {
|
||||
expect(roundToThousandths(0.0004)).toBe(0);
|
||||
});
|
||||
|
||||
it('keeps 1.2345 as 1.235 (half up)', () => {
|
||||
expect(roundToThousandths(1.2345)).toBe(1.235);
|
||||
});
|
||||
|
||||
it('rounds ties towards +Infinity and never returns -0', () => {
|
||||
expect(roundToThousandths(-0.0005)).toBe(0);
|
||||
expect(Object.is(roundToThousandths(-0.0005), 0)).toBe(true);
|
||||
expect(Object.is(roundToThousandths(-0.0004), 0)).toBe(true);
|
||||
expect(roundToThousandths(1.2345)).toBe(1.235);
|
||||
expect(roundToThousandths(-1.2345)).toBe(-1.234);
|
||||
});
|
||||
|
||||
it('cleans float noise of a sum', () => {
|
||||
expect(roundToThousandths(0.1 + 0.2)).toBe(0.3);
|
||||
});
|
||||
|
||||
it('keeps negative values', () => {
|
||||
expect(roundToThousandths(-3.3333)).toBe(-3.333);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Quantities (kilograms of honey, millilitres of a medicine, ...) are kept on
|
||||
* a grid of thousandths, so sums of floats compare and print cleanly.
|
||||
*/
|
||||
export function roundToThousandths(value: number): number {
|
||||
// `+ 0` turns -0 (a tiny negative value) into 0.
|
||||
return Math.round(value * 1000) / 1000 + 0;
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import {
|
||||
DEFAULT_RETRY_POLICY,
|
||||
MAX_ATTEMPTS,
|
||||
RETRY_DELAYS_MS,
|
||||
retryDelayMs,
|
||||
retryDelayMsFor,
|
||||
STALE_CLAIM_MS,
|
||||
} from './retry-policy';
|
||||
|
||||
@@ -26,4 +28,29 @@ describe('retry policy', () => {
|
||||
expect(() => retryDelayMs(attempts)).toThrow(RangeError);
|
||||
},
|
||||
);
|
||||
|
||||
it('keeps retryDelayMs identical to the default policy', () => {
|
||||
expect(DEFAULT_RETRY_POLICY).toEqual({
|
||||
delaysMs: RETRY_DELAYS_MS,
|
||||
maxAttempts: MAX_ATTEMPTS,
|
||||
staleClaimMs: STALE_CLAIM_MS,
|
||||
});
|
||||
for (const attempts of [1, 2, 3, 4, 5, 6, 9]) {
|
||||
expect(retryDelayMsFor(DEFAULT_RETRY_POLICY, attempts)).toBe(
|
||||
retryDelayMs(attempts),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("retryDelayMsFor uses the policy's delays and repeats the last one", () => {
|
||||
const policy = {
|
||||
delaysMs: [1_000, 5_000],
|
||||
maxAttempts: 4,
|
||||
staleClaimMs: 60_000,
|
||||
};
|
||||
expect([1, 2, 3].map((n) => retryDelayMsFor(policy, n))).toEqual([
|
||||
1_000, 5_000, 5_000,
|
||||
]);
|
||||
expect(() => retryDelayMsFor(policy, 0)).toThrow(RangeError);
|
||||
});
|
||||
});
|
||||
@@ -12,12 +12,36 @@ export const RETRY_DELAYS_MS = [
|
||||
export const MAX_ATTEMPTS = 8;
|
||||
export const STALE_CLAIM_MS = 300_000;
|
||||
|
||||
/** Delay after `attempts` failed attempts (1 = the first failure). */
|
||||
export function retryDelayMs(attempts: number): number {
|
||||
/**
|
||||
* A retry rule as data, for queues with their own pace (voice notes: 3
|
||||
* attempts, minutes instead of hours). `delaysMs[n - 1]` is the wait after
|
||||
* the n-th failure, the last entry repeats; the `maxAttempts`-th failure
|
||||
* ends in FAILED; a claim older than `staleClaimMs` belongs to a dead worker.
|
||||
*/
|
||||
export interface RetryPolicy {
|
||||
readonly delaysMs: readonly number[];
|
||||
readonly maxAttempts: number;
|
||||
readonly staleClaimMs: number;
|
||||
}
|
||||
|
||||
/** The rule of the outboxes (the constants above). */
|
||||
export const DEFAULT_RETRY_POLICY: RetryPolicy = {
|
||||
delaysMs: RETRY_DELAYS_MS,
|
||||
maxAttempts: MAX_ATTEMPTS,
|
||||
staleClaimMs: STALE_CLAIM_MS,
|
||||
};
|
||||
|
||||
/** Delay after `attempts` failed attempts (1 = the first failure) under `policy`. */
|
||||
export function retryDelayMsFor(policy: RetryPolicy, attempts: number): number {
|
||||
if (!Number.isInteger(attempts) || attempts < 1) {
|
||||
throw new RangeError(
|
||||
`Retry delay needs a positive number of failed attempts, got ${attempts}`,
|
||||
);
|
||||
}
|
||||
return RETRY_DELAYS_MS[Math.min(attempts, RETRY_DELAYS_MS.length) - 1];
|
||||
return policy.delaysMs[Math.min(attempts, policy.delaysMs.length) - 1];
|
||||
}
|
||||
|
||||
/** Delay after `attempts` failed attempts (1 = the first failure). */
|
||||
export function retryDelayMs(attempts: number): number {
|
||||
return retryDelayMsFor(DEFAULT_RETRY_POLICY, attempts);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ export const WAKE_CHANNELS = {
|
||||
calendarSync: 'calendar_sync',
|
||||
webhookDeliveries: 'webhook_delivery',
|
||||
notificationDeliveries: 'notification_delivery',
|
||||
voiceExtraction: 'voice_extraction',
|
||||
} as const;
|
||||
|
||||
export type WakeChannel = (typeof WAKE_CHANNELS)[keyof typeof WAKE_CHANNELS];
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { AuditLogService } from '../audit/audit-log.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { AuthorityNoticesService } from './authority-notices.service';
|
||||
|
||||
function notice(patch: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'n1',
|
||||
kind: 'HERD_CHANGE',
|
||||
status: 'DRAFT',
|
||||
year: null,
|
||||
referenceDate: new Date('2027-01-01T00:00:00.000Z'),
|
||||
countedAt: new Date('2027-01-02T10:00:00.000Z'),
|
||||
snapshot: { version: 1, apiaries: [], totalLiving: 0 },
|
||||
totalColonies: 0,
|
||||
sentOn: null,
|
||||
createdAt: new Date('2027-01-02T10:00:00.000Z'),
|
||||
updatedAt: new Date('2027-01-03T10:00:00.000Z'),
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
describe('AuthorityNoticesService.pdf', () => {
|
||||
let service: AuthorityNoticesService;
|
||||
let prisma: {
|
||||
authorityNotice: { findUnique: jest.Mock; findFirst: jest.Mock };
|
||||
siteSettings: { findUnique: jest.Mock };
|
||||
complianceSettings: { findUnique: jest.Mock };
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
prisma = {
|
||||
authorityNotice: {
|
||||
findUnique: jest.fn().mockResolvedValue(notice()),
|
||||
findFirst: jest.fn().mockResolvedValue(null),
|
||||
},
|
||||
siteSettings: { findUnique: jest.fn().mockResolvedValue(null) },
|
||||
complianceSettings: {
|
||||
findUnique: jest.fn().mockResolvedValue({
|
||||
id: 'singleton',
|
||||
veterinaryOfficeName: null,
|
||||
veterinaryOfficeAddress: null,
|
||||
registrationNumber: null,
|
||||
tskMemberNumber: null,
|
||||
}),
|
||||
},
|
||||
};
|
||||
service = new AuthorityNoticesService(
|
||||
prisma as unknown as PrismaService,
|
||||
{ record: jest.fn() } as unknown as AuditLogService,
|
||||
);
|
||||
});
|
||||
|
||||
it('renders a PDF named after the id only, even with every particular missing', async () => {
|
||||
const result = await service.pdf('n1');
|
||||
|
||||
expect(result.fileName).toBe('anzeige-n1.pdf');
|
||||
expect(result.buffer.subarray(0, 4).toString('latin1')).toBe('%PDF');
|
||||
});
|
||||
|
||||
it('compares a draft change notice with the newest sent notice', async () => {
|
||||
await service.pdf('n1');
|
||||
|
||||
expect(prisma.authorityNotice.findFirst).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: {
|
||||
status: 'SENT',
|
||||
kind: { in: ['REGISTRATION', 'HERD_CHANGE'] },
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('compares a sent change notice with the one sent before it', async () => {
|
||||
const sentOn = new Date('2027-02-01T00:00:00.000Z');
|
||||
prisma.authorityNotice.findUnique.mockResolvedValue(
|
||||
notice({ status: 'SENT', sentOn }),
|
||||
);
|
||||
|
||||
await service.pdf('n1');
|
||||
|
||||
const call = prisma.authorityNotice.findFirst.mock.calls[0] as [
|
||||
{ where: { id: unknown; OR: unknown[] } },
|
||||
];
|
||||
expect(call[0].where.id).toEqual({ not: 'n1' });
|
||||
expect(call[0].where.OR).toContainEqual({ sentOn: { lt: sentOn } });
|
||||
});
|
||||
|
||||
it('looks for no baseline for a first notice', async () => {
|
||||
prisma.authorityNotice.findUnique.mockResolvedValue(
|
||||
notice({ kind: 'REGISTRATION' }),
|
||||
);
|
||||
|
||||
await service.pdf('n1');
|
||||
|
||||
expect(prisma.authorityNotice.findFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('answers 404 for an unknown id', async () => {
|
||||
prisma.authorityNotice.findUnique.mockResolvedValue(null);
|
||||
|
||||
await expect(service.pdf('x')).rejects.toBeInstanceOf(NotFoundException);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
Res,
|
||||
} from '@nestjs/common';
|
||||
import type { Response } from 'express';
|
||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
import { RequirePermission } from '../auth/decorators/require-permission.decorator';
|
||||
import type { AuthenticatedUser } from '../auth/types/authenticated-user';
|
||||
import { Idempotent } from '../common/idempotency/idempotent.decorator';
|
||||
import { AuthorityNoticesService } from './authority-notices.service';
|
||||
import { CreateAuthorityNoticeDto } from './dto/create-authority-notice.dto';
|
||||
import { MarkSentDto } from './dto/mark-sent.dto';
|
||||
import { NoticeListQuery } from './dto/notice-list-query.dto';
|
||||
import { UpdateAuthorityNoticeDto } from './dto/update-authority-notice.dto';
|
||||
|
||||
@ApiTags('authority-notices')
|
||||
@ApiBearerAuth()
|
||||
@Controller('authority-notices')
|
||||
export class AuthorityNoticesController {
|
||||
constructor(private readonly notices: AuthorityNoticesService) {}
|
||||
|
||||
@RequirePermission('compliance:read')
|
||||
@Get()
|
||||
findAll(@Query() query: NoticeListQuery) {
|
||||
return this.notices.findAll(query);
|
||||
}
|
||||
|
||||
@RequirePermission('compliance:read')
|
||||
@Get(':id')
|
||||
findOne(@Param('id') id: string) {
|
||||
return this.notices.findOne(id);
|
||||
}
|
||||
|
||||
@RequirePermission('compliance:read')
|
||||
@Get(':id/pdf')
|
||||
async pdf(@Param('id') id: string, @Res() res: Response): Promise<void> {
|
||||
const { buffer, fileName } = await this.notices.pdf(id);
|
||||
res.setHeader('Content-Type', 'application/pdf');
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
|
||||
res.send(buffer);
|
||||
}
|
||||
|
||||
@RequirePermission('compliance:manage')
|
||||
@Idempotent()
|
||||
@Post()
|
||||
create(
|
||||
@Body() dto: CreateAuthorityNoticeDto,
|
||||
@CurrentUser() actor: AuthenticatedUser,
|
||||
) {
|
||||
return this.notices.create(dto, actor.id);
|
||||
}
|
||||
|
||||
@RequirePermission('compliance:manage')
|
||||
@Patch(':id')
|
||||
update(
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateAuthorityNoticeDto,
|
||||
@CurrentUser() actor: AuthenticatedUser,
|
||||
) {
|
||||
return this.notices.update(id, dto, actor.id);
|
||||
}
|
||||
|
||||
@RequirePermission('compliance:manage')
|
||||
@Post(':id/recount')
|
||||
recount(@Param('id') id: string, @CurrentUser() actor: AuthenticatedUser) {
|
||||
return this.notices.recount(id, actor.id);
|
||||
}
|
||||
|
||||
@RequirePermission('compliance:manage')
|
||||
@Post(':id/mark-sent')
|
||||
markSent(
|
||||
@Param('id') id: string,
|
||||
@Body() dto: MarkSentDto,
|
||||
@CurrentUser() actor: AuthenticatedUser,
|
||||
) {
|
||||
return this.notices.markSent(id, dto, actor.id);
|
||||
}
|
||||
|
||||
@RequirePermission('compliance:manage')
|
||||
@Post(':id/reopen')
|
||||
reopen(@Param('id') id: string, @CurrentUser() actor: AuthenticatedUser) {
|
||||
return this.notices.reopen(id, actor.id);
|
||||
}
|
||||
|
||||
@RequirePermission('compliance:manage')
|
||||
@Post(':id/cancel')
|
||||
cancel(@Param('id') id: string, @CurrentUser() actor: AuthenticatedUser) {
|
||||
return this.notices.cancel(id, actor.id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,617 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { Prisma } from '../../generated/prisma';
|
||||
import { AuditLogService } from '../audit/audit-log.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { lockRowForUpdate } from '../prisma/row-lock';
|
||||
import { AuthorityNoticesService } from './authority-notices.service';
|
||||
|
||||
jest.mock('../prisma/row-lock', () => ({
|
||||
lockRowForUpdate: jest.fn().mockResolvedValue(true),
|
||||
}));
|
||||
|
||||
const lockMock = lockRowForUpdate as jest.Mock;
|
||||
|
||||
const SETTINGS = {
|
||||
id: 'singleton',
|
||||
tskExcludedColonyTypes: [] as string[],
|
||||
};
|
||||
|
||||
function notice(patch: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'n1',
|
||||
kind: 'HERD_CHANGE',
|
||||
status: 'DRAFT',
|
||||
year: null,
|
||||
referenceDate: new Date('2027-01-01T00:00:00.000Z'),
|
||||
countedAt: new Date('2027-01-01T10:00:00.000Z'),
|
||||
snapshot: { version: 1, apiaries: [], totalLiving: 2 },
|
||||
totalColonies: 2,
|
||||
sentOn: null,
|
||||
sentVia: null,
|
||||
reference: null,
|
||||
notes: null,
|
||||
openKey: 'HERD_CHANGE',
|
||||
createdByUserId: 'u1',
|
||||
createdAt: new Date(0),
|
||||
updatedAt: new Date(0),
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
function p2002(): Prisma.PrismaClientKnownRequestError {
|
||||
return new Prisma.PrismaClientKnownRequestError('unique', {
|
||||
code: 'P2002',
|
||||
clientVersion: 'test',
|
||||
});
|
||||
}
|
||||
|
||||
describe('AuthorityNoticesService', () => {
|
||||
let service: AuthorityNoticesService;
|
||||
let tx: {
|
||||
complianceSettings: { upsert: jest.Mock; findUniqueOrThrow: jest.Mock };
|
||||
authorityNotice: {
|
||||
findFirst: jest.Mock;
|
||||
findUnique: jest.Mock;
|
||||
findMany: jest.Mock;
|
||||
create: jest.Mock;
|
||||
update: jest.Mock;
|
||||
};
|
||||
apiary: { findMany: jest.Mock };
|
||||
};
|
||||
let prisma: {
|
||||
$transaction: jest.Mock;
|
||||
authorityNotice: { findFirst: jest.Mock; findMany: jest.Mock };
|
||||
};
|
||||
let auditLog: { record: jest.Mock };
|
||||
|
||||
// The baseline lookup and the open-draft lookup both use findFirst: the
|
||||
// helper answers by the where clause.
|
||||
function stubLookups(opts: {
|
||||
baseline?: unknown;
|
||||
openDraft?: unknown;
|
||||
}): void {
|
||||
tx.authorityNotice.findFirst.mockImplementation(
|
||||
({ where }: { where: { openKey?: string; status?: string } }) =>
|
||||
Promise.resolve(
|
||||
where.openKey !== undefined
|
||||
? (opts.openDraft ?? null)
|
||||
: (opts.baseline ?? null),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
lockMock.mockReset().mockResolvedValue(true);
|
||||
tx = {
|
||||
complianceSettings: {
|
||||
upsert: jest.fn().mockResolvedValue(SETTINGS),
|
||||
findUniqueOrThrow: jest.fn().mockResolvedValue(SETTINGS),
|
||||
},
|
||||
authorityNotice: {
|
||||
findFirst: jest.fn().mockResolvedValue(null),
|
||||
findUnique: jest.fn().mockResolvedValue(notice()),
|
||||
findMany: jest.fn().mockResolvedValue([]),
|
||||
create: jest
|
||||
.fn()
|
||||
.mockImplementation(({ data }: { data: object }) =>
|
||||
Promise.resolve(notice(data as Record<string, unknown>)),
|
||||
),
|
||||
update: jest
|
||||
.fn()
|
||||
.mockImplementation(({ data }: { data: object }) =>
|
||||
Promise.resolve(notice(data as Record<string, unknown>)),
|
||||
),
|
||||
},
|
||||
apiary: {
|
||||
findMany: jest.fn().mockResolvedValue([
|
||||
{
|
||||
id: 'a1',
|
||||
name: 'Stand 1',
|
||||
address: null,
|
||||
location: null,
|
||||
latitude: null,
|
||||
longitude: null,
|
||||
colonies: [
|
||||
{ colonyType: 'PRODUCTION_COLONY' },
|
||||
{ colonyType: 'NUCLEUS_COLONY' },
|
||||
],
|
||||
},
|
||||
]),
|
||||
},
|
||||
};
|
||||
prisma = {
|
||||
$transaction: jest
|
||||
.fn()
|
||||
.mockImplementation((fn: (client: unknown) => unknown) => fn(tx)),
|
||||
authorityNotice: {
|
||||
findFirst: jest.fn().mockResolvedValue(null),
|
||||
findMany: jest.fn().mockResolvedValue([]),
|
||||
},
|
||||
};
|
||||
auditLog = { record: jest.fn() };
|
||||
service = new AuthorityNoticesService(
|
||||
prisma as unknown as PrismaService,
|
||||
auditLog as unknown as AuditLogService,
|
||||
);
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('one open draft per kind and year', async () => {
|
||||
stubLookups({
|
||||
baseline: notice({ status: 'SENT' }),
|
||||
openDraft: { id: 'existing' },
|
||||
});
|
||||
|
||||
const attempt = service.create({ kind: 'HERD_CHANGE' }, 'u1');
|
||||
|
||||
await expect(attempt).rejects.toBeInstanceOf(ConflictException);
|
||||
await expect(attempt).rejects.toMatchObject({
|
||||
response: { code: 'DRAFT_EXISTS', existingId: 'existing' },
|
||||
});
|
||||
});
|
||||
|
||||
it('answers DRAFT_EXISTS when the unique key of the open draft is hit', async () => {
|
||||
stubLookups({ baseline: notice({ status: 'SENT' }) });
|
||||
tx.authorityNotice.create.mockRejectedValueOnce(p2002());
|
||||
prisma.authorityNotice.findFirst.mockResolvedValue({ id: 'winner' });
|
||||
|
||||
await expect(
|
||||
service.create({ kind: 'HERD_CHANGE' }, 'u1'),
|
||||
).rejects.toMatchObject({
|
||||
response: { code: 'DRAFT_EXISTS', existingId: 'winner' },
|
||||
});
|
||||
});
|
||||
|
||||
it('create with sentOn is SENT at once and has no openKey', async () => {
|
||||
await service.create(
|
||||
{ kind: 'REGISTRATION', sentOn: '2026-05-01' },
|
||||
'u1',
|
||||
);
|
||||
|
||||
expect(tx.authorityNotice.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
kind: 'REGISTRATION',
|
||||
status: 'SENT',
|
||||
sentOn: new Date('2026-05-01T00:00:00.000Z'),
|
||||
openKey: null,
|
||||
totalColonies: 2,
|
||||
}) as unknown,
|
||||
});
|
||||
});
|
||||
|
||||
it('a notice created as sent does not collide with an open draft', async () => {
|
||||
stubLookups({ openDraft: { id: 'existing' } });
|
||||
|
||||
await service.create(
|
||||
{ kind: 'REGISTRATION', sentOn: '2026-05-01' },
|
||||
'u1',
|
||||
);
|
||||
|
||||
expect(tx.authorityNotice.create).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rethrows a unique violation that no open draft explains', async () => {
|
||||
stubLookups({ baseline: notice({ status: 'SENT' }) });
|
||||
const error = p2002();
|
||||
tx.authorityNotice.create.mockRejectedValueOnce(error);
|
||||
prisma.authorityNotice.findFirst.mockResolvedValue(null);
|
||||
|
||||
await expect(service.create({ kind: 'HERD_CHANGE' }, 'u1')).rejects.toBe(
|
||||
error,
|
||||
);
|
||||
});
|
||||
|
||||
it('a draft carries the open key and the counted snapshot', async () => {
|
||||
await service.create({ kind: 'REGISTRATION' }, 'u1');
|
||||
|
||||
expect(tx.authorityNotice.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
status: 'DRAFT',
|
||||
openKey: 'REGISTRATION',
|
||||
sentOn: null,
|
||||
totalColonies: 2,
|
||||
}) as unknown,
|
||||
});
|
||||
});
|
||||
|
||||
it('herd change needs a baseline and registration needs none', async () => {
|
||||
stubLookups({});
|
||||
await expect(
|
||||
service.create({ kind: 'HERD_CHANGE' }, 'u1'),
|
||||
).rejects.toMatchObject({
|
||||
response: expect.objectContaining({
|
||||
message: expect.stringContaining('Erstanzeige') as unknown,
|
||||
}) as unknown,
|
||||
});
|
||||
|
||||
stubLookups({ baseline: notice({ status: 'SENT' }) });
|
||||
await expect(
|
||||
service.create({ kind: 'REGISTRATION' }, 'u1'),
|
||||
).rejects.toBeInstanceOf(ConflictException);
|
||||
});
|
||||
|
||||
it('TSK_REPORT needs a year and uses it in the open key', async () => {
|
||||
await expect(
|
||||
service.create({ kind: 'TSK_REPORT' }, 'u1'),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
|
||||
await service.create({ kind: 'TSK_REPORT', year: 2027 }, 'u1');
|
||||
|
||||
expect(tx.authorityNotice.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
year: 2027,
|
||||
openKey: 'TSK_REPORT:2027',
|
||||
}) as unknown,
|
||||
});
|
||||
});
|
||||
|
||||
it('a year is only valid for the TSK report', async () => {
|
||||
await expect(
|
||||
service.create({ kind: 'REGISTRATION', year: 2027 }, 'u1'),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
|
||||
it('the TSK count leaves out the excluded colony types', async () => {
|
||||
tx.complianceSettings.findUniqueOrThrow.mockResolvedValue({
|
||||
...SETTINGS,
|
||||
tskExcludedColonyTypes: ['NUCLEUS_COLONY'],
|
||||
});
|
||||
|
||||
await service.create({ kind: 'TSK_REPORT', year: 2027 }, 'u1');
|
||||
|
||||
expect(tx.authorityNotice.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ totalColonies: 1 }) as unknown,
|
||||
});
|
||||
});
|
||||
|
||||
it('locks the settings row as mutex before reading and audits the create', async () => {
|
||||
await service.create({ kind: 'REGISTRATION' }, 'u1');
|
||||
|
||||
expect(lockMock).toHaveBeenCalledWith(
|
||||
tx,
|
||||
'ComplianceSettings',
|
||||
'singleton',
|
||||
);
|
||||
expect(lockMock.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
tx.authorityNotice.findFirst.mock.invocationCallOrder[0],
|
||||
);
|
||||
expect(auditLog.record).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
entityType: 'AuthorityNotice',
|
||||
action: 'CREATE',
|
||||
userId: 'u1',
|
||||
}),
|
||||
tx,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createDraftIn', () => {
|
||||
it('is the shared core: no actor needed and the caller owns the transaction', async () => {
|
||||
await service.createDraftIn(
|
||||
tx as never,
|
||||
{
|
||||
kind: 'TSK_REPORT',
|
||||
year: 2027,
|
||||
referenceDate: new Date('2027-01-01T00:00:00.000Z'),
|
||||
},
|
||||
null,
|
||||
);
|
||||
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled();
|
||||
expect(tx.authorityNotice.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
createdByUserId: null,
|
||||
openKey: 'TSK_REPORT:2027',
|
||||
}) as unknown,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('transitions', () => {
|
||||
it('recount only in DRAFT', async () => {
|
||||
tx.authorityNotice.findUnique.mockResolvedValue(
|
||||
notice({ status: 'SENT', openKey: null }),
|
||||
);
|
||||
|
||||
await expect(service.recount('n1', 'u1')).rejects.toBeInstanceOf(
|
||||
ConflictException,
|
||||
);
|
||||
|
||||
tx.authorityNotice.findUnique.mockResolvedValue(notice());
|
||||
await service.recount('n1', 'u1');
|
||||
|
||||
expect(tx.authorityNotice.update).toHaveBeenCalledWith({
|
||||
where: { id: 'n1' },
|
||||
data: expect.objectContaining({ totalColonies: 2 }) as unknown,
|
||||
});
|
||||
});
|
||||
|
||||
it('mark-sent on CANCELLED and recount on SENT answer 409', async () => {
|
||||
tx.authorityNotice.findUnique.mockResolvedValue(
|
||||
notice({ status: 'CANCELLED', openKey: null }),
|
||||
);
|
||||
await expect(service.markSent('n1', {}, 'u1')).rejects.toBeInstanceOf(
|
||||
ConflictException,
|
||||
);
|
||||
|
||||
tx.authorityNotice.findUnique.mockResolvedValue(
|
||||
notice({ status: 'SENT', openKey: null }),
|
||||
);
|
||||
await expect(service.recount('n1', 'u1')).rejects.toBeInstanceOf(
|
||||
ConflictException,
|
||||
);
|
||||
});
|
||||
|
||||
describe('sent day in the future', () => {
|
||||
const FUTURE = '2999-01-01';
|
||||
const MESSAGE = 'Das Sendedatum darf nicht in der Zukunft liegen.';
|
||||
|
||||
it('create rejects it', async () => {
|
||||
await expect(
|
||||
service.create({ kind: 'REGISTRATION', sentOn: FUTURE }, 'u1'),
|
||||
).rejects.toMatchObject({ message: MESSAGE });
|
||||
expect(tx.authorityNotice.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('mark-sent rejects it', async () => {
|
||||
await expect(
|
||||
service.markSent('n1', { sentOn: FUTURE }, 'u1'),
|
||||
).rejects.toMatchObject({ message: MESSAGE });
|
||||
expect(tx.authorityNotice.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('update rejects it', async () => {
|
||||
await expect(
|
||||
service.update('n1', { sentOn: FUTURE }, 'u1'),
|
||||
).rejects.toMatchObject({ message: MESSAGE });
|
||||
expect(tx.authorityNotice.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('accepts today (Berlin day) and clearing with null stays a different error', async () => {
|
||||
jest.useFakeTimers({ now: new Date('2027-03-01T23:30:00.000Z') });
|
||||
try {
|
||||
await service.markSent('n1', { sentOn: '2027-03-02' }, 'u1');
|
||||
await expect(
|
||||
service.markSent('n1', { sentOn: '2027-03-03' }, 'u1'),
|
||||
).rejects.toMatchObject({ message: MESSAGE });
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('mark-sent defaults the sent day to the Berlin day, not the UTC day', async () => {
|
||||
jest.useFakeTimers({ now: new Date('2027-03-01T23:30:00.000Z') });
|
||||
try {
|
||||
await service.markSent('n1', {}, 'u1');
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
|
||||
expect(tx.authorityNotice.update).toHaveBeenCalledWith({
|
||||
where: { id: 'n1' },
|
||||
data: expect.objectContaining({
|
||||
sentOn: new Date('2027-03-02T00:00:00.000Z'),
|
||||
}) as unknown,
|
||||
});
|
||||
});
|
||||
|
||||
it('mark-sent sets SENT, the sent day and drops the open key', async () => {
|
||||
await service.markSent(
|
||||
'n1',
|
||||
{ sentOn: '2026-02-02', sentVia: 'E-Mail' },
|
||||
'u1',
|
||||
);
|
||||
|
||||
expect(tx.authorityNotice.update).toHaveBeenCalledWith({
|
||||
where: { id: 'n1' },
|
||||
data: expect.objectContaining({
|
||||
status: 'SENT',
|
||||
sentOn: new Date('2026-02-02T00:00:00.000Z'),
|
||||
sentVia: 'E-Mail',
|
||||
openKey: null,
|
||||
}) as unknown,
|
||||
});
|
||||
});
|
||||
|
||||
it('a reopened registration can be marked sent again', async () => {
|
||||
tx.authorityNotice.findUnique.mockResolvedValue(
|
||||
notice({ kind: 'REGISTRATION', openKey: 'REGISTRATION' }),
|
||||
);
|
||||
stubLookups({ baseline: notice({ id: 'other', status: 'SENT' }) });
|
||||
|
||||
await service.markSent('n1', {}, 'u1');
|
||||
|
||||
expect(tx.authorityNotice.update).toHaveBeenCalledWith({
|
||||
where: { id: 'n1' },
|
||||
data: expect.objectContaining({ status: 'SENT' }) as unknown,
|
||||
});
|
||||
});
|
||||
|
||||
it('reopen answers 409 while another draft of the kind exists', async () => {
|
||||
tx.authorityNotice.findUnique.mockResolvedValue(
|
||||
notice({ status: 'SENT', openKey: null }),
|
||||
);
|
||||
stubLookups({ openDraft: { id: 'other' } });
|
||||
|
||||
await expect(service.reopen('n1', 'u1')).rejects.toMatchObject({
|
||||
response: { code: 'DRAFT_EXISTS', existingId: 'other' },
|
||||
});
|
||||
});
|
||||
|
||||
it('reopen turns a SENT notice back into a draft with its open key', async () => {
|
||||
tx.authorityNotice.findUnique.mockResolvedValue(
|
||||
notice({ status: 'SENT', openKey: null, sentOn: new Date(0) }),
|
||||
);
|
||||
|
||||
await service.reopen('n1', 'u1');
|
||||
|
||||
expect(tx.authorityNotice.update).toHaveBeenCalledWith({
|
||||
where: { id: 'n1' },
|
||||
data: expect.objectContaining({
|
||||
status: 'DRAFT',
|
||||
openKey: 'HERD_CHANGE',
|
||||
}) as unknown,
|
||||
});
|
||||
});
|
||||
|
||||
it('cancel only works on a draft and drops the open key', async () => {
|
||||
await service.cancel('n1', 'u1');
|
||||
expect(tx.authorityNotice.update).toHaveBeenCalledWith({
|
||||
where: { id: 'n1' },
|
||||
data: expect.objectContaining({
|
||||
status: 'CANCELLED',
|
||||
openKey: null,
|
||||
}) as unknown,
|
||||
});
|
||||
|
||||
tx.authorityNotice.findUnique.mockResolvedValue(
|
||||
notice({ status: 'SENT', openKey: null }),
|
||||
);
|
||||
await expect(service.cancel('n1', 'u1')).rejects.toBeInstanceOf(
|
||||
ConflictException,
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['recount', (s: AuthorityNoticesService) => s.recount('n1', 'u1')],
|
||||
['markSent', (s: AuthorityNoticesService) => s.markSent('n1', {}, 'u1')],
|
||||
['cancel', (s: AuthorityNoticesService) => s.cancel('n1', 'u1')],
|
||||
[
|
||||
'update',
|
||||
(s: AuthorityNoticesService) => s.update('n1', { notes: 'x' }, 'u1'),
|
||||
],
|
||||
])(
|
||||
'every transition locks the notice row and writes an audit entry (%s)',
|
||||
async (_name, run) => {
|
||||
await run(service);
|
||||
|
||||
expect(lockMock).toHaveBeenCalledWith(tx, 'AuthorityNotice', 'n1');
|
||||
const lockOrder = lockMock.mock.invocationCallOrder.at(-1) ?? 0;
|
||||
expect(lockOrder).toBeLessThan(
|
||||
tx.authorityNotice.findUnique.mock.invocationCallOrder[0],
|
||||
);
|
||||
expect(auditLog.record).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
entityType: 'AuthorityNotice',
|
||||
entityId: 'n1',
|
||||
action: 'UPDATE',
|
||||
userId: 'u1',
|
||||
beforeData: expect.anything() as unknown,
|
||||
afterData: expect.anything() as unknown,
|
||||
}),
|
||||
tx,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it('reopen locks the settings mutex before the notice row', async () => {
|
||||
tx.authorityNotice.findUnique.mockResolvedValue(
|
||||
notice({ status: 'SENT', openKey: null }),
|
||||
);
|
||||
|
||||
await service.reopen('n1', 'u1');
|
||||
|
||||
expect(lockMock.mock.calls.map((call: unknown[]) => call[1])).toEqual([
|
||||
'ComplianceSettings',
|
||||
'AuthorityNotice',
|
||||
]);
|
||||
});
|
||||
|
||||
it('answers 404 for a missing notice', async () => {
|
||||
lockMock.mockResolvedValue(false);
|
||||
|
||||
await expect(service.recount('missing', 'u1')).rejects.toBeInstanceOf(
|
||||
NotFoundException,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('changes the corrected fields but answers 409 on CANCELLED', async () => {
|
||||
await service.update(
|
||||
'n1',
|
||||
{ totalColonies: 7, notes: 'korrigiert' },
|
||||
'u1',
|
||||
);
|
||||
expect(tx.authorityNotice.update).toHaveBeenCalledWith({
|
||||
where: { id: 'n1' },
|
||||
data: expect.objectContaining({
|
||||
totalColonies: 7,
|
||||
notes: 'korrigiert',
|
||||
}) as unknown,
|
||||
});
|
||||
|
||||
tx.authorityNotice.findUnique.mockResolvedValue(
|
||||
notice({ status: 'CANCELLED', openKey: null }),
|
||||
);
|
||||
await expect(
|
||||
service.update('n1', { notes: 'x' }, 'u1'),
|
||||
).rejects.toBeInstanceOf(ConflictException);
|
||||
});
|
||||
|
||||
it('a draft has no sent day', async () => {
|
||||
await expect(
|
||||
service.update('n1', { sentOn: '2026-01-01' }, 'u1'),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
|
||||
it('changing the sent day takes the settings mutex first', async () => {
|
||||
tx.authorityNotice.findUnique.mockResolvedValue(
|
||||
notice({ kind: 'REGISTRATION', status: 'SENT', openKey: null }),
|
||||
);
|
||||
|
||||
await service.update('n1', { sentOn: '2026-01-02' }, 'u1');
|
||||
|
||||
expect(lockMock.mock.calls.map((call: unknown[]) => call[1])).toEqual([
|
||||
'ComplianceSettings',
|
||||
'AuthorityNotice',
|
||||
]);
|
||||
});
|
||||
|
||||
it('other edits do not take the settings mutex', async () => {
|
||||
await service.update('n1', { notes: 'x' }, 'u1');
|
||||
|
||||
expect(lockMock.mock.calls.map((call: unknown[]) => call[1])).toEqual([
|
||||
'AuthorityNotice',
|
||||
]);
|
||||
});
|
||||
|
||||
it('a sent notice keeps its sent day', async () => {
|
||||
tx.authorityNotice.findUnique.mockResolvedValue(
|
||||
notice({ status: 'SENT', openKey: null, sentOn: new Date(0) }),
|
||||
);
|
||||
|
||||
await expect(
|
||||
service.update('n1', { sentOn: null }, 'u1'),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findAll / findOne', () => {
|
||||
it('filters by kind and year', async () => {
|
||||
await service.findAll({ kind: 'TSK_REPORT', year: 2027 });
|
||||
|
||||
expect(prisma.authorityNotice.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { kind: 'TSK_REPORT', year: 2027 },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('answers 404 for an unknown id', async () => {
|
||||
(
|
||||
prisma.authorityNotice as unknown as { findUnique: jest.Mock }
|
||||
).findUnique = jest.fn().mockResolvedValue(null);
|
||||
|
||||
await expect(service.findOne('x')).rejects.toBeInstanceOf(
|
||||
NotFoundException,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,468 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
AuthorityNotice,
|
||||
AuthorityNoticeKind,
|
||||
Prisma,
|
||||
} from '../../generated/prisma';
|
||||
import { AuditLogService } from '../audit/audit-log.service';
|
||||
import { berlinToday, dayToDate } from '../common/dates';
|
||||
import { optionalDate } from '../common/patch-values';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { lockRowForUpdate } from '../prisma/row-lock';
|
||||
import { CreateAuthorityNoticeDto } from './dto/create-authority-notice.dto';
|
||||
import { MarkSentDto } from './dto/mark-sent.dto';
|
||||
import { UpdateAuthorityNoticeDto } from './dto/update-authority-notice.dto';
|
||||
import { buildHerdSnapshot, loadHerdApiaryRows } from './herd-snapshot';
|
||||
import {
|
||||
COMPLIANCE_SETTINGS_ID,
|
||||
complianceSettingsIn,
|
||||
findBaselineIn,
|
||||
} from './herd-status';
|
||||
import { buildNoticePdfModel } from './pdf/authority-notice-model';
|
||||
import { renderAuthorityNoticePdf } from './pdf/authority-notice-pdf';
|
||||
|
||||
const AUDIT_ENTITY = 'AuthorityNotice';
|
||||
const LIST_LIMIT = 200;
|
||||
const UNIQUE_VIOLATION = 'P2002';
|
||||
|
||||
type NoticeUpdate = Prisma.AuthorityNoticeUncheckedUpdateInput;
|
||||
|
||||
interface DraftInput {
|
||||
kind: AuthorityNoticeKind;
|
||||
year?: number;
|
||||
referenceDate: Date;
|
||||
}
|
||||
|
||||
interface TransitionOptions {
|
||||
/** Takes the ComplianceSettings mutex first (the open key is involved). */
|
||||
mutex?: boolean;
|
||||
}
|
||||
|
||||
/** "REGISTRATION" | "HERD_CHANGE" | "TSK_REPORT:<year>": at most one draft each. */
|
||||
function openKeyOf(kind: AuthorityNoticeKind, year: number | null): string {
|
||||
return kind === 'TSK_REPORT' ? `TSK_REPORT:${year}` : kind;
|
||||
}
|
||||
|
||||
function trimmedOrNull(
|
||||
value: string | null | undefined,
|
||||
): string | null | undefined {
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
return value?.trim() || null;
|
||||
}
|
||||
|
||||
function notAllowed(message: string): ConflictException {
|
||||
return new ConflictException({ statusCode: 409, message });
|
||||
}
|
||||
|
||||
function draftExists(existingId: string): ConflictException {
|
||||
return new ConflictException({
|
||||
statusCode: 409,
|
||||
code: 'DRAFT_EXISTS',
|
||||
message: 'Es gibt schon einen offenen Entwurf dieser Anzeige.',
|
||||
existingId,
|
||||
});
|
||||
}
|
||||
|
||||
function isUniqueViolation(error: unknown): boolean {
|
||||
return (
|
||||
error instanceof Prisma.PrismaClientKnownRequestError &&
|
||||
error.code === UNIQUE_VIOLATION
|
||||
);
|
||||
}
|
||||
|
||||
function assertYearFits(kind: AuthorityNoticeKind, year?: number): void {
|
||||
if (kind === 'TSK_REPORT' && year === undefined) {
|
||||
throw new BadRequestException('Die TSK-Zählung braucht ein Jahr');
|
||||
}
|
||||
if (kind !== 'TSK_REPORT' && year !== undefined) {
|
||||
throw new BadRequestException('Ein Jahr gibt es nur bei der TSK-Zählung');
|
||||
}
|
||||
}
|
||||
|
||||
/** A notice cannot have been sent tomorrow: sentOn must not lie after the Berlin day. */
|
||||
function futureSentOnError(
|
||||
sentOn: string | null | undefined,
|
||||
): BadRequestException | undefined {
|
||||
return sentOn && sentOn > berlinToday()
|
||||
? new BadRequestException(
|
||||
'Das Sendedatum darf nicht in der Zukunft liegen.',
|
||||
)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AuthorityNoticesService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly auditLog: AuditLogService,
|
||||
) {}
|
||||
|
||||
findAll(q: {
|
||||
kind?: AuthorityNoticeKind;
|
||||
year?: number;
|
||||
}): Promise<AuthorityNotice[]> {
|
||||
return this.prisma.authorityNotice.findMany({
|
||||
where: { kind: q.kind, year: q.year },
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
take: LIST_LIMIT,
|
||||
});
|
||||
}
|
||||
|
||||
async findOne(id: string): Promise<AuthorityNotice> {
|
||||
const notice = await this.prisma.authorityNotice.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!notice) {
|
||||
throw new NotFoundException('Anzeige nicht gefunden');
|
||||
}
|
||||
return notice;
|
||||
}
|
||||
|
||||
/**
|
||||
* The PDF of a notice. A change notice compares with the notice that was
|
||||
* the baseline when it was (or would be) sent. The file name carries the
|
||||
* id only, never user input.
|
||||
*/
|
||||
async pdf(id: string): Promise<{ buffer: Buffer; fileName: string }> {
|
||||
const notice = await this.findOne(id);
|
||||
const [site, settings, baseline] = await Promise.all([
|
||||
this.prisma.siteSettings.findUnique({ where: { id: 'singleton' } }),
|
||||
complianceSettingsIn(this.prisma),
|
||||
notice.kind === 'HERD_CHANGE'
|
||||
? this.baselineFor(notice)
|
||||
: Promise.resolve(null),
|
||||
]);
|
||||
const model = buildNoticePdfModel({
|
||||
notice,
|
||||
baseline,
|
||||
site: {
|
||||
holderName: site?.holderName ?? null,
|
||||
holderAddress: site?.holderAddress ?? null,
|
||||
},
|
||||
settings,
|
||||
now: new Date(),
|
||||
});
|
||||
return {
|
||||
buffer: await renderAuthorityNoticePdf(model),
|
||||
fileName: `anzeige-${notice.id}.pdf`,
|
||||
};
|
||||
}
|
||||
|
||||
/** A sent notice compares with the one sent before it, a draft with the newest. */
|
||||
private baselineFor(
|
||||
notice: AuthorityNotice,
|
||||
): Promise<AuthorityNotice | null> {
|
||||
if (notice.status !== 'SENT' || !notice.sentOn) {
|
||||
return findBaselineIn(this.prisma);
|
||||
}
|
||||
return this.prisma.authorityNotice.findFirst({
|
||||
where: {
|
||||
status: 'SENT',
|
||||
kind: { in: ['REGISTRATION', 'HERD_CHANGE'] },
|
||||
id: { not: notice.id },
|
||||
OR: [
|
||||
{ sentOn: { lt: notice.sentOn } },
|
||||
{
|
||||
sentOn: notice.sentOn,
|
||||
createdAt: { lt: notice.createdAt },
|
||||
},
|
||||
],
|
||||
},
|
||||
orderBy: [{ sentOn: 'desc' }, { createdAt: 'desc' }, { id: 'desc' }],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a draft, or a SENT notice at once when `sentOn` is given (the
|
||||
* way to record what was already reported). A second open draft of the
|
||||
* same kind and year answers 409 DRAFT_EXISTS with the id of the first.
|
||||
*/
|
||||
async create(
|
||||
dto: CreateAuthorityNoticeDto,
|
||||
actingUserId: string,
|
||||
): Promise<AuthorityNotice> {
|
||||
assertYearFits(dto.kind, dto.year);
|
||||
const futureError = futureSentOnError(dto.sentOn);
|
||||
if (futureError) {
|
||||
throw futureError;
|
||||
}
|
||||
const input = {
|
||||
kind: dto.kind,
|
||||
year: dto.year,
|
||||
referenceDate: dayToDate(dto.referenceDate ?? berlinToday()),
|
||||
sentOn: dto.sentOn ? dayToDate(dto.sentOn) : undefined,
|
||||
};
|
||||
try {
|
||||
return await this.prisma.$transaction((tx) =>
|
||||
this.insertIn(tx, input, actingUserId),
|
||||
);
|
||||
} catch (error) {
|
||||
if (!isUniqueViolation(error)) {
|
||||
throw error;
|
||||
}
|
||||
const winner = await this.prisma.authorityNotice.findFirst({
|
||||
where: { openKey: openKeyOf(dto.kind, dto.year ?? null) },
|
||||
select: { id: true },
|
||||
});
|
||||
if (winner) {
|
||||
throw draftExists(winner.id);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** The shared core of create: the daily TSK job calls it in its own transaction. */
|
||||
createDraftIn(
|
||||
tx: Prisma.TransactionClient,
|
||||
input: DraftInput,
|
||||
userId: string | null,
|
||||
): Promise<AuthorityNotice> {
|
||||
assertYearFits(input.kind, input.year);
|
||||
return this.insertIn(tx, input, userId);
|
||||
}
|
||||
|
||||
/** Replaces the herd picture and the total; only a draft can be recounted. */
|
||||
recount(id: string, actingUserId: string): Promise<AuthorityNotice> {
|
||||
return this.transition(id, actingUserId, {}, async (tx, before) => {
|
||||
if (before.status !== 'DRAFT') {
|
||||
throw notAllowed('Nur ein Entwurf kann neu gezählt werden.');
|
||||
}
|
||||
const countedAt = new Date();
|
||||
const snapshot = await this.countIn(tx, before.kind, countedAt);
|
||||
return {
|
||||
snapshot: snapshot as unknown as Prisma.InputJsonValue,
|
||||
totalColonies: snapshot.totalLiving,
|
||||
countedAt,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
markSent(
|
||||
id: string,
|
||||
dto: MarkSentDto,
|
||||
actingUserId: string,
|
||||
): Promise<AuthorityNotice> {
|
||||
const futureError = futureSentOnError(dto.sentOn);
|
||||
if (futureError) {
|
||||
return Promise.reject(futureError);
|
||||
}
|
||||
return this.transition(id, actingUserId, { mutex: true }, (_tx, before) => {
|
||||
if (before.status !== 'DRAFT') {
|
||||
return Promise.reject(
|
||||
notAllowed('Nur ein Entwurf kann als gesendet markiert werden.'),
|
||||
);
|
||||
}
|
||||
return Promise.resolve({
|
||||
status: 'SENT',
|
||||
sentOn: dayToDate(dto.sentOn ?? berlinToday()),
|
||||
sentVia: trimmedOrNull(dto.sentVia),
|
||||
reference: trimmedOrNull(dto.reference),
|
||||
openKey: null,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
reopen(id: string, actingUserId: string): Promise<AuthorityNotice> {
|
||||
return this.transition(
|
||||
id,
|
||||
actingUserId,
|
||||
{ mutex: true },
|
||||
async (tx, before) => {
|
||||
if (before.status !== 'SENT') {
|
||||
throw notAllowed('Nur eine gesendete Anzeige kann geöffnet werden.');
|
||||
}
|
||||
const openKey = openKeyOf(before.kind, before.year);
|
||||
const other = await tx.authorityNotice.findFirst({
|
||||
where: { openKey },
|
||||
select: { id: true },
|
||||
});
|
||||
if (other) {
|
||||
throw draftExists(other.id);
|
||||
}
|
||||
return { status: 'DRAFT', openKey, sentOn: null };
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
cancel(id: string, actingUserId: string): Promise<AuthorityNotice> {
|
||||
return this.transition(id, actingUserId, {}, (_tx, before) => {
|
||||
if (before.status !== 'DRAFT') {
|
||||
return Promise.reject(
|
||||
notAllowed('Nur ein Entwurf kann verworfen werden.'),
|
||||
);
|
||||
}
|
||||
return Promise.resolve({ status: 'CANCELLED', openKey: null });
|
||||
});
|
||||
}
|
||||
|
||||
update(
|
||||
id: string,
|
||||
dto: UpdateAuthorityNoticeDto,
|
||||
actingUserId: string,
|
||||
): Promise<AuthorityNotice> {
|
||||
// A new sent day can change which notice is the baseline: the mutex
|
||||
// comes first, in lock order, whenever the sent day is touched.
|
||||
const futureError = futureSentOnError(dto.sentOn);
|
||||
if (futureError) {
|
||||
return Promise.reject(futureError);
|
||||
}
|
||||
const mutex = dto.sentOn !== undefined;
|
||||
return this.transition(id, actingUserId, { mutex }, (_tx, before) => {
|
||||
if (before.status === 'CANCELLED') {
|
||||
return Promise.reject(
|
||||
notAllowed('Eine verworfene Anzeige kann nicht geändert werden.'),
|
||||
);
|
||||
}
|
||||
if (before.status === 'DRAFT' && dto.sentOn != null) {
|
||||
return Promise.reject(
|
||||
new BadRequestException('Ein Entwurf hat kein Sendedatum.'),
|
||||
);
|
||||
}
|
||||
if (before.status === 'SENT' && dto.sentOn === null) {
|
||||
return Promise.reject(
|
||||
new BadRequestException(
|
||||
'Eine gesendete Anzeige braucht ihr Sendedatum',
|
||||
),
|
||||
);
|
||||
}
|
||||
return Promise.resolve({
|
||||
totalColonies: dto.totalColonies,
|
||||
referenceDate: dto.referenceDate
|
||||
? dayToDate(dto.referenceDate)
|
||||
: undefined,
|
||||
sentOn: optionalDate(dto.sentOn),
|
||||
sentVia: trimmedOrNull(dto.sentVia),
|
||||
reference: trimmedOrNull(dto.reference),
|
||||
notes: trimmedOrNull(dto.notes),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private async countIn(
|
||||
tx: Prisma.TransactionClient,
|
||||
kind: AuthorityNoticeKind,
|
||||
countedAt: Date,
|
||||
) {
|
||||
const settings = await tx.complianceSettings.findUniqueOrThrow({
|
||||
where: { id: COMPLIANCE_SETTINGS_ID },
|
||||
});
|
||||
return buildHerdSnapshot(
|
||||
await loadHerdApiaryRows(tx),
|
||||
countedAt,
|
||||
kind === 'TSK_REPORT' ? settings.tskExcludedColonyTypes : [],
|
||||
);
|
||||
}
|
||||
|
||||
private async insertIn(
|
||||
tx: Prisma.TransactionClient,
|
||||
input: DraftInput & { sentOn?: Date },
|
||||
userId: string | null,
|
||||
): Promise<AuthorityNotice> {
|
||||
await this.lockSettingsIn(tx);
|
||||
const baseline = await findBaselineIn(tx);
|
||||
if (input.kind === 'REGISTRATION' && baseline) {
|
||||
throw notAllowed('Die Erstanzeige ist schon erfasst.');
|
||||
}
|
||||
if (input.kind === 'HERD_CHANGE' && !baseline) {
|
||||
throw notAllowed('Erst die Erstanzeige erfassen.');
|
||||
}
|
||||
const openKey = openKeyOf(input.kind, input.year ?? null);
|
||||
// A notice recorded as already sent has no open key and cannot collide.
|
||||
const draft = input.sentOn
|
||||
? null
|
||||
: await tx.authorityNotice.findFirst({
|
||||
where: { openKey },
|
||||
select: { id: true },
|
||||
});
|
||||
if (draft) {
|
||||
throw draftExists(draft.id);
|
||||
}
|
||||
const countedAt = new Date();
|
||||
const snapshot = await this.countIn(tx, input.kind, countedAt);
|
||||
const created = await tx.authorityNotice.create({
|
||||
data: {
|
||||
kind: input.kind,
|
||||
status: input.sentOn ? 'SENT' : 'DRAFT',
|
||||
year: input.year ?? null,
|
||||
referenceDate: input.referenceDate,
|
||||
countedAt,
|
||||
snapshot: snapshot as unknown as Prisma.InputJsonValue,
|
||||
totalColonies: snapshot.totalLiving,
|
||||
sentOn: input.sentOn ?? null,
|
||||
openKey: input.sentOn ? null : openKey,
|
||||
createdByUserId: userId,
|
||||
},
|
||||
});
|
||||
await this.auditLog.record(
|
||||
{
|
||||
entityType: AUDIT_ENTITY,
|
||||
entityId: created.id,
|
||||
action: 'CREATE',
|
||||
userId: userId ?? undefined,
|
||||
afterData: created,
|
||||
},
|
||||
tx,
|
||||
);
|
||||
return created;
|
||||
}
|
||||
|
||||
/** The ComplianceSettings row is the mutex of everything around the open key. */
|
||||
private async lockSettingsIn(tx: Prisma.TransactionClient): Promise<void> {
|
||||
await tx.complianceSettings.upsert({
|
||||
where: { id: COMPLIANCE_SETTINGS_ID },
|
||||
update: {},
|
||||
create: { id: COMPLIANCE_SETTINGS_ID },
|
||||
});
|
||||
await lockRowForUpdate(tx, 'ComplianceSettings', COMPLIANCE_SETTINGS_ID);
|
||||
}
|
||||
|
||||
/**
|
||||
* One state change: lock (settings mutex first when asked, then the notice
|
||||
* row), read "before" under the lock, check the transition, write, audit.
|
||||
*/
|
||||
private async transition(
|
||||
id: string,
|
||||
actingUserId: string,
|
||||
options: TransitionOptions,
|
||||
change: (
|
||||
tx: Prisma.TransactionClient,
|
||||
before: AuthorityNotice,
|
||||
) => Promise<NoticeUpdate>,
|
||||
): Promise<AuthorityNotice> {
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
if (options.mutex) {
|
||||
await this.lockSettingsIn(tx);
|
||||
}
|
||||
if (!(await lockRowForUpdate(tx, 'AuthorityNotice', id))) {
|
||||
throw new NotFoundException('Anzeige nicht gefunden');
|
||||
}
|
||||
const before = await tx.authorityNotice.findUnique({ where: { id } });
|
||||
if (!before) {
|
||||
throw new NotFoundException('Anzeige nicht gefunden');
|
||||
}
|
||||
const after = await tx.authorityNotice.update({
|
||||
where: { id },
|
||||
data: await change(tx, before),
|
||||
});
|
||||
await this.auditLog.record(
|
||||
{
|
||||
entityType: AUDIT_ENTITY,
|
||||
entityId: id,
|
||||
action: 'UPDATE',
|
||||
userId: actingUserId,
|
||||
beforeData: before,
|
||||
afterData: after,
|
||||
},
|
||||
tx,
|
||||
);
|
||||
return after;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import {
|
||||
describeNullContracts,
|
||||
NullContract,
|
||||
} from '../common/validation/null-contract.spec-helper';
|
||||
import { UpdateAuthorityNoticeDto } from './dto/update-authority-notice.dto';
|
||||
import { UpdateComplianceSettingsDto } from './dto/update-compliance-settings.dto';
|
||||
|
||||
const contracts: Record<string, NullContract> = {
|
||||
UpdateComplianceSettingsDto: {
|
||||
dto: UpdateComplianceSettingsDto,
|
||||
notNull: [
|
||||
'noticeOnColonyCountChange',
|
||||
'noticeOnApiaryChange',
|
||||
'tskReferenceDay',
|
||||
'tskExcludedColonyTypes',
|
||||
'netQuantityDigitRules',
|
||||
],
|
||||
clearable: [
|
||||
'veterinaryOfficeName',
|
||||
'veterinaryOfficeAddress',
|
||||
'registrationNumber',
|
||||
'tskReportDueDay',
|
||||
'tskMemberNumber',
|
||||
],
|
||||
},
|
||||
UpdateAuthorityNoticeDto: {
|
||||
dto: UpdateAuthorityNoticeDto,
|
||||
notNull: ['totalColonies', 'referenceDate'],
|
||||
clearable: ['sentOn', 'sentVia', 'reference', 'notes'],
|
||||
},
|
||||
};
|
||||
|
||||
describeNullContracts('Compliance DTO null contracts', contracts);
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Body, Controller, Get, Patch } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
import { RequirePermission } from '../auth/decorators/require-permission.decorator';
|
||||
import type { AuthenticatedUser } from '../auth/types/authenticated-user';
|
||||
import { ComplianceSettingsService } from './compliance-settings.service';
|
||||
import { UpdateComplianceSettingsDto } from './dto/update-compliance-settings.dto';
|
||||
|
||||
@ApiTags('compliance')
|
||||
@ApiBearerAuth()
|
||||
@Controller('compliance/settings')
|
||||
export class ComplianceSettingsController {
|
||||
constructor(private readonly settings: ComplianceSettingsService) {}
|
||||
|
||||
@RequirePermission('compliance:read')
|
||||
@Get()
|
||||
get() {
|
||||
return this.settings.get();
|
||||
}
|
||||
|
||||
@RequirePermission('compliance:manage')
|
||||
@Patch()
|
||||
update(
|
||||
@Body() dto: UpdateComplianceSettingsDto,
|
||||
@CurrentUser() actor: AuthenticatedUser,
|
||||
) {
|
||||
return this.settings.update(dto, actor.id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import { AuditLogService } from '../audit/audit-log.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { lockRowForUpdate } from '../prisma/row-lock';
|
||||
import { ComplianceSettingsService } from './compliance-settings.service';
|
||||
|
||||
jest.mock('../prisma/row-lock', () => ({
|
||||
lockRowForUpdate: jest.fn().mockResolvedValue(true),
|
||||
}));
|
||||
|
||||
const STORED = {
|
||||
id: 'singleton',
|
||||
veterinaryOfficeName: null,
|
||||
veterinaryOfficeAddress: null,
|
||||
registrationNumber: null,
|
||||
noticeOnColonyCountChange: true,
|
||||
noticeOnApiaryChange: true,
|
||||
tskReferenceDay: '01-01',
|
||||
tskReportDueDay: null,
|
||||
tskMemberNumber: null,
|
||||
tskExcludedColonyTypes: [],
|
||||
netQuantityDigitRules: [
|
||||
{ maxGrams: 50, minMm: 2 },
|
||||
{ maxGrams: null, minMm: 6 },
|
||||
],
|
||||
updatedAt: new Date(0),
|
||||
};
|
||||
|
||||
describe('ComplianceSettingsService', () => {
|
||||
let service: ComplianceSettingsService;
|
||||
let tx: {
|
||||
complianceSettings: {
|
||||
upsert: jest.Mock;
|
||||
findUniqueOrThrow: jest.Mock;
|
||||
update: jest.Mock;
|
||||
};
|
||||
};
|
||||
let prisma: {
|
||||
$transaction: jest.Mock;
|
||||
complianceSettings: { findUnique: jest.Mock; upsert: jest.Mock };
|
||||
};
|
||||
let auditLog: { record: jest.Mock };
|
||||
|
||||
beforeEach(() => {
|
||||
(lockRowForUpdate as jest.Mock).mockResolvedValue(true);
|
||||
tx = {
|
||||
complianceSettings: {
|
||||
upsert: jest.fn().mockResolvedValue(STORED),
|
||||
findUniqueOrThrow: jest.fn().mockResolvedValue(STORED),
|
||||
update: jest
|
||||
.fn()
|
||||
.mockImplementation(({ data }: { data: object }) =>
|
||||
Promise.resolve({ ...STORED, ...data }),
|
||||
),
|
||||
},
|
||||
};
|
||||
prisma = {
|
||||
$transaction: jest
|
||||
.fn()
|
||||
.mockImplementation((fn: (client: unknown) => unknown) => fn(tx)),
|
||||
complianceSettings: {
|
||||
findUnique: jest.fn().mockResolvedValue(null),
|
||||
upsert: jest.fn().mockResolvedValue(STORED),
|
||||
},
|
||||
};
|
||||
auditLog = { record: jest.fn() };
|
||||
service = new ComplianceSettingsService(
|
||||
prisma as unknown as PrismaService,
|
||||
auditLog as unknown as AuditLogService,
|
||||
);
|
||||
});
|
||||
|
||||
it('creates defaults on first read', async () => {
|
||||
const settings = await service.get();
|
||||
|
||||
expect(prisma.complianceSettings.upsert).toHaveBeenCalledWith({
|
||||
where: { id: 'singleton' },
|
||||
update: {},
|
||||
create: { id: 'singleton' },
|
||||
});
|
||||
expect(settings).toBe(STORED);
|
||||
});
|
||||
|
||||
it('returns the stored row without creating one', async () => {
|
||||
prisma.complianceSettings.findUnique.mockResolvedValue(STORED);
|
||||
|
||||
await service.get();
|
||||
|
||||
expect(prisma.complianceSettings.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects 02-29 as reference day with 400', async () => {
|
||||
await expect(
|
||||
service.update({ tskReferenceDay: '02-29' }, 'u1'),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
await expect(
|
||||
service.update({ tskReportDueDay: '13-01' }, 'u1'),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
|
||||
it('rejects digit rules that are not ascending or whose last rule has a limit', async () => {
|
||||
const attempts = [
|
||||
[
|
||||
{ maxGrams: 200, minMm: 3 },
|
||||
{ maxGrams: 50, minMm: 2 },
|
||||
{ maxGrams: null, minMm: 6 },
|
||||
],
|
||||
[
|
||||
{ maxGrams: 50, minMm: 2 },
|
||||
{ maxGrams: 50, minMm: 3 },
|
||||
{ maxGrams: null, minMm: 6 },
|
||||
],
|
||||
[{ maxGrams: 50, minMm: 2 }],
|
||||
[
|
||||
{ maxGrams: null, minMm: 2 },
|
||||
{ maxGrams: null, minMm: 6 },
|
||||
],
|
||||
[],
|
||||
];
|
||||
for (const rules of attempts) {
|
||||
await expect(
|
||||
service.update({ netQuantityDigitRules: rules }, 'u1'),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects a digit height outside 0.5 to 20 mm and more than 10 rules', async () => {
|
||||
await expect(
|
||||
service.update(
|
||||
{ netQuantityDigitRules: [{ maxGrams: null, minMm: 0.4 }] },
|
||||
'u1',
|
||||
),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
await expect(
|
||||
service.update(
|
||||
{ netQuantityDigitRules: [{ maxGrams: null, minMm: 20.5 }] },
|
||||
'u1',
|
||||
),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
const eleven = Array.from({ length: 10 }, (_, index) => ({
|
||||
maxGrams: (index + 1) * 10,
|
||||
minMm: 2,
|
||||
})).concat([{ maxGrams: null as never, minMm: 2 }]);
|
||||
await expect(
|
||||
service.update({ netQuantityDigitRules: eleven }, 'u1'),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
|
||||
it('treats a missing maxGrams key like null', async () => {
|
||||
await service.update(
|
||||
{
|
||||
netQuantityDigitRules: [
|
||||
{ maxGrams: 50, minMm: 2 },
|
||||
{ minMm: 6 } as never,
|
||||
],
|
||||
},
|
||||
'u1',
|
||||
);
|
||||
|
||||
const call = (
|
||||
tx.complianceSettings.update.mock.calls as unknown[][]
|
||||
)[0][0] as {
|
||||
data: { netQuantityDigitRules: unknown };
|
||||
};
|
||||
expect(call.data.netQuantityDigitRules).toEqual([
|
||||
{ maxGrams: 50, minMm: 2 },
|
||||
{ maxGrams: null, minMm: 6 },
|
||||
]);
|
||||
await expect(
|
||||
service.update(
|
||||
{
|
||||
netQuantityDigitRules: [{ minMm: 2 } as never, { minMm: 6 } as never],
|
||||
},
|
||||
'u1',
|
||||
),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
|
||||
it('rejects a colony type listed twice', async () => {
|
||||
await expect(
|
||||
service.update(
|
||||
{ tskExcludedColonyTypes: ['NUCLEUS_COLONY', 'NUCLEUS_COLONY'] },
|
||||
'u1',
|
||||
),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
|
||||
it('stores valid values under the row lock with an audit entry', async () => {
|
||||
await service.update(
|
||||
{
|
||||
veterinaryOfficeName: ' Veterinäramt ',
|
||||
tskReferenceDay: '04-15',
|
||||
tskReportDueDay: null,
|
||||
netQuantityDigitRules: [{ maxGrams: null, minMm: 3 }],
|
||||
},
|
||||
'u1',
|
||||
);
|
||||
|
||||
expect(lockRowForUpdate).toHaveBeenCalledWith(
|
||||
tx,
|
||||
'ComplianceSettings',
|
||||
'singleton',
|
||||
);
|
||||
expect(tx.complianceSettings.update).toHaveBeenCalledWith({
|
||||
where: { id: 'singleton' },
|
||||
data: expect.objectContaining({
|
||||
veterinaryOfficeName: 'Veterinäramt',
|
||||
tskReferenceDay: '04-15',
|
||||
tskReportDueDay: null,
|
||||
netQuantityDigitRules: [{ maxGrams: null, minMm: 3 }],
|
||||
}) as unknown,
|
||||
});
|
||||
expect(auditLog.record).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
entityType: 'ComplianceSettings',
|
||||
entityId: 'singleton',
|
||||
action: 'UPDATE',
|
||||
userId: 'u1',
|
||||
}),
|
||||
tx,
|
||||
);
|
||||
});
|
||||
|
||||
it('an omitted field keeps the stored value', async () => {
|
||||
await service.update({ noticeOnApiaryChange: false }, 'u1');
|
||||
|
||||
const call = (
|
||||
tx.complianceSettings.update.mock.calls as unknown[][]
|
||||
)[0][0] as {
|
||||
data: Record<string, unknown>;
|
||||
};
|
||||
expect(call.data.noticeOnApiaryChange).toBe(false);
|
||||
expect(call.data.tskReferenceDay).toBeUndefined();
|
||||
expect(call.data.veterinaryOfficeName).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { ComplianceSettings } from '../../generated/prisma';
|
||||
import { AuditLogService } from '../audit/audit-log.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { lockRowForUpdate } from '../prisma/row-lock';
|
||||
import { UpdateComplianceSettingsDto } from './dto/update-compliance-settings.dto';
|
||||
import { complianceSettingsIn, COMPLIANCE_SETTINGS_ID } from './herd-status';
|
||||
import { isValidMonthDay } from './tsk-day';
|
||||
|
||||
const AUDIT_ENTITY = 'ComplianceSettings';
|
||||
const MIN_DIGIT_RULES = 1;
|
||||
const MAX_DIGIT_RULES = 10;
|
||||
const MIN_DIGIT_MM = 0.5;
|
||||
const MAX_DIGIT_MM = 20;
|
||||
|
||||
interface DigitRuleInput {
|
||||
maxGrams: number | null;
|
||||
minMm: number;
|
||||
}
|
||||
|
||||
// undefined keeps the stored value, null or blank clears it, anything else is
|
||||
// stored trimmed.
|
||||
function trimmedOrNull(
|
||||
value: string | null | undefined,
|
||||
): string | null | undefined {
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
return value?.trim() || null;
|
||||
}
|
||||
|
||||
function assertMonthDay(field: string, value: string | null | undefined): void {
|
||||
if (value != null && !isValidMonthDay(value)) {
|
||||
throw new BadRequestException(
|
||||
`${field} muss ein gültiger Tag im Format MM-TT sein (ohne 29. Februar)`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 1 to 10 rules, the limits strictly ascending, only the last without a
|
||||
* limit, every height between 0.5 and 20 mm. The values themselves are the
|
||||
* owner's assumption - nothing here knows what the law asks for.
|
||||
*/
|
||||
function assertDigitRules(rules: readonly DigitRuleInput[]): void {
|
||||
if (rules.length < MIN_DIGIT_RULES || rules.length > MAX_DIGIT_RULES) {
|
||||
throw new BadRequestException(
|
||||
`Es braucht ${MIN_DIGIT_RULES} bis ${MAX_DIGIT_RULES} Regeln für die Ziffernhöhe`,
|
||||
);
|
||||
}
|
||||
let previous = 0;
|
||||
rules.forEach((rule, index) => {
|
||||
const isLast = index === rules.length - 1;
|
||||
if (rule.minMm < MIN_DIGIT_MM || rule.minMm > MAX_DIGIT_MM) {
|
||||
throw new BadRequestException(
|
||||
`Die Ziffernhöhe muss zwischen ${MIN_DIGIT_MM} und ${MAX_DIGIT_MM} mm liegen`,
|
||||
);
|
||||
}
|
||||
if (isLast) {
|
||||
if (rule.maxGrams !== null) {
|
||||
throw new BadRequestException(
|
||||
'Die letzte Regel gilt für alles darüber und hat keine Obergrenze',
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (rule.maxGrams === null || rule.maxGrams <= previous) {
|
||||
throw new BadRequestException(
|
||||
'Die Obergrenzen der Regeln müssen aufsteigen, nur die letzte hat keine',
|
||||
);
|
||||
}
|
||||
previous = rule.maxGrams;
|
||||
});
|
||||
}
|
||||
|
||||
function assertUnique(values: readonly string[]): void {
|
||||
if (new Set(values).size !== values.length) {
|
||||
throw new BadRequestException('Eine Völkerart steht doppelt in der Liste');
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ComplianceSettingsService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly auditLog: AuditLogService,
|
||||
) {}
|
||||
|
||||
/** Find-or-create, like SiteSettings. */
|
||||
get(): Promise<ComplianceSettings> {
|
||||
return complianceSettingsIn(this.prisma);
|
||||
}
|
||||
|
||||
async update(
|
||||
dto: UpdateComplianceSettingsDto,
|
||||
actingUserId: string,
|
||||
): Promise<ComplianceSettings> {
|
||||
assertMonthDay('Der Stichtag', dto.tskReferenceDay);
|
||||
assertMonthDay('Die Meldefrist', dto.tskReportDueDay);
|
||||
if (dto.tskExcludedColonyTypes) {
|
||||
assertUnique(dto.tskExcludedColonyTypes);
|
||||
}
|
||||
const digitRules = dto.netQuantityDigitRules?.map((rule) => ({
|
||||
maxGrams: rule.maxGrams ?? null,
|
||||
minMm: rule.minMm,
|
||||
}));
|
||||
if (digitRules) {
|
||||
assertDigitRules(digitRules);
|
||||
}
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
// The row must exist to be locked; "before" is read after the lock.
|
||||
await tx.complianceSettings.upsert({
|
||||
where: { id: COMPLIANCE_SETTINGS_ID },
|
||||
update: {},
|
||||
create: { id: COMPLIANCE_SETTINGS_ID },
|
||||
});
|
||||
await lockRowForUpdate(tx, 'ComplianceSettings', COMPLIANCE_SETTINGS_ID);
|
||||
const before = await tx.complianceSettings.findUniqueOrThrow({
|
||||
where: { id: COMPLIANCE_SETTINGS_ID },
|
||||
});
|
||||
const settings = await tx.complianceSettings.update({
|
||||
where: { id: COMPLIANCE_SETTINGS_ID },
|
||||
data: {
|
||||
veterinaryOfficeName: trimmedOrNull(dto.veterinaryOfficeName),
|
||||
veterinaryOfficeAddress: trimmedOrNull(dto.veterinaryOfficeAddress),
|
||||
registrationNumber: trimmedOrNull(dto.registrationNumber),
|
||||
noticeOnColonyCountChange: dto.noticeOnColonyCountChange,
|
||||
noticeOnApiaryChange: dto.noticeOnApiaryChange,
|
||||
tskReferenceDay: dto.tskReferenceDay,
|
||||
tskReportDueDay: dto.tskReportDueDay,
|
||||
tskMemberNumber: trimmedOrNull(dto.tskMemberNumber),
|
||||
tskExcludedColonyTypes: dto.tskExcludedColonyTypes,
|
||||
netQuantityDigitRules: digitRules,
|
||||
},
|
||||
});
|
||||
await this.auditLog.record(
|
||||
{
|
||||
entityType: AUDIT_ENTITY,
|
||||
entityId: COMPLIANCE_SETTINGS_ID,
|
||||
action: 'UPDATE',
|
||||
userId: actingUserId,
|
||||
beforeData: before,
|
||||
afterData: settings,
|
||||
},
|
||||
tx,
|
||||
);
|
||||
return settings;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
import type { Prisma } from '../../generated/prisma';
|
||||
import type {
|
||||
AnyDomainEventEnvelope,
|
||||
DomainEventType,
|
||||
} from '../domain-events/domain-event-types';
|
||||
import { domainEventHandlerMetadata } from '../domain-events/on-domain-event.decorator';
|
||||
import type { NotificationsService } from '../notifications/notifications.service';
|
||||
import type { AuthorityNoticesService } from './authority-notices.service';
|
||||
import { ComplianceEventHandlers } from './compliance.handlers';
|
||||
import { herdStatusIn } from './herd-status';
|
||||
|
||||
jest.mock('./herd-status', () => ({
|
||||
herdStatusIn: jest.fn(),
|
||||
complianceSettingsIn: jest.fn().mockResolvedValue({ id: 'singleton' }),
|
||||
}));
|
||||
jest.mock('../prisma/row-lock', () => ({
|
||||
lockRowForUpdate: jest.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
const herdStatus = herdStatusIn as jest.Mock;
|
||||
|
||||
const envelope = <T extends DomainEventType>(
|
||||
type: T,
|
||||
aggregateId: string,
|
||||
payload: Record<string, unknown>,
|
||||
) => ({ type, aggregateId, payload }) as unknown as AnyDomainEventEnvelope<T>;
|
||||
|
||||
const living = { status: 'ACTIVE', healthStatus: null };
|
||||
const ended = { status: 'SOLD', healthStatus: null };
|
||||
const NOW = new Date('2027-03-01T10:00:00Z');
|
||||
|
||||
/** A status with a baseline of 10 colonies on 2 apiaries, now 12 on 3. */
|
||||
const deviating = (triggered = true) => ({
|
||||
baseline: {
|
||||
totalColonies: 10,
|
||||
snapshot: { apiaries: [{ apiaryId: 'a1' }, { apiaryId: 'a2' }] },
|
||||
},
|
||||
current: {
|
||||
totalLiving: 12,
|
||||
apiaries: [{ apiaryId: 'a1' }, { apiaryId: 'a2' }, { apiaryId: 'a3' }],
|
||||
},
|
||||
deviation: { triggered },
|
||||
});
|
||||
|
||||
describe('ComplianceEventHandlers', () => {
|
||||
let notifications: { recordForPermissionOnce: jest.Mock };
|
||||
let notices: { createDraftIn: jest.Mock };
|
||||
let tx: {
|
||||
$queryRaw: jest.Mock;
|
||||
authorityNotice: { findMany: jest.Mock };
|
||||
};
|
||||
let handlers: ComplianceEventHandlers;
|
||||
|
||||
beforeEach(() => {
|
||||
herdStatus.mockReset().mockResolvedValue(deviating());
|
||||
notifications = {
|
||||
recordForPermissionOnce: jest.fn().mockResolvedValue([{ id: 'n1' }]),
|
||||
};
|
||||
notices = {
|
||||
createDraftIn: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ id: 'notice-1', totalColonies: 14 }),
|
||||
};
|
||||
tx = {
|
||||
$queryRaw: jest.fn().mockResolvedValue([{ now: NOW }]),
|
||||
authorityNotice: { findMany: jest.fn().mockResolvedValue([]) },
|
||||
};
|
||||
handlers = new ComplianceEventHandlers(
|
||||
notifications as unknown as NotificationsService,
|
||||
notices as unknown as AuthorityNoticesService,
|
||||
);
|
||||
});
|
||||
|
||||
const run = (
|
||||
event: AnyDomainEventEnvelope<
|
||||
'ColonyCreated' | 'ColonyStatusChanged' | 'ColonyEnded'
|
||||
>,
|
||||
) => handlers.herdChange(event, tx as unknown as Prisma.TransactionClient);
|
||||
|
||||
it('registers the two handler ids', () => {
|
||||
const ids = (method: object) =>
|
||||
domainEventHandlerMetadata(method).map((entry) => entry.handlerId);
|
||||
|
||||
// Metadata sits on the prototype function, not on a bound copy.
|
||||
const proto = Object.getPrototypeOf(handlers) as Record<string, object>;
|
||||
expect(ids(proto['herdChange'])).toEqual(['compliance.herd-change']);
|
||||
expect(ids(proto['tskReferenceDay'])).toEqual([
|
||||
'compliance.tsk-reference-day',
|
||||
]);
|
||||
});
|
||||
|
||||
describe('herd-change', () => {
|
||||
it('herd-change notifies each permitted user once while unread', async () => {
|
||||
await run(envelope('ColonyCreated', 'c1', { apiaryId: 'a1' }));
|
||||
|
||||
expect(herdStatus).toHaveBeenCalledWith(tx, NOW);
|
||||
expect(notifications.recordForPermissionOnce).toHaveBeenCalledWith(
|
||||
'compliance:manage',
|
||||
{
|
||||
priority: 'HINWEIS',
|
||||
category: 'COMPLIANCE',
|
||||
message:
|
||||
'Bestand geändert: jetzt 12 Völker an 3 Ständen. Angezeigt: 10 an 2. Anzeige ans Veterinäramt prüfen.',
|
||||
relatedType: 'ComplianceItem',
|
||||
relatedId: 'herd-change',
|
||||
link: '/compliance',
|
||||
},
|
||||
tx,
|
||||
);
|
||||
});
|
||||
|
||||
it('ignores a status change within living states and one within ended states', async () => {
|
||||
await run(
|
||||
envelope('ColonyStatusChanged', 'c1', { from: living, to: living }),
|
||||
);
|
||||
await run(
|
||||
envelope('ColonyStatusChanged', 'c1', { from: ended, to: ended }),
|
||||
);
|
||||
|
||||
expect(herdStatus).not.toHaveBeenCalled();
|
||||
expect(notifications.recordForPermissionOnce).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('handles a status change between living and ended', async () => {
|
||||
await run(
|
||||
envelope('ColonyStatusChanged', 'c1', { from: living, to: ended }),
|
||||
);
|
||||
await run(
|
||||
envelope('ColonyStatusChanged', 'c1', { from: ended, to: living }),
|
||||
);
|
||||
|
||||
expect(notifications.recordForPermissionOnce).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('handles an ended colony', async () => {
|
||||
await run(envelope('ColonyEnded', 'c1', { status: 'SOLD' }));
|
||||
|
||||
expect(notifications.recordForPermissionOnce).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does nothing without a baseline or without deviation', async () => {
|
||||
herdStatus.mockResolvedValueOnce({ ...deviating(), deviation: null });
|
||||
herdStatus.mockResolvedValueOnce(deviating(false));
|
||||
|
||||
await run(envelope('ColonyCreated', 'c1', { apiaryId: 'a1' }));
|
||||
await run(envelope('ColonyCreated', 'c2', { apiaryId: 'a1' }));
|
||||
|
||||
expect(notifications.recordForPermissionOnce).not.toHaveBeenCalled();
|
||||
expect(notices.createDraftIn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('a settings toggle from false to true waits for the next herd event', async () => {
|
||||
herdStatus.mockResolvedValueOnce(deviating(false));
|
||||
herdStatus.mockResolvedValueOnce(deviating(true));
|
||||
|
||||
await run(envelope('ColonyCreated', 'c1', { apiaryId: 'a1' }));
|
||||
expect(notifications.recordForPermissionOnce).not.toHaveBeenCalled();
|
||||
|
||||
await run(envelope('ColonyCreated', 'c2', { apiaryId: 'a1' }));
|
||||
expect(notifications.recordForPermissionOnce).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('the message uses the exact wording with counts and never an address', async () => {
|
||||
herdStatus.mockResolvedValue({
|
||||
...deviating(),
|
||||
current: {
|
||||
totalLiving: 1,
|
||||
apiaries: [{ apiaryId: 'a1', address: 'Hauptstr. 1' }],
|
||||
},
|
||||
});
|
||||
|
||||
await run(envelope('ColonyCreated', 'c1', { apiaryId: 'a1' }));
|
||||
|
||||
const [, input] = notifications.recordForPermissionOnce.mock.calls[0] as [
|
||||
string,
|
||||
{ message: string },
|
||||
];
|
||||
expect(input.message).toBe(
|
||||
'Bestand geändert: jetzt 1 Völker an 1 Ständen. Angezeigt: 10 an 2. Anzeige ans Veterinäramt prüfen.',
|
||||
);
|
||||
expect(input.message).not.toContain('Hauptstr');
|
||||
expect(input.message.length).toBeLessThan(600);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tsk-reference-day', () => {
|
||||
const tskEvent = envelope('TskReferenceDayReached', 'tsk:2027', {
|
||||
year: 2027,
|
||||
referenceDay: '2027-03-15',
|
||||
});
|
||||
const runTsk = () =>
|
||||
handlers.tskReferenceDay(
|
||||
tskEvent,
|
||||
tx as unknown as Prisma.TransactionClient,
|
||||
);
|
||||
|
||||
it('tsk handler creates one draft and skips a year already sent', async () => {
|
||||
await runTsk();
|
||||
|
||||
expect(notices.createDraftIn).toHaveBeenCalledWith(
|
||||
tx,
|
||||
{
|
||||
kind: 'TSK_REPORT',
|
||||
year: 2027,
|
||||
referenceDate: new Date('2027-03-15T00:00:00.000Z'),
|
||||
},
|
||||
null,
|
||||
);
|
||||
expect(tx.authorityNotice.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({
|
||||
kind: 'TSK_REPORT',
|
||||
year: 2027,
|
||||
}) as unknown,
|
||||
}),
|
||||
);
|
||||
|
||||
notices.createDraftIn.mockClear();
|
||||
tx.authorityNotice.findMany.mockResolvedValue([
|
||||
{ id: 'sent-1', status: 'SENT', totalColonies: 3 },
|
||||
]);
|
||||
await runTsk();
|
||||
|
||||
expect(notices.createDraftIn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('tsk handler with an existing draft creates none but still reminds', async () => {
|
||||
tx.authorityNotice.findMany.mockResolvedValue([
|
||||
{ id: 'draft-1', status: 'DRAFT', totalColonies: 9 },
|
||||
]);
|
||||
|
||||
await runTsk();
|
||||
|
||||
expect(notices.createDraftIn).not.toHaveBeenCalled();
|
||||
expect(notifications.recordForPermissionOnce).toHaveBeenCalledWith(
|
||||
'compliance:manage',
|
||||
expect.objectContaining({
|
||||
message:
|
||||
'TSK-Stichtag 15.03.2027: 9 Völker gezählt. Bitte prüfen und melden.',
|
||||
link: '/compliance/notices/draft-1',
|
||||
}),
|
||||
tx,
|
||||
);
|
||||
});
|
||||
|
||||
it('tsk handler stays silent when the year was sent', async () => {
|
||||
tx.authorityNotice.findMany.mockResolvedValue([
|
||||
{ id: 's', status: 'SENT', totalColonies: 3 },
|
||||
]);
|
||||
|
||||
await runTsk();
|
||||
|
||||
expect(notifications.recordForPermissionOnce).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('tsk handler notifies with WARNUNG and the exact wording', async () => {
|
||||
await runTsk();
|
||||
|
||||
expect(notifications.recordForPermissionOnce).toHaveBeenCalledWith(
|
||||
'compliance:manage',
|
||||
{
|
||||
priority: 'WARNUNG',
|
||||
category: 'COMPLIANCE',
|
||||
message:
|
||||
'TSK-Stichtag 15.03.2027: 14 Völker gezählt. Bitte prüfen und melden.',
|
||||
relatedType: 'ComplianceItem',
|
||||
relatedId: 'tsk-report:2027',
|
||||
link: '/compliance/notices/notice-1',
|
||||
},
|
||||
tx,
|
||||
);
|
||||
});
|
||||
|
||||
it('a second handler run for the same event adds no second draft', async () => {
|
||||
await runTsk();
|
||||
// The first run left a draft behind.
|
||||
tx.authorityNotice.findMany.mockResolvedValue([
|
||||
{ id: 'notice-1', status: 'DRAFT', totalColonies: 14 },
|
||||
]);
|
||||
await runTsk();
|
||||
|
||||
// The notification itself is deduplicated by recordForPermissionOnce.
|
||||
expect(notices.createDraftIn).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { Prisma } from '../../generated/prisma';
|
||||
import { isLivingColonyStatus } from '../colonies/colony-status';
|
||||
import { dayToDate } from '../common/dates';
|
||||
import type { AnyDomainEventEnvelope } from '../domain-events/domain-event-types';
|
||||
import { OnDomainEvent } from '../domain-events/on-domain-event.decorator';
|
||||
import { NotificationsService } from '../notifications/notifications.service';
|
||||
import { lockRowForUpdate } from '../prisma/row-lock';
|
||||
import { AuthorityNoticesService } from './authority-notices.service';
|
||||
import type { HerdSnapshot } from './herd-snapshot';
|
||||
import {
|
||||
COMPLIANCE_SETTINGS_ID,
|
||||
complianceSettingsIn,
|
||||
herdStatusIn,
|
||||
} from './herd-status';
|
||||
|
||||
const RECIPIENT_PERMISSION = 'compliance:manage';
|
||||
const NOTICE_TOPIC = 'ComplianceItem';
|
||||
const HERD_CHANGE_TOPIC_ID = 'herd-change';
|
||||
|
||||
/** TT.MM.JJJJ for a YYYY-MM-DD day. */
|
||||
function germanDay(day: string): string {
|
||||
const [year, month, date] = day.split('-');
|
||||
return `${date}.${month}.${year}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The authority chain (T6): a change of the herd leaves one notification per
|
||||
* permitted user while the earlier one is unread, and the TSK reference day
|
||||
* prepares the year's count as a draft. Pure DB writers through the delivery
|
||||
* transaction; errors propagate so a delivery is retried. No handler creates
|
||||
* a herd-change notice: the owner reports, the app only reminds.
|
||||
*/
|
||||
@Injectable()
|
||||
export class ComplianceEventHandlers {
|
||||
constructor(
|
||||
private readonly notifications: NotificationsService,
|
||||
private readonly notices: AuthorityNoticesService,
|
||||
) {}
|
||||
|
||||
// A status change only matters when the colony enters or leaves the living
|
||||
// herd; ColonyEnded always does.
|
||||
@OnDomainEvent(
|
||||
[
|
||||
'ColonyCreated',
|
||||
'ColonyMoved',
|
||||
'ColonyEnded',
|
||||
'ColonyStatusChanged',
|
||||
'ApiaryChanged',
|
||||
],
|
||||
'compliance.herd-change',
|
||||
)
|
||||
async herdChange(
|
||||
event: AnyDomainEventEnvelope<
|
||||
| 'ColonyCreated'
|
||||
| 'ColonyMoved'
|
||||
| 'ColonyEnded'
|
||||
| 'ColonyStatusChanged'
|
||||
| 'ApiaryChanged'
|
||||
>,
|
||||
tx: Prisma.TransactionClient,
|
||||
): Promise<void> {
|
||||
if (event.type === 'ColonyStatusChanged') {
|
||||
const { from, to } = event.payload;
|
||||
if (
|
||||
isLivingColonyStatus(from.status) === isLivingColonyStatus(to.status)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// The deviation is computed before any notification lock (READ COMMITTED):
|
||||
// at worst a notification comes early or late, never twice.
|
||||
const [{ now }] = await tx.$queryRaw<{ now: Date }[]>`SELECT now() AS now`;
|
||||
const { baseline, current, deviation } = await herdStatusIn(tx, now);
|
||||
if (!baseline || !deviation?.triggered) {
|
||||
return;
|
||||
}
|
||||
const reported = baseline.snapshot as unknown as HerdSnapshot;
|
||||
await this.notifications.recordForPermissionOnce(
|
||||
RECIPIENT_PERMISSION,
|
||||
{
|
||||
priority: 'HINWEIS',
|
||||
category: 'COMPLIANCE',
|
||||
message: `Bestand geändert: jetzt ${current.totalLiving} Völker an ${current.apiaries.length} Ständen. Angezeigt: ${baseline.totalColonies} an ${reported.apiaries.length}. Anzeige ans Veterinäramt prüfen.`,
|
||||
relatedType: NOTICE_TOPIC,
|
||||
relatedId: HERD_CHANGE_TOPIC_ID,
|
||||
link: '/compliance',
|
||||
},
|
||||
tx,
|
||||
);
|
||||
}
|
||||
|
||||
// One draft per year. A year already sent stays silent; with only an open
|
||||
// draft nothing new is created, but the reminder is sent (once while
|
||||
// unread), since the draft may never have been opened. The settings row is
|
||||
// the mutex.
|
||||
@OnDomainEvent('TskReferenceDayReached', 'compliance.tsk-reference-day')
|
||||
async tskReferenceDay(
|
||||
event: AnyDomainEventEnvelope<'TskReferenceDayReached'>,
|
||||
tx: Prisma.TransactionClient,
|
||||
): Promise<void> {
|
||||
const { year, referenceDay } = event.payload;
|
||||
await complianceSettingsIn(tx);
|
||||
await lockRowForUpdate(tx, 'ComplianceSettings', COMPLIANCE_SETTINGS_ID);
|
||||
const existing = await tx.authorityNotice.findMany({
|
||||
where: { kind: 'TSK_REPORT', year, status: { in: ['SENT', 'DRAFT'] } },
|
||||
select: { id: true, status: true, totalColonies: true },
|
||||
});
|
||||
if (existing.some((notice) => notice.status === 'SENT')) {
|
||||
return;
|
||||
}
|
||||
const draft =
|
||||
existing[0] ??
|
||||
(await this.notices.createDraftIn(
|
||||
tx,
|
||||
{ kind: 'TSK_REPORT', year, referenceDate: dayToDate(referenceDay) },
|
||||
null,
|
||||
));
|
||||
await this.notifications.recordForPermissionOnce(
|
||||
RECIPIENT_PERMISSION,
|
||||
{
|
||||
priority: 'WARNUNG',
|
||||
category: 'COMPLIANCE',
|
||||
message: `TSK-Stichtag ${germanDay(referenceDay)}: ${draft.totalColonies} Völker gezählt. Bitte prüfen und melden.`,
|
||||
relatedType: NOTICE_TOPIC,
|
||||
relatedId: `tsk-report:${year}`,
|
||||
link: `/compliance/notices/${draft.id}`,
|
||||
},
|
||||
tx,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { NotificationsModule } from '../notifications/notifications.module';
|
||||
import { AuthorityNoticesController } from './authority-notices.controller';
|
||||
import { AuthorityNoticesService } from './authority-notices.service';
|
||||
import { ComplianceEventHandlers } from './compliance.handlers';
|
||||
import { ComplianceSettingsController } from './compliance-settings.controller';
|
||||
import { ComplianceSettingsService } from './compliance-settings.service';
|
||||
|
||||
// No provider here may inject PermissionResolverService: the worker imports
|
||||
// this module too (it carries the event handlers).
|
||||
@Module({
|
||||
imports: [NotificationsModule],
|
||||
controllers: [ComplianceSettingsController, AuthorityNoticesController],
|
||||
providers: [
|
||||
ComplianceSettingsService,
|
||||
AuthorityNoticesService,
|
||||
ComplianceEventHandlers,
|
||||
],
|
||||
exports: [ComplianceSettingsService, AuthorityNoticesService],
|
||||
})
|
||||
export class ComplianceModule {}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import {
|
||||
IsDateString,
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsOptional,
|
||||
Matches,
|
||||
Max,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
import { AuthorityNoticeKind } from '../../../generated/prisma';
|
||||
|
||||
export const DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
||||
export const DAY_MESSAGE = 'muss ein Datum im Format JJJJ-MM-TT sein';
|
||||
export const MIN_NOTICE_YEAR = 2000;
|
||||
export const MAX_NOTICE_YEAR = 2100;
|
||||
|
||||
export class CreateAuthorityNoticeDto {
|
||||
@ApiProperty({ enum: AuthorityNoticeKind })
|
||||
@IsEnum(AuthorityNoticeKind)
|
||||
kind!: AuthorityNoticeKind;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'Nur für die TSK-Zählung (dort Pflicht)',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(MIN_NOTICE_YEAR)
|
||||
@Max(MAX_NOTICE_YEAR)
|
||||
year?: number;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
example: '2027-01-01',
|
||||
description: 'Vorgabe: heute (Berlin)',
|
||||
})
|
||||
@IsOptional()
|
||||
@Matches(DAY_PATTERN, { message: `referenceDate ${DAY_MESSAGE}` })
|
||||
@IsDateString({ strict: true })
|
||||
referenceDate?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
example: '2026-05-01',
|
||||
description:
|
||||
'Gesetzt: die Anzeige entsteht gleich als gesendet (Altbestand)',
|
||||
})
|
||||
@IsOptional()
|
||||
@Matches(DAY_PATTERN, { message: `sentOn ${DAY_MESSAGE}` })
|
||||
@IsDateString({ strict: true })
|
||||
sentOn?: string;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import {
|
||||
IsDateString,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Matches,
|
||||
MaxLength,
|
||||
} from 'class-validator';
|
||||
import { DAY_MESSAGE, DAY_PATTERN } from './create-authority-notice.dto';
|
||||
import { MAX_NOTICE_TEXT_LENGTH } from './update-authority-notice.dto';
|
||||
|
||||
export class MarkSentDto {
|
||||
@ApiPropertyOptional({
|
||||
example: '2027-01-15',
|
||||
description: 'Vorgabe: heute (Berlin)',
|
||||
})
|
||||
@IsOptional()
|
||||
@Matches(DAY_PATTERN, { message: `sentOn ${DAY_MESSAGE}` })
|
||||
@IsDateString({ strict: true })
|
||||
sentOn?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'z. B. E-Mail, Post' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(MAX_NOTICE_TEXT_LENGTH)
|
||||
sentVia?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Aktenzeichen' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(MAX_NOTICE_TEXT_LENGTH)
|
||||
reference?: string;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import { IsEnum, IsInt, IsOptional, Max, Min } from 'class-validator';
|
||||
import { AuthorityNoticeKind } from '../../../generated/prisma';
|
||||
import {
|
||||
MAX_NOTICE_YEAR,
|
||||
MIN_NOTICE_YEAR,
|
||||
} from './create-authority-notice.dto';
|
||||
|
||||
export class NoticeListQuery {
|
||||
@ApiPropertyOptional({ enum: AuthorityNoticeKind })
|
||||
@IsOptional()
|
||||
@IsEnum(AuthorityNoticeKind)
|
||||
kind?: AuthorityNoticeKind;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(MIN_NOTICE_YEAR)
|
||||
@Max(MAX_NOTICE_YEAR)
|
||||
year?: number;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import {
|
||||
IsDateString,
|
||||
IsInt,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Matches,
|
||||
MaxLength,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
import { IsOptionalNotNull } from '../../common/validation/is-optional-not-null';
|
||||
import { DAY_MESSAGE, DAY_PATTERN } from './create-authority-notice.dto';
|
||||
|
||||
export const MAX_NOTICE_TEXT_LENGTH = 300;
|
||||
export const MAX_NOTICE_NOTES_LENGTH = 2000;
|
||||
|
||||
export class UpdateAuthorityNoticeDto {
|
||||
@ApiPropertyOptional({
|
||||
description: 'Die angezeigte Zahl; bleibt korrigierbar',
|
||||
})
|
||||
@IsOptionalNotNull()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
totalColonies?: number;
|
||||
|
||||
@ApiPropertyOptional({ example: '2027-01-01' })
|
||||
@IsOptionalNotNull()
|
||||
@Matches(DAY_PATTERN, { message: `referenceDate ${DAY_MESSAGE}` })
|
||||
@IsDateString({ strict: true })
|
||||
referenceDate?: string;
|
||||
|
||||
@ApiPropertyOptional({ nullable: true, example: '2027-01-15' })
|
||||
@IsOptional()
|
||||
@Matches(DAY_PATTERN, { message: `sentOn ${DAY_MESSAGE}` })
|
||||
@IsDateString({ strict: true })
|
||||
sentOn?: string | null;
|
||||
|
||||
@ApiPropertyOptional({ nullable: true, description: 'z. B. E-Mail, Post' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(MAX_NOTICE_TEXT_LENGTH)
|
||||
sentVia?: string | null;
|
||||
|
||||
@ApiPropertyOptional({ nullable: true, description: 'Aktenzeichen' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(MAX_NOTICE_TEXT_LENGTH)
|
||||
reference?: string | null;
|
||||
|
||||
@ApiPropertyOptional({ nullable: true })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(MAX_NOTICE_NOTES_LENGTH)
|
||||
notes?: string | null;
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import {
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsEnum,
|
||||
IsNumber,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Matches,
|
||||
MaxLength,
|
||||
ValidateNested,
|
||||
} from 'class-validator';
|
||||
import { ColonyType } from '../../../generated/prisma';
|
||||
import { IsOptionalNotNull } from '../../common/validation/is-optional-not-null';
|
||||
|
||||
const MONTH_DAY_PATTERN = /^\d{2}-\d{2}$/;
|
||||
const MONTH_DAY_MESSAGE = 'muss ein Tag im Format MM-TT sein';
|
||||
const MAX_NAME_LENGTH = 200;
|
||||
const MAX_ADDRESS_LENGTH = 300;
|
||||
|
||||
/** One row of the label digit height table. Annahme - vom Inhaber zu prüfen. */
|
||||
export class NetQuantityDigitRuleDto {
|
||||
@ApiProperty({
|
||||
nullable: true,
|
||||
description: 'Obergrenze in g, null = alles darüber',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsNumber({ allowNaN: false, allowInfinity: false })
|
||||
maxGrams!: number | null;
|
||||
|
||||
@ApiProperty({ description: 'Mindesthöhe der Ziffern in mm' })
|
||||
@IsNumber({ allowNaN: false, allowInfinity: false })
|
||||
minMm!: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Legal values (deadlines, digit heights) are settings, not code. Every value
|
||||
* here is an assumption the owner has to check.
|
||||
*/
|
||||
export class UpdateComplianceSettingsDto {
|
||||
@ApiPropertyOptional({ nullable: true })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(MAX_NAME_LENGTH)
|
||||
veterinaryOfficeName?: string | null;
|
||||
|
||||
@ApiPropertyOptional({ nullable: true })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(MAX_ADDRESS_LENGTH)
|
||||
veterinaryOfficeAddress?: string | null;
|
||||
|
||||
@ApiPropertyOptional({ nullable: true })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(MAX_NAME_LENGTH)
|
||||
registrationNumber?: string | null;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptionalNotNull()
|
||||
@IsBoolean()
|
||||
noticeOnColonyCountChange?: boolean;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptionalNotNull()
|
||||
@IsBoolean()
|
||||
noticeOnApiaryChange?: boolean;
|
||||
|
||||
@ApiPropertyOptional({ example: '01-01', description: 'MM-TT, ohne 02-29' })
|
||||
@IsOptionalNotNull()
|
||||
@IsString()
|
||||
@Matches(MONTH_DAY_PATTERN, {
|
||||
message: `tskReferenceDay ${MONTH_DAY_MESSAGE}`,
|
||||
})
|
||||
tskReferenceDay?: string;
|
||||
|
||||
@ApiPropertyOptional({ nullable: true, example: '03-31' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Matches(MONTH_DAY_PATTERN, {
|
||||
message: `tskReportDueDay ${MONTH_DAY_MESSAGE}`,
|
||||
})
|
||||
tskReportDueDay?: string | null;
|
||||
|
||||
@ApiPropertyOptional({ nullable: true })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(MAX_NAME_LENGTH)
|
||||
tskMemberNumber?: string | null;
|
||||
|
||||
@ApiPropertyOptional({ enum: ColonyType, isArray: true })
|
||||
@IsOptionalNotNull()
|
||||
@IsArray()
|
||||
@IsEnum(ColonyType, { each: true })
|
||||
tskExcludedColonyTypes?: ColonyType[];
|
||||
|
||||
@ApiPropertyOptional({ type: [NetQuantityDigitRuleDto] })
|
||||
@IsOptionalNotNull()
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => NetQuantityDigitRuleDto)
|
||||
netQuantityDigitRules?: NetQuantityDigitRuleDto[];
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import { ColonyType } from '../../generated/prisma';
|
||||
import { LIVING_COLONY_WHERE } from '../colonies/colony-status';
|
||||
import {
|
||||
buildHerdSnapshot,
|
||||
herdDeviation,
|
||||
HerdApiaryRow,
|
||||
HerdSnapshot,
|
||||
loadHerdApiaryRows,
|
||||
} from './herd-snapshot';
|
||||
|
||||
const TAKEN_AT = new Date('2027-01-01T10:00:00.000Z');
|
||||
const ENABLED = { noticeOnColonyCountChange: true, noticeOnApiaryChange: true };
|
||||
const P = ColonyType.PRODUCTION_COLONY;
|
||||
const N = ColonyType.NUCLEUS_COLONY;
|
||||
|
||||
function row(
|
||||
apiaryId: string,
|
||||
colonyTypes: ColonyType[],
|
||||
patch: Partial<HerdApiaryRow> = {},
|
||||
): HerdApiaryRow {
|
||||
return {
|
||||
apiaryId,
|
||||
name: `Stand ${apiaryId}`,
|
||||
address: `Weg ${apiaryId}`,
|
||||
location: null,
|
||||
latitude: 48.1,
|
||||
longitude: 11.5,
|
||||
colonyTypes,
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
describe('buildHerdSnapshot', () => {
|
||||
it('counts per apiary and per type', () => {
|
||||
const snapshot = buildHerdSnapshot(
|
||||
[row('a', [P, P, N]), row('b', [P])],
|
||||
TAKEN_AT,
|
||||
);
|
||||
|
||||
expect(snapshot.version).toBe(1);
|
||||
expect(snapshot.takenAt).toBe(TAKEN_AT.toISOString());
|
||||
expect(snapshot.totalLiving).toBe(4);
|
||||
expect(snapshot.apiaries[0]).toMatchObject({
|
||||
apiaryId: 'a',
|
||||
livingColonies: 3,
|
||||
byType: { PRODUCTION_COLONY: 2, NUCLEUS_COLONY: 1 },
|
||||
});
|
||||
});
|
||||
|
||||
it('excluded colony types do not count', () => {
|
||||
const snapshot = buildHerdSnapshot([row('a', [P, N, N])], TAKEN_AT, [N]);
|
||||
|
||||
expect(snapshot.totalLiving).toBe(1);
|
||||
expect(snapshot.apiaries[0].byType).toEqual({ PRODUCTION_COLONY: 1 });
|
||||
});
|
||||
|
||||
it('keeps an apiary without colonies', () => {
|
||||
const snapshot = buildHerdSnapshot([row('a', [])], TAKEN_AT);
|
||||
|
||||
expect(snapshot.apiaries).toHaveLength(1);
|
||||
expect(snapshot.totalLiving).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadHerdApiaryRows', () => {
|
||||
it('counts only living colonies at active apiaries', async () => {
|
||||
const findMany = jest.fn().mockResolvedValue([
|
||||
{
|
||||
id: 'a',
|
||||
name: 'A',
|
||||
address: null,
|
||||
location: null,
|
||||
latitude: null,
|
||||
longitude: null,
|
||||
colonies: [{ colonyType: P }, { colonyType: N }],
|
||||
},
|
||||
]);
|
||||
const db = { apiary: { findMany } };
|
||||
|
||||
const rows = await loadHerdApiaryRows(db as never);
|
||||
|
||||
const args = (findMany.mock.calls as unknown[][])[0][0] as {
|
||||
where: unknown;
|
||||
select: { colonies: { where: unknown } };
|
||||
};
|
||||
expect(args.where).toEqual({ status: 'ACTIVE' });
|
||||
expect(args.select.colonies.where).toEqual(LIVING_COLONY_WHERE);
|
||||
expect(rows).toEqual([
|
||||
expect.objectContaining({ apiaryId: 'a', colonyTypes: [P, N] }),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('herdDeviation', () => {
|
||||
const base = [row('a', [P, P]), row('b', [P])];
|
||||
|
||||
function baselineOf(rows: HerdApiaryRow[], totalColonies?: number) {
|
||||
const snapshot = buildHerdSnapshot(rows, TAKEN_AT);
|
||||
return { snapshot, totalColonies: totalColonies ?? snapshot.totalLiving };
|
||||
}
|
||||
|
||||
it('no deviation without changes', () => {
|
||||
const deviation = herdDeviation(
|
||||
baselineOf(base),
|
||||
buildHerdSnapshot(base, TAKEN_AT),
|
||||
ENABLED,
|
||||
);
|
||||
|
||||
expect(deviation).toEqual({
|
||||
triggered: false,
|
||||
colonyCountChanged: false,
|
||||
apiariesAdded: [],
|
||||
apiariesRemoved: [],
|
||||
apiariesRelocated: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('count change triggers only when enabled', () => {
|
||||
const current = buildHerdSnapshot([row('a', [P, P, P]), base[1]], TAKEN_AT);
|
||||
|
||||
expect(herdDeviation(baselineOf(base), current, ENABLED).triggered).toBe(
|
||||
true,
|
||||
);
|
||||
const off = herdDeviation(baselineOf(base), current, {
|
||||
...ENABLED,
|
||||
noticeOnColonyCountChange: false,
|
||||
});
|
||||
expect(off.triggered).toBe(false);
|
||||
expect(off.colonyCountChanged).toBe(true);
|
||||
});
|
||||
|
||||
it('moving between apiaries keeps the total and triggers nothing', () => {
|
||||
const current = buildHerdSnapshot(
|
||||
[row('a', [P]), row('b', [P, P])],
|
||||
TAKEN_AT,
|
||||
);
|
||||
|
||||
const deviation = herdDeviation(baselineOf(base), current, ENABLED);
|
||||
|
||||
expect(deviation.colonyCountChanged).toBe(false);
|
||||
expect(deviation.triggered).toBe(false);
|
||||
});
|
||||
|
||||
it('new, removed or relocated apiary triggers when enabled', () => {
|
||||
const added = buildHerdSnapshot([...base, row('c', [])], TAKEN_AT);
|
||||
const removed = buildHerdSnapshot([base[0]], TAKEN_AT);
|
||||
const relocated = buildHerdSnapshot(
|
||||
[base[0], row('b', [P], { address: 'Neuer Weg 1' })],
|
||||
TAKEN_AT,
|
||||
);
|
||||
const sameCount = (current: HerdSnapshot) =>
|
||||
herdDeviation(baselineOf(base, current.totalLiving), current, ENABLED);
|
||||
|
||||
expect(sameCount(added)).toMatchObject({
|
||||
triggered: true,
|
||||
apiariesAdded: ['c'],
|
||||
});
|
||||
expect(sameCount(removed)).toMatchObject({
|
||||
triggered: true,
|
||||
apiariesRemoved: ['b'],
|
||||
});
|
||||
expect(sameCount(relocated)).toMatchObject({
|
||||
triggered: true,
|
||||
apiariesRelocated: ['b'],
|
||||
});
|
||||
expect(
|
||||
herdDeviation(baselineOf(base, 3), relocated, {
|
||||
...ENABLED,
|
||||
noticeOnApiaryChange: false,
|
||||
}).triggered,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('compares the count with the corrected totalColonies of the baseline', () => {
|
||||
const current = buildHerdSnapshot(base, TAKEN_AT);
|
||||
|
||||
const deviation = herdDeviation(baselineOf(base, 5), current, ENABLED);
|
||||
|
||||
expect(deviation.colonyCountChanged).toBe(true);
|
||||
expect(deviation.triggered).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,161 @@
|
||||
import { ColonyType, ComplianceSettings } from '../../generated/prisma';
|
||||
import { LIVING_COLONY_WHERE } from '../colonies/colony-status';
|
||||
import { DbClient } from '../prisma/db-client';
|
||||
|
||||
export const HERD_SNAPSHOT_VERSION = 1;
|
||||
|
||||
export interface HerdApiarySnapshot {
|
||||
apiaryId: string;
|
||||
name: string;
|
||||
address: string | null;
|
||||
location: string | null;
|
||||
latitude: number | null;
|
||||
longitude: number | null;
|
||||
livingColonies: number;
|
||||
byType: Partial<Record<ColonyType, number>>;
|
||||
}
|
||||
|
||||
export interface HerdSnapshot {
|
||||
version: 1;
|
||||
takenAt: string;
|
||||
apiaries: HerdApiarySnapshot[];
|
||||
totalLiving: number;
|
||||
}
|
||||
|
||||
/** An active apiary with the colony type of each living colony standing there. */
|
||||
export interface HerdApiaryRow {
|
||||
apiaryId: string;
|
||||
name: string;
|
||||
address: string | null;
|
||||
location: string | null;
|
||||
latitude: number | null;
|
||||
longitude: number | null;
|
||||
colonyTypes: ColonyType[];
|
||||
}
|
||||
|
||||
export interface HerdDeviation {
|
||||
triggered: boolean;
|
||||
colonyCountChanged: boolean;
|
||||
apiariesAdded: string[];
|
||||
apiariesRemoved: string[];
|
||||
apiariesRelocated: string[];
|
||||
}
|
||||
|
||||
type DeviationSettings = Pick<
|
||||
ComplianceSettings,
|
||||
'noticeOnColonyCountChange' | 'noticeOnApiaryChange'
|
||||
>;
|
||||
|
||||
/** Pure: counts the living colonies per apiary and per type. */
|
||||
export function buildHerdSnapshot(
|
||||
rows: readonly HerdApiaryRow[],
|
||||
takenAt: Date,
|
||||
excludedTypes: readonly ColonyType[] = [],
|
||||
): HerdSnapshot {
|
||||
const apiaries = rows.map((row): HerdApiarySnapshot => {
|
||||
const byType: Partial<Record<ColonyType, number>> = {};
|
||||
let livingColonies = 0;
|
||||
for (const type of row.colonyTypes) {
|
||||
if (excludedTypes.includes(type)) {
|
||||
continue;
|
||||
}
|
||||
byType[type] = (byType[type] ?? 0) + 1;
|
||||
livingColonies += 1;
|
||||
}
|
||||
return {
|
||||
apiaryId: row.apiaryId,
|
||||
name: row.name,
|
||||
address: row.address,
|
||||
location: row.location,
|
||||
latitude: row.latitude,
|
||||
longitude: row.longitude,
|
||||
livingColonies,
|
||||
byType,
|
||||
};
|
||||
});
|
||||
return {
|
||||
version: HERD_SNAPSHOT_VERSION,
|
||||
takenAt: takenAt.toISOString(),
|
||||
apiaries,
|
||||
totalLiving: apiaries.reduce(
|
||||
(sum, apiary) => sum + apiary.livingColonies,
|
||||
0,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/** Active apiaries with their living colonies (LIVING_COLONY_WHERE). */
|
||||
export async function loadHerdApiaryRows(
|
||||
db: DbClient,
|
||||
): Promise<HerdApiaryRow[]> {
|
||||
const apiaries = await db.apiary.findMany({
|
||||
where: { status: 'ACTIVE' },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
address: true,
|
||||
location: true,
|
||||
latitude: true,
|
||||
longitude: true,
|
||||
colonies: { where: LIVING_COLONY_WHERE, select: { colonyType: true } },
|
||||
},
|
||||
orderBy: [{ name: 'asc' }, { id: 'asc' }],
|
||||
});
|
||||
return apiaries.map((apiary) => ({
|
||||
apiaryId: apiary.id,
|
||||
name: apiary.name,
|
||||
address: apiary.address,
|
||||
location: apiary.location,
|
||||
latitude: apiary.latitude,
|
||||
longitude: apiary.longitude,
|
||||
colonyTypes: apiary.colonies.map((colony) => colony.colonyType),
|
||||
}));
|
||||
}
|
||||
|
||||
function sameSite(a: HerdApiarySnapshot, b: HerdApiarySnapshot): boolean {
|
||||
return (
|
||||
a.address === b.address &&
|
||||
a.location === b.location &&
|
||||
a.latitude === b.latitude &&
|
||||
a.longitude === b.longitude
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* How the current herd differs from the baseline. The count is compared with
|
||||
* the corrected `totalColonies` of the notice, not with its snapshot. A move
|
||||
* between apiaries keeps the total and triggers nothing.
|
||||
*/
|
||||
export function herdDeviation(
|
||||
baseline: { snapshot: HerdSnapshot; totalColonies: number },
|
||||
current: HerdSnapshot,
|
||||
settings: DeviationSettings,
|
||||
): HerdDeviation {
|
||||
const before = new Map(
|
||||
baseline.snapshot.apiaries.map((apiary) => [apiary.apiaryId, apiary]),
|
||||
);
|
||||
const now = new Map(
|
||||
current.apiaries.map((apiary) => [apiary.apiaryId, apiary]),
|
||||
);
|
||||
const apiariesAdded = [...now.keys()].filter((id) => !before.has(id));
|
||||
const apiariesRemoved = [...before.keys()].filter((id) => !now.has(id));
|
||||
const apiariesRelocated = [...now.entries()]
|
||||
.filter(([id, apiary]) => {
|
||||
const old = before.get(id);
|
||||
return old !== undefined && !sameSite(old, apiary);
|
||||
})
|
||||
.map(([id]) => id);
|
||||
const colonyCountChanged = baseline.totalColonies !== current.totalLiving;
|
||||
const apiaryChanged =
|
||||
apiariesAdded.length + apiariesRemoved.length + apiariesRelocated.length >
|
||||
0;
|
||||
return {
|
||||
triggered:
|
||||
(settings.noticeOnColonyCountChange && colonyCountChanged) ||
|
||||
(settings.noticeOnApiaryChange && apiaryChanged),
|
||||
colonyCountChanged,
|
||||
apiariesAdded,
|
||||
apiariesRemoved,
|
||||
apiariesRelocated,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { herdStatusIn } from './herd-status';
|
||||
|
||||
const NOW = new Date('2027-03-01T10:00:00.000Z');
|
||||
|
||||
function settings() {
|
||||
return {
|
||||
id: 'singleton',
|
||||
noticeOnColonyCountChange: true,
|
||||
noticeOnApiaryChange: true,
|
||||
tskExcludedColonyTypes: [],
|
||||
};
|
||||
}
|
||||
|
||||
function dbWith(baseline: unknown) {
|
||||
return {
|
||||
complianceSettings: {
|
||||
findUnique: jest.fn().mockResolvedValue(settings()),
|
||||
upsert: jest.fn().mockResolvedValue(settings()),
|
||||
},
|
||||
authorityNotice: { findFirst: jest.fn().mockResolvedValue(baseline) },
|
||||
apiary: {
|
||||
findMany: jest.fn().mockResolvedValue([
|
||||
{
|
||||
id: 'a',
|
||||
name: 'A',
|
||||
address: null,
|
||||
location: null,
|
||||
latitude: null,
|
||||
longitude: null,
|
||||
colonies: [{ colonyType: 'PRODUCTION_COLONY' }],
|
||||
},
|
||||
]),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('herdStatusIn', () => {
|
||||
it('no baseline means deviation null, not a herd change', async () => {
|
||||
const status = await herdStatusIn(dbWith(null) as never, NOW);
|
||||
|
||||
expect(status.baseline).toBeNull();
|
||||
expect(status.deviation).toBeNull();
|
||||
expect(status.current.totalLiving).toBe(1);
|
||||
});
|
||||
|
||||
it('the baseline is the newest SENT registration or herd change by sentOn and ignores TSK reports', async () => {
|
||||
const db = dbWith(null);
|
||||
|
||||
await herdStatusIn(db as never, NOW);
|
||||
|
||||
expect(db.authorityNotice.findFirst).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: {
|
||||
status: 'SENT',
|
||||
kind: { in: ['REGISTRATION', 'HERD_CHANGE'] },
|
||||
},
|
||||
orderBy: [{ sentOn: 'desc' }, { createdAt: 'desc' }, { id: 'desc' }],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('reports the deviation against the baseline', async () => {
|
||||
const baseline = {
|
||||
id: 'n1',
|
||||
totalColonies: 3,
|
||||
snapshot: {
|
||||
version: 1,
|
||||
takenAt: NOW.toISOString(),
|
||||
apiaries: [],
|
||||
totalLiving: 3,
|
||||
},
|
||||
};
|
||||
|
||||
const status = await herdStatusIn(dbWith(baseline) as never, NOW);
|
||||
|
||||
expect(status.deviation).toMatchObject({
|
||||
triggered: true,
|
||||
colonyCountChanged: true,
|
||||
apiariesAdded: ['a'],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { AuthorityNotice, ComplianceSettings } from '../../generated/prisma';
|
||||
import { DbClient } from '../prisma/db-client';
|
||||
import {
|
||||
buildHerdSnapshot,
|
||||
herdDeviation,
|
||||
HerdDeviation,
|
||||
HerdSnapshot,
|
||||
loadHerdApiaryRows,
|
||||
} from './herd-snapshot';
|
||||
|
||||
export const COMPLIANCE_SETTINGS_ID = 'singleton';
|
||||
|
||||
export interface HerdStatus {
|
||||
settings: ComplianceSettings;
|
||||
baseline: AuthorityNotice | null;
|
||||
current: HerdSnapshot;
|
||||
/** null without a baseline: there is nothing to deviate from. */
|
||||
deviation: HerdDeviation | null;
|
||||
}
|
||||
|
||||
/** The settings row, created with its defaults when it does not exist yet. */
|
||||
export async function complianceSettingsIn(
|
||||
db: DbClient,
|
||||
): Promise<ComplianceSettings> {
|
||||
const existing = await db.complianceSettings.findUnique({
|
||||
where: { id: COMPLIANCE_SETTINGS_ID },
|
||||
});
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
return db.complianceSettings.upsert({
|
||||
where: { id: COMPLIANCE_SETTINGS_ID },
|
||||
update: {},
|
||||
create: { id: COMPLIANCE_SETTINGS_ID },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The baseline is the newest SENT registration or herd change (by sentOn);
|
||||
* TSK reports go to another recipient and do not count.
|
||||
*/
|
||||
export function findBaselineIn(db: DbClient): Promise<AuthorityNotice | null> {
|
||||
return db.authorityNotice.findFirst({
|
||||
where: { status: 'SENT', kind: { in: ['REGISTRATION', 'HERD_CHANGE'] } },
|
||||
orderBy: [{ sentOn: 'desc' }, { createdAt: 'desc' }, { id: 'desc' }],
|
||||
});
|
||||
}
|
||||
|
||||
export async function herdStatusIn(
|
||||
db: DbClient,
|
||||
now: Date,
|
||||
): Promise<HerdStatus> {
|
||||
const settings = await complianceSettingsIn(db);
|
||||
const baseline = await findBaselineIn(db);
|
||||
const current = buildHerdSnapshot(await loadHerdApiaryRows(db), now);
|
||||
return {
|
||||
settings,
|
||||
baseline,
|
||||
current,
|
||||
deviation: baseline
|
||||
? herdDeviation(
|
||||
{
|
||||
snapshot: baseline.snapshot as unknown as HerdSnapshot,
|
||||
totalColonies: baseline.totalColonies,
|
||||
},
|
||||
current,
|
||||
settings,
|
||||
)
|
||||
: null,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
import type { AuthorityNotice } from '../../../generated/prisma';
|
||||
import type { HerdApiarySnapshot, HerdSnapshot } from '../herd-snapshot';
|
||||
import { buildNoticePdfModel } from './authority-notice-model';
|
||||
|
||||
function apiary(patch: Partial<HerdApiarySnapshot> = {}): HerdApiarySnapshot {
|
||||
return {
|
||||
apiaryId: 'a1',
|
||||
name: 'Heide',
|
||||
address: 'Heideweg 1, 34117 Kassel',
|
||||
location: 'Kassel',
|
||||
latitude: null,
|
||||
longitude: null,
|
||||
livingColonies: 3,
|
||||
byType: { PRODUCTION_COLONY: 2, NUCLEUS_COLONY: 1 },
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
function snapshot(apiaries: HerdApiarySnapshot[]): HerdSnapshot {
|
||||
return {
|
||||
version: 1,
|
||||
takenAt: '2027-01-02T10:00:00.000Z',
|
||||
apiaries,
|
||||
totalLiving: apiaries.reduce((sum, a) => sum + a.livingColonies, 0),
|
||||
};
|
||||
}
|
||||
|
||||
function notice(
|
||||
patch: Partial<AuthorityNotice> = {},
|
||||
apiaries: HerdApiarySnapshot[] = [apiary()],
|
||||
): AuthorityNotice {
|
||||
const snap = snapshot(apiaries);
|
||||
return {
|
||||
id: 'n1',
|
||||
kind: 'REGISTRATION',
|
||||
status: 'DRAFT',
|
||||
year: null,
|
||||
referenceDate: new Date('2027-01-01T00:00:00.000Z'),
|
||||
countedAt: new Date('2027-01-02T10:00:00.000Z'),
|
||||
snapshot: snap as never,
|
||||
totalColonies: snap.totalLiving,
|
||||
sentOn: null,
|
||||
sentVia: null,
|
||||
reference: null,
|
||||
notes: null,
|
||||
openKey: 'REGISTRATION',
|
||||
createdByUserId: null,
|
||||
createdAt: new Date(0),
|
||||
updatedAt: new Date('2027-01-03T09:00:00.000Z'),
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
const SITE = {
|
||||
holderName: 'Imkerei Muster',
|
||||
holderAddress: 'Weg 2, 34117 Kassel',
|
||||
};
|
||||
const SETTINGS = {
|
||||
veterinaryOfficeName: 'Veterinäramt Kassel' as string | null,
|
||||
veterinaryOfficeAddress: 'Amtsstr. 1, 34117 Kassel' as string | null,
|
||||
registrationNumber: 'DE-123' as string | null,
|
||||
tskMemberNumber: 'TSK-9' as string | null,
|
||||
};
|
||||
const NOW = new Date('2027-01-05T12:00:00.000Z');
|
||||
|
||||
function build(
|
||||
n: AuthorityNotice,
|
||||
baseline: AuthorityNotice | null = null,
|
||||
overrides: {
|
||||
site?: { holderName: string | null; holderAddress: string | null };
|
||||
settings?: typeof SETTINGS;
|
||||
} = {},
|
||||
) {
|
||||
return buildNoticePdfModel({
|
||||
notice: n,
|
||||
baseline,
|
||||
site: overrides.site ?? SITE,
|
||||
settings: overrides.settings ?? SETTINGS,
|
||||
now: NOW,
|
||||
});
|
||||
}
|
||||
|
||||
describe('buildNoticePdfModel', () => {
|
||||
it('keeps an empty veterinary office and an empty holder as null so the renderer prints FEHLT', () => {
|
||||
const model = build(notice(), null, {
|
||||
site: { holderName: null, holderAddress: ' ' },
|
||||
settings: {
|
||||
...SETTINGS,
|
||||
veterinaryOfficeName: '',
|
||||
veterinaryOfficeAddress: null,
|
||||
},
|
||||
});
|
||||
|
||||
expect(model.holder).toBeNull();
|
||||
expect(model.office).toEqual({ name: null, address: null });
|
||||
});
|
||||
|
||||
it('the first notice has the heading "Anzeige der Bienenhaltung (§ 1a BienSeuchV)" and no "vorher" column', () => {
|
||||
const model = build(notice());
|
||||
|
||||
expect(model.title).toBe('Anzeige der Bienenhaltung (§ 1a BienSeuchV)');
|
||||
expect(model.columns).toEqual(['Stand', 'Lage', 'Völker']);
|
||||
expect(model.rows[0].previous).toBeNull();
|
||||
expect(model.totals).toEqual({ current: 3, previous: null });
|
||||
expect(model.changes).toEqual([]);
|
||||
expect(model.referenceLine).toBe('Stand der Völker am 01.01.2027');
|
||||
});
|
||||
|
||||
it('the change notice shows the previous count per apiary and the totals', () => {
|
||||
const baseline = notice(
|
||||
{ kind: 'REGISTRATION', status: 'SENT', sentOn: new Date('2026-06-01') },
|
||||
[apiary({ livingColonies: 2 })],
|
||||
);
|
||||
const model = build(
|
||||
notice({ kind: 'HERD_CHANGE', openKey: 'HERD_CHANGE' }),
|
||||
baseline,
|
||||
);
|
||||
|
||||
expect(model.title).toBe(
|
||||
'Änderungsanzeige Bienenhaltung (§ 1a BienSeuchV)',
|
||||
);
|
||||
expect(model.columns).toEqual(['Stand', 'Lage', 'Völker', 'vorher']);
|
||||
expect(model.rows[0]).toMatchObject({
|
||||
name: 'Heide',
|
||||
cells: ['3'],
|
||||
previous: 2,
|
||||
});
|
||||
expect(model.totals).toEqual({ current: 3, previous: 2 });
|
||||
});
|
||||
|
||||
it('lists new and abandoned apiaries under "Änderungen seit der Anzeige vom {sentOn}"', () => {
|
||||
const baseline = notice(
|
||||
{ kind: 'REGISTRATION', status: 'SENT', sentOn: new Date('2026-06-01') },
|
||||
[apiary(), apiary({ apiaryId: 'a2', name: 'Alt', livingColonies: 1 })],
|
||||
);
|
||||
const model = build(
|
||||
notice({ kind: 'HERD_CHANGE' }, [
|
||||
apiary(),
|
||||
apiary({ apiaryId: 'a3', name: 'Neu', livingColonies: 1 }),
|
||||
]),
|
||||
baseline,
|
||||
);
|
||||
|
||||
expect(model.changes[0]).toBe(
|
||||
'Änderungen seit der Anzeige vom 01.06.2026:',
|
||||
);
|
||||
expect(model.changes).toContain('Stand „Neu“ neu');
|
||||
expect(model.changes).toContain('Stand „Alt“ aufgegeben');
|
||||
});
|
||||
|
||||
it('prints coordinates with five decimals only when there is no address', () => {
|
||||
const model = build(
|
||||
notice({}, [
|
||||
apiary({ apiaryId: 'a1', name: 'Mit', address: 'Weg 1' }),
|
||||
apiary({
|
||||
apiaryId: 'a2',
|
||||
name: 'Ohne',
|
||||
address: null,
|
||||
latitude: 51.3127,
|
||||
longitude: 9.4797,
|
||||
}),
|
||||
apiary({
|
||||
apiaryId: 'a3',
|
||||
name: 'Nichts',
|
||||
address: null,
|
||||
location: null,
|
||||
}),
|
||||
]),
|
||||
);
|
||||
|
||||
expect(model.rows.map((r) => r.location)).toEqual([
|
||||
'Weg 1',
|
||||
'51.31270, 9.47970',
|
||||
'FEHLT',
|
||||
]);
|
||||
});
|
||||
|
||||
it('the TSK model has one column per counted colony type and a sum', () => {
|
||||
const model = build(
|
||||
notice({ kind: 'TSK_REPORT', year: 2027, openKey: 'TSK_REPORT:2027' }),
|
||||
);
|
||||
|
||||
expect(model.title).toBe(
|
||||
'Zählnachweis Bienenvölker zum Stichtag 01.01.2027',
|
||||
);
|
||||
expect(model.columns).toEqual([
|
||||
'Stand',
|
||||
'Lage',
|
||||
'Wirtschaftsvolk',
|
||||
'Ableger',
|
||||
'Summe',
|
||||
]);
|
||||
expect(model.rows[0].cells).toEqual(['2', '1', '3']);
|
||||
expect(model.tskMemberNumber).toBe('TSK-9');
|
||||
expect(model.totals).toEqual({ current: 3, previous: null });
|
||||
});
|
||||
|
||||
it('the TSK model says "Gezählt am {countedAt}, nicht am Stichtag. Bitte prüfen." when counted after the reference day', () => {
|
||||
const late = build(notice({ kind: 'TSK_REPORT', year: 2027 }));
|
||||
const onTime = build(
|
||||
notice({
|
||||
kind: 'TSK_REPORT',
|
||||
year: 2027,
|
||||
countedAt: new Date('2026-12-31T23:30:00.000Z'),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(late.countedNote).toBe(
|
||||
'Gezählt am 02.01.2027, nicht am Stichtag. Bitte prüfen.',
|
||||
);
|
||||
expect(onTime.countedNote).toBe('Gezählt am 01.01.2027');
|
||||
});
|
||||
|
||||
it('the TSK footer says "Ersetzt nicht die Meldung an die Tierseuchenkasse."', () => {
|
||||
const model = build(notice({ kind: 'TSK_REPORT', year: 2027 }));
|
||||
|
||||
expect(model.footer).toContain(
|
||||
'Ersetzt nicht die Meldung an die Tierseuchenkasse.',
|
||||
);
|
||||
expect(model.footer).toContain(
|
||||
'Stand der Daten 03.01.2027 · erstellt mit ApiCore',
|
||||
);
|
||||
});
|
||||
|
||||
it('the registration footer has no TSK sentence and the TSK number stays out', () => {
|
||||
const model = build(notice());
|
||||
|
||||
expect(model.footer).toEqual([
|
||||
'Stand der Daten 03.01.2027 · erstellt mit ApiCore',
|
||||
]);
|
||||
expect(model.tskMemberNumber).toBeNull();
|
||||
expect(model.countedNote).toBeNull();
|
||||
});
|
||||
|
||||
it('derives the place from the last holder address line and dates the letter in Berlin time', () => {
|
||||
const model = build(notice());
|
||||
|
||||
expect(model.place).toBe('Kassel');
|
||||
expect(model.dateLine).toBe('Kassel, 05.01.2027');
|
||||
});
|
||||
|
||||
it('prints FEHLT for the address when only the holder name is entered', () => {
|
||||
const model = build(notice(), null, {
|
||||
site: { holderName: 'Imkerei Muster', holderAddress: null },
|
||||
});
|
||||
|
||||
expect(model.holder).toBe('Imkerei Muster, FEHLT');
|
||||
expect(model.place).toBeNull();
|
||||
expect(model.dateLine).toBe('05.01.2027');
|
||||
});
|
||||
|
||||
it('uses the stored total on both sides and notes a corrected total', () => {
|
||||
const baseline = notice(
|
||||
{
|
||||
kind: 'REGISTRATION',
|
||||
status: 'SENT',
|
||||
sentOn: new Date('2026-06-01'),
|
||||
totalColonies: 5,
|
||||
},
|
||||
[apiary({ livingColonies: 2 })],
|
||||
);
|
||||
const model = build(
|
||||
notice({ kind: 'HERD_CHANGE', totalColonies: 7 }),
|
||||
baseline,
|
||||
);
|
||||
|
||||
expect(model.totals).toEqual({ current: 7, previous: 5 });
|
||||
expect(model.totalNote).toBe('Gesamtzahl berichtigt (Summe der Stände: 3)');
|
||||
expect(model.changes).toContain('Zahl der Völker: 5 auf 7');
|
||||
});
|
||||
|
||||
it('has no total note while the total matches the rows', () => {
|
||||
expect(build(notice()).totalNote).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,247 @@
|
||||
import type {
|
||||
AuthorityNotice,
|
||||
AuthorityNoticeKind,
|
||||
ColonyType,
|
||||
ComplianceSettings,
|
||||
SiteSettings,
|
||||
} from '../../../generated/prisma';
|
||||
import { berlinDayOf } from '../../common/dates';
|
||||
import { formatDayDe } from '../../common/format-day';
|
||||
import type { HerdApiarySnapshot, HerdSnapshot } from '../herd-snapshot';
|
||||
|
||||
/** Printed in place of a mandatory particular that is not entered yet. */
|
||||
export const MISSING = 'FEHLT';
|
||||
|
||||
export interface NoticePdfModel {
|
||||
kind: AuthorityNoticeKind;
|
||||
title: string;
|
||||
holder: string | null;
|
||||
registrationNumber: string | null;
|
||||
tskMemberNumber: string | null;
|
||||
office: { name: string | null; address: string | null };
|
||||
place: string | null;
|
||||
dateLine: string;
|
||||
referenceLine: string;
|
||||
columns: string[];
|
||||
rows: {
|
||||
name: string;
|
||||
location: string;
|
||||
cells: string[];
|
||||
previous: number | null;
|
||||
}[];
|
||||
totals: { current: number; previous: number | null };
|
||||
changes: string[];
|
||||
/** Set when the stored total was corrected and differs from the rows. */
|
||||
totalNote: string | null;
|
||||
countedNote: string | null;
|
||||
footer: string[];
|
||||
}
|
||||
|
||||
export interface NoticePdfInput {
|
||||
notice: AuthorityNotice;
|
||||
baseline: AuthorityNotice | null;
|
||||
site: Pick<SiteSettings, 'holderName' | 'holderAddress'>;
|
||||
settings: Pick<
|
||||
ComplianceSettings,
|
||||
| 'veterinaryOfficeName'
|
||||
| 'veterinaryOfficeAddress'
|
||||
| 'registrationNumber'
|
||||
| 'tskMemberNumber'
|
||||
>;
|
||||
now: Date;
|
||||
}
|
||||
|
||||
const TITLE_REGISTRATION = 'Anzeige der Bienenhaltung (§ 1a BienSeuchV)';
|
||||
const TITLE_HERD_CHANGE = 'Änderungsanzeige Bienenhaltung (§ 1a BienSeuchV)';
|
||||
const TSK_DISCLAIMER = 'Ersetzt nicht die Meldung an die Tierseuchenkasse.';
|
||||
const COORDINATE_DECIMALS = 5;
|
||||
|
||||
/** In display order; the TSK columns follow it. */
|
||||
const COLONY_TYPES: readonly { type: ColonyType; label: string }[] = [
|
||||
{ type: 'PRODUCTION_COLONY', label: 'Wirtschaftsvolk' },
|
||||
{ type: 'NUCLEUS_COLONY', label: 'Ableger' },
|
||||
{ type: 'YOUNG_COLONY', label: 'Jungvolk' },
|
||||
{ type: 'CARETAKER_COLONY', label: 'Pflegevolk' },
|
||||
{ type: 'MATING_NUCLEUS', label: 'Begattungs-einheit' },
|
||||
{ type: 'RESERVE_COLONY', label: 'Reservevolk' },
|
||||
];
|
||||
|
||||
function clean(value: string | null | undefined): string | null {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed ? trimmed : null;
|
||||
}
|
||||
|
||||
/** A stored day (midnight UTC) as dd.mm.yyyy. */
|
||||
function storedDay(date: Date): string {
|
||||
return formatDayDe(date.toISOString().slice(0, 10), true);
|
||||
}
|
||||
|
||||
/** An instant as the dd.mm.yyyy of its Berlin calendar day. */
|
||||
function berlinDay(instant: Date): string {
|
||||
return formatDayDe(berlinDayOf(instant), true);
|
||||
}
|
||||
|
||||
/** The town of a "Street 1, 34117 Town" address, when it has a postcode. */
|
||||
function placeOf(address: string | null): string | null {
|
||||
const match = address ? /\b\d{5}\s+([^,\n]+?)\s*$/.exec(address) : null;
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
|
||||
function locationOf(apiary: HerdApiarySnapshot): string {
|
||||
const address = clean(apiary.address);
|
||||
if (address) {
|
||||
return address;
|
||||
}
|
||||
if (apiary.latitude !== null && apiary.longitude !== null) {
|
||||
return `${apiary.latitude.toFixed(COORDINATE_DECIMALS)}, ${apiary.longitude.toFixed(COORDINATE_DECIMALS)}`;
|
||||
}
|
||||
return clean(apiary.location) ?? MISSING;
|
||||
}
|
||||
|
||||
function sameSite(a: HerdApiarySnapshot, b: HerdApiarySnapshot): boolean {
|
||||
return (
|
||||
a.address === b.address &&
|
||||
a.location === b.location &&
|
||||
a.latitude === b.latitude &&
|
||||
a.longitude === b.longitude
|
||||
);
|
||||
}
|
||||
|
||||
function titleOf(notice: AuthorityNotice, hasBaseline: boolean): string {
|
||||
if (notice.kind === 'TSK_REPORT') {
|
||||
return `Zählnachweis Bienenvölker zum Stichtag ${storedDay(notice.referenceDate)}`;
|
||||
}
|
||||
return notice.kind === 'HERD_CHANGE' && hasBaseline
|
||||
? TITLE_HERD_CHANGE
|
||||
: TITLE_REGISTRATION;
|
||||
}
|
||||
|
||||
function changeLines(
|
||||
baseline: AuthorityNotice,
|
||||
before: HerdSnapshot,
|
||||
current: HerdSnapshot,
|
||||
currentTotal: number,
|
||||
): string[] {
|
||||
const old = new Map(before.apiaries.map((a) => [a.apiaryId, a]));
|
||||
const now = new Map(current.apiaries.map((a) => [a.apiaryId, a]));
|
||||
const lines = [
|
||||
`Änderungen seit der Anzeige vom ${baseline.sentOn ? storedDay(baseline.sentOn) : '–'}:`,
|
||||
];
|
||||
for (const apiary of current.apiaries) {
|
||||
const previous = old.get(apiary.apiaryId);
|
||||
if (!previous) {
|
||||
lines.push(`Stand „${apiary.name}“ neu`);
|
||||
} else if (!sameSite(previous, apiary)) {
|
||||
lines.push(`Stand „${apiary.name}“: Lage geändert`);
|
||||
}
|
||||
}
|
||||
for (const apiary of before.apiaries) {
|
||||
if (!now.has(apiary.apiaryId)) {
|
||||
lines.push(`Stand „${apiary.name}“ aufgegeben`);
|
||||
}
|
||||
}
|
||||
if (baseline.totalColonies !== currentTotal) {
|
||||
lines.push(
|
||||
`Zahl der Völker: ${baseline.totalColonies} auf ${currentTotal}`,
|
||||
);
|
||||
}
|
||||
return lines.length === 1 ? [...lines, 'keine'] : lines;
|
||||
}
|
||||
|
||||
function tskTypes(snapshot: HerdSnapshot) {
|
||||
return COLONY_TYPES.filter(({ type }) =>
|
||||
snapshot.apiaries.some((apiary) => (apiary.byType[type] ?? 0) > 0),
|
||||
);
|
||||
}
|
||||
|
||||
function footerOf(notice: AuthorityNotice): string[] {
|
||||
const lines = [
|
||||
`Stand der Daten ${berlinDay(notice.updatedAt)} · erstellt mit ApiCore`,
|
||||
];
|
||||
return notice.kind === 'TSK_REPORT' ? [...lines, TSK_DISCLAIMER] : lines;
|
||||
}
|
||||
|
||||
function countedNoteOf(notice: AuthorityNotice): string | null {
|
||||
if (notice.kind !== 'TSK_REPORT') {
|
||||
return null;
|
||||
}
|
||||
const counted = `Gezählt am ${berlinDay(notice.countedAt)}`;
|
||||
const countedDay = berlinDayOf(notice.countedAt);
|
||||
const referenceDay = notice.referenceDate.toISOString().slice(0, 10);
|
||||
return countedDay > referenceDay
|
||||
? `${counted}, nicht am Stichtag. Bitte prüfen.`
|
||||
: counted;
|
||||
}
|
||||
|
||||
/** Pure: everything the notice PDF prints, without any drawing. */
|
||||
export function buildNoticePdfModel(input: NoticePdfInput): NoticePdfModel {
|
||||
const { notice, baseline, site, settings, now } = input;
|
||||
const current = notice.snapshot as unknown as HerdSnapshot;
|
||||
const isTsk = notice.kind === 'TSK_REPORT';
|
||||
const compare = notice.kind === 'HERD_CHANGE' && baseline !== null;
|
||||
const before = compare
|
||||
? (baseline.snapshot as unknown as HerdSnapshot)
|
||||
: null;
|
||||
const previousOf = (apiaryId: string): number | null =>
|
||||
before
|
||||
? (before.apiaries.find((a) => a.apiaryId === apiaryId)?.livingColonies ??
|
||||
0)
|
||||
: null;
|
||||
|
||||
const types = isTsk ? tskTypes(current) : [];
|
||||
const columns = isTsk
|
||||
? ['Stand', 'Lage', ...types.map((t) => t.label), 'Summe']
|
||||
: ['Stand', 'Lage', 'Völker', ...(compare ? ['vorher'] : [])];
|
||||
const rows = current.apiaries.map((apiary) => ({
|
||||
name: apiary.name,
|
||||
location: locationOf(apiary),
|
||||
cells: isTsk
|
||||
? [
|
||||
...types.map((t) => String(apiary.byType[t.type] ?? 0)),
|
||||
String(apiary.livingColonies),
|
||||
]
|
||||
: [String(apiary.livingColonies)],
|
||||
previous: previousOf(apiary.apiaryId),
|
||||
}));
|
||||
|
||||
const holderName = clean(site.holderName);
|
||||
const holderAddress = clean(site.holderAddress);
|
||||
// One of the two missing is a gap worth printing; both missing is null.
|
||||
const holder =
|
||||
holderName || holderAddress
|
||||
? `${holderName ?? MISSING}, ${holderAddress ?? MISSING}`
|
||||
: '';
|
||||
const place = placeOf(clean(site.holderAddress));
|
||||
const today = berlinDay(now);
|
||||
|
||||
return {
|
||||
kind: notice.kind,
|
||||
title: titleOf(notice, baseline !== null),
|
||||
holder: holder || null,
|
||||
registrationNumber: clean(settings.registrationNumber),
|
||||
tskMemberNumber: isTsk ? clean(settings.tskMemberNumber) : null,
|
||||
office: {
|
||||
name: clean(settings.veterinaryOfficeName),
|
||||
address: clean(settings.veterinaryOfficeAddress),
|
||||
},
|
||||
place,
|
||||
dateLine: place ? `${place}, ${today}` : today,
|
||||
referenceLine: `Stand der Völker am ${storedDay(notice.referenceDate)}`,
|
||||
columns,
|
||||
rows,
|
||||
totals: {
|
||||
current: notice.totalColonies,
|
||||
previous: compare ? baseline.totalColonies : null,
|
||||
},
|
||||
totalNote:
|
||||
notice.totalColonies === current.totalLiving
|
||||
? null
|
||||
: `Gesamtzahl berichtigt (Summe der Stände: ${current.totalLiving})`,
|
||||
changes:
|
||||
compare && before
|
||||
? changeLines(baseline, before, current, notice.totalColonies)
|
||||
: [],
|
||||
countedNote: countedNoteOf(notice),
|
||||
footer: footerOf(notice),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import PDFDocument from 'pdfkit';
|
||||
import { PDF_MARGIN } from '../../export/pdf-table';
|
||||
import type { NoticePdfModel } from './authority-notice-model';
|
||||
import {
|
||||
noticeHeaderLines,
|
||||
renderAuthorityNoticePdf,
|
||||
} from './authority-notice-pdf';
|
||||
|
||||
function model(patch: Partial<NoticePdfModel> = {}): NoticePdfModel {
|
||||
return {
|
||||
kind: 'REGISTRATION',
|
||||
title: 'Anzeige der Bienenhaltung (§ 1a BienSeuchV)',
|
||||
holder: 'Imkerei Muster, Weg 2, 34117 Kassel',
|
||||
registrationNumber: 'DE-123',
|
||||
tskMemberNumber: null,
|
||||
office: { name: 'Veterinäramt Kassel', address: 'Amtsstr. 1' },
|
||||
place: 'Kassel',
|
||||
dateLine: 'Kassel, 05.01.2027',
|
||||
referenceLine: 'Stand der Völker am 01.01.2027',
|
||||
columns: ['Stand', 'Lage', 'Völker'],
|
||||
rows: [{ name: 'Heide', location: 'Weg 1', cells: ['3'], previous: null }],
|
||||
totals: { current: 3, previous: null },
|
||||
changes: [],
|
||||
totalNote: null,
|
||||
countedNote: null,
|
||||
footer: ['Stand der Daten 03.01.2027 · erstellt mit ApiCore'],
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
describe('noticeHeaderLines', () => {
|
||||
it('prints FEHLT for an empty veterinary office and an empty holder', () => {
|
||||
const lines = noticeHeaderLines(
|
||||
model({ holder: null, office: { name: null, address: null } }),
|
||||
);
|
||||
|
||||
expect(lines.holder).toBe('FEHLT');
|
||||
expect(lines.office).toEqual(['FEHLT']);
|
||||
});
|
||||
|
||||
it('prints the registration number or a dash, and FEHLT for a missing TSK number', () => {
|
||||
expect(
|
||||
noticeHeaderLines(model({ registrationNumber: null })).identifiers,
|
||||
).toEqual(['Registriernummer: –']);
|
||||
expect(
|
||||
noticeHeaderLines(model({ kind: 'TSK_REPORT', tskMemberNumber: null }))
|
||||
.identifiers,
|
||||
).toContain('TSK-Mitgliedsnummer: FEHLT');
|
||||
});
|
||||
|
||||
it('leaves out the recipient block for the TSK report', () => {
|
||||
expect(noticeHeaderLines(model({ kind: 'TSK_REPORT' })).office).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderAuthorityNoticePdf', () => {
|
||||
it.each([
|
||||
['REGISTRATION', model()],
|
||||
[
|
||||
'HERD_CHANGE',
|
||||
model({
|
||||
kind: 'HERD_CHANGE',
|
||||
columns: ['Stand', 'Lage', 'Völker', 'vorher'],
|
||||
rows: [{ name: 'Heide', location: 'Weg 1', cells: ['3'], previous: 2 }],
|
||||
totals: { current: 3, previous: 2 },
|
||||
changes: [
|
||||
'Änderungen seit der Anzeige vom 01.06.2026:',
|
||||
'Stand „Neu“ neu',
|
||||
],
|
||||
}),
|
||||
],
|
||||
[
|
||||
'TSK_REPORT',
|
||||
model({
|
||||
kind: 'TSK_REPORT',
|
||||
tskMemberNumber: 'TSK-9',
|
||||
columns: ['Stand', 'Lage', 'Wirtschaftsvolk', 'Summe'],
|
||||
rows: [
|
||||
{
|
||||
name: 'Heide',
|
||||
location: 'Weg 1',
|
||||
cells: ['3', '3'],
|
||||
previous: null,
|
||||
},
|
||||
],
|
||||
countedNote: 'Gezählt am 02.01.2027, nicht am Stichtag. Bitte prüfen.',
|
||||
footer: [
|
||||
'Stand der Daten 03.01.2027 · erstellt mit ApiCore',
|
||||
'Ersetzt nicht die Meldung an die Tierseuchenkasse.',
|
||||
],
|
||||
}),
|
||||
],
|
||||
])('renders a PDF buffer that starts with %PDF for %s', async (_kind, m) => {
|
||||
const buffer = await renderAuthorityNoticePdf(m);
|
||||
|
||||
expect(buffer.subarray(0, 4).toString('latin1')).toBe('%PDF');
|
||||
});
|
||||
|
||||
it('renders a notice without apiaries', async () => {
|
||||
const buffer = await renderAuthorityNoticePdf(
|
||||
model({ rows: [], totals: { current: 0, previous: null } }),
|
||||
);
|
||||
|
||||
expect(buffer.subarray(0, 4).toString('latin1')).toBe('%PDF');
|
||||
});
|
||||
});
|
||||
|
||||
function pageCount(buffer: Buffer): number {
|
||||
return (buffer.toString('latin1').match(/\/Type \/Page(?!s)/g) ?? []).length;
|
||||
}
|
||||
|
||||
function manyRows(count: number): NoticePdfModel['rows'] {
|
||||
return Array.from({ length: count }, (_, index) => ({
|
||||
name: `Bienenstand Müßiggang-Süd ${index + 1} am Fließgewässer`,
|
||||
location:
|
||||
'Äußere Gartenallee 12, Gemarkung Großalmerode, 37247 Großalmerode',
|
||||
cells: ['8'],
|
||||
previous: null,
|
||||
}));
|
||||
}
|
||||
|
||||
describe('notice PDF layout', () => {
|
||||
let restoreText = (): void => undefined;
|
||||
afterEach(() => restoreText());
|
||||
|
||||
it('keeps 15 apiaries with long addresses on one portrait page, signature included', async () => {
|
||||
const buffer = await renderAuthorityNoticePdf(
|
||||
model({ rows: manyRows(15), totals: { current: 120, previous: null } }),
|
||||
);
|
||||
|
||||
expect(pageCount(buffer)).toBe(1);
|
||||
});
|
||||
|
||||
it('prints the notes and the footer at the left margin after the table', async () => {
|
||||
const calls: { text: string; x: number }[] = [];
|
||||
type TextFn = (this: { x: number }, ...args: unknown[]) => unknown;
|
||||
const proto = PDFDocument.prototype as { text: TextFn };
|
||||
const original = proto.text;
|
||||
proto.text = function (this: { x: number }, ...args: unknown[]) {
|
||||
calls.push({
|
||||
text: String(args[0]),
|
||||
x: typeof args[1] === 'number' ? args[1] : this.x,
|
||||
});
|
||||
return original.apply(this, args);
|
||||
};
|
||||
restoreText = () => {
|
||||
proto.text = original;
|
||||
};
|
||||
|
||||
await renderAuthorityNoticePdf(
|
||||
model({
|
||||
rows: manyRows(3),
|
||||
totalNote: 'Gesamtzahl berichtigt (Summe der Stände: 24)',
|
||||
changes: [
|
||||
'Änderungen seit der Anzeige vom 01.06.2026:',
|
||||
'Stand „A“ neu',
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
for (const prefix of [
|
||||
'Gesamtzahl berichtigt',
|
||||
'Änderungen seit',
|
||||
'– Stand',
|
||||
'Stand der Daten',
|
||||
]) {
|
||||
const call = calls.find((c) => c.text.startsWith(prefix));
|
||||
expect(call?.x).toBe(PDF_MARGIN);
|
||||
}
|
||||
});
|
||||
|
||||
it('draws the TSK report landscape with room for the location column', async () => {
|
||||
const buffer = await renderAuthorityNoticePdf(
|
||||
model({
|
||||
kind: 'TSK_REPORT',
|
||||
columns: [
|
||||
'Stand',
|
||||
'Lage',
|
||||
'Wirtschaftsvolk',
|
||||
'Begattungs-einheit',
|
||||
'Summe',
|
||||
],
|
||||
rows: manyRows(15).map((row) => ({ ...row, cells: ['5', '3', '8'] })),
|
||||
totals: { current: 120, previous: null },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(buffer.toString('latin1')).toContain('/MediaBox [0 0 841.89');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,193 @@
|
||||
import PDFDocument from 'pdfkit';
|
||||
import {
|
||||
PDF_MARGIN,
|
||||
PdfColumn,
|
||||
drawTable,
|
||||
orDash,
|
||||
} from '../../export/pdf-table';
|
||||
import { MISSING, NoticePdfModel } from './authority-notice-model';
|
||||
|
||||
const NAME_WIDTH = 110;
|
||||
const MIN_NUMBER_WIDTH = 40;
|
||||
const NUMBER_PADDING = 8;
|
||||
const SIGNATURE_LINE_WIDTH = 200;
|
||||
|
||||
export interface NoticeHeaderLines {
|
||||
holder: string;
|
||||
identifiers: string[];
|
||||
/** The addressee block; empty for the TSK report (another recipient). */
|
||||
office: string[];
|
||||
}
|
||||
|
||||
/** Pure: the header texts, with FEHLT for every mandatory gap. */
|
||||
export function noticeHeaderLines(model: NoticePdfModel): NoticeHeaderLines {
|
||||
const isTsk = model.kind === 'TSK_REPORT';
|
||||
const identifiers = [`Registriernummer: ${orDash(model.registrationNumber)}`];
|
||||
if (isTsk) {
|
||||
identifiers.push(
|
||||
`TSK-Mitgliedsnummer: ${model.tskMemberNumber ?? MISSING}`,
|
||||
);
|
||||
}
|
||||
const office = isTsk
|
||||
? []
|
||||
: [
|
||||
model.office.name ?? MISSING,
|
||||
...(model.office.address ? [model.office.address] : []),
|
||||
];
|
||||
return { holder: model.holder ?? MISSING, identifiers, office };
|
||||
}
|
||||
|
||||
/** Room for the widest word of a header (it may break at a hyphen). */
|
||||
function numberWidth(doc: PDFKit.PDFDocument, header: string): number {
|
||||
doc.font('Helvetica-Bold').fontSize(8);
|
||||
const widest = Math.max(
|
||||
...header.split('-').map((part) => doc.widthOfString(part)),
|
||||
);
|
||||
return Math.max(MIN_NUMBER_WIDTH, Math.ceil(widest) + NUMBER_PADDING);
|
||||
}
|
||||
|
||||
function tableColumns(
|
||||
doc: PDFKit.PDFDocument,
|
||||
model: NoticePdfModel,
|
||||
): PdfColumn[] {
|
||||
const numeric = model.columns.slice(2).map((header) => ({
|
||||
header,
|
||||
width: numberWidth(doc, header),
|
||||
align: 'right' as const,
|
||||
}));
|
||||
const used = numeric.reduce((sum, column) => sum + column.width, 0);
|
||||
return [
|
||||
{ header: model.columns[0], width: NAME_WIDTH },
|
||||
{
|
||||
header: model.columns[1],
|
||||
width: doc.page.width - 2 * PDF_MARGIN - NAME_WIDTH - used,
|
||||
},
|
||||
...numeric,
|
||||
];
|
||||
}
|
||||
|
||||
/** Sums of the numeric columns, so the TSK table totals each colony type. */
|
||||
function totalsRow(model: NoticePdfModel): string[] {
|
||||
const isTsk = model.kind === 'TSK_REPORT';
|
||||
if (isTsk) {
|
||||
const typeCount = model.columns.length - 3;
|
||||
const sums = Array.from({ length: typeCount }, (_, index) =>
|
||||
model.rows.reduce((sum, row) => sum + Number(row.cells[index]), 0),
|
||||
);
|
||||
return ['Summe', '', ...sums.map(String), String(model.totals.current)];
|
||||
}
|
||||
return [
|
||||
'Summe',
|
||||
'',
|
||||
String(model.totals.current),
|
||||
...(model.totals.previous === null ? [] : [String(model.totals.previous)]),
|
||||
];
|
||||
}
|
||||
|
||||
function bodyRows(model: NoticePdfModel): string[][] {
|
||||
const rows = model.rows.map((row) => [
|
||||
row.name,
|
||||
row.location,
|
||||
...row.cells,
|
||||
...(row.previous === null || model.kind === 'TSK_REPORT'
|
||||
? []
|
||||
: [String(row.previous)]),
|
||||
]);
|
||||
return rows.length === 0 ? rows : [...rows, totalsRow(model)];
|
||||
}
|
||||
|
||||
function drawHeader(doc: PDFKit.PDFDocument, model: NoticePdfModel): void {
|
||||
const header = noticeHeaderLines(model);
|
||||
doc
|
||||
.font('Helvetica-Bold')
|
||||
.fontSize(10)
|
||||
.text(header.holder, PDF_MARGIN, PDF_MARGIN);
|
||||
doc.font('Helvetica').fontSize(9);
|
||||
for (const line of header.identifiers) writeLine(doc, line);
|
||||
if (header.office.length > 0) {
|
||||
doc.moveDown(1);
|
||||
doc.text(`An ${header.office[0]}`);
|
||||
for (const line of header.office.slice(1)) doc.text(` ${line}`);
|
||||
}
|
||||
doc.moveDown(0.6);
|
||||
doc.text(model.dateLine, { align: 'right' });
|
||||
doc.moveDown(0.6);
|
||||
doc.font('Helvetica-Bold').fontSize(13).text(model.title);
|
||||
doc.font('Helvetica').fontSize(9).text(model.referenceLine);
|
||||
doc.moveDown(0.6);
|
||||
}
|
||||
|
||||
/** A paragraph at the left margin; the table leaves x at its last column. */
|
||||
function writeLine(doc: PDFKit.PDFDocument, text: string): void {
|
||||
doc.text(text, PDF_MARGIN, doc.y, {
|
||||
width: doc.page.width - 2 * PDF_MARGIN,
|
||||
});
|
||||
}
|
||||
|
||||
function drawNotes(doc: PDFKit.PDFDocument, model: NoticePdfModel): void {
|
||||
doc.font('Helvetica').fontSize(9);
|
||||
if (model.totalNote) {
|
||||
writeLine(doc, model.totalNote);
|
||||
doc.moveDown(0.5);
|
||||
}
|
||||
if (model.changes.length > 0) {
|
||||
doc.font('Helvetica-Bold');
|
||||
writeLine(doc, model.changes[0]);
|
||||
doc.font('Helvetica');
|
||||
for (const line of model.changes.slice(1)) writeLine(doc, `– ${line}`);
|
||||
doc.moveDown(0.5);
|
||||
}
|
||||
if (model.countedNote) {
|
||||
writeLine(doc, model.countedNote);
|
||||
doc.moveDown(0.5);
|
||||
}
|
||||
}
|
||||
|
||||
function drawSignatureAndFooter(
|
||||
doc: PDFKit.PDFDocument,
|
||||
model: NoticePdfModel,
|
||||
): void {
|
||||
if (doc.y > doc.page.height - PDF_MARGIN - 110) doc.addPage();
|
||||
doc.moveDown(3);
|
||||
const y = doc.y;
|
||||
doc
|
||||
.moveTo(PDF_MARGIN, y)
|
||||
.lineTo(PDF_MARGIN + SIGNATURE_LINE_WIDTH, y)
|
||||
.lineWidth(0.5)
|
||||
.strokeColor('#000000')
|
||||
.stroke();
|
||||
doc
|
||||
.font('Helvetica')
|
||||
.fontSize(8)
|
||||
.text('Unterschrift', PDF_MARGIN, y + 3);
|
||||
doc.moveDown(1.5);
|
||||
doc.fillColor('#555555');
|
||||
for (const line of model.footer) writeLine(doc, line);
|
||||
doc.fillColor('#000000');
|
||||
}
|
||||
|
||||
export function renderAuthorityNoticePdf(
|
||||
model: NoticePdfModel,
|
||||
): Promise<Buffer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
// Seven colony-type columns need the width of a landscape page.
|
||||
const doc = new PDFDocument({
|
||||
size: 'A4',
|
||||
layout: model.kind === 'TSK_REPORT' ? 'landscape' : 'portrait',
|
||||
margin: PDF_MARGIN,
|
||||
});
|
||||
const chunks: Buffer[] = [];
|
||||
doc.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
doc.on('end', () => resolve(Buffer.concat(chunks)));
|
||||
doc.on('error', reject);
|
||||
|
||||
drawHeader(doc, model);
|
||||
drawTable(doc, tableColumns(doc, model), bodyRows(model), {
|
||||
boldLastRow: true,
|
||||
});
|
||||
doc.x = PDF_MARGIN;
|
||||
drawNotes(doc, model);
|
||||
drawSignatureAndFooter(doc, model);
|
||||
doc.end();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { AuditLogService } from '../../audit/audit-log.service';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { lockRowForUpdate } from '../../prisma/row-lock';
|
||||
import { AcknowledgementsService } from './acknowledgements.service';
|
||||
import { ReadinessService } from './readiness.service';
|
||||
import type { ReadinessItem, ReadinessRule } from './readiness.types';
|
||||
|
||||
jest.mock('../../prisma/row-lock', () => ({
|
||||
lockRowForUpdate: jest.fn().mockResolvedValue(true),
|
||||
}));
|
||||
|
||||
const lockMock = lockRowForUpdate as jest.Mock;
|
||||
const rules: ReadinessRule[] = [];
|
||||
const FINGERPRINT = 'a'.repeat(64);
|
||||
const NOTE = 'Geprüft, alles in Ordnung.';
|
||||
|
||||
function rule(patch: Partial<ReadinessRule>): ReadinessRule {
|
||||
return {
|
||||
key: 'soft',
|
||||
area: 'ETIKETTEN',
|
||||
severity: 'PRUEFEN',
|
||||
title: 'Weicher Punkt',
|
||||
legalBasis: null,
|
||||
acknowledgeable: true,
|
||||
evaluate: () => [],
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
function item(patch: Partial<ReadinessItem> = {}): ReadinessItem {
|
||||
return {
|
||||
key: 'soft',
|
||||
area: 'ETIKETTEN',
|
||||
severity: 'PRUEFEN',
|
||||
subjectId: 'global',
|
||||
title: 'Weicher Punkt',
|
||||
detail: 'Prüfen.',
|
||||
legalBasis: null,
|
||||
acknowledgeable: true,
|
||||
fingerprint: FINGERPRINT,
|
||||
subjects: [],
|
||||
more: 0,
|
||||
state: 'OPEN',
|
||||
acknowledgement: null,
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
function dto(patch: Record<string, string> = {}) {
|
||||
return {
|
||||
itemKey: 'soft',
|
||||
subjectId: 'global',
|
||||
fingerprint: FINGERPRINT,
|
||||
note: NOTE,
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
describe('AcknowledgementsService', () => {
|
||||
let service: AcknowledgementsService;
|
||||
let readiness: { evaluate: jest.Mock; invalidateSummary: jest.Mock };
|
||||
let auditLog: { record: jest.Mock };
|
||||
let tx: {
|
||||
complianceAcknowledgement: {
|
||||
create: jest.Mock;
|
||||
findUnique: jest.Mock;
|
||||
findUniqueOrThrow: jest.Mock;
|
||||
};
|
||||
$executeRaw: jest.Mock;
|
||||
};
|
||||
|
||||
function reportWith(...items: ReadinessItem[]) {
|
||||
readiness.evaluate.mockResolvedValue({
|
||||
status: 'OPEN',
|
||||
generatedAt: 'x',
|
||||
openCount: items.length,
|
||||
items,
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
rules.splice(
|
||||
0,
|
||||
rules.length,
|
||||
rule({}),
|
||||
rule({ key: 'must', severity: 'PFLICHT', acknowledgeable: false }),
|
||||
);
|
||||
lockMock.mockReset().mockResolvedValue(true);
|
||||
tx = {
|
||||
complianceAcknowledgement: {
|
||||
create: jest.fn().mockResolvedValue({
|
||||
id: 'ack1',
|
||||
note: NOTE,
|
||||
createdAt: new Date('2027-03-15T10:00:00.000Z'),
|
||||
user: { name: 'Imker Eins' },
|
||||
}),
|
||||
findUnique: jest.fn(),
|
||||
findUniqueOrThrow: jest.fn(),
|
||||
},
|
||||
$executeRaw: jest.fn().mockResolvedValue(1),
|
||||
};
|
||||
const prisma = {
|
||||
$transaction: jest.fn((callback: (client: unknown) => unknown) =>
|
||||
callback(tx),
|
||||
),
|
||||
} as unknown as PrismaService;
|
||||
readiness = { evaluate: jest.fn(), invalidateSummary: jest.fn() };
|
||||
auditLog = { record: jest.fn().mockResolvedValue(undefined) };
|
||||
service = new AcknowledgementsService(
|
||||
prisma,
|
||||
auditLog as unknown as AuditLogService,
|
||||
readiness as unknown as ReadinessService,
|
||||
rules,
|
||||
);
|
||||
reportWith(item());
|
||||
});
|
||||
|
||||
it('writes the acknowledgement and the audit entry in one transaction and returns the item acknowledged', async () => {
|
||||
const result = await service.create(dto(), 'u1');
|
||||
|
||||
expect(tx.complianceAcknowledgement.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: {
|
||||
itemKey: 'soft',
|
||||
subjectId: 'global',
|
||||
fingerprint: FINGERPRINT,
|
||||
note: NOTE,
|
||||
userId: 'u1',
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(auditLog.record).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
entityType: 'ComplianceAcknowledgement',
|
||||
entityId: 'ack1',
|
||||
action: 'CREATE',
|
||||
userId: 'u1',
|
||||
}),
|
||||
tx,
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
key: 'soft',
|
||||
state: 'ACKNOWLEDGED',
|
||||
acknowledgement: {
|
||||
id: 'ack1',
|
||||
note: NOTE,
|
||||
userName: 'Imker Eins',
|
||||
createdAt: '2027-03-15T10:00:00.000Z',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('refuses a stale fingerprint with 409', async () => {
|
||||
const error: unknown = await service
|
||||
.create(dto({ fingerprint: 'b'.repeat(64) }), 'u1')
|
||||
.catch((e: unknown) => e);
|
||||
|
||||
expect(error).toBeInstanceOf(ConflictException);
|
||||
expect((error as ConflictException).getResponse()).toEqual({
|
||||
code: 'READINESS_FINGERPRINT_STALE',
|
||||
message: 'Der Punkt hat sich geändert. Bitte neu laden.',
|
||||
});
|
||||
|
||||
expect(tx.complianceAcknowledgement.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses an item that is not open (gone or done) with 409', async () => {
|
||||
for (const setup of [
|
||||
() => reportWith(item({ state: 'DONE' })),
|
||||
() => reportWith(),
|
||||
]) {
|
||||
setup();
|
||||
const error: unknown = await service
|
||||
.create(dto(), 'u1')
|
||||
.catch((e: unknown) => e);
|
||||
|
||||
expect(error).toBeInstanceOf(ConflictException);
|
||||
expect((error as ConflictException).getResponse()).toMatchObject({
|
||||
code: 'READINESS_ITEM_NOT_OPEN',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it('refuses a PFLICHT item and an unknown item key with 400', async () => {
|
||||
await expect(
|
||||
service.create(dto({ itemKey: 'must' }), 'u1'),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
await expect(
|
||||
service.create(dto({ itemKey: 'nope' }), 'u1'),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
|
||||
expect(readiness.evaluate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('a note under 10 characters is a 400', async () => {
|
||||
await expect(
|
||||
service.create(dto({ note: ' kurz ' }), 'u1'),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
await expect(
|
||||
service.create(dto({ note: 'x'.repeat(2001) }), 'u1'),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
|
||||
it('revoke locks the acknowledgement row, sets revokedAt in SQL and audits', async () => {
|
||||
const row = {
|
||||
id: 'ack1',
|
||||
itemKey: 'soft',
|
||||
subjectId: 'global',
|
||||
fingerprint: FINGERPRINT,
|
||||
note: NOTE,
|
||||
revokedAt: null,
|
||||
};
|
||||
tx.complianceAcknowledgement.findUnique.mockResolvedValue(row);
|
||||
tx.complianceAcknowledgement.findUniqueOrThrow.mockResolvedValue({
|
||||
...row,
|
||||
revokedAt: new Date('2027-03-16T00:00:00.000Z'),
|
||||
revokedByUserId: 'u2',
|
||||
});
|
||||
|
||||
await service.revoke('ack1', 'u2');
|
||||
|
||||
expect(lockMock).toHaveBeenCalledWith(
|
||||
tx,
|
||||
'ComplianceAcknowledgement',
|
||||
'ack1',
|
||||
);
|
||||
expect(tx.$executeRaw).toHaveBeenCalledTimes(1);
|
||||
expect(auditLog.record).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
entityType: 'ComplianceAcknowledgement',
|
||||
entityId: 'ack1',
|
||||
action: 'UPDATE',
|
||||
userId: 'u2',
|
||||
beforeData: expect.objectContaining({ revokedAt: null }) as unknown,
|
||||
}),
|
||||
tx,
|
||||
);
|
||||
});
|
||||
|
||||
it('revoke refuses an already revoked acknowledgement and a missing one', async () => {
|
||||
tx.complianceAcknowledgement.findUnique.mockResolvedValue({
|
||||
id: 'ack1',
|
||||
revokedAt: new Date('2027-03-01T00:00:00.000Z'),
|
||||
});
|
||||
const revoked: unknown = await service
|
||||
.revoke('ack1', 'u2')
|
||||
.catch((e: unknown) => e);
|
||||
expect(revoked).toBeInstanceOf(ConflictException);
|
||||
expect((revoked as ConflictException).getResponse()).toMatchObject({
|
||||
code: 'READINESS_ACK_REVOKED',
|
||||
message: 'Die Quittung ist schon zurückgenommen.',
|
||||
});
|
||||
expect(tx.$executeRaw).not.toHaveBeenCalled();
|
||||
|
||||
lockMock.mockResolvedValue(false);
|
||||
await expect(service.revoke('gone', 'u2')).rejects.toBeInstanceOf(
|
||||
NotFoundException,
|
||||
);
|
||||
});
|
||||
|
||||
it('forgets the cached summary after an acknowledgement and after a revoke', async () => {
|
||||
await service.create(dto(), 'u1');
|
||||
expect(readiness.invalidateSummary).toHaveBeenCalledTimes(1);
|
||||
|
||||
tx.complianceAcknowledgement.findUnique.mockResolvedValue({
|
||||
id: 'ack1',
|
||||
revokedAt: null,
|
||||
});
|
||||
tx.complianceAcknowledgement.findUniqueOrThrow.mockResolvedValue({
|
||||
id: 'ack1',
|
||||
});
|
||||
await service.revoke('ack1', 'u2');
|
||||
expect(readiness.invalidateSummary).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('keeps the cache when the acknowledgement is refused', async () => {
|
||||
await service
|
||||
.create(dto({ fingerprint: 'b'.repeat(64) }), 'u1')
|
||||
.catch(() => undefined);
|
||||
|
||||
expect(readiness.invalidateSummary).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,167 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Inject,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { AuditLogService } from '../../audit/audit-log.service';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { lockRowForUpdate } from '../../prisma/row-lock';
|
||||
import type { CreateAcknowledgementDto } from './dto/create-acknowledgement.dto';
|
||||
import { ReadinessService } from './readiness.service';
|
||||
import type { ReadinessItem, ReadinessRule } from './readiness.types';
|
||||
import { READINESS_RULES_TOKEN } from './rules';
|
||||
|
||||
const AUDIT_ENTITY = 'ComplianceAcknowledgement';
|
||||
export const MIN_NOTE_LENGTH = 10;
|
||||
export const MAX_NOTE_LENGTH = 2000;
|
||||
const NO_PERMISSIONS: ReadonlySet<string> = new Set();
|
||||
|
||||
/** Stable codes of the 409 answers; the frontend switches on them. */
|
||||
export const READINESS_FINGERPRINT_STALE = 'READINESS_FINGERPRINT_STALE';
|
||||
export const READINESS_ITEM_NOT_OPEN = 'READINESS_ITEM_NOT_OPEN';
|
||||
export const READINESS_ACK_REVOKED = 'READINESS_ACK_REVOKED';
|
||||
|
||||
const STALE_MESSAGE = 'Der Punkt hat sich geändert. Bitte neu laden.';
|
||||
|
||||
@Injectable()
|
||||
export class AcknowledgementsService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly auditLog: AuditLogService,
|
||||
private readonly readiness: ReadinessService,
|
||||
@Inject(READINESS_RULES_TOKEN)
|
||||
private readonly rules: readonly ReadinessRule[],
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Acknowledges one open item as checked. The fingerprint must equal the one
|
||||
* of the item as it is computed now (409 otherwise). `permissions` only
|
||||
* decides which subjects the returned item shows.
|
||||
*/
|
||||
async create(
|
||||
dto: CreateAcknowledgementDto,
|
||||
userId: string,
|
||||
permissions: ReadonlySet<string> = NO_PERMISSIONS,
|
||||
): Promise<ReadinessItem> {
|
||||
const note = dto.note.trim();
|
||||
if (note.length < MIN_NOTE_LENGTH || note.length > MAX_NOTE_LENGTH) {
|
||||
throw new BadRequestException(
|
||||
`Die Notiz braucht ${MIN_NOTE_LENGTH} bis ${MAX_NOTE_LENGTH} Zeichen.`,
|
||||
);
|
||||
}
|
||||
const rule = this.rules.find((entry) => entry.key === dto.itemKey);
|
||||
if (!rule) {
|
||||
throw new BadRequestException('Diesen Prüfpunkt gibt es nicht.');
|
||||
}
|
||||
if (!rule.acknowledgeable) {
|
||||
throw new BadRequestException(
|
||||
'Dieser Prüfpunkt lässt sich nicht quittieren. Er muss behoben werden.',
|
||||
);
|
||||
}
|
||||
const report = await this.readiness.evaluate(new Date(), permissions);
|
||||
const item = report.items.find(
|
||||
(entry) => entry.key === dto.itemKey && entry.subjectId === dto.subjectId,
|
||||
);
|
||||
if (!item || item.state === 'DONE') {
|
||||
throw new ConflictException({
|
||||
code: READINESS_ITEM_NOT_OPEN,
|
||||
message: STALE_MESSAGE,
|
||||
});
|
||||
}
|
||||
if (item.fingerprint !== dto.fingerprint) {
|
||||
throw new ConflictException({
|
||||
code: READINESS_FINGERPRINT_STALE,
|
||||
message: STALE_MESSAGE,
|
||||
});
|
||||
}
|
||||
const created = await this.prisma.$transaction(async (tx) => {
|
||||
const row = await tx.complianceAcknowledgement.create({
|
||||
data: {
|
||||
itemKey: item.key,
|
||||
subjectId: item.subjectId,
|
||||
fingerprint: item.fingerprint,
|
||||
note,
|
||||
userId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
note: true,
|
||||
createdAt: true,
|
||||
user: { select: { name: true } },
|
||||
},
|
||||
});
|
||||
await this.auditLog.record(
|
||||
{
|
||||
entityType: AUDIT_ENTITY,
|
||||
entityId: row.id,
|
||||
action: 'CREATE',
|
||||
userId,
|
||||
afterData: {
|
||||
itemKey: item.key,
|
||||
subjectId: item.subjectId,
|
||||
fingerprint: item.fingerprint,
|
||||
note,
|
||||
},
|
||||
},
|
||||
tx,
|
||||
);
|
||||
return row;
|
||||
});
|
||||
this.readiness.invalidateSummary();
|
||||
return {
|
||||
...item,
|
||||
state: 'ACKNOWLEDGED',
|
||||
acknowledgement: {
|
||||
id: created.id,
|
||||
note: created.note,
|
||||
userName: created.user.name,
|
||||
createdAt: created.createdAt.toISOString(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Takes an acknowledgement back; the item is open again. */
|
||||
async revoke(id: string, userId: string): Promise<void> {
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
if (!(await lockRowForUpdate(tx, AUDIT_ENTITY, id))) {
|
||||
throw new NotFoundException('Die Quittung gibt es nicht.');
|
||||
}
|
||||
// Read after the lock: two parallel revokes queue up, the second sees
|
||||
// the first one's result.
|
||||
const before = await tx.complianceAcknowledgement.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!before) {
|
||||
throw new NotFoundException('Die Quittung gibt es nicht.');
|
||||
}
|
||||
if (before.revokedAt) {
|
||||
throw new ConflictException({
|
||||
code: READINESS_ACK_REVOKED,
|
||||
message: 'Die Quittung ist schon zurückgenommen.',
|
||||
});
|
||||
}
|
||||
await tx.$executeRaw`
|
||||
UPDATE "ComplianceAcknowledgement"
|
||||
SET "revokedAt" = now(), "revokedByUserId" = ${userId}
|
||||
WHERE id = ${id}
|
||||
`;
|
||||
const after = await tx.complianceAcknowledgement.findUniqueOrThrow({
|
||||
where: { id },
|
||||
});
|
||||
await this.auditLog.record(
|
||||
{
|
||||
entityType: AUDIT_ENTITY,
|
||||
entityId: id,
|
||||
action: 'UPDATE',
|
||||
userId,
|
||||
beforeData: before,
|
||||
afterData: after,
|
||||
},
|
||||
tx,
|
||||
);
|
||||
});
|
||||
this.readiness.invalidateSummary();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsString, Matches, MaxLength, MinLength } from 'class-validator';
|
||||
|
||||
const KEY_PATTERN = /^[a-z0-9-]+$/;
|
||||
const SUBJECT_PATTERN = /^[A-Za-z0-9_:.-]+$/;
|
||||
const FINGERPRINT_PATTERN = /^[a-f0-9]{64}$/;
|
||||
|
||||
export class CreateAcknowledgementDto {
|
||||
@ApiProperty({ example: 'harvest-withdrawal' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
@Matches(KEY_PATTERN)
|
||||
itemKey!: string;
|
||||
|
||||
@ApiProperty({ example: 'global', description: 'subjectId des Punktes' })
|
||||
@IsString()
|
||||
@MaxLength(200)
|
||||
@Matches(SUBJECT_PATTERN)
|
||||
subjectId!: string;
|
||||
|
||||
@ApiProperty({ description: 'Fingerabdruck des Punktes aus der Auswertung' })
|
||||
@IsString()
|
||||
@Matches(FINGERPRINT_PATTERN)
|
||||
fingerprint!: string;
|
||||
|
||||
@ApiProperty({ description: 'Notiz, 10 bis 2000 Zeichen' })
|
||||
@IsString()
|
||||
@MinLength(10)
|
||||
@MaxLength(2000)
|
||||
note!: string;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { fingerprintOf } from './fingerprint';
|
||||
|
||||
describe('fingerprintOf', () => {
|
||||
it('is stable for the same parts regardless of key order and differs when a value changes', () => {
|
||||
const a = fingerprintOf({
|
||||
year: 2027,
|
||||
ids: ['x', 'y'],
|
||||
nested: { a: 1, b: 2 },
|
||||
});
|
||||
const sameOtherOrder = fingerprintOf({
|
||||
nested: { b: 2, a: 1 },
|
||||
ids: ['x', 'y'],
|
||||
year: 2027,
|
||||
});
|
||||
const changedValue = fingerprintOf({
|
||||
year: 2028,
|
||||
ids: ['x', 'y'],
|
||||
nested: { a: 1, b: 2 },
|
||||
});
|
||||
|
||||
expect(a).toMatch(/^[a-f0-9]{64}$/);
|
||||
expect(sameOtherOrder).toBe(a);
|
||||
expect(changedValue).not.toBe(a);
|
||||
});
|
||||
|
||||
it('keeps the order of an array and treats dates by their ISO text', () => {
|
||||
expect(fingerprintOf({ ids: ['x', 'y'] })).not.toBe(
|
||||
fingerprintOf({ ids: ['y', 'x'] }),
|
||||
);
|
||||
expect(fingerprintOf({ at: new Date('2027-01-01T00:00:00.000Z') })).toBe(
|
||||
fingerprintOf({ at: '2027-01-01T00:00:00.000Z' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('ignores undefined properties and accepts null and plain values', () => {
|
||||
expect(fingerprintOf({ a: 1, b: undefined })).toBe(fingerprintOf({ a: 1 }));
|
||||
expect(fingerprintOf(null)).toMatch(/^[a-f0-9]{64}$/);
|
||||
expect(fingerprintOf(undefined)).toMatch(/^[a-f0-9]{64}$/);
|
||||
expect(fingerprintOf(5)).not.toBe(fingerprintOf('5'));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
// JSON with sorted keys at every level, so the same facts always give the same
|
||||
// text. Dates become their ISO text first (toJSON); undefined is dropped.
|
||||
function canonical(value: unknown): unknown {
|
||||
const plain: unknown =
|
||||
value !== null &&
|
||||
typeof value === 'object' &&
|
||||
typeof (value as { toJSON?: unknown }).toJSON === 'function'
|
||||
? (value as { toJSON(): unknown }).toJSON()
|
||||
: value;
|
||||
if (Array.isArray(plain)) {
|
||||
return plain.map((entry) => canonical(entry) ?? null);
|
||||
}
|
||||
if (plain !== null && typeof plain === 'object') {
|
||||
const sorted: Record<string, unknown> = {};
|
||||
for (const key of Object.keys(plain).sort()) {
|
||||
const entry = canonical((plain as Record<string, unknown>)[key]);
|
||||
if (entry !== undefined) {
|
||||
sorted[key] = entry;
|
||||
}
|
||||
}
|
||||
return sorted;
|
||||
}
|
||||
return plain;
|
||||
}
|
||||
|
||||
/** sha256 (hex) of the canonical JSON of `parts`. */
|
||||
export function fingerprintOf(parts: unknown): string {
|
||||
return createHash('sha256')
|
||||
.update(JSON.stringify(canonical(parts)) ?? 'null')
|
||||
.digest('hex');
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { DbClient } from '../../../prisma/db-client';
|
||||
import type { NotificationsService } from '../../../notifications/notifications.service';
|
||||
import { withdrawalWindowOf } from '../../../treatments/withdrawal-window';
|
||||
import { WithdrawalCheckService } from '../../../withdrawal/withdrawal-check.service';
|
||||
import { loadHarvests } from './harvests.loader';
|
||||
|
||||
const TREATMENT = {
|
||||
id: 't1',
|
||||
colonyId: 'c1',
|
||||
product: 'Mittel Eins',
|
||||
date: new Date('2027-02-01T00:00:00.000Z'),
|
||||
startDate: null,
|
||||
endDate: new Date('2027-02-05T00:00:00.000Z'),
|
||||
withdrawalPeriodDays: 10,
|
||||
};
|
||||
|
||||
function harvest(id: string, iso: string) {
|
||||
return {
|
||||
id,
|
||||
date: new Date(iso),
|
||||
colonies: [{ colonyId: 'c1' }],
|
||||
};
|
||||
}
|
||||
|
||||
function fakeDb(harvests: unknown[], treatments: unknown[] = [TREATMENT]) {
|
||||
const findHarvests = jest.fn().mockResolvedValue(harvests);
|
||||
const db = {
|
||||
harvest: { findMany: findHarvests },
|
||||
treatment: { findMany: jest.fn().mockResolvedValue(treatments) },
|
||||
} as unknown as DbClient;
|
||||
return { db, findHarvests };
|
||||
}
|
||||
|
||||
const withdrawal = new WithdrawalCheckService({} as NotificationsService);
|
||||
|
||||
describe('loadHarvests', () => {
|
||||
it('reads the harvests of the last 2 years', async () => {
|
||||
const { db, findHarvests } = fakeDb([]);
|
||||
|
||||
await loadHarvests(db, withdrawal, '2027-03-15');
|
||||
|
||||
const args = (findHarvests.mock.calls as unknown[][])[0][0] as {
|
||||
where: { date: { gte: Date } };
|
||||
};
|
||||
expect(args.where.date.gte).toEqual(new Date('2025-03-15T00:00:00.000Z'));
|
||||
});
|
||||
|
||||
it('reports a harvest inside the window of a participating colony and no harvest after it, exactly as the window helper says', async () => {
|
||||
const window = withdrawalWindowOf(TREATMENT);
|
||||
if (window === null) {
|
||||
throw new Error('window expected');
|
||||
}
|
||||
// fromDay 2027-02-01, untilDay 2027-02-15 (exclusive).
|
||||
const { db } = fakeDb([
|
||||
harvest('inside', '2027-02-14T10:00:00.000Z'),
|
||||
harvest('free', '2027-02-15T10:00:00.000Z'),
|
||||
harvest('before', '2027-01-31T10:00:00.000Z'),
|
||||
]);
|
||||
|
||||
const harvests = await loadHarvests(db, withdrawal, '2027-03-15');
|
||||
|
||||
expect(window.untilDay).toBe('2027-02-15');
|
||||
expect(harvests.map((entry) => [entry.id, entry.conflicts.length])).toEqual(
|
||||
[
|
||||
['inside', 1],
|
||||
['free', 0],
|
||||
['before', 0],
|
||||
],
|
||||
);
|
||||
expect(harvests[0].conflicts[0]).toMatchObject({
|
||||
harvestId: 'inside',
|
||||
colonyId: 'c1',
|
||||
treatmentId: 't1',
|
||||
untilDay: '2027-02-15',
|
||||
});
|
||||
expect(harvests[0].day).toBe('2027-02-14');
|
||||
});
|
||||
|
||||
it('asks the service once for all harvests', async () => {
|
||||
const spy = jest.spyOn(withdrawal, 'conflictsForHarvests');
|
||||
const { db } = fakeDb([
|
||||
harvest('a', '2027-02-10T10:00:00.000Z'),
|
||||
harvest('b', '2027-02-11T10:00:00.000Z'),
|
||||
]);
|
||||
|
||||
await loadHarvests(db, withdrawal, '2027-03-15');
|
||||
|
||||
expect(spy).toHaveBeenCalledTimes(1);
|
||||
expect(spy.mock.calls[0][1]).toEqual(['a', 'b']);
|
||||
spy.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import {
|
||||
addMonthsClamped,
|
||||
berlinDayOf,
|
||||
dayToDate,
|
||||
} from '../../../common/dates';
|
||||
import type { DbClient } from '../../../prisma/db-client';
|
||||
import type {
|
||||
WithdrawalCheckService,
|
||||
WithdrawalConflict,
|
||||
} from '../../../withdrawal/withdrawal-check.service';
|
||||
import { HARVEST_WITHDRAWAL_LOOKBACK_YEARS } from '../readiness-limits';
|
||||
|
||||
export interface ReadinessHarvest {
|
||||
id: string;
|
||||
/** Berlin calendar day of the harvest. */
|
||||
day: string;
|
||||
/** One per participating colony whose withdrawal window covers the day. */
|
||||
conflicts: WithdrawalConflict[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The harvests of the last 2 years with their withdrawal conflicts. The
|
||||
* windows are never calculated here: `conflictsForHarvests` decides, with
|
||||
* `withdrawalWindowOf` and `isInWindow`.
|
||||
*/
|
||||
export async function loadHarvests(
|
||||
db: DbClient,
|
||||
withdrawal: Pick<WithdrawalCheckService, 'conflictsForHarvests'>,
|
||||
today: string,
|
||||
): Promise<ReadinessHarvest[]> {
|
||||
const since = addMonthsClamped(
|
||||
today,
|
||||
-12 * HARVEST_WITHDRAWAL_LOOKBACK_YEARS,
|
||||
);
|
||||
const harvests = await db.harvest.findMany({
|
||||
where: { date: { gte: dayToDate(since) } },
|
||||
select: { id: true, date: true },
|
||||
orderBy: [{ date: 'asc' }, { id: 'asc' }],
|
||||
});
|
||||
const conflicts = await withdrawal.conflictsForHarvests(
|
||||
db,
|
||||
harvests.map((harvest) => harvest.id),
|
||||
);
|
||||
return harvests.map((harvest) => ({
|
||||
id: harvest.id,
|
||||
day: berlinDayOf(harvest.date),
|
||||
conflicts: conflicts.filter((entry) => entry.harvestId === harvest.id),
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import { SAMPLE_BOTTLING } from '../../../label-templates/label-particulars';
|
||||
import type { DbClient } from '../../../prisma/db-client';
|
||||
import { loadLabelTemplates } from './labels.loader';
|
||||
|
||||
const TEXT = {
|
||||
id: 'e1',
|
||||
type: 'text',
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 50,
|
||||
height: 10,
|
||||
text: 'Honig',
|
||||
placeholderKey: null,
|
||||
fontSize: 12,
|
||||
fontFamily: 'sans',
|
||||
bold: false,
|
||||
italic: false,
|
||||
color: '#000000',
|
||||
align: 'left',
|
||||
};
|
||||
|
||||
function template(patch: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'tpl1',
|
||||
name: 'Vorlage',
|
||||
minXHeightMm: 1.2,
|
||||
elements: [
|
||||
TEXT,
|
||||
{ id: 'q', type: 'qrCode', x: 0, y: 0, width: 10, height: 10 },
|
||||
{ id: 'l', type: 'line', x: 0, y: 0, width: 10, height: 1 },
|
||||
],
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
function bottling(id: string, jarCount: number, day: string) {
|
||||
return {
|
||||
id,
|
||||
jarSize: 500,
|
||||
jarCount,
|
||||
lotNumber: `L-${id}`,
|
||||
date: new Date(`${day}T00:00:00.000Z`),
|
||||
bestBeforeDate: new Date('2029-01-01T00:00:00.000Z'),
|
||||
honeyBatch: { batchNumber: 'HB', honeyType: null },
|
||||
product: { name: 'Honig', legalName: null },
|
||||
};
|
||||
}
|
||||
|
||||
function fakeDb(
|
||||
templates: unknown[],
|
||||
bottlings: unknown[] = [],
|
||||
movements: unknown[] = [],
|
||||
) {
|
||||
const findBottlings = jest.fn().mockResolvedValue(bottlings);
|
||||
const groupBy = jest.fn().mockResolvedValue(movements);
|
||||
const db = {
|
||||
labelTemplate: { findMany: jest.fn().mockResolvedValue(templates) },
|
||||
bottlingBatch: { findMany: findBottlings },
|
||||
batchMovement: { groupBy },
|
||||
} as unknown as DbClient;
|
||||
return { db, findBottlings, groupBy };
|
||||
}
|
||||
|
||||
describe('loadLabelTemplates', () => {
|
||||
it('reads only active templates and keeps their text elements', async () => {
|
||||
const { db } = fakeDb([template()]);
|
||||
|
||||
const templates = await loadLabelTemplates(db);
|
||||
|
||||
expect(
|
||||
(
|
||||
(db as unknown as { labelTemplate: { findMany: jest.Mock } })
|
||||
.labelTemplate.findMany.mock.calls as unknown[][]
|
||||
)[0][0],
|
||||
).toMatchObject({ where: { active: true } });
|
||||
expect(templates).toHaveLength(1);
|
||||
expect(templates[0].elements.map((element) => element.id)).toEqual(['e1']);
|
||||
});
|
||||
|
||||
it('asks for no bottling without an active template', async () => {
|
||||
const { db, findBottlings } = fakeDb([]);
|
||||
|
||||
expect(await loadLabelTemplates(db)).toEqual([]);
|
||||
expect(findBottlings).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('targets the newest bottling that still has stock', async () => {
|
||||
// Newest first, as asked: b3 is sold out (60 of 60), b2 has 10 left.
|
||||
const { db } = fakeDb(
|
||||
[template()],
|
||||
[
|
||||
bottling('b3', 60, '2027-03-01'),
|
||||
bottling('b2', 40, '2027-02-01'),
|
||||
bottling('b1', 20, '2027-01-01'),
|
||||
],
|
||||
[
|
||||
{ bottlingBatchId: 'b3', type: 'SHOP_SALE', _sum: { quantity: -60 } },
|
||||
{ bottlingBatchId: 'b2', type: 'WITHDRAWAL', _sum: { quantity: -30 } },
|
||||
],
|
||||
);
|
||||
|
||||
const [loaded] = await loadLabelTemplates(db);
|
||||
|
||||
expect(loaded.target.sample).toBe(false);
|
||||
expect(loaded.target.bottling.lotNumber).toBe('L-b2');
|
||||
});
|
||||
|
||||
it('falls back to the newest bottling when none has stock', async () => {
|
||||
const { db } = fakeDb(
|
||||
[template()],
|
||||
[bottling('b2', 40, '2027-02-01'), bottling('b1', 20, '2027-01-01')],
|
||||
[
|
||||
{ bottlingBatchId: 'b2', type: 'SHOP_SALE', _sum: { quantity: -40 } },
|
||||
{ bottlingBatchId: 'b1', type: 'SHOP_SALE', _sum: { quantity: -20 } },
|
||||
],
|
||||
);
|
||||
|
||||
const [loaded] = await loadLabelTemplates(db);
|
||||
|
||||
expect(loaded.target.sample).toBe(false);
|
||||
expect(loaded.target.bottling.lotNumber).toBe('L-b2');
|
||||
});
|
||||
|
||||
it('falls back to the sample values when there is no bottling at all', async () => {
|
||||
const { db } = fakeDb([template()], []);
|
||||
|
||||
const [loaded] = await loadLabelTemplates(db);
|
||||
|
||||
expect(loaded.target).toEqual({ sample: true, bottling: SAMPLE_BOTTLING });
|
||||
});
|
||||
|
||||
it('shares one target between all templates', async () => {
|
||||
const { db, findBottlings } = fakeDb(
|
||||
[template(), template({ id: 'tpl2' })],
|
||||
[bottling('b1', 20, '2027-01-01')],
|
||||
);
|
||||
|
||||
const templates = await loadLabelTemplates(db);
|
||||
|
||||
expect(templates[0].target).toBe(templates[1].target);
|
||||
expect(findBottlings).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('finds an older bottling with stock behind 200 sold-out ones', async () => {
|
||||
const soldOut = Array.from({ length: 200 }, (_, index) =>
|
||||
bottling(`s${index}`, 10, '2027-03-01'),
|
||||
);
|
||||
const older = bottling('old', 10, '2020-01-01');
|
||||
const findBottlings = jest
|
||||
.fn()
|
||||
.mockImplementation(({ skip }: { skip: number }) =>
|
||||
Promise.resolve(skip === 0 ? soldOut : [older]),
|
||||
);
|
||||
const groupBy = jest
|
||||
.fn()
|
||||
.mockImplementation(
|
||||
({ where }: { where: { bottlingBatchId: { in: string[] } } }) =>
|
||||
Promise.resolve(
|
||||
where.bottlingBatchId.in
|
||||
.filter((id) => id.startsWith('s'))
|
||||
.map((id) => ({
|
||||
bottlingBatchId: id,
|
||||
type: 'SHOP_SALE',
|
||||
_sum: { quantity: -10 },
|
||||
})),
|
||||
),
|
||||
);
|
||||
const db = {
|
||||
labelTemplate: { findMany: jest.fn().mockResolvedValue([template()]) },
|
||||
bottlingBatch: { findMany: findBottlings },
|
||||
batchMovement: { groupBy },
|
||||
} as unknown as DbClient;
|
||||
|
||||
const [loaded] = await loadLabelTemplates(db);
|
||||
|
||||
expect(loaded.target.bottling.lotNumber).toBe('L-old');
|
||||
expect(findBottlings).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
import type { LabelTextElement } from '../../../label-templates/label-element.types';
|
||||
import { SAMPLE_BOTTLING } from '../../../label-templates/label-particulars';
|
||||
import type { buildPlaceholderValues } from '../../../label-templates/label-templates.service';
|
||||
import type { DbClient } from '../../../prisma/db-client';
|
||||
import { summarizeStock } from '../../../stock/stock-ledger';
|
||||
|
||||
/** Bottlings read per page while looking for one with stock. */
|
||||
const BOTTLING_PAGE = 200;
|
||||
|
||||
export type LabelBottling = Parameters<typeof buildPlaceholderValues>[0];
|
||||
|
||||
/** What a template is checked against. */
|
||||
export interface ReadinessLabelTarget {
|
||||
/** True when no bottling exists and the sample values stand in. */
|
||||
sample: boolean;
|
||||
bottling: LabelBottling;
|
||||
}
|
||||
|
||||
export interface ReadinessLabelTemplate {
|
||||
id: string;
|
||||
name: string;
|
||||
minXHeightMm: number;
|
||||
/** Text elements only: images, lines and QR codes carry no particular. */
|
||||
elements: LabelTextElement[];
|
||||
target: ReadinessLabelTarget;
|
||||
}
|
||||
|
||||
function textElementsOf(elements: unknown): LabelTextElement[] {
|
||||
return Array.isArray(elements)
|
||||
? (elements as { type?: unknown }[]).filter(
|
||||
(element): element is LabelTextElement =>
|
||||
typeof element === 'object' &&
|
||||
element !== null &&
|
||||
element.type === 'text',
|
||||
)
|
||||
: [];
|
||||
}
|
||||
|
||||
const BOTTLING_SELECT = {
|
||||
id: true,
|
||||
jarSize: true,
|
||||
jarCount: true,
|
||||
lotNumber: true,
|
||||
date: true,
|
||||
bestBeforeDate: true,
|
||||
honeyBatch: { select: { batchNumber: true, honeyType: true } },
|
||||
product: { select: { name: true, legalName: true } },
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* The bottling a template is checked against: the newest with stock left
|
||||
* (the one being sold), else the newest, else the sample values. The
|
||||
* bottlings are read newest first in pages until one has stock, so a long
|
||||
* run of sold-out bottlings hides nothing; a movement sum per page uses the
|
||||
* stock arithmetic of the shop (`summarizeStock`).
|
||||
*/
|
||||
async function loadTarget(db: DbClient): Promise<ReadinessLabelTarget> {
|
||||
let newest: LabelBottling | null = null;
|
||||
for (let skip = 0; ; skip += BOTTLING_PAGE) {
|
||||
const page = await db.bottlingBatch.findMany({
|
||||
orderBy: [{ date: 'desc' }, { createdAt: 'desc' }, { id: 'desc' }],
|
||||
skip,
|
||||
take: BOTTLING_PAGE,
|
||||
select: BOTTLING_SELECT,
|
||||
});
|
||||
newest ??= page[0] ?? null;
|
||||
const withStock = await firstWithStock(db, page);
|
||||
if (withStock) {
|
||||
return { sample: false, bottling: withStock };
|
||||
}
|
||||
if (page.length < BOTTLING_PAGE) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return newest
|
||||
? { sample: false, bottling: newest }
|
||||
: { sample: true, bottling: SAMPLE_BOTTLING };
|
||||
}
|
||||
|
||||
async function firstWithStock<T extends { id: string; jarCount: number }>(
|
||||
db: DbClient,
|
||||
bottlings: readonly T[],
|
||||
): Promise<T | undefined> {
|
||||
if (bottlings.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
const sums = await db.batchMovement.groupBy({
|
||||
by: ['bottlingBatchId', 'type'],
|
||||
where: {
|
||||
bottlingBatchId: { in: bottlings.map((bottling) => bottling.id) },
|
||||
},
|
||||
_sum: { quantity: true },
|
||||
});
|
||||
return bottlings.find(
|
||||
(bottling) =>
|
||||
summarizeStock(
|
||||
bottling.jarCount,
|
||||
sums
|
||||
.filter((sum) => sum.bottlingBatchId === bottling.id)
|
||||
.map((sum) => ({ type: sum.type, quantity: sum._sum.quantity ?? 0 })),
|
||||
).remaining > 0,
|
||||
);
|
||||
}
|
||||
|
||||
/** The active templates, each with the bottling it is checked against. */
|
||||
export async function loadLabelTemplates(
|
||||
db: DbClient,
|
||||
): Promise<ReadinessLabelTemplate[]> {
|
||||
const templates = await db.labelTemplate.findMany({
|
||||
where: { active: true },
|
||||
select: { id: true, name: true, minXHeightMm: true, elements: true },
|
||||
orderBy: [{ name: 'asc' }, { id: 'asc' }],
|
||||
});
|
||||
if (templates.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const target = await loadTarget(db);
|
||||
return templates.map((template) => ({
|
||||
id: template.id,
|
||||
name: template.name,
|
||||
minXHeightMm: template.minXHeightMm,
|
||||
elements: textElementsOf(template.elements),
|
||||
target,
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import type { DbClient } from '../../../prisma/db-client';
|
||||
import { loadLots } from './lots.loader';
|
||||
|
||||
function lotRow(patch: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'l1',
|
||||
medicineId: 'm1',
|
||||
purchasedOn: new Date('2027-01-05T00:00:00.000Z'),
|
||||
quantity: 10,
|
||||
expiresOn: new Date('2028-01-05T00:00:00.000Z'),
|
||||
supplier: 'Lieferant',
|
||||
purchaseProof: 'Beleg',
|
||||
prescribingVet: null,
|
||||
medicine: { name: 'Mittel Eins', prescriptionOnly: true },
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
function fakeDb(lots: unknown[], medicines: unknown[], sums: unknown[] = []) {
|
||||
const groupBy = jest.fn().mockResolvedValue(sums);
|
||||
const db = {
|
||||
veterinaryMedicineLot: { findMany: jest.fn().mockResolvedValue(lots) },
|
||||
veterinaryMedicine: { findMany: jest.fn().mockResolvedValue(medicines) },
|
||||
veterinaryMedicineMovement: { groupBy },
|
||||
} as unknown as DbClient;
|
||||
return { db, groupBy };
|
||||
}
|
||||
|
||||
describe('loadLots', () => {
|
||||
it('computes the rest of each lot from one grouped sum query', async () => {
|
||||
const { db, groupBy } = fakeDb(
|
||||
[lotRow({ id: 'l1' }), lotRow({ id: 'l2', quantity: 5 })],
|
||||
[],
|
||||
[
|
||||
{ lotId: 'l1', _sum: { quantity: -3.5 }, _count: { _all: 2 } },
|
||||
{ lotId: 'l2', _sum: { quantity: -7 }, _count: { _all: 1 } },
|
||||
],
|
||||
);
|
||||
|
||||
const { lots } = await loadLots(db);
|
||||
|
||||
expect(lots.map((lot) => [lot.id, lot.remaining])).toEqual([
|
||||
['l1', 6.5],
|
||||
['l2', -2],
|
||||
]);
|
||||
expect(groupBy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('maps a lot with its medicine and days as day texts', async () => {
|
||||
const { db } = fakeDb([lotRow()], []);
|
||||
|
||||
const { lots } = await loadLots(db);
|
||||
|
||||
expect(lots[0]).toEqual({
|
||||
id: 'l1',
|
||||
medicineId: 'm1',
|
||||
medicineName: 'Mittel Eins',
|
||||
prescriptionOnly: true,
|
||||
purchasedOn: '2027-01-05',
|
||||
expiresOn: '2028-01-05',
|
||||
supplier: 'Lieferant',
|
||||
purchaseProof: 'Beleg',
|
||||
prescribingVet: null,
|
||||
remaining: 10,
|
||||
});
|
||||
});
|
||||
|
||||
it('leaves out a lot whose medicine vanished between the two reads', async () => {
|
||||
const { db } = fakeDb(
|
||||
[lotRow({ id: 'l1' }), lotRow({ id: 'gone', medicine: null })],
|
||||
[],
|
||||
);
|
||||
|
||||
const { lots } = await loadLots(db);
|
||||
|
||||
expect(lots.map((lot) => lot.id)).toEqual(['l1']);
|
||||
});
|
||||
|
||||
it('reads only active medicines', async () => {
|
||||
const { db } = fakeDb(
|
||||
[],
|
||||
[{ id: 'm1', name: 'A', withdrawalPeriodDays: null }],
|
||||
);
|
||||
|
||||
const { medicines } = await loadLots(db);
|
||||
|
||||
expect(medicines).toEqual([
|
||||
{ id: 'm1', name: 'A', withdrawalPeriodDays: null },
|
||||
]);
|
||||
expect(
|
||||
(
|
||||
(db as unknown as { veterinaryMedicine: { findMany: jest.Mock } })
|
||||
.veterinaryMedicine.findMany.mock.calls as unknown[][]
|
||||
)[0][0],
|
||||
).toMatchObject({ where: { active: true } });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import type { DbClient } from '../../../prisma/db-client';
|
||||
import {
|
||||
dayText,
|
||||
lotTotals,
|
||||
remainingOf,
|
||||
} from '../../../veterinary-medicines/medicine-views';
|
||||
|
||||
export interface ReadinessLot {
|
||||
id: string;
|
||||
medicineId: string;
|
||||
/** Only for subject labels, which need veterinary-medicines:read. */
|
||||
medicineName: string;
|
||||
prescriptionOnly: boolean;
|
||||
/** 'YYYY-MM-DD' */
|
||||
purchasedOn: string;
|
||||
/** 'YYYY-MM-DD' */
|
||||
expiresOn: string | null;
|
||||
supplier: string | null;
|
||||
purchaseProof: string | null;
|
||||
prescribingVet: string | null;
|
||||
/** quantity + Σ movements, the same number the lot pages show. */
|
||||
remaining: number;
|
||||
}
|
||||
|
||||
export interface ReadinessMedicine {
|
||||
id: string;
|
||||
name: string;
|
||||
withdrawalPeriodDays: number | null;
|
||||
}
|
||||
|
||||
export interface ReadinessLots {
|
||||
lots: ReadinessLot[];
|
||||
/** The active catalogue entries. */
|
||||
medicines: ReadinessMedicine[];
|
||||
}
|
||||
|
||||
/** All lots with their rest (one grouped sum query) and the active medicines. */
|
||||
export async function loadLots(db: DbClient): Promise<ReadinessLots> {
|
||||
const [rows, medicines] = await Promise.all([
|
||||
db.veterinaryMedicineLot.findMany({
|
||||
select: {
|
||||
id: true,
|
||||
medicineId: true,
|
||||
purchasedOn: true,
|
||||
quantity: true,
|
||||
expiresOn: true,
|
||||
supplier: true,
|
||||
purchaseProof: true,
|
||||
prescribingVet: true,
|
||||
medicine: { select: { name: true, prescriptionOnly: true } },
|
||||
},
|
||||
orderBy: [{ purchasedOn: 'asc' }, { id: 'asc' }],
|
||||
}),
|
||||
db.veterinaryMedicine.findMany({
|
||||
where: { active: true },
|
||||
select: { id: true, name: true, withdrawalPeriodDays: true },
|
||||
orderBy: [{ name: 'asc' }, { id: 'asc' }],
|
||||
}),
|
||||
]);
|
||||
// Prisma reads the medicine in a second query: a lot deleted together with
|
||||
// its medicine in between comes back with medicine null (CI run 836, 500).
|
||||
// Such a lot is gone, so it is left out.
|
||||
const present = rows.filter((row) => (row.medicine as unknown) !== null);
|
||||
const totals = await lotTotals(
|
||||
db,
|
||||
present.map((row) => row.id),
|
||||
);
|
||||
return {
|
||||
lots: present.map((row): ReadinessLot => ({
|
||||
id: row.id,
|
||||
medicineId: row.medicineId,
|
||||
medicineName: row.medicine.name,
|
||||
prescriptionOnly: row.medicine.prescriptionOnly,
|
||||
purchasedOn: dayText(row.purchasedOn),
|
||||
expiresOn: row.expiresOn === null ? null : dayText(row.expiresOn),
|
||||
supplier: row.supplier,
|
||||
purchaseProof: row.purchaseProof,
|
||||
prescribingVet: row.prescribingVet,
|
||||
remaining: remainingOf(row, totals.get(row.id)),
|
||||
})),
|
||||
medicines,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import type { DbClient } from '../../../prisma/db-client';
|
||||
import { loadTreatments } from './treatments.loader';
|
||||
|
||||
const MOVE = {
|
||||
colonyId: 'c1',
|
||||
apiaryId: 'a2',
|
||||
movedAt: new Date('2027-03-01T00:00:00.000Z'),
|
||||
};
|
||||
|
||||
function treatmentRow(patch: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 't1',
|
||||
colonyId: 'c1',
|
||||
date: new Date('2027-02-10T00:00:00.000Z'),
|
||||
startDate: null,
|
||||
endDate: null,
|
||||
product: 'Mittel Eins',
|
||||
amount: '30 ml',
|
||||
batchNumber: null,
|
||||
supplier: null,
|
||||
purchaseProof: null,
|
||||
prescribingVet: null,
|
||||
withdrawalPeriodDays: 0,
|
||||
apiaryId: null,
|
||||
doseQuantity: 2.5,
|
||||
medicineId: 'm1',
|
||||
colony: { code: 'V-1', apiaryId: 'a1' },
|
||||
user: { name: 'Imker' },
|
||||
medicine: { prescriptionOnly: true, unit: 'ML' },
|
||||
medicineLot: {
|
||||
id: 'l1',
|
||||
batchNumber: 'CH-1',
|
||||
supplier: 'Lieferant',
|
||||
purchaseProof: 'Beleg',
|
||||
prescribingVet: 'Dr. Vet',
|
||||
},
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
function fakeDb(rows: unknown[], moves: unknown[] = [MOVE]) {
|
||||
const findTreatments = jest.fn().mockResolvedValue(rows);
|
||||
const findMoves = jest.fn().mockResolvedValue(moves);
|
||||
const db = {
|
||||
treatment: { findMany: findTreatments },
|
||||
colonyApiaryHistory: { findMany: findMoves },
|
||||
} as unknown as DbClient;
|
||||
return { db, findTreatments, findMoves };
|
||||
}
|
||||
|
||||
describe('loadTreatments', () => {
|
||||
it('reads the last 6 calendar years with a column list, no whole rows', async () => {
|
||||
const { db, findTreatments } = fakeDb([]);
|
||||
|
||||
await loadTreatments(db, '2027-03-15');
|
||||
|
||||
const args = (findTreatments.mock.calls as unknown[][])[0][0] as {
|
||||
where: { date: { gte: Date } };
|
||||
select?: unknown;
|
||||
include?: unknown;
|
||||
};
|
||||
expect(args.where.date.gte).toEqual(new Date('2022-01-01T00:00:00.000Z'));
|
||||
expect(args.select).toBeDefined();
|
||||
expect(args.include).toBeUndefined();
|
||||
});
|
||||
|
||||
it('maps rows to the sources of the Bestandsbuch', async () => {
|
||||
const { db } = fakeDb([treatmentRow()]);
|
||||
|
||||
const { treatments } = await loadTreatments(db, '2027-03-15');
|
||||
|
||||
expect(treatments).toEqual([
|
||||
{
|
||||
id: 't1',
|
||||
colonyId: 'c1',
|
||||
colonyCode: 'V-1',
|
||||
colonyApiaryId: 'a1',
|
||||
apiaryId: null,
|
||||
date: new Date('2027-02-10T00:00:00.000Z'),
|
||||
startDate: null,
|
||||
endDate: null,
|
||||
product: 'Mittel Eins',
|
||||
amount: '30 ml',
|
||||
batchNumber: null,
|
||||
supplier: null,
|
||||
purchaseProof: null,
|
||||
prescribingVet: null,
|
||||
withdrawalPeriodDays: 0,
|
||||
administeredBy: 'Imker',
|
||||
medicineId: 'm1',
|
||||
prescriptionOnly: true,
|
||||
doseQuantity: 2.5,
|
||||
medicineUnit: 'ML',
|
||||
lot: {
|
||||
id: 'l1',
|
||||
batchNumber: 'CH-1',
|
||||
supplier: 'Lieferant',
|
||||
purchaseProof: 'Beleg',
|
||||
prescribingVet: 'Dr. Vet',
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('loads the moves of the colonies whose treatment has no stored apiary, and only those', async () => {
|
||||
const { db, findMoves } = fakeDb([
|
||||
treatmentRow({ id: 't1', colonyId: 'c1', apiaryId: null }),
|
||||
treatmentRow({ id: 't2', colonyId: 'c2', apiaryId: 'a1' }),
|
||||
treatmentRow({ id: 't3', colonyId: 'c1', apiaryId: null }),
|
||||
]);
|
||||
|
||||
const { moves } = await loadTreatments(db, '2027-03-15');
|
||||
|
||||
expect(moves).toEqual([MOVE]);
|
||||
expect((findMoves.mock.calls as unknown[][])[0][0]).toMatchObject({
|
||||
where: { colonyId: { in: ['c1'] } },
|
||||
});
|
||||
});
|
||||
|
||||
it('asks for no moves when every treatment stores its apiary', async () => {
|
||||
const { db, findMoves } = fakeDb([treatmentRow({ apiaryId: 'a1' })]);
|
||||
|
||||
const { moves } = await loadTreatments(db, '2027-03-15');
|
||||
|
||||
expect(moves).toEqual([]);
|
||||
expect(findMoves).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('treats a treatment without a catalogue entry as over the counter', async () => {
|
||||
const { db } = fakeDb([
|
||||
treatmentRow({ medicineId: null, medicine: null, medicineLot: null }),
|
||||
]);
|
||||
|
||||
const { treatments } = await loadTreatments(db, '2027-03-15');
|
||||
|
||||
expect(treatments[0]).toMatchObject({
|
||||
prescriptionOnly: false,
|
||||
medicineUnit: null,
|
||||
lot: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import type {
|
||||
ColonyMove,
|
||||
TreatmentLogSource,
|
||||
} from '../../../export/treatment-log';
|
||||
import type { DbClient } from '../../../prisma/db-client';
|
||||
import { firstTreatmentYear } from '../readiness-limits';
|
||||
|
||||
export interface ReadinessTreatments {
|
||||
treatments: TreatmentLogSource[];
|
||||
/** The moves of the colonies whose treatment stores no apiary. */
|
||||
moves: ColonyMove[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The treatments of the lookback as the sources of the Bestandsbuch (the
|
||||
* same shape the PDF is built from), with only the columns the rules read.
|
||||
*/
|
||||
export async function loadTreatments(
|
||||
db: DbClient,
|
||||
today: string,
|
||||
): Promise<ReadinessTreatments> {
|
||||
const rows = await db.treatment.findMany({
|
||||
where: {
|
||||
date: { gte: new Date(Date.UTC(firstTreatmentYear(today), 0, 1)) },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
colonyId: true,
|
||||
date: true,
|
||||
startDate: true,
|
||||
endDate: true,
|
||||
product: true,
|
||||
amount: true,
|
||||
batchNumber: true,
|
||||
supplier: true,
|
||||
purchaseProof: true,
|
||||
prescribingVet: true,
|
||||
withdrawalPeriodDays: true,
|
||||
apiaryId: true,
|
||||
doseQuantity: true,
|
||||
medicineId: true,
|
||||
colony: { select: { code: true, apiaryId: true } },
|
||||
user: { select: { name: true } },
|
||||
medicine: { select: { prescriptionOnly: true, unit: true } },
|
||||
medicineLot: {
|
||||
select: {
|
||||
id: true,
|
||||
batchNumber: true,
|
||||
supplier: true,
|
||||
purchaseProof: true,
|
||||
prescribingVet: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: [{ date: 'asc' }, { id: 'asc' }],
|
||||
});
|
||||
const treatments = rows.map((row): TreatmentLogSource => ({
|
||||
id: row.id,
|
||||
colonyId: row.colonyId,
|
||||
colonyCode: row.colony.code,
|
||||
colonyApiaryId: row.colony.apiaryId,
|
||||
apiaryId: row.apiaryId,
|
||||
date: row.date,
|
||||
startDate: row.startDate,
|
||||
endDate: row.endDate,
|
||||
product: row.product,
|
||||
amount: row.amount,
|
||||
batchNumber: row.batchNumber,
|
||||
supplier: row.supplier,
|
||||
purchaseProof: row.purchaseProof,
|
||||
prescribingVet: row.prescribingVet,
|
||||
withdrawalPeriodDays: row.withdrawalPeriodDays,
|
||||
administeredBy: row.user.name,
|
||||
medicineId: row.medicineId,
|
||||
prescriptionOnly: row.medicine?.prescriptionOnly ?? false,
|
||||
doseQuantity: row.doseQuantity,
|
||||
medicineUnit: row.medicine?.unit ?? null,
|
||||
lot: row.medicineLot,
|
||||
}));
|
||||
return { treatments, moves: await loadMoves(db, treatments) };
|
||||
}
|
||||
|
||||
async function loadMoves(
|
||||
db: DbClient,
|
||||
treatments: readonly TreatmentLogSource[],
|
||||
): Promise<ColonyMove[]> {
|
||||
const colonyIds = [
|
||||
...new Set(
|
||||
treatments
|
||||
.filter((treatment) => treatment.apiaryId === null)
|
||||
.map((treatment) => treatment.colonyId),
|
||||
),
|
||||
].sort();
|
||||
if (colonyIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
return db.colonyApiaryHistory.findMany({
|
||||
where: { colonyId: { in: colonyIds } },
|
||||
select: { colonyId: true, apiaryId: true, movedAt: true },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import type {
|
||||
ColonyMove,
|
||||
TreatmentLogSource,
|
||||
} from '../../export/treatment-log';
|
||||
import type {
|
||||
ApiaryRestriction,
|
||||
AuthorityNotice,
|
||||
ComplianceSettings,
|
||||
SiteSettings,
|
||||
} from '../../../generated/prisma';
|
||||
import { berlinToday, dayToDate } from '../../common/dates';
|
||||
import type { DbClient } from '../../prisma/db-client';
|
||||
import type { WithdrawalCheckService } from '../../withdrawal/withdrawal-check.service';
|
||||
import { herdStatusIn, type HerdStatus } from '../herd-status';
|
||||
import { loadHarvests, type ReadinessHarvest } from './loaders/harvests.loader';
|
||||
import {
|
||||
loadLabelTemplates,
|
||||
type ReadinessLabelTemplate,
|
||||
} from './loaders/labels.loader';
|
||||
import {
|
||||
loadLots,
|
||||
type ReadinessLot,
|
||||
type ReadinessMedicine,
|
||||
} from './loaders/lots.loader';
|
||||
import { loadTreatments } from './loaders/treatments.loader';
|
||||
|
||||
export {
|
||||
HARVEST_WITHDRAWAL_LOOKBACK_YEARS,
|
||||
TREATMENT_LOOKBACK_CALENDAR_YEARS,
|
||||
} from './readiness-limits';
|
||||
|
||||
const SITE_SETTINGS_ID = 'singleton';
|
||||
/** TSK reports of this year and the one before matter for the readiness. */
|
||||
const TSK_LOOKBACK_YEARS = 1;
|
||||
const MAX_TSK_NOTICES = 100;
|
||||
const MAX_RESTRICTIONS = 500;
|
||||
|
||||
/** A notice without its snapshot (addresses, large): the rules never read it. */
|
||||
export type ReadinessNotice = Omit<AuthorityNotice, 'snapshot'>;
|
||||
|
||||
export type ReadinessRestriction = ApiaryRestriction & {
|
||||
apiary: { id: string; name: string };
|
||||
};
|
||||
|
||||
/** What the context needs besides the database. */
|
||||
export interface ReadinessContextDeps {
|
||||
withdrawal: Pick<WithdrawalCheckService, 'conflictsForHarvests'>;
|
||||
}
|
||||
|
||||
/** Everything the rules read, loaded once per evaluation. */
|
||||
export interface ReadinessContext {
|
||||
now: Date;
|
||||
/** The Berlin calendar day of `now` (YYYY-MM-DD). */
|
||||
today: string;
|
||||
site: SiteSettings;
|
||||
settings: ComplianceSettings;
|
||||
herd: HerdStatus;
|
||||
notices: ReadinessNotice[];
|
||||
/** The restrictions active on `today`. */
|
||||
restrictions: ReadinessRestriction[];
|
||||
/** The last 6 calendar years, as the sources of the Bestandsbuch. */
|
||||
treatments: TreatmentLogSource[];
|
||||
/** The moves of the colonies whose treatment stores no apiary. */
|
||||
moves: ColonyMove[];
|
||||
/** All lots with their rest. */
|
||||
lots: ReadinessLot[];
|
||||
/** The active catalogue entries. */
|
||||
medicines: ReadinessMedicine[];
|
||||
/** The active label templates, each with the bottling it is checked on. */
|
||||
templates: ReadinessLabelTemplate[];
|
||||
/** The harvests of the last 2 years with their withdrawal conflicts. */
|
||||
harvests: ReadinessHarvest[];
|
||||
}
|
||||
|
||||
/** Before the first save there is no row: every field is empty. */
|
||||
const EMPTY_SITE_SETTINGS: SiteSettings = {
|
||||
id: SITE_SETTINGS_ID,
|
||||
youtubeUrl: null,
|
||||
instagramUrl: null,
|
||||
tiktokUrl: null,
|
||||
websiteUrl: null,
|
||||
holderName: null,
|
||||
holderAddress: null,
|
||||
foodBusinessName: null,
|
||||
foodBusinessAddress: null,
|
||||
originCountry: '',
|
||||
updatedAt: new Date(0),
|
||||
};
|
||||
|
||||
const NOTICE_COLUMNS = {
|
||||
id: true,
|
||||
kind: true,
|
||||
status: true,
|
||||
year: true,
|
||||
referenceDate: true,
|
||||
countedAt: true,
|
||||
totalColonies: true,
|
||||
sentOn: true,
|
||||
sentVia: true,
|
||||
reference: true,
|
||||
notes: true,
|
||||
openKey: true,
|
||||
createdByUserId: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
} as const;
|
||||
|
||||
/** A read: nothing here writes (the settings rows are seeded by migrations). */
|
||||
export async function loadReadinessContext(
|
||||
db: DbClient,
|
||||
now: Date,
|
||||
deps: ReadinessContextDeps,
|
||||
): Promise<ReadinessContext> {
|
||||
const today = berlinToday(now);
|
||||
const day = dayToDate(today);
|
||||
const firstTskYear = Number(today.slice(0, 4)) - TSK_LOOKBACK_YEARS;
|
||||
const [
|
||||
site,
|
||||
herd,
|
||||
sentRegistration,
|
||||
draftRegistration,
|
||||
tskReports,
|
||||
active,
|
||||
treatmentData,
|
||||
lotData,
|
||||
templates,
|
||||
harvests,
|
||||
] = await Promise.all([
|
||||
db.siteSettings.findUnique({ where: { id: SITE_SETTINGS_ID } }),
|
||||
herdStatusIn(db, now),
|
||||
// The registrations have their own queries, so an old registration can
|
||||
// never fall out of the window meant for the TSK reports.
|
||||
db.authorityNotice.findFirst({
|
||||
where: { kind: 'REGISTRATION', status: 'SENT' },
|
||||
orderBy: [{ sentOn: 'desc' }, { createdAt: 'desc' }, { id: 'desc' }],
|
||||
select: NOTICE_COLUMNS,
|
||||
}),
|
||||
db.authorityNotice.findFirst({
|
||||
where: { kind: 'REGISTRATION', status: 'DRAFT' },
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
select: NOTICE_COLUMNS,
|
||||
}),
|
||||
db.authorityNotice.findMany({
|
||||
where: {
|
||||
kind: 'TSK_REPORT',
|
||||
status: { not: 'CANCELLED' },
|
||||
year: { gte: firstTskYear },
|
||||
},
|
||||
select: NOTICE_COLUMNS,
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
take: MAX_TSK_NOTICES,
|
||||
}),
|
||||
db.apiaryRestriction.findMany({
|
||||
where: {
|
||||
startsOn: { lte: day },
|
||||
OR: [{ endsOn: null }, { endsOn: { gte: day } }],
|
||||
},
|
||||
include: { apiary: { select: { id: true, name: true } } },
|
||||
orderBy: [{ startsOn: 'asc' }, { id: 'asc' }],
|
||||
take: MAX_RESTRICTIONS,
|
||||
}),
|
||||
loadTreatments(db, today),
|
||||
loadLots(db),
|
||||
loadLabelTemplates(db),
|
||||
loadHarvests(db, deps.withdrawal, today),
|
||||
]);
|
||||
const registrations = [sentRegistration, draftRegistration].filter(
|
||||
(entry): entry is ReadinessNotice => entry !== null,
|
||||
);
|
||||
return {
|
||||
now,
|
||||
today,
|
||||
site: site ?? EMPTY_SITE_SETTINGS,
|
||||
settings: herd.settings,
|
||||
herd,
|
||||
notices: [...registrations, ...tskReports],
|
||||
restrictions: active,
|
||||
treatments: treatmentData.treatments,
|
||||
moves: treatmentData.moves,
|
||||
lots: lotData.lots,
|
||||
medicines: lotData.medicines,
|
||||
templates,
|
||||
harvests,
|
||||
};
|
||||
}
|
||||
Loaded 100 of 1264 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user