feat: T4 wave 10 – bottling quality, phenology and honey chain UI, Telegram link/receive and ops

- Bottling quality: water content above the legal limit (strict >) answers
  409 CONFIRMATION_REQUIRED bound to the measured value; prefill for jar
  size, best-before (shelfLifeMonths, month-end clamping) and water content;
  impossible dates give 400; water-content checks in src/common/quality.
- Frontend phenology: "Entwicklung melden" sheet, IndexedDB v4 queue,
  season header on the apiary page, confirmed revoke for all apiaries.
- Frontend honey chain: "Vorschlag aus …" hints with explicit take-over,
  prefill status note, movement ledger with withdraw/correct dialogs.
- Telegram: link tokens (hashed, single use), private-chat receiver with
  lease and offset CAS, bounded poison-update skip, Retry-After, pending
  deliveries skipped on disconnect; system API for deliveries and retry;
  worker-only secret wiring and manifest policy tests.
- ARCHITECTURE.md §7, §9, §10, §11.11–11.13, Annahmen 51–55.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
Nick SzaunigandClaude Opus 5.5 committed 2026-10-14 22:47:17 +02:00
1 parent 16cc557462
commit fab7f7e12f
91 files changed
+8463 -104

No files matched your search

+39 -10
View File
@@ -160,12 +160,17 @@ Fachliche Annahmen, getroffen weil das Lastenheft an der Stelle keine eindeutige
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.
43. **Pflanzenentwicklung: Tabellen und Fremdschlüssel**: Abweichend vom Entwurf (Spec 4.2) verweisen `ApiaryPhenology.apiaryId` und `ApiaryWeatherDay.apiaryId` mit `ON DELETE CASCADE` auf `Apiary` (abgeleitete Daten und Cache, keine Waisen, ein Restore von Ständen wird nie blockiert). `PhenologyReport.apiaryId` verweist mit `ON DELETE RESTRICT` auf `Apiary`: Der Prisma-Standard für eine optionale Relation, `SetNull`, machte aus einer Meldung still eine Meldung „für alle Stände“. Die Migration `20261015100000_t4_phenology` vergibt `phenology:read`, `phenology:create` und `phenology:update` (Gruppe „Pflanzenentwicklung“) an alle Systemrollen; `read` geht an Rollen, die `colonies:read` halten, `create` und `update` an Rollen mit `inspections:create`, jeweils nur Nicht-Systemrollen. Die Migration legt die Rechte selbst an, weil der Katalog-Abgleich beim Start neue Rechte nur für Zeilen vergibt, die er selbst anlegt (`PermissionCatalogSyncService`).
44. **Bewegungsbuch der Honigcharge**: `HoneyBatch.amount` bleibt der laufende Rest in kg, `HoneyBatch.initialAmount` (kg) ist die Anfangsmenge. `BatchMovement.quantity` ist bei Honig eine vorzeichenbehaftete Menge in Gramm mit `honeyBatchId`. Invariante: `amount = initialAmount + Summe(quantity) / 1000`, auf das Gramm gerundet, nie unter 0, Toleranz 0,5 g. Eine Charge ohne `amount` und `initialAmount` wird nicht gebucht. Jede `BatchMovement` gehört zu genau einer Quelle aus Abfüllung, Herstellungscharge, Rohstoff-Charge und Honigcharge (CHECK `BatchMovement_exactly_one_batch`, `num_nonnulls(…) = 1`). Rückrechnung für Altbestand (Migration `20261015100100_t4_honey_ledger`, Import alter Bundles): `initialAmount = amount + Summe(Gramm der Abfüllungen) / 1000`, je Abfüllung eine Buchung `BOTTLING` mit `sourceBottlingBatchId`, Datum und Benutzer der Abfüllung (Grammwerte halb aufgerundet, `floor(x·1000 + 0,5)`). Frühere Handkorrekturen von `amount` stecken damit in `initialAmount`. Die Migration endet mit einer Prüfung (`RAISE NOTICE` mit Zählern, `RAISE EXCEPTION` bei verletzter Invariante, dann Rollback). Laufzeit: `HoneyBatchLedgerService` (`src/honey-batches/honey-batch-ledger.service.ts`) ist der einzige Schreiber von `HoneyBatch.amount` (Wächter `honey-batch-amount-writes.spec.ts`). Buchungen laufen in der Transaktion des Aufrufers unter `lockRowForUpdate('HoneyBatch')`: `bookIn` (vorzeichenbehaftete Gramm; `amount` wird aus `initialAmount + Summe(quantity) / 1000` auf das Gramm neu berechnet, nie unter 0), `setInitialIn` (erste Menge: `amount` und `initialAmount` zugleich, keine Buchung) und `clearIn` (Menge entfernen, nur ohne Buchungen, sonst 400 „Die Menge wird ueber das Bewegungsbuch gefuehrt. Bitte eine Korrektur buchen.“). Eine Abbuchung braucht genug Rest (Toleranz 0,5 g), sonst 400 (Abfüllung: „Abfuellmenge uebersteigt die verfuegbare Menge der Honigcharge“, sonst „Die Menge kann nicht unter 0 sinken.“). Gerundet wird überall gleich, `floor(x·1000 + 0,5)` Gramm, auch bei Mengen, die Nutzer eingeben (12,3456 kg werden 12,346 kg). Eine Abfüllung anlegen bucht `BOTTLING` negativ mit `sourceBottlingBatchId`, Ändern die Differenz (bei Chargenwechsel zurück auf die alte, von der neuen), Entfernen `BOTTLING` positiv mit der Notiz „Abfuellung entfernt“ (ohne Quelle: die Abfüllung wird danach gelöscht). `PATCH amount` bucht `CORRECTION` (neu minus aktuell; `initialAmount` bleibt, Startmenge und Summe der Buchungen weichen danach ab); der erste Wert einer Charge ohne Menge (`null` → Wert) setzt `initialAmount`. Eine Charge ohne `initialAmount` bucht nichts, die Abfüllung setzt trotzdem den Status `BOTTLED`. Eine Abfüllung, die dem Buch nie etwas entnommen hat (Heuristik `drewFromLedger`: keine `BOTTLING`-Buchung mit `honeyBatchId` und ihrer `sourceBottlingBatchId`, etwa weil die Charge beim Abfüllen noch keine Menge hatte), bucht bei Änderung und Entfernung nichts zurück; wird sie in eine andere Charge verschoben, entnimmt sie erst dort. Das folgt aus den Buchungen und ist kein gespeichertes Merkmal. Sperrreihenfolge je Pfad: Abfüllung → Honigcharge (zwei Chargen in einer Anweisung, aufsteigend; die Abfüllung sperrt die Charge schon vor dem Anlegen), Schleuderung → Honigcharge. API des Buchs: Abschnitt 11.12.
45. **Honig-Kette: Vorschläge, Warnungen, nie sperren**: Vorbelegungen (Menge, Honigsorte, Wassergehalt) sind Vorschläge mit Übernehmen-Knopf, nie stillschweigend eingetragen. Plausibilitätswarnungen (`EXTRACTION_EXCEEDS_HARVEST`, `BATCHES_EXCEED_EXTRACTION`, Hinweis `HARVEST_NET_MISSING`) und die Wartezeitwarnung sperren nie (kein 4xx). Die Wartezeitwarnung `WITHDRAWAL_ACTIVE` bekommt jeder, der eine Schleuderung erfasst oder vorbelegt, auch ohne `treatments:read` (Lebensmittelsicherheit vor der Lese-Trennung). Die Vorbelegungs-Endpunkte hängen an den Anlege-Rechten (`extractions:create`, `honey-batches:create`): Sie liefern dieselben Daten wie der Anlege-Ablauf. Die Honigsorte kommt aus den Ernten, weil `Extraction` kein Sortenfeld hat. Abschnitt 11.12.
46. **Telegram: Token nur im Worker, Zustellung über Outbox**: Der Bot-Token (`TELEGRAM_BOT_TOKEN`) liegt nur in der Umgebung des Workers (optionales Secret `apicore-telegram`); der API-Pod kennt nur `TELEGRAM_BOT_USERNAME` für den Deep Link. Der Token erscheint nie in Logs oder Fehlern. Ein fehlerhaft geformter Token (oder in Produktion ein Platzhalter) lässt den Worker nicht abstürzen: Fehler-Log ohne Wert, Telegram bleibt aus. Gesendet wird nur aus Worker-Schleifen über `NotificationDelivery`, nie aus Anfragen, Handlern oder Jobs; die Zustellung läuft in der Schleife `telegram-send` (Abschnitt 11.13). Der Sender nimmt genau ein Worker-Replikat an (`replicas: 1`): Chat-Abstand, Senderate und die Pausen nach 401 und 429 liegen im Speicher des Pods, mit mehreren Pods hätte jeder seine eigenen. Die SQL-Regel „eine Zustellung je Nutzer und Batch“ und Telegrams 429-Antworten schützen den Bot auch dann. Ohne `FRONTEND_ORIGIN` geht die Nachricht außerhalb der Entwicklung (`NODE_ENV` leer oder `development`) ohne Link hinaus (ein Warn-Log je Pod), nie mit einem localhost-Link. Abschnitt 11.13.
45. **Honig-Kette: Vorschläge, Warnungen, nie sperren**: Vorbelegungen (Menge, Honigsorte, Wassergehalt, Glasgröße, MHD) sind Vorschläge mit Übernehmen-Knopf, nie stillschweigend eingetragen. Plausibilitätswarnungen (`EXTRACTION_EXCEEDS_HARVEST`, `BATCHES_EXCEED_EXTRACTION`, Hinweis `HARVEST_NET_MISSING`) und die Wartezeitwarnung sperren nie (kein 4xx). Die Wartezeitwarnung `WITHDRAWAL_ACTIVE` bekommt jeder, der eine Schleuderung erfasst oder vorbelegt, auch ohne `treatments:read` (Lebensmittelsicherheit vor der Lese-Trennung). Die Vorbelegungs-Endpunkte hängen an den Anlege-Rechten (`extractions:create`, `honey-batches:create`): Sie liefern dieselben Daten wie der Anlege-Ablauf. Die Honigsorte kommt aus den Ernten, weil `Extraction` kein Sortenfeld hat. Abschnitt 11.12.
46. **Telegram: Token nur im Worker, Zustellung über Outbox**: Der Bot-Token (`TELEGRAM_BOT_TOKEN`) liegt nur in der Umgebung des Workers (optionales Secret `apicore-telegram`); der API-Pod kennt nur `TELEGRAM_BOT_USERNAME` für den Deep Link. Der Token erscheint nie in Logs oder Fehlern. Ein fehlerhaft geformter Token (oder in Produktion ein Platzhalter) lässt den Worker nicht abstürzen: Fehler-Log ohne Wert, Telegram bleibt aus. Gesendet wird nur aus Worker-Schleifen über `NotificationDelivery`, nie aus Anfragen, Handlern oder Jobs; die Zustellung läuft in der Schleife `telegram-send`, der Empfang in `telegram-updates` (Abschnitt 11.13). Der Sender nimmt genau ein Worker-Replikat an (`replicas: 1`): Chat-Abstand, Senderate und die Pausen nach 401 und 429 liegen im Speicher des Pods, mit mehreren Pods hätte jeder seine eigenen. Die SQL-Regel „eine Zustellung je Nutzer und Batch“ und Telegrams 429-Antworten schützen den Bot auch dann. Ohne `FRONTEND_ORIGIN` geht die Nachricht außerhalb der Entwicklung (`NODE_ENV` leer oder `development`) ohne Link hinaus (ein Warn-Log je Pod), nie mit einem localhost-Link. Abschnitt 11.13.
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.
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. 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.
54. **Telegram: `LINKED` ohne Antwortgrenze**: Die Grenze von 3 Antworten je Chat in 10 Minuten gilt für `HELP`, `LINK_INVALID` und `STOPPED`, nicht für `LINKED`. `LINKED` braucht ein gültiges Einmal-Token des angemeldeten Nutzers, ein Fremder kann es nicht auslösen. Abschnitt 11.13.
55. **Pflanzenmeldung: doppelte Meldung beim erneuten Öffnen des Blatts**: Jede Meldung des Blatts „Entwicklung melden“ bekommt einen eigenen Schlüssel. Öffnet jemand das Blatt erneut und meldet dieselbe Phase noch einmal, entsteht eine zweite Meldung (auch aus der Offline-Warteschlange). Das ist bewusst hingenommen: Die Auswertung nimmt den frühesten Meldetag der Phase, die Zeile lässt sich zurückziehen (Kosten bei falscher Annahme: eine Zeile mehr). Abschnitt 11.11.
## 7. Kubernetes
@@ -180,6 +185,7 @@ Fachliche Annahmen, getroffen weil das Lastenheft an der Stelle keine eindeutige
- `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…`).
- `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.
**Rollen-Deployments** (ein Image, Rolle per `APICORE_ROLE`):
@@ -256,7 +262,7 @@ Grundlage: OWASP API Security Top 10 (2023) und OWASP ASVS Level 2. Umsetzung un
| Authentifizierung | JWT mit festem Algorithmus, Issuer und Audience je Zweck; MFA (TOTP) mit Replay-Schutz; Kontosperre 15 min nach 5 Fehlversuchen; gleiche Antwort für unbekannte/gesperrte Konten; bcrypt auf jedem Pfad |
| Passwörter | mind. 12 Zeichen, max. 72 Byte, Abgleich mit Have I Been Pwned (k-Anonymität, abschaltbar per `PASSWORD_BREACH_CHECK=false`) |
| Sitzungen | Refresh-Rotation atomar, Diebstahlerkennung, max. 7 Tage; Einmal-Tokens für SSO-Abschluss und MFA-Schritt |
| Step-up | Backup-Import, MFA ein/aus verlangen aktuelles Passwort (+ TOTP) |
| Step-up | Backup-Import, MFA ein/aus und Telegram verbinden verlangen aktuelles Passwort (+ TOTP); das Verbinden ist auf 10 pro Minute gedrosselt |
| Autorisierung | fail-closed `PermissionsGuard`; keine Rechteausweitung über Benutzer-/Rollenpflege; Suche nur über lesbare Objektarten |
| Maschinen-Zugriff | API-Schlüssel nur als Hash (Suche über den Hash, kein Vergleich von Geheimnissen), Scope-Allowlist (`shop-sync:read`, `shop-sync:write`, `erp-inventory:read`), IP-Allowlist, widerrufbar, befristbar; Ersteller kann nur eigene Rechte vergeben. Je neuem Schlüssel genau ein Recht: `ApiKeysService.create` lehnt mehrere Rechte mit 400 ab (Lesen und Buchen damit immer getrennt); bereits ausgestellte Schlüssel mit mehreren Rechten bleiben gültig und werden in der Oberfläche mit Hinweis markiert; `erp-inventory:read` zählt als Lesen. Nach 20 ungültigen Schlüsseln in 15 min je IP (IPv6: je /64) `429` für weitere ungültige – gültige Schlüssel nie, falsch aufgebaute Tokens zählen nicht; Zähler in `ThrottlerHit`, über alle Pods geteilt (Annahme 30); Warnung beim Start, wenn `TRUST_PROXY` in Produktion fehlt; Logs nur mit Schlüssel-Präfix |
| 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()` |
@@ -276,7 +282,7 @@ Grundlage: OWASP API Security Top 10 (2023) und OWASP ASVS Level 2. Umsetzung un
| `TELEGRAM_BOT_USERNAME` | ConfigMap, API und Worker | Benutzername des Bots (ohne `@`, 5–32 Zeichen, `^[A-Za-z][A-Za-z0-9_]{4,31}$`), erzeugt den Deep Link; ungültig = nicht gesetzt, mit Warnung in jeder Rolle |
| `TELEGRAM_BOT_TOKEN` | Secret `apicore-telegram`, nur Worker | Bot-Token von BotFather. Der API-Pod darf das Secret nicht mounten. Fehlt er, ist Telegram aus; ein Benutzername ohne Token oder umgekehrt warnt im Log |
Die Manifeste verdrahten das Telegram-Secret noch nicht; ohne Token läuft die Worker-Schleife `telegram-send` nicht (Abschnitt 10).
Die Manifeste binden das Secret nur am Worker ein (Abschnitt 7). Ohne Token laufen die Worker-Schleifen `telegram-send` und `telegram-updates` nicht (Abschnitt 10).
**Bekannte Restpunkte (bewusst nicht umgesetzt):**
@@ -367,7 +373,9 @@ Daraus folgen die Webhooks `batch.updated` und `stock.changed` (`webhooks.forwar
**Zustellplanung.** Kein Handler: `NotificationsService.write` plant nach dem Einfügen der Meldungen (dieselbe Transaktion; ohne Aufrufer-Transaktion öffnet es eine eigene, damit Meldungen und Zustellungen zusammen bestehen) über den `NotificationDeliveryPlanner` je neu eingefügter Meldung höchstens eine `NotificationDelivery` für Telegram und weckt den Worker per `pg_notify('notification_delivery', '')`, nur wenn Zeilen entstanden sind. Eine wiederholte Meldung (gleicher `dedupeKey`) plant nichts. Regeln: Annahme 49, Abschnitt 11.13.
**Worker-Schleife `telegram-send`.** Takt 5 000 ms und auf `notification_delivery`; sie ist nur registriert, wenn `TELEGRAM_BOT_TOKEN` gültig gesetzt ist (`TelegramClient.isConfigured()`). Ein Takt ruft `TelegramSender.releaseStaleClaims()` und dann `drain(stopping.signal)` auf. Mit `telegram-updates` (Task 36, noch offen) ist sie der einzige Netzzugriff zur Bot-API. Rechte kommen aus dem globalen `JobPermissionsModule` des Workers, `TelegramModule` importiert kein `PermissionsModule`.
**Worker-Schleife `telegram-send`.** Takt 5 000 ms und auf `notification_delivery`; sie ist nur registriert, wenn `TELEGRAM_BOT_TOKEN` gültig gesetzt ist (`TelegramClient.isConfigured()`). Ein Takt ruft `TelegramSender.releaseStaleClaims()` und dann `drain(stopping.signal)` auf. Mit `telegram-updates` ist sie der einzige Netzzugriff zur Bot-API. Rechte kommen aus dem globalen `JobPermissionsModule` des Workers, `TelegramModule` importiert kein `PermissionsModule`.
**Worker-Schleife `telegram-updates`.** Takt 30 000 ms (die Wartezeit ohne Lease, nach 409 und nach Fehlern), kein Weckkanal; wie `telegram-send` nur mit gültigem `TELEGRAM_BOT_TOKEN` registriert. Ein Takt ruft `TelegramUpdatesService.pollOnce(stopping.signal)`; nach `'polled'` wird die Schleife sofort wieder geweckt, das Stop-Signal bricht einen laufenden Abruf ab. Störungen stehen nur in `TelegramPollState.lastError` (Verwaltung > System) und im Log; sie machen den Worker nicht ungesund. Ablauf und Regeln: Abschnitt 11.13.
### Webhook-Zustellung
@@ -395,7 +403,7 @@ Daraus folgen die Webhooks `batch.updated` und `stock.changed` (`webhooks.forwar
- `ThrottlerHit`-Zeilen, deren Fenster abgelaufen ist und die keine aktive Sperre tragen (`"expiresAt" < now()` und `"blockedUntil"` leer oder `< now()`); eine noch laufende Sperre bleibt so erhalten.
- `DONE`-Ereignisse und `DELIVERED`-Zustellungen nach 30 Tagen (`occurredAt` bzw. `createdAt`), `FAILED`-Einträge beider Tabellen nach 90 Tagen; die Deliveries eines Ereignisses gehen per `ON DELETE CASCADE` mit. 30 Tage liegen bewusst über dem Nachholfenster der täglichen Auswertung, sonst würde ein gelöschter `dedupeKey` ein Vorkommen erneut erzeugen.
- `JobRun`-Zeilen nach 90 Tagen.
- `NotificationDelivery` (nach `createdAt`, auch Antworten des Bots ohne Nutzer): `DELIVERED` und `SKIPPED` nach 30 Tagen, `FAILED` nach 90 Tagen, `PENDING` nach 7 Tagen (`PENDING_DELIVERY_MAX_AGE_DAYS`; eine so alte Zustellung ist hängen geblieben, sie wird mit Warn-Log samt Zahl gelöscht). `TelegramLinkToken` 30 Tage nach Ablauf.
- `NotificationDelivery` (nach `createdAt`, auch Antworten des Bots ohne Nutzer): `DELIVERED` und `SKIPPED` nach 30 Tagen, `FAILED` nach 90 Tagen, `PENDING` nach 7 Tagen (`PENDING_DELIVERY_MAX_AGE_DAYS`; eine so alte Zustellung ist hängen geblieben, sie wird mit Warn-Log samt Zahl gelöscht). `TelegramLinkToken`, die seit mehr als 24 h abgelaufen oder verbraucht sind.
Das Ergebnis zählt jede Kategorie (`idempotencyRecords`, `consumedTokens`, `throttlerHits`, `domainEvents.done`, `domainEvents.failed`, `webhookDeliveries.delivered`, `webhookDeliveries.failed`, `jobRuns.aborted`, `jobRuns.deleted`, `notificationDeliveries.done`, `notificationDeliveries.failed`, `notificationDeliveries.pending`, `telegramLinkTokens`).
@@ -425,6 +433,8 @@ Das Ergebnis zählt jede Kategorie (`idempotencyRecords`, `consumedTokens`, `thr
Die Seite „Verwaltung > System“ (Rechte `system:read` zum Ansehen, `system:manage` zum Wiederholen; nur Systemrollen) zeigt je Job den letzten Lauf (`JobRun`), die Warteschlange der Domänenereignisse (offen, in Arbeit, fehlgeschlagen, Alter des ältesten offenen Eintrags nach DB-Uhr) und die offenen und fehlgeschlagenen Webhook-Zustellungen. Routen: `GET /system/overview`, `GET /system/job-runs?job=&limit=1..100` (Standard 50), `GET /system/domain-events/failed`, `POST /system/domain-events/:id/retry` (204), `GET /system/webhook-deliveries/failed`, `POST /system/webhook-deliveries/:id/retry` (204). Wiederholen ist nur für `FAILED` möglich (409 sonst, 404 unbekannt): Versuche und `availableAt` werden in SQL (`now()`) zurückgesetzt, fehlgeschlagene Handler-Zustellungen eines Ereignisses wieder `PENDING`, ein Audit-Eintrag (UPDATE) geschrieben und der Worker per `pg_notify` geweckt. Die Ansichten enthalten nie Payload, Webhook-Body, Secrets oder vollständige URLs (nur den Host); `lastError` steht wie gespeichert (`loggableError()`). API-Schlüssel erreichen `/system` nie (Scope-Allowlist).
**Telegram-Karte** (nur mit `system:manage`; Betrieb des Bots: Abschnitt 11.13). `GET /system/notification-deliveries?status=` liefert `telegram` und `deliveries`. `telegram.botNameSet` heißt nur, dass der Bot-Name gesetzt ist: Ob der Versand läuft, weiß die api nicht, weil sie das Token nie hat; er läuft nur im Worker, wenn das Secret vorhanden ist. `receiver`: `leaseOwner` (nur bei laufender Lease), `lastPollAgeSeconds` (DB-Uhr), `lastError`. `sender`: `pending`, `oldestPendingAgeSeconds` (längste Überfälligkeit; wegen der Ruhezeit Wartende zählen nicht), `failed24h` (in den letzten 24 h angelegt und fehlgeschlagen), `lastErrors` (letzte 5, mit `createdAt` = angelegt am). `deliveries`: die neuesten 100 (Status, Kategorie, Vorlage, Versuche, `availableAt`, Statuscode, Fehler, angelegt/zugestellt), nie Chat-ID, Nutzer oder Text. `POST /system/notification-deliveries/:id/retry` (204): nur `FAILED` (409 sonst, 404 unbekannt); setzt `PENDING`, Versuche 0, `availableAt = now()`, schreibt ein Audit und weckt den Worker. `POST /system/notification-deliveries/retry-failed` (200 `{ retried }`): dasselbe für die neuesten `FAILED`, höchstens 100 je Aufruf (bei mehr erneut aufrufen), unter Zeilensperre, ein Audit je Zeile.
## 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).
@@ -569,7 +579,7 @@ Ein einziger Fenster-Helfer (`src/treatments/withdrawal-window.ts`, Annahme 10)
### 11.11 Pflanzenentwicklung und Wetter
Stand: Schema, Wetterquelle, Berechnung, Job-Schritt und die Meldungs-API (Melden, Bearbeiten, Zurückziehen mit Neuberechnung) sind fertig.
Stand: Schema, Wetterquelle, Berechnung, Job-Schritt, die Meldungs-API (Melden, Bearbeiten, Zurückziehen mit Neuberechnung) und die Oberfläche zum Melden (Offline-Warteschlange eingeschlossen) sind fertig.
**Tabellen** (Migration `20261015100000_t4_phenology`, Annahme 43). `PhenologyReport` hält eine gemeldete Phase (Stand oder alle Stände, Datum, Rücknahme per `revokedAt`; Index `(apiaryId, phase, date)`). `ApiaryPhenology (apiaryId, year)` ist der abgeleitete Saisonzustand. `ApiaryWeatherDay` ist der Wetter-Cache (Tagesmittel, `source` `forecast` oder `archive`, `fetchedAt`). Rechte `phenology:read`, `phenology:create`, `phenology:update` (Gruppe „Pflanzenentwicklung“). Backup: Abschnitt 8.
@@ -589,9 +599,11 @@ Stand: Schema, Wetterquelle, Berechnung, Job-Schritt und die Meldungs-API (Melde
**Meldungen** (`PhenologyModule`, Annahme 47). Routen: `GET /phenology/state` (`apiaries:read`; je aktivem Stand Zustand ohne Koordinaten, `reportedOn` nur bei Quelle `REPORT` der früheste Meldetag der geltenden Phase), `GET /phenology/reports?year=` (`phenology:read`, Standard laufendes Jahr, auch zurückgezogene mit `revokedAt`, Stand- und Nutzername), `POST /phenology/reports` (`phenology:create`, `@Idempotent()`; Phase, Datum `JJJJ-MM-TT`, `apiaryId` oder `null` für alle, Notiz höchstens 500 Zeichen), `PATCH /phenology/reports/:id` (`phenology:update`; `null` auf Phase oder Datum: 400, auf Stand oder Notiz: leert), `POST /phenology/reports/:id/revoke` (`phenology:update`, `@Idempotent()`, schon zurückgezogen: 409). Datum in der Zukunft: 400 „Das Datum liegt in der Zukunft.“, ungültiger Tag: 400 „Das Datum ist ungültig.“, unbekannter Stand: 404 „Stand nicht gefunden.“, Bearbeiten einer zurückgezogenen Meldung: 409 „Die Meldung wurde schon zurückgezogen.“. Jede Änderung ist eine Transaktion aus Sperre auf die Meldung (`lockRowForUpdate`, danach „vorher“ neu lesen), Schreiben, Audit-Eintrag mit Vorher-Wert und Ereignis; Handler `phenology.recompute` und `phenology.recompute-apiary` (Abschnitt 10) berechnen danach die Stände neu. Saisonwechsel erscheinen in der Morgenübersicht (Abschnitt 11.9).
**Oberfläche** (Seite eines Standes). Der Kopf `ApiarySeason` zeigt Saisonabschnitt (`SeasonChip`), Phase und Quelle („gemeldet am TT.MM.“, „geschätzt“, „Kalender“) und bei schwacher Wetterbasis einen Hinweis. Das Intervall im Chip („alle 7 Tage“) stammt aus `GET /autopilot/today` (`inspectionDue[].intervalDays`) und fehlt für Stände ohne fällige Durchsicht oder ohne Recht; ein Feld `intervalDays` an `GET /phenology/state` würde es exakt machen (offen, Nachfolgearbeit). Der Knopf „Pflanze blüht“ (`phenology:create`) öffnet das Blatt „Entwicklung melden“ (`PhenologyReportSheet`): acht Zeilen (Icon und Wort, 56 px), ein Tipp meldet die Phase für heute (Berliner Tag), vorgewählt „Für alle Stände“, wahlweise „Nur <Stand>“. Jede Phase und jeder Bereich ist eine eigene Meldung mit eigenem `Idempotency-Key`. Ein Serverfehler bleibt im Blatt sichtbar; während einer Meldung oder Rücknahme lässt es sich nicht schließen. Darunter stehen die Meldungen des Jahres (`phenology:read`; eigener Stand und „alle Stände“, zurückgezogene durchgestrichen) mit „Zurückziehen“ (`phenology:update`, nur online, sonst „Nur mit Verbindung“); das Zurückziehen einer Meldung für alle Stände fragt über den `ConfirmDialog` nach. Offline landet die Meldung im IndexedDB-Speicher `pending-phenology-reports` (`apicore-offline`, Version 4; gleiche Form wie die übrigen Einzel-Warteschlangen mit Schlüssel und Besitzer; Anzeige „Pflanzenmeldung“). Der Sync sendet ihn mit den anderen Warteschlangen (`POST /phenology/reports`, originaler Schlüssel; abgelehnte Einträge bleiben mit der Antwort des Servers stehen). Danach lösen Offline-Band und Warteschlangen-Sheet ein globales `invalidateQueries()` aus, sodass Saisonzustand und Meldungsliste neu laden. Eine Meldung für einen früheren Tag bietet die Oberfläche nicht an (nur die API per PATCH). Dass ein erneutes Öffnen des Blatts dieselbe Phase doppelt melden kann, ist Annahme 55.
### 11.12 Honig-Kette und Bewegungsbuch
Stand: Ereignisse, Vorbelegung, Warnungen, Wartezeit bei der Schleuderung, der Webhook und die Laufzeit-Buchungen des Bewegungsbuchs sind fertig. Offen ist die Bestätigung beim Wassergehalt der Abfüllung (409, `acknowledgedWarnings`).
Stand: Ereignisse, Vorbelegung, Warnungen, Wartezeit bei der Schleuderung, der Webhook, die Laufzeit-Buchungen des Bewegungsbuchs und die Qualitätsprüfung der Abfüllung (API) sind fertig, ebenso die Oberfläche von Schleuderung, Honigcharge und Bewegungsbuch. Offen ist die Abfüllungsmaske mit der Wassergehalt-Bestätigung (409), sie folgt als Task 33.
**Ereignisse.** `ExtractionRecorded`/`ExtractionCorrected` und `HoneyBatchRecorded`/`HoneyBatchCorrected` entstehen in der Schreib-Transaktion mit dem Audit-Eintrag (Abschnitt 10). Der Webhook `batch.created` kommt über `webhooks.forward` aus `HoneyBatchRecorded`; `HoneyBatchCorrected` sendet nichts, wie vorher beim Ändern.
@@ -612,11 +624,20 @@ Stand: Ereignisse, Vorbelegung, Warnungen, Wartezeit bei der Schleuderung, der W
**API des Buchs.** `GET /honey-batches/:id/movements` (`honey-batches:read`; 404 für eine unbekannte Charge) antwortet `{ items, hasMore }` mit höchstens 200 Buchungen, neueste zuerst (`id`, `type`, `quantityGrams`, `reason`, `notes`, `sourceBottlingBatchId`, `createdAt`, `userId`). `POST /honey-batches/:id/movements` (`honey-batches:update`, `@Idempotent()`) nimmt `{ type: 'WITHDRAWAL' | 'CORRECTION', deltaKg, reason?, notes? }` (`deltaKg` endlich, ungleich 0, Betrag höchstens 100 000; Notiz höchstens 500 Zeichen) und antwortet mit der Buchung. Eine `WITHDRAWAL` braucht einen Grund („Bitte einen Grund angeben.“) und eine negative Menge („Eine Entnahme braucht eine negative Menge.“); bei einer `CORRECTION` ist ein Grund erlaubt und wird gespeichert. Eine Charge ohne erfasste Menge ergibt 400 „Die Menge dieser Honigcharge ist nicht erfasst. Bitte zuerst die Menge eintragen.“; ein widersprüchlicher Bestand (`initialAmount` gesetzt, `amount` leer) 409. Die Buchung schreibt Audit `HoneyBatch UPDATE` und `HoneyBatchCorrected`. Die Oberfläche zeigt die Startmenge getrennt von der Liste der Buchungen und liest `.items`.
**Antwort-Form.** Antworten von `POST/PATCH /extractions` und `/honey-batches` tragen `warnings`. Eine Bestätigung (`acknowledgedWarnings`, 409) gibt es hier nicht; sie gehört zur Abfüllung.
**Antwort-Form.** Antworten von `POST/PATCH /extractions` und `/honey-batches` tragen `warnings`. Eine Bestätigung (`acknowledgedWarnings`, 409) gibt es hier nicht; sie gehört zur Abfüllung (nächster Absatz).
**Qualität vor der Abfüllung** (Annahmen 52 und 53; `src/common/quality/water-content.ts`, `src/bottling/bottling-defaults.ts`). Der Wassergehalt der Honigcharge wird gegen die Regel `HONEY_WATER_CONTENT` geprüft (Standard: Warnschwelle 18 % nach D.I.B. „Echter Deutscher Honig“, Bestätigungsgrenze 20 % nach HonigV Anlage 2; je Honigsorte überschreibbar, etwa `{ "Heidehonig": { confirmAbovePercent: 23 } }`, Sorte ohne Beachtung der Groß-/Kleinschreibung, sonst exakt; ein Eintrag darf nur eine der beiden Grenzen setzen). Es zählt die neueste `HoneyMeasurement` (nach `measuredAt`), sonst `HoneyBatch.waterContent`.
- `WATER_CONTENT_HIGH` (WARNUNG): über der Warnschwelle. `WATER_CONTENT_MISSING` (HINWEIS): kein Wert. `WATER_CONTENT_ABOVE_LEGAL` (BESTÄTIGEN): streng über der Bestätigungsgrenze; genau 20,0 % warnt nur mit `WATER_CONTENT_HIGH`. `JAR_SIZE_DIFFERS` (HINWEIS): die gesendete Glasgröße weicht von `Product.packagingSize` ab.
- `POST /bottling-batches` antwortet bei `WATER_CONTENT_ABOVE_LEGAL` mit 409 `{ statusCode, code: 'CONFIRMATION_REQUIRED', message, waterContent, warnings }`, solange die Bestätigung fehlt. `warnings` enthält die Qualitätsbefunde der Anfrage (Wassergehalt und Glasgröße), nicht die Wartezeitwarnungen. Die Prüfung läuft in der Transaktion nach der Sperre der Honigcharge und vor dem Schreiben: Bei 409 entstehen weder Abfüllung noch Buchung, Ereignis oder Audit-Eintrag; eine zwischenzeitlich erfasste Messung zählt.
- Die bestätigte Wiederholung sendet denselben Body plus `acknowledgedWarnings: ['WATER_CONTENT_ABOVE_LEGAL']` (jeder andere Inhalt: 400) und `acknowledgedWaterContent` (Zahl 0–100) mit dem `waterContent` der 409-Antwort. Die Bestätigung gilt nur, wenn der unter der Sperre geprüfte Wert genau diesem Wert entspricht; sonst (neue Messung, Code ohne Wert, anderer Wert) folgt eine frische 409 mit dem neuen Wert. Der Idempotenz-Schlüssel wird bei Fehlern freigegeben, die Wiederholung darf also denselben `Idempotency-Key` nutzen; eine weitere Anfrage mit diesem Schlüssel nach dem 201 gibt die gespeicherte Antwort wieder.
- Die 201-Antwort trägt zuerst die Qualitätsbefunde (auch den bestätigten `WATER_CONTENT_ABOVE_LEGAL`), dann die Wartezeitwarnungen. `PATCH /bottling-batches/:id` und die Messungs-Routen der Honigcharge (`POST` und `PATCH …/measurements`, Antwort mit `warnings`) liefern nie 409. Das `PATCH` meldet Qualitätsbefunde nur, wenn sich Honigcharge oder Glasgröße ändern.
- Vorbelegung `GET /bottling-batches/prefill?honeyBatchId=&productId=&date=` (`bottling:create`, vor `:id` deklariert): `{ jarSize, jarSizeSource: 'PRODUCT' | null, bestBeforeDate, shelfLifeMonths, waterContent, warnings }`. Die Glasgröße kommt vom Artikel (`packagingSize`), das MHD aus `Product.shelfLifeMonths` (1–60, beim Anlegen und Ändern des Artikels setzbar, `null` löscht): Abfülltag plus Monate, gekürzt auf das Monatsende (31.01. + 1 Monat = 28.02.); ein Zeitstempel zählt als sein Berliner Tag, `date` ist standardmäßig heute. `honeyBatchId` fehlt: 400; unbekannte Charge oder Artikel: 404; Artikel nicht `BOTTLED_HONEY`: 400. Beim Anlegen gewinnt ein gesendeter Wert, sonst der Artikelwert; fehlt beides, antwortet die API mit 400 („Glasgröße und MHD fehlen. …“, „Ohne Haltbarkeit am Artikel bitte ein MHD eintragen.“, „Ohne Packungsgröße am Artikel bitte eine Glasgröße eintragen.“). Unmögliche Tage (30.02.) in `date`, `bestBeforeDate` und der Vorbelegung ergeben 400 „Das Datum ist ungültig. …“.
**Oberfläche der Honig-Kette.** Vorbelegungen heißen „Vorschlag aus …“ („aus 2 Ernten“, „aus den Ernten: Raps“, „aus der Schleuderung (Rest)“) und werden nur durch einen Knopf übernommen. Laden die Hinweise nicht, zeigt `PrefillStatus` (feste `aria-live`-Zeile) „Hinweise (z. B. Wartezeit) konnten nicht geladen werden.“ mit „Erneut versuchen“; Speichern bleibt erlaubt, das Backend prüft (Annahme 53). `lib/honey-batches/errors.ts` (`describeSaveError`, `saveErrorText`) ist der einzige Ort, der einen fehlgeschlagenen Speichervorgang liest (400-`issues` je Feld, Nest-`message[]` durch deutschen Text ersetzt, 409-Meldung durchgereicht, Netzfehler). Das Anlegen einer Honigcharge bietet „Wassergehalt (%)“ mit dem Vorschlag aus der Schleuderung. Die Detailseite hat die Karte „Bewegungen“ (Buchungen mit Link zur Abfüllung, Grund und Korrektur mit Vorzeichen; bei `hasMore` der Hinweis „Ältere Buchungen werden nicht angezeigt“). „Entnahme“ (nur `WITHDRAWAL`, Grund Pflicht und nicht vorgewählt, Menge mindestens 1 g und höchstens der Rest) und „Menge korrigieren“ (Ausgangswert beim Öffnen gesperrt, Differenz sichtbar, bei 0 „Keine Abweichung“, Grund optional, Buchung als „Korrektur“ beschriftet) gibt es mit `honey-batches:update` und erfasster Menge. Beide Auslöser sind offline gesperrt („Nur mit Verbindung“) und buchen mit eigenem Schlüssel je Buchung. Alle Abfragen der Detailseite liegen unter dem Schlüsselpräfix `["honey-batches"]`, das beide Dialoge ungültig machen. Die Bestätigung beim Wassergehalt (409) gehört zur Abfüllungsmaske (Task 33), nicht zu diesen Dialogen.
### 11.13 Telegram
Stand: Schema, Client, Prüfung beim Start, Planung und Senden sind fertig (`TelegramModule` importieren `WorkerRuntimeModule` und `WorkerModule`). Das Verknüpfen eines Chats und das Abfragen von Nachrichten (Task 36) fehlen noch: Es gibt noch keinen Weg, eine `TelegramLink` anzulegen. `NotificationPreference.telegramEnabled` setzt bisher nur der Sender, beim Lösen der Verbindung auf aus (Abschnitt 11.9).
Stand: Schema, Client, Prüfung beim Start, Planung, Senden, Verbinden, Empfangen und die Betriebsansicht sind fertig (`TelegramModule` importiert `WorkerRuntimeModule` und `WorkerModule`). `NotificationPreference.telegramEnabled` schaltet das Verbinden ein, das Trennen (und der Sender bei 403) aus (Abschnitt 11.9).
**Tabellen** (Migration `20261015110000_t4_telegram`). Enums `NotificationChannel` und `NotificationDeliveryStatus`. `TelegramLink` (Chat-Bindung eines Nutzers; eindeutig je Chat), `TelegramLinkToken` (Einmal-Token zum Verknüpfen), `NotificationDelivery` (Zustell-Warteschlange), `TelegramPollState` (genau eine Zeile `singleton`, per CHECK `id = 'singleton'`). Alle Fremdschlüssel auf `User` laufen mit `ON DELETE CASCADE`, ebenso `Notification.deliveries`. Keine dieser Tabellen ist Teil des Backups (Abschnitt 8).
@@ -647,4 +668,12 @@ Stand: Schema, Client, Prüfung beim Start, Planung und Senden sind fertig (`Tel
- 401 (Token ungültig): `deferClaim` um 15 min, der Sender pausiert 15 min (monotone Uhr, kein Claim), und `system:manage` bekommt einmal je Berliner Tag „Telegram: Bot-Token ungültig.“ (Schlüsselpräfix `telegram-token-invalid:<Tag>`). Scheitert die Meldung, wird das nur geloggt.
- Alles andere (5xx, Zeitüberschreitung, Netzfehler, sonstige 4xx, unerwartete Ausnahmen): `settleFailure` mit `loggableError(...).message`, Wiederholung nach der Outbox-Regel (30 s bis 6 h, nach 8 Versuchen `FAILED`).
**Verbinden.** `POST /profile/telegram/link-token` (jeder angemeldete Nutzer; Step-up mit aktuellem Passwort und bei MFA TOTP; 10 pro Minute; 201; nicht `@Idempotent`, weil die Antwort ein Geheimnis enthält; `Cache-Control: no-store`) antwortet `{ deepLink, expiresAt }` mit `https://t.me/<Bot>?start=<Token>`. Ohne `TELEGRAM_BOT_USERNAME` ergibt es 409 „Telegram ist nicht eingerichtet.“; das Bot-Token kennt die api nie. Das Token besteht aus 32 Zufallsbytes (Base64url, 43 Zeichen), gespeichert wird nur der SHA-256. Es gilt 10 Minuten (Ablauf nach DB-Uhr) und einmal; ein neues entwertet ältere offene Token desselben Nutzers. Der Job `cleanup` löscht Token, die seit mehr als 24 h abgelaufen oder verbraucht sind. `POST /profile/telegram/unlink` (204) trennt.
**Empfangen** (`TelegramUpdatesService.pollOnce`, Schleife `telegram-updates`, Abschnitt 10). Long Polling (`getUpdates`, `timeout=25`, `allowed_updates ['message']`), kein öffentlicher Eingang, nur private Chats. Genau ein Empfänger: eine Lease in `TelegramPollState` (60 s, nur DB-Uhr, jede Runde verlängert); wer sie nicht hat, wartet 30 s, ebenso nach 409 und nach Fehlern. Das setzt ein einzelnes Worker-Replikat voraus (Abschnitt 7). Jedes Update läuft in einer eigenen Transaktion, in der zuerst der Offset (`update_id + 1`) per Compare-and-Set auf Lease-Inhaber und alten Stand weitergeschoben wird; geht die Lease verloren, bricht die Transaktion samt Wirkung ab, jedes Update wirkt genau einmal. Nicht auswertbare Updates (etwa ohne `message.chat`) schiebt der Offset ohne Wirkung weiter, auch am Ende eines Batches (`getUpdates` liefert `{ updates, highestUpdateId }`). Ein Update, dessen Wirkung immer scheitert, wird nach 5 Versuchen oder 10 Minuten übersprungen (Annahme 51). Auf 429 wartet der Empfang bis `retry_after` (ohne Angabe 30 s, höchstens 1 Stunde), ohne DB und Telegram anzufassen. Beim Beenden bricht das Stop-Signal den Abruf ab, und der Worker gibt die Lease sofort frei. `lastPollAt` steht nach dem Abruf; `lastError` (fester Text plus Klassenname, nie IDs oder Nachrichtentext) wird erst nach einem Batch ohne Fehler und ohne Überspringen gelöscht.
**Befehle.** `/start <Token>` (auch `/start@Bot <Token>`) verbraucht das Token per Compare-and-Set (nur offen und nicht abgelaufen), legt die Präferenz an, sperrt `NotificationPreference` aller betroffenen Nutzer in einer Anweisung (aufsteigend) und liest Verbindung und Präferenz erst danach (dieselbe Sperre wie der 403-Pfad des Senders). Es ersetzt eine frühere Verbindung desselben Nutzers (`linkedAt` beginnt neu), löst die Verbindung eines anderen Nutzers mit demselben Chat (Meldung „Deine Telegram-Verbindung wurde getrennt, weil der Chat mit einem anderen Konto verbunden wurde.“), schaltet Telegram ein und schreibt die Meldung „Telegram verbunden mit „{Vorname}“ am TT.MM.JJJJ. Warst du das nicht? In den Einstellungen trennen.“ (deckt einen mitgelesenen Link auf; Vorname bereinigt, höchstens 64 Zeichen). Ist Nutzer oder Rolle inaktiv, oder das Token ungültig, abgelaufen oder benutzt, antwortet der Bot `LINK_INVALID` ohne Hinweis auf Konten. `/stop` und „Trennen“ in der App löschen die Verbindung, schalten Telegram aus und senden `STOPPED`. `/hilfe`, `/help`, `/start` ohne Token und anderer Text ergeben `HELP`. Antworten des Bots werden als `NotificationDelivery` mit `templateCode` und `chatId` eingereiht (kein Netzaufruf in der Transaktion) und vom Sender verschickt. Höchstens 3 Antworten je Chat in 10 Minuten (Zähler im Speicher, gezählt erst nach dem Commit); `LINKED` ist ausgenommen (Annahme 54). Jede Trennung (App, `/stop`, Chat zieht zu einem anderen Konto um) markiert die wartenden Telegram-Zustellungen des Nutzers (`PENDING`, `PROCESSING`) in derselben Transaktion als `SKIPPED` („unlinked“). Datenschutz: Vorname, Chat-ID und Token stehen nie in Logs; die Chat-ID verlässt den Server nicht (auch die Einstellungs-Antwort enthält sie nicht). Je Umgebung ein eigener Bot, weil ein Bot nur einen Empfänger haben darf.
**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. Verdrahtung des Secrets und Einrichtung des Bots: Abschnitt 7.
Logs nennen nur Zustellungs-IDs, nie Token, Chat-ID oder Text.
+3
View File
@@ -131,5 +131,8 @@ ENABLE_SWAGGER=false
# einbinden. Ein fehlerhaftes Token stoppt nichts: Telegram bleibt aus, der
# Worker loggt einen Fehler (nie den Wert). Bei BotFather Gruppen ausschalten
# (/setjoingroups) und keinen Webhook setzen.
# Je Umgebung ein eigener Bot. Im Cluster steht der Name in der ConfigMap
# (TELEGRAM_BOT_USERNAME, leer = Telegram in der App nicht eingerichtet); den
# Zustand zeigt Verwaltung > System (Telegram-Karte, nur system:manage).
# TELEGRAM_BOT_USERNAME=
# TELEGRAM_BOT_TOKEN=
@@ -0,0 +1,87 @@
import { BadRequestException } from '@nestjs/common';
import {
bestBeforeFromShelfLife,
dayOfDate,
jarSizeWarnings,
resolveJarAndBestBefore,
} from './bottling-defaults';
const article = { id: 'p1', packagingSize: 500, shelfLifeMonths: 24 };
describe('bottling defaults', () => {
it('a timestamp counts as the Berlin day, a plain day stays', () => {
expect(dayOfDate('2026-07-31')).toBe('2026-07-31');
expect(dayOfDate('2026-07-31T22:30:00.000Z')).toBe('2026-08-01');
});
it('best before is the day plus the shelf life, cut at the month end', () => {
expect(bestBeforeFromShelfLife('2027-01-31', 1)).toBe('2027-02-28');
expect(bestBeforeFromShelfLife('2026-05-10', 24)).toBe('2028-05-10');
expect(bestBeforeFromShelfLife('2026-05-10', null)).toBeNull();
});
it('takes both values from the article', () => {
expect(resolveJarAndBestBefore({ date: '2026-05-10' }, article)).toEqual({
jarSize: 500,
bestBeforeDate: '2028-05-10',
warnings: [],
});
});
it('sent values win', () => {
const result = resolveJarAndBestBefore(
{ date: '2026-05-10', jarSize: 250, bestBeforeDate: '2027-01-01' },
article,
);
expect(result.jarSize).toBe(250);
expect(result.bestBeforeDate).toBe('2027-01-01');
expect(result.warnings.map((w) => w.code)).toEqual(['JAR_SIZE_DIFFERS']);
});
it('the same jar size gives no hint, an article without a size neither', () => {
expect(jarSizeWarnings(500, article)).toEqual([]);
expect(jarSizeWarnings(250, { ...article, packagingSize: null })).toEqual(
[],
);
expect(jarSizeWarnings(250, null)).toEqual([]);
});
it('names what is missing', () => {
expect(() => resolveJarAndBestBefore({ date: '2026-05-10' }, null)).toThrow(
new BadRequestException(
'Glasgröße und MHD fehlen. Bitte einen Artikel wählen oder beides eintragen.',
),
);
expect(() =>
resolveJarAndBestBefore(
{ date: '2026-05-10' },
{ ...article, shelfLifeMonths: null },
),
).toThrow('Ohne Haltbarkeit am Artikel bitte ein MHD eintragen.');
expect(() =>
resolveJarAndBestBefore(
{ date: '2026-05-10' },
{ ...article, packagingSize: null },
),
).toThrow('Ohne Packungsgröße am Artikel');
});
});
describe('impossible days', () => {
it('are a 400, never a 500', () => {
expect(() => dayOfDate('2026-02-30')).toThrow(BadRequestException);
expect(() => dayOfDate('not a date')).toThrow(BadRequestException);
expect(() =>
resolveJarAndBestBefore(
{ date: '2026-02-30', jarSize: 500, bestBeforeDate: '2027-01-01' },
null,
),
).toThrow(BadRequestException);
expect(() =>
resolveJarAndBestBefore(
{ date: '2026-02-01', jarSize: 500, bestBeforeDate: '2027-02-30' },
null,
),
).toThrow(BadRequestException);
});
});
@@ -0,0 +1,109 @@
import { BadRequestException } from '@nestjs/common';
import { addMonthsClamped, berlinDayOf, dayToDate } from '../common/dates';
import {
WARNING_SEVERITY,
type PlausibilityWarning,
} from '../common/warnings/plausibility-warning';
import { formatNumberDe } from '../suggestions/texts/format-number';
/** What a bottling takes over from its article (spec 7.8). */
export interface ArticleDefaults {
id: string;
packagingSize: number | null;
shelfLifeMonths: number | null;
}
const DAY = /^\d{4}-\d{2}-\d{2}$/;
const INVALID_DATE =
'Das Datum ist ungültig. Bitte ein Datum wie 2026-07-31 angeben.';
/** The calendar day of a date or timestamp; a timestamp counts in Berlin. */
export function dayOfDate(date: string): string {
try {
const day = DAY.test(date) ? date : berlinDayOf(new Date(date));
dayToDate(day);
return day;
} catch {
throw new BadRequestException(INVALID_DATE);
}
}
/** Bottling day plus the article's shelf life; null without a shelf life. */
export function bestBeforeFromShelfLife(
date: string,
shelfLifeMonths: number | null,
): string | null {
return shelfLifeMonths === null
? null
: addMonthsClamped(dayOfDate(date), shelfLifeMonths);
}
export interface ResolvedJarAndBestBefore {
jarSize: number;
/** YYYY-MM-DD, or the text the client sent. */
bestBeforeDate: string;
warnings: PlausibilityWarning[];
}
/**
* Jar size and best-before date of a bottling: what was sent wins, else the
* article's packaging size and date + shelf life. There is no default shelf
* life: without one the beekeeper enters the date (spec 7.8).
*/
export function resolveJarAndBestBefore(
sent: { jarSize?: number; bestBeforeDate?: string; date: string },
article: ArticleDefaults | null,
): ResolvedJarAndBestBefore {
// An impossible day is the client's error (400), never a 500.
dayOfDate(sent.date);
if (sent.bestBeforeDate !== undefined) {
dayOfDate(sent.bestBeforeDate);
}
const jarSize = sent.jarSize ?? article?.packagingSize ?? null;
const bestBeforeDate =
sent.bestBeforeDate ??
bestBeforeFromShelfLife(sent.date, article?.shelfLifeMonths ?? null);
if (jarSize === null || bestBeforeDate === null) {
throw new BadRequestException(
missingMessage(jarSize, bestBeforeDate, article),
);
}
const warnings =
sent.jarSize === undefined ? [] : jarSizeWarnings(sent.jarSize, article);
return { jarSize, bestBeforeDate, warnings };
}
function missingMessage(
jarSize: number | null,
bestBeforeDate: string | null,
article: ArticleDefaults | null,
): string {
if (article === null || (jarSize === null && bestBeforeDate === null)) {
return 'Glasgröße und MHD fehlen. Bitte einen Artikel wählen oder beides eintragen.';
}
return jarSize === null
? 'Ohne Packungsgröße am Artikel bitte eine Glasgröße eintragen.'
: 'Ohne Haltbarkeit am Artikel bitte ein MHD eintragen.';
}
/** The hint for a jar size that differs from the article's packaging size. */
export function jarSizeWarnings(
jarSize: number,
article: ArticleDefaults | null,
): PlausibilityWarning[] {
if (
article === null ||
article.packagingSize === null ||
article.packagingSize === jarSize
) {
return [];
}
return [
{
code: 'JAR_SIZE_DIFFERS',
severity: WARNING_SEVERITY.JAR_SIZE_DIFFERS,
message: `Die Glasgröße (${formatNumberDe(jarSize, 0)} g) weicht vom Artikel ab (${formatNumberDe(article.packagingSize, 0)} g).`,
refs: [{ type: 'Product', id: article.id }],
},
];
}
@@ -0,0 +1,105 @@
import { BadRequestException, NotFoundException } from '@nestjs/common';
import type { PrismaService } from '../prisma/prisma.service';
import { BottlingPrefillService } from './bottling-prefill.service';
describe('BottlingPrefillService', () => {
let service: BottlingPrefillService;
let prisma: {
honeyBatch: { findUnique: jest.Mock };
honeyMeasurement: { findMany: jest.Mock };
automationRule: { findUnique: jest.Mock };
product: { findUnique: jest.Mock };
};
beforeEach(() => {
prisma = {
honeyBatch: {
findUnique: jest.fn().mockResolvedValue({
id: 'h1',
honeyType: null,
waterContent: 19,
}),
},
honeyMeasurement: { findMany: jest.fn().mockResolvedValue([]) },
automationRule: { findUnique: jest.fn().mockResolvedValue(null) },
product: { findUnique: jest.fn() },
};
service = new BottlingPrefillService(prisma as unknown as PrismaService);
});
it('offers jar size, best before and water content with the warning', async () => {
prisma.product.findUnique.mockResolvedValue({
kind: 'BOTTLED_HONEY',
packagingSize: 500,
shelfLifeMonths: 24,
});
const result = await service.prefill({
honeyBatchId: 'h1',
productId: 'p1',
date: '2026-05-10',
});
expect(result).toMatchObject({
jarSize: 500,
jarSizeSource: 'PRODUCT',
bestBeforeDate: '2028-05-10',
shelfLifeMonths: 24,
waterContent: 19,
});
expect(result.warnings.map((w) => w.code)).toEqual(['WATER_CONTENT_HIGH']);
});
it('without an article only the water content is offered', async () => {
const result = await service.prefill({ honeyBatchId: 'h1' });
expect(result).toMatchObject({
jarSize: null,
jarSizeSource: null,
bestBeforeDate: null,
shelfLifeMonths: null,
waterContent: 19,
});
});
it('an article without a shelf life gives no best before', async () => {
prisma.product.findUnique.mockResolvedValue({
kind: 'BOTTLED_HONEY',
packagingSize: 250,
shelfLifeMonths: null,
});
const result = await service.prefill({
honeyBatchId: 'h1',
productId: 'p1',
});
expect(result.jarSize).toBe(250);
expect(result.bestBeforeDate).toBeNull();
});
it('reports an unknown honey batch or article', async () => {
prisma.honeyBatch.findUnique.mockResolvedValue(null);
await expect(
service.prefill({ honeyBatchId: 'missing' }),
).rejects.toBeInstanceOf(NotFoundException);
prisma.honeyBatch.findUnique.mockResolvedValue({ id: 'h1' });
prisma.product.findUnique.mockResolvedValue(null);
await expect(
service.prefill({ honeyBatchId: 'h1', productId: 'missing' }),
).rejects.toBeInstanceOf(NotFoundException);
});
it('refuses an article that is not bottled honey', async () => {
prisma.product.findUnique.mockResolvedValue({
kind: 'MANUFACTURED',
packagingSize: null,
shelfLifeMonths: null,
});
await expect(
service.prefill({ honeyBatchId: 'h1', productId: 'p2' }),
).rejects.toBeInstanceOf(BadRequestException);
});
});
@@ -0,0 +1,99 @@
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { ApiProperty } from '@nestjs/swagger';
import { berlinToday } from '../common/dates';
import type { PlausibilityWarning } from '../common/warnings/plausibility-warning';
import { PrismaService } from '../prisma/prisma.service';
import { bestBeforeFromShelfLife } from './bottling-defaults';
import type { BottlingPrefillQuery } from './dto/bottling-prefill.query';
import { waterContentWarningsOfBatch } from '../common/quality/water-content';
const SOURCE_NOTE =
'Stammdaten des Artikels, keine Beobachtung. Das Formular nennt die Herkunft.';
/** What the bottling form may fill in for a honey batch and an article. */
export class BottlingPrefill {
@ApiProperty({ type: Number, nullable: true, description: SOURCE_NOTE })
jarSize!: number | null;
@ApiProperty({ enum: ['PRODUCT'], nullable: true })
jarSizeSource!: 'PRODUCT' | null;
@ApiProperty({
type: String,
nullable: true,
description: 'Abfülldatum plus Haltbarkeit des Artikels (YYYY-MM-DD)',
})
bestBeforeDate!: string | null;
@ApiProperty({ type: Number, nullable: true })
shelfLifeMonths!: number | null;
@ApiProperty({
type: Number,
nullable: true,
description: 'Jüngste Messung der Charge, sonst ihr eigener Wert',
})
waterContent!: number | null;
@ApiProperty({ type: 'array', items: { type: 'object' } })
warnings!: PlausibilityWarning[];
}
export type BottlingPrefillInput = Pick<
BottlingPrefillQuery,
'honeyBatchId' | 'productId' | 'date'
>;
/** Read only: nothing is written, nothing is locked. */
@Injectable()
export class BottlingPrefillService {
constructor(private readonly prisma: PrismaService) {}
async prefill(query: BottlingPrefillInput): Promise<BottlingPrefill> {
const water = await waterContentWarningsOfBatch(
this.prisma,
query.honeyBatchId,
);
if (water === null) {
throw new NotFoundException('Honey batch not found');
}
const product =
query.productId === undefined
? null
: await this.prisma.product.findUnique({
where: { id: query.productId },
select: {
kind: true,
packagingSize: true,
shelfLifeMonths: true,
},
});
if (query.productId !== undefined) {
if (!product) {
throw new NotFoundException('Product not found');
}
if (product.kind !== 'BOTTLED_HONEY') {
throw new BadRequestException(
'Abfüllungen nur für Honig-Artikel - hergestellte Waren bekommen Herstellungschargen',
);
}
}
const shelfLifeMonths = product?.shelfLifeMonths ?? null;
const jarSize = product?.packagingSize ?? null;
return {
jarSize,
jarSizeSource: jarSize === null ? null : 'PRODUCT',
bestBeforeDate: bestBeforeFromShelfLife(
query.date ?? berlinToday(),
shelfLifeMonths,
),
shelfLifeMonths,
waterContent: water.waterContent,
warnings: water.warnings,
};
}
}
@@ -15,6 +15,8 @@ import type { AuthenticatedUser } from '../auth/types/authenticated-user';
import { CreateBottlingBatchDto } from './dto/create-bottling-batch.dto';
import { UpdateBottlingBatchDto } from './dto/update-bottling-batch.dto';
import { BottlingService } from './bottling.service';
import { BottlingPrefillService } from './bottling-prefill.service';
import { BottlingPrefillQuery } from './dto/bottling-prefill.query';
import { Idempotent } from '../common/idempotency/idempotent.decorator';
import { StockService } from '../stock/stock.service';
import { WithdrawStockDto } from '../stock/dto/withdraw-stock.dto';
@@ -26,6 +28,7 @@ import { CorrectStockDto } from '../stock/dto/correct-stock.dto';
export class BottlingController {
constructor(
private readonly bottlingService: BottlingService,
private readonly prefillService: BottlingPrefillService,
private readonly stock: StockService,
) {}
@@ -35,6 +38,15 @@ export class BottlingController {
return this.bottlingService.findAll({ honeyBatchId });
}
// Before ':id', so 'prefill' is not read as an id. Needs the create
// permission, like the other prefill routes: it offers what the create
// flow needs.
@RequirePermission('bottling:create')
@Get('prefill')
prefill(@Query() query: BottlingPrefillQuery) {
return this.prefillService.prefill(query);
}
@RequirePermission('bottling:read')
@Get(':id')
findOne(@Param('id') id: string) {
@@ -5,6 +5,7 @@ import { StockModule } from '../stock/stock.module';
import { WithdrawalModule } from '../withdrawal/withdrawal.module';
import { BottlingController } from './bottling.controller';
import { BottlingService } from './bottling.service';
import { BottlingPrefillService } from './bottling-prefill.service';
@Module({
imports: [
@@ -14,6 +15,6 @@ import { BottlingService } from './bottling.service';
WithdrawalModule,
],
controllers: [BottlingController],
providers: [BottlingService],
providers: [BottlingService, BottlingPrefillService],
})
export class BottlingModule {}
@@ -70,6 +70,8 @@ describe('BottlingService', () => {
update: jest.Mock;
delete: jest.Mock;
};
honeyMeasurement: { findMany: jest.Mock };
automationRule: { findUnique: jest.Mock };
honeyBatch: { findUnique: jest.Mock; update: jest.Mock };
batchMovement: { count: jest.Mock };
};
@@ -94,6 +96,9 @@ describe('BottlingService', () => {
return Promise.resolve([{ id: 'row' }]);
}),
product: { findUnique: jest.fn() },
// No measurements and no rule row: the built-in limits apply.
honeyMeasurement: { findMany: jest.fn().mockResolvedValue([]) },
automationRule: { findUnique: jest.fn().mockResolvedValue(null) },
// By default a bottling has drawn from the ledger (own BOTTLING booking).
batchMovement: { count: jest.fn().mockResolvedValue(1) },
bottlingBatch: {
@@ -1006,4 +1011,311 @@ describe('BottlingService', () => {
);
});
});
describe('quality before bottling (spec 7.8)', () => {
const base = {
honeyBatchId: 'h1',
date: '2026-01-31',
jarCount: 10,
lotNumber: 'L-1',
};
/** A honey batch in the transaction with the given water content. */
function batchWith(waterContent: number | null, honeyType: string | null) {
prisma.honeyBatch.findUnique.mockResolvedValueOnce({ id: 'h1' });
honeyBatches.set('h1', { amount: 25 });
tx.honeyBatch.findUnique.mockImplementation(
({ where }: { where: { id: string } }) =>
Promise.resolve({
id: where.id,
amount: 25,
waterContent,
honeyType,
}),
);
tx.bottlingBatch.create.mockResolvedValue({
id: 'b1',
honeyBatchId: 'h1',
});
tx.bottlingBatch.findUnique.mockResolvedValue({ id: 'b1' });
}
function article(extra: Record<string, unknown> = {}) {
const product = {
id: 'p1',
kind: 'BOTTLED_HONEY',
packagingSize: 500,
shelfLifeMonths: 24,
...extra,
};
prisma.product.findUnique.mockResolvedValue(product);
return product;
}
it('19 % is written and answers WATER_CONTENT_HIGH', async () => {
batchWith(19, null);
const result = await service.create(
{ ...base, jarSize: 500, bestBeforeDate: '2027-01-01' },
'user-1',
);
expect(result.warnings.map((w) => w.code)).toEqual([
'WATER_CONTENT_HIGH',
]);
expect(tx.bottlingBatch.create).toHaveBeenCalledTimes(1);
});
it('above the legal limit it refuses with CONFIRMATION_REQUIRED and writes nothing', async () => {
batchWith(20.5, null);
const error = await service
.create(
{ ...base, jarSize: 500, bestBeforeDate: '2027-01-01' },
'user-1',
)
.catch((e: unknown) => e);
expect(error).toBeInstanceOf(ConflictException);
const body = (error as ConflictException).getResponse() as {
code: string;
message: string;
warnings: PlausibilityWarning[];
};
expect(body.code).toBe('CONFIRMATION_REQUIRED');
expect(body.warnings.map((w) => w.code)).toEqual([
'WATER_CONTENT_ABOVE_LEGAL',
]);
expect(typeof body.message).toBe('string');
expect(tx.bottlingBatch.create).not.toHaveBeenCalled();
expect(ledger.bookIn).not.toHaveBeenCalled();
});
it('the confirmed repeat is written and still reports the finding', async () => {
batchWith(20.5, null);
const result = await service.create(
{
...base,
jarSize: 500,
bestBeforeDate: '2027-01-01',
acknowledgedWarnings: ['WATER_CONTENT_ABOVE_LEGAL'],
acknowledgedWaterContent: 20.5,
},
'user-1',
);
expect(result.warnings.map((w) => w.code)).toEqual([
'WATER_CONTENT_ABOVE_LEGAL',
]);
expect(tx.bottlingBatch.create).toHaveBeenCalledTimes(1);
});
it('a newer measurement decides, read under the batch lock', async () => {
batchWith(21, null);
tx.honeyMeasurement.findMany.mockResolvedValue([
{ waterContent: 17, measuredAt: new Date('2026-01-20') },
]);
const result = await service.create(
{ ...base, jarSize: 500, bestBeforeDate: '2027-01-01' },
'user-1',
);
expect(result.warnings).toEqual([]);
expect(steps[0]).toBe('lock');
});
it('a missing water content is a hint, not a stop', async () => {
batchWith(null, null);
const result = await service.create(
{ ...base, jarSize: 500, bestBeforeDate: '2027-01-01' },
'user-1',
);
expect(result.warnings.map((w) => w.code)).toEqual([
'WATER_CONTENT_MISSING',
]);
});
it('takes jar size and best before from the article, month end cut', async () => {
batchWith(17, null);
article({ shelfLifeMonths: 1 });
await service.create({ ...base, productId: 'p1' }, 'user-1');
expect(tx.bottlingBatch.create).toHaveBeenCalledWith({
data: expect.objectContaining({
jarSize: 500,
totalAmount: 5,
bestBeforeDate: new Date('2026-02-28'),
}) as unknown,
});
});
it('a sent value wins, and another jar size gives JAR_SIZE_DIFFERS', async () => {
batchWith(17, null);
article();
const result = await service.create(
{
...base,
productId: 'p1',
jarSize: 250,
bestBeforeDate: '2027-05-05',
},
'user-1',
);
expect(result.warnings.map((w) => w.code)).toEqual(['JAR_SIZE_DIFFERS']);
expect(tx.bottlingBatch.create).toHaveBeenCalledWith({
data: expect.objectContaining({
jarSize: 250,
bestBeforeDate: new Date('2027-05-05'),
}) as unknown,
});
});
it('refuses with a clear text when neither jar size nor best before is known', async () => {
prisma.honeyBatch.findUnique.mockResolvedValueOnce({ id: 'h1' });
await expect(service.create(base, 'user-1')).rejects.toThrow(
new BadRequestException(
'Glasgröße und MHD fehlen. Bitte einen Artikel wählen oder beides eintragen.',
),
);
});
it('refuses without a shelf life on the article when no best before is sent', async () => {
prisma.honeyBatch.findUnique.mockResolvedValueOnce({ id: 'h1' });
article({ shelfLifeMonths: null });
await expect(
service.create({ ...base, productId: 'p1' }, 'user-1'),
).rejects.toThrow(
new BadRequestException(
'Ohne Haltbarkeit am Artikel bitte ein MHD eintragen.',
),
);
expect(tx.bottlingBatch.create).not.toHaveBeenCalled();
});
it('a correction only reports: never a 409', async () => {
const before = {
id: 'b1',
lotNumber: 'L-1',
honeyBatchId: 'h1',
productId: null,
honeyBatch: { id: 'h1', amount: 10 },
jarSize: 500,
jarCount: 10,
totalAmount: 5,
};
lockedRows(before, before);
tx.honeyBatch.findUnique.mockResolvedValue({
id: 'h1',
amount: 10,
waterContent: 22,
honeyType: null,
});
honeyBatches.set('h1', { amount: 10 });
const result = await service.update('b1', { jarSize: 250 }, 'user-1');
expect(result.warnings.map((w) => w.code)).toEqual([
'WATER_CONTENT_ABOVE_LEGAL',
]);
});
it('a correction that touches neither honey batch nor jar size reports no quality finding', async () => {
const before = {
id: 'b1',
lotNumber: 'L-1',
honeyBatchId: 'h1',
productId: null,
honeyBatch: { id: 'h1', amount: 10 },
jarSize: 500,
jarCount: 10,
totalAmount: 5,
};
lockedRows(before, before);
tx.honeyBatch.findUnique.mockResolvedValue({
id: 'h1',
amount: 10,
waterContent: 22,
honeyType: null,
});
const result = await service.update('b1', { lotNumber: 'L-2' }, 'user-1');
expect(result.warnings).toEqual([]);
});
async function refusal(
extra: Record<string, unknown>,
): Promise<{ waterContent: number; code: string }> {
batchWith(20.5, null);
const error = await service
.create(
{
...base,
jarSize: 500,
bestBeforeDate: '2027-01-01',
acknowledgedWarnings: ['WATER_CONTENT_ABOVE_LEGAL'],
...extra,
},
'user-1',
)
.catch((e: unknown) => e);
expect(error).toBeInstanceOf(ConflictException);
return (error as ConflictException).getResponse() as {
waterContent: number;
code: string;
};
}
it('the 409 names the checked value', async () => {
batchWith(20.5, null);
const error = await service
.create(
{ ...base, jarSize: 500, bestBeforeDate: '2027-01-01' },
'user-1',
)
.catch((e: unknown) => e);
expect(
((error as ConflictException).getResponse() as { waterContent: number })
.waterContent,
).toBe(20.5);
});
it('a confirmation for another value gets a fresh 409 with the new value', async () => {
const body = await refusal({ acknowledgedWaterContent: 20.2 });
expect(body).toMatchObject({
code: 'CONFIRMATION_REQUIRED',
waterContent: 20.5,
});
expect(tx.bottlingBatch.create).not.toHaveBeenCalled();
});
it('the code without the value is not a confirmation', async () => {
const body = await refusal({});
expect(body.code).toBe('CONFIRMATION_REQUIRED');
});
it('an impossible day is a 400', async () => {
prisma.honeyBatch.findUnique.mockResolvedValueOnce({ id: 'h1' });
await expect(
service.create(
{
...base,
date: '2026-02-30',
jarSize: 500,
bestBeforeDate: '2027-01-01',
},
'user-1',
),
).rejects.toBeInstanceOf(BadRequestException);
});
});
});
+114 -20
View File
@@ -12,10 +12,15 @@ import { DomainEventsService } from '../domain-events/domain-events.service';
import type { AnyNewDomainEvent } from '../domain-events/domain-event-types';
import { AutomationService } from '../automation/automation.service';
import { StockService } from '../stock/stock.service';
import { withWarnings } from '../common/warnings/plausibility-warning';
import {
withWarnings,
type PlausibilityWarning,
} from '../common/warnings/plausibility-warning';
import { WithdrawalCheckService } from '../withdrawal/withdrawal-check.service';
import { Prisma } from '../../generated/prisma';
import { HoneyBatchLedgerService } from '../honey-batches/honey-batch-ledger.service';
import { jarSizeWarnings, resolveJarAndBestBefore } from './bottling-defaults';
import { waterContentWarningsOfBatch } from '../common/quality/water-content';
import { CreateBottlingBatchDto } from './dto/create-bottling-batch.dto';
import { UpdateBottlingBatchDto } from './dto/update-bottling-batch.dto';
@@ -114,15 +119,36 @@ export class BottlingService {
db: DbClient,
honeyBatchId: string,
bottling: T,
qualityWarnings: readonly PlausibilityWarning[] = [],
) {
const conflicts = await this.withdrawalCheck.conflictsForHoneyBatch(
db,
honeyBatchId,
);
return withWarnings(
bottling,
await this.withdrawalCheck.warningsFor(db, conflicts),
);
return withWarnings(bottling, [
...qualityWarnings,
...(await this.withdrawalCheck.warningsFor(db, conflicts)),
]);
}
/**
* The quality findings for the honey batch as it stands in the caller's
* transaction: its newest water content against the rule (spec 7.8) and
* the hint for a jar size that differs from the article.
*/
private async qualityWarnings(
tx: Tx,
honeyBatchId: string,
jarWarnings: readonly PlausibilityWarning[],
): Promise<{
warnings: PlausibilityWarning[];
waterContent: number | null;
}> {
const water = await waterContentWarningsOfBatch(tx, honeyBatchId);
return {
warnings: [...(water?.warnings ?? []), ...jarWarnings],
waterContent: water?.waterContent ?? null,
};
}
async findAll(filter: BottlingBatchFilter = {}) {
@@ -158,10 +184,7 @@ export class BottlingService {
}
/** Honey is bottled; other articles keep their stock in production batches. */
private async assertBottledProduct(
productId: string,
tx?: Tx,
): Promise<void> {
private async assertBottledProduct(productId: string, tx?: Tx) {
const db: DbClient = tx ?? this.prisma;
const product = await db.product.findUnique({
where: { id: productId },
@@ -174,6 +197,7 @@ export class BottlingService {
'Abfüllungen nur für Honig-Artikel - hergestellte Waren bekommen Herstellungschargen',
);
}
return product;
}
async create(dto: CreateBottlingBatchDto, actingUserId: string) {
@@ -184,11 +208,11 @@ export class BottlingService {
if (!honeyBatch) {
throw new NotFoundException('Honey batch not found');
}
if (dto.productId) {
await this.assertBottledProduct(dto.productId);
}
const totalAmount = roundKg((dto.jarSize * dto.jarCount) / 1000);
const article = dto.productId
? await this.assertBottledProduct(dto.productId)
: null;
const resolved = resolveJarAndBestBefore(dto, article);
const totalAmount = roundKg((resolved.jarSize * dto.jarCount) / 1000);
const lotNumber =
dto.lotNumber ??
@@ -205,15 +229,22 @@ export class BottlingService {
if (!(await lockRowForUpdate(tx, 'HoneyBatch', dto.honeyBatchId))) {
throw new NotFoundException('Honey batch not found');
}
// Under the batch lock: a measurement entered meanwhile counts.
const quality = await this.qualityWarnings(
tx,
dto.honeyBatchId,
resolved.warnings,
);
this.assertConfirmed(quality, dto);
const created = await tx.bottlingBatch.create({
data: {
honeyBatchId: dto.honeyBatchId,
productId: dto.productId,
date: new Date(dto.date),
jarSize: dto.jarSize,
jarSize: resolved.jarSize,
jarCount: dto.jarCount,
totalAmount,
bestBeforeDate: new Date(dto.bestBeforeDate),
bestBeforeDate: new Date(resolved.bestBeforeDate),
lotNumber,
userId: actingUserId,
},
@@ -247,10 +278,52 @@ export class BottlingService {
tx,
created.honeyBatchId,
await this.findById(created.id, tx),
quality.warnings,
);
});
}
/**
* A finding that needs a confirmation (BESTAETIGEN) stops the write with
* 409 CONFIRMATION_REQUIRED, unless the request names its code in
* `acknowledgedWarnings` AND the checked value in `acknowledgedWaterContent`:
* a confirmation belongs to the value the beekeeper saw. If the value under
* the lock differs (a new measurement meanwhile), a fresh 409 with the new
* value follows. The body carries every finding of the request, so the form
* can show them in one dialog. The idempotency interceptor frees the key on
* this error: the confirmed repeat may use the same key.
*/
private assertConfirmed(
quality: {
warnings: readonly PlausibilityWarning[];
waterContent: number | null;
},
sent: Pick<
CreateBottlingBatchDto,
'acknowledgedWarnings' | 'acknowledgedWaterContent'
>,
): void {
const acknowledged: readonly string[] = sent.acknowledgedWarnings ?? [];
const open = quality.warnings.filter(
(warning) =>
warning.severity === 'BESTAETIGEN' &&
!(
acknowledged.includes(warning.code) &&
sent.acknowledgedWaterContent !== undefined &&
sent.acknowledgedWaterContent === quality.waterContent
),
);
if (open.length > 0) {
throw new ConflictException({
statusCode: 409,
code: 'CONFIRMATION_REQUIRED',
message: open.map((warning) => warning.message).join(' '),
waterContent: quality.waterContent,
warnings: quality.warnings,
});
}
}
/**
* Corrects any field of an existing bottling batch. Changing the honey
* batch, the jar size or the jar count also rebalances the remaining amount
@@ -269,9 +342,11 @@ export class BottlingService {
return this.prisma.$transaction(async (tx) => {
await lockRowForUpdate(tx, 'BottlingBatch', id);
const before = await this.findById(id, tx);
if (dto.productId) {
await this.assertBottledProduct(dto.productId, tx);
}
const article = dto.productId
? await this.assertBottledProduct(dto.productId, tx)
: dto.productId === undefined && before.productId
? await tx.product.findUnique({ where: { id: before.productId } })
: null;
const honeyBatchId = dto.honeyBatchId ?? before.honeyBatchId;
const movedToOtherHoneyBatch = honeyBatchId !== before.honeyBatchId;
@@ -342,6 +417,20 @@ export class BottlingService {
});
const bottlingBatch = await this.findById(id, tx);
// A correction only reports (spec 7.8): the confirmation belongs to
// the creation.
// Only when the correction touches what the findings are about.
const qualityChecked =
movedToOtherHoneyBatch || jarSize !== before.jarSize;
const quality = qualityChecked
? (
await this.qualityWarnings(
tx,
honeyBatchId,
jarSizeWarnings(jarSize, article),
)
).warnings
: [];
await this.auditLog.record(
{
entityType: 'BottlingBatch',
@@ -362,7 +451,12 @@ export class BottlingService {
payload: { honeyBatchId, removed: false },
actorUserId: actingUserId,
});
return this.withWithdrawalWarnings(tx, honeyBatchId, bottlingBatch);
return this.withWithdrawalWarnings(
tx,
honeyBatchId,
bottlingBatch,
quality,
);
});
}
@@ -0,0 +1,33 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import {
IsISO8601,
IsOptional,
IsString,
Matches,
MaxLength,
} from 'class-validator';
const MAX_ID_LENGTH = 64;
const ID_PATTERN = /^[A-Za-z0-9_-]+$/;
export class BottlingPrefillQuery {
@ApiProperty({ description: 'Die Honigcharge, die abgefüllt wird' })
@IsString()
@MaxLength(MAX_ID_LENGTH)
@Matches(ID_PATTERN)
honeyBatchId!: string;
@ApiPropertyOptional({ description: 'Der Artikel (Honig-Artikel)' })
@IsOptional()
@IsString()
@MaxLength(MAX_ID_LENGTH)
@Matches(ID_PATTERN)
productId?: string;
@ApiPropertyOptional({
description: 'Abfülldatum (Standard: heute), Grundlage für das MHD',
})
@IsOptional()
@IsISO8601({ strict: true })
date?: string;
}
@@ -1,6 +1,12 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import {
Max,
Min,
ArrayMaxSize,
ArrayUnique,
IsArray,
IsDateString,
IsIn,
IsInt,
IsNumber,
IsOptional,
@@ -8,6 +14,12 @@ import {
IsString,
} from 'class-validator';
export const BOTTLING_ACKNOWLEDGEABLE_WARNINGS = [
'WATER_CONTENT_ABOVE_LEGAL',
] as const;
export type AcknowledgeableWarning =
(typeof BOTTLING_ACKNOWLEDGEABLE_WARNINGS)[number];
export class CreateBottlingBatchDto {
@ApiProperty()
@IsString()
@@ -19,22 +31,30 @@ export class CreateBottlingBatchDto {
productId?: string;
@ApiProperty()
@IsDateString()
@IsDateString({ strict: true })
date!: string;
@ApiProperty({ description: 'Glasgröße in Gramm' })
@ApiPropertyOptional({
description:
'Glasgröße in Gramm. Fehlt sie, gilt die Packungsgröße des Artikels.',
})
@IsOptional()
@IsNumber()
@IsPositive()
jarSize!: number;
jarSize?: number;
@ApiProperty()
@IsInt()
@IsPositive()
jarCount!: number;
@ApiProperty()
@IsDateString()
bestBeforeDate!: string;
@ApiPropertyOptional({
description:
'MHD. Fehlt es, gilt Abfülldatum plus Haltbarkeit des Artikels (Monatsende abgeschnitten).',
})
@IsOptional()
@IsDateString({ strict: true })
bestBeforeDate?: string;
@ApiPropertyOptional({
description:
@@ -43,4 +63,27 @@ export class CreateBottlingBatchDto {
@IsOptional()
@IsString()
lotNumber?: string;
@ApiPropertyOptional({
enum: BOTTLING_ACKNOWLEDGEABLE_WARNINGS,
isArray: true,
description:
'Bestätigte Warnungen. Über der gesetzlichen Wassergehaltsgrenze nötig, sonst 409 CONFIRMATION_REQUIRED.',
})
@IsOptional()
@IsArray()
@ArrayMaxSize(1)
@ArrayUnique()
@IsIn(BOTTLING_ACKNOWLEDGEABLE_WARNINGS, { each: true })
acknowledgedWarnings?: AcknowledgeableWarning[];
@ApiPropertyOptional({
description:
'Der Wassergehalt (%), den die Bestätigung meint: der Wert aus der 409-Antwort. Weicht der geprüfte Wert ab, folgt eine neue 409.',
})
@IsOptional()
@IsNumber()
@Min(0)
@Max(100)
acknowledgedWaterContent?: number;
}
+16
View File
@@ -1,5 +1,6 @@
import {
addDays,
addMonthsClamped,
berlinDateTime,
berlinDayOf,
berlinToday,
@@ -97,4 +98,19 @@ describe('dates', () => {
it('daysBetween counts whole days across a DST change', () => {
expect(daysBetween('2026-03-28', '2026-03-30')).toBe(2);
});
it('best before 2027-01-31 plus 1 month is 2027-02-28', () => {
expect(addMonthsClamped('2027-01-31', 1)).toBe('2027-02-28');
});
it('addMonthsClamped keeps the leap day and crosses year ends', () => {
expect(addMonthsClamped('2028-01-31', 1)).toBe('2028-02-29');
expect(addMonthsClamped('2026-11-15', 3)).toBe('2027-02-15');
expect(addMonthsClamped('2026-03-31', 24)).toBe('2028-03-31');
expect(addMonthsClamped('2026-08-31', 1)).toBe('2026-09-30');
});
it('addMonthsClamped rejects an impossible day', () => {
expect(() => addMonthsClamped('2026-02-30', 1)).toThrow();
});
});
+21
View File
@@ -55,6 +55,27 @@ export function addDays(day: string, days: number): string {
return result.toISOString().slice(0, 10);
}
/**
* Calendar months on a YYYY-MM-DD string. A day the target month does not
* have is cut to its last day: 2027-01-31 + 1 month is 2027-02-28.
*/
export function addMonthsClamped(day: string, months: number): string {
const start = dayToDate(day);
const monthIndex = start.getUTCMonth() + months;
const lastDay = new Date(
Date.UTC(start.getUTCFullYear(), monthIndex + 1, 0),
).getUTCDate();
return new Date(
Date.UTC(
start.getUTCFullYear(),
monthIndex,
Math.min(start.getUTCDate(), lastDay),
),
)
.toISOString()
.slice(0, 10);
}
/** Whole calendar days from `from` to `to` (negative when `to` is earlier). */
export function daysBetween(from: string, to: string): number {
return dayNumber(to) - dayNumber(from);
@@ -0,0 +1,114 @@
import type { WaterContentConfig } from '../../automation/rule-config/rule-config.types';
import { latestWaterContent, waterContentWarnings } from './water-content';
const config: WaterContentConfig = {
warnAbovePercent: 18,
confirmAbovePercent: 20,
byHoneyType: {},
};
const refs = [{ type: 'HoneyBatch', id: 'hb1' }];
describe('latestWaterContent', () => {
it('the newest measurement wins over the batch value', () => {
expect(
latestWaterContent({ waterContent: 17 }, [
{ waterContent: 19, measuredAt: new Date('2026-08-01') },
{ waterContent: 21, measuredAt: new Date('2026-09-01') },
{ waterContent: 18, measuredAt: new Date('2026-07-01') },
]),
).toBe(21);
});
it('falls back to the batch value without measurements', () => {
expect(latestWaterContent({ waterContent: 17.5 }, [])).toBe(17.5);
});
it('is null without any value', () => {
expect(latestWaterContent({ waterContent: null }, [])).toBeNull();
});
});
describe('waterContentWarnings', () => {
it('stays silent at the warning limit and below', () => {
expect(waterContentWarnings(18, 'Blütenhonig', config, refs)).toEqual([]);
expect(waterContentWarnings(12, null, config, refs)).toEqual([]);
});
it('warns above 18 %', () => {
const [warning, ...rest] = waterContentWarnings(19, null, config, refs);
expect(rest).toEqual([]);
expect(warning).toMatchObject({
code: 'WATER_CONTENT_HIGH',
severity: 'WARNUNG',
refs,
});
});
it('asks for a confirmation above 20 %', () => {
const [warning, ...rest] = waterContentWarnings(20.5, null, config, refs);
expect(rest).toEqual([]);
expect(warning).toMatchObject({
code: 'WATER_CONTENT_ABOVE_LEGAL',
severity: 'BESTAETIGEN',
});
});
it('20.0 % itself only warns', () => {
expect(
waterContentWarnings(20, null, config, refs).map((w) => w.code),
).toEqual(['WATER_CONTENT_HIGH']);
});
it('hints at a missing value', () => {
expect(
waterContentWarnings(null, null, config, refs).map((w) => [
w.code,
w.severity,
]),
).toEqual([['WATER_CONTENT_MISSING', 'HINWEIS']]);
});
it('a configured heather honey confirms only above 23 %', () => {
const heather: WaterContentConfig = {
...config,
byHoneyType: { Heidehonig: { confirmAbovePercent: 23 } },
};
expect(
waterContentWarnings(22, 'heidehonig', heather, refs).map((w) => w.code),
).toEqual(['WATER_CONTENT_HIGH']);
expect(
waterContentWarnings(23.5, 'HEIDEHONIG', heather, refs).map(
(w) => w.code,
),
).toEqual(['WATER_CONTENT_ABOVE_LEGAL']);
// Another type keeps the general limits; a near name is not a match.
expect(
waterContentWarnings(22, 'Heidehonig-Mix', heather, refs).map(
(w) => w.code,
),
).toEqual(['WATER_CONTENT_ABOVE_LEGAL']);
});
it('a type entry with a warning limit only keeps the general confirm limit', () => {
const custom: WaterContentConfig = {
...config,
byHoneyType: { Raps: { warnAbovePercent: 17 } },
};
expect(
waterContentWarnings(17.5, 'Raps', custom, refs).map((w) => w.code),
).toEqual(['WATER_CONTENT_HIGH']);
});
});
describe('water content messages', () => {
it('shows two decimals when one decimal would hide the difference to the limit', () => {
const [warning] = waterContentWarnings(20.04, null, config, refs);
expect(warning.message).toContain('(20,04 %)');
expect(warning.message).toContain('Grenze von 20 %');
});
it('keeps one decimal otherwise', () => {
const [warning] = waterContentWarnings(20.5, null, config, refs);
expect(warning.message).toContain('(20,5 %)');
});
});
@@ -0,0 +1,152 @@
import type { HoneyBatch, HoneyMeasurement } from '../../../generated/prisma';
import type { WaterContentConfig } from '../../automation/rule-config/rule-config.types';
import { readRule } from '../../automation/rule-config/rule-config.reader';
import { formatNumberDe } from '../../suggestions/texts/format-number';
import type { DbClient } from '../../prisma/db-client';
import {
WARNING_SEVERITY,
type PlausibilityWarning,
} from '../warnings/plausibility-warning';
type Ref = { type: string; id: string };
/**
* The water content that counts (spec 7.8): the newest measurement by
* `measuredAt`, else the value on the batch itself.
*/
export function latestWaterContent(
batch: Pick<HoneyBatch, 'waterContent'>,
measurements: readonly Pick<
HoneyMeasurement,
'waterContent' | 'measuredAt'
>[],
): number | null {
let newest: Pick<HoneyMeasurement, 'waterContent' | 'measuredAt'> | null =
null;
for (const measurement of measurements) {
if (newest === null || measurement.measuredAt > newest.measuredAt) {
newest = measurement;
}
}
return newest === null ? batch.waterContent : newest.waterContent;
}
/** The limits for a honey type: its own entry (any case, exact name) first. */
function limitsFor(
honeyType: string | null,
config: WaterContentConfig,
): { warn: number; confirm: number } {
const wanted = honeyType?.trim().toLowerCase();
const own =
wanted === undefined || wanted === ''
? undefined
: Object.entries(config.byHoneyType).find(
([name]) => name.toLowerCase() === wanted,
)?.[1];
return {
warn: own?.warnAbovePercent ?? config.warnAbovePercent,
confirm: own?.confirmAbovePercent ?? config.confirmAbovePercent,
};
}
/**
* A percentage with one decimal; with more when one decimal would round the
* value onto the limit and hide that it is above it (20.04 % is "20,04 %").
*/
export function percentText(value: number, limit?: number): string {
const maxDigits = 3;
let digits = 1;
while (
limit !== undefined &&
value !== limit &&
Number(value.toFixed(digits)) === limit &&
digits < maxDigits
) {
digits += 1;
}
return `${formatNumberDe(value, digits)} %`;
}
/**
* Water content against the limits of the rule HONEY_WATER_CONTENT. Above
* the confirm limit only WATER_CONTENT_ABOVE_LEGAL is reported (the stronger
* finding); a warning never blocks, the confirmation is asked for by
* POST /bottling-batches only.
*/
export function waterContentWarnings(
value: number | null,
honeyType: string | null,
config: WaterContentConfig,
refs: Ref[],
): PlausibilityWarning[] {
if (value === null) {
return [
{
code: 'WATER_CONTENT_MISSING',
severity: WARNING_SEVERITY.WATER_CONTENT_MISSING,
message:
'Für diese Honigcharge ist kein Wassergehalt erfasst. Bitte vor dem Abfüllen messen.',
refs,
},
];
}
const { warn, confirm } = limitsFor(honeyType, config);
if (value > confirm) {
return [
{
code: 'WATER_CONTENT_ABOVE_LEGAL',
severity: WARNING_SEVERITY.WATER_CONTENT_ABOVE_LEGAL,
message: `Der Wassergehalt (${percentText(value, confirm)}) liegt über der gesetzlichen Grenze von ${percentText(confirm)}. Abfüllen nur mit Bestätigung.`,
refs,
},
];
}
if (value > warn) {
return [
{
code: 'WATER_CONTENT_HIGH',
severity: WARNING_SEVERITY.WATER_CONTENT_HIGH,
message: `Der Wassergehalt (${percentText(value, warn)}) liegt über ${percentText(warn)}. Das Warenzeichen „Echter Deutscher Honig“ verlangt höchstens 18 %.`,
refs,
},
];
}
return [];
}
/**
* The warnings for a honey batch as it stands now: its newest water content
* against the rule in force. Read only; null when the batch does not exist.
*/
export async function waterContentWarningsOfBatch(
db: DbClient,
honeyBatchId: string,
): Promise<{
waterContent: number | null;
warnings: PlausibilityWarning[];
} | null> {
const batch = await db.honeyBatch.findUnique({
where: { id: honeyBatchId },
select: { id: true, honeyType: true, waterContent: true },
});
if (!batch) {
return null;
}
const [measurements, rule] = await Promise.all([
db.honeyMeasurement.findMany({
where: { honeyBatchId },
select: { waterContent: true, measuredAt: true },
}),
readRule(db, 'HONEY_WATER_CONTENT'),
]);
const waterContent = latestWaterContent(batch, measurements);
return {
waterContent,
warnings: waterContentWarnings(
waterContent,
batch.honeyType ?? null,
rule.config,
[{ type: 'HoneyBatch', id: batch.id }],
),
};
}
@@ -209,7 +209,14 @@ const contracts: Record<string, NullContract> = {
UpdateProductDto: {
dto: UpdateProductDto,
notNull: ['name', 'status', 'kind', 'shopCategory'],
clearable: ['description', 'sku', 'packagingSize', 'weight', 'salesUnit'],
clearable: [
'description',
'sku',
'packagingSize',
'shelfLifeMonths',
'weight',
'salesUnit',
],
},
// apiaryId: null widens the report to all apiaries; notes: null clears them.
UpdatePhenologyReportDto: {
@@ -22,9 +22,11 @@ describe('HoneyBatchesService', () => {
};
honeyMeasurement: {
create: jest.Mock;
findMany: jest.Mock;
findUnique: jest.Mock;
update: jest.Mock;
};
automationRule: { findUnique: jest.Mock };
extraction: { findUnique: jest.Mock };
storageContainer: { findUnique: jest.Mock };
honeyBatchRelocation: { create: jest.Mock; findMany: jest.Mock };
@@ -85,9 +87,12 @@ describe('HoneyBatchesService', () => {
},
honeyMeasurement: {
create: jest.fn(),
findMany: jest.fn().mockResolvedValue([]),
findUnique: jest.fn(),
update: jest.fn(),
},
// No rule row: the built-in water content limits apply.
automationRule: { findUnique: jest.fn().mockResolvedValue(null) },
extraction: { findUnique: jest.fn() },
storageContainer: { findUnique: jest.fn() },
honeyBatchRelocation: { create: jest.fn(), findMany: jest.fn() },
@@ -949,4 +954,45 @@ describe('HoneyBatchesService', () => {
service.updateMeasurement('missing', { waterContent: 17.5 }, 'user-1'),
).rejects.toBeInstanceOf(NotFoundException);
});
describe('water content warnings on a measurement', () => {
function measured(newest: number) {
prisma.honeyBatch.findUnique.mockResolvedValue({
...honeyBatch,
honeyType: null,
waterContent: null,
});
prisma.honeyMeasurement.create.mockResolvedValue({ id: 'm1' });
prisma.honeyMeasurement.findMany.mockResolvedValue([
{ waterContent: newest, measuredAt: new Date('2026-08-01') },
]);
}
it('addMeasurement above the legal limit answers a warning and never refuses', async () => {
measured(21);
const result = await service.addMeasurement(
'batch-1',
{ waterContent: 21, measuredAt: '2026-08-01T10:00:00.000Z' },
'user-1',
);
expect(result.warnings.map((w) => w.code)).toEqual([
'WATER_CONTENT_ABOVE_LEGAL',
]);
expect(prisma.honeyMeasurement.create).toHaveBeenCalledTimes(1);
});
it('a good measurement answers no warning', async () => {
measured(16.5);
const result = await service.addMeasurement(
'batch-1',
{ waterContent: 16.5, measuredAt: '2026-08-01T10:00:00.000Z' },
'user-1',
);
expect(result.warnings).toEqual([]);
});
});
});
@@ -28,6 +28,7 @@ import { CreateHoneyMeasurementDto } from './dto/create-honey-measurement.dto';
import { UpdateHoneyMeasurementDto } from './dto/update-honey-measurement.dto';
import { RelocateHoneyBatchDto } from './dto/relocate-honey-batch.dto';
import { SetHoneyBatchContainerAllocationDto } from './dto/set-honey-batch-container-allocation.dto';
import { waterContentWarningsOfBatch } from '../common/quality/water-content';
import { honeyBatchInclude } from './honey-batch-include';
import {
batchWarnings,
@@ -403,6 +404,17 @@ export class HoneyBatchesService {
};
}
/**
* The honey batch as the answer to a measurement, with the water content
* findings of its newest value (spec 7.8). Only a report: a measurement is
* a fact and is never refused or held back for a confirmation.
*/
private async withWaterWarnings(honeyBatchId: string) {
const batch = await this.findById(honeyBatchId);
const water = await waterContentWarningsOfBatch(this.prisma, honeyBatchId);
return withWarnings(batch, water?.warnings ?? []);
}
async updateMeasurement(
measurementId: string,
dto: UpdateHoneyMeasurementDto,
@@ -429,7 +441,7 @@ export class HoneyBatchesService {
beforeData: before,
afterData: measurement,
});
return this.findById(before.honeyBatchId);
return this.withWaterWarnings(before.honeyBatchId);
}
async addMeasurement(
@@ -453,7 +465,7 @@ export class HoneyBatchesService {
userId: actingUserId,
afterData: measurement,
});
return this.findById(id);
return this.withWaterWarnings(id);
}
async relocate(id: string, dto: RelocateHoneyBatchDto, actingUserId: string) {
+5 -2
View File
@@ -137,7 +137,7 @@ describe('CleanupJob', () => {
}
});
it('cleanup deletes terminal NotificationDelivery rows after 30 days (FAILED after 90) and TelegramLinkToken rows expired for 30 days', async () => {
it('cleanup deletes terminal NotificationDelivery rows after 30 days (FAILED after 90) and TelegramLinkToken rows used or expired for 24 hours', async () => {
await job.run();
const failed = statementOn('NotificationDelivery', 'FAILED');
@@ -153,7 +153,10 @@ describe('CleanupJob', () => {
expect(delivered?.values).toEqual([WEBHOOK_DELIVERY_RETENTION_DAYS]);
expect(delivered?.sql).toContain('"createdAt" < now()');
const tokens = statementOn('TelegramLinkToken');
expect(tokens.sql).toContain('"expiresAt" < now() - interval \'30 days\'');
expect(tokens.sql).toContain('"expiresAt" < now() - interval \'24 hours\'');
expect(tokens.sql).toContain(
'"consumedAt" < now() - interval \'24 hours\'',
);
expect(tokens.values).toEqual([]);
});
+4 -2
View File
@@ -84,10 +84,12 @@ export class CleanupJob implements Job {
`Removed ${notificationDeliveriesPending} Telegram deliveries that stayed pending for over ${PENDING_DELIVERY_MAX_AGE_DAYS} days`,
);
}
// A link token lives 10 minutes; used or not, it is of no use after that.
// A link token lives 10 minutes and works once: a day after it was used
// or expired it is of no use (and the hash is not worth keeping).
const telegramLinkTokens = await this.prisma.$executeRaw`
DELETE FROM "TelegramLinkToken"
WHERE "expiresAt" < now() - interval '30 days'`;
WHERE "expiresAt" < now() - interval '24 hours'
OR "consumedAt" < now() - interval '24 hours'`;
// After abortStale: no run this old can still be RUNNING.
const jobRunsDeleted = await this.prisma.$executeRaw`
DELETE FROM "JobRun"
@@ -31,6 +31,7 @@ describe('NotificationPreferencesService', () => {
};
let prisma: {
notificationPreference: { upsert: jest.Mock };
telegramLink: { findUnique: jest.Mock };
$transaction: jest.Mock;
};
const order: string[] = [];
@@ -62,6 +63,7 @@ describe('NotificationPreferencesService', () => {
notificationPreference: {
upsert: jest.fn().mockResolvedValue(stored),
},
telegramLink: { findUnique: jest.fn().mockResolvedValue(null) },
$transaction: jest
.fn()
.mockImplementation((work: (t: unknown) => Promise<unknown>) =>
@@ -180,4 +182,75 @@ describe('NotificationPreferencesService', () => {
expect(arg.data).not.toHaveProperty('telegramEnabled');
expect(arg.data.telegramCategories).toEqual(['SYSTEM']);
});
describe('toView (Telegram status)', () => {
const originalUsername = process.env.TELEGRAM_BOT_USERNAME;
const originalToken = process.env.TELEGRAM_BOT_TOKEN;
afterEach(() => {
if (originalUsername === undefined) {
delete process.env.TELEGRAM_BOT_USERNAME;
} else {
process.env.TELEGRAM_BOT_USERNAME = originalUsername;
}
if (originalToken === undefined) {
delete process.env.TELEGRAM_BOT_TOKEN;
} else {
process.env.TELEGRAM_BOT_TOKEN = originalToken;
}
});
it('NotificationSettingsView.telegram.configured is true with the username set and no token in the API process', async () => {
process.env.TELEGRAM_BOT_USERNAME = '@apicore_test_bot';
delete process.env.TELEGRAM_BOT_TOKEN;
const view = await service.toView(stored as never);
expect(view.telegram).toEqual({
configured: true,
botUsername: 'apicore_test_bot',
linked: false,
firstName: null,
linkedAt: null,
enabled: false,
});
expect(JSON.stringify(view)).not.toMatch(/token/i);
});
it('is not configured without a bot username, even with a token', async () => {
process.env.TELEGRAM_BOT_USERNAME = '';
process.env.TELEGRAM_BOT_TOKEN =
'123456789:AAEhBOweik6ad9r_QXMENQjcrGbqCr4K-RM';
const view = await service.toView(stored as never);
expect(view.telegram.configured).toBe(false);
expect(view.telegram.botUsername).toBeNull();
});
it('shows the link without the chat id', async () => {
process.env.TELEGRAM_BOT_USERNAME = 'apicore_test_bot';
prisma.telegramLink.findUnique.mockResolvedValue({
userId: 'u1',
chatId: 4_711_000_001n,
telegramFirstName: 'Anna',
linkedAt: new Date('2026-10-14T08:00:00.000Z'),
});
const view = await service.toView({
...stored,
telegramEnabled: true,
} as never);
expect(view.telegram).toMatchObject({
linked: true,
firstName: 'Anna',
linkedAt: '2026-10-14T08:00:00.000Z',
enabled: true,
});
expect(JSON.stringify(view)).not.toContain('4711000001');
expect(prisma.telegramLink.findUnique).toHaveBeenCalledWith({
where: { userId: 'u1' },
});
});
});
});
@@ -2,10 +2,12 @@ import { BadRequestException, Injectable } from '@nestjs/common';
import {
NotificationCategory,
NotificationPreference,
TelegramLink,
} from '../../generated/prisma';
import { DbClient } from '../prisma/db-client';
import { PrismaService } from '../prisma/prisma.service';
import { lockRowForUpdate } from '../prisma/row-lock';
import { telegramConfig } from '../telegram/telegram-config';
import { UpdateNotificationSettingsDto } from './dto/update-notification-settings.dto';
/** The digest time the owner may choose, Europe/Berlin (inclusive). */
@@ -16,6 +18,19 @@ const DIGEST_TIME_MESSAGE =
const QUIET_PAIR_MESSAGE =
'Bitte Beginn und Ende der Ruhezeit zusammen leeren.';
/**
* Telegram as the API sees it. "configured" means the bot name is known
* (the API pod never holds the bot token); the chat id never leaves the server.
*/
export interface TelegramStatusView {
configured: boolean;
botUsername: string | null;
linked: boolean;
firstName: string | null;
linkedAt: string | null;
enabled: boolean;
}
export interface NotificationSettingsView {
taskDueEnabled: boolean;
digestEnabled: boolean;
@@ -24,10 +39,27 @@ export interface NotificationSettingsView {
quietUntil: string | null;
telegramCategories: NotificationCategory[];
telegramDetail: boolean;
telegram: TelegramStatusView;
}
function toTelegramStatus(
preference: NotificationPreference,
link: Pick<TelegramLink, 'telegramFirstName' | 'linkedAt'> | null,
): TelegramStatusView {
const { botUsername } = telegramConfig();
return {
configured: botUsername !== null,
botUsername,
linked: link !== null,
firstName: link?.telegramFirstName ?? null,
linkedAt: link?.linkedAt.toISOString() ?? null,
enabled: preference.telegramEnabled,
};
}
export function toNotificationSettingsView(
preference: NotificationPreference,
link: Pick<TelegramLink, 'telegramFirstName' | 'linkedAt'> | null,
): NotificationSettingsView {
return {
taskDueEnabled: preference.taskDueEnabled,
@@ -37,6 +69,7 @@ export function toNotificationSettingsView(
quietUntil: preference.quietUntil,
telegramCategories: preference.telegramCategories,
telegramDetail: preference.telegramDetail,
telegram: toTelegramStatus(preference, link),
};
}
@@ -63,6 +96,16 @@ export class NotificationPreferencesService {
});
}
/** The settings as the API returns them, with the Telegram status. */
async toView(
preference: NotificationPreference,
): Promise<NotificationSettingsView> {
const link = await this.prisma.telegramLink.findUnique({
where: { userId: preference.userId },
});
return toNotificationSettingsView(preference, link);
}
async update(
userId: string,
dto: UpdateNotificationSettingsDto,
@@ -7,7 +7,6 @@ import { UpdateNotificationSettingsDto } from './dto/update-notification-setting
import {
NotificationPreferencesService,
NotificationSettingsView,
toNotificationSettingsView,
} from './notification-preferences.service';
/**
@@ -25,7 +24,7 @@ export class NotificationSettingsController {
async get(
@CurrentUser() actor: AuthenticatedUser,
): Promise<NotificationSettingsView> {
return toNotificationSettingsView(
return this.preferences.toView(
await this.preferences.getOrCreate(actor.id),
);
}
@@ -35,7 +34,7 @@ export class NotificationSettingsController {
@Body() dto: UpdateNotificationSettingsDto,
@CurrentUser() actor: AuthenticatedUser,
): Promise<NotificationSettingsView> {
return toNotificationSettingsView(
return this.preferences.toView(
await this.preferences.update(actor.id, dto),
);
}
@@ -1,5 +1,13 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsEnum, IsNumber, IsOptional, IsString } from 'class-validator';
import {
IsEnum,
IsInt,
IsNumber,
IsOptional,
IsString,
Max,
Min,
} from 'class-validator';
import { ProductKind, ShopCategory } from '../../../generated/prisma';
import { IsOptionalNotNull } from '../../common/validation/is-optional-not-null';
@@ -23,6 +31,16 @@ export class CreateProductDto {
@IsNumber()
packagingSize?: number;
@ApiPropertyOptional({
description:
'Haltbarkeit in Monaten: Grundlage für das MHD beim Abfüllen (kein Standardwert)',
})
@IsOptional()
@IsInt()
@Min(1)
@Max(60)
shelfLifeMonths?: number;
@ApiPropertyOptional()
@IsOptional()
@IsNumber()
@@ -0,0 +1,15 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsOptional, IsString, Matches, MaxLength } from 'class-validator';
/** Step-up proof for a new Telegram link token (Spec 9a.5). */
export class TelegramLinkTokenDto {
@ApiProperty({ description: 'Aktuelles Passwort' })
@IsString()
@MaxLength(200)
password!: string;
@ApiPropertyOptional({ description: 'Aktueller TOTP-Code, falls MFA aktiv' })
@IsOptional()
@Matches(/^\d{6}$/, { message: 'mfaCode must be a 6-digit number' })
mfaCode?: string;
}
@@ -1,13 +1,15 @@
import { Module } from '@nestjs/common';
import { MfaModule } from '../auth/mfa/mfa.module';
import { ReauthModule } from '../auth/reauth/reauth.module';
import { TelegramModule } from '../telegram/telegram.module';
import { UsersModule } from '../users/users.module';
import { ProfileController } from './profile.controller';
import { ProfileService } from './profile.service';
import { TelegramController } from './telegram.controller';
@Module({
imports: [MfaModule, ReauthModule, UsersModule],
controllers: [ProfileController],
imports: [MfaModule, ReauthModule, TelegramModule, UsersModule],
controllers: [ProfileController, TelegramController],
providers: [ProfileService],
})
export class ProfileModule {}
@@ -0,0 +1,46 @@
import { Body, Controller, Header, HttpCode, Post } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { Throttle } from '@nestjs/throttler';
import { AnyAuthenticatedUser } from '../auth/decorators/any-authenticated-user.decorator';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import { ReauthService } from '../auth/reauth/reauth.service';
import type { AuthenticatedUser } from '../auth/types/authenticated-user';
import { SENSITIVE_ACTION_THROTTLE } from '../auth/util/throttle';
import { TelegramLinkService } from '../telegram/telegram-link.service';
import { TelegramLinkTokenDto } from './dto/telegram-link-token.dto';
/**
* Connect and disconnect the caller's own Telegram chat. Self-scoped like
* the rest of /profile (no permission applies); @AnyAuthenticatedUser keeps
* API keys out. A new channel to the outside is a sensitive change, hence
* the step-up. The link-token answer holds a secret, so the route is not
* @Idempotent() (no stored replay).
*/
@ApiTags('profile')
@ApiBearerAuth()
@AnyAuthenticatedUser()
@Controller('profile/telegram')
export class TelegramController {
constructor(
private readonly links: TelegramLinkService,
private readonly reauth: ReauthService,
) {}
@Throttle(SENSITIVE_ACTION_THROTTLE)
// The answer holds a secret: no cache, no proxy may keep it.
@Header('Cache-Control', 'no-store')
@Post('link-token')
async createLinkToken(
@Body() proof: TelegramLinkTokenDto,
@CurrentUser() actor: AuthenticatedUser,
): Promise<{ deepLink: string; expiresAt: Date }> {
await this.reauth.verify(actor.id, proof);
return this.links.createLinkToken(actor.id);
}
@Post('unlink')
@HttpCode(204)
async unlink(@CurrentUser() actor: AuthenticatedUser): Promise<void> {
await this.links.unlink(actor.id);
}
}
@@ -0,0 +1,13 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsEnum, IsOptional } from 'class-validator';
import { NotificationDeliveryStatus } from '../../../generated/prisma';
export class NotificationDeliveriesQueryDto {
@ApiPropertyOptional({
enum: NotificationDeliveryStatus,
description: 'Nur Zustellungen mit diesem Status',
})
@IsOptional()
@IsEnum(NotificationDeliveryStatus)
status?: NotificationDeliveryStatus;
}
@@ -0,0 +1,325 @@
import { ConflictException, NotFoundException } from '@nestjs/common';
import { AuditLogService } from '../audit/audit-log.service';
import { PrismaService } from '../prisma/prisma.service';
import { lockRowForUpdate, lockRowsForUpdate } from '../prisma/row-lock';
import {
DELIVERY_RETRY_ALL_LIMIT,
NotificationDeliveriesService,
} from './notification-deliveries.service';
jest.mock('../prisma/row-lock', () => ({
lockRowForUpdate: jest.fn().mockResolvedValue(true),
lockRowsForUpdate: jest.fn().mockResolvedValue(undefined),
}));
type RawCall = [readonly string[], ...unknown[]];
const lockRow = jest.mocked(lockRowForUpdate);
const lockRows = jest.mocked(lockRowsForUpdate);
describe('NotificationDeliveriesService', () => {
let tx: {
$queryRaw: jest.Mock<Promise<unknown>, RawCall>;
$executeRaw: jest.Mock<Promise<number>, RawCall>;
notificationDelivery: { findUnique: jest.Mock; findMany: jest.Mock };
};
let prisma: {
$queryRaw: jest.Mock<Promise<unknown>, RawCall>;
$transaction: jest.Mock;
notificationDelivery: { findMany: jest.Mock };
};
let audit: { record: jest.Mock };
let service: NotificationDeliveriesService;
const originalUsername = process.env.TELEGRAM_BOT_USERNAME;
const originalToken = process.env.TELEGRAM_BOT_TOKEN;
const sqlText = (call: RawCall): string => call[0].join('?');
const pollRow = (overrides: Record<string, unknown> = {}) => ({
leaseOwner: null,
lastPollAgeSeconds: null,
lastError: null,
...overrides,
});
const senderRow = (overrides: Record<string, unknown> = {}) => ({
pending: 0,
oldestPendingAgeSeconds: null,
failed24h: 0,
...overrides,
});
/** overview(): poll state, sender counts, last errors (in this order). */
function mockOverview(
poll: Record<string, unknown> | null,
sender: Record<string, unknown>,
errors: unknown[] = [],
): void {
prisma.$queryRaw
.mockResolvedValueOnce(poll ? [poll] : [])
.mockResolvedValueOnce([sender])
.mockResolvedValueOnce(errors);
}
beforeEach(() => {
jest.clearAllMocks();
lockRow.mockResolvedValue(true);
delete process.env.TELEGRAM_BOT_USERNAME;
delete process.env.TELEGRAM_BOT_TOKEN;
tx = {
$queryRaw: jest.fn<Promise<unknown>, RawCall>().mockResolvedValue([]),
$executeRaw: jest.fn<Promise<number>, RawCall>().mockResolvedValue(1),
notificationDelivery: { findUnique: jest.fn(), findMany: jest.fn() },
};
prisma = {
$queryRaw: jest.fn<Promise<unknown>, RawCall>(),
$transaction: jest.fn((fn: (t: typeof tx) => Promise<unknown>) => fn(tx)),
notificationDelivery: { findMany: jest.fn().mockResolvedValue([]) },
};
audit = { record: jest.fn().mockResolvedValue(undefined) };
service = new NotificationDeliveriesService(
prisma as unknown as PrismaService,
audit as unknown as AuditLogService,
);
});
afterAll(() => {
if (originalUsername === undefined) {
delete process.env.TELEGRAM_BOT_USERNAME;
} else {
process.env.TELEGRAM_BOT_USERNAME = originalUsername;
}
if (originalToken === undefined) {
delete process.env.TELEGRAM_BOT_TOKEN;
} else {
process.env.TELEGRAM_BOT_TOKEN = originalToken;
}
});
it('shows the oldest pending age from the database clock and never a chat id or token', async () => {
mockOverview(
pollRow(),
senderRow({ pending: 3, oldestPendingAgeSeconds: 42.5, failed24h: 1 }),
[
{
lastStatusCode: 502,
lastError: 'HTTP 502',
createdAt: new Date('2026-10-14T08:00:00Z'),
},
],
);
prisma.notificationDelivery.findMany.mockResolvedValue([
{
id: 'd1',
status: 'FAILED',
templateCode: null,
attempts: 8,
availableAt: new Date('2026-10-14T08:00:00Z'),
lastStatusCode: 502,
lastError: 'HTTP 502',
createdAt: new Date('2026-10-14T07:00:00Z'),
deliveredAt: null,
notification: { category: 'TASK_DUE' },
},
]);
const { telegram, deliveries } = await service.overview();
expect(telegram.sender).toEqual({
pending: 3,
oldestPendingAgeSeconds: 42.5,
failed24h: 1,
lastErrors: [
{
statusCode: 502,
error: 'HTTP 502',
createdAt: new Date('2026-10-14T08:00:00Z'),
},
],
});
const senderSql = sqlText(prisma.$queryRaw.mock.calls[1]);
expect(senderSql).toContain(
'EXTRACT(EPOCH FROM now() - MIN("availableAt")',
);
expect(senderSql).toContain('"NotificationDelivery"');
expect(deliveries).toEqual([
expect.objectContaining({
id: 'd1',
category: 'TASK_DUE',
templateCode: null,
attempts: 8,
}),
]);
const raw = JSON.stringify({ telegram, deliveries });
expect(raw).not.toMatch(/chatId|token/i);
expect(deliveries[0]).not.toHaveProperty('notification');
const args = (
prisma.notificationDelivery.findMany.mock.calls as unknown[][]
)[0][0] as { select: Record<string, unknown>; where: unknown };
expect(args.select).not.toHaveProperty('chatId');
expect(args.select).not.toHaveProperty('userId');
});
it('configured follows the bot username, not the token, and receiver.lastPollAgeSeconds is null while the worker never polled', async () => {
process.env.TELEGRAM_BOT_USERNAME = 'apicore_test_bot';
mockOverview(pollRow(), senderRow());
const configured = await service.overview();
expect(configured.telegram).toMatchObject({
botNameSet: true,
botUsername: 'apicore_test_bot',
receiver: {
leaseOwner: null,
lastPollAgeSeconds: null,
lastError: null,
},
});
delete process.env.TELEGRAM_BOT_USERNAME;
process.env.TELEGRAM_BOT_TOKEN = '123456789:' + 'A'.repeat(35);
mockOverview(null, senderRow());
const tokenOnly = await service.overview();
expect(tokenOnly.telegram.botNameSet).toBe(false);
expect(tokenOnly.telegram.botUsername).toBeNull();
expect(tokenOnly.telegram.receiver.lastPollAgeSeconds).toBeNull();
expect(JSON.stringify(tokenOnly)).not.toContain('AAAAAAAAAA');
});
it('reports the receiver lease owner and poll age from the database clock', async () => {
mockOverview(
pollRow({ leaseOwner: 'pod-1', lastPollAgeSeconds: 7.25 }),
senderRow(),
);
const { telegram } = await service.overview();
expect(telegram.receiver.leaseOwner).toBe('pod-1');
expect(telegram.receiver.lastPollAgeSeconds).toBe(7.25);
const pollSql = sqlText(prisma.$queryRaw.mock.calls[0]);
expect(pollSql).toContain('"TelegramPollState"');
expect(pollSql).toContain('EXTRACT(EPOCH FROM now() - "lastPollAt")');
expect(pollSql).toContain('"leaseUntil" > now()');
});
it('filters the list by status and caps it', async () => {
mockOverview(pollRow(), senderRow());
await service.overview('FAILED');
const args = (
prisma.notificationDelivery.findMany.mock.calls as unknown[][]
)[0][0] as { where: unknown; take: number };
expect(args.where).toEqual({ status: 'FAILED' });
expect(args.take).toBe(100);
mockOverview(pollRow(), senderRow());
await service.overview();
const unfiltered = (
prisma.notificationDelivery.findMany.mock.calls as unknown[][]
)[1][0] as { where: unknown };
expect(unfiltered.where).toEqual({});
});
it('retry moves FAILED back to PENDING, writes an audit entry and wakes the worker', async () => {
tx.notificationDelivery.findUnique.mockResolvedValue({
status: 'FAILED',
attempts: 8,
});
await service.retry('d1', 'user-1');
expect(lockRow).toHaveBeenCalledWith(tx, 'NotificationDelivery', 'd1');
const update = sqlText(tx.$executeRaw.mock.calls[0]);
expect(update).toContain('"status" = \'PENDING\'');
expect(update).toContain('"attempts" = 0');
expect(update).toContain('"availableAt" = now()');
expect(update).toContain('"claimedAt" = NULL');
expect(audit.record).toHaveBeenCalledWith(
expect.objectContaining({
entityType: 'NotificationDelivery',
entityId: 'd1',
action: 'UPDATE',
userId: 'user-1',
beforeData: { status: 'FAILED', attempts: 8 },
afterData: { status: 'PENDING', attempts: 0 },
}),
tx,
);
expect(
tx.$executeRaw.mock.calls.some((c) =>
c.slice(1).includes('notification_delivery'),
),
).toBe(true);
});
it('retry of a non-FAILED delivery is 409 and of an unknown one 404', async () => {
tx.notificationDelivery.findUnique.mockResolvedValueOnce({
status: 'DELIVERED',
attempts: 1,
});
await expect(service.retry('d1', 'u')).rejects.toBeInstanceOf(
ConflictException,
);
tx.notificationDelivery.findUnique.mockResolvedValueOnce(null);
await expect(service.retry('nope', 'u')).rejects.toBeInstanceOf(
NotFoundException,
);
expect(audit.record).not.toHaveBeenCalled();
expect(tx.$executeRaw).not.toHaveBeenCalled();
});
it('retryFailed requeues every FAILED delivery under lock and reports the count', async () => {
tx.notificationDelivery.findMany.mockResolvedValue([
{ id: 'a' },
{ id: 'b' },
]);
tx.$queryRaw.mockResolvedValueOnce([
{ id: 'a', attempts: 8 },
{ id: 'b', attempts: 3 },
]);
await expect(service.retryFailed('user-1')).resolves.toEqual({
retried: 2,
});
expect(lockRows).toHaveBeenCalledWith(tx, 'NotificationDelivery', [
'a',
'b',
]);
const update = sqlText(tx.$queryRaw.mock.calls[0]);
expect(update).toContain('"status" = \'FAILED\'');
expect(update).toContain('"availableAt" = now()');
expect(audit.record).toHaveBeenCalledTimes(2);
expect(
tx.$executeRaw.mock.calls.some((c) =>
c.slice(1).includes('notification_delivery'),
),
).toBe(true);
});
it('retryFailed with nothing failed retries nothing and wakes nobody', async () => {
tx.notificationDelivery.findMany.mockResolvedValue([]);
await expect(service.retryFailed('user-1')).resolves.toEqual({
retried: 0,
});
expect(audit.record).not.toHaveBeenCalled();
expect(tx.$executeRaw).not.toHaveBeenCalled();
});
it('retryFailed takes the newest FAILED ones, at most the limit', async () => {
tx.notificationDelivery.findMany.mockResolvedValue([{ id: 'a' }]);
tx.$queryRaw.mockResolvedValueOnce([{ id: 'a', attempts: 8 }]);
await service.retryFailed('user-1');
const args = (
tx.notificationDelivery.findMany.mock.calls as unknown[][]
)[0][0] as { take: number; orderBy: unknown; where: unknown };
expect(args.take).toBe(DELIVERY_RETRY_ALL_LIMIT);
expect(args.where).toEqual({ status: 'FAILED' });
expect(args.orderBy).toEqual([{ createdAt: 'desc' }, { id: 'desc' }]);
});
it('retryFailed reports 0 when the re-check after the lock finds nothing FAILED', async () => {
tx.notificationDelivery.findMany.mockResolvedValue([{ id: 'a' }]);
tx.$queryRaw.mockResolvedValueOnce([]);
await expect(service.retryFailed('user-1')).resolves.toEqual({
retried: 0,
});
expect(lockRows).toHaveBeenCalled();
expect(audit.record).not.toHaveBeenCalled();
expect(tx.$executeRaw).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,254 @@
import {
ConflictException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import {
NotificationCategory,
NotificationDeliveryStatus,
} from '../../generated/prisma';
import { AuditLogService } from '../audit/audit-log.service';
import { notifyWorker, WAKE_CHANNELS } from '../common/worker-wakeup';
import { PrismaService } from '../prisma/prisma.service';
import { lockRowForUpdate, lockRowsForUpdate } from '../prisma/row-lock';
import {
telegramBotAvailable,
telegramConfig,
} from '../telegram/telegram-config';
export interface TelegramStatusView {
/**
* The bot name is set. The API pod never has the token, so it cannot know
* whether sending works: that runs only in the worker, when the secret exists.
*/
botNameSet: boolean;
botUsername: string | null;
/** Whether updates are received shows only the poll state of the worker. */
receiver: {
leaseOwner: string | null;
lastPollAgeSeconds: number | null;
lastError: string | null;
};
sender: {
pending: number;
oldestPendingAgeSeconds: number | null;
failed24h: number;
lastErrors: { statusCode: number | null; error: string; createdAt: Date }[];
};
}
/** A delivery for the System page - never the chat id and never the text. */
export interface NotificationDeliveryView {
id: string;
status: NotificationDeliveryStatus;
category: NotificationCategory | null;
templateCode: string | null;
attempts: number;
availableAt: Date;
lastStatusCode: number | null;
lastError: string | null;
createdAt: Date;
deliveredAt: Date | null;
}
export interface NotificationDeliveriesOverview {
telegram: TelegramStatusView;
deliveries: NotificationDeliveryView[];
}
/** Most deliveries one list or one "retry all" call handles. */
export const DELIVERY_LIST_LIMIT = 100;
export const DELIVERY_RETRY_ALL_LIMIT = 100;
const LAST_ERRORS_LIMIT = 5;
interface PollRow {
leaseOwner: string | null;
lastPollAgeSeconds: number | null;
lastError: string | null;
}
interface SenderRow {
pending: number;
oldestPendingAgeSeconds: number | null;
failed24h: number;
}
interface RetriedRow {
id: string;
attempts: number;
}
/**
* Read model and retry actions of the Telegram card on the System page. All
* ages are computed by the database: the API pod's clock may differ.
*/
@Injectable()
export class NotificationDeliveriesService {
constructor(
private readonly prisma: PrismaService,
private readonly audit: AuditLogService,
) {}
async overview(
status?: NotificationDeliveryStatus,
): Promise<NotificationDeliveriesOverview> {
const [[poll], [sender], errors, rows] = await Promise.all([
// The lease owner counts only while its lease runs; no row = never polled.
this.prisma.$queryRaw<PollRow[]>`
SELECT
CASE WHEN "leaseUntil" > now() THEN "leaseOwner" END AS "leaseOwner",
EXTRACT(EPOCH FROM now() - "lastPollAt")::float8 AS "lastPollAgeSeconds",
"lastError"
FROM "TelegramPollState"
WHERE "id" = 'singleton'`,
// Oldest pending = the longest overdue one; a delivery held back until
// the end of the quiet hours is not late yet.
this.prisma.$queryRaw<SenderRow[]>`
SELECT
count(*) FILTER (WHERE "status" = 'PENDING')::int AS "pending",
EXTRACT(EPOCH FROM now() - MIN("availableAt") FILTER (WHERE "status" = 'PENDING' AND "availableAt" <= now()))::float8 AS "oldestPendingAgeSeconds",
count(*) FILTER (WHERE "status" = 'FAILED' AND "createdAt" > now() - interval '24 hours')::int AS "failed24h"
FROM "NotificationDelivery"`,
this.prisma.$queryRaw<
{ lastStatusCode: number | null; lastError: string; createdAt: Date }[]
>`
SELECT "lastStatusCode", "lastError", "createdAt"
FROM "NotificationDelivery"
WHERE "lastError" IS NOT NULL
ORDER BY "createdAt" DESC, "id" DESC
LIMIT ${LAST_ERRORS_LIMIT}`,
this.prisma.notificationDelivery.findMany({
where: status ? { status } : {},
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
take: DELIVERY_LIST_LIMIT,
// Never chatId, userId or a text: only what the System page shows.
select: {
id: true,
status: true,
templateCode: true,
attempts: true,
availableAt: true,
lastStatusCode: true,
lastError: true,
createdAt: true,
deliveredAt: true,
notification: { select: { category: true } },
},
}),
]);
return {
telegram: {
botNameSet: telegramBotAvailable(),
botUsername: telegramConfig().botUsername,
receiver: {
leaseOwner: poll?.leaseOwner ?? null,
lastPollAgeSeconds: poll?.lastPollAgeSeconds ?? null,
lastError: poll?.lastError ?? null,
},
sender: {
pending: sender?.pending ?? 0,
oldestPendingAgeSeconds: sender?.oldestPendingAgeSeconds ?? null,
failed24h: sender?.failed24h ?? 0,
lastErrors: errors.map((row) => ({
statusCode: row.lastStatusCode,
error: row.lastError,
createdAt: row.createdAt,
})),
},
},
deliveries: rows.map(({ notification, ...delivery }) => ({
...delivery,
category: notification?.category ?? null,
})),
};
}
/**
* Re-queues one FAILED delivery: lock, re-read, then PENDING with
* attempts 0 and availableAt from the database clock; audit in the same
* transaction, then wake the worker. 404 unknown, 409 not FAILED.
*/
async retry(id: string, actingUserId: string): Promise<void> {
await this.prisma.$transaction(async (tx) => {
await lockRowForUpdate(tx, 'NotificationDelivery', id);
const before = await tx.notificationDelivery.findUnique({
where: { id },
select: { status: true, attempts: true },
});
if (!before) {
throw new NotFoundException('Notification delivery not found');
}
if (before.status !== 'FAILED') {
throw new ConflictException('Notification delivery is not FAILED');
}
await tx.$executeRaw`
UPDATE "NotificationDelivery"
SET "status" = 'PENDING', "attempts" = 0, "availableAt" = now(),
"claimedAt" = NULL, "lastStatusCode" = NULL, "lastError" = NULL
WHERE "id" = ${id}`;
await this.audit.record(
{
entityType: 'NotificationDelivery',
entityId: id,
action: 'UPDATE',
userId: actingUserId,
beforeData: { status: 'FAILED', attempts: before.attempts },
afterData: { status: 'PENDING', attempts: 0 },
},
tx,
);
await notifyWorker(tx, WAKE_CHANNELS.notificationDeliveries);
});
}
/**
* Re-queues the newest FAILED deliveries (at most DELIVERY_RETRY_ALL_LIMIT
* per call; call again for more).
*/
async retryFailed(actingUserId: string): Promise<{ retried: number }> {
return this.prisma.$transaction(async (tx) => {
const candidates = await tx.notificationDelivery.findMany({
where: { status: 'FAILED' },
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
take: DELIVERY_RETRY_ALL_LIMIT,
select: { id: true },
});
const ids = candidates.map((row) => row.id);
if (ids.length === 0) {
return { retried: 0 };
}
await lockRowsForUpdate(tx, 'NotificationDelivery', ids);
// The status is checked again after the lock: a row retried or sent
// meanwhile is left alone.
const retried = await tx.$queryRaw<RetriedRow[]>`
WITH old AS (
SELECT "id", "attempts" FROM "NotificationDelivery"
WHERE "id" = ANY(${ids}) AND "status" = 'FAILED'
)
UPDATE "NotificationDelivery" d
SET "status" = 'PENDING', "attempts" = 0, "availableAt" = now(),
"claimedAt" = NULL, "lastStatusCode" = NULL, "lastError" = NULL
FROM old
WHERE d."id" = old."id"
RETURNING d."id" AS "id", old."attempts" AS "attempts"`;
for (const row of retried) {
await this.audit.record(
{
entityType: 'NotificationDelivery',
entityId: row.id,
action: 'UPDATE',
userId: actingUserId,
beforeData: { status: 'FAILED', attempts: row.attempts },
afterData: { status: 'PENDING', attempts: 0 },
},
tx,
);
}
if (retried.length > 0) {
await notifyWorker(tx, WAKE_CHANNELS.notificationDeliveries);
}
return { retried: retried.length };
});
}
}
@@ -11,6 +11,11 @@ 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 { NotificationDeliveriesQueryDto } from './dto/notification-deliveries.query';
import {
NotificationDeliveriesOverview,
NotificationDeliveriesService,
} from './notification-deliveries.service';
import {
JobRunListQueryDto,
SYSTEM_LIST_DEFAULT_LIMIT,
@@ -28,7 +33,10 @@ import {
@ApiBearerAuth()
@Controller('system')
export class SystemController {
constructor(private readonly queue: SystemQueueService) {}
constructor(
private readonly queue: SystemQueueService,
private readonly deliveries: NotificationDeliveriesService,
) {}
@RequirePermission('system:read')
@Get('overview')
@@ -84,4 +92,32 @@ export class SystemController {
): Promise<void> {
return this.queue.retryWebhookDelivery(id, actor.id);
}
@RequirePermission('system:manage')
@Get('notification-deliveries')
notificationDeliveries(
@Query() query: NotificationDeliveriesQueryDto,
): Promise<NotificationDeliveriesOverview> {
return this.deliveries.overview(query.status);
}
// Declared before ':id/retry' so that "retry-failed" is never read as an id.
@RequirePermission('system:manage')
@Post('notification-deliveries/retry-failed')
@HttpCode(HttpStatus.OK)
retryFailedNotificationDeliveries(
@CurrentUser() actor: AuthenticatedUser,
): Promise<{ retried: number }> {
return this.deliveries.retryFailed(actor.id);
}
@RequirePermission('system:manage')
@Post('notification-deliveries/:id/retry')
@HttpCode(HttpStatus.NO_CONTENT)
retryNotificationDelivery(
@Param('id') id: string,
@CurrentUser() actor: AuthenticatedUser,
): Promise<void> {
return this.deliveries.retry(id, actor.id);
}
}
+2 -1
View File
@@ -1,6 +1,7 @@
import { Module } from '@nestjs/common';
import { NotificationsModule } from '../notifications/notifications.module';
import { JobRunService } from './job-run.service';
import { NotificationDeliveriesService } from './notification-deliveries.service';
import { SystemController } from './system.controller';
import { SystemQueueService } from './system-queue.service';
@@ -11,7 +12,7 @@ import { SystemQueueService } from './system-queue.service';
@Module({
imports: [NotificationsModule],
controllers: [SystemController],
providers: [JobRunService, SystemQueueService],
providers: [JobRunService, SystemQueueService, NotificationDeliveriesService],
exports: [JobRunService],
})
export class SystemModule {}
@@ -286,7 +286,7 @@ describe('TelegramClient', () => {
}),
);
const updates = await client.getUpdates(100n);
const { updates, highestUpdateId } = await client.getUpdates(100n);
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe(`https://api.telegram.org/bot${TOKEN}/getUpdates`);
@@ -295,6 +295,8 @@ describe('TelegramClient', () => {
timeout: 25,
allowed_updates: ['message'],
});
// The dropped update 101 is not in the list, but 102 is the highest.
expect(highestUpdateId).toBe(102n);
expect(updates).toEqual([
{
updateId: 100n,
@@ -313,9 +315,29 @@ describe('TelegramClient', () => {
]);
});
it('reports the highest update_id even when every update was dropped', async () => {
fetchMock.mockResolvedValue(
jsonResponse({
ok: true,
result: [
{ update_id: 7, edited_message: {} },
{ update_id: 9, callback_query: {} },
],
}),
);
await expect(client.getUpdates(7n)).resolves.toEqual({
updates: [],
highestUpdateId: 9n,
});
});
it('returns an empty list when nothing arrived', async () => {
fetchMock.mockResolvedValue(jsonResponse({ ok: true, result: [] }));
await expect(client.getUpdates(0n)).resolves.toEqual([]);
await expect(client.getUpdates(0n)).resolves.toEqual({
updates: [],
highestUpdateId: null,
});
});
});
});
@@ -27,6 +27,17 @@ export interface TelegramUpdate {
firstName: string | null;
}
/**
* What one getUpdates call returned: the updates this code understands and
* the highest raw update_id of the answer, also of updates that were dropped
* (no chat, no id of the right type). The receiver advances the offset past
* it, so a dropped update is never fetched again.
*/
export interface TelegramUpdateBatch {
updates: TelegramUpdate[];
highestUpdateId: bigint | null;
}
// eslint-disable-next-line no-control-regex
const CONTROL_CHARACTERS = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g;
// Zero-width characters, bidi marks, overrides and isolates: invisible, and
@@ -104,6 +115,17 @@ function retryAfterOf(parsed: JsonObject): number | null {
);
}
function highestRawUpdateId(raw: unknown[]): bigint | null {
let highest: bigint | null = null;
for (const entry of raw) {
const id = asInteger(asObject(entry)?.update_id);
if (id !== null && (highest === null || id > highest)) {
highest = id;
}
}
return highest;
}
function parseUpdate(raw: unknown): TelegramUpdate | null {
const update = asObject(raw);
const updateId = asInteger(update?.update_id);
@@ -166,7 +188,7 @@ export class TelegramClient {
async getUpdates(
offset: bigint,
signal?: AbortSignal,
): Promise<TelegramUpdate[]> {
): Promise<TelegramUpdateBatch> {
const result = await this.call(
'getUpdates',
{
@@ -180,9 +202,12 @@ export class TelegramClient {
if (!Array.isArray(result)) {
throw new TelegramApiError('getUpdates', null, INVALID_RESPONSE, null);
}
return result
.map(parseUpdate)
.filter((update): update is TelegramUpdate => update !== null);
return {
updates: result
.map(parseUpdate)
.filter((update): update is TelegramUpdate => update !== null),
highestUpdateId: highestRawUpdateId(result),
};
}
private jsonNumber(method: string, value: bigint): number {
@@ -0,0 +1,435 @@
import { createHash } from 'node:crypto';
import { ConflictException } from '@nestjs/common';
import type { NotificationPreferencesService } from '../notifications/notification-preferences.service';
import type { NotificationsService } from '../notifications/notifications.service';
import type { PrismaService } from '../prisma/prisma.service';
import * as rowLock from '../prisma/row-lock';
import {
LINK_TOKEN_BYTES,
LINK_TOKEN_TTL_MS,
TelegramLinkService,
} from './telegram-link.service';
jest.mock('../prisma/row-lock');
const lockRowsForUpdate = jest.mocked(rowLock.lockRowsForUpdate);
const CHAT = 4_711_000_001n;
const TOKEN = 'A'.repeat(43);
const TOKEN_HASH = createHash('sha256').update(TOKEN).digest('hex');
interface FakeTx {
$queryRaw: jest.Mock;
$executeRaw: jest.Mock;
telegramLinkToken: { create: jest.Mock; findUnique: jest.Mock };
telegramLink: {
findUnique: jest.Mock;
delete: jest.Mock;
deleteMany: jest.Mock;
create: jest.Mock;
};
notificationPreference: { updateMany: jest.Mock };
notificationDelivery: { create: jest.Mock; updateMany: jest.Mock };
user: { findFirst: jest.Mock };
}
/** Flattens a tagged-template call to its SQL text and bound values. */
function sqlOf(call: unknown[]): { text: string; values: unknown[] } {
const [first, ...values] = call as [unknown, ...unknown[]];
if (Array.isArray(first)) {
return { text: (first as string[]).join('?'), values };
}
const sql = first as { strings: string[]; values: unknown[] };
return { text: sql.strings.join('?'), values: sql.values };
}
/** The arguments of one call of a mock (negative: counted from the end). */
function callOf(mock: jest.Mock, index: number): unknown[] {
const calls = mock.mock.calls as unknown[][];
return calls.at(index) ?? [];
}
describe('TelegramLinkService', () => {
let tx: FakeTx;
let prisma: { $transaction: jest.Mock };
let preferences: { getOrCreate: jest.Mock };
let notifications: { record: jest.Mock };
let service: TelegramLinkService;
const originalUsername = process.env.TELEGRAM_BOT_USERNAME;
const originalToken = process.env.TELEGRAM_BOT_TOKEN;
beforeEach(() => {
jest.resetAllMocks();
process.env.TELEGRAM_BOT_USERNAME = 'apicore_test_bot';
delete process.env.TELEGRAM_BOT_TOKEN;
tx = {
$queryRaw: jest.fn().mockResolvedValue([]),
$executeRaw: jest.fn().mockResolvedValue(1),
telegramLinkToken: {
create: jest.fn().mockResolvedValue({ id: 'tok-1' }),
findUnique: jest.fn().mockResolvedValue(null),
},
telegramLink: {
findUnique: jest.fn().mockResolvedValue(null),
delete: jest.fn().mockResolvedValue({}),
deleteMany: jest.fn().mockResolvedValue({ count: 1 }),
create: jest.fn().mockResolvedValue({}),
},
notificationPreference: {
updateMany: jest.fn().mockResolvedValue({ count: 1 }),
},
notificationDelivery: {
create: jest.fn().mockResolvedValue({}),
updateMany: jest.fn().mockResolvedValue({ count: 0 }),
},
user: { findFirst: jest.fn().mockResolvedValue({ id: 'u1' }) },
};
prisma = {
$transaction: jest
.fn()
.mockImplementation((work: (t: unknown) => unknown) =>
Promise.resolve(work(tx)),
),
};
preferences = { getOrCreate: jest.fn().mockResolvedValue({}) };
notifications = { record: jest.fn().mockResolvedValue({}) };
service = new TelegramLinkService(
prisma as unknown as PrismaService,
preferences as unknown as NotificationPreferencesService,
notifications as unknown as NotificationsService,
);
});
afterAll(() => {
if (originalUsername === undefined) {
delete process.env.TELEGRAM_BOT_USERNAME;
} else {
process.env.TELEGRAM_BOT_USERNAME = originalUsername;
}
if (originalToken !== undefined) {
process.env.TELEGRAM_BOT_TOKEN = originalToken;
}
});
describe('createLinkToken', () => {
beforeEach(() => {
tx.$queryRaw.mockResolvedValue([
{ expiresAt: new Date('2026-10-14T10:10:00.000Z') },
]);
});
it('creates a 43-character base64url token, stores only its SHA-256 and invalidates older open tokens', async () => {
const result = await service.createLinkToken('u1');
const prefix = 'https://t.me/apicore_test_bot?start=';
expect(result.deepLink.startsWith(prefix)).toBe(true);
const token = result.deepLink.slice(prefix.length);
expect(LINK_TOKEN_BYTES).toBe(32);
expect(token).toMatch(/^[A-Za-z0-9_-]{43}$/);
expect(result.expiresAt).toEqual(new Date('2026-10-14T10:10:00.000Z'));
const stored = callOf(tx.telegramLinkToken.create, 0)[0] as {
data: { userId: string; tokenHash: string };
};
expect(stored.data.tokenHash).toBe(
createHash('sha256').update(token).digest('hex'),
);
expect(JSON.stringify(stored)).not.toContain(token);
// Older open tokens end in the same transaction, before the new one.
const invalidate = sqlOf(callOf(tx.$executeRaw, 0));
expect(invalidate.text).toMatch(/"consumedAt" = now\(\)/);
expect(invalidate.text).toMatch(/"consumedAt" IS NULL/);
expect(invalidate.values).toEqual(['u1']);
expect(tx.$executeRaw.mock.invocationCallOrder[0]).toBeLessThan(
tx.telegramLinkToken.create.mock.invocationCallOrder[0],
);
});
it('sets the expiry with the database clock, ten minutes ahead', async () => {
await service.createLinkToken('u1');
expect(LINK_TOKEN_TTL_MS).toBe(600_000);
const expiry = sqlOf(callOf(tx.$queryRaw, 0));
expect(expiry.text).toMatch(/now\(\) \+ make_interval/);
expect(expiry.values.some((value) => value instanceof Date)).toBe(false);
});
it('locks the preference row of the user first', async () => {
await service.createLinkToken('u1');
expect(preferences.getOrCreate).toHaveBeenCalledWith('u1', tx);
expect(lockRowsForUpdate).toHaveBeenCalledWith(
tx,
'NotificationPreference',
['u1'],
);
expect(lockRowsForUpdate.mock.invocationCallOrder[0]).toBeLessThan(
tx.$executeRaw.mock.invocationCallOrder[0],
);
});
it('createLinkToken answers 409 only when the bot username is empty, not when the token is unset', async () => {
// Token unset (the API pod never has it) but username set: works.
await expect(service.createLinkToken('u1')).resolves.toBeDefined();
process.env.TELEGRAM_BOT_USERNAME = '';
await expect(service.createLinkToken('u1')).rejects.toThrow(
new ConflictException('Telegram ist nicht eingerichtet.'),
);
// Even with a valid token: no username, no link.
process.env.TELEGRAM_BOT_TOKEN =
'123456789:AAEhBOweik6ad9r_QXMENQjcrGbqCr4K-RM';
await expect(service.createLinkToken('u1')).rejects.toBeInstanceOf(
ConflictException,
);
});
});
describe('linkFromStartIn', () => {
/** A valid, unused token of user u1. */
function validToken(userId = 'u1'): void {
tx.telegramLinkToken.findUnique.mockResolvedValue({ userId });
tx.$queryRaw.mockResolvedValue([{ userId }]);
}
it('an expired or used token answers LINK_INVALID without naming an account', async () => {
tx.telegramLinkToken.findUnique.mockResolvedValue({ userId: 'u1' });
tx.$queryRaw.mockResolvedValue([]); // CAS found nothing: used or expired
const result = await service.linkFromStartIn(
tx as never,
TOKEN,
CHAT,
'Anna',
);
expect(result).toBe('LINK_INVALID');
expect(tx.telegramLink.create).not.toHaveBeenCalled();
expect(notifications.record).not.toHaveBeenCalled();
expect(tx.notificationPreference.updateMany).not.toHaveBeenCalled();
const cas = sqlOf(callOf(tx.$queryRaw, 0));
expect(cas.text).toMatch(/"consumedAt" IS NULL/);
expect(cas.text).toMatch(/"expiresAt" > now\(\)/);
expect(cas.text).toMatch(/RETURNING "userId"/);
expect(cas.values).toEqual([TOKEN_HASH]);
});
it('an unknown or malformed token answers LINK_INVALID without a lookup of its format', async () => {
await expect(
service.linkFromStartIn(tx as never, 'short', CHAT, null),
).resolves.toBe('LINK_INVALID');
tx.telegramLinkToken.findUnique.mockResolvedValue(null);
await expect(
service.linkFromStartIn(tx as never, TOKEN, CHAT, null),
).resolves.toBe('LINK_INVALID');
expect(tx.telegramLink.create).not.toHaveBeenCalled();
});
it('a new link shows an in-app notice with the Telegram first name', async () => {
validToken();
const result = await service.linkFromStartIn(
tx as never,
TOKEN,
CHAT,
' Anna\u0007 \u202e Beck ',
);
expect(result).toBe('LINKED');
expect(tx.telegramLink.create).toHaveBeenCalledWith({
data: { userId: 'u1', chatId: CHAT, telegramFirstName: 'Anna Beck' },
});
expect(tx.notificationPreference.updateMany).toHaveBeenCalledWith({
where: { userId: 'u1' },
data: { telegramEnabled: true },
});
const [notice, noticeTx] = notifications.record.mock.calls[0] as [
{ userId: string; category: string; message: string; link: string },
unknown,
];
expect(noticeTx).toBe(tx);
expect(notice.userId).toBe('u1');
expect(notice.category).toBe('SYSTEM');
expect(notice.link).toBe('/profile');
expect(notice.message).toMatch(
/^Telegram verbunden mit „Anna Beck“ am \d{2}\.\d{2}\.\d{4}\. Warst du das nicht\? In den Einstellungen trennen\.$/,
);
});
it('cuts a long first name to 64 characters', async () => {
validToken();
await service.linkFromStartIn(tx as never, TOKEN, CHAT, 'x'.repeat(200));
const data = (
callOf(tx.telegramLink.create, 0)[0] as {
data: { telegramFirstName: string };
}
).data;
expect(data.telegramFirstName).toHaveLength(64);
});
it('a chat that moves to another user unlinks the previous user with an in-app notice', async () => {
validToken('u2');
tx.telegramLink.findUnique.mockResolvedValue({
userId: 'u1',
chatId: CHAT,
});
const result = await service.linkFromStartIn(
tx as never,
TOKEN,
CHAT,
'Ben',
);
expect(result).toBe('LINKED');
// Both users are locked in one statement, after their rows exist.
expect(preferences.getOrCreate).toHaveBeenCalledWith('u1', tx);
expect(preferences.getOrCreate).toHaveBeenCalledWith('u2', tx);
expect(lockRowsForUpdate).toHaveBeenCalledTimes(1);
expect(lockRowsForUpdate).toHaveBeenCalledWith(
tx,
'NotificationPreference',
expect.arrayContaining(['u1', 'u2']),
);
expect(tx.telegramLink.delete).toHaveBeenCalledWith({
where: { userId: 'u1' },
});
expect(tx.notificationPreference.updateMany).toHaveBeenCalledWith({
where: { userId: 'u1' },
data: { telegramEnabled: false },
});
const notices = notifications.record.mock.calls.map(
([input]) => input as { userId: string; message: string },
);
expect(notices.find((notice) => notice.userId === 'u1')?.message).toBe(
'Deine Telegram-Verbindung wurde getrennt, weil der Chat mit einem anderen Konto verbunden wurde.',
);
expect(notices.find((notice) => notice.userId === 'u2')?.message).toMatch(
/^Telegram verbunden mit „Ben“/,
);
// The old link goes before the new one: the chat id is unique.
expect(tx.telegramLink.delete.mock.invocationCallOrder[0]).toBeLessThan(
tx.telegramLink.create.mock.invocationCallOrder[0],
);
});
it('reads the link of the chat before and after taking the locks and refuses a chat that changed owner', async () => {
validToken('u2');
tx.telegramLink.findUnique
.mockResolvedValueOnce(null) // peek: free
.mockResolvedValueOnce({ userId: 'u9', chatId: CHAT }); // after lock: taken
await expect(
service.linkFromStartIn(tx as never, TOKEN, CHAT, 'Ben'),
).rejects.toThrow('changed owner');
expect(tx.telegramLink.create).not.toHaveBeenCalled();
});
it('an inactive user answers LINK_INVALID', async () => {
validToken();
tx.user.findFirst.mockResolvedValue(null);
await expect(
service.linkFromStartIn(tx as never, TOKEN, CHAT, 'Anna'),
).resolves.toBe('LINK_INVALID');
expect(tx.telegramLink.create).not.toHaveBeenCalled();
});
it('locks first, reads the link afterwards', async () => {
validToken();
await service.linkFromStartIn(tx as never, TOKEN, CHAT, 'Anna');
const lockOrder = lockRowsForUpdate.mock.invocationCallOrder[0];
const casOrder = tx.$queryRaw.mock.invocationCallOrder[0];
expect(lockOrder).toBeLessThan(casOrder);
});
});
describe('stopIn / unlink', () => {
it('stopIn deletes the link of the chat and switches Telegram off under the preference lock', async () => {
tx.telegramLink.findUnique.mockResolvedValue({
userId: 'u1',
chatId: CHAT,
});
await service.stopIn(tx as never, CHAT);
expect(lockRowsForUpdate).toHaveBeenCalledWith(
tx,
'NotificationPreference',
['u1'],
);
expect(tx.telegramLink.delete).toHaveBeenCalledWith({
where: { userId: 'u1' },
});
expect(tx.notificationPreference.updateMany).toHaveBeenCalledWith({
where: { userId: 'u1' },
data: { telegramEnabled: false },
});
});
it('stopIn for an unknown chat changes nothing', async () => {
await service.stopIn(tx as never, CHAT);
expect(tx.telegramLink.delete).not.toHaveBeenCalled();
expect(tx.notificationPreference.updateMany).not.toHaveBeenCalled();
expect(lockRowsForUpdate).not.toHaveBeenCalled();
});
it('unlink deletes the link, switches Telegram off and queues STOPPED for the chat', async () => {
tx.telegramLink.findUnique.mockResolvedValue({
userId: 'u1',
chatId: CHAT,
});
await service.unlink('u1');
expect(preferences.getOrCreate).toHaveBeenCalledWith('u1', tx);
expect(lockRowsForUpdate).toHaveBeenCalledWith(
tx,
'NotificationPreference',
['u1'],
);
expect(tx.telegramLink.delete).toHaveBeenCalledWith({
where: { userId: 'u1' },
});
expect(tx.notificationPreference.updateMany).toHaveBeenCalledWith({
where: { userId: 'u1' },
data: { telegramEnabled: false },
});
expect(tx.notificationDelivery.create).toHaveBeenCalledWith({
data: { channel: 'TELEGRAM', chatId: CHAT, templateCode: 'STOPPED' },
});
});
it('every disconnect marks the pending Telegram deliveries of the user SKIPPED', async () => {
tx.telegramLink.findUnique.mockResolvedValue({
userId: 'u1',
chatId: CHAT,
});
await service.unlink('u1');
await service.stopIn(tx as never, CHAT);
expect(tx.notificationDelivery.updateMany).toHaveBeenCalledTimes(2);
expect(tx.notificationDelivery.updateMany).toHaveBeenCalledWith({
where: {
userId: 'u1',
channel: 'TELEGRAM',
status: { in: ['PENDING', 'PROCESSING'] },
},
data: { status: 'SKIPPED', lastError: 'unlinked' },
});
});
it('unlink without a link is a no-op', async () => {
await service.unlink('u1');
expect(tx.telegramLink.delete).not.toHaveBeenCalled();
expect(tx.notificationDelivery.create).not.toHaveBeenCalled();
});
});
});
@@ -0,0 +1,277 @@
import { createHash, randomBytes } from 'node:crypto';
import { ConflictException, Injectable } from '@nestjs/common';
import { Prisma } from '../../generated/prisma';
import { berlinToday } from '../common/dates';
import { notifyWorker, WAKE_CHANNELS } from '../common/worker-wakeup';
import { assertTransactionClient } from '../prisma/db-client';
import { PrismaService } from '../prisma/prisma.service';
import { lockRowsForUpdate } from '../prisma/row-lock';
import { NotificationPreferencesService } from '../notifications/notification-preferences.service';
import { NotificationsService } from '../notifications/notifications.service';
import { telegramConfig } from './telegram-config';
import type { TelegramTemplateCode } from './telegram-texts';
export const LINK_TOKEN_TTL_MS = 600_000;
export const LINK_TOKEN_BYTES = 32;
/** 32 random bytes as base64url. */
const LINK_TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
const MAX_FIRST_NAME_CHARS = 64;
const NOT_CONFIGURED_MESSAGE = 'Telegram ist nicht eingerichtet.';
const UNLINKED_NOTICE =
'Deine Telegram-Verbindung wurde getrennt, weil der Chat mit einem anderen Konto verbunden wurde.';
const PROFILE_LINK = '/profile';
const UNKNOWN_FIRST_NAME = 'Telegram';
export type LinkResult = 'LINKED' | 'LINK_INVALID';
// eslint-disable-next-line no-control-regex
const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/g;
const INVISIBLE_CHARACTERS = /[\u200b-\u200f\u202a-\u202e\u2066-\u2069]/g;
function hashToken(token: string): string {
return createHash('sha256').update(token).digest('hex');
}
/**
* The first name Telegram reports: trimmed, no control or invisible
* characters, whitespace collapsed, at most 64 characters (by code point).
* It ends up in a notice of the app, so nothing else may ride along.
*/
function sanitizeFirstName(name: string | null): string | null {
if (name === null) {
return null;
}
const clean = name
.replace(CONTROL_CHARACTERS, ' ')
.replace(INVISIBLE_CHARACTERS, ' ')
.replace(/\s+/g, ' ')
.trim();
const characters = [...clean].slice(0, MAX_FIRST_NAME_CHARS).join('').trim();
return characters === '' ? null : characters;
}
/** 2026-10-14 -> 14.10.2026 */
function germanDate(day: string): string {
const [year, month, date] = day.split('-');
return `${date}.${month}.${year}`;
}
function uniqueIds(ids: readonly (string | undefined)[]): string[] {
return [...new Set(ids.filter((id): id is string => id !== undefined))];
}
/**
* Connects and disconnects a user's private Telegram chat (Spec 9a.5).
* The one-time link token lives 10 minutes and is stored only as SHA-256.
* Every change of a connection takes the preference row of each user it
* touches first (the sender's 403 path does the same), in one statement in
* ascending key order, and reads link and preference only afterwards.
* Never logs a token, a link code or a chat id.
*/
@Injectable()
export class TelegramLinkService {
constructor(
private readonly prisma: PrismaService,
private readonly preferences: NotificationPreferencesService,
private readonly notifications: NotificationsService,
) {}
/**
* A fresh link token for the user; older open tokens end. 409 exactly
* when no bot username is configured: the API pod never has the token,
* so it cannot be what "set up" means here.
*/
async createLinkToken(
userId: string,
): Promise<{ deepLink: string; expiresAt: Date }> {
const { botUsername } = telegramConfig();
if (botUsername === null) {
throw new ConflictException(NOT_CONFIGURED_MESSAGE);
}
const token = randomBytes(LINK_TOKEN_BYTES).toString('base64url');
const expiresAt = await this.prisma.$transaction(async (tx) => {
await this.lockPreferences(tx, [userId]);
await tx.$executeRaw`UPDATE "TelegramLinkToken" SET "consumedAt" = now() WHERE "userId" = ${userId} AND "consumedAt" IS NULL`;
const { id } = await tx.telegramLinkToken.create({
data: { userId, tokenHash: hashToken(token), expiresAt: new Date() },
select: { id: true },
});
// The expiry comes from the database clock, like every comparison.
const [row] = await tx.$queryRaw<{ expiresAt: Date }[]>`
UPDATE "TelegramLinkToken"
SET "expiresAt" = now() + make_interval(secs => ${LINK_TOKEN_TTL_MS / 1000}::double precision)
WHERE "id" = ${id}
RETURNING "expiresAt"`;
return row.expiresAt;
});
return {
deepLink: `https://t.me/${botUsername}?start=${token}`,
expiresAt,
};
}
/** Disconnects in the app: the link goes, Telegram is off, the chat hears STOPPED. */
async unlink(userId: string): Promise<void> {
await this.prisma.$transaction(async (tx) => {
await this.lockPreferences(tx, [userId]);
const link = await tx.telegramLink.findUnique({ where: { userId } });
if (!link) {
return;
}
await this.removeLinkIn(tx, link.userId);
await this.queueReplyIn(tx, link.chatId, 'STOPPED');
});
}
/**
* /start <token> from a private chat (receiver transaction). Consumes the
* token by compare-and-set, replaces the link of the user, takes the chat
* from a previous user if needed and tells the app. Anything unusable
* answers LINK_INVALID, never naming an account.
*/
async linkFromStartIn(
tx: Prisma.TransactionClient,
token: string,
chatId: bigint,
firstName: string | null,
): Promise<LinkResult> {
assertTransactionClient(tx, 'TelegramLinkService.linkFromStartIn');
if (!LINK_TOKEN_PATTERN.test(token)) {
return 'LINK_INVALID';
}
const tokenHash = hashToken(token);
const candidate = await tx.telegramLinkToken.findUnique({
where: { tokenHash },
select: { userId: true },
});
if (!candidate) {
return 'LINK_INVALID';
}
const peeked = await tx.telegramLink.findUnique({
where: { chatId },
select: { userId: true },
});
const userId = candidate.userId;
await this.lockPreferences(tx, uniqueIds([userId, peeked?.userId]));
// Everything below reads after the locks.
const [consumed] = await tx.$queryRaw<{ userId: string }[]>`
UPDATE "TelegramLinkToken" SET "consumedAt" = now()
WHERE "tokenHash" = ${tokenHash} AND "consumedAt" IS NULL AND "expiresAt" > now()
RETURNING "userId"`;
if (!consumed) {
return 'LINK_INVALID';
}
const owner = await tx.telegramLink.findUnique({ where: { chatId } });
if (owner && owner.userId !== userId && owner.userId !== peeked?.userId) {
// Not locked: the transaction fails and the update is handled again.
throw new Error('Telegram chat changed owner while linking');
}
const active = await tx.user.findFirst({
where: { id: userId, isActive: true, role: { status: 'ACTIVE' } },
select: { id: true },
});
if (!active) {
return 'LINK_INVALID';
}
if (owner && owner.userId !== userId) {
await this.removeLinkIn(tx, owner.userId);
await this.notifications.record(
{
userId: owner.userId,
priority: 'HINWEIS',
category: 'SYSTEM',
message: UNLINKED_NOTICE,
link: PROFILE_LINK,
},
tx,
);
}
const name = sanitizeFirstName(firstName);
// The user's own earlier chat is replaced; linkedAt starts again.
await tx.telegramLink.deleteMany({ where: { userId } });
await tx.telegramLink.create({
data: { userId, chatId, telegramFirstName: name },
});
await tx.notificationPreference.updateMany({
where: { userId },
data: { telegramEnabled: true },
});
// The notice that exposes a link someone else used (Spec 9a.5).
await this.notifications.record(
{
userId,
priority: 'HINWEIS',
category: 'SYSTEM',
message: `Telegram verbunden mit „${name ?? UNKNOWN_FIRST_NAME}“ am ${germanDate(berlinToday())}. Warst du das nicht? In den Einstellungen trennen.`,
link: PROFILE_LINK,
},
tx,
);
return 'LINKED';
}
/** /stop from a chat (receiver transaction): link gone, Telegram off. */
async stopIn(tx: Prisma.TransactionClient, chatId: bigint): Promise<void> {
assertTransactionClient(tx, 'TelegramLinkService.stopIn');
const peeked = await tx.telegramLink.findUnique({
where: { chatId },
select: { userId: true },
});
if (!peeked) {
return;
}
await this.lockPreferences(tx, [peeked.userId]);
const link = await tx.telegramLink.findUnique({
where: { chatId },
select: { userId: true },
});
if (link) {
await this.removeLinkIn(tx, link.userId);
}
}
/** Queues a bot reply to a chat (it ignores quiet hours) and wakes the sender. */
async queueReplyIn(
tx: Prisma.TransactionClient,
chatId: bigint,
code: TelegramTemplateCode,
): Promise<void> {
assertTransactionClient(tx, 'TelegramLinkService.queueReplyIn');
await tx.notificationDelivery.create({
data: { channel: 'TELEGRAM', chatId, templateCode: code },
});
await notifyWorker(tx, WAKE_CHANNELS.notificationDeliveries);
}
private async removeLinkIn(
tx: Prisma.TransactionClient,
userId: string,
): Promise<void> {
await tx.telegramLink.delete({ where: { userId } });
await tx.notificationPreference.updateMany({
where: { userId },
data: { telegramEnabled: false },
});
// Whatever was queued for the old chat must never reach a chat linked later.
await tx.notificationDelivery.updateMany({
where: {
userId,
channel: 'TELEGRAM',
status: { in: ['PENDING', 'PROCESSING'] },
},
data: { status: 'SKIPPED', lastError: 'unlinked' },
});
}
/** Rows must exist, then one statement locks them all in key order. */
private async lockPreferences(
tx: Prisma.TransactionClient,
userIds: readonly string[],
): Promise<void> {
for (const userId of userIds) {
await this.preferences.getOrCreate(userId, tx);
}
await lockRowsForUpdate(tx, 'NotificationPreference', userIds);
}
}
@@ -0,0 +1,557 @@
import { Logger } from '@nestjs/common';
import type { PrismaService } from '../prisma/prisma.service';
import { TelegramApiError } from './telegram-api-error';
import type {
TelegramClient,
TelegramUpdate,
TelegramUpdateBatch,
} from './telegram-client';
import type { TelegramLinkService } from './telegram-link.service';
import {
HELP_REPLIES_PER_CHAT,
MAX_UPDATE_ATTEMPTS,
MAX_UPDATE_RETRY_MS,
SKIPPED_UPDATE_TEXT,
HELP_WINDOW_MS,
LEASE_SECONDS,
NO_LEASE_WAIT_MS,
TelegramUpdatesService,
} from './telegram-updates.service';
const TOKEN = 'B'.repeat(43);
const PRIVATE_CHAT = 5_000_000_001n;
const GROUP_CHAT = -1_000_000_000_001n;
function update(
updateId: number,
text: string | null,
options: { chatId?: bigint; chatType?: string; firstName?: string } = {},
): TelegramUpdate {
return {
updateId: BigInt(updateId),
chatId: options.chatId ?? PRIVATE_CHAT,
chatType: options.chatType ?? 'private',
text,
firstName: options.firstName ?? 'Anna',
};
}
/** Flattens a tagged-template call to its SQL text and bound values. */
function sqlOf(call: unknown[]): { text: string; values: unknown[] } {
const [first, ...values] = call as [unknown, ...unknown[]];
if (Array.isArray(first)) {
return { text: (first as string[]).join('?'), values };
}
const sql = first as { strings: string[]; values: unknown[] };
return { text: sql.strings.join('?'), values: sql.values };
}
/** The arguments of one call of a mock (negative: counted from the end). */
function callOf(mock: jest.Mock, index: number): unknown[] {
const calls = mock.mock.calls as unknown[][];
return calls.at(index) ?? [];
}
describe('TelegramUpdatesService', () => {
let prisma: {
$queryRaw: jest.Mock;
$executeRaw: jest.Mock;
$transaction: jest.Mock;
};
let tx: { $executeRaw: jest.Mock };
let client: { isConfigured: jest.Mock; getUpdates: jest.Mock };
let links: {
linkFromStartIn: jest.Mock;
stopIn: jest.Mock;
queueReplyIn: jest.Mock;
};
let service: TelegramUpdatesService;
let signal: AbortSignal;
/** The lease is free and the stored offset is `offset`. */
function leaseGranted(offset: bigint | null = 7n): void {
prisma.$queryRaw.mockResolvedValue(
offset === null ? [] : [{ updateOffset: offset }],
);
}
/** What the next getUpdates calls return; the highest id counts too. */
function giveUpdates(updates: TelegramUpdate[], highest?: number): void {
const ids = updates.map((entry) => entry.updateId);
const batch: TelegramUpdateBatch = {
updates,
highestUpdateId:
highest !== undefined
? BigInt(highest)
: ids.length > 0
? ids.reduce((a, b) => (a > b ? a : b))
: null,
};
client.getUpdates.mockResolvedValue(batch);
}
const replies = (): string[] =>
(links.queueReplyIn.mock.calls as unknown[][]).map(
(call) => call[2] as string,
);
beforeEach(() => {
jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
signal = new AbortController().signal;
tx = { $executeRaw: jest.fn().mockResolvedValue(1) };
prisma = {
$queryRaw: jest.fn().mockResolvedValue([]),
$executeRaw: jest.fn().mockResolvedValue(1),
$transaction: jest
.fn()
.mockImplementation((work: (t: unknown) => unknown) =>
Promise.resolve(work(tx)),
),
};
client = {
isConfigured: jest.fn().mockReturnValue(true),
getUpdates: jest
.fn()
.mockResolvedValue({ updates: [], highestUpdateId: null }),
};
links = {
linkFromStartIn: jest.fn().mockResolvedValue('LINKED'),
stopIn: jest.fn().mockResolvedValue(undefined),
queueReplyIn: jest.fn().mockResolvedValue(undefined),
};
service = new TelegramUpdatesService(
prisma as unknown as PrismaService,
client as unknown as TelegramClient,
links as unknown as TelegramLinkService,
);
leaseGranted();
});
afterEach(() => {
jest.restoreAllMocks();
});
it('exposes the documented constants', () => {
expect(LEASE_SECONDS).toBe(60);
expect(NO_LEASE_WAIT_MS).toBe(30_000);
expect(HELP_REPLIES_PER_CHAT).toBe(3);
expect(HELP_WINDOW_MS).toBe(600_000);
});
it('does nothing without a configured bot', async () => {
client.isConfigured.mockReturnValue(false);
await expect(service.pollOnce(signal)).resolves.toBe('disabled');
expect(prisma.$queryRaw).not.toHaveBeenCalled();
expect(client.getUpdates).not.toHaveBeenCalled();
});
it('takes the lease with the database clock only', async () => {
await service.pollOnce(signal);
const lease = sqlOf(callOf(prisma.$queryRaw, 0));
expect(lease.text).toMatch(/"leaseUntil" = now\(\) \+ make_interval/);
expect(lease.text).toMatch(/"id" = 'singleton'/);
expect(lease.text).toMatch(
/\("leaseUntil" IS NULL OR "leaseUntil" < now\(\) OR "leaseOwner" = /,
);
expect(lease.text).toMatch(/RETURNING "updateOffset"/);
// Owner and lease seconds are the only parameters: no Date, no clock.
expect(lease.values).toHaveLength(3);
expect(lease.values.some((value) => value instanceof Date)).toBe(false);
expect(lease.values).toContain(LEASE_SECONDS);
});
it('waits without the lease and does not call Telegram', async () => {
leaseGranted(null);
await expect(service.pollOnce(signal)).resolves.toBe('no-lease');
expect(client.getUpdates).not.toHaveBeenCalled();
});
it('asks Telegram from the stored offset and reports polled', async () => {
leaseGranted(42n);
await expect(service.pollOnce(signal)).resolves.toBe('polled');
expect(client.getUpdates).toHaveBeenCalledWith(42n, signal);
// lastPollAt is written with the database clock, lastError is cleared
// only after the batch was applied.
const stamp = sqlOf(callOf(prisma.$executeRaw, 0));
expect(stamp.text).toMatch(/"lastPollAt" = now\(\)/);
expect(stamp.text).not.toMatch(/lastError/);
const cleared = sqlOf(callOf(prisma.$executeRaw, 1));
expect(cleared.text).toMatch(/"lastError" = NULL/);
});
it('handles /start, /stop and /hilfe and ignores groups', async () => {
giveUpdates([
update(10, `/start ${TOKEN}`, { firstName: 'Anna' }),
update(11, '/stop'),
update(12, '/hilfe'),
update(13, '/help'),
update(14, 'hallo'),
update(15, '/start'),
update(16, `/start ${TOKEN}`, {
chatId: GROUP_CHAT,
chatType: 'group',
}),
update(17, '/stop', { chatId: GROUP_CHAT, chatType: 'supergroup' }),
]);
links.linkFromStartIn.mockResolvedValueOnce('LINKED');
await expect(service.pollOnce(signal)).resolves.toBe('polled');
expect(links.linkFromStartIn).toHaveBeenCalledTimes(1);
expect(links.linkFromStartIn).toHaveBeenCalledWith(
tx,
TOKEN,
PRIVATE_CHAT,
'Anna',
);
expect(links.stopIn).toHaveBeenCalledTimes(1);
expect(links.stopIn).toHaveBeenCalledWith(tx, PRIVATE_CHAT);
// LINKED, STOPPED, then HELP for /hilfe, /help (3rd reply of the
// window) - the next ones stay silent; groups get nothing at all.
expect(replies()).toEqual(['LINKED', 'STOPPED', 'HELP', 'HELP']);
expect(
(links.queueReplyIn.mock.calls as unknown[][]).every(
(call) => call[1] === PRIVATE_CHAT,
),
).toBe(true);
});
it('answers a start with an unusable token with LINK_INVALID and /start@bot with a token like /start', async () => {
links.linkFromStartIn.mockResolvedValue('LINK_INVALID');
giveUpdates([update(10, `/start@apicore_test_bot ${TOKEN}`)]);
await service.pollOnce(signal);
expect(links.linkFromStartIn).toHaveBeenCalledWith(
tx,
TOKEN,
PRIVATE_CHAT,
'Anna',
);
expect(replies()).toEqual(['LINK_INVALID']);
});
it('answers at most 3 times per chat in 10 minutes', async () => {
jest.useFakeTimers();
try {
giveUpdates([20, 21, 22, 23, 24].map((id) => update(id, 'hallo')));
await service.pollOnce(signal);
expect(replies()).toEqual(['HELP', 'HELP', 'HELP']);
// Another chat has its own count.
links.queueReplyIn.mockClear();
giveUpdates([update(25, 'hallo', { chatId: 5_000_000_002n })]);
await service.pollOnce(signal);
expect(replies()).toEqual(['HELP']);
// After the window the chat is answered again.
links.queueReplyIn.mockClear();
jest.advanceTimersByTime(HELP_WINDOW_MS + 1);
giveUpdates([update(26, 'hallo')]);
await service.pollOnce(signal);
expect(replies()).toEqual(['HELP']);
} finally {
jest.useRealTimers();
}
});
it('moves the offset in the same transaction as the effect', async () => {
giveUpdates([update(10, '/stop'), update(11, 'x')]);
leaseGranted(10n);
await service.pollOnce(signal);
expect(prisma.$transaction).toHaveBeenCalledTimes(2);
// Per update: offset first, then the effect, both on the same tx.
const offsets = (tx.$executeRaw.mock.calls as unknown[][]).map((call) =>
sqlOf(call),
);
expect(offsets).toHaveLength(2);
expect(offsets[0].values).toEqual(expect.arrayContaining([11n, 10n]));
expect(offsets[1].values).toEqual(expect.arrayContaining([12n, 11n]));
expect(tx.$executeRaw.mock.invocationCallOrder[0]).toBeLessThan(
links.stopIn.mock.invocationCallOrder[0],
);
expect(links.stopIn).toHaveBeenCalledWith(tx, PRIVATE_CHAT);
});
it('the offset advance is a compare-and-set on leaseOwner and the old offset; a lost lease rolls the effect back', async () => {
giveUpdates([update(10, '/stop'), update(11, 'x')]);
leaseGranted(10n);
await service.pollOnce(signal);
const cas = sqlOf(callOf(tx.$executeRaw, 0));
expect(cas.text).toMatch(/UPDATE "TelegramPollState"/);
expect(cas.text).toMatch(/SET "updateOffset" = /);
expect(cas.text).toMatch(/"id" = 'singleton'/);
expect(cas.text).toMatch(/"leaseOwner" = /);
expect(cas.text).toMatch(/"leaseUntil" > now\(\)/);
expect(cas.text).toMatch(/"updateOffset" = /);
expect(cas.values.some((value) => value instanceof Date)).toBe(false);
// Lease lost (count 0): the transaction throws - effect and offset roll
// back together - and the cycle ends; the rest is not touched.
tx.$executeRaw.mockReset().mockResolvedValue(0);
links.stopIn.mockClear();
links.queueReplyIn.mockClear();
prisma.$transaction.mockClear();
await expect(service.pollOnce(signal)).resolves.toBe('no-lease');
expect(links.stopIn).not.toHaveBeenCalled();
expect(links.queueReplyIn).not.toHaveBeenCalled();
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
});
it('a failing effect keeps the offset and ends the cycle with error', async () => {
giveUpdates([update(10, '/stop'), update(11, 'x')]);
links.stopIn.mockRejectedValue(new Error('db down'));
await expect(service.pollOnce(signal)).resolves.toBe('error');
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
// The failure is recorded for the system page, without ids.
const failure = sqlOf(callOf(prisma.$executeRaw, -1));
expect(failure.text).toMatch(/"lastError" = /);
expect(JSON.stringify(failure.values)).not.toContain('5000000001');
// Fixed text plus the error class: never the message of the error.
expect(failure.values).toContain('update not handled: Error');
expect(JSON.stringify(failure.values)).not.toContain('db down');
});
it('answers conflict on 409 and stores the description as lastError', async () => {
client.getUpdates.mockRejectedValue(
new TelegramApiError(
'getUpdates',
409,
'Conflict: terminated by other getUpdates request',
null,
),
);
await expect(service.pollOnce(signal)).resolves.toBe('conflict');
const stored = sqlOf(callOf(prisma.$executeRaw, 0));
expect(stored.text).toMatch(/"lastError" = /);
// Fixed text plus the error class, not the description from Telegram.
expect(stored.values).toContain(
'getUpdates conflict (409): TelegramApiError',
);
expect(JSON.stringify(stored.values)).not.toContain('terminated');
});
it('answers error on other failures and never stores a token', async () => {
client.getUpdates.mockRejectedValue(
new TelegramApiError('getUpdates', null, 'timeout', null),
);
await expect(service.pollOnce(signal)).resolves.toBe('error');
expect(JSON.stringify(prisma.$executeRaw.mock.calls)).not.toMatch(
/\d{5,}:[A-Za-z0-9_-]{20,}/,
);
});
it('an aborted poll (shutdown) records no error and hands the lease back', async () => {
const controller = new AbortController();
client.getUpdates.mockImplementation(() => {
controller.abort();
return Promise.reject(
new TelegramApiError('getUpdates', null, 'aborted', null),
);
});
await expect(service.pollOnce(controller.signal)).resolves.toBe('error');
// Only the release: no lastError, no lastPollAt.
expect(prisma.$executeRaw).toHaveBeenCalledTimes(1);
const release = sqlOf(callOf(prisma.$executeRaw, 0));
expect(release.text).toMatch(/SET "leaseUntil" = now\(\)/);
expect(release.text).toMatch(/"leaseOwner" = /);
expect(release.text).not.toMatch(/lastError/);
});
it('does not touch the lease on shutdown when it never held it', async () => {
leaseGranted(null);
const controller = new AbortController();
controller.abort();
await service.pollOnce(controller.signal);
expect(prisma.$executeRaw).not.toHaveBeenCalled();
});
describe('poison updates', () => {
it('exposes the documented limits', () => {
expect(MAX_UPDATE_ATTEMPTS).toBe(5);
expect(MAX_UPDATE_RETRY_MS).toBe(600_000);
expect(SKIPPED_UPDATE_TEXT).toBe('Telegram-Nachricht übersprungen');
});
it('retries a failing update and skips it after 5 attempts in its own transaction', async () => {
const warn = jest.spyOn(Logger.prototype, 'warn');
giveUpdates([update(10, '/stop'), update(11, 'x')]);
links.stopIn.mockRejectedValue(new Error('private text of Anna'));
for (let attempt = 1; attempt < MAX_UPDATE_ATTEMPTS; attempt++) {
await expect(service.pollOnce(signal)).resolves.toBe('error');
}
expect(links.stopIn).toHaveBeenCalledTimes(MAX_UPDATE_ATTEMPTS - 1);
tx.$executeRaw.mockClear();
prisma.$executeRaw.mockClear();
// The fifth failure skips: offset past it, fixed lastError, the next one runs.
await expect(service.pollOnce(signal)).resolves.toBe('polled');
const statements = (tx.$executeRaw.mock.calls as unknown[][]).map(
(call) => sqlOf(call),
);
const skipOffset = statements.find(
(statement) =>
/SET "updateOffset"/.test(statement.text) &&
statement.values.includes(11n),
);
expect(skipOffset).toBeDefined();
expect(
statements.some((statement) =>
statement.values.includes(SKIPPED_UPDATE_TEXT),
),
).toBe(true);
expect(warn).toHaveBeenCalledWith(
'Telegram update skipped after repeated failures',
);
// No id and no text anywhere in the log.
expect(JSON.stringify(warn.mock.calls)).not.toMatch(/10|Anna/);
// The following update was handled, and the skip keeps its lastError.
expect(replies()).toContain('HELP');
expect(
(prisma.$executeRaw.mock.calls as unknown[][]).some((call) =>
sqlOf(call).text.includes('"lastError" = NULL'),
),
).toBe(false);
});
it('skips after the time limit even with fewer attempts', async () => {
jest.useFakeTimers();
try {
giveUpdates([update(10, '/stop')]);
links.stopIn.mockRejectedValue(new Error('boom'));
await expect(service.pollOnce(signal)).resolves.toBe('error');
jest.advanceTimersByTime(MAX_UPDATE_RETRY_MS + 1);
await expect(service.pollOnce(signal)).resolves.toBe('polled');
expect(links.stopIn).toHaveBeenCalledTimes(2);
} finally {
jest.useRealTimers();
}
});
it('a lost lease is no failure of the update', async () => {
giveUpdates([update(10, '/stop')]);
tx.$executeRaw.mockResolvedValue(0);
for (let attempt = 0; attempt < MAX_UPDATE_ATTEMPTS + 2; attempt++) {
await expect(service.pollOnce(signal)).resolves.toBe('no-lease');
}
expect(links.stopIn).not.toHaveBeenCalled();
});
});
it('moves the offset past a batch of only unparseable updates', async () => {
leaseGranted(7n);
giveUpdates([], 12);
await expect(service.pollOnce(signal)).resolves.toBe('polled');
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
const cas = sqlOf(callOf(tx.$executeRaw, 0));
expect(cas.text).toMatch(/SET "updateOffset"/);
expect(cas.values).toEqual(expect.arrayContaining([13n, 7n]));
expect(links.queueReplyIn).not.toHaveBeenCalled();
});
it('moves the offset past dropped updates behind the last handled one, once', async () => {
leaseGranted(10n);
giveUpdates([update(10, 'x')], 14);
await service.pollOnce(signal);
const offsets = (tx.$executeRaw.mock.calls as unknown[][]).map((call) =>
sqlOf(call),
);
expect(offsets).toHaveLength(2);
expect(offsets[0].values).toEqual(expect.arrayContaining([11n, 10n]));
expect(offsets[1].values).toEqual(expect.arrayContaining([15n, 11n]));
});
it('counts the reply quota only after the transaction committed', async () => {
giveUpdates([update(10, 'hallo')]);
// The commit fails after the reply was queued.
prisma.$transaction.mockImplementationOnce(
async (work: (t: unknown) => Promise<unknown>) => {
await work(tx);
throw new Error('commit failed');
},
);
await service.pollOnce(signal);
links.queueReplyIn.mockClear();
// Three helps are still allowed: the rolled-back one was not counted.
for (const id of [11, 12, 13, 14]) {
leaseGranted(BigInt(id));
giveUpdates([update(id, 'hallo')]);
await service.pollOnce(signal);
}
expect(replies()).toEqual(['HELP', 'HELP', 'HELP']);
});
describe('429 from Telegram', () => {
it('stays away until retry_after has passed', async () => {
jest.useFakeTimers();
try {
client.getUpdates.mockRejectedValueOnce(
new TelegramApiError('getUpdates', 429, 'Too Many Requests', 120),
);
await expect(service.pollOnce(signal)).resolves.toBe('error');
const stored = sqlOf(callOf(prisma.$executeRaw, 0));
expect(stored.values).toContain(
'getUpdates rate limited (429): TelegramApiError',
);
// Cycles inside the pause do not even ask for the lease.
prisma.$queryRaw.mockClear();
client.getUpdates.mockClear();
jest.advanceTimersByTime(119_000);
await expect(service.pollOnce(signal)).resolves.toBe('error');
expect(prisma.$queryRaw).not.toHaveBeenCalled();
expect(client.getUpdates).not.toHaveBeenCalled();
jest.advanceTimersByTime(1_001);
await expect(service.pollOnce(signal)).resolves.toBe('polled');
expect(client.getUpdates).toHaveBeenCalledTimes(1);
} finally {
jest.useRealTimers();
}
});
it('caps the pause at one hour', async () => {
jest.useFakeTimers();
try {
client.getUpdates.mockRejectedValueOnce(
new TelegramApiError('getUpdates', 429, 'x', 86_400),
);
await service.pollOnce(signal);
jest.advanceTimersByTime(3_600_001);
client.getUpdates.mockClear();
await expect(service.pollOnce(signal)).resolves.toBe('polled');
expect(client.getUpdates).toHaveBeenCalledTimes(1);
} finally {
jest.useRealTimers();
}
});
});
});
@@ -0,0 +1,446 @@
import { randomUUID } from 'node:crypto';
import { Injectable, Logger } from '@nestjs/common';
import { Prisma } from '../../generated/prisma';
import { loggableError } from '../common/loggable-error';
import { PrismaService } from '../prisma/prisma.service';
import { TelegramApiError } from './telegram-api-error';
import {
TelegramClient,
TelegramUpdate,
TelegramUpdateBatch,
} from './telegram-client';
import { TelegramLinkService } from './telegram-link.service';
import type { TelegramTemplateCode } from './telegram-texts';
export const LEASE_SECONDS = 60;
/** Loop interval: also how long a receiver without the lease (or after a 409) waits. */
export const NO_LEASE_WAIT_MS = 30_000;
export const HELP_REPLIES_PER_CHAT = 3;
export const HELP_WINDOW_MS = 600_000;
/** An update that keeps failing is skipped after this many attempts or this long. */
export const MAX_UPDATE_ATTEMPTS = 5;
export const MAX_UPDATE_RETRY_MS = 600_000;
const MAX_RATE_LIMIT_PAUSE_MS = 3_600_000;
/** Fixed texts for the system page: no ids, no message text. */
export const SKIPPED_UPDATE_TEXT = 'Telegram-Nachricht übersprungen';
const MAX_LAST_ERROR_CHARS = 300;
const START_COMMAND = /^\/([A-Za-z]+)(?:@[A-Za-z0-9_]+)?(?:\s+(\S+))?/;
export type PollOutcome =
'disabled' | 'no-lease' | 'polled' | 'conflict' | 'error';
type Command =
{ name: 'start'; token: string | null } | { name: 'stop' } | { name: 'help' };
/** The lease or the stored offset changed: nothing of this update may stay. */
class LeaseLostError extends Error {
constructor() {
super('Telegram poll lease lost');
this.name = 'LeaseLostError';
}
}
/**
* What may go to a log or lastError: Prisma errors by name, code and model
* (loggableError), every other error by its class name only - a message can
* quote user data.
*/
function describeError(error: unknown): string {
if (
error instanceof Prisma.PrismaClientKnownRequestError ||
error instanceof Prisma.PrismaClientUnknownRequestError ||
error instanceof Prisma.PrismaClientValidationError ||
error instanceof Prisma.PrismaClientInitializationError ||
error instanceof Prisma.PrismaClientRustPanicError
) {
return loggableError(error).message;
}
return error instanceof Error ? error.name : 'unknown error';
}
function parseCommand(text: string | null): Command {
const match = START_COMMAND.exec(text?.trim() ?? '');
const name = match?.[1].toLowerCase();
if (name === 'start') {
return { name: 'start', token: match?.[2] ?? null };
}
return name === 'stop' ? { name: 'stop' } : { name: 'help' };
}
/**
* At most HELP_REPLIES_PER_CHAT replies per chat in HELP_WINDOW_MS, counted
* in memory (there is exactly one receiver, the lease sees to that). A
* stranger writing to the bot cannot make it talk without end. Monotonic
* clock, so a clock step changes nothing.
*/
class ReplyLimiter {
private readonly sentAt = new Map<string, number[]>();
/** Would one more reply to this chat be within the limit? Counts nothing. */
allows(chatId: bigint): boolean {
this.prune();
return (
(this.sentAt.get(String(chatId))?.length ?? 0) < HELP_REPLIES_PER_CHAT
);
}
/** Counts a reply that was queued and committed. */
record(chatId: bigint): void {
const key = String(chatId);
this.sentAt.set(key, [...(this.sentAt.get(key) ?? []), performance.now()]);
}
private prune(): void {
const now = performance.now();
for (const [chat, times] of this.sentAt) {
const recent = times.filter((time) => now - time < HELP_WINDOW_MS);
if (recent.length === 0) {
this.sentAt.delete(chat);
} else {
this.sentAt.set(chat, recent);
}
}
}
}
/**
* Receives what people write to the bot (Spec 9a.5, 9a.7): long polling
* getUpdates in the worker, no public endpoint. Exactly one receiver per
* bot: the lease in TelegramPollState (database clock only) says who. Each
* update runs in its own transaction together with the offset advance, which
* is a compare-and-set on lease owner and old offset - a receiver that lost
* the lease changes nothing, so every update takes effect once. Replies are
* queued as deliveries (the sender talks to Telegram, not this class).
* Never logs a token, a link code, a chat id or a message text.
*/
@Injectable()
export class TelegramUpdatesService {
private readonly logger = new Logger(TelegramUpdatesService.name);
/** Names this receiver in the lease. */
private readonly instanceId = randomUUID();
private readonly replies = new ReplyLimiter();
private holdsLease = false;
/** Monotonic time until which Telegram asked us to stay away (429). */
private rateLimitedUntil = 0;
/** Failed attempts per update, in memory: a restart gives them a fresh start. */
private readonly failures = new Map<
bigint,
{ attempts: number; firstAt: number }
>();
/** Test seam: after how many attempts / how long a failing update is skipped. */
retryLimits = {
attempts: MAX_UPDATE_ATTEMPTS,
windowMs: MAX_UPDATE_RETRY_MS,
};
constructor(
private readonly prisma: PrismaService,
private readonly client: TelegramClient,
private readonly links: TelegramLinkService,
) {}
/**
* One cycle: take or extend the lease, fetch updates (long poll), handle
* them one by one. 'polled' means the next cycle may start at once. A
* cycle that ends because of shutdown hands the lease back.
*/
async pollOnce(signal: AbortSignal): Promise<PollOutcome> {
try {
return await this.cycle(signal);
} finally {
if (signal.aborted && this.holdsLease) {
await this.releaseLease();
}
}
}
private async cycle(signal: AbortSignal): Promise<PollOutcome> {
if (!this.client.isConfigured()) {
return 'disabled';
}
if (signal.aborted || performance.now() < this.rateLimitedUntil) {
return 'error';
}
const offset = await this.acquireLease();
if (offset === null) {
return 'no-lease';
}
let batch: TelegramUpdateBatch;
try {
batch = await this.client.getUpdates(offset, signal);
} catch (error: unknown) {
return this.onFetchError(error, signal);
}
await this.markPolled();
return this.applyBatch(batch, offset, signal);
}
/** The updates in order, then the offset past dropped ones; a clean batch clears lastError. */
private async applyBatch(
batch: TelegramUpdateBatch,
offset: bigint,
signal: AbortSignal,
): Promise<PollOutcome> {
let current = offset;
let skipped = false;
for (const update of batch.updates) {
if (signal.aborted) {
return 'polled';
}
try {
const reply = await this.prisma.$transaction((tx) =>
this.applyUpdate(tx, update, current),
);
// Counted only now: a rolled-back reply was never queued.
if (reply !== null) {
this.replies.record(reply);
}
this.failures.delete(update.updateId);
} catch (error: unknown) {
if (error instanceof LeaseLostError) {
return 'no-lease';
}
if (!(await this.shouldSkip(update, error))) {
return 'error';
}
try {
await this.skipUpdate(update, current);
} catch (skipError: unknown) {
return this.onUpdateError(skipError);
}
skipped = true;
}
current = update.updateId + 1n;
}
const dropped = await this.skipDropped(batch, current, signal);
if (dropped !== 'ok') {
return dropped;
}
if (!skipped) {
await this.clearLastError();
}
return 'polled';
}
/** Dropped updates (no chat, wrong shape): move the offset past them, never fetch them again. */
private async skipDropped(
batch: TelegramUpdateBatch,
current: bigint,
signal: AbortSignal,
): Promise<'ok' | PollOutcome> {
const highest = batch.highestUpdateId;
if (highest === null || highest < current || signal.aborted) {
return 'ok';
}
try {
await this.prisma.$transaction((tx) =>
this.advanceOffsetIn(tx, current, highest + 1n),
);
} catch (error: unknown) {
return this.onUpdateError(error);
}
return 'ok';
}
/** Lease SQL, database clock only. The stored offset, or null without the lease. */
private async acquireLease(): Promise<bigint | null> {
const rows = await this.prisma.$queryRaw<{ updateOffset: bigint }[]>`
UPDATE "TelegramPollState"
SET "leaseOwner" = ${this.instanceId},
"leaseUntil" = now() + make_interval(secs => ${LEASE_SECONDS})
WHERE "id" = 'singleton'
AND ("leaseUntil" IS NULL OR "leaseUntil" < now() OR "leaseOwner" = ${this.instanceId})
RETURNING "updateOffset"`;
this.holdsLease = rows.length > 0;
return rows[0]?.updateOffset ?? null;
}
/** Shutdown: the next receiver need not wait for the lease to run out. */
private async releaseLease(): Promise<void> {
this.holdsLease = false;
try {
await this.prisma.$executeRaw`
UPDATE "TelegramPollState"
SET "leaseUntil" = now()
WHERE "id" = 'singleton' AND "leaseOwner" = ${this.instanceId}`;
} catch (error: unknown) {
this.logger.warn(`Telegram lease not released: ${describeError(error)}`);
}
}
private async markPolled(): Promise<void> {
await this.prisma.$executeRaw`
UPDATE "TelegramPollState"
SET "lastPollAt" = now()
WHERE "id" = 'singleton' AND "leaseOwner" = ${this.instanceId}`;
}
private async clearLastError(): Promise<void> {
await this.prisma.$executeRaw`
UPDATE "TelegramPollState"
SET "lastError" = NULL
WHERE "id" = 'singleton' AND "leaseOwner" = ${this.instanceId}`;
}
private async setLastError(text: string): Promise<void> {
await this.prisma.$executeRaw`
UPDATE "TelegramPollState"
SET "lastError" = ${text.slice(0, MAX_LAST_ERROR_CHARS)}
WHERE "id" = 'singleton' AND "leaseOwner" = ${this.instanceId}`;
}
/**
* 409: another getUpdates or a webhook; wait. 429: stay away until
* retry_after has passed (at most an hour). The texts are fixed plus the
* error class: nothing from the answer, no token, no URL.
*/
private async onFetchError(
error: unknown,
signal: AbortSignal,
): Promise<PollOutcome> {
if (signal.aborted) {
return 'error';
}
const status = error instanceof TelegramApiError ? error.statusCode : null;
if (status === 429) {
const seconds =
error instanceof TelegramApiError ? error.retryAfterSec : null;
this.rateLimitedUntil =
performance.now() +
Math.min(
(seconds ?? NO_LEASE_WAIT_MS / 1_000) * 1_000,
MAX_RATE_LIMIT_PAUSE_MS,
);
}
let label = 'getUpdates failed';
if (status === 409) {
label = 'getUpdates conflict (409)';
} else if (status === 429) {
label = 'getUpdates rate limited (429)';
}
await this.setLastError(`${label}: ${describeError(error)}`);
return status === 409 ? 'conflict' : 'error';
}
private async onUpdateError(error: unknown): Promise<PollOutcome> {
if (error instanceof LeaseLostError) {
return 'no-lease';
}
// The offset stays: the update is tried again in the next cycle.
const text = `update not handled: ${describeError(error)}`;
this.logger.error(`Telegram ${text}`);
await this.setLastError(text);
return 'error';
}
/**
* Counts a failed attempt of an update; true once it failed too often or
* for too long and has to be skipped (otherwise the failure is recorded).
*/
private async shouldSkip(
update: TelegramUpdate,
error: unknown,
): Promise<boolean> {
const now = performance.now();
const known = this.failures.get(update.updateId);
const state = {
attempts: (known?.attempts ?? 0) + 1,
firstAt: known?.firstAt ?? now,
};
this.failures.set(update.updateId, state);
const exhausted =
state.attempts >= this.retryLimits.attempts ||
now - state.firstAt >= this.retryLimits.windowMs;
if (!exhausted) {
await this.onUpdateError(error);
}
return exhausted;
}
/** Offset past a poison update in its own transaction, so the queue moves on. */
private async skipUpdate(
update: TelegramUpdate,
oldOffset: bigint,
): Promise<void> {
await this.prisma.$transaction(async (tx) => {
await this.advanceOffsetIn(tx, oldOffset, update.updateId + 1n);
await tx.$executeRaw`
UPDATE "TelegramPollState"
SET "lastError" = ${SKIPPED_UPDATE_TEXT}
WHERE "id" = 'singleton' AND "leaseOwner" = ${this.instanceId}`;
});
this.failures.delete(update.updateId);
this.logger.warn('Telegram update skipped after repeated failures');
}
/** Offset compare-and-set on lease owner and old offset; count 0: lease lost. */
private async advanceOffsetIn(
tx: Prisma.TransactionClient,
oldOffset: bigint,
newOffset: bigint,
): Promise<void> {
const advanced = await tx.$executeRaw`
UPDATE "TelegramPollState"
SET "updateOffset" = ${newOffset}
WHERE "id" = 'singleton'
AND "leaseOwner" = ${this.instanceId}
AND "leaseUntil" > now()
AND "updateOffset" = ${oldOffset}`;
if (advanced === 0) {
throw new LeaseLostError();
}
}
/**
* Offset first (a lost lease ends here), then the effect, all in `tx`.
* Returns the chat whose reply quota must be counted once `tx` commits.
*/
private async applyUpdate(
tx: Prisma.TransactionClient,
update: TelegramUpdate,
oldOffset: bigint,
): Promise<bigint | null> {
await this.advanceOffsetIn(tx, oldOffset, update.updateId + 1n);
// Groups and channels: the bot is not for them.
if (update.chatType !== 'private') {
return null;
}
const command = parseCommand(update.text);
if (command.name === 'stop') {
await this.links.stopIn(tx, update.chatId);
return this.reply(tx, update.chatId, 'STOPPED');
}
if (command.name === 'start' && command.token !== null) {
const result = await this.links.linkFromStartIn(
tx,
command.token,
update.chatId,
update.firstName,
);
return this.reply(tx, update.chatId, result);
}
return this.reply(tx, update.chatId, 'HELP');
}
/**
* LINKED always goes out (it needs a valid one-time token, so no
* stranger can trigger it); every other reply counts against the limit.
* Returns the chat to count after the commit, or null.
*/
private async reply(
tx: Prisma.TransactionClient,
chatId: bigint,
code: TelegramTemplateCode,
): Promise<bigint | null> {
if (code === 'LINKED') {
await this.links.queueReplyIn(tx, chatId, code);
return null;
}
if (!this.replies.allows(chatId)) {
return null;
}
await this.links.queueReplyIn(tx, chatId, code);
return chatId;
}
}
@@ -2,10 +2,13 @@ import { Module } from '@nestjs/common';
import { NotificationsModule } from '../notifications/notifications.module';
import { telegramConfig } from './telegram-config';
import { TELEGRAM_CONFIG, TelegramClient } from './telegram-client';
import { TelegramLinkService } from './telegram-link.service';
import { TelegramSender } from './telegram-sender';
import { TelegramUpdatesService } from './telegram-updates.service';
/**
* The Bot API client for the worker's Telegram loops. Reads the token from
* The Bot API client for the worker's Telegram loops (send, receive) and the
* connect/disconnect logic the profile routes use. Reads the token from
* the environment once; without it the client reports isConfigured() false
* and the loops do not run. The sender needs the permission resolver, which
* the global JobPermissionsModule (worker) or PermissionsModule (API) provides:
@@ -18,7 +21,14 @@ import { TelegramSender } from './telegram-sender';
{ provide: TELEGRAM_CONFIG, useFactory: () => telegramConfig() },
TelegramClient,
TelegramSender,
TelegramLinkService,
TelegramUpdatesService,
],
exports: [
TelegramClient,
TelegramSender,
TelegramLinkService,
TelegramUpdatesService,
],
exports: [TelegramClient, TelegramSender],
})
export class TelegramModule {}
@@ -12,6 +12,10 @@ import {
TELEGRAM_SEND_POLL_MS,
type TelegramSender,
} from '../telegram/telegram-sender';
import {
NO_LEASE_WAIT_MS,
type TelegramUpdatesService,
} from '../telegram/telegram-updates.service';
import type { WeatherHistoryService } from '../weather/history/weather-history.service';
import {
WEATHER_FIRST_TICK_DELAY_MS,
@@ -69,6 +73,12 @@ class FakeTelegramSender {
drain = jest.fn<Promise<number>, unknown[]>().mockResolvedValue(0);
}
class FakeTelegramUpdates {
pollOnce = jest
.fn<Promise<string>, [AbortSignal]>()
.mockResolvedValue('no-lease');
}
describe('WorkerRuntime', () => {
const ListenerMock = PgListener as unknown as jest.Mock;
const originalDatabaseUrl = process.env.DATABASE_URL;
@@ -82,6 +92,7 @@ describe('WorkerRuntime', () => {
let weatherHistory: { syncOnce: jest.Mock };
let telegramConfigured: boolean;
let telegramSender: FakeTelegramSender;
let telegramUpdates: FakeTelegramUpdates;
let runtime: WorkerRuntime;
let logError: jest.SpyInstance;
@@ -122,6 +133,7 @@ describe('WorkerRuntime', () => {
jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
telegramConfigured = false;
telegramSender = new FakeTelegramSender();
telegramUpdates = new FakeTelegramUpdates();
runtime = createRuntime();
});
@@ -134,6 +146,7 @@ describe('WorkerRuntime', () => {
weatherHistory as unknown as WeatherHistoryService,
{ isConfigured: () => telegramConfigured } as unknown as TelegramClient,
telegramSender as unknown as TelegramSender,
telegramUpdates as unknown as TelegramUpdatesService,
);
}
@@ -269,6 +282,85 @@ describe('WorkerRuntime', () => {
});
});
describe('telegram-updates loop', () => {
it('is not registered without a bot token', async () => {
await bootstrap();
await jest.advanceTimersByTimeAsync(NO_LEASE_WAIT_MS * 2);
expect(telegramUpdates.pollOnce).not.toHaveBeenCalled();
});
describe('with a bot token', () => {
beforeEach(async () => {
await runtime.onModuleDestroy();
telegramConfigured = true;
runtime = createRuntime();
});
it('polls with the stop signal and has no wake channel', async () => {
await bootstrap();
expect(telegramUpdates.pollOnce).toHaveBeenCalledTimes(1);
expect(telegramUpdates.pollOnce).toHaveBeenCalledWith(
expect.any(AbortSignal),
);
expect(listenerOptions().channels).toEqual([
'domain_event',
'calendar_sync',
'webhook_delivery',
'notification_delivery',
]);
});
it('waits 30 s after no-lease, conflict and error', async () => {
for (const outcome of ['no-lease', 'conflict', 'error']) {
telegramUpdates.pollOnce.mockClear().mockResolvedValue(outcome);
await runtime.onModuleDestroy();
runtime = createRuntime();
await bootstrap();
expect(telegramUpdates.pollOnce).toHaveBeenCalledTimes(1);
await jest.advanceTimersByTimeAsync(NO_LEASE_WAIT_MS - 1);
expect(telegramUpdates.pollOnce).toHaveBeenCalledTimes(1);
await jest.advanceTimersByTimeAsync(1);
expect(telegramUpdates.pollOnce).toHaveBeenCalledTimes(2);
}
});
it('polls again at once after a successful poll', async () => {
telegramUpdates.pollOnce
.mockResolvedValueOnce('polled')
.mockResolvedValueOnce('polled')
.mockResolvedValue('no-lease');
await bootstrap();
await jest.advanceTimersByTimeAsync(1);
await jest.advanceTimersByTimeAsync(1);
expect(telegramUpdates.pollOnce).toHaveBeenCalledTimes(3);
await jest.advanceTimersByTimeAsync(NO_LEASE_WAIT_MS - 1);
expect(telegramUpdates.pollOnce).toHaveBeenCalledTimes(3);
});
it('a failing poll does not make the worker unhealthy', async () => {
telegramUpdates.pollOnce.mockRejectedValue(new Error('boom'));
await bootstrap();
await expect(runtime.health()).resolves.toEqual({ ok: true });
expect(logError).toHaveBeenCalled();
});
it('aborts the running poll at shutdown', async () => {
await bootstrap();
const [signal] = telegramUpdates.pollOnce.mock.calls[0];
await runtime.onModuleDestroy();
expect(signal.aborted).toBe(true);
});
});
});
it('polls webhook deliveries every 5 s', async () => {
await bootstrap();
expect(webhookDeliveries.drain).toHaveBeenCalledTimes(1);
@@ -19,6 +19,10 @@ import {
TELEGRAM_SEND_POLL_MS,
TelegramSender,
} from '../telegram/telegram-sender';
import {
NO_LEASE_WAIT_MS,
TelegramUpdatesService,
} from '../telegram/telegram-updates.service';
import {
WEATHER_FIRST_TICK_DELAY_MS,
WEATHER_HISTORY_POLL_MS,
@@ -32,6 +36,7 @@ import { HEALTH_STALE_MS, WorkerHealth } from './worker-health';
export const DOMAIN_EVENT_POLL_MS = 5_000;
export const CALENDAR_OUTBOX_POLL_MS = 60_000;
export const WEBHOOK_DELIVERY_POLL_MS = 5_000;
const TELEGRAM_UPDATES_LOOP = 'telegram-updates';
/** The health check's SELECT 1 must answer within this. */
export const HEALTH_QUERY_TIMEOUT_MS = 5_000;
@@ -84,6 +89,7 @@ export class WorkerRuntime implements OnApplicationBootstrap, OnModuleDestroy {
private readonly weatherHistory: WeatherHistoryService,
private readonly telegramClient: TelegramClient,
private readonly telegramSender: TelegramSender,
private readonly telegramUpdates: TelegramUpdatesService,
) {
const loops = this.workerLoops().map((definition) => ({
definition,
@@ -135,6 +141,14 @@ export class WorkerRuntime implements OnApplicationBootstrap, OnModuleDestroy {
channel: WAKE_CHANNELS.notificationDeliveries,
tick: () => this.sendTelegram(),
},
{
// Long polling getUpdates; no wake channel. After a poll the
// next one starts at once, otherwise the interval is the wait
// (no lease, 409, error).
name: TELEGRAM_UPDATES_LOOP,
intervalMs: NO_LEASE_WAIT_MS,
tick: () => this.receiveTelegram(),
},
]
: []),
{
@@ -239,6 +253,13 @@ export class WorkerRuntime implements OnApplicationBootstrap, OnModuleDestroy {
await this.telegramSender.drain(this.stopping.signal);
}
private async receiveTelegram(): Promise<void> {
const outcome = await this.telegramUpdates.pollOnce(this.stopping.signal);
if (outcome === 'polled') {
this.loops.get(TELEGRAM_UPDATES_LOOP)?.wake();
}
}
private async deliverWebhooks(): Promise<void> {
await this.webhookDeliveries.releaseStaleClaims();
// No filter: every due delivery of the database.
@@ -0,0 +1,563 @@
import { INestApplication } from '@nestjs/common';
import * as bcrypt from 'bcryptjs';
import { randomUUID } from 'node:crypto';
import request from 'supertest';
import { App } from 'supertest/types';
import { PrismaService } from '../src/prisma/prisma.service';
import { createTestApp } from './utils/create-test-app';
import { login } from './utils/api';
interface Warning {
code: string;
severity: string;
message: string;
refs: { type: string; id: string }[];
}
interface BottlingBody {
id: string;
jarSize: number;
bestBeforeDate: string;
warnings: Warning[];
}
interface ConfirmationBody {
statusCode: number;
code: string;
waterContent: number;
message: string;
warnings: Warning[];
}
interface PrefillBody {
jarSize: number | null;
jarSizeSource: string | null;
bestBeforeDate: string | null;
shelfLifeMonths: number | null;
waterContent: number | null;
warnings: Warning[];
}
describe('Bottling quality (e2e)', () => {
let app: INestApplication<App>;
let prisma: PrismaService;
const stamp = Date.now();
const email = `bottling-quality-e2e-${stamp}@example.com`;
const password = 'SuperSecret123!';
let userId: string;
let token: string;
let staffId: string;
let staffToken: string;
let extractionId: string;
const honeyBatchIds: string[] = [];
const productIds: string[] = [];
const bottlingIds: string[] = [];
const api = () => request(app.getHttpServer());
const auth = (req: request.Test) =>
req.set('Authorization', `Bearer ${token}`);
async function newBatch(
waterContent: number | null,
honeyType: string | null = null,
): Promise<string> {
const batch = await prisma.honeyBatch.create({
data: {
batchNumber: `BQ-${stamp}-${honeyBatchIds.length}`,
extractionId,
amount: 25,
initialAmount: 25,
waterContent,
honeyType,
},
});
honeyBatchIds.push(batch.id);
return batch.id;
}
async function newProduct(data: {
packagingSize?: number;
shelfLifeMonths?: number;
}): Promise<string> {
const product = await prisma.product.create({
data: {
name: `Qualität ${stamp}-${productIds.length}`,
kind: 'BOTTLED_HONEY',
...data,
},
});
productIds.push(product.id);
return product.id;
}
/** What a write would leave behind for the batch: movements, events, audit. */
async function writtenCounts(honeyBatchId: string) {
return {
movements: await prisma.batchMovement.count({ where: { honeyBatchId } }),
events: await prisma.domainEvent.count({
where: {
aggregateType: 'BottlingBatch',
payload: { path: ['honeyBatchId'], equals: honeyBatchId },
},
}),
audits: await prisma.auditLog.count({
where: { userId, entityType: 'BottlingBatch', action: 'CREATE' },
}),
};
}
function create(body: Record<string, unknown>, key?: string): request.Test {
const req = auth(api().post('/api/v1/bottling-batches'));
if (key) {
req.set('Idempotency-Key', key);
}
return req.send({
date: '2026-01-31',
jarCount: 2,
lotNumber: `BQ-L-${stamp}-${randomUUID()}`,
...body,
});
}
function remember(response: { body: unknown }): BottlingBody {
const body = response.body as BottlingBody;
bottlingIds.push(body.id);
return body;
}
beforeAll(async () => {
app = await createTestApp();
prisma = app.get(PrismaService);
const user = await prisma.user.create({
data: {
email,
passwordHash: await bcrypt.hash(password, 12),
name: 'Quality',
role: { connect: { key: 'BEEKEEPER' } },
},
});
userId = user.id;
token = (await login(app, email, password)).accessToken;
const extraction = await prisma.extraction.create({
data: { date: new Date(), userId },
});
extractionId = extraction.id;
// STAFF has no bottling:create.
const staff = await prisma.user.create({
data: {
email: `bottling-quality-staff-${stamp}@example.com`,
passwordHash: await bcrypt.hash(password, 12),
name: 'Staff',
role: { connect: { key: 'STAFF' } },
},
});
staffId = staff.id;
staffToken = (await login(app, staff.email, password)).accessToken;
});
afterAll(async () => {
await prisma.domainEvent.deleteMany({
where: {
aggregateType: 'BottlingBatch',
aggregateId: { in: bottlingIds },
},
});
await prisma.bottlingBatch.deleteMany({
where: { id: { in: bottlingIds } },
});
await prisma.batchMovement.deleteMany({
where: { honeyBatchId: { in: honeyBatchIds } },
});
await prisma.honeyMeasurement.deleteMany({
where: { honeyBatchId: { in: honeyBatchIds } },
});
await prisma.honeyBatch.deleteMany({
where: { id: { in: honeyBatchIds } },
});
await prisma.extraction.deleteMany({ where: { id: extractionId } });
await prisma.product.deleteMany({ where: { id: { in: productIds } } });
await prisma.idempotencyRecord.deleteMany({ where: { userId } });
const userIds = [userId, staffId];
await prisma.refreshToken.deleteMany({
where: { userId: { in: userIds } },
});
await prisma.auditLog.deleteMany({ where: { userId: { in: userIds } } });
await prisma.user.deleteMany({ where: { id: { in: userIds } } });
await app.close();
});
it('17 % -> 201 without a quality warning', async () => {
const honeyBatchId = await newBatch(17);
const response = await create({
honeyBatchId,
jarSize: 500,
bestBeforeDate: '2027-01-31',
}).expect(201);
expect(remember(response).warnings).toEqual([]);
});
it('19 % -> 201 with WATER_CONTENT_HIGH', async () => {
const honeyBatchId = await newBatch(19);
const response = await create({
honeyBatchId,
jarSize: 500,
bestBeforeDate: '2027-01-31',
}).expect(201);
const warnings = remember(response).warnings;
expect(warnings.map((w) => w.code)).toEqual(['WATER_CONTENT_HIGH']);
expect(warnings[0].severity).toBe('WARNUNG');
});
it('no water content at all -> 201 with the hint WATER_CONTENT_MISSING', async () => {
const honeyBatchId = await newBatch(null);
const response = await create({
honeyBatchId,
jarSize: 500,
bestBeforeDate: '2027-01-31',
}).expect(201);
expect(remember(response).warnings.map((w) => w.code)).toEqual([
'WATER_CONTENT_MISSING',
]);
});
it('20.5 % -> 409 CONFIRMATION_REQUIRED; confirmed retry with the same key -> 201', async () => {
const honeyBatchId = await newBatch(20.5);
const key = randomUUID();
const body = { honeyBatchId, jarSize: 500, bestBeforeDate: '2027-01-31' };
const countsBefore = await writtenCounts(honeyBatchId);
const refused = await create(body, key).expect(409);
const refusal = refused.body as ConfirmationBody;
expect(refusal.code).toBe('CONFIRMATION_REQUIRED');
expect(refusal.warnings.map((w) => [w.code, w.severity])).toEqual([
['WATER_CONTENT_ABOVE_LEGAL', 'BESTAETIGEN'],
]);
expect(refusal.warnings[0].refs).toEqual([
{ type: 'HoneyBatch', id: honeyBatchId },
]);
expect(refusal.waterContent).toBe(20.5);
// Nothing was written: no bottling, the rest is untouched.
expect(await prisma.bottlingBatch.count({ where: { honeyBatchId } })).toBe(
0,
);
expect(
(
await prisma.honeyBatch.findUniqueOrThrow({
where: { id: honeyBatchId },
})
).amount,
).toBe(25);
expect(await writtenCounts(honeyBatchId)).toEqual(countsBefore);
const confirmed = await create(
{
...body,
acknowledgedWarnings: ['WATER_CONTENT_ABOVE_LEGAL'],
acknowledgedWaterContent: 20.5,
},
key,
).expect(201);
expect(remember(confirmed).warnings.map((w) => w.code)).toEqual([
'WATER_CONTENT_ABOVE_LEGAL',
]);
expect(await prisma.bottlingBatch.count({ where: { honeyBatchId } })).toBe(
1,
);
// A third call with the same key replays the stored 201.
const replay = await create(
{
...body,
acknowledgedWarnings: ['WATER_CONTENT_ABOVE_LEGAL'],
acknowledgedWaterContent: 20.5,
},
key,
).expect(201);
expect((replay.body as BottlingBody).id).toBe(
(confirmed.body as BottlingBody).id,
);
expect(await prisma.bottlingBatch.count({ where: { honeyBatchId } })).toBe(
1,
);
});
it('a confirmation is bound to the value: another value gets a fresh 409', async () => {
const honeyBatchId = await newBatch(21);
const body = {
honeyBatchId,
jarSize: 500,
bestBeforeDate: '2027-01-31',
acknowledgedWarnings: ['WATER_CONTENT_ABOVE_LEGAL'],
};
// Confirmed for 20.5 %, but the batch holds 21 %.
const stale = await create({
...body,
acknowledgedWaterContent: 20.5,
}).expect(409);
expect((stale.body as ConfirmationBody).waterContent).toBe(21);
// The code alone is no confirmation either.
await create(body).expect(409);
await create({ ...body, acknowledgedWaterContent: 101 }).expect(400);
expect(await prisma.bottlingBatch.count({ where: { honeyBatchId } })).toBe(
0,
);
remember(
await create({ ...body, acknowledgedWaterContent: 21 }).expect(201),
);
});
it('exactly 20.0 % only warns: 201 with WATER_CONTENT_HIGH', async () => {
const honeyBatchId = await newBatch(20);
const response = await create({
honeyBatchId,
jarSize: 500,
bestBeforeDate: '2027-01-31',
}).expect(201);
expect(remember(response).warnings.map((w) => w.code)).toEqual([
'WATER_CONTENT_HIGH',
]);
});
it('an impossible day is a 400, never a 500', async () => {
const honeyBatchId = await newBatch(17);
await create({
honeyBatchId,
jarSize: 500,
date: '2026-02-30',
bestBeforeDate: '2027-01-31',
}).expect(400);
await create({
honeyBatchId,
jarSize: 500,
bestBeforeDate: '2027-02-30',
}).expect(400);
await auth(api().get('/api/v1/bottling-batches/prefill'))
.query({ honeyBatchId, date: '2026-02-30' })
.expect(400);
});
it('a newer low measurement lifts the stop; a newer high one sets it', async () => {
const honeyBatchId = await newBatch(21);
const userRow = { honeyBatchId, userId };
await prisma.honeyMeasurement.create({
data: {
...userRow,
waterContent: 16.8,
measuredAt: new Date('2026-08-01'),
},
});
const body = { honeyBatchId, jarSize: 500, bestBeforeDate: '2027-01-31' };
remember(await create(body).expect(201));
await prisma.honeyMeasurement.create({
data: {
...userRow,
waterContent: 22,
measuredAt: new Date('2026-09-01'),
},
});
const refused = await create(body).expect(409);
expect((refused.body as ConfirmationBody).code).toBe(
'CONFIRMATION_REQUIRED',
);
});
it('rejects an unknown acknowledged code and more than one', async () => {
const honeyBatchId = await newBatch(17);
const body = { honeyBatchId, jarSize: 500, bestBeforeDate: '2027-01-31' };
await create({ ...body, acknowledgedWarnings: ['SOMETHING'] }).expect(400);
await create({
...body,
acknowledgedWarnings: [
'WATER_CONTENT_ABOVE_LEGAL',
'WATER_CONTENT_ABOVE_LEGAL',
],
}).expect(400);
});
it('a correction reports quality findings only when it changes the jar size or honey batch', async () => {
const honeyBatchId = await newBatch(17);
const created = remember(
await create({
honeyBatchId,
jarSize: 500,
bestBeforeDate: '2027-01-31',
}).expect(201),
);
await prisma.honeyBatch.update({
where: { id: honeyBatchId },
data: { waterContent: 21 },
});
const lotOnly = await auth(
api().patch(`/api/v1/bottling-batches/${created.id}`),
)
.send({ lotNumber: `BQ-L-${stamp}-${randomUUID()}` })
.expect(200);
expect((lotOnly.body as BottlingBody).warnings).toEqual([]);
const patched = await auth(
api().patch(`/api/v1/bottling-batches/${created.id}`),
)
.send({ jarSize: 250 })
.expect(200);
expect((patched.body as BottlingBody).warnings.map((w) => w.code)).toEqual([
'WATER_CONTENT_ABOVE_LEGAL',
]);
});
it('a honey measurement above the limit answers warnings and is never refused', async () => {
const honeyBatchId = await newBatch(17);
const response = await auth(
api().post(`/api/v1/honey-batches/${honeyBatchId}/measurements`),
)
.send({ waterContent: 21, measuredAt: '2026-10-01T09:00:00.000Z' })
.expect(201);
const warnings = (response.body as { warnings: Warning[] }).warnings;
expect(warnings.map((w) => w.code)).toEqual(['WATER_CONTENT_ABOVE_LEGAL']);
expect(
await prisma.honeyMeasurement.count({ where: { honeyBatchId } }),
).toBe(1);
});
it('best before comes from shelfLifeMonths and a different jar size gives a hint', async () => {
const honeyBatchId = await newBatch(17);
const productId = await newProduct({
packagingSize: 500,
shelfLifeMonths: 1,
});
const fromArticle = remember(
await create({ honeyBatchId, productId }).expect(201),
);
expect(fromArticle.jarSize).toBe(500);
// 2026-01-31 plus one month, cut at the month end.
expect(fromArticle.bestBeforeDate.slice(0, 10)).toBe('2026-02-28');
expect(fromArticle.warnings).toEqual([]);
const otherJar = remember(
await create({ honeyBatchId, productId, jarSize: 250 }).expect(201),
);
expect(otherJar.jarSize).toBe(250);
expect(otherJar.warnings.map((w) => w.code)).toEqual(['JAR_SIZE_DIFFERS']);
const sentDate = remember(
await create({
honeyBatchId,
productId,
bestBeforeDate: '2030-05-05',
}).expect(201),
);
expect(sentDate.bestBeforeDate.slice(0, 10)).toBe('2030-05-05');
});
it('refuses with a clear text when jar size and best before are unknown', async () => {
const honeyBatchId = await newBatch(17);
const noShelfLife = await newProduct({ packagingSize: 500 });
const none = await create({ honeyBatchId }).expect(400);
expect((none.body as { message: string }).message).toBe(
'Glasgröße und MHD fehlen. Bitte einen Artikel wählen oder beides eintragen.',
);
const noDate = await create({
honeyBatchId,
productId: noShelfLife,
}).expect(400);
expect((noDate.body as { message: string }).message).toBe(
'Ohne Haltbarkeit am Artikel bitte ein MHD eintragen.',
);
});
describe('GET /bottling-batches/prefill', () => {
it('prefill returns jar size and best before from the product', async () => {
const honeyBatchId = await newBatch(19);
const productId = await newProduct({
packagingSize: 250,
shelfLifeMonths: 24,
});
const response = await auth(api().get('/api/v1/bottling-batches/prefill'))
.query({ honeyBatchId, productId, date: '2026-05-10' })
.expect(200);
const prefill = response.body as PrefillBody;
expect(prefill).toMatchObject({
jarSize: 250,
jarSizeSource: 'PRODUCT',
bestBeforeDate: '2028-05-10',
shelfLifeMonths: 24,
waterContent: 19,
});
expect(prefill.warnings.map((w) => w.code)).toEqual([
'WATER_CONTENT_HIGH',
]);
// Read only.
expect(
await prisma.bottlingBatch.count({ where: { honeyBatchId } }),
).toBe(0);
});
it('without an article it still reports the water content', async () => {
const honeyBatchId = await newBatch(null);
const response = await auth(api().get('/api/v1/bottling-batches/prefill'))
.query({ honeyBatchId })
.expect(200);
const prefill = response.body as PrefillBody;
expect(prefill.jarSize).toBeNull();
expect(prefill.bestBeforeDate).toBeNull();
expect(prefill.warnings.map((w) => w.code)).toEqual([
'WATER_CONTENT_MISSING',
]);
});
it('needs bottling:create: 403 for STAFF', async () => {
const honeyBatchId = await newBatch(17);
await api()
.get('/api/v1/bottling-batches/prefill')
.set('Authorization', `Bearer ${staffToken}`)
.query({ honeyBatchId })
.expect(403);
});
it('refuses an article that is not bottled honey with 400', async () => {
const honeyBatchId = await newBatch(17);
const product = await prisma.product.create({
data: { name: `Kerze ${stamp}`, kind: 'MANUFACTURED' },
});
productIds.push(product.id);
await auth(api().get('/api/v1/bottling-batches/prefill'))
.query({ honeyBatchId, productId: product.id })
.expect(400);
});
it('answers 404 for unknown ids and 400 without a honey batch', async () => {
await auth(api().get('/api/v1/bottling-batches/prefill'))
.query({ honeyBatchId: 'missing' })
.expect(404);
await auth(api().get('/api/v1/bottling-batches/prefill')).expect(400);
});
});
});
@@ -132,6 +132,8 @@ describe('Bottling (e2e)', () => {
amount: 25,
// The movement book keeps this batch: bookings need a start amount.
initialAmount: 25,
// Below the warning limit: this file expects no quality warning.
waterContent: 17,
},
});
honeyBatchId = honeyBatch.id;
+12 -1
View File
@@ -348,7 +348,10 @@ describe('Notifications (e2e)', () => {
.set(as('bare'))
.expect(200);
expect(response.body).toEqual({
const { telegram, ...settings } = response.body as {
telegram: Record<string, unknown>;
};
expect(settings).toEqual({
taskDueEnabled: true,
digestEnabled: true,
digestTime: '06:30',
@@ -357,6 +360,14 @@ describe('Notifications (e2e)', () => {
telegramCategories: ['TASK_DUE', 'DIGEST'],
telegramDetail: true,
});
// configured / botUsername follow the environment of the process.
expect(telegram).toMatchObject({
linked: false,
firstName: null,
linkedAt: null,
enabled: false,
});
expect(typeof telegram.configured).toBe('boolean');
});
it('PATCH notification-settings stores digest time, quiet hours and Telegram categories', async () => {
+40
View File
@@ -104,4 +104,44 @@ describe('Products (e2e)', () => {
const product = response.body as ProductBody;
expect(product.status).toBe('DISCONTINUED');
});
it('keeps the shelf life in months and lets it be cleared', async () => {
const created = await request(app.getHttpServer())
.post('/api/v1/products')
.set('Authorization', `Bearer ${beekeeperToken}`)
.send({
name: `Haltbar ${Date.now()}`,
packagingSize: 500,
shelfLifeMonths: 24,
})
.expect(201);
const id = (created.body as ProductBody).id;
try {
expect(
(created.body as ProductBody & { shelfLifeMonths: number })
.shelfLifeMonths,
).toBe(24);
const cleared = await request(app.getHttpServer())
.patch(`/api/v1/products/${id}`)
.set('Authorization', `Bearer ${beekeeperToken}`)
.send({ shelfLifeMonths: null })
.expect(200);
expect(
(cleared.body as { shelfLifeMonths: number | null }).shelfLifeMonths,
).toBeNull();
} finally {
await prisma.product.deleteMany({ where: { id } });
}
});
it('rejects a shelf life outside 1 to 60 months', async () => {
for (const shelfLifeMonths of [0, 61, 1.5]) {
await request(app.getHttpServer())
.post('/api/v1/products')
.set('Authorization', `Bearer ${beekeeperToken}`)
.send({ name: `Ungültig ${Date.now()}`, shelfLifeMonths })
.expect(400);
}
});
});
+224
View File
@@ -19,6 +19,14 @@ interface FailedDeliveryBody {
[key: string]: unknown;
}
interface DeliveriesBody {
telegram: {
botNameSet: boolean;
sender: { failed24h: number };
};
deliveries: { id: string; [key: string]: unknown }[];
}
interface OverviewBody {
jobs: unknown[];
domainEvents: { failed: number; oldestPendingAgeSeconds: number | null };
@@ -234,4 +242,220 @@ describe('System API (e2e)', () => {
await prisma.webhookSubscription.delete({ where: { id: subscription.id } });
});
describe('notification deliveries (Telegram card)', () => {
const CHAT_ID = 987654321n;
let userId: string;
const createdNotificationIds: string[] = [];
const templateDeliveryIds: string[] = [];
/** A bot reply: addressed by chat id, no user, no notification. */
async function createTemplateDelivery(): Promise<string> {
const delivery = await prisma.notificationDelivery.create({
data: {
channel: 'TELEGRAM',
chatId: CHAT_ID,
templateCode: 'HELP',
status: 'FAILED',
attempts: 8,
lastError: 'HTTP 502',
},
});
templateDeliveryIds.push(delivery.id);
return delivery.id;
}
async function createDelivery(
status: 'FAILED' | 'DELIVERED',
): Promise<string> {
const notification = await prisma.notification.create({
data: {
userId,
priority: 'HINWEIS',
category: 'TASK_DUE',
message: 'private reminder text',
dedupeKey: `system-e2e:${suffix}:${createdNotificationIds.length}:${Date.now()}`,
},
});
createdNotificationIds.push(notification.id);
const delivery = await prisma.notificationDelivery.create({
data: {
channel: 'TELEGRAM',
userId,
notificationId: notification.id,
status,
attempts: status === 'FAILED' ? 8 : 1,
lastStatusCode: status === 'FAILED' ? 502 : null,
lastError: status === 'FAILED' ? 'HTTP 502' : null,
},
});
return delivery.id;
}
beforeAll(async () => {
const admin = await prisma.user.findUniqueOrThrow({
where: { email: `system-admin-${suffix}@example.com` },
select: { id: true },
});
userId = admin.id;
});
afterAll(async () => {
// Only this block's own notifications (deliveries cascade).
await prisma.notification.deleteMany({
where: { id: { in: createdNotificationIds } },
});
await prisma.notificationDelivery.deleteMany({
where: { id: { in: templateDeliveryIds } },
});
});
it('GET /system/notification-deliveries shows FAILED entries and retry moves them back to PENDING', async () => {
const failedId = await createDelivery('FAILED');
const deliveredId = await createDelivery('DELIVERED');
const templateId = await createTemplateDelivery();
const response = await request(server())
.get('/api/v1/system/notification-deliveries?status=FAILED')
.set(auth(adminToken))
.expect(200);
const body = response.body as DeliveriesBody;
const listed = body.deliveries.find((d) => d.id === failedId);
expect(listed).toMatchObject({
status: 'FAILED',
category: 'TASK_DUE',
attempts: 8,
lastStatusCode: 502,
});
expect(body.deliveries.some((d) => d.id === deliveredId)).toBe(false);
expect(body.deliveries.find((d) => d.id === templateId)).toMatchObject({
category: null,
templateCode: 'HELP',
});
expect(typeof body.telegram.botNameSet).toBe('boolean');
expect(body.telegram.sender.failed24h).toBeGreaterThanOrEqual(1);
const raw = JSON.stringify(body);
expect(raw).not.toContain(CHAT_ID.toString());
expect(raw).not.toContain('private reminder text');
expect(listed).not.toHaveProperty('chatId');
await request(server())
.get('/api/v1/system/notification-deliveries?status=NOPE')
.set(auth(adminToken))
.expect(400);
await request(server())
.post(`/api/v1/system/notification-deliveries/${failedId}/retry`)
.set(auth(adminToken))
.expect(204);
const reset = await prisma.notificationDelivery.findUniqueOrThrow({
where: { id: failedId },
});
expect(reset).toMatchObject({
status: 'PENDING',
attempts: 0,
lastError: null,
lastStatusCode: null,
claimedAt: null,
});
expect(reset.availableAt.getTime()).toBeLessThanOrEqual(
Date.now() + 5_000,
);
await expect(
prisma.auditLog.count({
where: { entityType: 'NotificationDelivery', entityId: failedId },
}),
).resolves.toBe(1);
// PENDING is not FAILED any more, a DELIVERED one never was.
await request(server())
.post(`/api/v1/system/notification-deliveries/${failedId}/retry`)
.set(auth(adminToken))
.expect(409);
await request(server())
.post(`/api/v1/system/notification-deliveries/${deliveredId}/retry`)
.set(auth(adminToken))
.expect(409);
await request(server())
.post('/api/v1/system/notification-deliveries/does-not-exist/retry')
.set(auth(adminToken))
.expect(404);
});
it('retry-failed requeues the FAILED entries and reports how many', async () => {
const own = [
await createDelivery('FAILED'),
await createDelivery('FAILED'),
];
// Other files share this DB: remember their FAILED rows to restore them.
const others = await prisma.notificationDelivery.findMany({
where: { status: 'FAILED', id: { notIn: own } },
});
const ownAudits = () =>
prisma.auditLog.count({
where: { entityType: 'NotificationDelivery', entityId: { in: own } },
});
try {
const response = await request(server())
.post('/api/v1/system/notification-deliveries/retry-failed')
.set(auth(adminToken))
.expect(200);
expect(
(response.body as { retried: number }).retried,
).toBeGreaterThanOrEqual(2);
const rows = await prisma.notificationDelivery.findMany({
where: { id: { in: own } },
select: { status: true, attempts: true },
});
expect(rows).toEqual([
{ status: 'PENDING', attempts: 0 },
{ status: 'PENDING', attempts: 0 },
]);
await expect(ownAudits()).resolves.toBe(2);
// A second call leaves the own rows alone: no new audit rows.
await request(server())
.post('/api/v1/system/notification-deliveries/retry-failed')
.set(auth(adminToken))
.expect(200);
await expect(
prisma.notificationDelivery.count({
where: { id: { in: own }, status: 'PENDING' },
}),
).resolves.toBe(2);
await expect(ownAudits()).resolves.toBe(2);
} finally {
for (const row of others) {
await prisma.notificationDelivery.updateMany({
where: { id: row.id },
data: {
status: row.status,
attempts: row.attempts,
availableAt: row.availableAt,
claimedAt: row.claimedAt,
lastStatusCode: row.lastStatusCode,
lastError: row.lastError,
},
});
}
}
});
it('staff without system:manage gets 403', async () => {
await request(server())
.get('/api/v1/system/notification-deliveries')
.set(auth(staffToken))
.expect(403);
await request(server())
.post('/api/v1/system/notification-deliveries/x/retry')
.set(auth(staffToken))
.expect(403);
await request(server())
.post('/api/v1/system/notification-deliveries/retry-failed')
.set(auth(staffToken))
.expect(403);
});
});
});
+527
View File
@@ -1,5 +1,7 @@
import { createHash } from 'node:crypto';
import { INestApplication } from '@nestjs/common';
import * as bcrypt from 'bcryptjs';
import request from 'supertest';
import { App } from 'supertest/types';
import type { NotificationCategory } from '../generated/prisma';
import { berlinDateTime, berlinToday, dayToDate } from '../src/common/dates';
@@ -11,7 +13,11 @@ import {
} from '../src/notifications/delivery-time';
import { NotificationsService } from '../src/notifications/notifications.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { TelegramClient } from '../src/telegram/telegram-client';
import { TelegramLinkService } from '../src/telegram/telegram-link.service';
import { TelegramSender } from '../src/telegram/telegram-sender';
import { TelegramUpdatesService } from '../src/telegram/telegram-updates.service';
import { login } from './utils/api';
import { drainDomainEvents } from './utils/domain-events';
import { createTelegramTestApp, FakeTelegramClient } from './utils/telegram';
@@ -489,4 +495,525 @@ describe('Telegram delivery (e2e)', () => {
).toBeGreaterThanOrEqual(1_000);
});
});
describe('connect, disconnect and receive', () => {
const PASSWORD = 'SuperSecret123!';
const API = '/api/v1';
const BOT = 'apicore_e2e_bot';
const OFFSET_BASE = 9_000;
const originalUsername = process.env.TELEGRAM_BOT_USERNAME;
let updates: TelegramUpdatesService;
let nextUpdateId = OFFSET_BASE;
let savedPollState: {
updateOffset: bigint;
leaseOwner: string | null;
leaseUntil: Date | null;
};
const emailOf = (label: string) =>
`telegram-e2e-${label}-${suffix}@example.com`;
async function tokenOf(label: string): Promise<string> {
return (await login(app, emailOf(label), PASSWORD)).accessToken;
}
function requestLinkToken(
accessToken: string,
body: object = { password: PASSWORD },
) {
return request(app.getHttpServer())
.post(`${API}/profile/telegram/link-token`)
.set('Authorization', `Bearer ${accessToken}`)
.send(body);
}
/**
* A link token for the user, made by the service (the route's budget of
* 10 per minute is kept for the tests of the route itself).
*/
async function newLinkToken(userId: string): Promise<string> {
const { deepLink } = await app
.get(TelegramLinkService)
.createLinkToken(userId);
return deepLink.slice(`https://t.me/${BOT}?start=`.length);
}
function say(
chatId: bigint,
text: string,
options: { chatType?: string; firstName?: string } = {},
): void {
telegram.queueUpdate({
updateId: BigInt(nextUpdateId++),
chatId,
chatType: options.chatType ?? 'private',
text,
firstName: options.firstName ?? 'Anna',
});
}
/** Fresh poll state: the offset where the next update id starts, no lease. */
async function resetPollState(): Promise<void> {
await prisma.telegramPollState.update({
where: { id: 'singleton' },
data: {
updateOffset: BigInt(nextUpdateId),
leaseOwner: null,
leaseUntil: null,
},
});
}
const repliesTo = async (chatId: bigint) =>
(
await prisma.notificationDelivery.findMany({
where: { chatId },
orderBy: { createdAt: 'asc' },
})
).map((row) => row.templateCode);
const poll = () => updates.pollOnce(NEVER_ABORTED);
/** A user without Telegram link and with Telegram switched off. */
async function createUnlinkedUser(label: string) {
const user = await createUser(label, [], {}, false);
await prisma.notificationPreference.update({
where: { userId: user.id },
data: { telegramEnabled: false },
});
return user;
}
beforeAll(async () => {
process.env.TELEGRAM_BOT_USERNAME = BOT;
updates = app.get(TelegramUpdatesService);
savedPollState = await prisma.telegramPollState.findUniqueOrThrow({
where: { id: 'singleton' },
select: { updateOffset: true, leaseOwner: true, leaseUntil: true },
});
});
afterAll(async () => {
if (originalUsername === undefined) {
delete process.env.TELEGRAM_BOT_USERNAME;
} else {
process.env.TELEGRAM_BOT_USERNAME = originalUsername;
}
await prisma.telegramPollState.update({
where: { id: 'singleton' },
data: { ...savedPollState, lastError: null },
});
await prisma.notificationDelivery.deleteMany({
where: { chatId: { gte: chatBase, lte: chatBase + 10_000n } },
});
// Logins of this block leave refresh tokens behind.
await prisma.refreshToken.deleteMany({
where: { userId: { in: userIds } },
});
});
beforeEach(async () => {
await resetPollState();
telegram.sent.length = 0;
});
it('link token -> /start links the chat once; a second /start with the same token answers LINK_INVALID', async () => {
const user = await createUnlinkedUser('connect');
const accessToken = await tokenOf('connect');
const response = await requestLinkToken(accessToken).expect(201);
// The answer holds a secret: never cached.
expect(response.headers['cache-control']).toBe('no-store');
const { deepLink, expiresAt } = response.body as {
deepLink: string;
expiresAt: string;
};
expect(deepLink).toMatch(
new RegExp(`^https://t\\.me/${BOT}\\?start=[A-Za-z0-9_-]{43}$`),
);
const token = deepLink.slice(`https://t.me/${BOT}?start=`.length);
// Ten minutes from the database clock; only the hash is stored.
const ttlMs = new Date(expiresAt).getTime() - Date.now();
expect(ttlMs).toBeGreaterThan(9 * 60_000);
expect(ttlMs).toBeLessThanOrEqual(10 * 60_000 + CLOCK_TOLERANCE_MS);
const stored = await prisma.telegramLinkToken.findMany({
where: { userId: user.id },
});
expect(stored).toHaveLength(1);
expect(stored[0].tokenHash).toBe(
createHash('sha256').update(token).digest('hex'),
);
expect(stored[0].tokenHash).not.toBe(token);
say(user.chatId, `/start ${token}`, { firstName: 'Anna' });
await expect(poll()).resolves.toBe('polled');
const link = await prisma.telegramLink.findUniqueOrThrow({
where: { userId: user.id },
});
expect(link.chatId).toBe(user.chatId);
expect(link.telegramFirstName).toBe('Anna');
const preference = await prisma.notificationPreference.findUniqueOrThrow({
where: { userId: user.id },
});
expect(preference.telegramEnabled).toBe(true);
const notice = await prisma.notification.findFirstOrThrow({
where: { userId: user.id, category: 'SYSTEM' },
});
expect(notice.message).toMatch(
/^Telegram verbunden mit „Anna“ am \d{2}\.\d{2}\.\d{4}\. Warst du das nicht\? In den Einstellungen trennen\.$/,
);
expect(notice.link).toBe('/profile');
expect(await repliesTo(user.chatId)).toEqual(['LINKED']);
const state = await prisma.telegramPollState.findUniqueOrThrow({
where: { id: 'singleton' },
});
expect(state.updateOffset).toBe(BigInt(nextUpdateId));
expect(state.lastPollAt).not.toBeNull();
// The same token again - from the same or another chat - is spent.
const stranger = chatBase + 9_001n;
say(user.chatId, `/start ${token}`);
say(stranger, `/start ${token}`);
await poll();
expect(await repliesTo(user.chatId)).toEqual(['LINKED', 'LINK_INVALID']);
expect(await repliesTo(stranger)).toEqual(['LINK_INVALID']);
expect(
await prisma.telegramLink.count({ where: { chatId: stranger } }),
).toBe(0);
});
it('a new link token makes the older open one invalid, and a chat that moves unlinks the previous user', async () => {
const first = await createUnlinkedUser('move-a');
const second = await createUnlinkedUser('move-b');
const old = await newLinkToken(first.id);
const fresh = await newLinkToken(first.id);
const other = await newLinkToken(second.id);
say(first.chatId, `/start ${old}`);
say(first.chatId, `/start ${fresh}`);
await poll();
expect(await repliesTo(first.chatId)).toEqual(['LINK_INVALID', 'LINKED']);
// User B connects from the chat of user A.
say(first.chatId, `/start ${other}`);
await poll();
const links = await prisma.telegramLink.findMany({
where: { userId: { in: [first.id, second.id] } },
});
expect(links).toHaveLength(1);
expect(links[0].userId).toBe(second.id);
expect(links[0].chatId).toBe(first.chatId);
const previous = await prisma.notificationPreference.findUniqueOrThrow({
where: { userId: first.id },
});
expect(previous.telegramEnabled).toBe(false);
const notice = await prisma.notification.findFirstOrThrow({
where: { userId: first.id, message: { contains: 'getrennt' } },
});
expect(notice.message).toBe(
'Deine Telegram-Verbindung wurde getrennt, weil der Chat mit einem anderen Konto verbunden wurde.',
);
});
it('link-token answers 409 when the bot username is not set', async () => {
await createUnlinkedUser('nobot');
const accessToken = await tokenOf('nobot');
process.env.TELEGRAM_BOT_USERNAME = '';
try {
const response = await requestLinkToken(accessToken).expect(409);
expect((response.body as { message: string }).message).toBe(
'Telegram ist nicht eingerichtet.',
);
} finally {
process.env.TELEGRAM_BOT_USERNAME = BOT;
}
});
it('only the lease holder polls; a second worker waits', async () => {
const links = app.get(TelegramLinkService);
const workerA = new TelegramUpdatesService(
prisma,
telegram as unknown as TelegramClient,
links,
);
const workerB = new TelegramUpdatesService(
prisma,
telegram as unknown as TelegramClient,
links,
);
telegram.polledOffsets.length = 0;
await expect(workerA.pollOnce(NEVER_ABORTED)).resolves.toBe('polled');
await expect(workerB.pollOnce(NEVER_ABORTED)).resolves.toBe('no-lease');
expect(telegram.polledOffsets).toHaveLength(1);
// Every round extends the holder's lease.
await expect(workerA.pollOnce(NEVER_ABORTED)).resolves.toBe('polled');
await expect(workerB.pollOnce(NEVER_ABORTED)).resolves.toBe('no-lease');
// An expired lease (database clock) passes to the next one.
await prisma.$executeRaw`UPDATE "TelegramPollState" SET "leaseUntil" = now() - interval '1 second' WHERE "id" = 'singleton'`;
await expect(workerB.pollOnce(NEVER_ABORTED)).resolves.toBe('polled');
await expect(workerA.pollOnce(NEVER_ABORTED)).resolves.toBe('no-lease');
});
it('a lease lost during the cycle rolls the update back and the next holder handles it once', async () => {
const user = await createUnlinkedUser('lostlease');
const token = await newLinkToken(user.id);
say(user.chatId, `/start ${token}`);
// Another receiver takes over right after the updates were fetched.
telegram.onGetUpdates = async () => {
await prisma.telegramPollState.update({
where: { id: 'singleton' },
data: { leaseOwner: 'someone-else' },
});
};
try {
await expect(poll()).resolves.toBe('no-lease');
} finally {
telegram.onGetUpdates = null;
}
expect(
await prisma.telegramLink.count({ where: { userId: user.id } }),
).toBe(0);
expect(await repliesTo(user.chatId)).toEqual([]);
const open = await prisma.telegramLinkToken.findFirstOrThrow({
where: { userId: user.id },
});
expect(open.consumedAt).toBeNull();
const state = await prisma.telegramPollState.findUniqueOrThrow({
where: { id: 'singleton' },
});
expect(state.updateOffset).toBe(BigInt(nextUpdateId - 1));
// The other lease ran out: the update is handled, exactly once.
await prisma.$executeRaw`UPDATE "TelegramPollState" SET "leaseUntil" = now() - interval '1 second' WHERE "id" = 'singleton'`;
await expect(poll()).resolves.toBe('polled');
await expect(poll()).resolves.toBe('polled');
expect(await repliesTo(user.chatId)).toEqual(['LINKED']);
});
it('/stop in the chat unlinks, and groups are ignored', async () => {
const user = await createUser('stopchat', []);
const group = chatBase + 9_100n;
say(group, '/stop', { chatType: 'group' });
say(group, '/start abc', { chatType: 'supergroup' });
say(user.chatId, '/stop');
await poll();
expect(
await prisma.telegramLink.count({ where: { userId: user.id } }),
).toBe(0);
const preference = await prisma.notificationPreference.findUniqueOrThrow({
where: { userId: user.id },
});
expect(preference.telegramEnabled).toBe(false);
expect(await repliesTo(user.chatId)).toEqual(['STOPPED']);
expect(await repliesTo(group)).toEqual([]);
});
it('unlink sends STOPPED and switches Telegram off', async () => {
const user = await createUser('unlink', []);
const accessToken = await tokenOf('unlink');
const view = await request(app.getHttpServer())
.get(`${API}/profile/notification-settings`)
.set('Authorization', `Bearer ${accessToken}`)
.expect(200);
expect((view.body as { telegram: object }).telegram).toMatchObject({
configured: true,
botUsername: BOT,
linked: true,
firstName: 'unlink',
enabled: true,
});
expect(JSON.stringify(view.body)).not.toContain(String(user.chatId));
// A message still waiting for the old chat must never arrive later.
const waiting = await queue(user.id, { message: 'wartet noch' });
await request(app.getHttpServer())
.post(`${API}/profile/telegram/unlink`)
.set('Authorization', `Bearer ${accessToken}`)
.expect(204);
expect(
await prisma.telegramLink.count({ where: { userId: user.id } }),
).toBe(0);
const dropped = await prisma.notificationDelivery.findUniqueOrThrow({
where: { id: waiting.deliveryId },
});
expect(dropped.status).toBe('SKIPPED');
expect(dropped.lastError).toBe('unlinked');
await drainFor(user.id);
expect(telegram.sentTo(user.chatId)).toHaveLength(0);
const preference = await prisma.notificationPreference.findUniqueOrThrow({
where: { userId: user.id },
});
expect(preference.telegramEnabled).toBe(false);
expect(await repliesTo(user.chatId)).toEqual(['STOPPED']);
// Unlinking again changes nothing.
await request(app.getHttpServer())
.post(`${API}/profile/telegram/unlink`)
.set('Authorization', `Bearer ${accessToken}`)
.expect(204);
expect(await repliesTo(user.chatId)).toEqual(['STOPPED']);
await request(app.getHttpServer())
.post(`${API}/profile/telegram/unlink`)
.expect(401);
});
it('the same token claimed at once by two different chats links exactly one', async () => {
const user = await createUnlinkedUser('race-chats');
const token = await newLinkToken(user.id);
const links = app.get(TelegramLinkService);
const chatA = chatBase + 9_200n;
const chatB = chatBase + 9_201n;
const results = await Promise.all(
[chatA, chatB].map((chat) =>
prisma.$transaction((tx) =>
links.linkFromStartIn(tx, token, chat, 'Racer'),
),
),
);
expect([...results].sort()).toEqual(['LINKED', 'LINK_INVALID']);
const stored = await prisma.telegramLink.findMany({
where: { chatId: { in: [chatA, chatB] } },
});
expect(stored).toHaveLength(1);
expect(stored[0].userId).toBe(user.id);
});
it('two /start with the same token and chat in separate transactions: exactly one LINKED', async () => {
const user = await createUnlinkedUser('race-same');
const token = await newLinkToken(user.id);
const links = app.get(TelegramLinkService);
const results = await Promise.all(
[1, 2].map(() =>
prisma.$transaction((tx) =>
links.linkFromStartIn(tx, token, user.chatId, 'Racer'),
),
),
);
expect([...results].sort()).toEqual(['LINKED', 'LINK_INVALID']);
expect(
await prisma.telegramLink.count({ where: { userId: user.id } }),
).toBe(1);
expect(
await prisma.notification.count({
where: {
userId: user.id,
message: { startsWith: 'Telegram verbunden' },
},
}),
).toBe(1);
});
it('an expired token answers LINK_INVALID and links nothing', async () => {
const user = await createUnlinkedUser('expired');
const token = await newLinkToken(user.id);
await prisma.$executeRaw`UPDATE "TelegramLinkToken" SET "expiresAt" = now() - interval '1 minute' WHERE "userId" = ${user.id}`;
say(user.chatId, `/start ${token}`);
await poll();
expect(await repliesTo(user.chatId)).toEqual(['LINK_INVALID']);
expect(
await prisma.telegramLink.count({ where: { userId: user.id } }),
).toBe(0);
const row = await prisma.telegramLinkToken.findFirstOrThrow({
where: { userId: user.id },
});
expect(row.consumedAt).toBeNull();
});
it('a poison update is skipped after the attempt limit and the queue moves on', async () => {
const user = await createUser('poison', []);
const other = chatBase + 9_300n;
const links = app.get(TelegramLinkService);
const stop = jest
.spyOn(links, 'stopIn')
.mockRejectedValue(new Error('boom'));
updates.retryLimits = { attempts: 2, windowMs: 600_000 };
const first = nextUpdateId;
say(user.chatId, '/stop');
say(other, 'hallo');
try {
await expect(poll()).resolves.toBe('error');
const failing = await prisma.telegramPollState.findUniqueOrThrow({
where: { id: 'singleton' },
});
expect(failing.updateOffset).toBe(BigInt(first));
expect(failing.lastError).toBe('update not handled: Error');
await expect(poll()).resolves.toBe('polled');
} finally {
stop.mockRestore();
updates.retryLimits = { attempts: 5, windowMs: 600_000 };
}
const state = await prisma.telegramPollState.findUniqueOrThrow({
where: { id: 'singleton' },
});
expect(state.updateOffset).toBe(BigInt(nextUpdateId));
expect(state.lastError).toBe('Telegram-Nachricht übersprungen');
// The skipped /stop did nothing; the update behind it was answered.
expect(
await prisma.telegramLink.count({ where: { userId: user.id } }),
).toBe(1);
expect(await repliesTo(other)).toEqual(['HELP']);
// A clean batch afterwards clears the notice.
await poll();
const cleared = await prisma.telegramPollState.findUniqueOrThrow({
where: { id: 'singleton' },
});
expect(cleared.lastError).toBeNull();
});
// Last on purpose: it uses up the 10-per-minute budget of the route.
it('link-token requires step-up and is throttled', async () => {
await createUnlinkedUser('stepup');
const accessToken = await tokenOf('stepup');
await request(app.getHttpServer())
.post(`${API}/profile/telegram/link-token`)
.send({ password: PASSWORD })
.expect(401);
// A missing password is a malformed request.
await requestLinkToken(accessToken, {}).expect(400);
await requestLinkToken(accessToken, {
password: 'wrong-password',
}).expect(401);
expect(
await prisma.telegramLinkToken.count({
where: { user: { email: emailOf('stepup') } },
}),
).toBe(0);
// 10 per minute: the 429 arrives within 11 attempts, after 401s only.
const statuses: number[] = [];
for (
let attempt = 0;
attempt < 11 && !statuses.includes(429);
attempt++
) {
const { status } = await requestLinkToken(accessToken, {
password: 'wrong-password',
});
statuses.push(status);
}
expect(statuses.at(-1)).toBe(429);
expect(statuses.slice(0, -1).every((status) => status === 401)).toBe(
true,
);
});
});
});
+39 -1
View File
@@ -7,7 +7,11 @@ import { AppModule } from '../../src/app.module';
import { configureApp } from '../../src/app.config';
import { THROTTLER_NAMESPACE } from '../../src/common/throttler/prisma-throttler.storage';
import { TelegramApiError } from '../../src/telegram/telegram-api-error';
import { TelegramClient } from '../../src/telegram/telegram-client';
import {
TelegramClient,
type TelegramUpdate,
type TelegramUpdateBatch,
} from '../../src/telegram/telegram-client';
import { TelegramModule } from '../../src/telegram/telegram.module';
export interface SentMessage {
@@ -23,6 +27,12 @@ export interface SentMessage {
export class FakeTelegramClient {
readonly sent: SentMessage[] = [];
private readonly failures: { chatId: bigint | null; error: Error }[] = [];
private readonly updates: TelegramUpdate[] = [];
/** Every offset getUpdates was asked for, in order. */
readonly polledOffsets: bigint[] = [];
/** Runs inside getUpdates, after the updates are chosen (e.g. steal the lease). */
onGetUpdates: (() => Promise<void>) | null = null;
private getUpdatesError: Error | null = null;
isConfigured(): boolean {
return true;
@@ -47,6 +57,34 @@ export class FakeTelegramClient {
return Promise.resolve();
}
/** What the next getUpdates calls return (from `offset` on, like Telegram). */
queueUpdate(update: TelegramUpdate): void {
this.updates.push(update);
}
failNextGetUpdates(error: Error): void {
this.getUpdatesError = error;
}
async getUpdates(offset: bigint): Promise<TelegramUpdateBatch> {
this.polledOffsets.push(offset);
if (this.getUpdatesError !== null) {
const error = this.getUpdatesError;
this.getUpdatesError = null;
throw error;
}
const due = this.updates.filter((update) => update.updateId >= offset);
await this.onGetUpdates?.();
const highestUpdateId = due.reduce<bigint | null>(
(highest, update) =>
highest === null || update.updateId > highest
? update.updateId
: highest,
null,
);
return { updates: due, highestUpdateId };
}
sentTo(chatId: bigint): SentMessage[] {
return this.sent.filter((message) => message.chatId === chatId);
}
@@ -308,6 +308,7 @@ describe('Withdrawal chain (e2e)', () => {
batchNumber: `WD-HC-${suffix}`,
extractionId: extraction.id,
amount: 20,
waterContent: 17,
},
});
honeyBatchIds.push(honeyBatch.id);
@@ -0,0 +1,52 @@
import { describe, expect, it, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { fetchApiary } from "@/lib/apiaries/api";
import ApiaryDetailPage from "./page";
vi.mock("next/navigation", () => ({ useParams: () => ({ id: "a-1" }) }));
vi.mock("@/lib/apiaries/api", () => ({ fetchApiary: vi.fn() }));
vi.mock("@/lib/export/api", () => ({
exportApiaryAnnualReportPdf: vi.fn(),
exportTreatmentLogPdf: vi.fn(),
}));
vi.mock("@/components/qr-code-dialog", () => ({ QrCodeDialog: () => null }));
vi.mock("@/components/document-upload-card", () => ({ DocumentUploadCard: () => null }));
vi.mock("@/components/detail-header", () => ({
DetailHeader: ({ title }: { title: string }) => <h1>{title}</h1>,
DetailQueryFallback: () => <p>Lädt</p>,
DetailStatus: () => null,
}));
vi.mock("./apiary-colonies-card", () => ({
ApiaryColoniesCard: () => null,
StartRoundButton: () => null,
}));
vi.mock("./apiary-edit-card", () => ({ ApiaryEditCard: () => null }));
vi.mock("./weather-card", () => ({ WeatherCard: () => null }));
vi.mock("@/components/phenology/apiary-season", () => ({
ApiarySeason: ({ apiary }: { apiary: { id: string; name: string } }) => (
<p>Saison von {apiary.name}</p>
),
}));
describe("ApiaryDetailPage", () => {
it("shows the season of the apiary below the header", async () => {
vi.mocked(fetchApiary).mockResolvedValue({
id: "a-1",
name: "Obstwiese",
location: null,
status: "ACTIVE",
latitude: null,
longitude: null,
} as never);
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(
<QueryClientProvider client={client}>
<ApiaryDetailPage />
</QueryClientProvider>,
);
expect(await screen.findByText("Saison von Obstwiese")).toBeInTheDocument();
});
});
@@ -8,6 +8,7 @@ import { fetchApiary } from "@/lib/apiaries/api";
import { exportApiaryAnnualReportPdf, exportTreatmentLogPdf } from "@/lib/export/api";
import { QrCodeDialog } from "@/components/qr-code-dialog";
import { DocumentUploadCard } from "@/components/document-upload-card";
import { ApiarySeason } from "@/components/phenology/apiary-season";
import { DetailHeader, DetailQueryFallback, DetailStatus } from "@/components/detail-header";
import { ApiaryColoniesCard, StartRoundButton } from "./apiary-colonies-card";
import { ApiaryEditCard } from "./apiary-edit-card";
@@ -76,6 +77,7 @@ export default function ApiaryDetailPage() {
]}
{...BACK}
/>
<ApiarySeason apiary={{ id: apiary.id, name: apiary.name }} />
<div className="grid grid-cols-1 items-start gap-4 lg:grid-cols-2">
<div className="flex flex-col gap-4">
<ApiaryColoniesCard apiary={{ id: apiary.id, name: apiary.name }} />
@@ -3,8 +3,9 @@ import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import NewExtractionPage from "./page";
import { createExtraction } from "@/lib/extractions/api";
import { createExtraction, fetchExtractionPrefill } from "@/lib/extractions/api";
import { fetchHarvests } from "@/lib/harvests/api";
import { toastWarnings } from "@/lib/warnings/toast-warnings";
const push = vi.fn();
vi.mock("next/navigation", () => ({
@@ -12,7 +13,11 @@ vi.mock("next/navigation", () => ({
useSearchParams: () => new URLSearchParams(),
}));
vi.mock("@/lib/harvests/api", () => ({ fetchHarvests: vi.fn() }));
vi.mock("@/lib/extractions/api", () => ({ createExtraction: vi.fn() }));
vi.mock("@/lib/extractions/api", () => ({
createExtraction: vi.fn(),
fetchExtractionPrefill: vi.fn(),
}));
vi.mock("@/lib/warnings/toast-warnings", () => ({ toastWarnings: vi.fn() }));
function renderPage() {
const client = new QueryClient({
@@ -35,7 +40,20 @@ describe("NewExtractionPage", () => {
date: "2026-07-01T00:00:00.000Z",
colonies: [{ colony: { code: "V-01" } }],
},
{
id: "harvest-2",
date: "2026-07-02T00:00:00.000Z",
colonies: [{ colony: { code: "V-02" } }],
},
] as never);
vi.mocked(fetchExtractionPrefill).mockReset();
vi.mocked(fetchExtractionPrefill).mockResolvedValue({
amountKg: null,
honeyType: null,
sources: [],
warnings: [],
});
vi.mocked(toastWarnings).mockReset();
vi.mocked(createExtraction).mockReset();
});
@@ -80,4 +98,75 @@ describe("NewExtractionPage", () => {
expect(screen.getByRole("group", { name: /^Ernten/ })).toHaveFocus();
expect(createExtraction).not.toHaveBeenCalled();
});
it("offers „Vorschlag aus 2 Ernten: 42,5 kg · übernehmen“ and fills only on tap", async () => {
vi.mocked(fetchExtractionPrefill).mockResolvedValue({
amountKg: 42.5,
honeyType: null,
sources: [],
warnings: [],
});
renderPage();
await userEvent.click(await screen.findByRole("checkbox", { name: /V-01/ }));
await userEvent.click(screen.getByRole("checkbox", { name: /V-02/ }));
expect(await screen.findByText(/Vorschlag aus 2 Ernten: 42,5 kg/)).toBeInTheDocument();
expect(fetchExtractionPrefill).toHaveBeenLastCalledWith(["harvest-1", "harvest-2"]);
expect(screen.getByLabelText(/Menge/)).toHaveValue(null);
await userEvent.click(screen.getByRole("button", { name: /übernehmen/ }));
expect(screen.getByLabelText(/Menge/)).toHaveValue(42.5);
});
it("keeps a note when the hints could not be loaded and lets the save through", async () => {
vi.mocked(fetchExtractionPrefill).mockRejectedValue(new Error("down"));
renderPage();
await userEvent.click(await screen.findByRole("checkbox", { name: /V-01/ }));
expect(
await screen.findByText(/Hinweise \(z\. B\. Wartezeit\) konnten nicht geladen werden/),
).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Erneut versuchen" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Schleuderung speichern" })).toBeEnabled();
});
it("shows the plausibility warnings above „Schleuderung speichern“", async () => {
vi.mocked(fetchExtractionPrefill).mockResolvedValue({
amountKg: null,
honeyType: null,
sources: [],
warnings: [
{
code: "WITHDRAWAL_ACTIVE",
severity: "WARNUNG",
message: "Volk V-01 ist noch in der Wartezeit.",
refs: [],
},
],
});
renderPage();
await userEvent.click(await screen.findByRole("checkbox", { name: /V-01/ }));
const warning = await screen.findByText("Volk V-01 ist noch in der Wartezeit.");
const save = screen.getByRole("button", { name: "Schleuderung speichern" });
expect(
warning.compareDocumentPosition(save) & Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
});
it("keeps the warnings of the save in a toast that stays", async () => {
const warnings = [
{ code: "WITHDRAWAL_ACTIVE", severity: "WARNUNG", message: "Wartezeit", refs: [] },
];
vi.mocked(createExtraction).mockResolvedValue({ id: "e-1", warnings } as never);
renderPage();
await userEvent.click(await screen.findByRole("checkbox", { name: /V-01/ }));
await userEvent.click(screen.getByRole("button", { name: "Schleuderung speichern" }));
expect(toastWarnings).toHaveBeenCalledWith(warnings, "Schleuderung gespeichert");
});
});
@@ -6,7 +6,15 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Droplet } from "lucide-react";
import { fetchHarvests } from "@/lib/harvests/api";
import { createExtraction } from "@/lib/extractions/api";
import {
createExtraction,
fetchExtractionPrefill,
} from "@/lib/extractions/api";
import { formatKg } from "@/lib/honey-batches/movements";
import { toastWarnings } from "@/lib/warnings/toast-warnings";
import { WarningList } from "@/components/warnings/warning-list";
import { PrefillStatus } from "@/components/warnings/prefill-status";
import { PreviousValueHint } from "@/components/form/previous-value-hint";
import { useFormDraft } from "@/lib/forms/use-form-draft";
import { errorMessage } from "@/lib/forms/error-message";
import { Button } from "@/components/ui/button";
@@ -58,6 +66,16 @@ export default function NewExtractionPage() {
const [submitError, setSubmitError] = useState<string | null>(null);
const draft = useFormDraft("extraction-new", values, dirty);
// A proposal from the chosen harvests: shown with a take-over button, never
// written into the field by itself. Its warnings are the ones the save
// will answer, so they are visible before "Speichern".
const prefillQuery = useQuery({
queryKey: ["extractions", "prefill", values.harvestIds],
queryFn: () => fetchExtractionPrefill(values.harvestIds),
enabled: values.harvestIds.length > 0,
});
const prefill = values.harvestIds.length > 0 ? prefillQuery.data : undefined;
function set<K extends keyof ExtractionFormValues>(
key: K,
value: ExtractionFormValues[K],
@@ -83,7 +101,11 @@ export default function NewExtractionPage() {
onSuccess: (extraction) => {
draft.clear();
void queryClient.invalidateQueries({ queryKey: ["extractions"] });
toast.success("Schleuderung gespeichert");
if (extraction.warnings?.length) {
toastWarnings(extraction.warnings, "Schleuderung gespeichert");
} else {
toast.success("Schleuderung gespeichert");
}
router.push(`/extractions/${extraction.id}`);
},
onError: (mutationError) => {
@@ -203,17 +225,32 @@ export default function NewExtractionPage() {
<FormSection step={2} title="Ergebnis">
<Field label="Menge (kg)" hint="Geschleuderter Honig, ohne Eimer.">
{({ id, describedBy }) => (
<Input
id={id}
aria-describedby={describedBy}
type="number"
inputMode="decimal"
min={0}
step="any"
className="h-11"
value={values.amount}
onChange={(event) => set("amount", event.target.value)}
/>
<>
<Input
id={id}
aria-describedby={describedBy}
type="number"
inputMode="decimal"
min={0}
step="any"
className="h-11"
value={values.amount}
onChange={(event) => set("amount", event.target.value)}
/>
{prefill?.amountKg != null &&
values.amount !== String(prefill.amountKg) ? (
<PreviousValueHint
fieldLabel="Menge"
valueLabel={formatKg(prefill.amountKg)}
prefix={`Vorschlag aus ${values.harvestIds.length} ${
values.harvestIds.length === 1 ? "Ernte" : "Ernten"
}`}
onTakeOver={() =>
set("amount", String(prefill.amountKg))
}
/>
) : null}
</>
)}
</Field>
<Field
@@ -267,6 +304,15 @@ export default function NewExtractionPage() {
</Field>
</FormSection>
<PrefillStatus
enabled={values.harvestIds.length > 0}
isLoading={prefillQuery.isLoading}
isError={prefillQuery.isError}
isRetrying={prefillQuery.isFetching}
onRetry={() => void prefillQuery.refetch()}
/>
<WarningList warnings={prefill?.warnings ?? []} />
<StickySubmit
note={
submitError ? (
@@ -0,0 +1,74 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { CorrectAmountDialog } from "./correct-amount-dialog";
import { bookHoneyBatchMovement } from "@/lib/honey-batches/api";
import { ApiError } from "@/lib/auth/api-client";
vi.mock("@/lib/honey-batches/api", () => ({ bookHoneyBatchMovement: vi.fn() }));
function renderDialog(amount = 20) {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<QueryClientProvider client={client}>
<CorrectAmountDialog honeyBatchId="h1" amount={amount} />
</QueryClientProvider>,
);
}
describe("CorrectAmountDialog", () => {
beforeEach(() => {
vi.mocked(bookHoneyBatchMovement).mockReset();
});
it("books nothing while the weighed amount equals the booked one", async () => {
renderDialog();
await userEvent.click(screen.getByRole("button", { name: /Menge korrigieren/ }));
expect(await screen.findByRole("button", { name: "Korrektur buchen" })).toBeDisabled();
});
it("says Keine Abweichung when nothing differs", async () => {
renderDialog();
await userEvent.click(screen.getByRole("button", { name: /Menge korrigieren/ }));
expect(await screen.findByText("Keine Abweichung")).toBeInTheDocument();
});
it("shows the message of a 409 and the field text of a 400", async () => {
renderDialog();
await userEvent.click(screen.getByRole("button", { name: /Menge korrigieren/ }));
const input = await screen.findByLabelText(/Neu gewogen/);
await userEvent.clear(input);
await userEvent.type(input, "19");
vi.mocked(bookHoneyBatchMovement).mockRejectedValueOnce(new ApiError(409, "Gerade geändert.", {}));
await userEvent.click(screen.getByRole("button", { name: "Korrektur buchen" }));
expect(await screen.findByRole("alert")).toHaveTextContent("Gerade geändert.");
vi.mocked(bookHoneyBatchMovement).mockRejectedValueOnce(
new ApiError(400, "Bad", { issues: [{ field: "deltaKg", message: "Menge nicht erlaubt." }] }),
);
await userEvent.click(screen.getByRole("button", { name: "Korrektur buchen" }));
expect(await screen.findByText("Menge nicht erlaubt.")).toBeInTheDocument();
});
it("books a positive difference with the reason and shows a failed booking in the dialog", async () => {
vi.mocked(bookHoneyBatchMovement).mockRejectedValue(new Error("Boom"));
renderDialog();
await userEvent.click(screen.getByRole("button", { name: /Menge korrigieren/ }));
const input = await screen.findByLabelText(/Neu gewogen/);
await userEvent.clear(input);
await userEvent.type(input, "21");
await userEvent.type(screen.getByLabelText(/Grund/), "Eimer nachgewogen");
await userEvent.click(screen.getByRole("button", { name: "Korrektur buchen" }));
expect(bookHoneyBatchMovement).toHaveBeenCalledWith(
"h1",
{ type: "CORRECTION", deltaKg: 1, notes: "Eimer nachgewogen" },
expect.anything(),
);
expect(await screen.findByRole("alert")).toHaveTextContent(/nicht gebucht/);
});
});
@@ -0,0 +1,172 @@
"use client";
import { FormEvent, useRef, useState } from "react";
import { Scale } from "lucide-react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { bookHoneyBatchMovement } from "@/lib/honey-batches/api";
import { differenceKg, formatKg, formatSignedKg } from "@/lib/honey-batches/movements";
import { newIdempotencyKey } from "@/lib/offline/idempotency";
import { emptyToNull } from "@/lib/forms/empty-to-null";
import { saveErrorText } from "@/lib/honey-batches/errors";
import { OnlineOnlyHint, useOnlineOnly } from "@/components/offline/stand-note";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { MovementNotesField } from "./movement-notes-field";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
interface CorrectAmountDialogProps {
honeyBatchId: string;
/** The booked rest in kg. */
amount: number;
/** Switched off from outside, e.g. offline; `describedBy` names the reason. */
disabled?: boolean;
describedBy?: string;
}
/**
* „Menge korrigieren“: the beekeeper types what the scale shows now, the
* booking is the difference to the booked rest (CORRECTION). Nothing is
* overwritten - the movement book keeps both numbers.
*/
export function CorrectAmountDialog({
honeyBatchId,
amount,
disabled = false,
describedBy: triggerDescribedBy,
}: CorrectAmountDialogProps) {
const queryClient = useQueryClient();
const [open, setOpen] = useState(false);
// The rest the difference is computed against: fixed when the dialog opens,
// so a reload behind it cannot move the booking.
const [baseline, setBaseline] = useState(amount);
const [weighed, setWeighed] = useState(String(amount));
const [notes, setNotes] = useState("");
const [error, setError] = useState<string | null>(null);
const idempotencyKey = useRef(newIdempotencyKey());
const { isOffline, hintId, describedBy } = useOnlineOnly();
const weighedKg = weighed === "" ? Number.NaN : Number(weighed);
const isNumber = Number.isFinite(weighedKg);
const isNegative = isNumber && weighedKg < 0;
const difference = isNumber && !isNegative ? differenceKg(weighedKg, baseline) : 0;
const differenceText = !isNumber
? "Bitte das Gewicht eingeben."
: isNegative
? "Das Gewicht kann nicht negativ sein."
: difference === 0
? "Keine Abweichung"
: `Differenz: ${formatSignedKg(difference)}`;
const mutation = useMutation({
mutationFn: () =>
bookHoneyBatchMovement(
honeyBatchId,
{
type: "CORRECTION",
deltaKg: difference,
...(emptyToNull(notes) ? { notes: notes.trim() } : {}),
},
{ idempotencyKey: idempotencyKey.current },
),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ["honey-batches"] });
toast.success(`Menge korrigiert: ${formatSignedKg(difference)}`);
idempotencyKey.current = newIdempotencyKey();
setNotes("");
setOpen(false);
},
onError: (mutationError) => {
setError(saveErrorText(mutationError, "Die Korrektur wurde nicht gebucht."));
},
});
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setError(null);
if (difference === 0 || isOffline) return;
mutation.mutate();
}
return (
<Dialog
open={open}
onOpenChange={(next) => {
setOpen(next);
if (next) {
setBaseline(amount);
setWeighed(String(amount));
setNotes("");
setError(null);
}
}}
>
<DialogTrigger
render={
<Button
variant="outline"
size="touch"
disabled={disabled}
aria-describedby={triggerDescribedBy}
>
<Scale className="size-4" aria-hidden="true" />
Menge korrigieren
</Button>
}
/>
<DialogContent>
<DialogHeader>
<DialogTitle>Menge korrigieren</DialogTitle>
</DialogHeader>
<form className="flex flex-col gap-4" onSubmit={handleSubmit} noValidate>
<p className="text-sm text-muted-foreground">
Gebucht sind {formatKg(baseline)}. Trag ein, was die Waage jetzt zeigt – gebucht wird
die Differenz.
</p>
<div className="flex flex-col gap-2">
<Label htmlFor="correct-amount-weighed">Neu gewogen (kg)</Label>
<Input
id="correct-amount-weighed"
type="number"
inputMode="decimal"
step="any"
className="h-11"
value={weighed}
onChange={(event) => setWeighed(event.target.value)}
/>
<p aria-live="polite" className="min-h-5 text-sm text-muted-foreground">
{differenceText}
</p>
</div>
<MovementNotesField
id="correct-amount-reason"
label="Grund (optional)"
value={notes}
onChange={setNotes}
/>
{error ? (
<p role="alert" className="text-sm text-destructive">
{error}
</p>
) : null}
<OnlineOnlyHint id={hintId} />
<Button
type="submit"
size="touch"
disabled={mutation.isPending || difference === 0 || isOffline}
aria-describedby={describedBy}
>
{mutation.isPending ? "Bucht…" : "Korrektur buchen"}
</Button>
</form>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,147 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, render, screen } from "@testing-library/react";
import { reportRequestOutcome } from "@/lib/offline/connectivity";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { HoneyBatchMovementsCard } from "./honey-batch-movements-card";
import { bookHoneyBatchMovement, fetchHoneyBatchMovementPage } from "@/lib/honey-batches/api";
vi.mock("@/lib/honey-batches/api", () => ({
fetchHoneyBatchMovementPage: vi.fn(),
bookHoneyBatchMovement: vi.fn(),
}));
const PAGE = {
hasMore: false,
items: [
{
id: "m2",
type: "CORRECTION",
quantityGrams: -500,
reason: null,
notes: "Nachgewogen",
sourceBottlingBatchId: null,
createdAt: "2026-10-02T10:00:00.000Z",
userId: "u1",
},
{
id: "m1",
type: "BOTTLING",
quantityGrams: -12500,
reason: null,
notes: null,
sourceBottlingBatchId: "bb1",
createdAt: "2026-10-01T10:00:00.000Z",
userId: "u1",
},
{
id: "m0",
type: "WITHDRAWAL",
quantityGrams: -1000,
reason: "PROBE",
notes: null,
sourceBottlingBatchId: null,
createdAt: "2026-10-01T09:00:00.000Z",
userId: "u1",
},
],
};
function renderCard(props: { canBook?: boolean; amount?: number | null } = {}) {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<QueryClientProvider client={client}>
<HoneyBatchMovementsCard
honeyBatchId="h1"
amount={props.amount === undefined ? 20 : props.amount}
canBook={props.canBook ?? true}
/>
</QueryClientProvider>,
);
}
describe("HoneyBatchMovementsCard", () => {
afterEach(() => act(() => reportRequestOutcome("reached-server")));
beforeEach(() => {
vi.mocked(fetchHoneyBatchMovementPage).mockReset();
vi.mocked(fetchHoneyBatchMovementPage).mockResolvedValue(PAGE as never);
vi.mocked(bookHoneyBatchMovement).mockReset();
vi.mocked(bookHoneyBatchMovement).mockResolvedValue({} as never);
});
it("lists bottlings, withdrawals and corrections with signed kilograms", async () => {
renderCard();
expect(await screen.findByText("−12,5 kg")).toBeInTheDocument();
expect(screen.getByText("Entnahme · Probe / Muster")).toBeInTheDocument();
expect(screen.getByText("Korrektur")).toBeInTheDocument();
expect(screen.getByText("Nachgewogen")).toBeInTheDocument();
expect(screen.getByRole("link", { name: /Abfüllung/ })).toHaveAttribute("href", "/bottling/bb1");
});
it("„Menge korrigieren“ books the difference to the weighed amount as CORRECTION", async () => {
renderCard();
await screen.findByText("−12,5 kg");
await userEvent.click(screen.getByRole("button", { name: /Menge korrigieren/ }));
const input = await screen.findByLabelText(/Neu gewogen/);
await userEvent.clear(input);
await userEvent.type(input, "18.5");
expect(screen.getByText(/Differenz: −1,5 kg/)).toBeInTheDocument();
await userEvent.click(screen.getByRole("button", { name: "Korrektur buchen" }));
expect(bookHoneyBatchMovement).toHaveBeenCalledWith(
"h1",
expect.objectContaining({ type: "CORRECTION", deltaKg: -1.5 }),
expect.anything(),
);
});
it("„Entnahme“ books a negative WITHDRAWAL with its reason", async () => {
renderCard();
await screen.findByText("−12,5 kg");
await userEvent.click(screen.getByRole("button", { name: /^Entnahme$/ }));
await userEvent.type(await screen.findByLabelText(/Menge \(kg\)/), "2");
await userEvent.click(screen.getByRole("combobox"));
await userEvent.click(await screen.findByRole("option", { name: "Hofladen" }));
await userEvent.click(screen.getByRole("button", { name: "Entnahme buchen" }));
expect(bookHoneyBatchMovement).toHaveBeenCalledWith(
"h1",
expect.objectContaining({ type: "WITHDRAWAL", deltaKg: -2, reason: "HOFLADEN" }),
expect.anything(),
);
});
it("offers no booking without permission or without a tracked amount", async () => {
const { unmount } = renderCard({ canBook: false });
await screen.findByText("−12,5 kg");
expect(screen.queryByRole("button", { name: /Menge korrigieren/ })).not.toBeInTheDocument();
unmount();
renderCard({ amount: null });
await screen.findByText("−12,5 kg");
expect(screen.queryByRole("button", { name: /Menge korrigieren/ })).not.toBeInTheDocument();
});
it("switches the booking buttons off offline and says why", async () => {
renderCard();
await screen.findByText("−12,5 kg");
act(() => reportRequestOutcome("network-error"));
expect(await screen.findByText("Nur mit Verbindung")).toBeInTheDocument();
for (const name of [/Menge korrigieren/, /^Entnahme$/]) {
const button = screen.getByRole("button", { name });
expect(button).toBeDisabled();
expect(button).toHaveAccessibleDescription("Nur mit Verbindung");
}
});
it("says when older bookings are not shown", async () => {
vi.mocked(fetchHoneyBatchMovementPage).mockResolvedValue({ ...PAGE, hasMore: true } as never);
renderCard();
expect(await screen.findByText(/Ältere Buchungen werden nicht angezeigt/)).toBeInTheDocument();
});
});
@@ -0,0 +1,141 @@
"use client";
import Link from "next/link";
import { useQuery } from "@tanstack/react-query";
import { fetchHoneyBatchMovementPage } from "@/lib/honey-batches/api";
import {
formatSignedKg,
gramsToKg,
movementTitle,
} from "@/lib/honey-batches/movements";
import type { HoneyBatchMovement } from "@/lib/honey-batches/types";
import { ErrorState, LoadingState } from "@/components/query-state";
import { OnlineOnlyHint, useOnlineOnly } from "@/components/offline/stand-note";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { CorrectAmountDialog } from "./correct-amount-dialog";
import { HoneyBatchWithdrawDialog } from "./honey-batch-withdraw-dialog";
interface HoneyBatchMovementsCardProps {
honeyBatchId: string;
/** The booked rest in kg; `null` = not recorded, so nothing can be booked. */
amount: number | null;
canBook: boolean;
}
/**
* The movement book of a honey batch: every change of the rest, newest
* first - bottlings book themselves, loose goods and weighing again are
* booked by hand. The rest is the sum of these lines, so it cannot drift.
*/
export function HoneyBatchMovementsCard({
honeyBatchId,
amount,
canBook,
}: HoneyBatchMovementsCardProps) {
const query = useQuery({
queryKey: ["honey-batches", honeyBatchId, "movements"],
queryFn: () => fetchHoneyBatchMovementPage(honeyBatchId),
});
const page = query.data;
const { isOffline, hintId, describedBy } = useOnlineOnly();
return (
<Card>
<CardHeader className="flex flex-row flex-wrap items-center justify-between gap-2.5">
<CardTitle>Bewegungen</CardTitle>
{canBook && amount !== null ? (
<div className="flex flex-wrap items-center gap-2">
<HoneyBatchWithdrawDialog
honeyBatchId={honeyBatchId}
amount={amount}
disabled={isOffline}
describedBy={describedBy}
/>
<CorrectAmountDialog
honeyBatchId={honeyBatchId}
amount={amount}
disabled={isOffline}
describedBy={describedBy}
/>
</div>
) : null}
</CardHeader>
<CardContent className="flex flex-col gap-3 text-sm">
{canBook && amount !== null ? <OnlineOnlyHint id={hintId} /> : null}
{amount === null ? (
<p className="text-muted-foreground">
Für diese Charge ist keine Menge erfasst – es wird nichts gebucht.
</p>
) : null}
{query.isLoading ? <LoadingState what="Bewegungen" /> : null}
{query.isError ? (
<ErrorState
what="Bewegungen"
onRetry={() => void query.refetch()}
isRetrying={query.isFetching}
/>
) : null}
{page ? <MovementList movements={page.items} /> : null}
{page?.hasMore ? (
<p className="text-muted-foreground">
Ältere Buchungen werden nicht angezeigt.
</p>
) : null}
</CardContent>
</Card>
);
}
function MovementList({ movements }: { movements: HoneyBatchMovement[] }) {
if (movements.length === 0) {
return (
<p className="text-muted-foreground">
Noch keine Bewegungen – der Rest entspricht der Ausgangsmenge.
</p>
);
}
return (
<ul className="flex flex-col divide-y rounded-lg border">
{movements.map((movement) => (
<li
key={movement.id}
className="flex flex-wrap items-baseline justify-between gap-2 p-3"
>
<div className="flex flex-col">
<MovementTitle movement={movement} />
<span className="text-xs text-muted-foreground">
{new Date(movement.createdAt).toLocaleString("de-DE")}
</span>
{movement.notes ? (
<span className="text-xs text-muted-foreground">{movement.notes}</span>
) : null}
</div>
<span
className={
movement.quantityGrams < 0
? "font-semibold tabular-nums text-destructive"
: "font-semibold tabular-nums text-primary"
}
>
{formatSignedKg(gramsToKg(movement.quantityGrams))}
</span>
</li>
))}
</ul>
);
}
function MovementTitle({ movement }: { movement: HoneyBatchMovement }) {
const title = movementTitle(movement);
if (movement.sourceBottlingBatchId) {
return (
<Link
href={`/bottling/${movement.sourceBottlingBatchId}`}
className="min-h-11 content-center font-medium underline underline-offset-4"
>
{title}
</Link>
);
}
return <span className="font-medium">{title}</span>;
}
@@ -0,0 +1,91 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { HoneyBatchWithdrawDialog } from "./honey-batch-withdraw-dialog";
import { bookHoneyBatchMovement } from "@/lib/honey-batches/api";
import { ApiError } from "@/lib/auth/api-client";
import { reportRequestOutcome } from "@/lib/offline/connectivity";
vi.mock("@/lib/honey-batches/api", () => ({ bookHoneyBatchMovement: vi.fn() }));
function renderDialog() {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<QueryClientProvider client={client}>
<HoneyBatchWithdrawDialog honeyBatchId="h1" amount={20} />
</QueryClientProvider>,
);
}
async function open() {
await userEvent.click(screen.getByRole("button", { name: /^Entnahme$/ }));
return screen.findByLabelText(/Menge \(kg\)/);
}
describe("HoneyBatchWithdrawDialog", () => {
beforeEach(() => vi.mocked(bookHoneyBatchMovement).mockReset());
afterEach(() => act(() => reportRequestOutcome("reached-server")));
it("has no preselected reason and says what is missing", async () => {
renderDialog();
const quantity = await open();
expect(screen.getByRole("combobox")).toHaveTextContent("Grund wählen");
await userEvent.type(quantity, "2");
expect(screen.getByText("Bitte einen Grund wählen.")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Entnahme buchen" })).toBeDisabled();
});
it("refuses more than the rest and less than a gram in words", async () => {
renderDialog();
const quantity = await open();
await userEvent.type(quantity, "25");
expect(screen.getByText("Mehr als der Rest (20 kg)")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Entnahme buchen" })).toBeDisabled();
await userEvent.clear(quantity);
await userEvent.type(quantity, "0.0001");
expect(screen.getByText("Mindestens 1 g")).toBeInTheDocument();
});
it("shows the field texts of a 400 and the message of a 409", async () => {
renderDialog();
const quantity = await open();
await userEvent.type(quantity, "2");
await userEvent.click(screen.getByRole("combobox"));
await userEvent.click(await screen.findByRole("option", { name: "Hofladen" }));
vi.mocked(bookHoneyBatchMovement).mockRejectedValueOnce(
new ApiError(400, "Bad", { issues: [{ field: "deltaKg", message: "Nicht genug Rest." }] }),
);
await userEvent.click(screen.getByRole("button", { name: "Entnahme buchen" }));
expect(await screen.findByRole("alert")).toHaveTextContent("Nicht genug Rest.");
vi.mocked(bookHoneyBatchMovement).mockRejectedValueOnce(
new ApiError(409, "Die Charge wurde gerade geändert.", {}),
);
await userEvent.click(screen.getByRole("button", { name: "Entnahme buchen" }));
expect(await screen.findByText("Die Charge wurde gerade geändert.")).toBeInTheDocument();
});
it("is off while offline and says why", async () => {
renderDialog();
const quantity = await open();
await userEvent.type(quantity, "2");
act(() => reportRequestOutcome("network-error"));
expect(await screen.findByText("Nur mit Verbindung")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Entnahme buchen" })).toBeDisabled();
});
it("starts empty again when it is reopened", async () => {
renderDialog();
const quantity = await open();
await userEvent.type(quantity, "2");
await userEvent.keyboard("{Escape}");
expect(await open()).toHaveValue(null);
});
});
@@ -0,0 +1,180 @@
"use client";
import { FormEvent, useRef, useState } from "react";
import { PackageMinus } from "lucide-react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { bookHoneyBatchMovement } from "@/lib/honey-batches/api";
import { saveErrorText } from "@/lib/honey-batches/errors";
import { formatKg } from "@/lib/honey-batches/movements";
import { WITHDRAWAL_REASON_LABELS } from "@/lib/stock/labels";
import type { WithdrawalReason } from "@/lib/stock/types";
import { newIdempotencyKey } from "@/lib/offline/idempotency";
import { emptyToNull } from "@/lib/forms/empty-to-null";
import { OnlineOnlyHint, useOnlineOnly } from "@/components/offline/stand-note";
import { EnumSelect } from "@/components/form/enum-select";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { MovementNotesField } from "./movement-notes-field";
interface HoneyBatchWithdrawDialogProps {
honeyBatchId: string;
/** The booked rest in kg. */
amount: number;
/** Switched off from outside, e.g. offline; `describedBy` names the reason. */
disabled?: boolean;
describedBy?: string;
}
const GRAMS_PER_KG = 1000;
/** What keeps the booking from being sent, in words; null = nothing. */
function problemWith(quantity: string, amount: number, reason: WithdrawalReason | ""): string | null {
const kg = Number(quantity);
if (quantity === "" || !Number.isFinite(kg)) return "Bitte eine Menge eingeben.";
if (Math.round(kg * GRAMS_PER_KG) < 1) return "Mindestens 1 g";
if (Math.round(kg * GRAMS_PER_KG) > Math.round(amount * GRAMS_PER_KG)) {
return `Mehr als der Rest (${formatKg(amount)})`;
}
if (reason === "") return "Bitte einen Grund wählen.";
return null;
}
/** „Entnahme“: loose goods, samples, breakage - books a negative WITHDRAWAL with its reason. */
export function HoneyBatchWithdrawDialog({
honeyBatchId,
amount,
disabled = false,
describedBy: triggerDescribedBy,
}: HoneyBatchWithdrawDialogProps) {
const queryClient = useQueryClient();
const [open, setOpen] = useState(false);
const [quantity, setQuantity] = useState("");
const [reason, setReason] = useState<WithdrawalReason | "">("");
const [notes, setNotes] = useState("");
const [error, setError] = useState<string | null>(null);
const idempotencyKey = useRef(newIdempotencyKey());
const { isOffline, hintId, describedBy } = useOnlineOnly();
const problem = problemWith(quantity, amount, reason);
const mutation = useMutation({
mutationFn: (chosenReason: WithdrawalReason) =>
bookHoneyBatchMovement(
honeyBatchId,
{
type: "WITHDRAWAL",
deltaKg: -Number(quantity),
reason: chosenReason,
...(emptyToNull(notes) ? { notes: notes.trim() } : {}),
},
{ idempotencyKey: idempotencyKey.current },
),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ["honey-batches"] });
toast.success(`${formatKg(Number(quantity))} entnommen`);
idempotencyKey.current = newIdempotencyKey();
setOpen(false);
},
onError: (mutationError) => {
setError(saveErrorText(mutationError, "Die Entnahme wurde nicht gebucht."));
},
});
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setError(null);
if (problem !== null || reason === "" || isOffline) return;
mutation.mutate(reason);
}
return (
<Dialog
open={open}
onOpenChange={(next) => {
setOpen(next);
if (next) {
setQuantity("");
setReason("");
setNotes("");
setError(null);
}
}}
>
<DialogTrigger
render={
<Button
variant="outline"
size="touch"
disabled={disabled || amount <= 0}
aria-describedby={triggerDescribedBy}
>
<PackageMinus className="size-4" aria-hidden="true" />
Entnahme
</Button>
}
/>
<DialogContent>
<DialogHeader>
<DialogTitle>Entnahme</DialogTitle>
</DialogHeader>
<form className="flex flex-col gap-4" onSubmit={handleSubmit} noValidate>
<p className="text-sm text-muted-foreground">Noch da: {formatKg(amount)}.</p>
<div className="flex flex-col gap-2">
<Label htmlFor="honey-withdraw-quantity">Menge (kg)</Label>
<Input
id="honey-withdraw-quantity"
type="number"
inputMode="decimal"
step="any"
className="h-11"
value={quantity}
onChange={(event) => setQuantity(event.target.value)}
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="honey-withdraw-reason">Grund</Label>
<EnumSelect
id="honey-withdraw-reason"
value={reason}
onChange={setReason}
noneLabel="Grund wählen"
labels={WITHDRAWAL_REASON_LABELS}
/>
</div>
<MovementNotesField
id="honey-withdraw-notes"
label="Notiz (optional)"
value={notes}
onChange={setNotes}
/>
<p aria-live="polite" className="min-h-5 text-sm text-muted-foreground">
{problem}
</p>
{error ? (
<p role="alert" className="text-sm text-destructive">
{error}
</p>
) : null}
<OnlineOnlyHint id={hintId} />
<Button
type="submit"
size="touch"
disabled={mutation.isPending || problem !== null || isOffline}
aria-describedby={describedBy}
>
{mutation.isPending ? "Bucht…" : "Entnahme buchen"}
</Button>
</form>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,33 @@
"use client";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
/** The server accepts at most 500 characters of notes per booking. */
export const MOVEMENT_NOTES_MAX = 500;
interface MovementNotesFieldProps {
id: string;
label: string;
value: string;
onChange: (value: string) => void;
}
/** A note for a booking with a visible counter, so the limit is no surprise. */
export function MovementNotesField({ id, label, value, onChange }: MovementNotesFieldProps) {
return (
<div className="flex flex-col gap-2">
<Label htmlFor={id}>{label}</Label>
<Textarea
id={id}
maxLength={MOVEMENT_NOTES_MAX}
aria-describedby={`${id}-count`}
value={value}
onChange={(event) => onChange(event.target.value)}
/>
<p id={`${id}-count`} className="text-xs text-muted-foreground">
{value.length} / {MOVEMENT_NOTES_MAX}
</p>
</div>
);
}
@@ -0,0 +1,64 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import HoneyBatchDetailPage from "./page";
import { useAuth } from "@/lib/auth/auth-context";
import { fetchHoneyBatch, fetchHoneyBatchMovementPage } from "@/lib/honey-batches/api";
vi.mock("next/navigation", () => ({ useParams: () => ({ id: "h1" }) }));
vi.mock("@/lib/auth/auth-context", () => ({ useAuth: vi.fn() }));
vi.mock("@/lib/honey-batches/api", () => ({
fetchHoneyBatch: vi.fn(),
fetchHoneyBatchTraceability: vi.fn(() => new Promise(() => undefined)),
fetchHoneyBatchMovementPage: vi.fn(),
bookHoneyBatchMovement: vi.fn(),
}));
vi.mock("./honey-batch-edit-dialog", () => ({ HoneyBatchEditDialog: () => null }));
vi.mock("./honey-batch-storage-card", () => ({ HoneyBatchStorageCard: () => null }));
vi.mock("./honey-batch-container-allocations-card", () => ({
HoneyBatchContainerAllocationsCard: () => null,
}));
vi.mock("./add-measurement-dialog", () => ({ AddMeasurementDialog: () => null }));
vi.mock("./edit-measurement-dialog", () => ({ EditMeasurementDialog: () => null }));
vi.mock("./extraction-edit-dialog", () => ({ ExtractionEditDialog: () => null }));
vi.mock("@/components/qr-code-dialog", () => ({ QrCodeDialog: () => null }));
vi.mock("@/components/document-upload-card", () => ({ DocumentUploadCard: () => null }));
vi.mock("@/lib/export/api", () => ({ exportHoneyBatchTraceabilityPdf: vi.fn() }));
function renderPage(permissions: string[]) {
vi.mocked(useAuth).mockReturnValue({
hasPermission: (permission: string) => permissions.includes(permission),
} as never);
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<QueryClientProvider client={client}>
<HoneyBatchDetailPage />
</QueryClientProvider>,
);
}
describe("HoneyBatchDetailPage movements", () => {
beforeEach(() => {
vi.mocked(fetchHoneyBatch).mockResolvedValue({
id: "h1",
batchNumber: "H-1",
honeyType: null,
amount: 20,
waterContent: null,
status: "STORED",
measurements: [],
} as never);
vi.mocked(fetchHoneyBatchMovementPage).mockResolvedValue({ items: [], hasMore: false });
});
it("offers the bookings only with honey-batches:update", async () => {
const { unmount } = renderPage(["honey-batches:read", "honey-batches:update"]);
expect(await screen.findByRole("button", { name: /Menge korrigieren/ })).toBeInTheDocument();
unmount();
renderPage(["honey-batches:read"]);
await screen.findByText("Bewegungen");
expect(screen.queryByRole("button", { name: /Menge korrigieren/ })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: /^Entnahme$/ })).not.toBeInTheDocument();
});
});
@@ -22,11 +22,15 @@ import { AddMeasurementDialog } from "./add-measurement-dialog";
import { EditMeasurementDialog } from "./edit-measurement-dialog";
import { ExtractionEditDialog } from "./extraction-edit-dialog";
import { HoneyBatchEditDialog } from "./honey-batch-edit-dialog";
import { HoneyBatchMovementsCard } from "./honey-batch-movements-card";
import { useAuth } from "@/lib/auth/auth-context";
import { formatKg } from "@/lib/honey-batches/movements";
const BACK = { backHref: "/honey-batches", backLabel: "Alle Honigchargen" };
export default function HoneyBatchDetailPage() {
const params = useParams<{ id: string }>();
const { hasPermission } = useAuth();
const honeyBatchQuery = useQuery({
queryKey: ["honey-batches", params.id],
queryFn: () => fetchHoneyBatch(params.id),
@@ -91,12 +95,17 @@ export default function HoneyBatchDetailPage() {
</CardHeader>
<CardContent className="flex flex-col gap-3 text-sm">
{honeyBatch.honeyType ? <p>Sorte: {honeyBatch.honeyType}</p> : null}
{honeyBatch.amount !== null ? <p>Menge: {honeyBatch.amount} kg</p> : null}
{honeyBatch.amount !== null ? <p>Rest: {formatKg(honeyBatch.amount)}</p> : null}
{honeyBatch.waterContent !== null ? (
<p>Wassergehalt: {honeyBatch.waterContent}%</p>
) : null}
</CardContent>
</Card>
<HoneyBatchMovementsCard
honeyBatchId={honeyBatch.id}
amount={honeyBatch.amount}
canBook={hasPermission("honey-batches:update")}
/>
<HoneyBatchStorageCard honeyBatch={honeyBatch} />
<HoneyBatchContainerAllocationsCard honeyBatch={honeyBatch} />
</div>
@@ -0,0 +1,137 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { CreateHoneyBatchDialog } from "./create-honey-batch-dialog";
import { fetchExtractions } from "@/lib/extractions/api";
import { createHoneyBatch, fetchHoneyBatchPrefill } from "@/lib/honey-batches/api";
import { toastWarnings } from "@/lib/warnings/toast-warnings";
import { ApiError } from "@/lib/auth/api-client";
vi.mock("@/lib/extractions/api", () => ({ fetchExtractions: vi.fn() }));
vi.mock("@/lib/honey-batches/api", () => ({
createHoneyBatch: vi.fn(),
fetchHoneyBatchPrefill: vi.fn(),
}));
vi.mock("@/lib/warnings/toast-warnings", () => ({ toastWarnings: vi.fn() }));
function renderDialog() {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<QueryClientProvider client={client}>
<CreateHoneyBatchDialog />
</QueryClientProvider>,
);
}
async function openAndChooseExtraction() {
await userEvent.click(screen.getByRole("button", { name: "+ Neue Charge" }));
await userEvent.click(await screen.findByRole("combobox"));
await userEvent.click(await screen.findByRole("option", { name: /V-01/ }));
}
describe("CreateHoneyBatchDialog", () => {
beforeEach(() => {
vi.mocked(fetchExtractions).mockResolvedValue([
{
id: "x1",
date: "2026-07-03T00:00:00.000Z",
harvests: [{ harvest: { colonies: [{ colony: { code: "V-01" } }] } }],
},
] as never);
vi.mocked(fetchHoneyBatchPrefill).mockReset();
vi.mocked(fetchHoneyBatchPrefill).mockResolvedValue({
remainingKg: 30,
honeyType: "Raps",
waterContent: 17.2,
warnings: [
{
code: "BATCHES_EXCEED_EXTRACTION",
severity: "WARNUNG",
message: "Die Chargen übersteigen die Schleuderung.",
refs: [],
},
],
});
vi.mocked(createHoneyBatch).mockReset();
vi.mocked(toastWarnings).mockReset();
});
it("offers the rest of the extraction and the honey type and fills only on tap", async () => {
renderDialog();
await openAndChooseExtraction();
expect(await screen.findByText(/Vorschlag aus der Schleuderung \(Rest\): 30 kg/)).toBeInTheDocument();
expect(screen.getByLabelText(/Menge/)).toHaveValue(null);
expect(screen.getByLabelText(/Honigsorte/)).toHaveValue("");
await userEvent.click(screen.getByRole("button", { name: /übernehmen.*Menge/ }));
await userEvent.click(screen.getByRole("button", { name: /übernehmen.*Honigsorte/ }));
expect(screen.getByLabelText(/Menge/)).toHaveValue(30);
expect(screen.getByLabelText(/Honigsorte/)).toHaveValue("Raps");
});
it("offers the water content as a proposal with its own take-over", async () => {
renderDialog();
await openAndChooseExtraction();
expect(await screen.findByText(/Vorschlag aus der Schleuderung: 17,2 %/)).toBeInTheDocument();
expect(screen.getByLabelText(/Wassergehalt/)).toHaveValue(null);
await userEvent.click(screen.getByRole("button", { name: /übernehmen.*Wassergehalt/ }));
expect(screen.getByLabelText(/Wassergehalt/)).toHaveValue(17.2);
});
it("does not hide a failed prefill: note stays, retry loads again, saving is possible", async () => {
vi.mocked(fetchHoneyBatchPrefill).mockRejectedValueOnce(new Error("down"));
renderDialog();
await openAndChooseExtraction();
expect(
await screen.findByText(/Hinweise \(z\. B\. Wartezeit\) konnten nicht geladen werden/),
).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Anlegen" })).toBeEnabled();
await userEvent.click(screen.getByRole("button", { name: "Erneut versuchen" }));
expect(await screen.findByText(/Vorschlag aus der Schleuderung \(Rest\)/)).toBeInTheDocument();
});
it("says that the hints are loading", async () => {
vi.mocked(fetchHoneyBatchPrefill).mockReturnValue(new Promise(() => undefined));
renderDialog();
await openAndChooseExtraction();
expect(await screen.findByText("Hinweise werden geladen …")).toBeInTheDocument();
});
it("puts a 400 issue next to its field and shows a 409 message", async () => {
renderDialog();
await openAndChooseExtraction();
vi.mocked(createHoneyBatch).mockRejectedValueOnce(
new ApiError(400, "Bad", { issues: [{ field: "amount", message: "Menge zu groß." }] }),
);
await userEvent.click(screen.getByRole("button", { name: "Anlegen" }));
expect(await screen.findByText("Menge zu groß.")).toBeInTheDocument();
vi.mocked(createHoneyBatch).mockRejectedValueOnce(new ApiError(409, "Chargennummer vergeben.", {}));
await userEvent.click(screen.getByRole("button", { name: "Anlegen" }));
expect(await screen.findByText("Chargennummer vergeben.")).toBeInTheDocument();
});
it("shows the warnings above „Anlegen“ and keeps those of the save in a toast", async () => {
vi.mocked(createHoneyBatch).mockResolvedValue({ id: "b1", warnings: [{ code: "X" }] } as never);
renderDialog();
await openAndChooseExtraction();
const warning = await screen.findByText("Die Chargen übersteigen die Schleuderung.");
const save = screen.getByRole("button", { name: "Anlegen" });
expect(
warning.compareDocumentPosition(save) & Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
await userEvent.click(save);
expect(createHoneyBatch).toHaveBeenCalled();
expect(toastWarnings).toHaveBeenCalledWith([{ code: "X" }], "Honigcharge angelegt");
});
});
@@ -3,7 +3,13 @@
import { FormEvent, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { fetchExtractions } from "@/lib/extractions/api";
import { createHoneyBatch } from "@/lib/honey-batches/api";
import { createHoneyBatch, fetchHoneyBatchPrefill } from "@/lib/honey-batches/api";
import { formatKg } from "@/lib/honey-batches/movements";
import { toastWarnings } from "@/lib/warnings/toast-warnings";
import { WarningList } from "@/components/warnings/warning-list";
import { PreviousValueHint } from "@/components/form/previous-value-hint";
import { PrefillStatus } from "@/components/warnings/prefill-status";
import { describeSaveError, type SaveError } from "@/lib/honey-batches/errors";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
@@ -18,6 +24,14 @@ import {
import { RecordSelect } from "@/components/form/record-select";
import { emptyToNull } from "@/lib/forms/empty-to-null";
function FieldIssue({ message }: { message: string | undefined }) {
return message ? (
<p role="alert" className="text-sm font-medium text-destructive">
{message}
</p>
) : null;
}
export function CreateHoneyBatchDialog() {
const queryClient = useQueryClient();
const [open, setOpen] = useState(false);
@@ -25,34 +39,50 @@ export function CreateHoneyBatchDialog() {
const [extractionId, setExtractionId] = useState("");
const [honeyType, setHoneyType] = useState("");
const [amount, setAmount] = useState("");
const [error, setError] = useState<string | null>(null);
const [waterContent, setWaterContent] = useState("");
const [saveError, setSaveError] = useState<SaveError | null>(null);
const fieldError = (field: string) => saveError?.fields[field];
const { data: extractions } = useQuery({
queryKey: ["extractions"],
queryFn: fetchExtractions,
});
// Proposals from the extraction: shown with a take-over button, never
// written into a field by themselves.
const prefillQuery = useQuery({
queryKey: ["honey-batches", "prefill", extractionId],
queryFn: () => fetchHoneyBatchPrefill(extractionId),
enabled: extractionId !== "",
});
const prefill = extractionId ? prefillQuery.data : undefined;
const mutation = useMutation({
mutationFn: createHoneyBatch,
onSuccess: () => {
onSuccess: (honeyBatch) => {
if (honeyBatch.warnings?.length) {
toastWarnings(honeyBatch.warnings, "Honigcharge angelegt");
}
void queryClient.invalidateQueries({ queryKey: ["honey-batches"] });
setOpen(false);
setBatchNumber("");
setExtractionId("");
setHoneyType("");
setAmount("");
setError(null);
setWaterContent("");
setSaveError(null);
},
onError: () => {
setError("Honigcharge konnte nicht angelegt werden.");
onError: (mutationError) => {
setSaveError(describeSaveError(mutationError, "Honigcharge konnte nicht angelegt werden."));
},
});
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setError(null);
setSaveError(null);
if (!extractionId) {
setError("Bitte eine Schleuderung auswählen.");
setSaveError({ general: null, fields: { extractionId: "Bitte eine Schleuderung auswählen." } });
return;
}
mutation.mutate({
@@ -61,6 +91,7 @@ export function CreateHoneyBatchDialog() {
extractionId,
honeyType: emptyToNull(honeyType),
amount: emptyToNull(amount, Number),
waterContent: emptyToNull(waterContent, Number),
});
}
@@ -80,6 +111,7 @@ export function CreateHoneyBatchDialog() {
value={batchNumber}
onChange={(event) => setBatchNumber(event.target.value)}
/>
<FieldIssue message={fieldError("batchNumber")} />
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="batch-extraction">Schleuderung</Label>
@@ -95,6 +127,7 @@ export function CreateHoneyBatchDialog() {
}
placeholder="Schleuderung wählen"
/>
<FieldIssue message={fieldError("extractionId")} />
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="batch-honey-type">Honigsorte</Label>
@@ -103,6 +136,15 @@ export function CreateHoneyBatchDialog() {
value={honeyType}
onChange={(event) => setHoneyType(event.target.value)}
/>
{prefill?.honeyType && honeyType !== prefill.honeyType ? (
<PreviousValueHint
fieldLabel="Honigsorte"
valueLabel={prefill.honeyType}
prefix="Vorschlag aus den Ernten"
onTakeOver={() => setHoneyType(prefill.honeyType ?? "")}
/>
) : null}
<FieldIssue message={fieldError("honeyType")} />
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="batch-amount">Menge (kg)</Label>
@@ -113,10 +155,47 @@ export function CreateHoneyBatchDialog() {
value={amount}
onChange={(event) => setAmount(event.target.value)}
/>
{prefill?.remainingKg != null && amount !== String(prefill.remainingKg) ? (
<PreviousValueHint
fieldLabel="Menge"
valueLabel={formatKg(prefill.remainingKg)}
prefix="Vorschlag aus der Schleuderung (Rest)"
onTakeOver={() => setAmount(String(prefill.remainingKg))}
/>
) : null}
<FieldIssue message={fieldError("amount")} />
</div>
{error ? (
<div className="flex flex-col gap-2">
<Label htmlFor="batch-water-content">Wassergehalt (%)</Label>
<Input
id="batch-water-content"
type="number"
inputMode="decimal"
step="any"
value={waterContent}
onChange={(event) => setWaterContent(event.target.value)}
/>
{prefill?.waterContent != null && waterContent !== String(prefill.waterContent) ? (
<PreviousValueHint
fieldLabel="Wassergehalt"
valueLabel={`${prefill.waterContent.toLocaleString("de-DE")} %`}
prefix="Vorschlag aus der Schleuderung"
onTakeOver={() => setWaterContent(String(prefill.waterContent))}
/>
) : null}
<FieldIssue message={fieldError("waterContent")} />
</div>
<PrefillStatus
enabled={extractionId !== ""}
isLoading={prefillQuery.isLoading}
isError={prefillQuery.isError}
isRetrying={prefillQuery.isFetching}
onRetry={() => void prefillQuery.refetch()}
/>
<WarningList warnings={prefill?.warnings ?? []} />
{saveError?.general ? (
<p role="alert" className="text-sm text-destructive">
{error}
{saveError.general}
</p>
) : null}
<DialogFooter>
@@ -19,4 +19,22 @@ describe("PreviousValueHint", () => {
expect(onTakeOver).toHaveBeenCalledTimes(1);
});
it("keeps „Letztes Mal“ as default prefix and lets a caller name the source", () => {
const { rerender } = render(
<PreviousValueHint fieldLabel="Menge" valueLabel="42,5 kg" onTakeOver={() => undefined} />,
);
expect(screen.getByText(/Letztes Mal: 42,5 kg/)).toBeInTheDocument();
rerender(
<PreviousValueHint
fieldLabel="Menge"
valueLabel="42,5 kg"
prefix="Aus 2 Ernten"
onTakeOver={() => undefined}
/>,
);
expect(screen.getByText(/Aus 2 Ernten: 42,5 kg/)).toBeInTheDocument();
expect(screen.queryByText(/Letztes Mal/)).not.toBeInTheDocument();
});
});
@@ -8,6 +8,8 @@ export interface PreviousValueHintProps {
/** The earlier answer in words, e.g. "Ja" or "4 von 5". */
valueLabel: string;
onTakeOver: () => void;
/** Where the value comes from; "Letztes Mal" unless the caller names a source, e.g. "Aus 2 Ernten". */
prefix?: string;
className?: string;
}
@@ -20,12 +22,13 @@ export function PreviousValueHint({
fieldLabel,
valueLabel,
onTakeOver,
prefix = "Letztes Mal",
className,
}: PreviousValueHintProps) {
return (
<p className={cn("flex flex-wrap items-center gap-x-2 text-sm text-muted-foreground", className)}>
<span>
Letztes Mal: {valueLabel} <span aria-hidden="true">·</span>
{prefix}: {valueLabel} <span aria-hidden="true">·</span>
</span>
<button
type="button"
@@ -0,0 +1,158 @@
import "fake-indexeddb/auto";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { fetchAutopilotToday } from "@/lib/autopilot/api";
import { createPhenologyReport, fetchPhenologyState } from "@/lib/phenology/api";
import type { PhenologyState } from "@/lib/phenology/types";
import { ApiarySeason } from "./apiary-season";
vi.mock("@/lib/phenology/api", async (importOriginal) => ({
...(await importOriginal<typeof import("@/lib/phenology/api")>()),
fetchPhenologyState: vi.fn(),
fetchPhenologyReports: vi.fn().mockResolvedValue([]),
createPhenologyReport: vi.fn(),
}));
vi.mock("@/lib/autopilot/api", async (importOriginal) => ({
...(await importOriginal<typeof import("@/lib/autopilot/api")>()),
fetchAutopilotToday: vi.fn(),
}));
const auth = vi.hoisted(() => ({ permissions: new Set<string>() }));
vi.mock("@/lib/auth/auth-context", () => ({
useCurrentUserId: () => "user-1",
useAuth: () => ({
hasPermission: (permission: string) => auth.permissions.has(permission),
}),
}));
const apiary = { id: "a-1", name: "Obstwiese" };
function state(overrides: Partial<PhenologyState>): PhenologyState {
return {
apiaryId: "a-1",
apiaryName: "Obstwiese",
phase: "KIRSCHE",
segment: "SCHWARMZEIT",
phaseSource: "REPORT",
reportedOn: "2026-04-18",
gts: null,
gtsThroughDay: null,
note: null,
...overrides,
};
}
function renderSeason() {
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
return render(
<QueryClientProvider client={client}>
<ApiarySeason apiary={apiary} />
</QueryClientProvider>,
);
}
beforeEach(() => {
auth.permissions = new Set(["phenology:create"]);
vi.mocked(fetchPhenologyState)
.mockReset()
.mockResolvedValue([
state({ apiaryId: "a-2", apiaryName: "Wald", segment: "SOMMER" }),
state({}),
]);
vi.mocked(fetchAutopilotToday)
.mockReset()
.mockResolvedValue({
nextStep: null,
inspectionDue: [
{
apiaryId: "a-1",
apiaryName: "Obstwiese",
segment: "SCHWARMZEIT",
intervalDays: 7,
colonies: [],
},
],
suggestionsOpen: 0,
seasons: [],
tasksVisible: true,
});
});
describe("ApiarySeason", () => {
it("shows the season with its source on the apiary page", async () => {
renderSeason();
expect(await screen.findByText("Schwarmzeit · alle 7 Tage")).toBeInTheDocument();
expect(screen.getByText("gemeldet am 18.04.")).toBeInTheDocument();
expect(screen.getByText("Kirsche blüht")).toBeInTheDocument();
});
it("names an estimated phase and a calendar phase by their source", async () => {
vi.mocked(fetchPhenologyState).mockResolvedValue([
state({ phaseSource: "GTS", reportedOn: null, phase: "APFEL" }),
]);
const { unmount } = renderSeason();
expect(await screen.findByText("geschätzt")).toBeInTheDocument();
unmount();
vi.mocked(fetchPhenologyState).mockResolvedValue([
state({ phaseSource: "CALENDAR", reportedOn: null, phase: null }),
]);
renderSeason();
expect(await screen.findByText("Kalender")).toBeInTheDocument();
});
it("falls back to the season without an interval when the interval is unknown", async () => {
vi.mocked(fetchAutopilotToday).mockRejectedValue(new Error("403"));
renderSeason();
expect(await screen.findByText("Schwarmzeit")).toBeInTheDocument();
});
it("shows „Pflanze blüht“ only with phenology:create and opens the sheet", async () => {
renderSeason();
await userEvent.click(await screen.findByRole("button", { name: "Pflanze blüht" }));
expect(await screen.findByRole("dialog")).toHaveTextContent("Entwicklung melden");
expect(screen.getByRole("button", { name: "Salweide blüht" })).toBeInTheDocument();
});
it("hides the button without phenology:create", async () => {
auth.permissions = new Set();
renderSeason();
await screen.findByText("Schwarmzeit · alle 7 Tage");
expect(screen.queryByRole("button", { name: "Pflanze blüht" })).toBeNull();
});
it("explains a missing weather basis in words", async () => {
vi.mocked(fetchPhenologyState).mockResolvedValue([
state({
phaseSource: "CALENDAR",
reportedOn: null,
note: "WEATHER_STALE",
}),
]);
renderSeason();
expect(await screen.findByText("Wetterdaten veraltet")).toBeInTheDocument();
});
it("closes the sheet after a report and returns the focus to „Pflanze blüht“", async () => {
vi.mocked(createPhenologyReport).mockResolvedValue({} as never);
renderSeason();
const trigger = await screen.findByRole("button", {
name: "Pflanze blüht",
});
await userEvent.click(trigger);
await userEvent.click(await screen.findByRole("button", { name: "Salweide blüht" }));
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
await waitFor(() => expect(trigger).toHaveFocus());
});
});
@@ -0,0 +1,75 @@
"use client";
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Flower2 } from "lucide-react";
import { SeasonChip } from "@/components/autopilot/season-chip";
import { PhenologyReportSheet } from "@/components/phenology/phenology-report-sheet";
import { Button } from "@/components/ui/button";
import { autopilotTodayKey, fetchAutopilotToday } from "@/lib/autopilot/api";
import { useAuth } from "@/lib/auth/auth-context";
import { fetchPhenologyState, phenologyStateKey } from "@/lib/phenology/api";
import { PHASE_REPORT_LABELS, SEASON_NOTE_LABELS, phaseSourceText } from "@/lib/phenology/labels";
interface ApiarySeasonProps {
apiary: { id: string; name: string };
}
/**
* The season of an apiary with where it comes from („Schwarmzeit · alle 7
* Tage · gemeldet am 18.04.“), and the way to report a blooming plant.
*/
export function ApiarySeason({ apiary }: ApiarySeasonProps) {
const { hasPermission } = useAuth();
const [isSheetOpen, setSheetOpen] = useState(false);
const stateQuery = useQuery({
queryKey: phenologyStateKey,
queryFn: fetchPhenologyState,
});
// The interval is only known for apiaries with colonies to inspect; without
// it (or without the right to see it) the chip names just the season.
const todayQuery = useQuery({
queryKey: autopilotTodayKey,
queryFn: fetchAutopilotToday,
});
const state = stateQuery.data?.find((entry) => entry.apiaryId === apiary.id);
const intervalDays =
todayQuery.data?.inspectionDue.find((entry) => entry.apiaryId === apiary.id)?.intervalDays ??
null;
const source = state ? phaseSourceText(state.phaseSource, state.reportedOn) : null;
const canReport = hasPermission("phenology:create");
if (!state && !canReport) return null;
return (
<section aria-label="Saison" className="flex flex-wrap items-center gap-x-3 gap-y-2">
{state ? (
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">
<SeasonChip segment={state.segment} intervalDays={intervalDays} />
{state.phase ? <span>{PHASE_REPORT_LABELS[state.phase]}</span> : null}
{source ? (
<>
<span aria-hidden className="text-muted-foreground">
·
</span>
<span className="text-muted-foreground">{source}</span>
</>
) : null}
{state.note ? (
<span className="text-warning-foreground">{SEASON_NOTE_LABELS[state.note]}</span>
) : null}
</div>
) : null}
{canReport ? (
<>
<Button type="button" size="touch" variant="outline" onClick={() => setSheetOpen(true)}>
<Flower2 aria-hidden />
Pflanze blüht
</Button>
<PhenologyReportSheet open={isSheetOpen} onOpenChange={setSheetOpen} apiary={apiary} />
</>
) : null}
</section>
);
}
@@ -0,0 +1,356 @@
import "fake-indexeddb/auto";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { toast } from "sonner";
import { ApiError } from "@/lib/auth/api-client";
import { berlinCalendarDay } from "@/lib/dates";
import { reportRequestOutcome } from "@/lib/offline/connectivity";
import {
createPhenologyReport,
fetchPhenologyReports,
queuePhenologyReport,
revokePhenologyReport,
} from "@/lib/phenology/api";
import type { PhenologyReport } from "@/lib/phenology/types";
import { PhenologyReportSheet } from "./phenology-report-sheet";
vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
vi.mock("@/lib/phenology/api", async (importOriginal) => ({
...(await importOriginal<typeof import("@/lib/phenology/api")>()),
createPhenologyReport: vi.fn(),
fetchPhenologyReports: vi.fn(),
queuePhenologyReport: vi.fn(),
revokePhenologyReport: vi.fn(),
}));
const auth = vi.hoisted(() => ({ permissions: new Set<string>() }));
vi.mock("@/lib/auth/auth-context", () => ({
useCurrentUserId: () => "user-1",
useAuth: () => ({
hasPermission: (permission: string) => auth.permissions.has(permission),
}),
}));
const apiary = { id: "a-1", name: "Obstwiese" };
function report(overrides: Partial<PhenologyReport>): PhenologyReport {
return {
id: "r-1",
apiaryId: null,
apiaryName: null,
phase: "SALWEIDE",
date: "2026-03-20",
notes: null,
userId: "user-2",
userName: "Karla",
revokedAt: null,
createdAt: "2026-03-20T08:00:00.000Z",
...overrides,
};
}
function renderSheet(onOpenChange = vi.fn()) {
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
render(
<QueryClientProvider client={client}>
<PhenologyReportSheet open onOpenChange={onOpenChange} apiary={apiary} />
</QueryClientProvider>,
);
return onOpenChange;
}
const today = () => berlinCalendarDay(new Date().toISOString());
beforeEach(() => {
auth.permissions = new Set(["phenology:create", "phenology:read", "phenology:update"]);
vi.mocked(createPhenologyReport).mockReset().mockResolvedValue(report({}));
vi.mocked(fetchPhenologyReports).mockReset().mockResolvedValue([]);
vi.mocked(queuePhenologyReport).mockReset().mockResolvedValue(undefined);
vi.mocked(revokePhenologyReport)
.mockReset()
.mockResolvedValue(report({ revokedAt: "x" }));
vi.mocked(toast.success).mockReset();
});
afterEach(() => {
vi.useRealTimers();
act(() => reportRequestOutcome("reached-server"));
});
describe("PhenologyReportSheet", () => {
it("one tap reports the phase for today for all apiaries", async () => {
const onOpenChange = renderSheet();
await userEvent.click(screen.getByRole("button", { name: "Salweide blüht" }));
await waitFor(() => expect(createPhenologyReport).toHaveBeenCalledTimes(1));
expect(createPhenologyReport).toHaveBeenCalledWith(
{ phase: "SALWEIDE", date: today(), apiaryId: null },
{ idempotencyKey: expect.any(String) },
);
await waitFor(() => expect(toast.success).toHaveBeenCalledWith("Salweide blüht gemeldet"));
expect(onOpenChange).toHaveBeenCalledWith(false);
});
it("rows are 56 px and „für alle Stände“ is preselected", () => {
renderSheet();
expect(screen.getByRole("radio", { name: "Für alle Stände" })).toBeChecked();
expect(screen.getByRole("radio", { name: "Nur Obstwiese" })).not.toBeChecked();
const rows = screen.getAllByRole("button", {
name: /(blüht|vorbei)$|^Winterruhe$/,
});
expect(rows).toHaveLength(8);
for (const row of rows) {
expect(row).toHaveClass("min-h-14");
}
});
it("reports for this apiary only after switching the scope", async () => {
renderSheet();
await userEvent.click(screen.getByRole("radio", { name: "Nur Obstwiese" }));
await userEvent.click(screen.getByRole("button", { name: "Kirsche blüht" }));
await waitFor(() => expect(createPhenologyReport).toHaveBeenCalledTimes(1));
expect(vi.mocked(createPhenologyReport).mock.calls[0][0]).toMatchObject({
phase: "KIRSCHE",
apiaryId: "a-1",
});
});
it("sends a different key for a different phase in the same opened sheet", async () => {
vi.mocked(createPhenologyReport).mockRejectedValue(new ApiError(500, "Fehler", {}));
renderSheet();
await userEvent.click(screen.getByRole("button", { name: "Salweide blüht" }));
await waitFor(() => expect(createPhenologyReport).toHaveBeenCalledTimes(1));
await userEvent.click(screen.getByRole("button", { name: "Apfel blüht" }));
await waitFor(() => expect(createPhenologyReport).toHaveBeenCalledTimes(2));
const [first, second] = vi.mocked(createPhenologyReport).mock.calls;
expect(first[1]?.idempotencyKey).not.toBe(second[1]?.idempotencyKey);
});
it("offline the report is queued and synced later", async () => {
vi.mocked(createPhenologyReport).mockRejectedValue(new TypeError("Failed to fetch"));
const onOpenChange = renderSheet();
await userEvent.click(screen.getByRole("button", { name: "Holunder blüht" }));
await waitFor(() => expect(queuePhenologyReport).toHaveBeenCalledTimes(1));
const [input, key, owner] = vi.mocked(queuePhenologyReport).mock.calls[0];
expect(input).toEqual({ phase: "HOLUNDER", date: today(), apiaryId: null });
expect(key).toBe(vi.mocked(createPhenologyReport).mock.calls[0][1]?.idempotencyKey);
expect(owner).toBe("user-1");
await waitFor(() =>
expect(toast.success).toHaveBeenCalledWith(
"Holunder blüht gespeichert – wird gesendet, sobald wieder Verbindung besteht",
),
);
expect(onOpenChange).toHaveBeenCalledWith(false);
});
it("shows the reason of the server and stays open when the report is rejected", async () => {
vi.mocked(createPhenologyReport).mockRejectedValue(
new ApiError(400, "Das Datum liegt in der Zukunft.", {}),
);
const onOpenChange = renderSheet();
await userEvent.click(screen.getByRole("button", { name: "Linde blüht" }));
expect(await screen.findByText("Das Datum liegt in der Zukunft.")).toBeVisible();
expect(queuePhenologyReport).not.toHaveBeenCalled();
expect(onOpenChange).not.toHaveBeenCalledWith(false);
});
it("lists this year's reports that count for the apiary and withdraws one", async () => {
vi.mocked(fetchPhenologyReports).mockResolvedValue([
report({ id: "r-1", phase: "SALWEIDE", date: "2026-03-20" }),
report({
id: "r-2",
phase: "KIRSCHE",
date: "2026-04-10",
apiaryId: "a-1",
apiaryName: "Obstwiese",
userName: "Nick",
}),
report({
id: "r-3",
phase: "APFEL",
date: "2026-04-20",
apiaryId: "a-9",
apiaryName: "Wald",
}),
report({
id: "r-4",
phase: "LINDE",
date: "2026-06-01",
revokedAt: "2026-06-02T08:00:00.000Z",
}),
]);
renderSheet();
const list = await screen.findByRole("list", {
name: "Meldungen dieses Jahres",
});
const items = within(list).getAllByRole("listitem");
expect(items).toHaveLength(3);
expect(items[0]).toHaveTextContent("Salweide blüht");
expect(items[0]).toHaveTextContent("20.03.");
expect(items[0]).toHaveTextContent("alle Stände");
expect(items[1]).toHaveTextContent("Kirsche blüht");
expect(items[1]).toHaveTextContent("Obstwiese");
expect(items[2]).toHaveTextContent("zurückgezogen");
expect(within(items[2]).queryByRole("button", { name: /Zurückziehen/ })).toBeNull();
await userEvent.click(within(items[1]).getByRole("button", { name: /Zurückziehen/ }));
await waitFor(() =>
expect(revokePhenologyReport).toHaveBeenCalledWith("r-2", {
idempotencyKey: expect.any(String),
}),
);
await waitFor(() => expect(toast.success).toHaveBeenCalledWith("Meldung zurückgezogen"));
});
it("does not load the list without phenology:read", () => {
auth.permissions = new Set(["phenology:create"]);
renderSheet();
expect(screen.queryByRole("list", { name: "Meldungen dieses Jahres" })).toBeNull();
expect(fetchPhenologyReports).not.toHaveBeenCalled();
});
it("offers „Zurückziehen“ only with phenology:update", async () => {
auth.permissions = new Set(["phenology:create", "phenology:read"]);
vi.mocked(fetchPhenologyReports).mockResolvedValue([report({})]);
renderSheet();
await screen.findByRole("list", { name: "Meldungen dieses Jahres" });
expect(screen.queryByRole("button", { name: /Zurückziehen/ })).toBeNull();
});
it("switches off „Zurückziehen“ with „Nur mit Verbindung“ offline", async () => {
vi.mocked(fetchPhenologyReports).mockResolvedValue([report({})]);
renderSheet();
const withdraw = await screen.findByRole("button", {
name: /zurückziehen/i,
});
act(() => reportRequestOutcome("network-error"));
expect(withdraw).toBeDisabled();
expect(screen.getByText("Nur mit Verbindung")).toBeInTheDocument();
});
it("asks first before withdrawing a report for all apiaries", async () => {
vi.mocked(fetchPhenologyReports).mockResolvedValue([report({ id: "r-1" })]);
renderSheet();
await userEvent.click(
await screen.findByRole("button", {
name: "Für alle Stände zurückziehen: Salweide blüht vom 20.03.",
}),
);
expect(revokePhenologyReport).not.toHaveBeenCalled();
const dialog = await screen.findByRole("dialog", {
name: "Für alle Stände zurückziehen?",
});
await userEvent.click(within(dialog).getByRole("button", { name: "Zurückziehen" }));
await waitFor(() =>
expect(revokePhenologyReport).toHaveBeenCalledWith("r-1", {
idempotencyKey: expect.any(String),
}),
);
});
it("does not withdraw when the question is cancelled", async () => {
vi.mocked(fetchPhenologyReports).mockResolvedValue([report({ id: "r-1" })]);
renderSheet();
await userEvent.click(
await screen.findByRole("button", {
name: /Für alle Stände zurückziehen/,
}),
);
const dialog = await screen.findByRole("dialog", {
name: "Für alle Stände zurückziehen?",
});
await userEvent.click(within(dialog).getByRole("button", { name: "Abbrechen" }));
expect(revokePhenologyReport).not.toHaveBeenCalled();
});
it("moves the focus to the list heading after a withdrawal", async () => {
vi.mocked(fetchPhenologyReports).mockResolvedValue([
report({ id: "r-2", apiaryId: "a-1", apiaryName: "Obstwiese" }),
]);
renderSheet();
await userEvent.click(await screen.findByRole("button", { name: /Zurückziehen/ }));
await waitFor(() =>
expect(screen.getByRole("heading", { name: "Meldungen dieses Jahres" })).toHaveFocus(),
);
});
it("has a neutral heading", () => {
renderSheet();
expect(screen.getByRole("dialog", { name: "Entwicklung melden" })).toBeInTheDocument();
});
it("closes with Escape", async () => {
const onOpenChange = renderSheet();
await userEvent.keyboard("{Escape}");
expect(onOpenChange).toHaveBeenCalledWith(false);
});
it("stays open while the report is on its way", async () => {
let answer: (saved: PhenologyReport) => void = () => undefined;
vi.mocked(createPhenologyReport).mockReturnValue(
new Promise<PhenologyReport>((resolve) => {
answer = resolve;
}),
);
const onOpenChange = renderSheet();
await userEvent.click(screen.getByRole("button", { name: "Salweide blüht" }));
await waitFor(() => expect(createPhenologyReport).toHaveBeenCalled());
await userEvent.keyboard("{Escape}");
expect(onOpenChange).not.toHaveBeenCalled();
expect(screen.getByRole("button", { name: "Schließen" })).toBeDisabled();
await act(async () => answer(report({})));
await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false));
});
it("says „Nur mit Verbindung“ instead of a load error offline", async () => {
vi.mocked(fetchPhenologyReports).mockRejectedValue(new TypeError("Failed to fetch"));
renderSheet();
act(() => reportRequestOutcome("network-error"));
expect(await screen.findByText("Nur mit Verbindung")).toBeInTheDocument();
expect(screen.queryByText("Die Meldungen konnten nicht geladen werden.")).toBeNull();
});
it.each([
["summer time", "2026-07-10T23:30:00.000Z", "2026-07-11"],
["winter time", "2026-01-10T23:30:00.000Z", "2026-01-11"],
])("reports the Berlin day at 23:30 UTC in %s", async (_name, now, berlinDay) => {
vi.useFakeTimers({ toFake: ["Date"] });
vi.setSystemTime(new Date(now));
renderSheet();
await userEvent.click(screen.getByRole("button", { name: "Linde blüht" }));
await waitFor(() => expect(createPhenologyReport).toHaveBeenCalledTimes(1));
expect(vi.mocked(createPhenologyReport).mock.calls[0][0].date).toBe(berlinDay);
});
});
@@ -0,0 +1,343 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Flower2 } from "lucide-react";
import { toast } from "sonner";
import { ConfirmDialog } from "@/components/confirm-dialog";
import { OnlineOnlyHint, useOnlineOnly } from "@/components/offline/stand-note";
import { Button } from "@/components/ui/button";
import {
Sheet,
SheetClose,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet";
import { autopilotTodayKey } from "@/lib/autopilot/api";
import { formatDayMonth } from "@/lib/autopilot/format";
import { useAuth } from "@/lib/auth/auth-context";
import { berlinCalendarDay } from "@/lib/dates";
import { errorMessage } from "@/lib/forms/error-message";
import { newIdempotencyKey } from "@/lib/offline/idempotency";
import { useCaptureMutation } from "@/lib/offline/use-capture-mutation";
import {
createPhenologyReport,
fetchPhenologyReports,
phenologyReportsKey,
queuePhenologyReport,
revokePhenologyReport,
} from "@/lib/phenology/api";
import { PHASE_REPORT_LABELS } from "@/lib/phenology/labels";
import {
PHENOLOGY_PHASES,
type CreatePhenologyReportInput,
type PhenologyReport,
} from "@/lib/phenology/types";
import { cn } from "@/lib/utils";
interface PhenologyReportSheetProps {
open: boolean;
onOpenChange: (open: boolean) => void;
apiary: { id: string; name: string };
}
type Scope = "all" | "apiary";
const QUEUED_TEXT = "gespeichert – wird gesendet, sobald wieder Verbindung besteht";
/** Which plant is in bloom? One tap reports it for today. */
export function PhenologyReportSheet({ open, onOpenChange, apiary }: PhenologyReportSheetProps) {
// While a report or a withdrawal is on its way the sheet stays open, so the
// answer (or the server's reason) is never lost behind a closed sheet.
const [isBusy, setBusy] = useState(false);
function handleOpenChange(next: boolean) {
if (!next && isBusy) return;
onOpenChange(next);
}
return (
<Sheet open={open} onOpenChange={handleOpenChange}>
<SheetContent
side="bottom"
showCloseButton={false}
className="max-h-[85dvh] gap-0 overflow-y-auto rounded-t-2xl pb-(--safe-area-bottom)"
>
{/* Remounted per opening: a fresh idempotency key and the preselected scope. */}
{open ? (
<ReportForm
apiary={apiary}
onOpenChange={onOpenChange}
isBusy={isBusy}
onBusyChange={setBusy}
/>
) : null}
</SheetContent>
</Sheet>
);
}
function ReportForm({
apiary,
onOpenChange,
isBusy,
onBusyChange,
}: Pick<PhenologyReportSheetProps, "apiary" | "onOpenChange"> & {
isBusy: boolean;
onBusyChange: (busy: boolean) => void;
}) {
const queryClient = useQueryClient();
const [scope, setScope] = useState<Scope>("all");
const capture = useCaptureMutation<CreatePhenologyReportInput, unknown>({
create: createPhenologyReport,
queue: queuePhenologyReport,
failureMessage: "Die Meldung konnte nicht gespeichert werden.",
// Each phase and scope is its own report and needs its own key.
keyPerSubmission: true,
onSaved: (outcome, input) => {
const label = PHASE_REPORT_LABELS[input.phase];
if (outcome.via === "online") {
toast.success(`${label} gemeldet`);
void queryClient.invalidateQueries({ queryKey: ["phenology"] });
void queryClient.invalidateQueries({ queryKey: autopilotTodayKey });
} else {
toast.success(`${label} ${QUEUED_TEXT}`);
}
onOpenChange(false);
},
});
const [revokeError, setRevokeError] = useState<string | null>(null);
const [isRevoking, setRevoking] = useState(false);
const status = capture.submitError ?? revokeError;
const busy = capture.isPending || isRevoking;
useEffect(() => {
onBusyChange(busy);
return () => onBusyChange(false);
}, [busy, onBusyChange]);
return (
<div className="flex flex-col gap-4 px-4 pb-4">
<SheetHeader className="px-0">
<SheetTitle>Entwicklung melden</SheetTitle>
<SheetDescription>Ein Tipp meldet die Pflanze für heute.</SheetDescription>
</SheetHeader>
<ScopeChoice apiaryName={apiary.name} scope={scope} onChange={setScope} />
<div role="group" aria-label="Pflanze" className="flex flex-col gap-2">
{PHENOLOGY_PHASES.map((phase) => (
<button
key={phase}
type="button"
disabled={capture.isPending}
onClick={() =>
capture.submit({
phase,
date: berlinCalendarDay(new Date().toISOString()),
apiaryId: scope === "all" ? null : apiary.id,
})
}
className={cn(
"flex min-h-14 w-full items-center gap-3 rounded-xl border border-border bg-background px-4",
"text-left text-base font-medium outline-none transition-colors",
"hover:bg-muted focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50",
"disabled:pointer-events-none disabled:opacity-50",
)}
>
<Flower2 className="size-5 shrink-0 text-muted-foreground" aria-hidden />
{PHASE_REPORT_LABELS[phase]}
</button>
))}
</div>
{/* Always mounted, so a screen reader announces the text when it appears. */}
<p role="status" aria-live="polite" className="min-h-5 text-sm text-destructive">
{status}
</p>
<ReportsOfTheYear
apiary={apiary}
onRevokeError={setRevokeError}
onRevokingChange={setRevoking}
/>
<SheetClose
disabled={isBusy}
render={<Button type="button" size="touch" variant="outline" />}
>
Schließen
</SheetClose>
</div>
);
}
function ScopeChoice({
apiaryName,
scope,
onChange,
}: {
apiaryName: string;
scope: Scope;
onChange: (scope: Scope) => void;
}) {
const options: { value: Scope; label: string }[] = [
{ value: "all", label: "Für alle Stände" },
{ value: "apiary", label: `Nur ${apiaryName}` },
];
return (
<fieldset className="flex flex-col gap-1">
<legend className="mb-1 text-sm font-medium">Gilt für</legend>
{options.map((option) => (
<label
key={option.value}
className="flex min-h-11 items-center gap-3 rounded-lg px-1 text-base has-focus-visible:ring-3 has-focus-visible:ring-ring/50"
>
<input
type="radio"
name="phenology-scope"
className="size-5 accent-primary"
checked={scope === option.value}
onChange={() => onChange(option.value)}
/>
{option.label}
</label>
))}
</fieldset>
);
}
/** The reports that count for this apiary: its own and those for all apiaries. */
function appliesTo(report: PhenologyReport, apiaryId: string): boolean {
return report.apiaryId === null || report.apiaryId === apiaryId;
}
function ReportsOfTheYear({
apiary,
onRevokeError,
onRevokingChange,
}: {
apiary: { id: string };
onRevokeError: (message: string | null) => void;
onRevokingChange: (isRevoking: boolean) => void;
}) {
const { hasPermission } = useAuth();
const queryClient = useQueryClient();
const year = Number(berlinCalendarDay(new Date().toISOString()).slice(0, 4));
const canRead = hasPermission("phenology:read");
const canWithdraw = hasPermission("phenology:update");
const { isOffline, hintId, describedBy } = useOnlineOnly();
const heading = useRef<HTMLHeadingElement>(null);
const reports = useQuery({
queryKey: phenologyReportsKey(year),
queryFn: () => fetchPhenologyReports(year),
enabled: canRead,
});
const revoke = useMutation({
mutationFn: (id: string) => revokePhenologyReport(id, { idempotencyKey: newIdempotencyKey() }),
onMutate: () => onRevokeError(null),
onSuccess: () => {
toast.success("Meldung zurückgezogen");
void queryClient.invalidateQueries({ queryKey: ["phenology"] });
void queryClient.invalidateQueries({ queryKey: autopilotTodayKey });
heading.current?.focus();
},
onError: (error) =>
onRevokeError(errorMessage(error, "Die Meldung konnte nicht zurückgezogen werden.")),
});
useEffect(() => {
onRevokingChange(revoke.isPending);
}, [revoke.isPending, onRevokingChange]);
if (!canRead) return null;
const items = (reports.data ?? []).filter((report) => appliesTo(report, apiary.id));
return (
<section className="flex flex-col gap-2" aria-labelledby="phenology-reports-heading">
<h3
id="phenology-reports-heading"
ref={heading}
tabIndex={-1}
className="text-sm font-medium outline-none"
>
Meldungen dieses Jahres
</h3>
{reports.isError && !isOffline ? (
<p className="text-sm text-destructive">Die Meldungen konnten nicht geladen werden.</p>
) : null}
{reports.isSuccess && items.length === 0 ? (
<p className="text-sm text-muted-foreground">Noch keine Meldung in diesem Jahr.</p>
) : null}
{items.length > 0 ? (
<ul aria-label="Meldungen dieses Jahres" className="flex flex-col gap-2">
{items.map((report) => (
<ReportItem
key={report.id}
report={report}
canWithdraw={canWithdraw}
disabled={isOffline || revoke.isPending}
describedBy={describedBy}
onWithdraw={() => revoke.mutate(report.id)}
/>
))}
</ul>
) : null}
<OnlineOnlyHint id={hintId} />
</section>
);
}
function ReportItem({
report,
canWithdraw,
disabled,
describedBy,
onWithdraw,
}: {
report: PhenologyReport;
canWithdraw: boolean;
disabled: boolean;
describedBy: string | undefined;
onWithdraw: () => void;
}) {
const label = PHASE_REPORT_LABELS[report.phase];
const day = formatDayMonth(report.date);
const isRevoked = report.revokedAt !== null;
const isForAll = report.apiaryId === null;
const withdrawLabel = `${label} vom ${day}`;
return (
<li className="flex min-h-14 items-center justify-between gap-3 rounded-xl border border-border px-4 py-2">
<div className="min-w-0">
<p className={cn("font-medium", isRevoked && "text-muted-foreground line-through")}>
{label}
</p>
<p className="text-sm text-muted-foreground">
{day} · {report.apiaryName ?? "alle Stände"} · {report.userName}
{isRevoked ? " · zurückgezogen" : ""}
</p>
</div>
{canWithdraw && !isRevoked && isForAll ? (
// A report for all apiaries changes the season of every apiary: ask first.
<ConfirmDialog
triggerLabel="Für alle Stände zurückziehen"
triggerAriaLabel={`Für alle Stände zurückziehen: ${withdrawLabel}`}
triggerSize="touch"
triggerDisabled={disabled}
title="Für alle Stände zurückziehen?"
description={`${withdrawLabel} gilt für alle Stände. Beim Zurückziehen wird die Saison aller Stände neu berechnet.`}
confirmLabel="Zurückziehen"
onConfirm={onWithdraw}
/>
) : null}
{canWithdraw && !isRevoked && !isForAll ? (
<Button
type="button"
size="touch"
variant="outline"
disabled={disabled}
aria-describedby={describedBy}
aria-label={`Zurückziehen: ${withdrawLabel}`}
onClick={onWithdraw}
>
Zurückziehen
</Button>
) : null}
</li>
);
}
@@ -0,0 +1,36 @@
"use client";
import { Button } from "@/components/ui/button";
export interface PrefillStatusProps {
/** The prefill is asked for at all (something is chosen). */
enabled: boolean;
isLoading: boolean;
isError: boolean;
isRetrying: boolean;
onRetry: () => void;
}
/**
* What the prefill is doing, so that a missing warning never reads as "no
* warning": while loading a short line, after a failure a note that stays
* until a retry works. Saving stays possible - the server checks anyway. The
* region stays mounted so the change is announced.
*/
export function PrefillStatus({ enabled, isLoading, isError, isRetrying, onRetry }: PrefillStatusProps) {
return (
<div role="status" aria-live="polite">
{enabled && isLoading ? (
<p className="text-sm text-muted-foreground">Hinweise werden geladen …</p>
) : null}
{enabled && isError ? (
<div className="flex flex-wrap items-center gap-2 rounded-lg bg-warning/20 px-3 py-2 text-sm">
<span>Hinweise (z. B. Wartezeit) konnten nicht geladen werden.</span>
<Button type="button" variant="outline" size="touch" onClick={onRetry} disabled={isRetrying}>
Erneut versuchen
</Button>
</div>
) : null}
</div>
);
}
+12 -1
View File
@@ -1,5 +1,10 @@
import { apiFetch } from "@/lib/auth/api-client";
import { CreateExtractionInput, Extraction, UpdateExtractionInput } from "./types";
import {
CreateExtractionInput,
Extraction,
ExtractionPrefill,
UpdateExtractionInput,
} from "./types";
export function fetchExtractions(): Promise<Extraction[]> {
return apiFetch<Extraction[]>("/extractions");
@@ -9,6 +14,12 @@ export function fetchExtraction(id: string): Promise<Extraction> {
return apiFetch<Extraction>(`/extractions/${encodeURIComponent(id)}`);
}
/** Proposal from the chosen harvests (query key ["extractions", "prefill", ids]). */
export function fetchExtractionPrefill(harvestIds: string[]): Promise<ExtractionPrefill> {
const ids = harvestIds.map(encodeURIComponent).join(",");
return apiFetch<ExtractionPrefill>(`/extractions/prefill?harvestIds=${ids}`);
}
export function createExtraction(input: CreateExtractionInput): Promise<Extraction> {
return apiFetch<Extraction>("/extractions", {
method: "POST",
+11 -1
View File
@@ -1,3 +1,5 @@
import type { PlausibilityWarning, WithWarnings } from "@/lib/warnings/types";
export interface ExtractionHarvestEntry {
id: string;
harvestId: string;
@@ -11,7 +13,7 @@ export interface ExtractionHarvestEntry {
};
}
export interface Extraction {
export interface Extraction extends WithWarnings {
id: string;
date: string;
userId: string;
@@ -46,3 +48,11 @@ export interface UpdateExtractionInput {
temperature?: number | null;
notes?: string | null;
}
/** A proposal from the chosen harvests: never a measurement, never applied silently. */
export interface ExtractionPrefill {
amountKg: number | null;
honeyType: string | null;
sources: { harvestId: string; date: string; netWeight: number | null }[];
warnings: PlausibilityWarning[];
}
@@ -1,6 +1,11 @@
import { apiFetch } from "@/lib/auth/api-client";
import { CreateOptions, idempotencyHeaders } from "@/lib/offline/idempotency";
import {
BookHoneyBatchMovementInput,
CreateHoneyBatchInput,
HoneyBatchMovement,
HoneyBatchMovementPage,
HoneyBatchPrefill,
CreateHoneyMeasurementInput,
UpdateHoneyMeasurementInput,
HoneyBatch,
@@ -107,3 +112,30 @@ export function removeHoneyBatchContainerAllocation(
method: "DELETE",
});
}
export function fetchHoneyBatchPrefill(extractionId: string): Promise<HoneyBatchPrefill> {
return apiFetch<HoneyBatchPrefill>(
`/honey-batches/prefill?extractionId=${encodeURIComponent(extractionId)}`,
);
}
/** The newest bookings and whether older ones exist (the server sends 200). */
export function fetchHoneyBatchMovementPage(id: string): Promise<HoneyBatchMovementPage> {
return apiFetch<HoneyBatchMovementPage>(`/honey-batches/${encodeURIComponent(id)}/movements`);
}
export async function fetchHoneyBatchMovements(id: string): Promise<HoneyBatchMovement[]> {
return (await fetchHoneyBatchMovementPage(id)).items;
}
export function bookHoneyBatchMovement(
id: string,
input: BookHoneyBatchMovementInput,
options: CreateOptions,
): Promise<HoneyBatchMovement> {
return apiFetch<HoneyBatchMovement>(`/honey-batches/${encodeURIComponent(id)}/movements`, {
method: "POST",
headers: idempotencyHeaders(options),
body: JSON.stringify(input),
});
}
@@ -0,0 +1,37 @@
import { ApiError } from "@/lib/auth/api-client";
import { isNetworkError } from "@/lib/http/fetch-with-timeout";
import { issuesByField } from "@/lib/automation/rule-configs";
const OFFLINE_TEXT = "Keine Verbindung – nichts gespeichert.";
const INVALID_TEXT = "Die Eingabe ist ungültig.";
export interface SaveError {
/** A text for the whole form (no field named). */
general: string | null;
/** Server messages per field (400 `issues[]`). */
fields: Record<string, string>;
}
/**
* The ONE place that reads a failed honey save: 400 `issues[]` per field,
* Nest's English `message[]` replaced, a service message (409) as it is.
* A 409 `CONFIRMATION_REQUIRED` (water content) is to be recognised here
* (`status === 409` and `body.code`) once that flow exists.
*/
export function describeSaveError(error: unknown, fallback: string): SaveError {
if (isNetworkError(error)) return { general: OFFLINE_TEXT, fields: {} };
if (!(error instanceof ApiError)) return { general: fallback, fields: {} };
const fields = issuesByField(error);
if (Object.keys(fields).length > 0) return { general: null, fields };
if (error.status === 400) {
const message = (error.body as { message?: unknown } | null)?.message;
return { general: typeof message === "string" && message ? message : INVALID_TEXT, fields: {} };
}
return { general: error.message || fallback, fields: {} };
}
/** One line for forms without field slots (the booking dialogs). */
export function saveErrorText(error: unknown, fallback: string): string {
const { general, fields } = describeSaveError(error, fallback);
return general ?? Object.values(fields).join(" ");
}
@@ -0,0 +1,43 @@
import { WITHDRAWAL_REASON_LABELS } from "@/lib/stock/labels";
import type { HoneyBatchMovement, HoneyBatchMovementType } from "./types";
const GRAMS_PER_KG = 1000;
const MINUS = "−";
const KG_FORMAT = new Intl.NumberFormat("de-DE", { maximumFractionDigits: 3 });
export const HONEY_MOVEMENT_TYPE_LABELS: Record<HoneyBatchMovementType, string> = {
BOTTLING: "Abfüllung",
WITHDRAWAL: "Entnahme",
CORRECTION: "Korrektur",
SHOP_SALE: "Webshop-Verkauf",
SHOP_RETURN: "Webshop-Rückbuchung",
CONSUMPTION: "Verbrauch in Herstellung",
};
export function gramsToKg(grams: number): number {
return grams / GRAMS_PER_KG;
}
/** "12,5 kg" - German decimal comma, gram precision. */
export function formatKg(kg: number): string {
return `${KG_FORMAT.format(Math.round(kg * GRAMS_PER_KG) / GRAMS_PER_KG)} kg`;
}
/** "+2 kg" / "−12,5 kg": the sign is always written, a real minus sign. */
export function formatSignedKg(kg: number): string {
const rounded = Math.round(kg * GRAMS_PER_KG) / GRAMS_PER_KG;
const sign = rounded < 0 ? MINUS : "+";
return `${sign}${formatKg(Math.abs(rounded))}`;
}
/** Title of one booking, e.g. "Entnahme · Probe / Muster". */
export function movementTitle(movement: HoneyBatchMovement): string {
const label = HONEY_MOVEMENT_TYPE_LABELS[movement.type];
return movement.reason ? `${label} · ${WITHDRAWAL_REASON_LABELS[movement.reason]}` : label;
}
/** Difference between the weighed amount and the booked one, on the gram grid. */
export function differenceKg(weighedKg: number, bookedKg: number): number {
return Math.round((weighedKg - bookedKg) * GRAMS_PER_KG) / GRAMS_PER_KG;
}
@@ -1,3 +1,6 @@
import type { PlausibilityWarning, WithWarnings } from "@/lib/warnings/types";
import type { WithdrawalReason } from "@/lib/stock/types";
export type HoneyBatchStatus =
| "RAW"
| "EXTRACTED"
@@ -23,7 +26,7 @@ export interface StorageContainerRef {
location: string | null;
}
export interface HoneyBatch {
export interface HoneyBatch extends WithWarnings {
id: string;
batchNumber: string;
extractionId: string;
@@ -120,3 +123,45 @@ export interface UpdateHoneyMeasurementInput {
temperature?: number | null;
notes?: string | null;
}
/** A proposal for the new batch from its extraction: never a measurement. */
export interface HoneyBatchPrefill {
remainingKg: number | null;
honeyType: string | null;
waterContent: number | null;
warnings: PlausibilityWarning[];
}
export type HoneyBatchMovementType =
| "BOTTLING"
| "WITHDRAWAL"
| "CORRECTION"
| "SHOP_SALE"
| "SHOP_RETURN"
| "CONSUMPTION";
/** One booking in the movement book; the quantity is signed grams. */
export interface HoneyBatchMovement {
id: string;
type: HoneyBatchMovementType;
quantityGrams: number;
reason: WithdrawalReason | null;
notes: string | null;
sourceBottlingBatchId: string | null;
createdAt: string;
userId: string | null;
}
/** The newest bookings; `hasMore` when older ones are not sent. */
export interface HoneyBatchMovementPage {
items: HoneyBatchMovement[];
hasMore: boolean;
}
/** A manual booking. deltaKg is signed and never 0 (a withdrawal is negative). */
export interface BookHoneyBatchMovementInput {
type: "WITHDRAWAL" | "CORRECTION";
deltaKg: number;
reason?: WithdrawalReason;
notes?: string;
}
+105 -2
View File
@@ -63,12 +63,114 @@ async function createVersion2Queue(entry: object): Promise<void> {
db.close();
}
/** A device that last opened the app with DB v3 (before plant reports). */
async function createVersion3Queue(inspection: object): Promise<void> {
const db = await openDB(DB_NAME, 3, {
upgrade(database) {
for (const store of [...VERSION_2_STORES, "pending-bulk"]) {
database.createObjectStore(store, {
keyPath: "id",
autoIncrement: true,
});
}
const photos = database.createObjectStore("pending-photos", {
keyPath: "id",
});
photos.createIndex("sessionId", "sessionId");
photos.createIndex("inspectionIdempotencyKey", "inspectionIdempotencyKey");
photos.createIndex("ownerUserId", "ownerUserId");
database.createObjectStore("offline-packs", { keyPath: "apiaryId" });
database.createObjectStore("meta");
},
});
await db.add("pending-inspections", inspection);
db.close();
}
describe("offline queue database", () => {
beforeEach(() => {
globalThis.indexedDB = new IDBFactory();
});
it("upgrading v2 → v3 keeps already queued inspections", async () => {
it.each([
["a fresh install (0)", 0],
["version 1", 1],
])("opening from %s creates the plant report store at version 4", async (_name, from) => {
if (from === 1) {
const old = await openDB(DB_NAME, 1, {
upgrade(database) {
database.createObjectStore("pending-inspections", {
keyPath: "id",
autoIncrement: true,
});
},
});
await old.add("pending-inspections", {
input: INSPECTION,
queuedAt: "2026-10-01T08:00:00.000Z",
});
old.close();
}
const db = await loadDb();
await db.queuePhenologyReport(
{ phase: "APFEL", date: "2026-04-20" },
"plant-key-0000000003",
"user-1",
);
const upgraded = await openDB(DB_NAME);
expect(upgraded.version).toBe(4);
expect([...upgraded.objectStoreNames]).toContain("pending-phenology-reports");
expect(await upgraded.count("pending-phenology-reports")).toBe(1);
expect(await upgraded.count("pending-inspections")).toBe(from === 1 ? 1 : 0);
upgraded.close();
});
it("db upgrade 3 -> 4 keeps queued inspections and adds the plant report queue", async () => {
await createVersion3Queue({
input: INSPECTION,
idempotencyKey: "key-from-v3",
ownerUserId: "user-1",
queuedAt: "2026-10-01T08:00:00.000Z",
});
const db = await loadDb();
const entries = await db.getPendingEntries("pending-inspections");
expect(entries).toEqual([
{
id: 1,
input: INSPECTION,
idempotencyKey: "key-from-v3",
ownerUserId: "user-1",
queuedAt: "2026-10-01T08:00:00.000Z",
},
]);
await db.queuePhenologyReport(
{ phase: "SALWEIDE", date: "2026-03-20", apiaryId: null },
"key-plant-0000000001",
"user-1",
);
expect(await db.getPendingEntries("pending-phenology-reports")).toEqual([
expect.objectContaining({
input: { phase: "SALWEIDE", date: "2026-03-20", apiaryId: null },
idempotencyKey: "key-plant-0000000001",
ownerUserId: "user-1",
}),
]);
expect(await db.summarizeQueue("user-1")).toEqual({
own: 2,
failed: 0,
foreign: 0,
});
expect((await db.listQueue("user-1")).map((item) => item.label)).toContain("Pflanzenmeldung");
const upgraded = await openDB(DB_NAME);
expect(upgraded.version).toBe(4);
upgraded.close();
});
it("upgrading v2 → v4 keeps already queued inspections", async () => {
await createVersion2Queue({
input: INSPECTION,
idempotencyKey: "key-from-v2",
@@ -90,7 +192,7 @@ describe("offline queue database", () => {
expect(await db.summarizeQueue("user-1")).toEqual({ own: 1, failed: 0, foreign: 0 });
const upgraded = await openDB(DB_NAME);
expect(upgraded.version).toBe(3);
expect(upgraded.version).toBe(4);
expect([...upgraded.objectStoreNames]).toEqual(
expect.arrayContaining([
...VERSION_2_STORES,
@@ -98,6 +200,7 @@ describe("offline queue database", () => {
"pending-photos",
"offline-packs",
"meta",
"pending-phenology-reports",
]),
);
expect([...upgraded.transaction("pending-photos").store.indexNames].sort()).toEqual([
+21 -2
View File
@@ -7,6 +7,7 @@ import { CreateFeedingInput } from "@/lib/feedings/types";
import { CreateVarroaMeasurementInput } from "@/lib/varroa/types";
import { CreateSwarmControlCheckInput } from "@/lib/swarm-control/types";
import { CreateHarvestInput } from "@/lib/harvests/types";
import type { CreatePhenologyReportInput } from "@/lib/phenology/types";
import {
colonyIdsOfBulkInput,
invalidColonyIdsOfBody,
@@ -21,6 +22,7 @@ export interface RecordQueueInputs {
"pending-varroa-measurements": CreateVarroaMeasurementInput;
"pending-swarm-control-checks": CreateSwarmControlCheckInput;
"pending-harvests": CreateHarvestInput;
"pending-phenology-reports": CreatePhenologyReportInput;
}
export type RecordStoreName = keyof RecordQueueInputs;
/** Every store whose entries wait to be sent and are shown in the queue sheet. */
@@ -107,11 +109,12 @@ export interface OfflineDB extends DBSchema, RecordStores {
const DB_NAME = "apicore-offline";
// v1 only had "pending-inspections", v2 added the other five quick-capture
// types, v3 adds bulk entries, photos, offline packs and meta. Entries already
// types, v3 adds bulk entries, photos, offline packs and meta, v4 adds plant
// reports (Pflanzenentwicklung). Entries already
// queued on a phone must survive every upgrade, so each store is only created
// if it doesn't exist yet (guarded by oldVersion, per idb's upgrade()
// convention), never recreated.
const DB_VERSION = 3;
const DB_VERSION = 4;
const RECORD_STORES: readonly RecordStoreName[] = [
"pending-inspections",
@@ -120,6 +123,7 @@ const RECORD_STORES: readonly RecordStoreName[] = [
"pending-varroa-measurements",
"pending-swarm-control-checks",
"pending-harvests",
"pending-phenology-reports",
];
const QUEUE_STORES: readonly QueueStoreName[] = [...RECORD_STORES, "pending-bulk"];
@@ -130,6 +134,7 @@ const RECORD_LABELS: Record<RecordStoreName, string> = {
"pending-varroa-measurements": "Varroamessung",
"pending-swarm-control-checks": "Schwarmkontrolle",
"pending-harvests": "Ernte",
"pending-phenology-reports": "Pflanzenmeldung",
};
const BULK_LABELS: Record<BulkKind, string> = {
treatments: "Behandlung für mehrere Völker",
@@ -172,6 +177,12 @@ export function getDb(): Promise<IDBPDatabase<OfflineDB>> {
db.createObjectStore("offline-packs", { keyPath: "apiaryId" });
db.createObjectStore("meta");
}
if (oldVersion < 4) {
db.createObjectStore("pending-phenology-reports", {
keyPath: "id",
autoIncrement: true,
});
}
},
// A newer app version in another tab wants to upgrade: step aside
// instead of blocking it. The next call here opens the new version.
@@ -263,6 +274,14 @@ export function queueHarvest(
return queue("pending-harvests", input, idempotencyKey, ownerUserId);
}
export function queuePhenologyReport(
input: CreatePhenologyReportInput,
idempotencyKey: string,
ownerUserId: string,
): Promise<void> {
return queue("pending-phenology-reports", input, idempotencyKey, ownerUserId);
}
/**
* One entry for several colonies. The key belongs to this exact selection of
* colonies: it is stored with the entry and sent again unchanged.
@@ -7,6 +7,7 @@ import { readHandOvers, rememberHandOver } from "@/lib/photos/handover";
vi.mock("@/lib/inspections/api", () => ({ createInspection: vi.fn() }));
vi.mock("@/lib/treatments/api", () => ({ createTreatment: vi.fn() }));
vi.mock("@/lib/documents/api", () => ({ uploadDocument: vi.fn() }));
vi.mock("@/lib/phenology/api", () => ({ createPhenologyReport: vi.fn() }));
vi.mock("@/lib/apiaries/offline-pack", () => ({ refreshPacksAfterSync: vi.fn() }));
// What the inspection drain hands over to the photos, seen at that moment.
@@ -45,6 +46,9 @@ let photos: PhotoStoreModule;
let ApiError: ApiErrorClass;
let createInspection: MockedFunction<typeof import("@/lib/inspections/api").createInspection>;
let createTreatment: MockedFunction<typeof import("@/lib/treatments/api").createTreatment>;
let createPhenologyReport: MockedFunction<
typeof import("@/lib/phenology/api").createPhenologyReport
>;
let uploadDocument: MockedFunction<typeof import("@/lib/documents/api").uploadDocument>;
let refreshPacksAfterSync: MockedFunction<
typeof import("@/lib/apiaries/offline-pack").refreshPacksAfterSync
@@ -95,6 +99,9 @@ describe("syncPendingEntries", () => {
createInspection = vi.mocked((await import("@/lib/inspections/api")).createInspection);
createTreatment = vi.mocked((await import("@/lib/treatments/api")).createTreatment);
uploadDocument = vi.mocked((await import("@/lib/documents/api")).uploadDocument);
createPhenologyReport = vi.mocked(
(await import("@/lib/phenology/api")).createPhenologyReport,
);
refreshPacksAfterSync = vi.mocked(
(await import("@/lib/apiaries/offline-pack")).refreshPacksAfterSync,
);
@@ -102,6 +109,7 @@ describe("syncPendingEntries", () => {
createInspection.mockReset();
createTreatment.mockReset();
uploadDocument.mockReset();
createPhenologyReport.mockReset();
refreshPacksAfterSync.mockReset().mockResolvedValue(undefined);
photoHandOver.calls.length = 0;
photoHandOver.failFor = null;
@@ -122,6 +130,55 @@ describe("syncPendingEntries", () => {
expect(await db.getPendingEntries("pending-inspections")).toEqual([]);
});
it("offline the plant report is queued and synced later with its key", async () => {
const report = {
phase: "SALWEIDE",
date: "2026-03-20",
apiaryId: null,
} as const;
await db.queuePhenologyReport(report, "plant-key-0000000001", "user-1");
createPhenologyReport.mockResolvedValue({ id: "r-1" } as never);
const result = await sync.syncPendingEntries("user-1");
expect(result).toEqual({ synced: 1, failed: 0, skippedForeign: 0 });
expect(createPhenologyReport).toHaveBeenCalledWith(report, {
idempotencyKey: "plant-key-0000000001",
});
expect(await db.getPendingEntries("pending-phenology-reports")).toEqual([]);
});
it("skips a plant report of another account", async () => {
await db.queuePhenologyReport(
{ phase: "SALWEIDE", date: "2026-03-20" },
"plant-key-0000000004",
"user-2",
);
const result = await sync.syncPendingEntries("user-1");
expect(result).toEqual({ synced: 0, failed: 0, skippedForeign: 1 });
expect(createPhenologyReport).not.toHaveBeenCalled();
expect(await db.getPendingEntries("pending-phenology-reports")).toHaveLength(1);
});
it("keeps a plant report the server rejected, with the reason", async () => {
await db.queuePhenologyReport(
{ phase: "KIRSCHE", date: "2026-04-02" },
"plant-key-0000000002",
"user-1",
);
createPhenologyReport.mockRejectedValue(
new ApiError(400, "Das Datum liegt in der Zukunft.", {}),
);
const result = await sync.syncPendingEntries("user-1");
expect(result.failed).toBe(1);
const [entry] = await db.getPendingEntries("pending-phenology-reports");
expect(entry.lastError?.message).toBe("Das Datum liegt in der Zukunft.");
});
it("resends a queued entry with the idempotency key it was queued with", async () => {
// The server may already have saved the first attempt; the same key lets
// it answer with that record instead of storing a duplicate.
+3 -1
View File
@@ -6,6 +6,7 @@ import { createFeeding } from "@/lib/feedings/api";
import { createVarroaMeasurement } from "@/lib/varroa/api";
import { createSwarmControlCheck } from "@/lib/swarm-control/api";
import { createHarvest } from "@/lib/harvests/api";
import { createPhenologyReport } from "@/lib/phenology/api";
import { uploadDocument } from "@/lib/documents/api";
import {
createFeedingsBulk,
@@ -80,7 +81,7 @@ let generation = 0;
let isOpen = true;
/**
* Drains all six offline queues in one pass (not just inspections) - a
* Drains all seven offline queues in one pass (not just inspections) - a
* beekeeper working a row of hives with no signal may have queued several
* different record types before connectivity returns. Only entries of
* `currentUserId` (and ownerless ones from before owners existed) are sent.
@@ -336,6 +337,7 @@ async function runSync(run: SyncRun): Promise<SyncResult> {
drain("pending-varroa-measurements", createVarroaMeasurement, run),
drain("pending-swarm-control-checks", createSwarmControlCheck, run),
drain("pending-harvests", createHarvest, run),
drain("pending-phenology-reports", createPhenologyReport, run),
drainBulk(run),
]);
// Photos last: the drains above have just given them their inspection's
+48
View File
@@ -0,0 +1,48 @@
import { apiFetch } from "@/lib/auth/api-client";
import { CreateOptions, idempotencyHeaders } from "@/lib/offline/idempotency";
import { queuePhenologyReport as queueInOfflineDb } from "@/lib/offline/db";
import type { CreatePhenologyReportInput, PhenologyReport, PhenologyState } from "./types";
export const phenologyStateKey = ["phenology", "state"] as const;
export function phenologyReportsKey(year: number) {
return ["phenology", "reports", year] as const;
}
export function fetchPhenologyState(): Promise<PhenologyState[]> {
return apiFetch<PhenologyState[]>("/phenology/state");
}
export function fetchPhenologyReports(year: number): Promise<PhenologyReport[]> {
return apiFetch<PhenologyReport[]>(`/phenology/reports?year=${encodeURIComponent(year)}`);
}
export function createPhenologyReport(
input: CreatePhenologyReportInput,
options: CreateOptions = {},
): Promise<PhenologyReport> {
return apiFetch<PhenologyReport>("/phenology/reports", {
method: "POST",
headers: idempotencyHeaders(options),
body: JSON.stringify(input),
});
}
export function revokePhenologyReport(
id: string,
options: CreateOptions = {},
): Promise<PhenologyReport> {
return apiFetch<PhenologyReport>(`/phenology/reports/${encodeURIComponent(id)}/revoke`, {
method: "POST",
headers: idempotencyHeaders(options),
});
}
/** Without a connection the report waits in the offline queue until it can be sent. */
export function queuePhenologyReport(
input: CreatePhenologyReportInput,
idempotencyKey: string,
ownerUserId: string,
): Promise<void> {
return queueInOfflineDb(input, idempotencyKey, ownerUserId);
}
@@ -0,0 +1,42 @@
import { describe, expect, it } from "vitest";
import { PHASE_REPORT_LABELS, SEASON_NOTE_LABELS, PHASE_SOURCE_LABELS, phaseSourceText } from "./labels";
import { PHENOLOGY_PHASES } from "./types";
describe("phenology labels", () => {
it("names every phase the way a beekeeper says it", () => {
expect(PHENOLOGY_PHASES.map((phase) => PHASE_REPORT_LABELS[phase])).toEqual([
"Salweide blüht",
"Kirsche blüht",
"Apfel blüht",
"Holunder blüht",
"Linde blüht",
"Tracht vorbei",
"Efeu blüht",
"Winterruhe",
]);
});
it("names the three sources", () => {
expect(PHASE_SOURCE_LABELS).toEqual({
REPORT: "gemeldet",
GTS: "geschätzt",
CALENDAR: "Kalender",
});
});
it("explains each weak basis in words", () => {
expect(SEASON_NOTE_LABELS).toEqual({
NO_COORDINATES: "Keine Koordinaten",
WEATHER_GAPS: "Wetterdaten lückenhaft",
WEATHER_STALE: "Wetterdaten veraltet",
});
});
it("adds the report day only for reported phases", () => {
expect(phaseSourceText("REPORT", "2026-04-18")).toBe("gemeldet am 18.04.");
expect(phaseSourceText("REPORT", null)).toBe("gemeldet");
expect(phaseSourceText("GTS", "2026-04-18")).toBe("geschätzt");
expect(phaseSourceText("CALENDAR", null)).toBe("Kalender");
expect(phaseSourceText(null, null)).toBeNull();
});
});
@@ -0,0 +1,36 @@
import { formatDayMonth } from "@/lib/autopilot/format";
import type { PhaseSource, PhenologyPhase, SeasonNote } from "./types";
export const PHASE_REPORT_LABELS: Record<PhenologyPhase, string> = {
SALWEIDE: "Salweide blüht",
KIRSCHE: "Kirsche blüht",
APFEL: "Apfel blüht",
HOLUNDER: "Holunder blüht",
LINDE: "Linde blüht",
TRACHTENDE: "Tracht vorbei",
HERBST: "Efeu blüht",
WINTER: "Winterruhe",
};
export const PHASE_SOURCE_LABELS: Record<PhaseSource, string> = {
REPORT: "gemeldet",
GTS: "geschätzt",
CALENDAR: "Kalender",
};
/** Why the estimate is weak, when it is. */
export const SEASON_NOTE_LABELS: Record<NonNullable<SeasonNote>, string> = {
NO_COORDINATES: "Keine Koordinaten",
WEATHER_GAPS: "Wetterdaten lückenhaft",
WEATHER_STALE: "Wetterdaten veraltet",
};
/** „gemeldet am 18.04.“, „geschätzt“, „Kalender“; null without a known source. */
export function phaseSourceText(
source: PhaseSource | null,
reportedOn: string | null,
): string | null {
if (!source) return null;
const label = PHASE_SOURCE_LABELS[source];
return source === "REPORT" && reportedOn ? `${label} am ${formatDayMonth(reportedOn)}` : label;
}
@@ -0,0 +1,58 @@
import type { SeasonSegment } from "@/lib/autopilot/types";
// Mirrors ApiCore-Backend/src/phenology (phenology.service.ts, dto/) and
// src/season/season-types.ts - keep both in step.
export const PHENOLOGY_PHASES = [
"SALWEIDE",
"KIRSCHE",
"APFEL",
"HOLUNDER",
"LINDE",
"TRACHTENDE",
"HERBST",
"WINTER",
] as const;
export type PhenologyPhase = (typeof PHENOLOGY_PHASES)[number];
export type PhaseSource = "REPORT" | "GTS" | "CALENDAR";
export type SeasonNote = "NO_COORDINATES" | "WEATHER_GAPS" | "WEATHER_STALE" | null;
export interface CreatePhenologyReportInput {
phase: PhenologyPhase;
/** YYYY-MM-DD, not after today (Europe/Berlin). */
date: string;
/** null or omitted = the report counts for all apiaries. */
apiaryId?: string | null;
notes?: string | null;
}
export interface PhenologyReport {
id: string;
apiaryId: string | null;
/** null = the report counts for all apiaries. */
apiaryName: string | null;
phase: PhenologyPhase;
/** YYYY-MM-DD */
date: string;
notes: string | null;
userId: string;
userName: string;
revokedAt: string | null;
createdAt: string;
}
/** The season state of an apiary; the API never sends coordinates. */
export interface PhenologyState {
apiaryId: string;
apiaryName: string;
phase: PhenologyPhase | null;
segment: SeasonSegment;
phaseSource: PhaseSource | null;
/** YYYY-MM-DD; only set when the phase comes from a report. */
reportedOn: string | null;
gts: number | null;
gtsThroughDay: string | null;
note: SeasonNote;
}
@@ -45,6 +45,9 @@ data:
# WEATHER_USER_AGENT_CONTACT: ""
# Telegram-Erinnerungen (optional). Name des Bots ohne @ (5-32 Zeichen:
# Buchstaben, Ziffern, Unterstrich) fuer den Deep Link; API und Worker lesen
# ihn aus dieser ConfigMap. Das Token steht NICHT hier, siehe Kommentar in
# secret.example.yaml (Secret apicore-telegram, nur Worker).
# TELEGRAM_BOT_USERNAME: "<bot-username>"
# ihn aus dieser ConfigMap. Leer = Telegram ist in der App nicht
# eingerichtet (Platzhalter; Runbook: Bot bei BotFather anlegen, ohne
# Gruppen (/setjoingroups) und ohne Webhook, je Umgebung ein eigener Bot,
# dann hier den Namen eintragen). Das Token steht NICHT hier, siehe Kommentar
# in secret.example.yaml (Secret apicore-telegram, nur Worker).
TELEGRAM_BOT_USERNAME: ""
+2 -1
View File
@@ -43,7 +43,8 @@ stringData:
# Telegram-Bot-Token (optional) - NICHT in diesem Secret, sondern im eigenen
# Secret apicore-telegram, das nur der Worker einbindet (Secret mit
# TELEGRAM_BOT_TOKEN, envFrom/secretKeyRef mit optional: true). Der API-Pod
# TELEGRAM_BOT_TOKEN; einzelne secretKeyRef-Variable (optional: true), kein
# envFrom, kein Volume). Der API-Pod
# darf es nicht einbinden. Der Inhaber legt den Bot bei BotFather und das
# Secret selbst an; ohne Token laeuft Telegram nicht, alles andere schon.
#
@@ -79,6 +79,12 @@ spec:
value: "3002"
- name: HOME
value: /tmp
- name: TELEGRAM_BOT_TOKEN
valueFrom:
secretKeyRef:
name: apicore-telegram
key: TELEGRAM_BOT_TOKEN
optional: true
envFrom:
- configMapRef:
name: apicore-backend-config
@@ -22,6 +22,7 @@ data:
WEATHER_HISTORY_SOURCE: "open-meteo"
OPEN_METEO_FORECAST_URL: "https://api.open-meteo.com/v1/forecast"
OPEN_METEO_ARCHIVE_URL: "https://archive-api.open-meteo.com/v1/archive"
# Telegram: Name des Bots (ohne @) fuer den Deep Link, sobald der Bot bei
# BotFather angelegt ist. Das Token liegt im Secret apicore-telegram (nur Worker).
# TELEGRAM_BOT_USERNAME: "<bot-username>"
# Telegram: Name des Bots (ohne @) fuer den Deep Link. Leer, solange der Bot
# bei BotFather noch nicht angelegt ist (Runbook); dann den Namen eintragen.
# Das Token liegt im Secret apicore-telegram (nur Worker).
TELEGRAM_BOT_USERNAME: ""
+84
View File
@@ -315,6 +315,90 @@ test('resources match the spec table; HPA api 1–2 at 70 % CPU', () => {
assert.equal(api.doc.spec.replicas, undefined, 'the HPA owns the api replica count');
});
// The Telegram bot token belongs to the worker alone (Spec T4c): one optional
// secretKeyRef on its main container, no envFrom, no volume, no other pod.
const TELEGRAM_SECRET = 'apicore-telegram';
const TELEGRAM_TOKEN_KEY = 'TELEGRAM_BOT_TOKEN';
/** Every place a pod template can pull `secretName` in: env, envFrom, volumes. */
function secretReferences(pod, secretName) {
const refs = [];
const containers = [
...pod.containers.map((c) => ({ c, init: false })),
...pod.initContainers.map((c) => ({ c, init: true })),
];
for (const { c, init } of containers) {
for (const e of c.env ?? []) {
const ref = e.valueFrom?.secretKeyRef;
if (ref?.name === secretName) refs.push({ kind: 'env', container: c.name, init, name: e.name, ref });
}
for (const from of c.envFrom ?? []) {
if (from.secretRef?.name === secretName) refs.push({ kind: 'envFrom', container: c.name, init });
}
}
for (const v of pod.spec.volumes ?? []) {
const projected = (v.projected?.sources ?? []).some((src) => src.secret?.name === secretName);
if (v.secret?.secretName === secretName || projected) refs.push({ kind: 'volume', volume: v.name });
}
return refs;
}
for (const [label, model] of [['target', target], ...stages]) {
test(`${label}: only the worker references the apicore-telegram secret, and only optionally`, () => {
const workers = model.byApp('apicore-worker');
if (label === 'target' || workers.length > 0) {
assert.equal(workers.length, 1, `${label}: expected exactly one apicore-worker pod`);
}
for (const pod of model.pods) {
const refs = secretReferences(pod, TELEGRAM_SECRET);
if (pod.labels.app !== 'apicore-worker') {
assert.deepEqual(refs, [], `${pod.owner} must not use secret ${TELEGRAM_SECRET}`);
continue;
}
assert.equal(refs.length, 1, `${pod.owner}: expected exactly one reference to ${TELEGRAM_SECRET}`);
const [only] = refs;
assert.equal(only.kind, 'env', `${pod.owner}: the secret must come in as a single env variable`);
assert.equal(only.init, false, `${pod.owner}: init containers must not see the bot token`);
assert.equal(only.container, mainContainer(pod).name, `${pod.owner}: only the main container takes the token`);
assert.equal(only.name, TELEGRAM_TOKEN_KEY);
assert.deepEqual(only.ref, { name: TELEGRAM_SECRET, key: TELEGRAM_TOKEN_KEY, optional: true });
const tokenEnvs = [...pod.containers, ...pod.initContainers].flatMap((c) =>
(c.env ?? []).filter((e) => e.name === TELEGRAM_TOKEN_KEY),
);
assert.equal(tokenEnvs.length, 1, `${pod.owner}: expected exactly one ${TELEGRAM_TOKEN_KEY} entry`);
assert.equal(tokenEnvs[0].value, undefined, `${pod.owner}: ${TELEGRAM_TOKEN_KEY} must not be a literal`);
}
// No other pod may carry the token by value or under that variable name.
for (const pod of model.pods.filter((p) => p.labels.app !== 'apicore-worker')) {
for (const c of [...pod.containers, ...pod.initContainers]) {
assert.ok(
!(c.env ?? []).some((e) => e.name === TELEGRAM_TOKEN_KEY),
`${pod.owner}/${c.name} defines ${TELEGRAM_TOKEN_KEY}`,
);
}
}
});
test(`${label}: the bot name sits in the shared ConfigMap, the token never does`, () => {
const configMaps = model.docs.filter((d) => d.kind === 'ConfigMap' && d.metadata.name === 'apicore-backend-config');
assert.equal(configMaps.length, 1, 'expected one apicore-backend-config');
const data = configMaps[0].data ?? {};
assert.ok('TELEGRAM_BOT_USERNAME' in data, 'TELEGRAM_BOT_USERNAME missing in apicore-backend-config');
assert.ok(!(TELEGRAM_TOKEN_KEY in data), `${TELEGRAM_TOKEN_KEY} must not be in a ConfigMap`);
for (const doc of model.docs.filter((d) => d.kind === 'ConfigMap')) {
assert.ok(!(TELEGRAM_TOKEN_KEY in (doc.data ?? {})), `${doc.metadata.name} holds ${TELEGRAM_TOKEN_KEY}`);
}
// Both roles read the name from the one ConfigMap through envFrom.
// (The worker only exists from the stage that rolls out backend-roles.)
for (const pod of [...model.byApp('apicore-backend'), ...model.byApp('apicore-worker')]) {
assert.ok(
(mainContainer(pod).envFrom ?? []).some((f) => f.configMapRef?.name === 'apicore-backend-config'),
`${pod.owner} does not read apicore-backend-config`,
);
}
});
}
test('api and worker run prisma migrate deploy as initContainer; only api seeds', () => {
const api = onePod(target, 'apicore-backend');
const worker = onePod(target, 'apicore-worker');