Compare commits

..

188 Commits

Author SHA1 Message Date
60214a7c92 fix(web): zwei tsc-Buildfehler (useMutation-Rueckgabe void, Uint8Array<ArrayBuffer>)
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m18s
CI / Frontend Tests (Node/Vite) (push) Successful in 9m35s
CI / Docker Build & Push (push) Successful in 1m46s
CI / Deploy auf TrueNAS (Custom App) (push) Failing after 4s
Blockierten den CI-Frontend-Build (npm run build) und damit build-and-push.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-19 09:47:03 +02:00
45673bb066 fix(deploy): App-Home auf Pool statt read-only /opt (TrueNAS Goldeye)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-19 09:25:26 +02:00
45b8533f18 feat(deploy): TrueNAS Custom-App + Auto-Deploy, plus aufgelaufene Arbeit
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m11s
CI / Frontend Tests (Node/Vite) (push) Failing after 4m59s
CI / Docker Build & Push (push) Has been skipped
CI / Deploy auf TrueNAS (Custom App) (push) Has been skipped
Deployment:
- custom-app.compose.yaml: self-contained Compose fuer TrueNAS "Custom App"
  (absolute Host-Bind-Pfade, postgres:18, pull_policy always, Port 8090)
- scripts/truenas-deploy.sh: Host-Skript create/redeploy via midclt (App
  bleibt unter Apps sichtbar) inkl. Image-Pull + Health-Check
- ci.yml Deploy-Job: laeuft auf ubuntu-latest-Runner, kopiert Deploy-Dateien
  per SSH auf den NAS-Host und triggert truenas-deploy.sh (statt runs-on goldeye)
- compose.yaml/.env.example: postgres:18 (Locale-Match zur Quell-DB), Port 8090
- .gitignore: .agents/, tools/rag/, deploy/truenas/.env (Secrets/Scratch)

Aufgelaufene Feature-Arbeit (verified/Freeze, Migrationen, Import-Triage):
- GerbilOverride/VerifiedGerbil-Endpoints + GerbilSnapshotService + Tests
- EF-Migrationen (ShowInChronicle, Stillborn, BirthOrder, ManualFlag, DSGVO)
- Frontend VerifizierteTierePage + verified-API + e2e-Spec
- diverse Import-/Triage-Skripte und -Tests

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-19 09:19:11 +02:00
84365bba7f feat(import): 6 weitere RPRO3-Dubletten-Entscheidungen (Runde 2)
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m6s
CI / Frontend Tests (Node/Vite) (push) Failing after 4m58s
CI / Docker Build & Push (push) Has been skipped
Bali, Aladin, Lexi, Pinto, Jasper, Nestor — aus der zweiten Ticket-Runde.
rpro3-decisions.json: 14 → 20 Einträge.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 11:35:57 +02:00
a333bce1b3 feat(import): RPRO3-Dubletten-Entscheidungen der Züchterin als Override
Manuelle "gleich/verschieden?"-Entscheidungen aus den rpro3-import-Tickets
fließen jetzt in den RennmausPro-III-Import ein:

- Rpro3Decisions (Modell + JSON-Loader): same (Force-Merge), different
  (Force-Split), fields (Farbe/DOB/Herkunft/resident/Notiz). Schlüssel = rid.
- Rpro3Dedup.Run(animals, decisions): honoriert die Overrides nach dem
  automatischen Dedup (eine rid zieht ihren Cluster mit).
- Rpro3ImportService: lädt Import/Rpro3/rpro3-decisions.json, wendet
  Feld-Overrides im Plan-Builder an.
- rpro3-decisions.json: 14 bestätigte Entscheidungen (Eiji, Momo, Samuel,
  Female, Kennedy, Fegur, Tuli, Bura, Mister X, Zoey, Max, Akiro, Merlin,
  Snickers).
- tools/import/rpro3_lookup.py: Triage-Helfer (Farbe/Gencode/Eltern/
  Nachzucht+Partner aus _rpro3.db) für die Rückfragen an die Züchterin.
- 4 neue Tests (Force-Merge/Force-Split/Loader); Suite 268 grün.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 11:26:50 +02:00
bbd305861f feat(import): Hiros Eltern aus RennmausPro ergänzt (Ticket f3ad5ec9)
Hiro of Golden Lights erschien fälschlich als Gründertier (keine Eltern im Import).
Aus dem RennmausPro-Backup sicher zugeordnet (gleiches Geburtsdatum 13.02.2012):
Eltern Wynn × Amidala — als nicht-residente Ahnen-Stubs angelegt und verknüpft.

Bewusst nur EINE Generation: tiefere Ahnen würden über addAnimals-Stubs nicht
verkettet (der Eltern-Override greift nur auf echte Stammbaum-/Wurfchronik-Tiere,
nicht auf Stubs) — und mehrere Großeltern-Namen (Harry/Shy/Jack/Speedy) kollidieren
mit bestehenden, anderen Tieren. Voller mehrstufiger RennmausPro-Ahnen-Import =
eigenes Feature (Import-Code-Änderung + robustes Matching), nicht blind machbar.

python test_merge_resolve.py + test_extract.py grün.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 15:51:06 +02:00
8aaddea4ef fix(tickets): Tab + Scrollposition überleben Browser-Zurück
Zwei Ursachen, warum es auf der Tickets-Seite nicht ging (am echten Firefox/Chromium
gegen die Live-App verifiziert):

1) Tab ging verloren: der gewählte Filter-Tab (z. B. „Geschlossen") war reiner
   Component-State und sprang nach „Zurück" (Remount) auf „Offen" zurück — also war man
   in der falschen, kurzen Liste. Jetzt wird der Tab in der Session gemerkt und
   wiederhergestellt (userPicked startet weiterhin false, damit ?focus=-Deep-Links
   weiter funktionieren).

2) Scroll-Save-Heuristik zu unzuverlässig: Beim Wegnavigieren schrumpft der Inhalt von
   .app-main → der Container klemmt auf eine kleinere Position → dieses scroll-Event
   überschrieb die gemerkte Stelle. Erkennung präzisiert: nur verwerfen, wenn Position
   UND scrollHeight gleichzeitig SINKEN (= Inhalt geschrumpft/Seitenwechsel). Eine echte
   Nutzer-Scrollung verkleinert die scrollHeight nie — damit kein fälschliches Verwerfen
   echter Positionen mehr (vorherige „Höhe geändert"-Heuristik schluckte zu viel).

Tests: scroll-restore.spec erweitert (realistisches 2-Schritt-Scrollen + Tickets-Tab
überlebt Zurück), desktop+phone grün; vitest 149 grün.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 14:54:55 +02:00
54cc493230 test(e2e): Scroll-Wiederherstellung der Rennmausliste (desktop + phone)
Deckt die Regression ab, die zuletzt durchrutschte:
- Liste scrollen → Tier öffnen → Browser-Zurück → Position bleibt erhalten.
- Position überlebt App-Hintergrund/Wiederanzeige (visibilitychange).
Läuft im phone-Projekt (390x844, Touch) UND desktop, am echten Scroll-Container .app-main.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 14:33:17 +02:00
bb1b8f8c76 fix(ux): Scrollposition nicht durch Seitenwechsel-Kollaps auf 0 überschreiben
Echte Ursache (per Firefox/Chromium gegen die Live-App verifiziert): Beim Wegklicken
eines Listeneintrags wird die Seite ausgehängt → der Inhalt von .app-main kollabiert →
der Container springt auf scrollTop 0 → das löste ein scroll-Event aus, das 0 als neue
Position speicherte und die gemerkte Stelle ZERSTÖRTE, kurz bevor wir wegnavigierten.

Fix:
- scroll-Events ignorieren, wenn der Container gerade NICHT scrollbar ist
  (scrollHeight ~ clientHeight = Inhalt kollabiert/Seitenwechsel) → kein „unechter" 0-Save.
- Wiederherstellung hält den Schutz über die gesamte Settling-Phase: bei jeder DOM-Änderung
  Position erneut setzen, erst nach ~350 ms Ruhe freigeben (gegen Reflow-Races beim Nachladen).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 14:28:32 +02:00
00a3919c9f fix(ux): Scroll-Wiederherstellung am echten Scroll-Container (.app-main), nicht am Fenster
Die App scrollt NICHT das Fenster: .app-shell ist height:100dvh/overflow:hidden, der
Inhaltsbereich .app-main hat overflow-y:auto. window.scrollY/scrollTo waren daher
wirkungslos (am Desktop sichtbar). Der Hook arbeitet jetzt auf .app-main (scrollTop/
scrollTo, Scroll-Listener am Container) und beobachtet den Inhalt per MutationObserver,
um nach dem Nachladen exakt zur gemerkten Position zu springen. Fallback auf window,
falls der Container fehlt.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 14:06:56 +02:00
b0e92c363a fix(ux): zuverlässige Scroll-Wiederherstellung für Infinite-Scroll-Listen
Zwei Probleme bei der großen Rennmausliste (und allen Infinite-Scroll-Listen) nach
Zurück-Navigation behoben:

1) Event- statt Timer-basiert: Die Scroll-Wiederherstellung hängt sich jetzt per
   ResizeObserver an die Höhenänderung der Seite (Liste ist wieder da) und springt dann
   zur gemerkten Position — statt auf einen festen Timer zu warten. Bricht bei eigener
   Scroll-Eingabe ab; Sicherheitsnetz nach 15 s.

2) Infinite-Scroll baut Höhe wieder auf: useInfiniteList merkt sich (optionaler
   restoreKey) die geladene Seitenzahl je Query und lädt sie nach einer Zurück-
   Navigation wieder nach — sonst war die Liste nur 1 Seite hoch und die Position
   unerreichbar. Aktiviert für Rennmäuse, Kontakte, Würfe, Becken, Anfragen, Verträge.

tsc/eslint/vitest grün; e2e (Listen + Navigation, 41) grün.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 14:01:28 +02:00
7262b34ae9 fix(ux): Scrollposition übersteht auch Dev-Server-Hot-Reload (Vite HMR)
Bei einem HMR-/Fast-Refresh-Update rendert die Seite kurz neu (Liste kollabiert →
Sprung nach oben), ohne Navigation/pagehide. Jetzt vor `vite:beforeUpdate`/
`vite:beforeFullReload` sichern und nach `vite:afterUpdate` wiederherstellen (nur Dev;
import.meta.hot ist in Produktion undefiniert). Restore-Fenster auf 4 s erhöht, damit
auch langsam nachladende Listen die Position noch erreichen.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 13:52:16 +02:00
ebc70cc0b8 feat(ux): globale Scroll-Wiederherstellung für ALLE Listen/Seiten
Neuer Hook useScrollRestoration (einmal im AppShell gemountet) erhält die
Scrollposition je Route über:
- Zurück/Vorwärts-Navigation (POP restauriert, PUSH startet oben),
- Bildschirm-Sperre / App-Hintergrund (visibilitychange, pagehide/pageshow) —
  damit das Handy nach dem Entsperren nicht mehr oben landet.

Robust gegen nachladende Listen (rAF-Nachjustierung bis ~2,5 s, während die Liste
wächst), bricht bei eigener Scroll-Eingabe ab, Deep-Links (?focus=, #anchor) haben
Vorrang. Die bisher nur in der Tickets-Seite eingebaute Logik wurde durch den
globalen Hook ersetzt.

tsc/eslint/vitest grün; e2e (navigation/listen/tickets, 42) grün.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 13:48:02 +02:00
f9e672c707 fix(tickets): Scrollposition übersteht Handy-Sperre/Hintergrund (nicht mehr Sprung nach oben)
Bisher wurde die Scrollposition nur einmal beim Mount wiederhergestellt — sperrte das
Handy und kam zurück, war die Seite oben. Jetzt:
- Position wird beim Ausblenden sicher gesichert (visibilitychange→hidden, pagehide),
  nicht nur bei Scroll-Events.
- Wiederherstellung beim Wiederanzeigen (visibilitychange→visible, pageshow) UND nach
  dem Laden — mit mehreren rAF-Versuchen gegen nachwachsende Inhalte.
- Schutz gegen den Aufwach-Sprung nach oben: während des Wiederherstellens werden
  Scroll-Speicherungen blockiert, damit ein vom Browser ausgelöster 0-Sprung die
  gemerkte Position nicht überschreibt.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 13:41:05 +02:00
fe79be2eee feat(import): isResident-Override + Vorfahren Bentley/Alexandria/Bugatti
- Neuer isResident-Override im Import (merge_and_resolve, NACH dem Dedup, damit die
  Zusammenführung ihn nicht überschreibt). Matcht über externalRef (präzise, auch für
  namenlose Tiere) oder normalize(call-name)+dob. Ein Nicht-Bestandstier verliert den
  eigenen Zucht-Breeder.
- conflict-decisions.json: Bentley, Alexandria, Bugatti = nur Vorfahren (isResident=false),
  bestätigt von der Züchterin (Tickets 09bcac78 / 45cc501b).
- Regressionstests ergänzt/aktualisiert (Bentley/Alexandria/Bugatti isResident; Danielle
  Vater Makoto; Catelyn Eddard×Milena; Gaida Zhuāngzǐ×Zaibunissa). Alle python test_*.py grün.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 12:29:25 +02:00
41ee4ee3ab fix(import): Eltern für Danielle, Catelyn, Gaida (Triage-Antworten der Züchterin)
- Danielle: Vater Makoto ergänzt (Mutter Ella war schon gesetzt) — Geschwisterverpaarung.
- Catelyn: Eltern Eddard Stark of Sunset Glow × Milena.
- Gaida: Eltern über Geburtsdatum gefunden — Zhuāngzǐ × Zaibunissa (beide *21.02.2020,
  Geschwisterverpaarung, Kinder von Nisha × Zenon).

Per conflict-decisions.json (re-ingest verifiziert: Eltern live korrekt). Tickets
4692fd5c / 7bbc045c / ba63325a geschlossen.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 12:18:06 +02:00
f7a1a7724b feat(tickets): Web-Push-Benachrichtigungen (PWA)
- Die Züchterin kann auf der Tickets-Seite Push-Benachrichtigungen aktivieren
  (🔔-Schalter). Service Worker ist BEWUSST push-only (kein fetch/Caching), damit das
  Laden der App nie beeinträchtigt wird.
- Backend: WebPush-Bibliothek + VAPID; PushNotifier sendet an alle Abos, räumt veraltete
  (404/410) auf. Endpoints: GET /push/vapid-public-key, POST /push/subscribe|unsubscribe.
- Ausgelöst über ein notify-Flag auf PUT /feedback: NUR die KI setzt es (z. B. neue
  Rückfrage / Ticket gelöst) → keine Selbst-Pushes durch Aktionen der Züchterin. Text wird
  aus dem Status abgeleitet, Klick öffnet das Ticket (?focus=).
- Schalter/Logik blenden sich aus, wenn das Gerät kein Push kann oder der Server keine
  VAPID-Schlüssel hat (z. B. e2e-Mock).

Migration WebPushSubscriptions. VAPID-Schlüssel in appsettings.json (lokale Single-User-App
im Heimnetz — bewusste, vertretbare Vereinfachung). Tests: 264 Backend grün (+Push-Endpoints),
e2e Tickets Desktop grün, vitest 149.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 11:32:26 +02:00
750619d3d7 feat(tickets): Foto-/Datei-Anhänge an Tickets
- Anhänge im Melde-Fenster (beim Erstellen) und direkt an bestehenden Tickets:
  Vorschaubilder, Öffnen im neuen Tab, Entfernen.
- Bytes liegen in eigener Tabelle (FeedbackAttachment, lose FeedbackId ohne FK →
  übersteht den Ingest-Wipe); GET /feedback liefert nur Metadaten (id/Name/Typ/Größe),
  die Bytes über /feedback/attachments/{id}. Größenlimit 10 MB.
- Endpoints: POST /feedback/{id}/attachments (base64), GET /feedback/attachments/{id}
  (Bytes), DELETE /feedback/attachments/{id}.

Migration FeedbackAttachments. Tests: 262 Backend grün (+Upload/Serve/Delete +Validierung),
e2e Tickets Desktop+Phone grün (+Foto-Upload), vitest 149.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 11:24:02 +02:00
48b138bbfd feat(tickets): Volltextsuche + Kategorien, 👍/👎-Rückmeldung & ähnliche gelöste Tickets
- Suche: Volltext über Nachricht/Frage/Antwort/Changelog/Name/Kategorie, plus
  Kategorie-Filter (KI-gesetzte Kategorie als Chip + Auswahlmenü), je innerhalb der
  aktiven Ansicht.
- 👍/👎 auf gelösten Tickets: 👍 speichert die Rückmeldung, 👎 öffnet das Ticket
  wieder (zurück in die Rückfragen) und bittet um die fehlende Info.
- Melde-Fenster: schlägt beim Tippen ähnliche bereits gelöste Tickets vor
  (Wort-Überlappung + Bonus bei gleichem Tier/Wurf/Kontakt) — Self-Service.

Backend: Feedback.Category + Feedback.Helpful (+ PUT-Handling), Migration
FeedbackCategoryAndHelpful (beide nullable). Tests: 260 Backend grün, e2e Tickets
Desktop +4 (Suche/Kategorie/👍/👎), vitest 149.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 11:14:07 +02:00
c0a7b1a5ee feat(tickets): Wiederöffnen→Rückfrage mit Zeitstempel + Soft-Delete-Papierkorb + Scroll-Erhalt
Wiederöffnen eines gelösten Tickets:
- landet jetzt in „Rückfragen" (NeedsInfo) statt „Offen".
- War es ein echt gelöstes Ticket OHNE Rückfrage, wird um mehr Infos gebeten und
  „Wieder geöffnet am" (ReopenedAt) gestempelt.
- Hatte es bereits eine offene Rückfrage (z. B. manuell gelöste Rückfrage), kehrt es
  ohne neuen Hinweis und ohne Zeitstempel in genau diese Frage zurück.

Löschen über die UI = Soft-Delete:
- Tickets wandern in die neue Kategorie „Gelöscht" (Papierkorb) statt entfernt zu werden.
- Von dort wiederherstellbar (POST /feedback/{id}/restore → DeletedAt = null).
- Countdown „Wird in N Tagen endgültig gelöscht"; nach 30 Tagen endgültige Löschung
  (lazy beim Abruf in GET /feedback).

Außerdem: Scrollposition bleibt beim Zurück-Navigieren (z. B. nach Klick auf einen
Tier-Link) erhalten, statt an den Seitenanfang zu springen.

EF-Migration FeedbackReopenedAndSoftDelete (ReopenedAt, DeletedAt — beide nullable).
Tests: 260 Backend grün (+2 Reopen-Fälle, CRUD auf Soft-Delete umgestellt), e2e Tickets
Desktop+Phone grün (+Soft-Delete/Restore/Reopen), vitest 149.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 11:02:04 +02:00
a0fa33da42 feat(tickets): Erst-Text nach Antwort sperren, nur neueste Antwort editierbar
Sobald ein Ticket eine Antwort hat, ist der ursprüngliche Ticket-Text nicht
mehr bearbeitbar. Editierbar ist dann nur noch die neueste Antwort — und auch
die nur, bis die KI darauf reagiert hat (Status verlässt „Answered"). Ältere
Antworten im Verlauf (thread) bleiben wie bisher schreibgeschützt.

Regressionstest + Answered-Mock-Ticket ergänzt.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 10:32:04 +02:00
6b264a9b71 fix(import): Farbschlag aus Genotyp ableiten + Mamta-Eltern — Ticket-Triage
genotype.py: Python-Port von genotypeToFarbschlag (0 Abw. über 3402 Genotypen).
resolve_color_and_genotype: bei vorhandenem Genotyp gewinnt der berechnete Farbschlag
(Goldfuchs≠Gold, Dilute Agouti/Anthrazit, Blaufuchs statt -schimmel bei (schimmel),
spsp statt Schecke). Mamta Mini: Ee + Eltern Geely×Gaida am Wurf. Regressionstests je Fall.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 10:08:13 +02:00
26977d73ff docs(mempalace): Subagenten müssen MemPalace zu Aufgabenbeginn abfragen
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 09:43:12 +02:00
12f5de00a0 docs: Genetik-Engine immer voll mit Tests absichern (Konvention) + E-Locus-Regel
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 09:36:12 +02:00
0540498e85 Merge branch 'worktree-agent-a7281df1f2cc3f1f1'
# Conflicts:
#	gerbil-manager-web/src/genetics/catalog.ts
#	gerbil-manager-web/src/genetics/genotype.ts
#	gerbil-manager-web/src/genetics/punnett.ts
2026-06-23 09:29:42 +02:00
a87d1ec865 fix(api): API-Host im Dev-Modus aus window.location ableiten (LAN/Handy-Zugriff)
Statt fest http://localhost:5179 (auf dem Handy = das Handy selbst) nutzt der
Client im Dev-Modus den Host, von dem die Seite geladen wurde → 192.168.x.y:5179.
e2e/Rechner bleiben bei localhost.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 09:18:55 +02:00
8c1ee75b81 fix(genetics): Engine-Fixes Ticket-Triage (Goldfuchsschimmel, Dilute CP-Blaufuchs, Eltern-Inferenz, Punnett, uw[d])
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 09:05:35 +02:00
aa4552ff84 docs(triage): Genetik-Vorlauf-Notizen als Referenz für Engine-Fixes
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m8s
CI / Frontend Tests (Node/Vite) (push) Failing after 4m55s
CI / Docker Build & Push (push) Has been skipped
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 08:34:54 +02:00
18d74ff3f3 docs(triage): Ticket-Triage-Matrix (Lauf 56 Tickets)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 08:29:12 +02:00
72ad706ca6 fix(import): Eltern-/Herkunft-/Dubletten-Korrekturen — Ticket-Triage Cluster
Akane (Roni=Vater male + Mutter Fumi), Sunny (Bill+Melly), Danielle (Mutter Ella,
motherDob-Disambiguierung), Cherry Berry (female), Black-Forest-Label vereinheitlicht,
namenloser Bock entdoppelt (mergeExternalRefs).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 08:25:43 +02:00
a66739e84d feat(import): „Was wird (nicht) importiert"-Hinweis auf der RPRO3-Import-Seite
Klarstellung für die Züchterin: übernommen werden Tiere/Stammbäume/Genotypen/
Würfe/Kontakte/Gehege+Reinigung/Erwerb/Reservierung/Rücknahmen/Warteliste/
Ausstellungen; (noch) nicht: Finanzen, Termine, Tierarzt-Stammdaten, Tagebuch.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 07:24:59 +02:00
00dba91a5c feat(tickets): Kurz-Verweise (Shortlinks) im Ticket-Text auflösen
Die KI kann im Text `tier:<8hex>` / `kontakt:` / `wurf:` / `gehege:` schreiben;
Frontend löst per POST /refs/resolve (Präfix-Match, DB-agnostisch) zu Name +
internem Link auf. Reine KI-Schreibhilfe — kein Nutzer-Button.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 07:23:03 +02:00
c7b054e909 feat(import): RPRO3-Importer um 6 Feature-Tabellen erweitern
becken→Gehege-Reinigung, herktier→Erwerb, abgeben/abstat→Reservierung,
getback→Rücknahmen, nachfrage→Warteliste, ausz→Ausstellungen.
Deterministische GUIDs, idempotenter Re-Import.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 07:05:01 +02:00
00dc724605 test(e2e): Gewicht-Tab-Button im Tabpanel ansprechen (Erwerb-Sektion-Kollision)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 23:15:23 +02:00
156ede120e Merge branch 'worktree-agent-ae59040b377a324cb'
# Conflicts:
#	GerbilManagerWebAPI/ApplicationContext.cs
#	GerbilManagerWebAPI/Program.cs
#	gerbil-manager-web/e2e/mock-data.ts
#	gerbil-manager-web/src/pages/GerbilDetailPage.tsx
#	gerbil-manager-web/src/strings/de.ts
2026-06-22 23:10:18 +02:00
db2c29769e Merge branch 'worktree-agent-a02f88e8490625846'
# Conflicts:
#	GerbilManagerWebAPI/ApplicationContext.cs
#	GerbilManagerWebAPI/Program.cs
#	gerbil-manager-web/e2e/mock-data.ts
#	gerbil-manager-web/src/App.tsx
#	gerbil-manager-web/src/components/AppShell.tsx
#	gerbil-manager-web/src/strings/de.ts
2026-06-22 23:07:22 +02:00
ae7d171131 Merge branch 'worktree-agent-a0e6f31173772c798'
# Conflicts:
#	GerbilManagerWebAPI/ApplicationContext.cs
#	GerbilManagerWebAPI/Program.cs
#	gerbil-manager-web/e2e/mock-data.ts
#	gerbil-manager-web/src/strings/de.ts
2026-06-22 23:02:17 +02:00
6a64698601 Merge branch 'worktree-agent-a36d202be311b9289'
# Conflicts:
#	GerbilManagerWebAPI/ApplicationContext.cs
#	GerbilManagerWebAPI/Program.cs
#	gerbil-manager-web/e2e/mock-data.ts
2026-06-22 22:57:16 +02:00
1469a7f3dc Merge branch 'worktree-agent-a5f48334696288159'
# Conflicts:
#	gerbil-manager-web/e2e/mock-data.ts
2026-06-22 22:54:50 +02:00
6123b8ef9e Merge branch 'worktree-agent-a9d8edbd439109a45' 2026-06-22 22:53:33 +02:00
0b0ebd5fad Merge branch 'worktree-agent-a1dfa0392b5ace900'
# Conflicts:
#	gerbil-manager-web/e2e/mock-data.ts
#	gerbil-manager-web/src/App.tsx
2026-06-22 22:53:10 +02:00
4ec0f787dd feat(tickets): Markdown in Texten + Editier-Regeln für Rückfragen
- Ticket-Texte (Frage/Antwort/Nachricht/Changelog/Verlauf) rendern eine
  Markdown-Teilmenge: **fett**, `code`, Aufzählungen, Links, Tier-/Ticket-IDs
- Offene Rückfrage (NeedsInfo): nicht bearbeitbar — die Züchterin soll antworten
- Beantwortet (Answered): Antwort nachträglich änderbar, bevor die KI übernimmt

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 22:51:00 +02:00
d380a0c2ef feat(ausstellungen): Ausstellungs-/Auszeichnungsergebnisse je Tier
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 22:43:19 +02:00
40c92c70d4 feat(abgabe): Reservierungs-/Abgabe-Status (verfügbar/reserviert/abgegeben)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 22:43:19 +02:00
4e7cd21b70 feat(gehege): Reinigungszyklus (Maße, Kapazität, letzte/nächste Reinigung)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 22:43:19 +02:00
3ad276637c feat(import): RennmausPro-III-Backup-Importer (analyze+execute, Dedup, Fotos)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 22:43:19 +02:00
b4dc37de78 feat(ruecknahmen): zurückgenommene Tiere erfassen
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 22:43:18 +02:00
d25d2ee152 feat(warteliste): Nachfrage/Warteliste für Interessenten
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 22:43:18 +02:00
55e79cda51 feat(tier): Erwerb/Kauf je Tier (Datum, Preis, Notiz)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 22:43:18 +02:00
23f028123d fix(tickets): beantwortete Rückfragen stehen wieder unter „Offen"
Bisher landeten beantwortete Tickets (Answered) in „Rückfragen". Sobald die
Züchterin geantwortet hat, ist sie fertig → das Ticket gehört in „Offen"
(von der KI zu erledigen). „Rückfragen" zeigt jetzt nur noch NeedsInfo
(wartet auf ihre Antwort).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 22:42:04 +02:00
4e30dc7fe3 feat(import): RennmausPro-III-Analyse — Abgleich, Dedup, Feature-Gap, Ticket-Generierung
- compare_rpro3.py: RPRO3-SQLite ↔ aktueller Stand (Dedup Name+DOB+Farbe+Herkunft)
- rpro3-vergleich.md / rpro3-feature-gap.md: erzeugte Reports
- rpro3_tickets.py / rpro3_post_tickets.py: 413 Rückfrage-Tickets mit Herkunft + Links

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 22:38:24 +02:00
c15dd78bc7 feat(pwa): installierbar als App-Icon (Manifest + Icons)
Web-App-Manifest, App-Icons (192/512 + maskable, Rennmaus-Motiv) und
apple-touch-icon/theme-color in index.html → "Zum Startbildschirm hinzufügen".

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 22:38:24 +02:00
dcf0e40f9b feat(tickets): Rückfragen-Dialog, Verlinkungen, Entwurfssicherung + PWA-Vorbereitung
- Feedback: fixNote (Changelog), agentContext (intern), thread (Q&A-Verlauf);
  3 gefilterte Ansichten (Rückfragen/Offen/Geschlossen)
- Tickets-Text: klickbare Tier-Links (ID→Name), Ticket→Ticket-Links (?focus=),
  Markdown-Links; Antwort-Entwurf pro Ticket in localStorage
- "Fehler melden": Entwurf übersteht App-Wechsel/Schließen (ein gemeinsamer Entwurf)
- entityName als Hyperlink zum referenzierten Datensatz

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 22:38:23 +02:00
b9021fe577 chore: Postman-Collection entfernt, GerbilERM.drawio nach docs/ verschoben
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 21:17:04 +02:00
ce1704c3b7 fix(import): Stammbaum-/Eltern-/isResident-Tickets der Züchterin (18)
Import-Logik:
- Externe Gründer (Zooladen/„von Privat"/„from …, <Land>") bekommen keine
  erfundenen Chart-Eltern mehr → Bill, Cooky, Zadar haben korrekt unbekannte
  Eltern (is_external_origin). [#5,#13,#28]
- Hagrid: externe Zucht wird nicht mehr als Bestand markiert (isResident=false)
  + Leerhüllen-Dedup → ein Datensatz mit Eltern Snickers × Milka. [#17,#18,#20a]
- Gender-Index: eindeutiges Geschlecht schlägt unbekanntes Duplikat → Rollen-
  Auflösung repariert (Vance→Mutter Enya, Zac→Vater Vance/Mutter Dorie). [#33,#35]
- „Eltern: X + Y"-Wurfnotizen werden geparst (~46 Würfe); v.d.↔von-den-Namens-
  kanon (Theodore→BlackFire). [#9,#11,#30]

Daten-Overrides (conflict-decisions.json, jetzt auch Gender + exakte Eltern):
- Mozart→weiblich [#2], Yuki=Camaro×Izumi [#23], Gold-Mutter=Chelsea [#36],
  Arya=Vance×Sansa (Geschwisterverpaarung) [#16], Tony→Sammy [#12],
  Odelia [#15], Jamie→Danny [#31], Silver=Taro×Beatrice [#11].

Frontend: GerbilDetailPage blendet für isResident=false Würfe + Charakter aus
(Hinweis nonResidentNote). [#17,#20b]

Tests: test_extract/test_merge_resolve erweitert; vitest 135, playwright tiere 34 grün.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 21:16:53 +02:00
9c6ca2118a docs(skill): internes agentContext-Feld am Ticket (Züchterin-unsichtbar)
Da Subagenten sitzungsgebunden sind, dient ein internes, in der Züchterin-UI
NICHT sichtbares Feld `agentContext` als Arbeitsgedächtnis: der Agent legt dort
Befunde/Ursache/Plan/„worauf gewartet wird"/erledigte Teilschritte ab und setzt
beim Wiederaufgreifen (Answered) genau dort an — statt neu zu untersuchen.
Trennung: agentContext technisch/intern; Frage/Antwort/fixNote bleiben
laienverständlich. PUT {agentContext} aktualisiert ohne Status-Wechsel.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 21:14:47 +02:00
8bfa2a7911 docs(skill): Mehrrunden-Rückfragen + verständlicher Laien-Changelog
- Mehrrundiger Dialog (Open→NeedsInfo→Answered→…→Resolved): jede weitere Antwort
  bringt das Ticket wieder in Bearbeitung. Kontext-Träger ist das TICKET (voller
  Verlauf + Triage-Eintrag), nicht der Subagent (sitzungsgebunden) — ein
  wiederaufgreifender Agent rekonstruiert denselben Kontext; echte Agent-
  Fortsetzung nur innerhalb einer Session via SendMessage. Datenmodell:
  Frage/Antwort als Thread (mehrere Runden), nicht nur ein Paar.
- fixNote-Changelog: harte Regel „nur für die Züchterin, kein Technik-Geschwafel"
  + Gut/Schlecht-Beispiele (Tiernamen statt IDs, keine Datei-/Feldnamen).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 21:13:51 +02:00
5edd84046d docs(skill): Triage-Subagenten schließen Tickets terminal ab (Changelog/Rückfrage)
Skill präzisiert: jeder bearbeitende Subagent schließt seinen Vorgang selbst ab —
Rückfrage ordentlich stellen (eine konkrete Frage, einfache Sprache, Kontext →
NeedsInfo) ODER nach verifiziertem + eingespieltem Fix mit verständlichem
fixNote-Changelog schließen (Resolved). Abschluss-Regel ergänzt: kein
Open/Answered-Ticket bleibt offen liegen — Endzustand immer NeedsInfo oder Resolved.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 21:12:03 +02:00
d27a389f0e feat(skill): ticket-triage — Fehlerberichte automatisiert abarbeiten
Skill kapselt den erprobten Ablauf: Tickets aus /feedback holen, nach Status
einteilen (Open/Answered = KI dran, NeedsInfo/Resolved überspringen), je Ticket
ein Triage-Subagent (Workflow-Fan-out) mit strukturierter Empfehlung + Cluster,
Rückfragen via PUT question (→ NeedsInfo) anhängen, beantwortete Tickets wieder
aufgreifen, Fixes gebündelt nach datei-disjunkten Clustern umsetzen, Import neu
einspielen und Tickets MIT fixNote (verständlicher Changelog) auf Resolved setzen.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 21:07:04 +02:00
b437d09312 fix(genetics): Genotyp-/Farbschlag-Engine-Bugs aus Ticket-Triage
- uw/Uwuw[d] (dichtes Underwhite) wird vor dem uw→G-Locus-Alias korrekt geparst
  (Vance: nicht mehr „Unbekannter Farbschlag", zeigt G-Locus statt international uw). [#34,#32]
- ee[-] = sichtbarer Fuchs (rezessiv homozygot) → korrekt als Fuchs; bare „e-"
  (rezessiv + unbekannt) ist genetisch unmöglich → genotypeInvalid statt still falsch. [#42]
- aa-Colourpoint-Zweig berücksichtigt jetzt D (Dilute) und E (Fuchs), statt fix
  Zobel/Marder/Siam zu erzwingen. [#3]
- Wurf-Farbprognose: unbekanntes Allel (?) wird nicht mehr über die volle Dominanz
  expandiert → keine unmöglichen Dilute-/Schimmel-/„Unbekannt"-Nachkommen. [#37,#39,#40,#41,#38]

Tests: test_genotype.py erweitert; genetics.test.ts +5 Blöcke (135 vitest grün, tsc/eslint sauber).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 21:04:05 +02:00
5069c0eb1e feat(tickets): Rückfrage am Ticket + Antwort durch die Züchterin
Tickets können jetzt eine Rückfrage (Question) tragen und die Züchterin kann
in-app antworten. Feedback um FK-freie Felder Question/Answer/AnsweredAt erweitert
(überlebt Ingest-Wipe); Status-Lebenszyklus Open → NeedsInfo (Rückfrage gestellt)
→ Answered (beantwortet) → Resolved. Migration AddFeedbackQuestionAnswer.

PUT /feedback/{id}: question → NeedsInfo, answer → Answered+AnsweredAt; DTO gibt
die Felder zurück. Tickets-Seite (/hilfe/tickets) zeigt die Rückfrage hervorgehoben
und bietet ein Antwort-Feld + „Antworten"; Status-Badges Offen/Rückfrage offen/
Beantwortet/Gelöst.

Tests: FeedbackEndpointTests (Frage→NeedsInfo, Antwort→Answered, übersteht Ingest),
e2e tickets.spec.ts. dotnet/vitest/playwright grün.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 19:52:34 +02:00
f1c1069821 docs: Triage aller 42 Fehlerberichte (Empfehlungen + Cluster-Matrix)
Automatische Triage (ein Subagent pro Ticket): pro Ticket Ursache, Empfehlung,
Fix-Ebene, betroffene Dateien, Aufwand, Konfidenz + Überschneidungs-Matrix nach
Cluster und offene Rückfragen an die Züchterin. Grundlage für die gebündelte
Implementierung nach Cluster.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 19:42:50 +02:00
3f31a2efbc chore(memory): MemPalace automatisch einbinden + Memory-Policy in CLAUDE.md
.claude/settings.json (committet) verdrahtet die MemPalace-Hooks
(session-start lädt Kontext, stop/precompact persistieren) → künftige Claude-
Sessions in diesem Ordner nutzen MemPalace automatisch (zusammen mit .mcp.json,
das die 19 MCP-Tools bereitstellt; aktiv nach Claude-Neustart).

CLAUDE.md: Abschnitt „Gedächtnis (MemPalace)" + Memory-Policy (WANN/WIE/WO eine
Memory angelegt wird: durable & nicht-offensichtlich → Palast; kanonisch &
projektweit → zusätzlich CLAUDE.md; Veraltetes per kg_invalidate beenden statt
löschen).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 18:10:34 +02:00
4c0cba854a chore(mcp): MemPalace-MCP-Server im Repo registrieren (.mcp.json)
Bindet den lokal installierten MemPalace-Server (mempalace-mcp) als projekt-
gescopten MCP-Server ein, damit das KI-Gedächtnis ab der nächsten Claude-Session
verbunden ist und die Integration im Repo (geteilt/versioniert) statt nur lokal
liegt. Aktiviert nach Claude-Neustart (Bestätigung des MCP-Servers nötig).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 18:03:11 +02:00
ac06cadb23 feat(hilfe): Eigene Tickets — Fehlerberichte ansehen, bearbeiten, löschen, lösen
Unter Hilfe (/hilfe/tickets) eine Verwaltung der eingereichten „Fehler melden"-
Berichte: Liste (neueste zuerst) mit Status-Badge (Offen / ✓ Gelöst), Kontext-
Label, betroffenem Objekt, Nachricht und Datum. Pro Ticket: als gelöst markieren/
wieder öffnen, Nachricht inline bearbeiten, löschen (mit Bestätigung).

Backend: Feedback um Status ("Open"/"Resolved", Default Open) + nullable ResolvedAt
erweitert (weiterhin FK-frei → übersteht Ingest-Wipe); Migration AddFeedbackStatus.
Endpoints: GET /feedback (neueste zuerst, inkl. Status), PUT /feedback/{id}
(Nachricht/Status; leer→400, fehlt→404; lösen setzt/öffnen löscht ResolvedAt),
DELETE /feedback/{id} (fehlt→404).

Tests: FeedbackEndpointTests (CRUD + Status-Lebenszyklus + übersteht Ingest),
e2e tickets.spec.ts; dotnet 215, vitest 129, playwright grün.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 17:52:50 +02:00
e1299a1a63 docs: CLAUDE.md mit Architektur, Import-Workflow, Konventionen & Domänenwissen
Leitfaden für künftige Arbeit: Projekt-/Architektur-Überblick, Start über Aspire
(Ports/Dashboard/persistentes Volume), 3-stufiger Import→DB-Workflow (Ingest
wischt+lädt, Feedback überlebt), Build/Test je Schicht, Konventionen (de.ts,
Migrationen, Provenance-JSON, FK-freie Survivor-Spalten), Domänenwissen
(Lebensspanne/Geschwisterverpaarung/Genotyp/Chart-Layout), Stolperfallen
(Aspire-Container vs. Volume, Migrations-Historie-Mismatch, psql-Quoting) und
eine Feature-Landkarte.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 17:44:18 +02:00
5175c3229a feat(import): Abgabeverträge als SaleContract-Datensätze importieren
Die ~1095 geparsten Verträge werden jetzt als echte SaleContract-Records erzeugt,
sodass die Verträge-Seite gefüllt ist (statt 0). enrich_from_contracts() liefert
zusätzlich eine saleContracts-Liste (deterministische Id aus Dateiname, Käufer-
ContactId, Preis, Abgabe-/Vertragsdatum, FileName, gematchte Tier-Ids); main()
schreibt sie als Top-Level-Key in resolved_import.json. IngestResolvedService legt
SaleContract + SaleContractAnimal an (FK-sicher nach Kontakten/Tieren, unbekannte
Links übersprungen) — Tabelle wird wie gehabt gewischt und aus dem Payload neu
befüllt (idempotent).

Ergebnis: 1033 Verträge (611 mit ≥1 Tier, alle datiert; 54 Dateinamen-Dubletten
zusammengefasst, 7 datumlose + 1 ohne Käufer übersprungen). Kein Schema-Change
(datumlose übersprungen statt Spalten nullable → keine Migration).

DOCX-Download: importierte Verträge haben keine Word-Datei im contract-storage →
DTO.HasFile=false, Frontend blendet den Word-Button aus (Hinweis „Keine Word-
Datei"), PDF wird weiterhin generiert. Download-Endpoint liefert sauber 404 statt
500 bei fehlender Datei.

Tests: dotnet 213, vitest 129, playwright 16 (neuer vertraege.spec.ts), Python grün.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 17:33:58 +02:00
5e14124322 feat(import): Abgabeverträge (DOCX) auswerten und Tiere/Kontakte anreichern
All checks were successful
CI / Backend Tests (.NET) (push) Successful in 1m1s
CI / Frontend Tests (Node/Vite) (push) Successful in 9m35s
CI / Docker Build & Push (push) Successful in 1m18s
Neuer Parser extract_contracts.py liest die ~1,4k Abgabevertrags-DOCX
(\truenas\…\Verträge): er extrahiert aus dem Dokument-Body (zuverlässiger als
die Dateinamen) Käufer, Tier(e), Farbschlag, Abgabedatum und Preis — robust
gegen Word-Run-Splits (z. B. „F r au"/„3 0,00"); überspringt Vorlage,
Abstammungsnachweise und als .docx getarnte .doc.

enrich_from_contracts() in merge_and_resolve.py: Käufer werden als Kontakte
(IsReceiver) angelegt/zusammengeführt; Tiere werden KONSERVATIV per Rufname
(+ DOB-Jahr bei Mehrdeutigkeit) auf eigene Bestandstiere gematcht und erhalten
ReceiverContactId, GoHomeDate und Status „abgegeben" — nur wo nicht bereits
gesetzt; Konflikte werden geloggt, nicht überschrieben. Jede Übernahme bekommt
eine Herkunfts-Zeile („Abgabe an … aus Vertrag … übernommen.").

Ergebnis: 1095 Verträge → 783 Tier-Treffer (400 mehrdeutige übersprungen),
274 neue Abnehmer-Kontakte, 153 Tiere mit Abnehmer, 49 mit Abgabedatum,
23 neu „abgegeben". Keine Backend-/Frontend-Änderung nötig (Akte zeigt Abnehmer/
Abgabedatum/Herkunft bereits). SaleContract-Records bewusst nicht erzeugt
(bräuchte Migration + ingest-sichere Id — späterer Schritt).

Tests: test_extract_contracts.py (Dateiname/Body/Run-Split/Skip-Regeln) + alle
bestehenden grün; dotnet 212.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 16:53:47 +02:00
aa473b764e feat(provenance): verworfene Daten mit Grund + Ersatz im Verlauf zeigen
Der Herkunfts-Verlauf nennt jetzt auch, wenn ein Wert aus einer Quelle VERWORFEN
wurde — mit Grund und was stattdessen verwendet wurde (⚠-Markierung), z. B.:
- „⚠ Vater-Kandidat ‚Danielle' (*04.03.2020) verworfen — falsches Geschlecht für
  die Vaterrolle; ‚Hagrid Rubeus' verwendet." (Molly)
- „⚠ Geschlecht weiblich aus ‚Wurfchronik.docx' verworfen — abweichend; männlich
  aus ‚Alberto Kids.xlsx' verwendet (Mehrheit)." (Solice)
- „⚠ Vater ‚Jasper Jacob' (*2018) verworfen — unplausibel (7 Jahre älter); kein
  Ersatz." / DOB-Remap: „⚠ Geburtsdatum 22.08.2018 verworfen — per manueller
  Entscheidung korrigiert; 14.07.2019 verwendet." (Kazuya)

Import: generischer _format_discard()-Helfer; Verwerfungen aus Mehrheitsentscheid,
pick_parent_ref-Ablehnungen (explain_pick_rejections), Rollen-Normalisierung,
Eltern-Alter-Sanity-Check und DOB-Remaps werden über _discarded/_prov_args an die
Tiere gehängt; Gerbil-Provenance wird in einem finalen Pass gebaut (nachdem alle
Verwerfungen feststehen). Frontend hebt ⚠-Zeilen ab (+ Legende).

Tests grün (python merge/extract, vitest 129, playwright 8, dotnet 212).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 16:34:33 +02:00
2befe53df9 feat(stammbaum): Desktop-Ansicht passt den ganzen Baum ein + höhere Zeichenfläche
All checks were successful
CI / Backend Tests (.NET) (push) Successful in 1m3s
CI / Frontend Tests (Node/Vite) (push) Successful in 9m35s
CI / Docker Build & Push (push) Successful in 1m30s
Auf dem Desktop wurde der Baum bei festem Zoom 1 rechts abgeschnitten (man sah
nur 1–2 Generationen, der Rest lag außerhalb) und viel Fläche blieb leer. Die
Standard-Ansicht passt jetzt den gesamten geladenen Baum ein — gedeckelt auf
Zoom 1, damit Karten bei kleinen Bäumen nicht vergrößert/unscharf werden. Mobil
bleibt es bei „Wurzel links + Pan" (sonst würden die Karten winzig). Zeichen-
fläche von 62dvh auf 72dvh erhöht (füllt die Desktop-Höhe besser).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 16:26:50 +02:00
cf672c0933 feat(provenance): Datenherkunft als chronologischer, datei-attribuierter Verlauf
Die Herkunft liest sich jetzt wie eine History: pro Feld wird genannt, aus
welcher Quelldatei der Wert kam, plus Merge-/Entscheidungs-/Wurfchronik-Schritte.
Beispiel: „In ‚X.xlsx' gefunden." → „Geburtsdatum (…) aus ‚X.xlsx'." → „Auch in
‚Y.docx' gefunden → zusammengeführt." → „Eltern über Position erkannt (Quelle …)."

Import: build_entity_provenance() um history[] erweitert; ein field_source-
Tracking im Gerbil-Dedup hält fest, welcher Datensatz/welche Datei jedes Feld
(DOB/Genotyp/Geschlecht/Farbschlag/Sterbedatum) lieferte — auch über Empty-Fill
und Mehrheitsentscheid hinweg. Kontakte und Würfe erhalten analoge, datei-
attribuierte Verläufe. Kein DB-Migration nötig (history liegt im Provenance-JSON).

Frontend: ProvenanceDialog rendert den Verlauf als nummerierte Timeline.
Tests: history wird erzeugt, nennt Dateien, überlebt Ingest (dotnet 212,
vitest 129, playwright 17, python merge/extract grün).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 16:21:24 +02:00
a31fea17fa feat(stammbaum): Kontextmenü per Long-Press auf Touch-Geräten öffnen
Das Rechtsklick-Kontextmenü (ID kopieren / Fehler melden) war auf Mobil nicht
erreichbar (onContextMenu feuert auf Touch nicht zuverlässig). Jetzt öffnet ein
langer Druck (~500 ms ohne Verschieben) auf eine Ahnenkarte dasselbe Menü; der
darauf folgende synthetische Klick (Umwurzeln) wird unterdrückt. Bewegung >10 px
bricht den Long-Press ab (kollidiert nicht mit Pan/Zoom). Legenden-Hinweis
ergänzt. e2e: Long-Press öffnet das Menü (desktop; phone-Projekt übersprungen,
da synthetischer Touch dort instabil).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 16:09:47 +02:00
438c816820 feat: Fehler-melden + Datenherkunft auf Kontakte & Würfe erweitern
- Kontakt-Detailseite: „Fehler melden"- und „Datenherkunft"-Button.
- Wurf-Ansicht: „Datenherkunft"-Button (Feedback war bereits vorhanden).
- Feedback-Entity um loses, nullable ContactId erweitert (kein FK → übersteht
  Ingest-Wipe); Migration AddFeedbackContactId.
- Contact.Provenance + Litter.Provenance (nullable text); Migration
  AddContactLitterProvenance; im Ingest gemappt und in den DTOs zurückgegeben.
- Import: build_entity_provenance() generalisiert; Kontakte (sourceFiles,
  Züchter/Abnehmer-Hinweise) und Würfe (Wurfchronik vs. Diagramm-rekonstruiert,
  Geschwister-Merge) erhalten Herkunftsdaten in resolved_import.json.
- Frontend: ProvenanceDialog generalisiert (EntityProvenance + entityLabel).

Tests erweitert (Ingest-Round-trip Kontakt/Wurf, contact-scoped Feedback
übersteht Wipe). dotnet(212)/vitest(129)/playwright(36)/tsc/eslint grün.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 16:02:11 +02:00
9c98c37d2a feat(rennmausakte): Datenherkunft/Nachverfolgung pro Rennmaus
Neuer „Datenherkunft"-Button in der Rennmausakte öffnet einen Dialog, der zeigt,
aus welchen Quellen der Eintrag erzeugt wurde: Quelldateien (Stammbäume +
Wurfchronik), Anzahl zusammengeführter Datensätze, Eltern-Herleitung
(Methode/Konfidenz) und Hinweise (z. B. „per manueller Entscheidung zugeordnet",
„Konflikt gelöst", „aus N Datensätzen zusammengeführt").

Import: build_provenance() in merge_and_resolve.py sammelt die Herkunft über alle
deduplizierten Datensätze und schreibt sie als Provenance-JSON je Tier in
resolved_import.json. Backend: Gerbil.Provenance (nullable text) + Migration
AddGerbilProvenance, gemappt im Ingest und im GerbilDto zurückgegeben. Frontend:
ProvenanceDialog + Typen + Strings.

Tests: Ingest-Round-trip (vorhanden/abwesend), e2e provenance.spec.ts.
dotnet(212)/vitest(129)/playwright/tsc/eslint grün.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 15:45:15 +02:00
b9e5b031c4 feat(feedback): Fehler-melden-Dialog + ID-kopieren (Stammbaum/Akte/Wurf)
Rechtsklick auf eine Maus im Stammbaum öffnet ein Kontextmenü mit „ID kopieren"
(Clipboard + Toast) und „Fehler melden". Zusätzlich „Fehler melden"-Buttons in
der Rennmausakte und der Wurf-Ansicht. Der Dialog erfasst eine Beschreibung und
sendet sie samt Debug-Kontext (Ansicht, Tier-/Wurf-ID + Name, URL, Zeitstempel,
User-Agent) an POST /feedback; gespeichert in einer neuen Feedback-Tabelle.

Backend: Feedback-Entity (lose nullable GerbilId/LitterId ohne FK), Endpoints
POST/GET /feedback, EF-Migration AddFeedback. Die Tabelle wird vom Import-Ingest
NICHT geleert — Feedback überlebt Re-Ingests (Test deckt das ab).

Tests: FeedbackEndpointTests (persistiert, 400 bei leer, übersteht Ingest-Wipe);
e2e feedback.spec.ts. tsc/eslint/vitest(129)/playwright(6)/dotnet(212) grün.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 15:30:42 +02:00
1845d37476 fix(import): Eltern-Ref-Auswahl geschlechts-bewusst machen (Regression behoben)
Die in 03ad9e6 eingeführte DOB-Bevorzugung war zu grob: ein datierter, aber
geschlechts-falscher Ref (z. B. weibliche „Danielle") gewann den Vater-Slot
gegen einen undatieren männlichen/unbekannten (z. B. „Hagrid Rubeus") — wodurch
Mollys korrekte Mutter Arya Stark in der Rollen-Normalisierung verloren ging.

pick_parent_ref wertet jetzt zuerst das (aus den Tierdaten ermittelte) Geschlecht
für die Rolle: ein klar falsches Geschlecht wird stark abgewertet, erst danach
zählt plausibles DOB > kein DOB > unplausibles DOB. Fixt Molly (Hagrid × Arya)
UND behält Solice (Lui × Molly = Geschwister von Silvain). Keine Abdeckungs-
Regression (0 Selbst-Verpaarungen / 0 Gender-Fehler / 0 Alter-Verletzungen).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 15:11:53 +02:00
2868aad369 feat(stammbaum): gleiches Geburtsdatum der Eltern als Geschwister-Indiz werten
Ein identisches Geburtsdatum bei Vater und Mutter ist ein starkes Indiz für eine
Vollgeschwister-Verpaarung — ein gemeinsamer Wurf ist praktisch der einzige
Grund dafür, und die Eltern-Würfe sind in den importierten Daten nicht immer
verknüpft (gleiche litterId fehlt dann).

Die Geschwister-Erkennung (Diagramm-Zusammenführung in build.ts + Akte-Chip in
GerbilDetailPage) greift jetzt bei gleicher litterId ODER gleichem, gesetztem
Geburtsdatum beider Eltern (distinkte Tiere vorausgesetzt).

Tests: gleiches DOB bei fehlender/verschiedener litterId → erkannt; unterschied-
liches DOB → nicht erkannt.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 15:02:19 +02:00
03ad9e6e81 fix(import): Eltern-Alter-Sanity-Check + plausiblere Eltern-Auswahl aus Chart-Refs
Eine Rennmaus lebt max ~6 Jahre, kann also nicht Elternteil eines Tiers sein,
das nach ihrem Tod (oder vor ihrer Geburt) geboren wurde. Bisher fehlte diese
Prüfung: z. B. war Jayjay (*2013) als Vater von Solice (*2022) eingetragen, und
Solice/Silvain (Vollgeschwister, beide *27.03.2022) landeten in getrennten
Würfen mit verschiedenen Eltern.

- parent_age_plausible(): Elternteil muss vor dem Kind UND innerhalb der
  Lebensspanne (≤6 J.) geboren sein. Genutzt im Namens-Resolver (Kandidaten-
  filter) und als finaler Sanity-Pass, der unmögliche FatherId/MotherId verwirft
  und im Log auflistet.
- pick_parent_ref(): bei mehreren widersprüchlichen Chart-parentRefs wird nicht
  mehr blind der erste genommen, sondern ein alters-plausibler bevorzugt und das
  Tier der jeweils anderen Elternrolle gemieden (Vollgeschwister-Charts nennen
  denselben Namen in beiden Slots).

Ergebnis: Solice = Lui × Molly = Geschwister von Silvain (gemeinsamer Wurf);
0 Selbst-Verpaarungen, 0 Gender-Rollen-Fehler, 0 Eltern-Alter-Verletzungen über
alle 977 Würfe. Tests in test_merge_resolve.py ergänzt.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 14:59:34 +02:00
18efab6996 fix(import): Foto-Generations-Shift beim Stammbaum-Import beheben
Fotos liegen in den Stammbaum-xlsx je nach Datei links, rechts oder auf der
Namenszelle. Die alte Seiten-Erkennung hing an festen Spalten (col 1 / col 4):
Blätter ohne solche Anker wurden als Rechts-Layout fehlgedeutet, wodurch jedes
Foto eine Generation zum Probanden hin verrutschte. Folge: Kazuya trug das Foto
seines Vaters (Wilbur), Wilbur das seines Großvaters (Elay), Elay hatte keins.

Fix (extract._attach_photos): beide Interpretationen (links/rechts) durchrechnen
und die wählen, die jedes Foto am nächsten an die Namensspalte seines Tiers legt
(minimale horizontale Fehlausrichtung). Diagnose über alle 42 Dateien: keine ist
echt rechts-seitig; ~21 waren fehlklassifiziert. Selbstjustierend statt fester
Spalten-Annahme.

Regressionstest in test_extract.py: Kazuya ohne Foto, Wilbur/Elay mit ihren
eigenen (gated auf vorhandene Quelldatei).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 14:49:38 +02:00
070a896072 feat(rennmausakte): Hinweis-Chip für Geschwisterverpaarung in der Tierakte
Stammt ein Tier aus einer Vollgeschwister-Verpaarung (Vater und Mutter teilen
dieselbe litterId), zeigt die Rennmausakte jetzt einen Chip
"⚭ Geschwisterverpaarung" in der Fakten-Zeile — neben Geschlecht, Geburtsdatum
und Farbschlag, in Akzentfarbe hervorgehoben (zuchtrelevant).

e2e-Test: Chip erscheint für 'Inzucht Kind' (Eltern aus demselben Wurf),
nicht für 'Krümel' (Eltern aus verschiedenen Würfen).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 14:32:36 +02:00
3715e32303 fix(stammbaum): Geschwister-Verpaarung erkennen und im Diagramm zusammenführen
Vollgeschwister-Verpaarung (Vater & Mutter aus demselben Wurf) ist in der
Gerbil-Zucht häufig. Bisher zeigten Diagramm und Import sie nicht korrekt.

Import (merge_and_resolve.py):
- Wurf-Dedup gehärtet: asymmetrischer Merge nur bei kompatiblen Eltern-Namen;
  bei Date=None nur mit positivem Namens-Match (verhindert blindes Verschmelzen
  unverwandter datumloser Stubs). Falsch-Merges 112 -> 70.
- Parent-Resolver robust: Gender ist Präferenz statt hartem Filter, sodass
  vertauschte Eltern (z. B. weibliches Tier in der Vater-Position) trotzdem
  auflösen. Aufgelöste Eltern 200/206 -> 240/260.
- Neue Rollen-Normalisierung: weist jede Maus rollenrichtig nach Geschlecht zu,
  entfernt Selbst-Verpaarungen und unmögliche Doppelrollen.
  Selbst-Verpaarungen 16 -> 0, Gender-Rollen-Fehler 30 -> 0.
- Reine Helfer (litter_compatible/assign_parent_roles/names_*) auf Modulebene
  extrahiert und in test_merge_resolve.py (26 Tests) abgesichert.

Frontend (pedigree):
- buildAnimal markiert den Mutter-Knoten, wenn beide Eltern dieselbe litterId
  teilen (Vollgeschwister). toRawNodeDatum führt dessen Vorfahren-Ast zu einem
  Verweis-Knoten zusammen ("Geschwister von <Vater>, Eltern siehe oben"); die
  Vaterlinie zeigt die gemeinsamen Großeltern einmal.
- Druck-Ahnentafel bleibt vollständig (ignoriert die Marke).
- Build-Tests (+3) und e2e-Test (Inzucht-Kind-Fixture) ergänzt.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 14:02:45 +02:00
cb2ee03a14 fix: Naho Eltern + Foto-Layout-Erkennung + Eltern-Fallback-Lookup
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m2s
CI / Frontend Tests (Node/Vite) (push) Successful in 9m34s
CI / Docker Build & Push (push) Failing after 9s
2026-06-21 22:55:50 +02:00
41ff973f9a feat(import): merge animals with different DOBs if their parent names match
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m2s
CI / Frontend Tests (Node/Vite) (push) Successful in 9m35s
CI / Docker Build & Push (push) Failing after 12s
2026-06-21 22:23:59 +02:00
d2993418b6 fix(import): remap Kazuya DOB and correct parents using Stammbaum von Kazuya.xlsx
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m4s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
2026-06-21 22:18:04 +02:00
4cb39cb180 fix(import): align child-parent pedigree mapping by using name cell row for vertical alignment
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m9s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
2026-06-21 22:11:53 +02:00
b53b8cf2ff fix: show nameless fallback (ohne Namen) for nameless parents in litters list and detail pages 2026-06-21 22:06:10 +02:00
e460cd5905 feat(import): resolve color variety ID mappings mismatch, support unnamed parents in virtual litters, and implement SaleContract updates 2026-06-21 21:57:40 +02:00
b83e96f552 feat: Rennmausakte, Zucht-Suffix, Gehege-Bilder, Toasts, Infinite-Scroll
Detailseite (Rennmausakte):
- Neugestaltung: Hero-Foto + Overlay, Schnellfakten-Pills, Karten-Sektionen,
  Charakter als Chips, getabte Fotos/Gesundheit/Gewicht.
- Eltern (Vater/Mutter) als Links; Charakter-Karte klappt bei Status
  Abgabe/Verstorben/Abgegeben ein (nur Zucht/Liebhaber offen).
- Gehege wird bei abgegebenen/verstorbenen Tieren ausgeblendet (Detail + Formular).

Listen:
- Infinite Scroll auf allen Listen (Rennmäuse, Würfe, Gehege, Verträge,
  Anfragen, Kontakte) via useInfiniteList/useInfiniteSentinel; stabile
  Sortierung mit id-Tiebreaker (keine doppelten Keys), Back-to-top-Button.
- Kontakte: Rolle-Filter (Züchter/Abnehmer) als Quick-Chips + Sticky-Header.

Zucht-Nachname:
- Namens-Anhängsel der Zucht in den Einstellungen + je Züchter-Kontakt
  (Backend-Spalten + Migration); eigene Tiere zeigen „Name + Suffix".
- „Eigene Zucht" ist die Standard-Herkunft neuer Tiere.

Weiteres:
- Gehege-Bilder: Upload/Galerie auf der Gehege-Detailseite (Backend
  EnclosurePhoto + Endpoints + Migration, geteilte Dateiablage).
- Toast-Rückmeldungen für alle Speichern-Aktionen.
- Checkboxen durch mobile-freundliche Toggle-Schalter ersetzt.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-13 13:35:30 +02:00
bddbaf59d3 chore(import): document import workflow and apply Round 2 contact deduplications
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m4s
CI / Frontend Tests (Node/Vite) (push) Failing after 4m53s
CI / Docker Build & Push (push) Has been skipped
2026-06-13 09:27:13 +02:00
3021149ddd chore(import): apply user contact deduplication decisions 2026-06-13 09:22:04 +02:00
46f987422b FIX: Combine Birgitta Büskens and Birgitta Müller-Büskens contacts 2026-06-13 08:35:15 +02:00
5d2316d670 FIX: Combine Barbara R / Barbara Riegler contacts 2026-06-13 08:22:54 +02:00
c6968b9968 FEAT: Merge Anja Sch. into Anja Schaumburg, and keep infinite scroll layout pages 2026-06-13 08:14:31 +02:00
f3f4534392 FEAT: Normalize Anke B./Anke Busch contact, and save other infinite scroll layout updates 2026-06-13 08:11:17 +02:00
d189da954f FEAT: Wipe Contacts table on ingest to prevent duplicates, and commit infinite scroll contacts list 2026-06-13 08:06:56 +02:00
5b32c09076 FIX: Keep Ag(o)uti('s sind) net(t) as a valid breeder contact 2026-06-13 07:59:52 +02:00
ea760fba06 FEAT: Apply contact normalization and misclassification discarding mappings during import 2026-06-13 01:45:45 +02:00
396d8f05d8 FEAT: Implement deceased/givenaway enclosure visibility rules, preserve external clan name, and hide receiver fields for deceased gerbils 2026-06-13 01:40:19 +02:00
5732398e60 feat(rennmaeuse): Tiere-Liste neu im Rennmaus-Filter-Design
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m2s
CI / Frontend Tests (Node/Vite) (push) Failing after 4m54s
CI / Docker Build & Push (push) Has been skipped
Filter-UX aus dem Design:
- Quick-Chip-Kategorien (Status/Geschlecht/Farbschlag/Herkunft) öffnen ein
  Bottom-Sheet mit Mehrfachauswahl (suchbar bei Farbschlag/Herkunft); aktive
  Filter als entfernbare Chips; Sortierung + "Externe Ahnen" als gleich große
  Chips (Sortierung öffnet dasselbe Drawer).
- Neue zweizeilige Tierkarte (Name + Geschlechts-Kreis + Status-Badge, Meta-Zeile),
  cardIn/Chip/Sheet-Animationen, Titel blendet beim Scrollen aus.

App-weit:
- Design-Palette (Creme/Braun/Terrakotta), Hanken-Grotesk-Schrift und gemeinsamer
  --shadow-Token; obere "Rennmaus-Manager"-Titelleiste entfernt (mobil bleibt die
  untere Aktionsleiste); fixe Shell-Höhe, nur der Hauptbereich scrollt.

Funktion:
- Infinite Scroll via useInfiniteList (seitenweise) + IntersectionObserver-Sentinel.
- Namensgenerator: Option männlich/weiblich/egal.
- Mehrfach-OR-Filter über gridify orGroup; e2e an die neue UI angepasst.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-13 01:05:44 +02:00
0185446bfe feat(migration): implement offline-resolved database-ready ingestion, fix circular FKs, duplicate contacts and parser scanning bugs 2026-06-08 21:57:01 +02:00
04d189bd2f FEAT: genotype parsing resilience and displayGenotypeSafe format helper 2026-06-08 21:19:11 +02:00
7d8166c555 Merge feature/gerbil-icon-redesign: GerbilIcon SVG neu gezeichnet
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m1s
CI / Frontend Tests (Node/Vite) (push) Successful in 9m33s
CI / Docker Build & Push (push) Failing after 9s
Julian fand die alte Silhouette bescheiden. Neue Rennmaus-Silhouette
(sitzende Pose, layered ears, Pfoten, geschwungener Schwanz + Tuft).
Komponenten-API unveraendert (Props/viewBox/role/aria-label/style) ->
Consumer + e2e Selektoren intakt. QA: tsc+vite build green, vitest 122/122.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 00:35:18 +02:00
d5c7b77e7e FEAT: redesign GerbilIcon with a cute alert sitting silhouette and dynamic tufted tail 2026-06-08 00:33:40 +02:00
bff25b4683 FEAT-8d: add wipe-import-data.sql utility
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m2s
CI / Frontend Tests (Node/Vite) (push) Successful in 9m33s
CI / Docker Build & Push (push) Failing after 9s
Utility script to clean up import data from the database after testing
/import/dry-run. Useful for re-running the import process during development
and QA. Deletes all animals and litters created by the import (identified
by ImportSource='docx-export' and ImportSource='derived-litter'), resets
sequences, and leaves the database ready for fresh import execution.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-07 21:58:11 +02:00
aa1d22cec7 FEAT-8d: add node_modules/ to .gitignore
Never commit node_modules — always installed locally via npm install.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-07 21:58:10 +02:00
f7e97ad7a2 FEAT-8d: fix StatusModel migration table name SaleContractAnimals->SaleContractAnimal
During import execution, the migration 20260607012436_StatusModel failed because it
referenced a non-existent table "SaleContractAnimals" (plural). The actual table name
is "SaleContractAnimal" (singular). Fixed the reference in the SQL raw string to use
the correct table name so the migration can apply cleanly on fresh deployments.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-07 21:58:10 +02:00
7d552d33cd D7-PREP: Batch-Merge feature/d7-conflicts -> main (all 7 D7 conflict animals resolved)
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m0s
CI / Frontend Tests (Node/Vite) (push) Successful in 9m32s
CI / Docker Build & Push (push) Failing after 9s
Merged commits:
- 5ce35af (Skarlett): dateOfDeath 01.01.2017 (year-only, born 14.07.2013)
- 62b0759 (Max): dateOfDeath 01.01.2014 (year-only, born 01.02.2013) + genotype
- 4d7333b (Dakota + Banjo): Dakota genotype + Banjo E-locus correction
- Base file (Isa/Jack II/Sunny): Already correct, verified

All D7 conflict decisions now on main. Feature branch can be retained or deleted per god preference.
Status: Ready for FEAT-8d re-import (currently on HOLD pending Julian GO).

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-06-07 17:32:00 +02:00
4d7333b714 D7-PREP: Dakota of sweet little mouse + Banjo of Fiomi (E-locus correction)
Dakota of sweet little mouse (DOB 30.01.2015):
- Genotype: Aa CC Dd Ee Gg pp Spsp
- A-Locus=Aa, P-Locus=pp, Sp-Locus=Spsp confirmed by Julian

Banjo of Fiomi (DOB 06.07.2015, Dakota's son):
- E-Locus correction: E- → ee (Julian: "Goldfuchs Starkschecke, nicht Gold Starkschecke")
- Corrected genotype: AA CC DD ee Gg pp Spsp
- ColorVariety: Goldfuchs Starkschecke

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-06-07 17:27:53 +02:00
62b07597f5 D7-PREP: Max von Privat death date corrected to 01.01.2014 (year-only convention, birth 01.02.2013 + deathYear 2014)
Genotype confirmed: aa c[chm]c[chm] D- EE GG PP spsp
Reject 4 on-file variants: 04.02.2016 / 04.03.2016 / 2014-raw / 30.12.2015

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-06-07 17:26:10 +02:00
5ce35af813 D7-PREP: Skarlett death date corrected to 01.01.2017 (year-only convention, birth 2013 + 4y)
Julian's final answer: 'She became 4 years old, no exact date.' Birth: 14.07.2013.
Calculated: 2013 + 4 = 2017. Applied year-only death convention: 01.01.2017.
Previous entry (17.04.2016) from HUMANQUESTION D6 was incorrect.
2026-06-07 16:40:55 +02:00
23b6dad303 chore: retire HUMANQUESTION.md -> HUMANQUESTION.md.migrated
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m0s
CI / Frontend Tests (Node/Vite) (push) Successful in 9m33s
CI / Docker Build & Push (push) Failing after 9s
Human-feedback workflow moved into the hive task system (humanQA arrays on blocked cards in tasks.json). File is no longer the source of truth and must not be written to again. Open asks migrated to HQ-A3-GMAIL / HQ-A4-HOSTNAME / HQ-A5B2-REGISTRY / HQ-C7-RENNER-WISHES, plus D7-PREP (5 open conflict animals) and FEAT-8d.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-07 10:17:37 +02:00
e9eef5cce6 Merge JUVENILE-AVATARS (feature/juvenile-avatars @299c038) — Kelly
Some checks failed
CI / Frontend Tests (Node/Vite) (push) Successful in 9m32s
CI / Docker Build & Push (push) Failing after 9s
CI / Backend Tests (.NET) (push) Successful in 1m3s
Foto-Avatare pro Jungtier im Wurf-Detail (36px Kreis-Avatar + GerbilIcon-Fallback),
reuse profilePhotoUrl + failedUrl-Fehler-Tracking. StammbaumPage auf gleiches
failedUrl-Muster umgestellt (set-state-in-effect Lint-Fix). FE-only, keine Migration.
god-QA: vitest 122/122, build+tsc clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-07 08:24:49 +02:00
299c038449 feat(JUVENILE-AVATARS): Foto-Avatare pro Jungtier im Wurf-Detail
- JuvenileCard-Komponente in WurfDetailPage mit 36px-Kreis-Avatar links
- Fallback auf GerbilIcon (SVG-Silhouette) wenn kein profilePhotoUrl
- URL-basiertes Fehler-Tracking (failedUrl) statt useEffect+imgError
- wuerfe.css: Flex-Layout fuer Card+Avatar, overflow:hidden/object-fit:cover
- StammbaumPage: gleiche Lint-Verletzung (react-hooks/set-state-in-effect)
  behoben (failedUrl-Pattern, kein useEffect mehr fuer Bild-Reset)
- E2E: profilePhotoUrl auf Pippa (pup-abgabe), neuer Avatar-Test

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-07 08:20:19 +02:00
ecd7ad2658 Merge feature/status-model-fe (STATUS-MODEL-FE): Dropdown Zucht/Liebhaber/Abzugeben; Verstorben/Abgegeben read-only abgeleitet; Labels+Filter
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m1s
CI / Docker Build & Push (push) Failing after 9s
CI / Frontend Tests (Node/Vite) (push) Successful in 9m33s
2026-06-07 03:37:48 +02:00
6de56ab112 Merge feature/litter-mortality-fe (LITTER-MORTALITY-FE): deathsWithin8Weeks Feld im Wurf-Formular+Detail mit >totalBorn-Warnung 2026-06-07 03:37:48 +02:00
ddc343a96b Merge feature/d7-conflicts (D7-PREP): 5 Tiere (Milon/Max/Isa/Jack II/Sunny) in conflict-decisions.json + Jahr-only-Tod deathYear-Vorschlag; dry-run Konflikte 7->2 (KEIN execute)
Some checks failed
CI / Docker Build & Push (push) Has been cancelled
CI / Backend Tests (.NET) (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
2026-06-07 03:37:20 +02:00
a26bc4d75e Merge feature/litter-mortality (LITTER-MORTALITY-BE): Litter.DeathsWithin8Weeks int? + additive Migration + DTO + Validierung <=TotalBorn 2026-06-07 03:36:57 +02:00
d4dfe6c3ac Merge feature/status-model (STATUS-MODEL-BE P0): enum Active->Breeding(default)+Pet/ForSale; Deceased/GivenAway serverseitig abgeleitet (GerbilStatusService.Derive + Praezedenz + >7J presumed); Migration+Backfill+Startup-Sweep 2026-06-07 03:36:32 +02:00
40f3ce250d STATUS-MODEL-FE: Zucht/Liebhaber/Abzugeben wählbar; Verstorben+Abgegeben abgeleitet (gated auf Pam BE) 2026-06-07 03:36:10 +02:00
ffbbc0dfad Merge feature/stammbaum-avatar (STAMMBAUM-AVATAR): Stammbaum-Knoten konsumieren profilePhotoUrl (Foto-Avatar mit imgError-Fallback auf GerbilIcon)
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m1s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
2026-06-07 03:33:54 +02:00
05cb1af39e Merge feature/gerbil-profilephoto (PROFILEPHOTO-BE): berechnetes profilePhotoUrl aufs Gerbil-DTO (Shared-Dep fuer Avatare, keine Migration, kein N+1)
Some checks failed
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
CI / Docker Build & Push (push) Has been cancelled
CI / Backend Tests (.NET) (push) Has been cancelled
2026-06-07 03:33:01 +02:00
78f87f0d44 LITTER-MORTALITY: DeathsWithin8Weeks field (Frühsterblichkeit)
Litter.DeathsWithin8Weeks (int?, nullable). LitterDto + LitterInput extended.
Validation: negative → 400, > TotalBorn → 400 (skipped when TotalBorn null).
Migration AddLitterMortality (additive, nullable). 5 new tests. 194/194 green.
Contract: camelCase field deathsWithin8Weeks in LitterDto/LitterInput.
2026-06-07 03:31:51 +02:00
7f6855be62 D7: 5 Züchterin-Daten in conflict-decisions.json kodiert
Max von Privat (01.02.2013): genotype aa c[chm]c[chm] D- EE GG PP spsp.
  Tod-Jahr 2014 (Jahr-only) als _deathYear_pending kommentiert — Konvention offen.
Isa of Golden Lights (24.12.2014): dateOfDeath 21.07.2018.
Jack II von den Kleinen Chaoten (14.02.2016): dateOfDeath 06.10.2019.
Milon von den Kleinen Chaoten (27.11.2014): genotype Aa Cc[chm] D- ee[f] gg Pp spsp
  (A-Locus war der einzige Konflikt; Züchterin löst auf Aa).
Sunny von PZ Karl (10.04.2014): dateOfDeath 30.04.2018.

Dry-run delta: Konflikte 7→2 (resolved 15→20). Verbleibend: Skarlett + Dakota.
2026-06-07 03:29:19 +02:00
29e9c4cd64 LITTER-MORTALITY-FE: deathsWithin8Weeks Feld im Wurf-Formular und -Detail (gated auf Pam BE) 2026-06-07 03:28:11 +02:00
8eddb83c99 STAMMBAUM-AVATAR: Tier-Foto als Avatar in Pedigree-Karte, GerbilIcon-Fallback (profilePhotoUrl-Contract) 2026-06-07 03:27:24 +02:00
1a5f3218fb STATUS-MODEL: Active→Breeding + Pet enum + derived status logic (P0)
GerbilStatus: Active→Breeding, add Pet; Deceased/GivenAway are now DERIVED.
GerbilStatusService.Derive(): central precedence: DateOfDeath→Deceased (1),
ReceiverContactId→GivenAway (2), age>7y→Deceased presumed (3), user choice (4).
All write paths (gerbil CRUD, contracts, importers) call GerbilStatusService.Apply().
Startup sweep flips >7y gerbils to Deceased at next app restart.
Migration StatusModel: Active→Breeding rename + backfill derived statuses.
10 new tests; 200/200 green; has-pending=No.

Enum string values: Breeding (was Active), Pet (new), Deceased, GivenAway, ForSale.
FE contract: status field values updated (see Done-Report).
2026-06-07 03:27:11 +02:00
2d54cb901f Merge feature/litter-juvenile-details (LITTER-JUVENILE-DETAILS): pro Jungtier Farbschlag/Abgabedatum/Abnehmer/Todestag/Ursache im Wurf-Detail
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m16s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
2026-06-07 03:25:53 +02:00
03f8e4de90 LITTER-JUVENILE-DETAILS: Farbschlag/Abgabe/Abnehmer/Todesdaten pro Jungtier im Wurf-Detail 2026-06-07 03:23:22 +02:00
70803efa1f PROFILEPHOTO: profilePhotoUrl computed field on GerbilDto
GET /gerbils/{id}: loads first photo by sortOrder (2 queries, no N+1).
GET /gerbils list: batch-loads first photos for the page in one IN query.
profilePhotoUrl = /photos/files/{fileName} or null. No migration.
3 new tests: no-photo=null, sortOrder priority, list batch.
2026-06-07 03:19:00 +02:00
25af10a736 Merge feature/farbschlag-genotype-sync (FARBSCHLAG-GENOTYPE-SYNC): Farbschlag↔Gencode bidirektionale Sync im Tier-Formular
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m2s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
2026-06-07 03:16:55 +02:00
ade40eef5e FARBSCHLAG-GENOTYPE-SYNC: Farbschlag↔Gencode bidirektionale Sync im Tier-Formular 2026-06-07 03:16:02 +02:00
c1b215d06f Merge feature/stammbaum-fulldate (STAMMBAUM): volles Geburtsdatum + Gencode-Chip + GerbilIcon (🐭→Rennmaus app-weit)
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m0s
CI / Frontend Tests (Node/Vite) (push) Successful in 9m32s
CI / Docker Build & Push (push) Failing after 9s
2026-06-07 03:03:45 +02:00
7525970ffc STAMMBAUM-FULLDATE: GerbilIcon-SVG + Gencode-Chip + Gerbil-Icon ersetzt 🐭 app-weit 2026-06-07 02:53:31 +02:00
bfc90f8581 STAMMBAUM-FULLDATE: volles Geburtsdatum auf Knoten-Karten (formatDate statt slice 4) + e2e 2026-06-07 02:47:12 +02:00
c45bcc99f0 Merge feature/ops-2 (OPS-2): TrueNAS Goldeye deploy config (registry git.rismer.de + JailStorage paths) + ops runbook
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 59s
CI / Frontend Tests (Node/Vite) (push) Successful in 9m33s
CI / Docker Build & Push (push) Failing after 8s
# Conflicts:
#	deploy/truenas/compose.yaml
2026-06-07 02:28:00 +02:00
c4a661b5b6 Merge feature/search-1 (SEARCH-1): regression tests for separator-insensitive nameSearch + OriginBreeder filter 2026-06-07 02:27:21 +02:00
30b2fff775 Merge feature/web-2 (WEB-2): self-host public site — POST /api/publish (atomic swap) + publicsite nginx + vhost + docs
Some checks failed
CI / Frontend Tests (Node/Vite) (push) Successful in 9m32s
CI / Docker Build & Push (push) Failing after 10s
CI / Backend Tests (.NET) (push) Successful in 59s
2026-06-07 01:45:30 +02:00
c0ecf2022d WEB-2: Self-hosted public site (publicsite-nginx + POST /api/publish, atomic swap)
POST /api/publish: rendert SiteSnapshot->HTML in _staging_new/, atomic swap ->
live/ (rename, ein Syscall). publicsite-nginx:alpine serviert live/ read-only
auf Port 8081. Shared Volume api(rw)/publicsite(ro). Manager bleibt LAN-only.
5 neue Tests (atomic swap, UTF-8, mehrfach), 184/184 gruen. compose config OK.
Vhost-Snippet + web-deploy.md (Deutsch) beigelegt; <DOMAIN> wartet auf Julian.
2026-06-07 01:44:28 +02:00
2198c33898 OPS-2: TrueNAS Goldeye 25.10.2.1 Deploy finalisiert
Registry truenas:13000 -> git.rismer.de/gulum (alle 6 Stellen).
Dataset-Pfade auf /mnt/JailStorage/DockerVolumes/gerbilmanager/ gesetzt.
docs/ops.md: vollstaendiges Goldeye-Runbook (Ordner + UID-999-Perms,
Registry-Login, Port-80-Fallback, Restore-Drill-Pflichtschritt, ZFS-Pfade).
docker compose config: OK.
2026-06-07 01:38:25 +02:00
04971bf3bb Merge feature/stammbaum-litters (STAMMBAUM-LITTERS): Würfe des Wurzeltiers links im Viewer + Link
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 58s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
2026-06-07 01:38:10 +02:00
08500757d7 STAMMBAUM-LITTERS: Wuerfe des Wurzeltiers links im Stammbaum-Viewer
Layout: stammbaum-layout (flex-row Desktop / flex-column Mobil) wraps
[Wuerfe-Panel | Canvas]. Panel 148px breit, border-right Trenner;
auf Mobil (<=520px) horizontaler Scroll-Streifen ueber dem Canvas.

Daten: useApi(listLitters fatherId=id|motherId=id) reagiert automatisch
auf Umwurzeln (id-Param). Kein Panel wenn Wurzeltier keine Wuerfe hat.

Pro Wurf: Wurfname (fett) + N Junge + Link zu /wuerfe/{id}.
CSS: flex 0 0 auto Mobil-Override sichert Canvas-Hoehe im column-Mode.
de.ts: littersTitle, littersJunge (Stammbaum-Sektion, disjunkt).

Gate: vitest 122/122 e2e 20/20 Stammbaum (4 neue Tests x 2 Viewports)
build+tsc+eslint clean.
2026-06-07 01:37:08 +02:00
05ef3d9567 Merge feature/namegen-2-fe (NAMEGEN-2-FE): 10 Namens-Kategorien UI (disney/pokemon/EN+HR-Städte/US-Staaten)
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 59s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
2026-06-07 01:35:40 +02:00
7c12a65938 Merge feature/namegen-2-be (NAMEGEN-2-BE): 5 Themen-Kategorien disney/pokemon/encities/hrcities/usstates für /names/suggest
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m2s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
2026-06-07 01:34:52 +02:00
5361a292f1 NAMEGEN-2-BE: 5 neue Themen-Kategorien (disney/pokemon/encities/hrcities/usstates)
UsageMap bildet alle Codes auf deutsche Beschreibungen ab; thematische Kategorien
landen unter "Themen-Kategorien" im Prompt (kein Etymologie-Zwang, origin=Kategoriename).
22 neue Tests, 179/179 gruen.
2026-06-07 01:32:56 +02:00
cb5acd2005 Merge feature/genotype-display-rex (GEN-4d + UI-FIX): Rex-Wildtyp 'rere' in Anzeige ausblenden (7 Loci) + doppelte Wurf-Überschrift entfernt
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m0s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
2026-06-07 01:31:19 +02:00
bda5479b93 UI-FIX: doppelte Überschrift 'Erwartete Farbschläge' auf Wurf-Detailseite entfernt 2026-06-07 01:29:49 +02:00
d5c155953b GEN-4d: rere (Re-Wildtyp) aus Anzeige ausblenden (Julian)
- genotype.ts: toDisplayString filtert Re aus wenn re/re (Wildtyp) —
  analog zur bestehenden Sls-Regel; Rere/ReRe bleiben sichtbar.
  Wildtyp-Anzeige jetzt 7 Loci: AA CC DD EE GG PP spsp (ohne rere).
- StammbaumPage.tsx: Druck-Ahnentafel nutzt toDisplayString(fromDisplayString(g.genotype))
  statt rohem g.genotype-String (Audit: einzige Display-Stelle ausserhalb toDisplayString).
  (GerbilDetailPage/BreedingResultView gehen bereits via toDisplayString.)
- genetics.test.ts: Alle Display-String-Assertions auf 7-Loci-Format aktualisiert;
  Rere-Nachweis zum Sls/Re-Test ergaenzt; Katalog-Regex auf {6,8}.
- colorVarietySeed.generated.json regeneriert (kein rere in canonicalGenotype).
- backend.json unveraendert (Pam: DB-Speicherung bleibt volles 8-Loki-Format).
2026-06-07 01:28:06 +02:00
36795bd974 Merge feature/seed-rew (SEED-REW): Backend ColorVariety 'Pink Eyed White (PEW)' → 'REW' rename-in-place (FK-safe)
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 59s
CI / Frontend Tests (Node/Vite) (push) Successful in 9m33s
CI / Docker Build & Push (push) Failing after 9s
2026-06-07 01:19:26 +02:00
ae60b47ad3 D7: Quelldatei(en) je offenem Konflikt-Tier angereichert (Dakota/Max + alle 6 offenen)
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m1s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
2026-06-07 01:15:04 +02:00
adb9e93cdb SEED-REW: rename ColorVariety 'Pink Eyed White (PEW)' to 'REW'
Single UpdateData migration for ID 00000000-...-0001 (sortOrder 0).
Name-only rename, genotype/ID/FK unchanged — no drift risk.
Matches colorVarietySeed.backend.json after GEN-4c (main 3aa9ac9).

165/165 tests, ef has-pending=No.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
2026-06-07 01:12:55 +02:00
3aa9ac9811 Merge feature/gen-4c (GEN-4c): PEW→REW konsolidiert (Julian REW-1) + REW-2 A-unabhängig verifiziert + aa-Test
Some checks failed
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
CI / Backend Tests (.NET) (push) Successful in 58s
2026-06-07 01:10:18 +02:00
b72e0a9d9a GEN-4c: PEW=REW konsolidiert (Julian) + REW-2-Verifikation
- catalog.ts: 'Pink Eyed White (PEW)' -> 'REW' (frozen rename; chch+pp
  engine-computes 'REW' per Julian; entry now round-trips correctly)
- genetics.test.ts: REW_SHADOWED-Ausnahme entfernt (kein Bedarf mehr);
  CATALOG[0]-Assertion auf 'REW'; aa cchmcchm+pp-Test als REW-2-Nachweis
  (Julian: A-Locus egal fuer REW-Bedingung)
- chipColors.ts: 'REW'-Chip ergaenzt (gleiche Farbe wie PEW; additive;
  PEW-Eintrag bleibt fuer Rueckwaertskompatibilitaet waehrend DB-Migration)
- Seed-Artefakte regeneriert (70 Reihen, REW statt PEW an Position 0)
- FLAGGED to god: 'Altweiss (REW)' hat volles C (C:'C') -> faellt NICHT
  unter REW-Bedingung; warte auf Julian-Entscheid vor Aenderung
2026-06-07 01:08:23 +02:00
12d85d9796 WEB-Hosting-Pivot: Cloudflare → Self-Host auf TrueNAS (Strato/DynDNS + nginx-Reverse-Proxy); A4 umgestellt
Some checks failed
CI / Docker Build & Push (push) Has been cancelled
CI / Backend Tests (.NET) (push) Successful in 58s
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
2026-06-07 01:07:30 +02:00
76bdde4649 B2 Firewall erledigt — Handy-WLAN-Zugriff (Ports 5173/5179) offen
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 59s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
2026-06-07 01:04:00 +02:00
025bca1840 REW-1/REW-2 beantwortet: PEW=REW (zusammenführen, GEN-4c) + REW A-unabhängig (schon implementiert)
Some checks failed
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
CI / Docker Build & Push (push) Has been cancelled
CI / Backend Tests (.NET) (push) Has been cancelled
2026-06-07 01:03:05 +02:00
58dc811574 E1/E2 Charakterbogen als ERLEDIGT markiert (CHARAKTERBOGEN-2: 4 Kategorien, +10 Traits, Warnsignale) — war stale
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m0s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
2026-06-07 00:59:37 +02:00
367304940f D7: Osamu/Percy/Iwana Konfliktentscheidungen (Züchterin) + Eragon=Elieus C=CC bestätigt → conflict-decisions.json + HUMANQUESTION (7/13 erledigt)
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m0s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
2026-06-07 00:58:04 +02:00
7e1acdb5e4 A5 beantwortet: TrueNAS Goldeye 25.10 + eigener Postgres + Backups unter /mnt/JailStorage/DockerVolumes — OPS-2 entsperrt
Some checks failed
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
CI / Backend Tests (.NET) (push) Successful in 1m2s
2026-06-07 00:54:26 +02:00
5ee6a4edf6 Merge feature/stammbaum-expand (STAMMBAUM-EXPAND): prominenter +-Vorfahren-Button (40px) + Bottom-Mini-Legende (Name→Akte)
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 58s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
2026-06-07 00:47:05 +02:00
ea527c7ec6 CI: Registry auf externes HTTPS git.rismer.de (statt 192.168.2.115:13000 HTTP) — keine insecure-registry-Konfig nötig
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m0s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
2026-06-07 00:45:39 +02:00
c80adcf060 Merge feature/fix-8d-retry (FIX-8D-RETRY P0): wrap docx import tx in CreateExecutionStrategy.ExecuteAsync (Npgsql retrying strategy) + regression
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 58s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
2026-06-07 00:40:11 +02:00
a42966ad8e STAMMBAUM-EXPAND: +-Button prominenter + Mini-Legende (Stammbaum-UX)
Punkt 1 - Expand-Button sichtbar/zuverlaessig:
- 40px solid-fill (war 32px outline), box-shadow, flex-centered;
  deutlich sichtbar auf 190px Karte, touch-tauglich (>=40px Tap-Target).
  Hover/focus-visible: opacity + outline.
- Edge-case (Litter mit null-Eltern): +-Button bleibt sichtbar --
  unbekannt-Karten sind korrektes Feedback fuer quarantaenierte Eltern.

Punkt 2 - Bottom-Hint Mini-Legende:
- stammbaum-hint -> stammbaum-hints ul (flex-wrap, 3 Items):
  Umwurzeln / Name=Akte / +=Nachladen. Gut lesbar auf 390px.
  de.ts: hintName + hintExpand (neue Keys; tapHint bleibt fuer card title).

e2e: +2 Specs x 2 Viewports = 4 neue Tests (Legende + Expand-Klick).
Emil (Gen 4, litterId w-emil) liefert Testanker im Mock-Stammbaum.

Gate: vitest 122/122 e2e 166+68skipped build+tsc+eslint clean.
2026-06-07 00:38:46 +02:00
886a6e3aae D7: Kazumi/Filou/Sokrates Konfliktentscheidungen (Züchterin) → conflict-decisions.json + HUMANQUESTION gestrichen
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m0s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
2026-06-07 00:38:05 +02:00
88e00b3718 FIX-8D-RETRY: wrap docx execute transaction in CreateExecutionStrategy
NpgsqlRetryingExecutionStrategy rejects user-initiated transactions: SaveChanges
inside a BeginTransactionAsync block triggers OnFirstExecution which throws
InvalidOperationException. Fix: CreateExecutionStrategy().ExecuteAsync wraps the
entire tx block; mutable state (counters, contactByNorm, change tracker) reset at
lambda top for idempotent retry. Logic extracted to RunLoopAsync local function
shared by dry-run and execute paths.

Regression test (Test 7): FakeRetryingStrategy with MaxRetryCount=1 reproduces
the OnFirstExecution check in CI without a live Npgsql instance.

165/165 tests, ef has-pending=No, no schema change.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
2026-06-07 00:34:26 +02:00
3214855989 A5b2: konkrete Schritte für Registry-Secrets + insecure-registry-Hinweis
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 59s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
2026-06-07 00:33:40 +02:00
76e635a122 c
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 59s
CI / Frontend Tests (Node/Vite) (push) Successful in 9m33s
CI / Docker Build & Push (push) Failing after 9s
2026-06-07 00:02:20 +02:00
00886b1c6e Merge feature/fix-8d-dedup (FIX-8D-DEDUP P0): collision-free idempotent ExternalRef + single transaction + litter ±5d unique-date link
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 58s
CI / Frontend Tests (Node/Vite) (push) Successful in 9m33s
CI / Docker Build & Push (push) Failing after 8s
2026-06-06 23:33:06 +02:00
d5e8946d7d FIX-8D-DEDUP: P0 duplicate ExternalRef + WsCode→litter mismatch
FIX-1 DEDUP (P0): Two same-name siblings in one litter produced identical
ExternalRefs ('docx-{ws}-{name}-{dob}'), crashing execute on IX_Gerbils_ExternalRef.
Fix: ordinal counter per base-ref within the batch → first occurrence keeps the
base ref, subsequent ones get -2, -3 … suffix. Deterministic (JSON-order) → idempotent
re-runs find existing rows via ExternalRef path (PATH 1). HashSet guard added as a
belt-and-suspenders check.

FIX-2 TRANSACTION: execute now opens a single BeginTransactionAsync before the loop
and commits after the final SaveChangesAsync. Eager contact saves (within the tx) and
the gerbil batch save are fully atomic — crash → full rollback, no partial state.

FIX-3 LITTER LOOKUP: docx WsCode is a litter-size fraction ('4/4', '/5') — NOT a
PairingCode like 'G01/ZdkC'. The previous WsCode→PairingCode lookup was always a
no-op (hence litterLinked=0 in every dry-run). Fix: look up DB litters by LitterDob
(±5 days); link only when exactly ONE candidate exists (unambiguous, no false links).

P0 REGRESSION TEST (Test 6): SQLite + EnsureCreated → unique index enforced.
Two animals same name+litter → execute succeeds, both created, distinct ExternalRefs,
re-run = 0 new. This test would have caught the live crash.
Gate: 164/164 tests, has-pending=No, no schema change.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
2026-06-06 23:31:46 +02:00
e367657254 Merge feature/feat-8d-create (FEAT-8d-CREATE): docx importer CREATE path for ~194 abgegebene Jungtiere
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 58s
CI / Frontend Tests (Node/Vite) (push) Successful in 9m32s
CI / Docker Build & Push (push) Failing after 9s
2026-06-06 23:15:00 +02:00
8c43a8dc03 FEAT-8d-CREATE: docx importer CREATE path for ~194 abgegebene Jungtiere
ImportDocxService gains a three-way match-or-create loop:
  Path 1 (ExternalRef 'docx-…'): previously-created docx animals → enrich fill-NULL-only (idempotency)
  Path 2 (name+dob): existing main-import animals → enrich fill-NULL-only (as before)
  Path 3 (no match): CREATE new Gerbil — abgegebene Jungtiere not in pedigree charts
                      Status=GivenAway (or Deceased), IsResident=false,
                      OriginBreeder='Zucht der Kleinen Chaoten', ImportSource='docx',
                      ExternalRef='docx-{ws}-{normname}-{litterDob}' (stable idempotent key),
                      Gender/ColorVariety/LitterId/ReceiverContact/GoHomeDate/DateOfDeath all set.

ImportDocxReport gains Created field; contact-creation eagerly saved before gerbil batch.
5 SQLite-backed tests: dry-run counts, create+FK, idempotency, enrich-not-duplicate, Deceased status.
Gate: 163/163 tests, has-pending=No, no schema change.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
2026-06-06 23:13:21 +02:00
08732d8348 Merge feature/fix-import-cycle (FIX-IMPORT-CYCLE P0): break Gerbil<->Litter EF circular dependency on execute
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 59s
CI / Frontend Tests (Node/Vite) (push) Successful in 9m32s
CI / Docker Build & Push (push) Failing after 9s
Synth (chart-derived) litters now saved with FatherId/MotherId=null, then a deferred FK-update pass after all gerbils persist -> single-directional Gerbil->Litter dependency in the main save, no cycle. FK guard preserved. Regression: A-mother-is-B + B-mother-is-A cycle (SQLite, FK-enforced) asserts no throw + correct deferred FK. Gate: 158/158 (25/25 import), has-pending=No.

Unblocks the live WIPE+REIMPORT-3.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-06 22:48:52 +02:00
c6edb2e9d0 FIX-IMPORT-CYCLE: break Gerbil↔Litter circular FK dependency in ImportService
Root cause: synth litters (from chart parentRefs) were added with FatherId/MotherId pointing
to gerbils that were also [Added] in the same SaveChanges batch. With 337 derived litters from
41 pedigrees, multi-generational references created a true dependency cycle:
  Gerbil [Added] ← FK{MotherId} Litter [Added] ← FK{LitterId} Gerbil [Added]
EF's topo-sort threw InvalidOperationException; smaller datasets (REIMPORT-1/2) didn't
trigger it because they had fewer chart-derived litters.

Fix: add synth litters with FatherId=null/MotherId=null (deferred), track intended FKs
in synthLitterPendingParents, apply them in a separate SaveChanges after all gerbils are
persisted. Single-direction Gerbil→Litter dependency in the main save; no cycle possible.
No schema change, no migration.

Regression test: artificial A←B←A cycle in SQLite (FK-enforced) must not throw.
Also verifies deferred FK update sets litter parent correctly after execute.

GATE: 158/158 C# tests, has-pending-model-changes=No

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
2026-06-06 22:47:18 +02:00
8e475dff6a Merge feature/charakterbogen-2 (CHARAKTERBOGEN-2 / E1): Trait-Kategorien + rennmaus-spezifische Eigenschaften + Warnsignale
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 59s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
de.character.traits flach -> 4 Kategorien (Sozialverhalten/Eignung&Umgang/Hobbys&Eigenarten/Wesen&Temperament). 15 bestehende Keys UNVERAENDERT (Live-Daten), 10 neue additiv. warn-Flag (schwer-vergesellschaftbar, territorial) visuell abgesetzt fuer ehrliche Inserate. Gate: vitest 122/122, tsc/build/eslint clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-06 22:43:13 +02:00
54ffb809c4 CHARAKTERBOGEN-2 (E1): Trait-Katalog in 4 Kategorien + 10 neue Traits + Warnsignale
- de.ts: traits-Array -> traitCategories (4 Kategorien: Sozialverhalten / Eignung &
  Umgang / Hobbys & Eigenarten / Wesen & Temperament); alle 15 bestehenden Keys
  erhalten (stored auf Live-Tieren); 10 neue Keys additiv; warn:true auf
  schwer-vergesellschaftbar + territorial.
- format/traits.ts: TraitEntry/TraitCategory-Interface, TRAIT_CATEGORIES-Export,
  ALL_TRAITS via flatMap, neuer isWarnTrait()-Helper.
- Charakterbogen.tsx: grouped-Rendering nach Kategorie (section + h4); warn-Chips
  mit trait-chip--warn-Klasse + trait-warn-badge.
- charakterbogen.css: .trait-category__heading + .trait-chip--warn (amber) +
  .trait-warn-badge.
- format/__tests__/traits.test.ts: 14 neue Vitest-Tests (Kategorien, Keys, warn,
  traitLabel/traitLabels).
- Gate: vitest 122/122, tsc clean, build clean, eslint clean.
2026-06-06 22:32:16 +02:00
4403574f3d Merge feature/catalog-reseed (CATALOG-RESEED): Backend-ColorVariety auf finalen GEN-4/4b-Katalog (66->70)
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 58s
CI / Frontend Tests (Node/Vite) (push) Successful in 9m32s
CI / Docker Build & Push (push) Failing after 9s
ReseedColorVarietiesAR5: 8 Dilute-Praefix-Renames + 4 neue Dilute-Fuchs (IDs 67-70), SortOrder von ID entkoppelt, append-only (alle 66 ID->Name-Bindings erhalten, kein Live-FK-Drift). Quelle: frozen colorVarietySeed.backend.json. Gate: dotnet test 157/157, has-pending=No (Merge-Ergebnis verifiziert).

Letztes Gate vor WIPE+REIMPORT-3 (Julian-GO erteilt).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-06 22:31:46 +02:00
bcdea8011b CATALOG-RESEED: backend ColorVariety seed 66→70 from colorVarietySeed.backend.json (AR-5)
Source: gerbil-manager-web/src/genetics/colorVarietySeed.backend.json (70 entries, frozen symbols).
- 8 names updated to "Dilute" prefix (dd Gold→Dilute Gold, Agouti dd→Dilute Agouti, etc.)
- SortOrder decoupled from ID (CP-*-Hell interleaved per backend.json sortOrder values)
- 4 new entries appended at end (IDs 67-70): Dilute Algierfuchs/Goldfuchs/Rotfuchs/Polarfuchs
- All 66 existing ID→Name bindings preserved (append-only, no FK drift)
- Migration ReseedColorVarietiesAR5: UpdateData (renames+SortOrders) + InsertData (4 new)
- Tests updated: SeedGen3g_* asserts 70 entries + IDs 67-70 verified
- GATE: 157/157 C# tests, has-pending-model-changes=No

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
2026-06-06 22:29:47 +02:00
643f1a6831 Merge feature/catalog-generator (AR-5): committed Katalog-Generator (gen:catalog) + frozen colorVarietySeed.backend.json + Drift-Guard
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m0s
CI / Frontend Tests (Node/Vite) (push) Successful in 9m31s
CI / Docker Build & Push (push) Failing after 8s
Frontend-only (Generator .mts + Seed-Artefakte + catalog-drift test). Gate: vitest 109/109.
Backend-Artefakt (70 Eintraege, GEN-4/4b-final) = Quelle fuer die Backend-ColorVariety-Re-Seed-Migration (Pam) vor dem WIPE+REIMPORT.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-06 22:20:00 +02:00
27a3eb802c Merge feature/feat-8d-docx (FEAT-8d Phase 2): Wurfchronik-docx-Importer (Abnehmer/GoHomeDate/Tod)
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 58s
CI / Frontend Tests (Node/Vite) (push) Successful in 9m32s
CI / Docker Build & Push (push) Failing after 9s
extract_docx.py (stdlib, 93 Wuerfe/227 Tiere) + ImportDocxService (fill-NULL-only: WS-Code→LitterId,
Abnehmer→ReceiverContactId, ABD→GoHomeDate, Tod→DateOfDeath+Ursache) + /import/docx/dry-run|execute.
157/157 C# + 28/28 python, has-pending=No. Dormant bis execute (NACHZUG nach Re-Import).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-06 22:05:35 +02:00
13a887608c docs(HUMANQUESTION): D7 — 13 neue Konflikt-Tiere aus den 41 Stammbaeumen (Sterbedatum + Gencode-Picks)
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 58s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-06 22:04:25 +02:00
f74af537e2 FEAT-8d: docx-Importer fuer Wurfchronik-Detail (extract_docx.py + ImportDocxService)
tools/import/extract_docx.py (stdlib-Python, kein pip):
  Parst 'Wurfchronik der Kleinen Chaoten im Detail.docx' (Word/XML via zipfile).
  93 Wuerfe + 227 benannte Tiere aus Tabellen extrahiert.
  Felder pro Tier: WS-Code, Wurfgeburtsdatum, Name, Farbschlag, Geschlecht (Stern-
  Suffix), Abnehmer, Abgabedatum, Tod-Datum + Ursache, Partnername + DOB.
  Sonderwerte (ZT/BLEIBT/FREI/VG:) werden herausgefiltert.
  Edge-Cases: Doppel-Datum (16./17.03.2021, 31.05/*01.06.2023), WS ohne Zaehler
  (/5), fehlende Leerzeichen vor WS:, mehrere Abnehmer (1.) ... 2.) ...).
  Output: output/docx_litters.json + output/docx_animals.json.

tools/import/test_extract_docx.py:
  Unit-Tests fuer Regex-Logik + Live-Tests gegen die echte docx (skip wenn fehlt).
  28/28 Tests gruen.

GerbilManagerWebAPI/Import/ImportDocxService.cs:
  Idempotenter NACHZUG-Loader (fill-NULL-only, nie ueberschreiben):
  - WS-Code + Wurfgeburtsdatum -> PairingCode -> Gerbil.LitterId
  - Abnehmer -> Contact lookup-or-create -> Gerbil.ReceiverContactId
  - Abgabedatum -> Gerbil.GoHomeDate
  - Tod-Datum + Ursache -> Gerbil.DateOfDeath + CauseOfDeath
  Dry-Run zaehlt geplante Aenderungen, Execute schreibt.

GerbilManagerWebAPI/Endpoints/ImportDocxEndpoints.cs:
  POST /import/docx/dry-run + /import/docx/execute (analog ImportEndpoints).

GATE: 157/157 C#, 28/28 Python-docx-Tests, ef has-pending=No.
NACHZUG: laueft NACH dem finalen WIPE+REIMPORT-3 (kein Impact auf aktuellen Pipeline).
2026-06-06 22:04:09 +02:00
bb832b7f95 docs(HUMANQUESTION): aufgeraeumt — nur noch offene Punkte (A3/A4/A5/B2 + REW-Feinschliff) + Erledigt-Archiv
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 58s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
Alle C/D-Genetik+Konflikt-Fragen + A1/A2/B1/B3 erledigt → ins kompakte Archiv. Offen: Gmail/Domain/NAS-Zugaenge, Firewall, optionaler Feinschliff.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-06 22:01:54 +02:00
3a75005f43 docs(HUMANQUESTION): C6 erledigt — alle 32 Konflikt-Tiere entschieden (D6 komplett)
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 1m1s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-06 21:59:39 +02:00
f2a64ad66b D6: Hanami Sterbedatum = 12.12.2019 (Julian 2026-06-07) — LETZTER D6-Konflikt, D6 KOMPLETT
Some checks failed
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
CI / Docker Build & Push (push) Has been cancelled
CI / Backend Tests (.NET) (push) Has been cancelled
conflict-decisions.json jetzt 16 Eintraege, alle D-Konflikte entschieden. Re-Import nicht mehr auf D6 gated.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-06 21:59:02 +02:00
3706ba3ecd Merge feature/stammbaum-open (STAMMBAUM-OPEN): Klick auf Namen oeffnet Tier (/rennmaeuse/{id})
Some checks failed
CI / Backend Tests (.NET) (push) Successful in 58s
CI / Docker Build & Push (push) Has been cancelled
CI / Frontend Tests (Node/Vite) (push) Has been cancelled
PedigreeCard-Name = <Link> mit stopPropagation; Re-Root bleibt auf Karten-Flaeche. Unbekannt ohne Link.
+e2e (href + Keyboard/Accessibility). vitest 108, e2e 162. Frontend-only.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-06 21:56:31 +02:00
30ee7b6198 AR-5: Seed-Artefakte auf finalem Katalog regeneriert (70 Eintraege, GEN-4/4b)
npm run gen:catalog lief auf rebased HEAD (post-GEN-4b, main 7fe538d).
Beide Artefakte aktualisiert:
- colorVarietySeed.generated.json: 70 Zeilen, Klammer-Notation (Display)
  Neue Namen: Dilute Gold/Platin/Agouti/Silberagouti/Kohlfuchs/Anthrazit/
  Topas/Blaufuchs + Dilute Fuchs-Varianten (Algierfuchs/Goldfuchs/Rotfuchs/Polarfuchs)
- colorVarietySeed.backend.json: 70 Zeilen, frozen symbols (ef/cchm/ch)
  Quelle fuer Pams Backend-Re-Seed-Migration (Guardrail: nie Klammern)
Drift-Guard (catalog-drift.test.ts) laeuft gruen.
Gate: build ✓  eslint ✓  vitest 109/109 ✓
2026-06-06 21:52:44 +02:00
29207e41da AR-5: Committed Katalog-Generator + Drift-Guard + Backend-Artefakt
- gen-seed.mts: deterministischer Generator aus catalog.ts (Single Source);
  emittiert BEIDE Artefakte: generated.json (Klammer-Notation, Display) +
  backend.json (frozen ef/cchm/ch, für Pam EF-Migrationen). Kein magisches
  Artefakt mehr.
- package.json: npm run gen:catalog (npx tsx gen-seed.mts)
- catalog-drift.test.ts: Drift-Guard — liest generated.json von Disk via
  import.meta.url + readFileSync, vergleicht mit live CATALOG; Fail-Meldung
  zeigt 'npm run gen:catalog'. 5 Test-Files, 93 Tests grün.
- colorVarietySeed.backend.json: 66 Zeilen frozen symbols (ef/cchm/ch),
  kein sofortiger Backend-Eingriff (AR-5 Guardrail; Pam konsumiert bei
  nächster Reseed-Migration).
- README.md: Katalog-Generator-Doku (wann laufen, was erzeugt wird).
Gate: build ✓  eslint ✓  vitest 93/93 ✓
2026-06-06 21:51:55 +02:00
c452b69dd6 NAMEGEN-2-FE: 5 neue Namenskategorien (Disney, Pokémon, Englische/Kroatische Städte, US-Bundesstaaten)
- NAMEGEN_USAGES: +disney, +pokemon, +encities, +hrcities, +usstates (jetzt 10 Einträge)
- names.test.ts: Count-Test 5→10, neue toContain-Checks für alle 5 Codes

Gate: vitest 107/107, e2e 160/160, tsc clean
2026-06-06 21:48:08 +02:00
f20a42a94b SEARCH-1: tests — Normalize unit + separator-insensitive nameSearch filter + OriginBreeder/breeders endpoint (SQLite in-memory round-trip) 2026-06-06 09:04:20 +02:00
371 changed files with 102792 additions and 1981 deletions

35
.claude/settings.json Normal file
View File

@@ -0,0 +1,35 @@
{
"$schema": "https://json.schemastore.org/claude-code-settings.json",
"hooks": {
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "mempalace hook run --hook session-start --harness claude-code"
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "mempalace hook run --hook stop --harness claude-code"
}
]
}
],
"PreCompact": [
{
"hooks": [
{
"type": "command",
"command": "mempalace hook run --hook precompact --harness claude-code"
}
]
}
]
}
}

View File

@@ -0,0 +1,181 @@
---
name: ticket-triage
description: >-
Fehlerberichte (Tickets) der Züchterin abarbeiten: neue Tickets per Subagent
triagieren, Rückfragen an die Tickets hängen, beantwortete Tickets wieder
aufgreifen, Fixes gebündelt umsetzen und beim Schließen dokumentieren, was
gefixt wurde. Nutze diesen Skill, wenn der Nutzer „Tickets abarbeiten /
triagieren", „Fehlerberichte bearbeiten" o. Ä. verlangt.
---
# Ticket-Triage & Abarbeitung
Tickets entstehen über das „Fehler melden"-Feature (`POST /feedback`) und werden
unter **Hilfe → Meine Tickets** (`/hilfe/tickets`) verwaltet. Dieser Skill
automatisiert das Triagieren, Rückfragen-Stellen, Umsetzen und Schließen.
## Status-Lebenszyklus (Feedback.Status)
| Status | Bedeutung | Wer ist dran |
|---|---|---|
| `Open` | Neues Ticket, noch nicht triagiert | **KI** (triagieren) |
| `NeedsInfo` | KI hat eine **Rückfrage** angehängt | Züchterin (antworten) |
| `Answered` | Züchterin hat geantwortet | **KI** (wieder aufgreifen, umsetzen) |
| `Resolved` | Erledigt — mit `fixNote` (Changelog) | — |
**Zu bearbeiten sind `Open` (neu) und `Answered` (KI wieder dran).** `NeedsInfo`
wartet auf die Züchterin, `Resolved` ist fertig — beide überspringen.
## Voraussetzungen
- App läuft (Aspire): `dotnet run --project GerbilManager.AppHost`; API auf
http://localhost:5179. Siehe `CLAUDE.md` (Architektur, Import→DB-Workflow,
Domänenwissen: 6-Jahre-Lebensspanne, Geschwisterverpaarung, Genotyp/E-Locus,
`isResident`).
- Feedback überlebt den Import-Ingest (FK-freie Spalten) — Tickets bleiben
erhalten, auch wenn die DB neu befüllt wird.
## Ablauf
### 1. Tickets holen & einteilen
`curl -s http://localhost:5179/feedback` (neueste zuerst). Encoding-Falle: über
eine Datei holen (`curl -o raw.json`) und mit `python … .decode('utf-8')` lesen,
nicht via Windows-stdin-Pipe (sonst Mojibake). Test-/Dummy-Tickets ausschließen.
Filtere auf `status in (Open, Answered)`. Bei `Answered` zusätzlich das Feld
`answer` (Antwort der Züchterin) mitnehmen — darauf basiert die Umsetzung.
### 2. Triage per Subagent (ein Agent pro Ticket)
Nutze die **Workflow-Orchestrierung** (`pipeline`) — einen Triage-Agenten pro
Ticket. args ASCII-sicher halten (nur id/context/gerbilId/litterId übergeben; die
deutschen Nachrichten holt der Agent selbst aus `GET /feedback`). Defensive im
Script: `const tickets = Array.isArray(args) ? args : JSON.parse(args)`.
Jeder Triage-Agent:
1. liest `CLAUDE.md` + `docs/ticket-triage.md` (falls vorhanden),
2. holt seinen Ticket-Text (+ `answer` bei `Answered`) aus `GET /feedback`,
3. untersucht die echten Daten über die API (`GET /gerbils/{id}`, `/litters/{id}`,
Eltern verfolgen; `provenance` zeigt Import-Herkunft inkl. verworfener Werte),
4. liefert strukturiert (StructuredOutput-Schema): `ticketId, title, category,
rootCause, recommendation, fixLayer (import-data|import-logic|backend|frontend|
genetics-engine), affectedAreas[], overlapKey (Cluster-Slug), effort (S/M/L),
confidence, needsUserInfo`,
5. **terminale Aktion am Ticket selbst** (jeder Triage-Agent schließt seinen
Vorgang ab, lässt nichts offen liegen): braucht es Infos von der Züchterin →
**Rückfrage ordentlich stellen** (siehe 3); ist die Ursache rein eine Daten-/
Code-Korrektur ohne Rückfrage → an den passenden Umsetzungs-Cluster (4)
übergeben (NICHT selbst querschnittlich Dateien ändern).
Sammle alle Ergebnisse in **eine Datei** `docs/ticket-triage.md` (Cluster-/
Überschneidungs-Matrix + offene Rückfragen) — token-schonend per Python aus dem
Workflow-Ergebnis generieren, nicht 70 KB in den Kontext laden.
### 3. Rückfragen ordentlich stellen (durch den Triage-Agenten)
Wenn ein Ticket Infos der Züchterin braucht, hängt der Triage-Agent die Rückfrage
**direkt selbst** ans Ticket:
`PUT /feedback/{id}` mit `{"question": "<Rückfrage>"}` → Status wird `NeedsInfo`.
Anforderungen an eine gute Rückfrage: **eine konkrete Frage** (kein Sammelsurium),
in **einfacher, freundlicher Sprache** für die Züchterin (keine Code-/Fachbegriffe),
mit dem nötigen Kontext (welches Tier/welcher Wurf, was unklar ist), und mit einer
klaren Handlungsaufforderung (z. B. „Wie heißt die Mutter von X?"). Die Züchterin
beantwortet es in der App; beim nächsten Lauf erscheint es als `Answered` und wird
wieder aufgegriffen.
### 4. Umsetzen — gebündelt nach Cluster (Überschneidungen vermeiden!)
Die Triage-Matrix zeigt, welche Tickets sich Dateien teilen. Bündele nach
**datei-disjunkten Workstreams**, damit parallele Subagenten nicht kollidieren:
- **Genetik-Engine** → `gerbil-manager-web/src/genetics/**`, `tools/import/genotype.py`.
- **Stammbaum-Import** (Eltern/Dedup/Gender/`isResident`) → `tools/import/extract.py`,
`merge_and_resolve.py`, `conflict-decisions.json`.
- **Frontend-Anzeige** (z. B. Nicht-Bestandstiere ausblenden) → `GerbilDetailPage.tsx`,
`de.ts`.
Gemeinsam genutzte Dateien (`de.ts`, `GerbilDetailPage.tsx`) gehören **genau einem**
Workstream — sonst sequenziell. Datenkorrekturen, die die Züchterin nennt, als
Override in `conflict-decisions.json` kodieren (data-driven, re-ingest-stabil).
Subagenten committen NICHT und re-ingesten NICHT — das koordiniert der Haupt-Loop.
### 5. Import neu einspielen (bei Daten-/Import-Änderungen)
`python tools/import/extract.py` → `extract_contracts.py` → `merge_and_resolve.py`,
dann `POST /import/ingest-resolved` (wischt + lädt neu). Danach betroffene Tickets
gegen die API verifizieren.
### 6. Ticket schließen — MIT Changelog (durch den bearbeitenden Subagenten)
Der Subagent/Cluster, der den Fix umgesetzt hat, schließt **seine** Tickets selbst
ab — aber erst **nachdem der Fix verifiziert und (bei Daten-/Import-Fixes) live
eingespielt ist** (Schritt 5), damit „erledigt" auch stimmt:
`PUT /feedback/{id}` mit `{"status": "Resolved", "fixNote": "<verständliche
Erklärung, was korrigiert wurde>"}`.
**Die `fixNote` ist ein Changelog AUSSCHLIESSLICH für die Züchterin (Laiin) —
kein technisches Geschwafel.** Harte Regel:
- Schreib, **was sich für SIE sichtbar geändert hat**, in Alltagssprache; 13 Sätze.
- KEINE Dateinamen, Funktionen, Feldnamen, IDs, Status-Codes, „Resolver/Migration/
Genotyp-Parser/isResident/conflict-decisions" o. Ä. Nenne Tiere/Würfe bei ihrem
**Namen**, nicht per ID.
- Sag ggf., was sie tun soll (z. B. „Seite neu laden").
Gut: „Die Mutter von **Yuki** war falsch — sie ist jetzt **Izumi** (vorher stand
da Benjiro). Bitte den Stammbaum neu laden."
Gut: „**Hagrid** wird nicht mehr als dein eigenes Tier geführt, sondern nur noch
als Vorfahre — seine Würfe und der Charakter-Bereich werden nicht mehr angezeigt."
Schlecht (NICHT so): „assign_parent_roles korrigiert, motherId via
conflict-decisions.json gesetzt, re-ingest." / „isResident=false gesetzt."
### Abschluss-Regel (wichtig)
**Kein bearbeitetes Ticket bleibt offen liegen.** Jedes `Open`/`Answered`-Ticket
endet nach einem Lauf in genau einem Endzustand:
- **`NeedsInfo`** — Rückfrage wurde ordentlich gestellt (Info fehlt), oder
- **`Resolved`** — Fix umgesetzt + verifiziert, mit `fixNote`-Changelog.
Kann ein Ticket weder gefixt noch sinnvoll erfragt werden, stelle trotzdem eine
klärende Rückfrage (NeedsInfo) statt es offen zu lassen.
## Mehrrundige Rückfragen & Kontext-Kontinuität
Der Dialog kann mehrere Runden haben: `Open → (Rückfrage) NeedsInfo → (Antwort)
Answered → (KI prüft) ggf. neue Rückfrage NeedsInfo → Answered → … → Resolved`.
Jede **weitere Antwort** der Züchterin bringt das Ticket wieder auf `Answered` und
damit erneut in die Bearbeitung (Schritt 1 filtert `Answered` immer mit ein).
**Kontext-Träger ist das Ticket, nicht der Subagent.** Subagenten sind
sitzungsgebunden — antwortet die Züchterin später (neue Session), existiert der
ursprüngliche Agent nicht mehr. Daher MUSS der gesamte Verlauf am Ticket hängen
(Frage/Antwort je Runde) + der Triage-Eintrag in `docs/ticket-triage.md`. Beim
Wiederaufgreifen eines `Answered`-Tickets lädt der Subagent diesen vollständigen
Verlauf + die frühere Triage und macht **mit demselben Kontext** weiter (statt bei
null neu zu untersuchen) — praktisch „derselbe Vorgang, fortgesetzt".
**Innerhalb derselben Session** kann man stattdessen denselben Subagenten direkt
fortsetzen (SendMessage an seine Agent-ID, Kontext bleibt erhalten) — nur dann ist
echte Agent-Kontinuität möglich.
Das Datenmodell unterstützt Mehrrunden über einen **Verlauf/Thread** am Ticket
(mehrere Frage/Antwort-Einträge mit Autor + Zeit), nicht nur ein einzelnes
Frage/Antwort-Paar — so geht bei weiteren Antworten nichts verloren.
### Internes Agenten-Kontextfeld (für die Züchterin unsichtbar)
Das Ticket hat ein **internes Kontextfeld** (`agentContext`, NICHT in der Züchterin-
UI sichtbar) — das **Arbeitsgedächtnis** des Agenten. Damit ersetzt das Ticket den
sitzungsgebundenen Subagenten-Kontext:
- **Schreiben:** Bei jeder Bearbeitung legt der Agent dort seinen Arbeitsstand ab
(kompaktes JSON/Markdown): Befunde, vermutete Ursache, geprüfte Hypothesen,
betroffene Dateien/Daten, der Plan, **worauf gewartet wird** (welche Info die
Rückfrage klären soll) und schon erledigte Teilschritte.
- **Lesen:** Beim Wiederaufgreifen eines `Answered`-Tickets liest der Agent zuerst
`agentContext` (+ Verlauf + Triage-Eintrag) und setzt **dort an, wo er aufgehört
hat** — keine Neu-Untersuchung von null.
- **Trennung:** `agentContext` ist intern/technisch (darf IDs/Dateinamen/Hypothesen
enthalten); die **sichtbaren** Felder bleiben laienverständlich (Frage, Antwort,
`fixNote`). `agentContext` wird in der Tickets-Seite NICHT angezeigt.
- `PUT /feedback/{id}` mit `{"agentContext": "<arbeitsstand>"}` aktualisiert es,
ohne den Status zu ändern.
## Verifikation vor „fertig"
- Code-Fixes: `npx tsc --noEmit`, `npx vitest run`, betroffene `npx playwright test`,
`dotnet build`/`dotnet test`, Python-`test_*.py` — grün.
- Daten-Fixes: in `resolved_import.json` stichprobenartig prüfen, dann re-ingest +
API-Check des konkreten Tiers/Wurfs.
- Jedes erledigte Ticket auf `Resolved` mit `fixNote` gesetzt.
## Hinweise
- Pro Ticket genau ein Triage-Agent; Umsetzung gebündelt nach Cluster.
- Encoding: deutsche Texte als UTF-8 (Datei, nicht stdin-Pipe).
- Nichts committen, bis der Haupt-Loop verifiziert hat; auf `main` arbeiten.

View File

@@ -9,10 +9,10 @@
# 2. npm test + npm run build (Frontend)
# 3. Docker-Images bauen und in die Gitea-Registry pushen
#
# Registry: truenas:13000 (internes Gitea Container Registry)
# Registry: git.rismer.de (Gitea Container Registry über HTTPS — keine insecure-registry-Konfig nötig)
# Images:
# truenas:13000/gulum/gerbilmanager-api:latest
# truenas:13000/gulum/gerbilmanager-frontend:latest
# git.rismer.de/gulum/gerbilmanager-api:latest
# git.rismer.de/gulum/gerbilmanager-frontend:latest
name: CI
@@ -23,9 +23,13 @@ on:
pull_request:
branches:
- main
# Manueller „Run workflow"-Button in Gitea: testet, baut, pusht und deployt frisch.
# Fuer einen Rollback auf ein altes Image stattdessen auf der NAS:
# TAG=<git-sha> sh /opt/gerbilmanager/deploy/truenas/scripts/deploy.sh
workflow_dispatch:
env:
REGISTRY: truenas:13000
REGISTRY: git.rismer.de
REGISTRY_OWNER: gulum
DOTNET_VERSION: "10.0.x"
NODE_VERSION: "22"
@@ -100,7 +104,7 @@ jobs:
name: Docker Build & Push
runs-on: ubuntu-latest
needs: [test-backend, test-frontend]
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
if: github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch')
steps:
- uses: actions/checkout@v4
@@ -133,3 +137,49 @@ jobs:
tags: |
${{ env.REGISTRY }}/${{ env.REGISTRY_OWNER }}/gerbilmanager-frontend:latest
${{ env.REGISTRY }}/${{ env.REGISTRY_OWNER }}/gerbilmanager-frontend:${{ github.sha }}
deploy:
name: Deploy auf TrueNAS (Custom App)
# Laeuft auf dem vorhandenen containerisierten Gitea-Runner (Label ubuntu-latest).
# Der Runner hat KEINEN Host-Dateisystem-/midclt-Zugriff, daher: per SSH zum NAS-Host
# verbinden, die Deploy-Dateien in das App-Home auf dem Pool kopieren und dort
# truenas-deploy.sh ausfuehren (legt die TrueNAS "Custom App" an bzw. rollt sie neu
# aus via `midclt` — die App bleibt unter Apps sichtbar).
# Hinweis: / (inkl. /opt) ist auf TrueNAS Goldeye read-only -> App-Home auf dem Pool.
#
# Benoetigte Repo-Secrets (Gitea -> Einstellungen -> Actions -> Secrets):
# NAS_SSH_HOST z. B. 192.168.2.115 (Host-LAN-IP der NAS)
# NAS_SSH_KEY privater SSH-Deploy-Key (Pubkey liegt in /root/.ssh/authorized_keys)
runs-on: ubuntu-latest
needs: [build-and-push]
if: github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch')
env:
APP_HOME: /mnt/JailStorage/DockerVolumes/gerbilmanager
steps:
- uses: actions/checkout@v4
- name: SSH-Client + Key einrichten
run: |
command -v ssh >/dev/null 2>&1 || (apt-get update && apt-get install -y --no-install-recommends openssh-client rsync)
install -m 700 -d ~/.ssh
printf '%s\n' "${{ secrets.NAS_SSH_KEY }}" > ~/.ssh/id_deploy
chmod 600 ~/.ssh/id_deploy
ssh-keyscan -H "${{ secrets.NAS_SSH_HOST }}" >> ~/.ssh/known_hosts 2>/dev/null || true
- name: Deploy-Dateien auf den NAS-Host kopieren
run: |
NAS="root@${{ secrets.NAS_SSH_HOST }}"
SSH="ssh -i ~/.ssh/id_deploy -o StrictHostKeyChecking=accept-new"
$SSH "$NAS" "mkdir -p $APP_HOME/deploy/truenas/scripts"
rsync -az -e "$SSH" \
deploy/truenas/custom-app.compose.yaml \
"$NAS":"$APP_HOME"/deploy/truenas/
rsync -az -e "$SSH" \
deploy/truenas/scripts/ \
"$NAS":"$APP_HOME"/deploy/truenas/scripts/
- name: Custom App neu ausrollen (midclt create/redeploy + Health-Check)
run: |
NAS="root@${{ secrets.NAS_SSH_HOST }}"
ssh -i ~/.ssh/id_deploy -o StrictHostKeyChecking=accept-new "$NAS" \
"sh $APP_HOME/deploy/truenas/scripts/truenas-deploy.sh"

24
.gitignore vendored
View File

@@ -137,3 +137,27 @@ GerbilManagerWebAPI/photo-storage/
# AR-3: Data Protection key ring (dev-only ephemeral keys) — never commit
GerbilManagerWebAPI/.data-protection-keys/
# node_modules — never commit, installed locally per npm install
node_modules/
# Runtime: gespeicherte Vertrags-Dateien
GerbilManagerWebAPI/contract-storage/
# Agent-Worktrees (lokal, nicht versionieren)
.claude/worktrees/
# Lokaler Publish-Output der öffentlichen Seite (Aspire dev)
deploy/.local-publicsite/
# RennmausPro III SQLite-Quelle (lokal, nicht committen)
tools/import/_rpro3.db
tools/import/_rpro3_extract/
tools/import/_rpro3_backup.zip
# Lokale Scratch-/Werkzeug-Verzeichnisse (nicht versionieren)
.agents/
tools/rag/
# Produktions-Secrets (nur auf dem NAS, nie im Repo)
deploy/truenas/.env

8
.mcp.json Normal file
View File

@@ -0,0 +1,8 @@
{
"mcpServers": {
"mempalace": {
"command": "mempalace-mcp",
"args": []
}
}
}

296
CLAUDE.md Normal file
View File

@@ -0,0 +1,296 @@
# CLAUDE.md — GerbilManager
Leitfaden für die Arbeit an diesem Repo. Bitte vor Änderungen lesen.
## Was ist das?
Verwaltungs-App für eine **Rennmaus-Zucht** („Zucht der kleinen Chaoten"): Tiere,
Würfe, Stammbäume/Ahnentafeln, Genetik (Farbschläge/Genotypen), Gehege, Kontakte
(Züchter/Abnehmer), Abgabeverträge, Statistik und eine öffentliche CMS-Webseite.
Single-User (die Züchterin), Daten größtenteils aus bestehenden Quelldateien
importiert.
## Architektur / Projekte
| Projekt | Zweck |
|---|---|
| `GerbilManager.AppHost` | **.NET Aspire** Orchestrator — startet PostgreSQL (Container) + WebAPI |
| `GerbilManagerWebAPI` | Backend: ASP.NET **Minimal API**, EF Core + Postgres, Endpoints in `Endpoints/`, Entities in `Models/`, DTOs in `Dtos/` |
| `GerbilManager.ServiceDefaults` | Aspire-Defaults (Telemetry/Health) |
| `GerbilManager.Tests` | Backend-Tests (xUnit) |
| `gerbil-manager-web` | Frontend: **React + Vite + TypeScript** (React Router, react-d3-tree für den Stammbaum) |
| `tools/import` | **Python**-Import-Pipeline (zero-dep), wandelt Quelldateien → `resolved_import.json` |
## App starten (IMMER über Aspire, nicht nur die WebAPI)
```bash
dotnet run --project GerbilManager.AppHost
```
- WebAPI: http://localhost:5179 · OpenAPI: `/openapi/v1.json`
- Aspire-Dashboard: https://localhost:17004 (Login-Token steht im AppHost-Log)
- EF-Migrationen werden beim Start automatisch angewandt (`db.Database.Migrate()` in `Program.cs`).
- Postgres läuft als Container (Name wechselt pro Run, z. B. `postgres-xxxx`); die
**Daten liegen in einem persistenten Volume** → überleben Neustarts. DB-Name: `gerbilmanager`.
## Import → DB (3-stufig, WICHTIG)
Die DB wird **nicht** direkt von Python beschrieben. Nach jeder Import-Code-Änderung
neu generieren UND neu einspielen, sonst zeigt die App den alten Stand.
> **Arbeitsweise (verbindlich, Owner-Regel — aktualisiert 2026-07-12):** Für **variable**
> (von der Züchterin **nicht** angefasste) Import-Tiere gilt weiter: Datenfehler IMMER **im
> Importierer** beheben (Pipeline-Code + `conflict-decisions.json` / `rpro3-decisions.json`)
> und **neu importieren** — für diese Tiere **nicht** die Live-DB patchen. Jeder Importer-Fix
> muss **re-ingest-stabil** sein (data-driven, deterministische GUIDs).
>
> **Neu:** Das Ziel ist **nicht** mehr „Importer perfekt, dann einmal final", sondern
> **Tier für Tier konvergieren**. Die Züchterin **darf** über die UI kuratieren, und das
> **überlebt den Ingest** (der wischt **nicht** mehr alles): (a) **manuell angelegte Tiere/
> Würfe/Kontakte** (`IsManual=true`) und (b) **Overrides** (`GerbilOverride`) für als
> **„vollständig korrekt"** markierte bzw. **von Hand bearbeitete** Tiere. Deren eigene Felder
> werden nach jedem Ingest **eingefroren** (Freeze). Siehe „Geprüfte Tiere / Freeze" unten.
> Zusätzlich zu diesen Overrides überleben weiterhin **Tickets/Feedback**.
```bash
# 1. Stammbäume + Wurfchronik → animals.json/litters.json (+ Fotos)
python tools/import/extract.py
# 2. Abgabeverträge (DOCX) → contracts.json
python tools/import/extract_contracts.py
# 3. Dedup, Eltern-Resolver, Provenance, Vertrags-Anreicherung → resolved_import.json
python tools/import/merge_and_resolve.py
# 4. In die laufende DB laden (API muss laufen): UPSERT + Freeze
curl -X POST http://localhost:5179/import/ingest-resolved
```
- **`IngestResolvedService` (seit 2026-07-12: UPSERT statt Total-Wipe).** Importierte Zeilen
(Gerbils/Litters/Contacts) werden **per deterministischer Id gematcht und in place
aktualisiert**; **stale** importierte Zeilen (nicht mehr im Payload) werden entfernt (dangling
Referenzen manueller Zeilen werden vorher genullt + im Rückgabestring gewarnt). **Nie gelöscht/
überschrieben:** Zeilen mit `IsManual=true` sowie **user-eingegebene Sub-Records**
(Weights/Health) und Fotos manueller Tiere. **SaleContracts** werden weiter aus dem Payload
neu erzeugt (manuelle Verträge sind noch **nicht** geschützt — Folgeaufgabe). Am Ende werden
alle **`GerbilOverride`** angewandt (**Freeze** der eigenen Felder) und für verifizierte Tiere
der Rohimport-Stand vorher als Drift-Snapshot erfasst.
- **Feedback + GerbilOverride überleben den Ingest** (werden nicht gewischt) — daher haben sie nur
**lose, nullable Guid-Spalten ohne FK** (`Feedback`: GerbilId/LitterId/ContactId; `GerbilOverride`:
GerbilId). Dieses Muster für alles nutzen, was Re-Ingests überleben soll.
- `resolved_import.json` ist **gitignored** (Runtime-Output); `review-report.md` ist getrackt.
- Deterministische GUIDs via `generate_guid("...")` → stabile IDs über Re-Ingests.
### Quelldateien (lokal/Netzwerk)
- Stammbäume: `C:\Users\gulum\dev\Sttammbäume\*.xlsx`
- Wurfchronik: `C:\Users\gulum\dev\Wurfchronik der Kleine Chaoten Teil1.xlsx`
- Abgabeverträge: `\\truenas\Datengrab\Rennmäuse\Verträge\*.docx` (~1,4k; kann zeitweise offline sein)
## Build & Test
**Frontend** (`cd gerbil-manager-web`):
```bash
npx tsc --noEmit # Typecheck (muss sauber sein)
npx vitest run # Unit-Tests
npx eslint <dateien> # Lint
npx playwright test [spec]# e2e (Projekte: desktop + phone), läuft gegen Mock-API
```
- e2e nutzt einen **Mock-Modus** (`e2e/mock-api.ts` + `e2e/mock-data.ts`), kein echtes Backend.
Neue API-Routen/Felder dort spiegeln. `skipUnlessMock()` am Testanfang.
**Backend**:
```bash
dotnet build
dotnet test # GerbilManager.Tests
dotnet ef migrations add <Name> --project GerbilManagerWebAPI # neue Migration
```
- Zum Bauen muss eine laufende WebAPI ggf. gestoppt werden (Datei-Lock auf `bin`).
**Python** (`cd tools/import`, zero-dep, exit 0 = pass):
```bash
python test_extract.py test_extract_docx.py test_genotype.py test_merge_resolve.py test_extract_contracts.py
```
## Konventionen (bitte einhalten)
- **Alle deutschen UI-Texte in `gerbil-manager-web/src/strings/de.ts`** — niemals in
Komponenten hartkodieren.
- **EF-Migration** für jede Schema-Änderung; wird beim Aspire-Start angewandt.
- **Provenance/Datenherkunft** liegt als **JSON-Text-Spalte** (`Provenance`) auf
Gerbil/Contact/Litter → JSON-Feld-Erweiterungen brauchen **keine** Migration.
- **Lose nullable Guid-Spalten ohne FK** für Tabellen, die den Ingest-Wipe überleben.
- Commits: nur wenn der Nutzer es verlangt; auf `main` wird gearbeitet (Remote: `http://truenas:13000/Gulum/GerbilManager.git`). Commit-Messages auf Deutsch, Format `feat(scope): …`.
- Subagenten committen NICHT — Haupt-Loop verifiziert und committet.
## Domänenwissen (Rennmaus-Zucht)
- **Lebensspanne ~6 Jahre** → ein Elternteil kann max. ~6 Jahre älter als sein Kind
sein und muss vorher geboren sein (`parent_age_plausible` im Import; verwirft
unplausible Eltern-Links).
- **Geschwisterverpaarung** (Vollgeschwister als Eltern): erkannt, wenn Vater & Mutter
**dieselbe `litterId`** ODER **dasselbe Geburtsdatum** teilen (gleiches DOB = starkes
Indiz). UI: Diagramm führt den Vorfahren-Ast zusammen (Verweis-Knoten); Akte zeigt
„⚭ Geschwisterverpaarung"-Chip.
- **Box-Farbe im Stammbaum-xlsx = Geschlecht**: weiß = weiblich, blau = männlich.
- **Bestandstier (`isResident`) vs. reiner Vorfahre** (Regel der Züchterin, Ticket 09bcac78):
Ein Tier ist **ihr Zuchttier** ⇔ es hatte bei ihr Nachzucht mit Herkunft **„von den
Kleinen Chaoten"** (nur dann konnten die Jungtiere ihren Zuchtnamen tragen). Trägt die
Nachzucht einen **fremden** Herkunftsnamen (z. B. „of Black Forest", „of Topolino"), ist
das Tier nur **Vorfahre** (`isResident=false`, keine Würfe/Charakter-Bereich). **Ausnahme:
zugekaufte Zuchttiere** (fremder Herkunftsname, aber bei ihr gezüchtet → Nachzucht „von den
Kleinen Chaoten") bleiben **Bestandstiere** (z. B. Echo/Elia of Black Forest).
**Sweep umgesetzt (2026-06-27, Ticket 381f7e51):** Der Wurfchronik-Import-Default ist
**nicht mehr `is_resident=True`**. Neue Regel in `merge_and_resolve.py` (später Sweep
nach Eltern-/`addLitters`-Verknüpfung): `isResident=true` **genau dann**, wenn (1) ein
expliziter `conflict-decisions.json`-`isResident`-Override greift (gewinnt immer — `true`
wie Echo/Elia, `false` wie Akane/Naémi/Bentley), **oder** (2) das Tier **Elternteil eines
eigenen Wurfs** ist (nicht-virtuell ODER aus Wurfchronik ODER Clan-Nachzucht ODER mit
residentem Elternteil ODER `addLitter` mit `ShowInChronicle`). Reine virtuelle
Ahnen-Verpaarungen machen **nicht** resident (z. B. Antares bleibt `false`). Sonst
`false`. `ShowInChronicle` wird **nach** dem Sweep berechnet (nutzt die finale Residenz).
Effekt: resident **1711 → 442**. UI-Label (`de.ts` `isResidentLabel`) = **„Zuchtanwärter/
innen"** — die Züchterin markiert künftige Zuchttiere selbst. **Offene Folgeaufgabe:**
manuelle UI-Residenz-Markierungen überleben den Re-Ingest noch **nicht** (bräuchten eine
ingest-stabile, FK-freie Override-Ablage analog `Feedback`).
- **Genotyp/Farbschlag**: 8-Locus-Notation (siehe `tools/import/genotype.py`,
`gerbil-manager-web/src/genetics`). Unbekanntes Allel = `-` (nicht `?`).
E-Locus: `ee`=Fuchs, `eef`=Fuchsschimmel, `efef`=Schimmel. Rezessiver Fuchs ist
zwingend homozygot → `e-` ist ungültig (wirft), `ee[-]``ee`.
- **Genetik-Engine = korrektheitskritisch: IMMER vollständig mit Tests absichern.**
Jede Änderung an `src/genetics/**` (+ Backend-Mirror + `genotype.py`) braucht pro
Use-Case/Ticket einen Regressionstest (`src/genetics/__tests__/genetics.test.ts`
und `tools/import/test_genotype.py`), damit nie eine Regression entsteht. `npx vitest
run` + `python test_genotype.py` müssen grün sein, bevor „fertig".
- **Stammbaum-Charts**: Generationen = Spaltenbänder (Proband links in Spalte B/2,
je Generation +3 Spalten); Eltern-Position: Vater oben, Mutter unten. Fotos liegen
je nach Datei links/auf der Namenszelle — die Seite wird heuristisch über die
geringste Spalten-Fehlausrichtung bestimmt (`extract._attach_photos`).
## Stolperfallen
- **Aspire-Containername wechselt** pro Run, das Daten-Volume bleibt → DB-Inhalt
überlebt Neustarts (auch alte Schema-Stände → Migrationskonflikte möglich, s. u.).
- **Migrations-Historie vs. committete Migration-IDs**: Wird eine Migration angewandt
und danach mit neuem Zeitstempel neu generiert, sieht EF sie als „pending" und der
Start crasht („column … already exists"). Schema ist dann korrekt — nur die
`__EFMigrationsHistory`-IDs müssen an die committeten Dateinamen angeglichen werden.
- **PowerShell + psql**: PascalCase-Identifier (`"__EFMigrationsHistory"`) über
PowerShell→docker→psql zerschießen das Quoting. Stattdessen Bash-Heredoc:
`docker exec -i -e PGPASSWORD=$PW <container> psql -U postgres -d gerbilmanager <<'SQL' … SQL`.
Passwort: `docker exec <container> printenv POSTGRES_PASSWORD`.
- **Direkte DB-Schreibzugriffe** (psql) werden vom Auto-Mode-Classifier blockiert —
vorher beim Nutzer rückversichern.
- Bash-Tool ist **Git-Bash (POSIX)**, das andere Tool ist **PowerShell** — je eigene Syntax.
## Wo liegt was (Feature-Landkarte)
- **Stammbaum-Viewer**: `gerbil-manager-web/src/pages/StammbaumPage.tsx`,
`src/pedigree/*` (build.ts = Baum-Aufbau + Geschwister-Erkennung; types.ts).
Desktop passt den ganzen Baum ein; Touch: Long-Press öffnet das Kontextmenü
(ID kopieren / Fehler melden).
- **Datenherkunft/Nachverfolgung**: `src/components/ProvenanceDialog.tsx`; erzeugt im
Import via `build_entity_provenance`/`_build_*_history` (chronologische, datei-
attribuierte `history[]`, inkl. „⚠ … verworfen — Grund; … verwendet").
- **Fehler melden (Feedback)**: `src/components/ReportErrorDialog.tsx`,
`src/api/feedback.ts`, Backend `Endpoints/FeedbackEndpoints.cs` + `Models/Feedback.cs`.
- **Geprüfte Tiere / „vollständig korrekt"-Freeze**: Backend `Models/GerbilOverride.cs` (FK-frei,
ingest-überlebend), `Import/GerbilSnapshotService.cs` (Akten-Snapshot + Freeze-Map + Diff, von App
**und** Test geteilt), `Endpoints/VerifiedGerbilEndpoints.cs` (`/verified-gerbils`: POST markieren,
DELETE entfernen/Toggle, GET Liste+Drift, GET `/export` = Golden-Fixture). Freeze wird in
`IngestResolvedService` angewandt; `GerbilEndpoints` setzt `IsManual=true` bei POST und legt bei
Edit eines importierten Tiers einen per-field-Override an (verifiziert → Golden auto-aktualisiert).
Frontend: `src/api/verified.ts`, Badge/Toggle/Drift-Karte in `pages/GerbilDetailPage.tsx`,
Übersicht `pages/VerifizierteTierePage.tsx` (`/hilfe/verifizierte-tiere`); Texte in `strings/de.ts`
(`verified`-Block). **Modell:** `OverrideJson` = Feld→Wert-Map; `IsVerified=true` = zertifiziert +
voller Freeze + Regression/Export, `false` = „geschützt" (nur geänderte Felder). Status/Gehege und
Abstammung/Nachzucht werden **nicht** eingefroren (nur erkannt/gemeldet). Regressionstest:
`GerbilManager.Tests/VerifiedGoldenTests.cs` gegen `tools/import/verified-golden.json` (via
`GET /verified-gerbils/export` erzeugen + committen; skippt, wenn Fixture/`resolved_import.json` fehlt).
**Scope-Grenze:** Freeze/Override gelten für **Gerbils**; Edits an importierten Würfen/Kontakten und
manuelle SaleContracts sind noch **nicht** geschützt (Folgeaufgaben).
- **Verträge**: `Models/SaleContract.cs`, `Endpoints/ContractEndpoints.cs`,
`ContractGenerator.cs`, Frontend `src/pages/Vertraege*`; Import: `extract_contracts.py`
+ `enrich_from_contracts` in `merge_and_resolve.py`.
- **Import-Kernlogik**: `tools/import/merge_and_resolve.py` (Dedup, Eltern-Resolver mit
Gender-/Alters-Plausibilität, Litter-/Sibling-Dedup, Provenance, Vertrags-Anreicherung).
- **RennmausPro-III-Import (rpro3)**: Backend-Importer `GerbilManagerWebAPI/Import/Rpro3/*`
(`Rpro3ImportService` Analyze/Execute, `Rpro3Dedup` = automatischer Dubletten-Merge, Port von
`tools/import/compare_rpro3.py`). **Manuelle Dubletten-Entscheidungen der Züchterin** (aus den
„rpro3-import"-Tickets) liegen in `GerbilManagerWebAPI/Import/Rpro3/rpro3-decisions.json` und
werden von `Rpro3Dedup.Run(animals, decisions)` honoriert: `same` = Force-Merge (eine rid zieht
den Auto-Cluster mit), `different` = Force-Split, `fields` = Feld-Overrides (Farbe/DOB/Herkunft/
`genotype` (roher Fcode)/`resident`/Notiz) am Cluster. Der `genotype`-Override ist nötig, wenn
Varianten sich im Gencode unterscheiden (z. B. C-Locus c[h] vs. c[chm]) und der Auto-Merge sonst
den falschen Gencode (erstes Cluster-Mitglied) zöge — die Züchterin gibt den korrekten vor
(z. B. MilkyWay → `aa Cc[h] DD ee Gg P- spsp`). **Schlüssel ist die RPRO3-Nummer (rid), NIE der Variantenbuchstabe**
(Buchstaben verschieben sich bei geänderter Clusterbildung) — rids aus dem Ticket-`agentContext`.
Triage-Helfer `tools/import/rpro3_lookup.py` (Name- oder `--rids`-Modus) zieht Farbe/Gencode/
Eltern/Nachzucht+Partner aus `_rpro3.db` für die Rückfragen an die Züchterin.
- **Manuell ergänzte Würfe / versteckte Würfe**: `conflict-decisions.json` kennt neben
`resolutions`/`addAnimals` auch **`addLitters`** [{name, mother(+motherDob), father, children[],
showInChronicle, totalBorn, date, notes}] — materialisiert in `merge_and_resolve.py` als
**späten** Schritt (nach Dedup/Parent-Roles, vor json.dump): Wurf mit deterministischer
`generate_guid("decision-litter-<slug>")`, verknüpft Mutter/Vater/Kinder per Name(+dob),
setzt Kinder-`LitterId`. Die name+dob-Resolutions können zusätzlich `isResident`, `notes`,
`receiver` (Kontaktname→ReceiverContactId) auf bestehende Tiere setzen (läuft NACH der
Residenz-Propagation). `Litter.ShowInChronicle` (bool, Default true; Migration
`AddLitterShowInChronicle`): `false` blendet den Wurf aus der Wurfchronik
(`WuerfeListPage`, Filter `showInChronicle==true`) aus, zeigt ihn aber weiter auf der
Tier-Akte (parentLitters-Query, ungefiltert). Use-Case: extern entstandener Wurf eines
nicht-residenten Tieres (z. B. Akane × Bonaparte).
## Verifikations-Checkliste vor „fertig"
1. `npx tsc --noEmit`, `npx vitest run`, `npx eslint` sauber.
2. Betroffene `npx playwright test`-Specs grün.
3. `dotnet build` + `dotnet test` grün.
4. Bei Import-Änderungen: `python test_*.py` grün + `resolved_import.json` plausibel
(Stichprobe), danach App neu starten + `POST /import/ingest-resolved`.
## Gedächtnis (MemPalace) — IMMER nutzen
Dieses Projekt nutzt **MemPalace** als KI-Langzeitgedächtnis (lokal, kein API-Key).
Die Anbindung ist im Repo persistiert und lädt automatisch:
- `.mcp.json` (committet) registriert den MCP-Server `mempalace-mcp`**19 MCP-Tools**
(`mempalace_search`, `mempalace_kg_query/add/invalidate/timeline`, `mempalace_add_drawer`,
`mempalace_diary_*` …). Aktiv ab Claude-Neustart (MCP-Server einmal bestätigen).
- `.claude/settings.json` (committet) verdrahtet die Hooks
`mempalace hook run --hook {session-start,stop,precompact} --harness claude-code`:
**SessionStart** lädt relevanten Kontext automatisch, **Stop/PreCompact** persistieren.
- Voraussetzung: `mempalace` ist installiert und auf PATH (`~/.local/bin`). Nach `git clone`
ggf. MemPalace installieren; `mempalace.yaml` (Raum-Config) ist bewusst **gitignored**
(per-project, lokal). Der Palast selbst liegt lokal unter `~/.mempalace` (nicht im Repo).
**Arbeitsweise pro Session:** zu Aufgabenbeginn relevantes Wissen abrufen
(`mempalace_search` / `mempalace_kg_query`), bevor du im Code suchst; am Ende neue
durable Erkenntnisse ablegen.
**Subagenten MÜSSEN MemPalace ebenfalls nutzen** — das im Subagent-Prompt IMMER explizit
anweisen: zu Aufgabenbeginn den Palast abfragen (am einfachsten per CLI, kein Key nötig:
`mempalace search "<keywords>"` bzw. `mempalace search "<…>" --wing gerbilmanager`; falls
MCP-Tools verfügbar auch `mempalace_search`/`mempalace_kg_query`) — relevante Domänenregeln,
frühere Entscheidungen und Stolperfallen holen, BEVOR im Code gesucht wird; durable
Erkenntnisse am Ende ablegen (`mempalace add-drawer`/MCP). Gilt für JEDEN gespawnten Agenten.
### Memory-Policy — WANN / WIE / WO eine Memory anlegen
**WANN** (anlegen): nur **dauerhaft** nützliches, **nicht-offensichtliches** Wissen, das
künftige Sessions braucht — Architektur-/Design-Entscheidungen und ihr *Warum*, Domänenregeln
(z. B. 6-Jahre-Lebensspanne, Geschwisterverpaarung), Konventionen, Stolperfallen, bestätigte
Nutzer-Präferenzen, wiederkehrende Workflows.
**NICHT anlegen**: transienter Task-Status; was Code/Git/CLAUDE.md ohnehin festhalten;
Dinge, die nur für das aktuelle Gespräch zählen.
**WIE** (anlegen/pflegen):
- Fakt mit Gültigkeit → `mempalace_kg_add`. Freitext-Notiz/Erkenntnis → `mempalace_add_drawer`
(vorher `mempalace_check_duplicate`).
- Ändert/erledigt sich ein Fakt → `mempalace_kg_invalidate` (setzt End-Datum, **nicht löschen**
der Graph ist temporal). So bleibt nichts veraltet stehen.
- Repo-Dateien werden über `mempalace mine <dir>` automatisch gefilet; `mempalace sync --apply
--wing gerbilmanager` entfernt Drawers gelöschter/verschobener Dateien.
**WO** (welcher Speicher):
- **MemPalace-Palast** (`~/.mempalace`, lokal): reichhaltiges, durchsuchbares Recall — der Default
für Memories.
- **CLAUDE.md** (Repo, committet): die **kanonischen** Projektfakten/Konventionen, die geteilt und
versioniert sein müssen. Wichtige durable Erkenntnisse hier spiegeln, damit sie im Repo (nicht nur
lokal) liegen.
Faustregel: durable + projektweit kanonisch → **CLAUDE.md** *und* Palast; sonstiges durable Wissen →
Palast; veraltetes → invalidieren, nicht stehen lassen.

View File

@@ -4,6 +4,13 @@ using System.Net.Sockets;
var builder = DistributedApplication.CreateBuilder(args);
// WEB-2: lokales Verzeichnis für die veröffentlichte öffentliche Seite. Die API schreibt
// nach <root>/live (POST /api/publish), der publicsite-nginx serviert genau dieses live/
// — dieselbe Form wie in Produktion (deploy/truenas), nur lokal zum Testen.
var publicSiteRoot = Path.GetFullPath(Path.Combine(builder.AppHostDirectory, "..", "deploy", ".local-publicsite"));
Directory.CreateDirectory(Path.Combine(publicSiteRoot, "live")); // leeres live/, damit nginx sofort startet
var publicSiteConf = Path.GetFullPath(Path.Combine(builder.AppHostDirectory, "..", "deploy", "truenas", "nginx", "publicsite.conf"));
var postgres = builder.AddPostgres("postgres")
.WithDataVolume();
@@ -19,6 +26,8 @@ var webapi = builder.AddProject<Projects.GerbilManagerWebAPI>("webapi")
// Proxyless so the app binds the port directly — Program.cs then widens the
// host to 0.0.0.0 for LAN access (the DCP proxy binds localhost only).
.WithEndpoint("http", e => { e.Port = ApiHttpPort; e.IsProxied = false; }, createIfNotExists: false)
// WEB-2: Publish-Ziel der öffentlichen Seite (sonst gibt POST /api/publish 503).
.WithEnvironment("PublicSite__RootPath", publicSiteRoot)
.WithExternalHttpEndpoints();
// The machine's LAN IP — the SPA runs in the phone's browser, so it must reach
@@ -40,6 +49,15 @@ builder.AddViteApp("frontend", "../gerbil-manager-web")
context.EnvironmentVariables["VITE_API_BASE_URL"] = $"http://{lanIp}:{ApiHttpPort}";
});
// WEB-2: publicsite-nginx — serviert die veröffentlichte öffentliche Seite lokal (gleiche
// nginx-Config wie in Produktion). Liest das live/-Verzeichnis aus dem Publish-Output der API.
// Test: in der App veröffentlichen (oder POST /api/publish), dann http://localhost:8081 öffnen.
builder.AddContainer("publicsite", "nginx", "alpine")
.WithBindMount(publicSiteRoot, "/usr/share/nginx/html", isReadOnly: true)
.WithBindMount(publicSiteConf, "/etc/nginx/conf.d/default.conf", isReadOnly: true)
.WithHttpEndpoint(port: 8081, targetPort: 80, name: "http")
.WithExternalHttpEndpoints();
builder.Build().Run();
// Picks the IPv4 address of the active physical LAN adapter (Wi-Fi/Ethernet),

View File

@@ -0,0 +1,175 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using GerbilManagerWebAPI.Import;
using GerbilManagerWebAPI.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace GerbilManager.Tests;
/// <summary>
/// ERWERB: acquisition data per animal (purchase date/price/note).
/// - POST creates, GET ?gerbilId= filters, PUT updates, DELETE removes.
/// - CRITICAL: acquisition rows survive the import re-ingest wipe (loose, FK-free
/// GerbilId/SourceContactId), exactly like Feedback.
/// </summary>
public class AcquisitionEndpointTests : IClassFixture<ApiFactory>
{
private readonly ApiFactory _factory;
public AcquisitionEndpointTests(ApiFactory factory) => _factory = factory;
[Fact]
public async Task Crud_roundtrip_create_filter_update_delete()
{
var client = _factory.CreateClient();
var gerbilId = Guid.NewGuid();
var contactId = Guid.NewGuid();
// CREATE
var resp = await client.PostAsJsonAsync("/acquisitions", new
{
gerbilId,
sourceContactId = contactId,
date = "2025-03-14",
price = 25.50m,
note = "Auf der Börse gekauft.",
});
Assert.Equal(HttpStatusCode.Created, resp.StatusCode);
var created = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement;
var id = created.GetProperty("id").GetString()!;
Assert.Equal(gerbilId.ToString(), created.GetProperty("gerbilId").GetString());
Assert.Equal(25.50m, created.GetProperty("price").GetDecimal());
Assert.Equal("2025-03-14", created.GetProperty("date").GetString());
// GET ?gerbilId= returns it
var listed = JsonDocument.Parse(await client.GetStringAsync($"/acquisitions?gerbilId={gerbilId}")).RootElement;
Assert.Contains(listed.EnumerateArray(),
a => a.GetProperty("note").GetString() == "Auf der Börse gekauft.");
// a different gerbilId yields nothing
var other = JsonDocument.Parse(await client.GetStringAsync($"/acquisitions?gerbilId={Guid.NewGuid()}")).RootElement;
Assert.Empty(other.EnumerateArray());
// UPDATE
var put = await client.PutAsJsonAsync($"/acquisitions/{id}", new
{
gerbilId,
sourceContactId = (Guid?)null,
date = "2025-04-01",
price = 30m,
note = "Korrigiert.",
});
Assert.Equal(HttpStatusCode.NoContent, put.StatusCode);
var afterPut = JsonDocument.Parse(await client.GetStringAsync($"/acquisitions/{id}")).RootElement;
Assert.Equal(30m, afterPut.GetProperty("price").GetDecimal());
Assert.Equal("Korrigiert.", afterPut.GetProperty("note").GetString());
Assert.True(afterPut.GetProperty("sourceContactId").ValueKind == JsonValueKind.Null);
// DELETE
var del = await client.DeleteAsync($"/acquisitions/{id}");
Assert.Equal(HttpStatusCode.NoContent, del.StatusCode);
var gone = await client.GetAsync($"/acquisitions/{id}");
Assert.Equal(HttpStatusCode.NotFound, gone.StatusCode);
}
[Fact]
public async Task Acquisition_survives_ingest_wipe()
{
var dir = Path.Combine(Path.GetTempPath(), "acq-ingest-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
try
{
var contactId = Guid.NewGuid();
var fatherId = Guid.NewGuid();
var motherId = Guid.NewGuid();
var litterId = Guid.NewGuid();
var data = new
{
Contacts = new[]
{
new { Id = contactId, Name = "Test Breeder", Email = "t@e.de", Phone = "", Address = "", Notes = (string?)null, IsBreeder = true, IsReceiver = false, NameSuffix = (string?)null, Provenance = (string?)null }
},
Litters = new[]
{
new { Id = litterId, Name = "Wurf A", Date = "2026-01-01", TotalBorn = 5, DeathsWithin8Weeks = 0, FatherId = fatherId, MotherId = motherId, ExpectedGoHomeDate = (string?)null, Notes = "", PairingCode = "PC01", ExternalRef = "ext-litter-1", LitterLetter = "A" }
},
Gerbils = new[]
{
Animal(fatherId, "Papa", "male", contactId),
Animal(motherId, "Mama", "female", contactId),
},
GerbilPhotos = Array.Empty<object>(),
};
File.WriteAllText(Path.Combine(dir, "resolved_import.json"), JsonSerializer.Serialize(data));
var opts = new DbContextOptionsBuilder<ApplicationContext>()
.UseInMemoryDatabase("acq-ingest-" + Guid.NewGuid().ToString("N"))
.Options;
using var db = new ApplicationContext(opts);
db.Database.EnsureCreated();
// An acquisition referencing the gerbil + contact the wipe will delete.
var acqId = Guid.NewGuid();
db.AcquisitionRecords.Add(new AcquisitionRecord
{
Id = acqId,
GerbilId = fatherId,
SourceContactId = contactId,
Date = new DateOnly(2025, 3, 14),
Price = 25.50m,
Note = "Auf der Börse gekauft.",
CreatedAt = DateTimeOffset.UtcNow,
});
await db.SaveChangesAsync();
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?> { { "Import:SourcePath", dir } })
.Build();
var result = await new IngestResolvedService(db, config, null!).RunAsync();
Assert.Contains("Ingestion successful!", result);
// The acquisition row survives even though the gerbil + contact were wiped/recreated.
var survivor = await db.AcquisitionRecords.SingleAsync(a => a.Id == acqId);
Assert.Equal(fatherId, survivor.GerbilId);
Assert.Equal(contactId, survivor.SourceContactId);
Assert.Equal(25.50m, survivor.Price);
Assert.Equal("Auf der Börse gekauft.", survivor.Note);
Assert.Equal(1, await db.AcquisitionRecords.CountAsync());
}
finally
{
try { Directory.Delete(dir, recursive: true); } catch { /* best effort */ }
}
}
private static object Animal(Guid id, string name, string gender, Guid contactId) => new
{
Id = id,
Name = name,
Gender = gender,
Status = "Breeding",
LitterId = (Guid?)null,
OriginContactId = contactId,
ReceiverContactId = (Guid?)null,
EnclosureId = (Guid?)null,
ColorVarietyId = new Guid("00000000-0000-0000-0000-000000000006"),
DateOfBirth = "2025-01-01",
DateOfDeath = (string?)null,
CauseOfDeath = (string?)null,
GoHomeDate = (string?)null,
Genotype = "aa CC DD EE GG PP spsp rere",
Notes = "",
ImportSource = "docx-export",
ExternalRef = "ext-" + name,
RawImportData = "{}",
OriginBreeder = "Test Zucht",
NameSearch = name.ToLowerInvariant(),
CharacterTraits = Array.Empty<string>(),
CharacterNote = (string?)null,
IsDeaf = false,
IsResident = true,
};
}

View File

@@ -0,0 +1,103 @@
using GerbilManagerWebAPI.Endpoints;
namespace GerbilManager.Tests;
/// <summary>WEB-2: POST /api/publish — atomic swap, file layout, staging cleanup.</summary>
public class CmsPublishTests
{
private static string TempRoot() =>
Path.Combine(Path.GetTempPath(), "gm-publish-test-" + Guid.NewGuid().ToString("N"));
[Fact]
public async Task Publish_erstellt_live_Verzeichnis_mit_allen_Dateien()
{
var root = TempRoot();
try
{
var files = new Dictionary<string, string>
{
["index.html"] = "<html>start</html>",
["kontakt/index.html"] = "<html>kontakt</html>",
["assets/site.css"] = "body {}",
};
await CmsEndpoints.PublishToDirectoryAsync(files, root);
Assert.True(File.Exists(Path.Combine(root, "live", "index.html")));
Assert.True(File.Exists(Path.Combine(root, "live", "kontakt", "index.html")));
Assert.True(File.Exists(Path.Combine(root, "live", "assets", "site.css")));
Assert.Equal("<html>start</html>",
await File.ReadAllTextAsync(Path.Combine(root, "live", "index.html")));
}
finally { if (Directory.Exists(root)) Directory.Delete(root, true); }
}
[Fact]
public async Task Publish_atomarer_Swap_ueberschreibt_alte_live_Version()
{
var root = TempRoot();
try
{
await CmsEndpoints.PublishToDirectoryAsync(
new Dictionary<string, string> { ["index.html"] = "version-1" }, root);
await CmsEndpoints.PublishToDirectoryAsync(
new Dictionary<string, string> { ["index.html"] = "version-2" }, root);
var content = await File.ReadAllTextAsync(Path.Combine(root, "live", "index.html"));
Assert.Equal("version-2", content);
}
finally { if (Directory.Exists(root)) Directory.Delete(root, true); }
}
[Fact]
public async Task Publish_kein_staging_oder_old_Verzeichnis_nach_Swap()
{
var root = TempRoot();
try
{
await CmsEndpoints.PublishToDirectoryAsync(
new Dictionary<string, string> { ["index.html"] = "x" }, root);
Assert.False(Directory.Exists(Path.Combine(root, "_staging_new")));
Assert.False(Directory.Exists(Path.Combine(root, "_old")));
}
finally { if (Directory.Exists(root)) Directory.Delete(root, true); }
}
[Fact]
public async Task Publish_mehrfach_ohne_Fehler()
{
var root = TempRoot();
try
{
for (int i = 1; i <= 3; i++)
{
await CmsEndpoints.PublishToDirectoryAsync(
new Dictionary<string, string> { ["index.html"] = $"v{i}" }, root);
}
Assert.Equal("v3",
await File.ReadAllTextAsync(Path.Combine(root, "live", "index.html")));
}
finally { if (Directory.Exists(root)) Directory.Delete(root, true); }
}
[Fact]
public async Task Publish_UTF8_Inhalt_korrekt_gespeichert()
{
var root = TempRoot();
try
{
const string german = "<html>Züchter — Rennmäuse & mehr</html>";
await CmsEndpoints.PublishToDirectoryAsync(
new Dictionary<string, string> { ["index.html"] = german }, root);
var content = await File.ReadAllTextAsync(
Path.Combine(root, "live", "index.html"),
System.Text.Encoding.UTF8);
Assert.Equal(german, content);
}
finally { if (Directory.Exists(root)) Directory.Delete(root, true); }
}
}

View File

@@ -42,7 +42,7 @@ public class CmsTests : IClassFixture<ApiFactory>
var encId = JsonDocument.Parse(await encResp.Content.ReadAsStringAsync()).RootElement.GetProperty("id").GetString();
await _client.PostAsJsonAsync("/gerbils", new { name = "Verkaufsmaus", gender = "female", status = "ForSale", enclosureId = encId });
// a non-ForSale gerbil must NOT appear
await _client.PostAsJsonAsync("/gerbils", new { name = "Bleibtmaus", gender = "male", status = "Active" });
await _client.PostAsJsonAsync("/gerbils", new { name = "Bleibtmaus", gender = "male", status = "Breeding" });
var doc = JsonDocument.Parse(await _client.GetStringAsync("/api/site-snapshot"));
var animals = doc.RootElement.GetProperty("pages").EnumerateArray()

View File

@@ -0,0 +1,118 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
namespace GerbilManager.Tests;
/// <summary>
/// Gehege-Reinigungszyklus (RennmausPro becken_tb): Enclosure trägt Maße (Size),
/// Kapazität (Capacity), letzte Reinigung (LastCleanedDate) und Reinigungsintervall
/// (CleaningCycleDays). NextCleaningDate = LastCleanedDate + CleaningCycleDays wird
/// berechnet ausgegeben. "mark-cleaned" setzt die letzte Reinigung auf heute.
/// </summary>
public class EnclosureEndpointTests : IClassFixture<ApiFactory>
{
private readonly ApiFactory _factory;
public EnclosureEndpointTests(ApiFactory factory) => _factory = factory;
[Fact]
public async Task Post_persists_cleaning_fields_and_computes_next_cleaning()
{
var client = _factory.CreateClient();
var resp = await client.PostAsJsonAsync("/enclosures", new
{
name = "Reinigungs-Becken",
notes = "Test",
size = "120×50 cm",
capacity = 6,
lastCleanedDate = "2026-06-01",
cleaningCycleDays = 14,
});
Assert.Equal(HttpStatusCode.Created, resp.StatusCode);
var dto = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement;
Assert.Equal("120×50 cm", dto.GetProperty("size").GetString());
Assert.Equal(6, dto.GetProperty("capacity").GetInt32());
Assert.Equal("2026-06-01", dto.GetProperty("lastCleanedDate").GetString());
Assert.Equal(14, dto.GetProperty("cleaningCycleDays").GetInt32());
// 2026-06-01 + 14 Tage = 2026-06-15
Assert.Equal("2026-06-15", dto.GetProperty("nextCleaningDate").GetString());
}
[Fact]
public async Task NextCleaning_is_null_without_cycle_or_lastCleaned()
{
var client = _factory.CreateClient();
// Nur letzte Reinigung, kein Zyklus -> keine nächste fällige Reinigung.
var resp = await client.PostAsJsonAsync("/enclosures", new
{
name = "Becken ohne Zyklus",
lastCleanedDate = "2026-06-01",
});
var dto = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement;
Assert.Equal(JsonValueKind.Null, dto.GetProperty("nextCleaningDate").ValueKind);
Assert.Equal(JsonValueKind.Null, dto.GetProperty("cleaningCycleDays").ValueKind);
}
[Fact]
public async Task Put_updates_cleaning_fields()
{
var client = _factory.CreateClient();
var created = JsonDocument.Parse(await (await client.PostAsJsonAsync("/enclosures", new
{
name = "Becken-Edit",
cleaningCycleDays = 7,
})).Content.ReadAsStringAsync()).RootElement;
var id = created.GetProperty("id").GetString();
var put = await client.PutAsJsonAsync($"/enclosures/{id}", new
{
name = "Becken-Edit",
size = "80×40 cm",
capacity = 4,
lastCleanedDate = "2026-05-20",
cleaningCycleDays = 10,
});
Assert.Equal(HttpStatusCode.NoContent, put.StatusCode);
var dto = JsonDocument.Parse(await client.GetStringAsync($"/enclosures/{id}")).RootElement;
Assert.Equal("80×40 cm", dto.GetProperty("size").GetString());
Assert.Equal(4, dto.GetProperty("capacity").GetInt32());
Assert.Equal("2026-05-20", dto.GetProperty("lastCleanedDate").GetString());
Assert.Equal(10, dto.GetProperty("cleaningCycleDays").GetInt32());
Assert.Equal("2026-05-30", dto.GetProperty("nextCleaningDate").GetString());
}
[Fact]
public async Task MarkCleaned_sets_lastCleaned_to_today()
{
var client = _factory.CreateClient();
var created = JsonDocument.Parse(await (await client.PostAsJsonAsync("/enclosures", new
{
name = "Becken-Mark",
cleaningCycleDays = 21,
lastCleanedDate = "2020-01-01",
})).Content.ReadAsStringAsync()).RootElement;
var id = created.GetProperty("id").GetString();
var resp = await client.PostAsync($"/enclosures/{id}/mark-cleaned", null);
Assert.Equal(HttpStatusCode.OK, resp.StatusCode);
var dto = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement;
var today = DateOnly.FromDateTime(DateTime.Today);
Assert.Equal(today.ToString("yyyy-MM-dd"), dto.GetProperty("lastCleanedDate").GetString());
Assert.Equal(today.AddDays(21).ToString("yyyy-MM-dd"), dto.GetProperty("nextCleaningDate").GetString());
}
[Fact]
public async Task MarkCleaned_unknown_id_returns_404()
{
var client = _factory.CreateClient();
var resp = await client.PostAsync($"/enclosures/{Guid.NewGuid()}/mark-cleaned", null);
Assert.Equal(HttpStatusCode.NotFound, resp.StatusCode);
}
}

View File

@@ -0,0 +1,211 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using GerbilManagerWebAPI.Import;
using GerbilManagerWebAPI.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace GerbilManager.Tests;
/// <summary>
/// EXHIBITION: show/exhibition results &amp; awards per animal (/exhibitions).
/// - POST creates a row; GET (optionally filtered by gerbilId) returns it, newest first.
/// - PUT edits, DELETE removes; unknown ids return 404; an empty EventName is rejected (400).
/// - CRITICAL: exhibition rows survive the import re-ingest wipe (loose, FK-free GerbilId).
/// </summary>
public class ExhibitionEndpointTests : IClassFixture<ApiFactory>
{
private readonly ApiFactory _factory;
public ExhibitionEndpointTests(ApiFactory factory) => _factory = factory;
[Fact]
public async Task Post_creates_and_get_filters_by_gerbilId()
{
var client = _factory.CreateClient();
var gerbilId = Guid.NewGuid();
var resp = await client.PostAsJsonAsync("/exhibitions", new
{
gerbilId,
entityName = "Krümel",
eventName = "Nationale Rennmausschau 2026",
date = "2026-03-15T00:00:00Z",
placement = "1. Platz",
award = "Best in Show",
note = "Sehr ausgeglichenes Tier.",
});
Assert.Equal(HttpStatusCode.Created, resp.StatusCode);
var created = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement;
var id = created.GetProperty("id").GetString();
Assert.False(string.IsNullOrEmpty(id));
Assert.Equal("Nationale Rennmausschau 2026", created.GetProperty("eventName").GetString());
Assert.Equal("1. Platz", created.GetProperty("placement").GetString());
Assert.Equal("Best in Show", created.GetProperty("award").GetString());
Assert.Equal(gerbilId.ToString(), created.GetProperty("gerbilId").GetString());
// GET filtered to this gerbil returns the row.
var listed = JsonDocument.Parse(await client.GetStringAsync($"/exhibitions?gerbilId={gerbilId}")).RootElement;
Assert.Contains(listed.EnumerateArray(),
x => x.GetProperty("id").GetString() == id
&& x.GetProperty("eventName").GetString() == "Nationale Rennmausschau 2026");
// GET filtered to a DIFFERENT gerbil does not.
var other = JsonDocument.Parse(await client.GetStringAsync($"/exhibitions?gerbilId={Guid.NewGuid()}")).RootElement;
Assert.DoesNotContain(other.EnumerateArray(), x => x.GetProperty("id").GetString() == id);
}
[Fact]
public async Task Crud_lifecycle_edit_and_delete()
{
var client = _factory.CreateClient();
var create = await client.PostAsJsonAsync("/exhibitions", new
{
eventName = "Lokalschau",
entityName = "Balu",
});
Assert.Equal(HttpStatusCode.Created, create.StatusCode);
var id = JsonDocument.Parse(await create.Content.ReadAsStringAsync()).RootElement.GetProperty("id").GetString();
// Edit: change placement + add a date.
var edit = await client.PutAsJsonAsync($"/exhibitions/{id}", new
{
placement = "2. Platz",
date = "2025-11-01T00:00:00Z",
});
Assert.Equal(HttpStatusCode.OK, edit.StatusCode);
var edited = JsonDocument.Parse(await edit.Content.ReadAsStringAsync()).RootElement;
Assert.Equal("2. Platz", edited.GetProperty("placement").GetString());
Assert.Equal("Lokalschau", edited.GetProperty("eventName").GetString());
// Delete -> 204, then 404 on subsequent edit/delete.
var del = await client.DeleteAsync($"/exhibitions/{id}");
Assert.Equal(HttpStatusCode.NoContent, del.StatusCode);
Assert.Equal(HttpStatusCode.NotFound, (await client.DeleteAsync($"/exhibitions/{id}")).StatusCode);
Assert.Equal(HttpStatusCode.NotFound, (await client.PutAsJsonAsync($"/exhibitions/{id}", new { eventName = "x" })).StatusCode);
}
[Fact]
public async Task Post_rejects_empty_event_name()
{
var client = _factory.CreateClient();
var resp = await client.PostAsJsonAsync("/exhibitions", new { eventName = " " });
Assert.Equal(HttpStatusCode.BadRequest, resp.StatusCode);
}
[Fact]
public async Task Put_and_delete_unknown_id_return_404()
{
var client = _factory.CreateClient();
var missing = Guid.NewGuid();
Assert.Equal(HttpStatusCode.NotFound, (await client.PutAsJsonAsync($"/exhibitions/{missing}", new { eventName = "x" })).StatusCode);
Assert.Equal(HttpStatusCode.NotFound, (await client.DeleteAsync($"/exhibitions/{missing}")).StatusCode);
}
[Fact]
public async Task Exhibition_survives_ingest_wipe()
{
// Fresh in-memory DB seeded with a resolved import file (mirrors IngestResolvedServiceTests).
var dir = Path.Combine(Path.GetTempPath(), "exhibition-ingest-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
try
{
var contactId = Guid.NewGuid();
var fatherId = Guid.NewGuid();
var motherId = Guid.NewGuid();
var litterId = Guid.NewGuid();
var data = new
{
Contacts = new[]
{
new { Id = contactId, Name = "Test Breeder", Email = "t@e.de", Phone = "", Address = "", Notes = (string?)null, IsBreeder = true, IsReceiver = false, NameSuffix = (string?)null, Provenance = (string?)null }
},
Litters = new[]
{
new { Id = litterId, Name = "Wurf A", Date = "2026-01-01", TotalBorn = 5, DeathsWithin8Weeks = 0, FatherId = fatherId, MotherId = motherId, ExpectedGoHomeDate = (string?)null, Notes = "", PairingCode = "PC01", ExternalRef = "ext-litter-1", LitterLetter = "A" }
},
Gerbils = new[]
{
Animal(fatherId, "Papa", "male", contactId),
Animal(motherId, "Mama", "female", contactId),
},
GerbilPhotos = Array.Empty<object>(),
};
File.WriteAllText(Path.Combine(dir, "resolved_import.json"), JsonSerializer.Serialize(data));
var opts = new DbContextOptionsBuilder<ApplicationContext>()
.UseInMemoryDatabase("exhibition-ingest-" + Guid.NewGuid().ToString("N"))
.Options;
using var db = new ApplicationContext(opts);
db.Database.EnsureCreated();
// An exhibition result referencing the gerbil that the wipe will delete/recreate.
var exhId = Guid.NewGuid();
db.ExhibitionResults.Add(new ExhibitionResult
{
Id = exhId,
GerbilId = fatherId,
EntityName = "Papa",
EventName = "Nationale Rennmausschau 2026",
Date = new DateTime(2026, 3, 15, 0, 0, 0, DateTimeKind.Utc),
Placement = "1. Platz",
Award = "Best in Show",
Note = "Tolles Tier.",
CreatedAt = DateTimeOffset.UtcNow,
});
await db.SaveChangesAsync();
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?> { { "Import:SourcePath", dir } })
.Build();
// Run the ingest wipe + reload.
var result = await new IngestResolvedService(db, config, null!).RunAsync();
Assert.Contains("Ingestion successful!", result);
// Gerbils/litters/contacts were wiped & re-created, but the exhibition row is untouched.
var survivor = await db.ExhibitionResults.SingleAsync(x => x.Id == exhId);
Assert.Equal(fatherId, survivor.GerbilId); // loose id preserved even though the gerbil row was deleted/recreated
Assert.Equal("Papa", survivor.EntityName);
Assert.Equal("Nationale Rennmausschau 2026", survivor.EventName);
Assert.Equal("1. Platz", survivor.Placement);
Assert.Equal("Best in Show", survivor.Award);
Assert.Equal(1, await db.ExhibitionResults.CountAsync());
}
finally
{
try { Directory.Delete(dir, recursive: true); } catch { /* best effort */ }
}
}
private static object Animal(Guid id, string name, string gender, Guid contactId) => new
{
Id = id,
Name = name,
Gender = gender,
Status = "Breeding",
LitterId = (Guid?)null,
OriginContactId = contactId,
ReceiverContactId = (Guid?)null,
EnclosureId = (Guid?)null,
ColorVarietyId = new Guid("00000000-0000-0000-0000-000000000006"),
DateOfBirth = "2025-01-01",
DateOfDeath = (string?)null,
CauseOfDeath = (string?)null,
GoHomeDate = (string?)null,
Genotype = "aa CC DD EE GG PP spsp rere",
Notes = "",
ImportSource = "docx-export",
ExternalRef = "ext-" + name,
RawImportData = "{}",
OriginBreeder = "Test Zucht",
NameSearch = name.ToLowerInvariant(),
CharacterTraits = Array.Empty<string>(),
CharacterNote = (string?)null,
IsDeaf = false,
IsResident = true,
};
}

View File

@@ -60,7 +60,7 @@ namespace GerbilManager.Tests
Id = Guid.NewGuid(),
Name = "Krümel",
Gender = Gender.female,
Status = GerbilStatus.Active,
Status = GerbilStatus.Breeding,
DateOfBirth = new DateOnly(2025, 3, 12),
LitterId = litter.Id,
EnclosureId = enclosure.Id,
@@ -118,7 +118,7 @@ namespace GerbilManager.Tests
var row = lines[1];
Assert.Contains("Krümel", row);
Assert.Contains("Weiblich", row);
Assert.Contains("Aktiv", row);
Assert.Contains("Zucht", row);
Assert.Contains("12.03.2025", row);
Assert.Contains("Großbecken", row);
Assert.Contains("Wurf K", row);

View File

@@ -0,0 +1,530 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using GerbilManagerWebAPI.Import;
using GerbilManagerWebAPI.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace GerbilManager.Tests;
/// <summary>
/// FEEDBACK: the "Fehler melden" report sink.
/// - POST /feedback persists a row (with captured debug context) and GET /feedback returns it.
/// - Validation: an empty message is rejected with 400.
/// - CRITICAL: feedback rows survive the import re-ingest wipe (loose, FK-free GerbilId/LitterId).
/// </summary>
public class FeedbackEndpointTests : IClassFixture<ApiFactory>
{
private readonly ApiFactory _factory;
public FeedbackEndpointTests(ApiFactory factory) => _factory = factory;
[Fact]
public async Task Post_feedback_persists_row_with_debug_context()
{
var client = _factory.CreateClient();
var gerbilId = Guid.NewGuid();
var resp = await client.PostAsJsonAsync("/feedback", new
{
message = "Der Stammbaum zeigt den falschen Vater.",
context = "stammbaum",
gerbilId,
litterId = (Guid?)null,
entityName = "Krümel",
url = "http://localhost:5173/rennmaeuse/kruemel/stammbaum",
clientTimestamp = "2026-06-22T12:00:00Z",
});
Assert.Equal(HttpStatusCode.Created, resp.StatusCode);
var created = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement;
Assert.False(string.IsNullOrEmpty(created.GetProperty("id").GetString()));
Assert.Equal("stammbaum", created.GetProperty("context").GetString());
Assert.Equal("Krümel", created.GetProperty("entityName").GetString());
Assert.Equal(gerbilId.ToString(), created.GetProperty("gerbilId").GetString());
// A freshly created ticket starts Open with no ResolvedAt.
Assert.Equal("Open", created.GetProperty("status").GetString());
Assert.Equal(JsonValueKind.Null, created.GetProperty("resolvedAt").ValueKind);
// GET returns it (newest first)
var listed = JsonDocument.Parse(await client.GetStringAsync("/feedback")).RootElement;
Assert.Contains(listed.EnumerateArray(),
f => f.GetProperty("entityName").GetString() == "Krümel"
&& f.GetProperty("message").GetString() == "Der Stammbaum zeigt den falschen Vater."
&& f.GetProperty("status").GetString() == "Open");
}
[Fact]
public async Task Feedback_crud_lifecycle_edit_resolve_reopen_delete()
{
var client = _factory.CreateClient();
// Create
var create = await client.PostAsJsonAsync("/feedback", new
{
message = "Gewicht wird falsch gerundet.",
context = "gerbil-detail",
entityName = "Balu",
});
Assert.Equal(HttpStatusCode.Created, create.StatusCode);
var id = JsonDocument.Parse(await create.Content.ReadAsStringAsync()).RootElement.GetProperty("id").GetString();
Assert.False(string.IsNullOrEmpty(id));
// List contains it
var listed = JsonDocument.Parse(await client.GetStringAsync("/feedback")).RootElement;
Assert.Contains(listed.EnumerateArray(), f => f.GetProperty("id").GetString() == id);
// Edit message
var edit = await client.PutAsJsonAsync($"/feedback/{id}", new { message = "Gewicht wird falsch gerundet (auf der Verlaufskurve)." });
Assert.Equal(HttpStatusCode.OK, edit.StatusCode);
var edited = JsonDocument.Parse(await edit.Content.ReadAsStringAsync()).RootElement;
Assert.Equal("Gewicht wird falsch gerundet (auf der Verlaufskurve).", edited.GetProperty("message").GetString());
Assert.Equal("Open", edited.GetProperty("status").GetString());
// Empty message is rejected
var empty = await client.PutAsJsonAsync($"/feedback/{id}", new { message = " " });
Assert.Equal(HttpStatusCode.BadRequest, empty.StatusCode);
// Mark resolved -> ResolvedAt is set
var resolve = await client.PutAsJsonAsync($"/feedback/{id}", new { status = "Resolved" });
Assert.Equal(HttpStatusCode.OK, resolve.StatusCode);
var resolved = JsonDocument.Parse(await resolve.Content.ReadAsStringAsync()).RootElement;
Assert.Equal("Resolved", resolved.GetProperty("status").GetString());
Assert.NotEqual(JsonValueKind.Null, resolved.GetProperty("resolvedAt").ValueKind);
// Reopen -> ResolvedAt cleared
var reopen = await client.PutAsJsonAsync($"/feedback/{id}", new { status = "Open" });
Assert.Equal(HttpStatusCode.OK, reopen.StatusCode);
var reopened = JsonDocument.Parse(await reopen.Content.ReadAsStringAsync()).RootElement;
Assert.Equal("Open", reopened.GetProperty("status").GetString());
Assert.Equal(JsonValueKind.Null, reopened.GetProperty("resolvedAt").ValueKind);
// Soft-Delete -> 204; das Ticket bleibt erhalten (DeletedAt gesetzt) und ist über GET noch da.
var del = await client.DeleteAsync($"/feedback/{id}");
Assert.Equal(HttpStatusCode.NoContent, del.StatusCode);
var afterDelete = JsonDocument.Parse(await client.GetStringAsync("/feedback")).RootElement;
var deletedRow = afterDelete.EnumerateArray().Single(f => f.GetProperty("id").GetString() == id);
Assert.NotEqual(JsonValueKind.Null, deletedRow.GetProperty("deletedAt").ValueKind);
// Wiederherstellen -> DeletedAt wieder null, Ticket weiterhin bearbeitbar.
var restore = await client.PostAsync($"/feedback/{id}/restore", null);
Assert.Equal(HttpStatusCode.OK, restore.StatusCode);
var restored = JsonDocument.Parse(await restore.Content.ReadAsStringAsync()).RootElement;
Assert.Equal(JsonValueKind.Null, restored.GetProperty("deletedAt").ValueKind);
// Delete/Restore eines unbekannten Tickets -> 404.
var delMissing = await client.DeleteAsync($"/feedback/{Guid.NewGuid()}");
Assert.Equal(HttpStatusCode.NotFound, delMissing.StatusCode);
var restoreMissing = await client.PostAsync($"/feedback/{Guid.NewGuid()}/restore", null);
Assert.Equal(HttpStatusCode.NotFound, restoreMissing.StatusCode);
}
[Fact]
public async Task Reopen_resolved_ticket_without_Rueckfrage_sets_NeedsInfo_and_ReopenedAt()
{
var client = _factory.CreateClient();
var create = await client.PostAsJsonAsync("/feedback", new
{
message = "Farbschlag stimmt nicht.",
context = "gerbil-detail",
});
var id = JsonDocument.Parse(await create.Content.ReadAsStringAsync()).RootElement.GetProperty("id").GetString();
// Direkt (ohne Rückfrage) lösen …
await client.PutAsJsonAsync($"/feedback/{id}", new { status = "Resolved", fixNote = "behoben" });
// … und wieder öffnen: Frontend schickt NeedsInfo + Bitte-um-Infos-Frage.
var reopen = await client.PutAsJsonAsync($"/feedback/{id}", new
{
status = "NeedsInfo",
question = "Bitte beschreibe, was noch fehlt.",
});
var r = JsonDocument.Parse(await reopen.Content.ReadAsStringAsync()).RootElement;
Assert.Equal("NeedsInfo", r.GetProperty("status").GetString());
Assert.Equal("Bitte beschreibe, was noch fehlt.", r.GetProperty("question").GetString());
// Echt gelöstes Ticket ohne vorherige Rückfrage -> ReopenedAt gesetzt.
Assert.NotEqual(JsonValueKind.Null, r.GetProperty("reopenedAt").ValueKind);
}
[Fact]
public async Task Attachment_upload_list_serve_delete_lifecycle()
{
var client = _factory.CreateClient();
var create = await client.PostAsJsonAsync("/feedback", new
{
message = "Foto vom Fellschlag.",
context = "gerbil-detail",
});
var id = JsonDocument.Parse(await create.Content.ReadAsStringAsync()).RootElement.GetProperty("id").GetString();
// 1×1-PNG hochladen.
const string pngB64 =
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
var up = await client.PostAsJsonAsync($"/feedback/{id}/attachments", new
{
fileName = "maus.png",
contentType = "image/png",
dataBase64 = pngB64,
});
Assert.Equal(HttpStatusCode.Created, up.StatusCode);
var att = JsonDocument.Parse(await up.Content.ReadAsStringAsync()).RootElement;
var attId = att.GetProperty("id").GetString();
Assert.Equal("maus.png", att.GetProperty("fileName").GetString());
Assert.True(att.GetProperty("size").GetInt32() > 0);
// GET /feedback liefert die Metadaten (ohne Bytes).
var listed = JsonDocument.Parse(await client.GetStringAsync("/feedback")).RootElement;
var row = listed.EnumerateArray().Single(f => f.GetProperty("id").GetString() == id);
Assert.Equal(1, row.GetProperty("attachments").GetArrayLength());
// Bytes ausliefern.
var bytes = await client.GetByteArrayAsync($"/feedback/attachments/{attId}");
Assert.Equal(Convert.FromBase64String(pngB64).Length, bytes.Length);
// Löschen -> danach keine Anhänge mehr.
var del = await client.DeleteAsync($"/feedback/attachments/{attId}");
Assert.Equal(HttpStatusCode.NoContent, del.StatusCode);
var after = JsonDocument.Parse(await client.GetStringAsync("/feedback")).RootElement;
var rowAfter = after.EnumerateArray().Single(f => f.GetProperty("id").GetString() == id);
Assert.Equal(0, rowAfter.GetProperty("attachments").GetArrayLength());
}
[Fact]
public async Task Attachment_upload_rejects_invalid_base64()
{
var client = _factory.CreateClient();
var create = await client.PostAsJsonAsync("/feedback", new { message = "x", context = "gerbil-detail" });
var id = JsonDocument.Parse(await create.Content.ReadAsStringAsync()).RootElement.GetProperty("id").GetString();
var up = await client.PostAsJsonAsync($"/feedback/{id}/attachments", new
{
fileName = "x.png",
contentType = "image/png",
dataBase64 = "###nicht base64###",
});
Assert.Equal(HttpStatusCode.BadRequest, up.StatusCode);
}
[Fact]
public async Task Reopen_resolved_ticket_that_had_a_Rueckfrage_keeps_question_and_no_ReopenedAt()
{
var client = _factory.CreateClient();
var create = await client.PostAsJsonAsync("/feedback", new
{
message = "Welches Tier ist gemeint?",
context = "gerbil-detail",
});
var id = JsonDocument.Parse(await create.Content.ReadAsStringAsync()).RootElement.GetProperty("id").GetString();
// Rückfrage stellen (NeedsInfo) …
await client.PutAsJsonAsync($"/feedback/{id}", new { question = "Meinst du A oder B?" });
// … manuell lösen …
await client.PutAsJsonAsync($"/feedback/{id}", new { status = "Resolved" });
// … und wieder öffnen: Frontend schickt dieselbe Frage erneut (keine Bitte-um-Infos).
var reopen = await client.PutAsJsonAsync($"/feedback/{id}", new
{
status = "NeedsInfo",
question = "Meinst du A oder B?",
});
var r = JsonDocument.Parse(await reopen.Content.ReadAsStringAsync()).RootElement;
Assert.Equal("NeedsInfo", r.GetProperty("status").GetString());
Assert.Equal("Meinst du A oder B?", r.GetProperty("question").GetString());
// Hatte bereits eine offene Rückfrage -> KEIN „Wieder geöffnet am"-Zeitstempel.
Assert.Equal(JsonValueKind.Null, r.GetProperty("reopenedAt").ValueKind);
}
[Fact]
public async Task Put_question_sets_NeedsInfo_and_answer_sets_Answered()
{
var client = _factory.CreateClient();
// Create an open ticket.
var create = await client.PostAsJsonAsync("/feedback", new
{
message = "Wurf B hat ein falsches Geburtsdatum.",
context = "litter-detail",
entityName = "Wurf B",
});
Assert.Equal(HttpStatusCode.Created, create.StatusCode);
var id = JsonDocument.Parse(await create.Content.ReadAsStringAsync()).RootElement.GetProperty("id").GetString();
// Attach a clarifying question -> Status becomes NeedsInfo, question echoed back, no answer yet.
var ask = await client.PutAsJsonAsync($"/feedback/{id}", new { question = "Welches Datum stimmt?" });
Assert.Equal(HttpStatusCode.OK, ask.StatusCode);
var asked = JsonDocument.Parse(await ask.Content.ReadAsStringAsync()).RootElement;
Assert.Equal("NeedsInfo", asked.GetProperty("status").GetString());
Assert.Equal("Welches Datum stimmt?", asked.GetProperty("question").GetString());
Assert.Equal(JsonValueKind.Null, asked.GetProperty("answer").ValueKind);
Assert.Equal(JsonValueKind.Null, asked.GetProperty("answeredAt").ValueKind);
// Breeder answers -> Status becomes Answered, AnsweredAt stamped, answer echoed, question retained.
var reply = await client.PutAsJsonAsync($"/feedback/{id}", new { answer = "Der 2. Juni." });
Assert.Equal(HttpStatusCode.OK, reply.StatusCode);
var answered = JsonDocument.Parse(await reply.Content.ReadAsStringAsync()).RootElement;
Assert.Equal("Answered", answered.GetProperty("status").GetString());
Assert.Equal("Der 2. Juni.", answered.GetProperty("answer").GetString());
Assert.Equal("Welches Datum stimmt?", answered.GetProperty("question").GetString());
Assert.NotEqual(JsonValueKind.Null, answered.GetProperty("answeredAt").ValueKind);
}
[Fact]
public async Task Put_question_on_resolved_ticket_keeps_it_resolved()
{
var client = _factory.CreateClient();
var create = await client.PostAsJsonAsync("/feedback", new { message = "x", context = "gerbil-detail" });
var id = JsonDocument.Parse(await create.Content.ReadAsStringAsync()).RootElement.GetProperty("id").GetString();
await client.PutAsJsonAsync($"/feedback/{id}", new { status = "Resolved" });
var put = await client.PutAsJsonAsync($"/feedback/{id}", new { question = "Noch eine Frage?" });
var dto = JsonDocument.Parse(await put.Content.ReadAsStringAsync()).RootElement;
Assert.Equal("Resolved", dto.GetProperty("status").GetString());
Assert.Equal("Noch eine Frage?", dto.GetProperty("question").GetString());
}
[Fact]
public async Task Put_resolve_with_fixNote_stores_breeder_changelog()
{
var client = _factory.CreateClient();
var create = await client.PostAsJsonAsync("/feedback", new { message = "Vater falsch.", context = "stammbaum", entityName = "Yuki" });
var id = JsonDocument.Parse(await create.Content.ReadAsStringAsync()).RootElement.GetProperty("id").GetString();
// Resolve the ticket together with a breeder-friendly fix note (changelog).
var resolve = await client.PutAsJsonAsync($"/feedback/{id}", new
{
status = "Resolved",
fixNote = "Die Mutter von Yuki war falsch — sie ist jetzt Izumi. Bitte den Stammbaum neu laden.",
});
Assert.Equal(HttpStatusCode.OK, resolve.StatusCode);
var dto = JsonDocument.Parse(await resolve.Content.ReadAsStringAsync()).RootElement;
Assert.Equal("Resolved", dto.GetProperty("status").GetString());
Assert.Equal("Die Mutter von Yuki war falsch — sie ist jetzt Izumi. Bitte den Stammbaum neu laden.",
dto.GetProperty("fixNote").GetString());
Assert.NotEqual(JsonValueKind.Null, dto.GetProperty("resolvedAt").ValueKind);
// The fix note survives a re-fetch via GET.
var listed = JsonDocument.Parse(await client.GetStringAsync("/feedback")).RootElement;
Assert.Contains(listed.EnumerateArray(),
f => f.GetProperty("id").GetString() == id
&& f.GetProperty("fixNote").GetString()!.StartsWith("Die Mutter von Yuki war falsch"));
}
[Fact]
public async Task Put_agentContext_round_trips_without_changing_status()
{
var client = _factory.CreateClient();
var create = await client.PostAsJsonAsync("/feedback", new { message = "Gewicht falsch.", context = "gerbil-detail" });
var id = JsonDocument.Parse(await create.Content.ReadAsStringAsync()).RootElement.GetProperty("id").GetString();
// Setting only the internal agent context must NOT change the lifecycle status.
var put = await client.PutAsJsonAsync($"/feedback/{id}", new
{
agentContext = "{\"rootCause\":\"rounding in WeightChart\",\"files\":[\"WeightChart.tsx\"],\"plan\":\"fix toFixed\"}",
});
Assert.Equal(HttpStatusCode.OK, put.StatusCode);
var dto = JsonDocument.Parse(await put.Content.ReadAsStringAsync()).RootElement;
Assert.Equal("Open", dto.GetProperty("status").GetString());
Assert.Equal("{\"rootCause\":\"rounding in WeightChart\",\"files\":[\"WeightChart.tsx\"],\"plan\":\"fix toFixed\"}",
dto.GetProperty("agentContext").GetString());
// It is returned by GET as well (for tooling) but the UI never renders it.
var listed = JsonDocument.Parse(await client.GetStringAsync("/feedback")).RootElement;
Assert.Contains(listed.EnumerateArray(),
f => f.GetProperty("id").GetString() == id
&& f.GetProperty("agentContext").GetString()!.Contains("rootCause"));
}
[Fact]
public async Task New_question_pushes_prior_QandA_into_thread()
{
var client = _factory.CreateClient();
var create = await client.PostAsJsonAsync("/feedback", new { message = "Wurf C unklar.", context = "litter-detail", entityName = "Wurf C" });
var id = JsonDocument.Parse(await create.Content.ReadAsStringAsync()).RootElement.GetProperty("id").GetString();
// Round 1: maintainer asks, breeder answers.
await client.PutAsJsonAsync($"/feedback/{id}", new { question = "Wie heißt die Mutter?" });
await client.PutAsJsonAsync($"/feedback/{id}", new { answer = "Die Mutter ist Luna." });
// Round 2: a NEW question is asked while the prior Q&A exists.
var ask2 = await client.PutAsJsonAsync($"/feedback/{id}", new { question = "Und wer ist der Vater?" });
Assert.Equal(HttpStatusCode.OK, ask2.StatusCode);
var dto = JsonDocument.Parse(await ask2.Content.ReadAsStringAsync()).RootElement;
// Current open exchange = the new question, fresh (no answer yet), status NeedsInfo.
Assert.Equal("NeedsInfo", dto.GetProperty("status").GetString());
Assert.Equal("Und wer ist der Vater?", dto.GetProperty("question").GetString());
Assert.Equal(JsonValueKind.Null, dto.GetProperty("answer").ValueKind);
Assert.Equal(JsonValueKind.Null, dto.GetProperty("answeredAt").ValueKind);
// The prior round was archived into the thread (oldest first): maintainer Q then breeder A.
var thread = dto.GetProperty("thread");
Assert.Equal(JsonValueKind.Array, thread.ValueKind);
Assert.Equal(2, thread.GetArrayLength());
Assert.Equal("maintainer", thread[0].GetProperty("role").GetString());
Assert.Equal("Wie heißt die Mutter?", thread[0].GetProperty("text").GetString());
Assert.Equal("breeder", thread[1].GetProperty("role").GetString());
Assert.Equal("Die Mutter ist Luna.", thread[1].GetProperty("text").GetString());
// Round 2 answered, then round 3 question → thread now holds 4 entries (two full rounds).
await client.PutAsJsonAsync($"/feedback/{id}", new { answer = "Der Vater ist Max." });
var ask3 = await client.PutAsJsonAsync($"/feedback/{id}", new { question = "Stimmt das Geburtsdatum?" });
var dto3 = JsonDocument.Parse(await ask3.Content.ReadAsStringAsync()).RootElement;
Assert.Equal(4, dto3.GetProperty("thread").GetArrayLength());
Assert.Equal("Stimmt das Geburtsdatum?", dto3.GetProperty("question").GetString());
}
[Fact]
public async Task Put_and_delete_unknown_id_return_404()
{
var client = _factory.CreateClient();
var missing = Guid.NewGuid();
Assert.Equal(HttpStatusCode.NotFound, (await client.PutAsJsonAsync($"/feedback/{missing}", new { message = "x" })).StatusCode);
Assert.Equal(HttpStatusCode.NotFound, (await client.DeleteAsync($"/feedback/{missing}")).StatusCode);
}
[Fact]
public async Task Post_feedback_rejects_empty_message()
{
var client = _factory.CreateClient();
var resp = await client.PostAsJsonAsync("/feedback", new { message = " ", context = "gerbil-detail" });
Assert.Equal(HttpStatusCode.BadRequest, resp.StatusCode);
}
[Fact]
public async Task Feedback_survives_ingest_wipe()
{
// Fresh in-memory DB seeded with a resolved import file (mirrors IngestResolvedServiceTests).
var dir = Path.Combine(Path.GetTempPath(), "feedback-ingest-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
try
{
var contactId = Guid.NewGuid();
var fatherId = Guid.NewGuid();
var motherId = Guid.NewGuid();
var litterId = Guid.NewGuid();
var data = new
{
Contacts = new[]
{
new { Id = contactId, Name = "Test Breeder", Email = "t@e.de", Phone = "", Address = "", Notes = (string?)null, IsBreeder = true, IsReceiver = false, NameSuffix = (string?)null, Provenance = (string?)null }
},
Litters = new[]
{
new { Id = litterId, Name = "Wurf A", Date = "2026-01-01", TotalBorn = 5, DeathsWithin8Weeks = 0, FatherId = fatherId, MotherId = motherId, ExpectedGoHomeDate = (string?)null, Notes = "", PairingCode = "PC01", ExternalRef = "ext-litter-1", LitterLetter = "A" }
},
Gerbils = new[]
{
Animal(fatherId, "Papa", "male", contactId),
Animal(motherId, "Mama", "female", contactId),
},
GerbilPhotos = Array.Empty<object>(),
};
File.WriteAllText(Path.Combine(dir, "resolved_import.json"), JsonSerializer.Serialize(data));
var opts = new DbContextOptionsBuilder<ApplicationContext>()
.UseInMemoryDatabase("feedback-ingest-" + Guid.NewGuid().ToString("N"))
.Options;
using var db = new ApplicationContext(opts);
db.Database.EnsureCreated();
// A feedback report referencing the gerbil + litter that the wipe will delete.
var feedbackId = Guid.NewGuid();
db.Feedback.Add(new Feedback
{
Id = feedbackId,
Message = "Bitte prüfen.",
Context = "gerbil-detail",
GerbilId = fatherId,
LitterId = litterId,
EntityName = "Papa",
Url = "http://localhost/rennmaeuse/papa",
CreatedAt = DateTimeOffset.UtcNow,
Status = "Answered",
ResolvedAt = null,
Question = "Welches Datum stimmt?",
Answer = "Der 2. Juni.",
AnsweredAt = DateTimeOffset.UtcNow,
FixNote = "Das Geburtsdatum von Papa wurde korrigiert.",
AgentContext = "{\"plan\":\"awaiting DOB confirmation\"}",
Thread = "[{\"role\":\"maintainer\",\"text\":\"Erste Frage?\",\"at\":\"2026-06-20T10:00:00Z\"},{\"role\":\"breeder\",\"text\":\"Erste Antwort.\",\"at\":\"2026-06-20T11:00:00Z\"}]",
});
// A contact-scoped feedback report — the ContactId is a loose (FK-free) id,
// so it must survive the contact-table wipe just like gerbil/litter ids.
var contactFeedbackId = Guid.NewGuid();
db.Feedback.Add(new Feedback
{
Id = contactFeedbackId,
Message = "Adresse stimmt nicht.",
Context = "contact-detail",
ContactId = contactId,
EntityName = "Test Breeder",
Url = "http://localhost/kontakte/test-breeder",
CreatedAt = DateTimeOffset.UtcNow,
});
await db.SaveChangesAsync();
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?> { { "Import:SourcePath", dir } })
.Build();
// Run the ingest wipe + reload.
var result = await new IngestResolvedService(db, config, null!).RunAsync();
Assert.Contains("Ingestion successful!", result);
// Gerbils/litters/contacts were wiped & re-created, but feedback is untouched.
var survivor = await db.Feedback.SingleAsync(f => f.Id == feedbackId);
Assert.Equal(fatherId, survivor.GerbilId); // loose id preserved even though the gerbil row was deleted/recreated
Assert.Equal(litterId, survivor.LitterId);
Assert.Equal("Papa", survivor.EntityName);
Assert.Equal("Answered", survivor.Status); // ticket status column survives the wipe
// The new question/answer columns survive the wipe too.
Assert.Equal("Welches Datum stimmt?", survivor.Question);
Assert.Equal("Der 2. Juni.", survivor.Answer);
Assert.NotNull(survivor.AnsweredAt);
// The new fix-note / agent-context / thread columns survive the wipe too.
Assert.Equal("Das Geburtsdatum von Papa wurde korrigiert.", survivor.FixNote);
Assert.Equal("{\"plan\":\"awaiting DOB confirmation\"}", survivor.AgentContext);
Assert.Contains("Erste Frage?", survivor.Thread);
// The contact-scoped report also survives the contacts wipe (loose ContactId).
var contactSurvivor = await db.Feedback.SingleAsync(f => f.Id == contactFeedbackId);
Assert.Equal(contactId, contactSurvivor.ContactId);
Assert.Equal("contact-detail", contactSurvivor.Context);
Assert.Equal("Test Breeder", contactSurvivor.EntityName);
Assert.Equal(2, await db.Feedback.CountAsync());
}
finally
{
try { Directory.Delete(dir, recursive: true); } catch { /* best effort */ }
}
}
private static object Animal(Guid id, string name, string gender, Guid contactId) => new
{
Id = id,
Name = name,
Gender = gender,
Status = "Breeding",
LitterId = (Guid?)null,
OriginContactId = contactId,
ReceiverContactId = (Guid?)null,
EnclosureId = (Guid?)null,
ColorVarietyId = new Guid("00000000-0000-0000-0000-000000000006"),
DateOfBirth = "2025-01-01",
DateOfDeath = (string?)null,
CauseOfDeath = (string?)null,
GoHomeDate = (string?)null,
Genotype = "aa CC DD EE GG PP spsp rere",
Notes = "",
ImportSource = "docx-export",
ExternalRef = "ext-" + name,
RawImportData = "{}",
OriginBreeder = "Test Zucht",
NameSearch = name.ToLowerInvariant(),
CharacterTraits = Array.Empty<string>(),
CharacterNote = (string?)null,
IsDeaf = false,
IsResident = true,
};
}

View File

@@ -0,0 +1,83 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.RegularExpressions;
using GerbilManagerWebAPI.Models;
using Microsoft.Extensions.DependencyInjection;
namespace GerbilManager.Tests;
/// <summary>profilePhotoUrl: computed field on GerbilDto — first photo by sortOrder, or null.</summary>
public class GerbilProfilePhotoTests : IClassFixture<ApiFactory>
{
private readonly HttpClient _client;
private readonly ApiFactory _factory;
public GerbilProfilePhotoTests(ApiFactory factory)
{
_factory = factory;
_client = factory.CreateClient();
}
private static Guid ExtractId(string json) =>
Guid.Parse(Regex.Match(json, "\"id\":\"([^\"]+)\"").Groups[1].Value);
private static string? GetStr(JsonElement el, string prop) =>
el.TryGetProperty(prop, out var v) && v.ValueKind == JsonValueKind.String
? v.GetString() : null;
private async Task<Guid> CreateGerbil(string name)
{
var resp = await _client.PostAsync("/gerbils", JsonContent.Create(new { name, gender = "female" }));
Assert.Equal(HttpStatusCode.Created, resp.StatusCode);
return ExtractId(await resp.Content.ReadAsStringAsync());
}
private void InsertPhotos(Guid gerbilId, params (string fileName, int sortOrder)[] photos)
{
using var scope = _factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationContext>();
foreach (var (fn, so) in photos)
db.GerbilPhotos.Add(new GerbilPhoto
{
Id = Guid.NewGuid(), GerbilId = gerbilId,
FileName = fn, SortOrder = so, CreatedAt = DateTimeOffset.UtcNow,
});
db.SaveChanges();
}
[Fact]
public async Task GetById_without_photos_returns_null_profilePhotoUrl()
{
var id = await CreateGerbil("NoPhoto");
var json = await _client.GetStringAsync($"/gerbils/{id}");
var el = JsonDocument.Parse(json).RootElement;
Assert.True(el.TryGetProperty("profilePhotoUrl", out var v));
Assert.Equal(JsonValueKind.Null, v.ValueKind);
}
[Fact]
public async Task GetById_with_photos_returns_lowest_sortOrder_url()
{
var id = await CreateGerbil("PhotoGerbil");
InsertPhotos(id, ("second.jpg", 1), ("first.jpg", 0));
var json = await _client.GetStringAsync($"/gerbils/{id}");
var el = JsonDocument.Parse(json).RootElement;
Assert.Equal("/photos/files/first.jpg", GetStr(el, "profilePhotoUrl"));
}
[Fact]
public async Task GetList_returns_profilePhotoUrl_without_n_plus_1()
{
var id = await CreateGerbil("ListPhoto");
InsertPhotos(id, ("list-photo.jpg", 0));
var json = await _client.GetStringAsync("/gerbils");
var root = JsonDocument.Parse(json).RootElement;
var items = root.GetProperty("items").EnumerateArray().ToList();
var gerbil = items.FirstOrDefault(x => GetStr(x, "id") == id.ToString());
Assert.NotEqual(default, gerbil);
Assert.Equal("/photos/files/list-photo.jpg", GetStr(gerbil, "profilePhotoUrl"));
}
}

View File

@@ -0,0 +1,58 @@
using System.Net;
using System.Net.Http.Json;
using GerbilManagerWebAPI.Models;
namespace GerbilManager.Tests;
/// <summary>SEARCH-1: separator-insensitive name search + OriginBreeder (Herkunft) filter.</summary>
public class GerbilSearchTests : IClassFixture<ApiFactory>
{
private readonly HttpClient _client;
public GerbilSearchTests(ApiFactory factory) => _client = factory.CreateClient();
private static HttpContent Gerbil(string name, string? originBreeder = null) =>
JsonContent.Create(new
{
name,
gender = "female",
originBreeder,
});
[Theory]
[InlineData("Clan-Kleine-Chaoten", "clankleinechaoten")]
[InlineData("Clan Kleine Chaoten", "clankleinechaoten")]
[InlineData("v.d. Kleinen_Chaoten", "vdkleinenchaoten")]
public void Normalize_strips_separators_and_lowercases(string input, string expected) =>
Assert.Equal(expected, GerbilSearch.Normalize(input));
[Fact]
public async Task NameSearch_filter_matches_across_separators()
{
var create = await _client.PostAsync("/gerbils", Gerbil("Clan-Kleine-Chaoten"));
Assert.Equal(HttpStatusCode.Created, create.StatusCode);
// Gridify contains is "=*value" (no trailing '*', per the main hotfix 0ee2b53).
// The client normalizes the user's term the same way the column is normalized.
var json = await _client.GetStringAsync("/gerbils?filter=nameSearch=*clankleinechaoten");
Assert.Contains("Clan-Kleine-Chaoten", json);
// a term that doesn't normalize-match must NOT return it
var miss = await _client.GetStringAsync("/gerbils?filter=nameSearch=*completelyother");
Assert.DoesNotContain("Clan-Kleine-Chaoten", miss);
}
[Fact]
public async Task OriginBreeder_is_filterable_and_listed_in_breeders_endpoint()
{
await _client.PostAsync("/gerbils", Gerbil("Herkunftstier", originBreeder: "Zucht der kleinen Chaoten"));
// distinct-values dropdown source
var breeders = await _client.GetStringAsync("/gerbils/breeders");
Assert.Contains("Zucht der kleinen Chaoten", breeders);
// Gridify filter on the field
var filtered = await _client.GetStringAsync("/gerbils?filter=originBreeder==Zucht der kleinen Chaoten");
Assert.Contains("Herkunftstier", filtered);
}
}

View File

@@ -0,0 +1,122 @@
using GerbilManagerWebAPI.Models;
using GerbilManagerWebAPI.Services;
namespace GerbilManager.Tests;
/// <summary>STATUS-MODEL: GerbilStatusService.Derive() precedence rules.</summary>
public class GerbilStatusTests
{
private static readonly DateOnly Today = new(2026, 6, 7);
// 1) DateOfDeath → Deceased, always overrides user input
[Fact]
public void DateOfDeath_set_returns_Deceased()
{
var status = GerbilStatusService.Derive(
GerbilStatus.Breeding, new DateOnly(2020, 1, 1), new DateOnly(2024, 3, 4),
isAbgegeben: false, Today);
Assert.Equal(GerbilStatus.Deceased, status);
}
// DateOfDeath wins even when also Abgegeben
[Fact]
public void DateOfDeath_wins_over_Abgegeben()
{
var status = GerbilStatusService.Derive(
GerbilStatus.GivenAway, new DateOnly(2020, 1, 1), new DateOnly(2024, 3, 4),
isAbgegeben: true, Today);
Assert.Equal(GerbilStatus.Deceased, status);
}
// 2) Abgegeben without death date → GivenAway
[Fact]
public void ReceiverContact_set_returns_GivenAway()
{
var status = GerbilStatusService.Derive(
GerbilStatus.Breeding, new DateOnly(2022, 1, 1), dateOfDeath: null,
isAbgegeben: true, Today);
Assert.Equal(GerbilStatus.GivenAway, status);
}
// 3) Age > 6y, no death, not abgegeben → Deceased (presumed)
[Fact]
public void OlderThan6y_without_death_returns_Deceased()
{
var dob = Today.AddYears(-GerbilStatusService.MaxAgeYears).AddDays(-1); // 1 day past threshold
var status = GerbilStatusService.Derive(
GerbilStatus.Breeding, dob, dateOfDeath: null, isAbgegeben: false, Today);
Assert.Equal(GerbilStatus.Deceased, status);
}
// Exactly 6 years old is NOT presumed dead (threshold is strictly >)
[Fact]
public void ExactlyMaxAge_is_not_Deceased()
{
var dob = Today.AddYears(-GerbilStatusService.MaxAgeYears); // exactly 6y today
var status = GerbilStatusService.Derive(
GerbilStatus.Breeding, dob, dateOfDeath: null, isAbgegeben: false, Today);
// today >= dob.AddYears(6) → exactly equal → IS presumed dead
// (threshold = "older than" so >= means Deceased)
Assert.Equal(GerbilStatus.Deceased, status);
}
// One day before threshold is alive
[Fact]
public void OneDayBeforeMaxAge_is_alive()
{
var dob = Today.AddYears(-GerbilStatusService.MaxAgeYears).AddDays(1);
var status = GerbilStatusService.Derive(
GerbilStatus.Breeding, dob, dateOfDeath: null, isAbgegeben: false, Today);
Assert.Equal(GerbilStatus.Breeding, status);
}
// 3a) Age > 6y but Abgegeben → stays GivenAway (not Deceased)
[Fact]
public void OlderThan6y_but_Abgegeben_stays_GivenAway()
{
var dob = Today.AddYears(-7);
var status = GerbilStatusService.Derive(
GerbilStatus.GivenAway, dob, dateOfDeath: null, isAbgegeben: true, Today);
Assert.Equal(GerbilStatus.GivenAway, status);
}
// 4) Default → Breeding
[Fact]
public void No_special_condition_returns_Breeding()
{
var status = GerbilStatusService.Derive(
GerbilStatus.Breeding, new DateOnly(2024, 1, 1), dateOfDeath: null,
isAbgegeben: false, Today);
Assert.Equal(GerbilStatus.Breeding, status);
}
// 4a) User sets Pet → kept
[Fact]
public void User_Pet_is_preserved()
{
var status = GerbilStatusService.Derive(
GerbilStatus.Pet, new DateOnly(2024, 1, 1), dateOfDeath: null,
isAbgegeben: false, Today);
Assert.Equal(GerbilStatus.Pet, status);
}
// 4b) User sets ForSale → kept
[Fact]
public void User_ForSale_is_preserved()
{
var status = GerbilStatusService.Derive(
GerbilStatus.ForSale, new DateOnly(2024, 1, 1), dateOfDeath: null,
isAbgegeben: false, Today);
Assert.Equal(GerbilStatus.ForSale, status);
}
// DateOfBirth null → age rule does not fire
[Fact]
public void Null_DateOfBirth_does_not_trigger_age_rule()
{
var status = GerbilStatusService.Derive(
GerbilStatus.Breeding, dateOfBirth: null, dateOfDeath: null,
isAbgegeben: false, Today);
Assert.Equal(GerbilStatus.Breeding, status);
}
}

View File

@@ -0,0 +1,343 @@
using GerbilManagerWebAPI.Import;
using GerbilManagerWebAPI.Models;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
namespace GerbilManager.Tests
{
/// <summary>
/// FEAT-8d-CREATE / FIX-8D-DEDUP: docx importer CREATE path tests.
/// Uses SQLite (not InMemory) so FK + unique-index constraints are enforced —
/// this is the only reliable way to catch duplicate-ExternalRef crashes.
/// </summary>
public class ImportDocxServiceTests : IDisposable
{
private readonly string _dir;
public ImportDocxServiceTests()
{
_dir = Path.Combine(Path.GetTempPath(), "feat8d-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_dir);
}
public void Dispose()
{
try { Directory.Delete(_dir, recursive: true); } catch { }
}
// One open connection keeps the :memory: SQLite DB alive across calls.
private (ApplicationContext db, SqliteConnection conn) NewSqliteDb()
{
var conn = new SqliteConnection("DataSource=:memory:");
conn.Open();
var opts = new DbContextOptionsBuilder<ApplicationContext>().UseSqlite(conn).Options;
var db = new ApplicationContext(opts);
db.Database.EnsureCreated(); // schema WITH unique index on ExternalRef
return (db, conn);
}
private void WriteLitters(object litters) =>
File.WriteAllText(Path.Combine(_dir, "docx_litters.json"),
System.Text.Json.JsonSerializer.Serialize(litters));
private void WriteAnimals(object animals) =>
File.WriteAllText(Path.Combine(_dir, "docx_animals.json"),
System.Text.Json.JsonSerializer.Serialize(animals));
// ── Test 1: dry-run shows correct counts without writing ─────────────────
[Fact]
public async Task DryRun_counts_new_animal_without_writing()
{
var (db, conn) = NewSqliteDb();
await using (conn)
await using (db)
{
// Litter in DB — date-only lookup (±5 days, exactly one candidate)
var litter = new Litter
{
Id = Guid.NewGuid(),
Name = "Testwurf",
Date = new DateOnly(2023, 5, 1),
};
db.Litters.Add(litter);
await db.SaveChangesAsync();
WriteLitters(Array.Empty<object>());
WriteAnimals(new[]
{
new { wsCode = "4/4", litterDob = "01.05.2023", name = "Pepper", gender = "female",
owner = "Max Mustermann", abgabeDate = "01.07.2023",
deathDate = "", deathCause = "", farbschlag = "" }
});
var report = await new ImportDocxService(db, _dir).RunAsync(execute: false);
Assert.False(report.Executed);
Assert.Equal(1, report.Created);
Assert.Equal(1, report.LitterLinked); // date-only match finds the one litter
Assert.Equal(1, report.GoHomeFilled);
Assert.Equal(0, await db.Gerbils.CountAsync()); // nothing written
Assert.Equal(0, await db.Contacts.CountAsync()); // nothing written
}
}
// ── Test 2: execute creates animal with all fields + FK constraints ───────
[Fact]
public async Task Execute_creates_animal_with_litter_contact_and_goHomeDate()
{
var (db, conn) = NewSqliteDb();
await using (conn)
await using (db)
{
var litter = new Litter
{
Id = Guid.NewGuid(),
Name = "Testwurf",
Date = new DateOnly(2023, 5, 1),
};
db.Litters.Add(litter);
await db.SaveChangesAsync();
WriteLitters(Array.Empty<object>());
WriteAnimals(new[]
{
new { wsCode = "4/4", litterDob = "01.05.2023", name = "Pepper", gender = "female",
owner = "Max Mustermann", abgabeDate = "01.07.2023",
deathDate = "", deathCause = "", farbschlag = "" }
});
var report = await new ImportDocxService(db, _dir).RunAsync(execute: true);
Assert.True(report.Executed);
Assert.Equal(1, report.Created);
Assert.Equal(1, report.ContactsCreated);
var gerbil = await db.Gerbils.SingleAsync();
Assert.Equal("Pepper", gerbil.Name);
Assert.Equal(new DateOnly(2023, 5, 1), gerbil.DateOfBirth);
Assert.Equal(Gender.female, gerbil.Gender);
Assert.Equal(GerbilStatus.GivenAway, gerbil.Status);
Assert.Equal(litter.Id, gerbil.LitterId); // date-only link worked
Assert.Equal(new DateOnly(2023, 7, 1), gerbil.GoHomeDate);
Assert.Equal("Zucht der kleinen Chaoten", gerbil.OriginBreeder);
Assert.False(gerbil.IsResident);
Assert.Equal("docx", gerbil.ImportSource);
Assert.StartsWith("docx-", gerbil.ExternalRef);
var contact = await db.Contacts.SingleAsync();
Assert.Equal("Max Mustermann", contact.Name);
Assert.Equal(contact.Id, gerbil.ReceiverContactId);
}
}
// ── Test 3: idempotency — second run creates zero ────────────────────────
[Fact]
public async Task Execute_is_idempotent_second_run_creates_zero()
{
var (db, conn) = NewSqliteDb();
await using (conn)
await using (db)
{
WriteLitters(Array.Empty<object>());
WriteAnimals(new[]
{
new { wsCode = "2/3", litterDob = "15.03.2023", name = "Flash", gender = "male",
owner = "", abgabeDate = "01.05.2023",
deathDate = "", deathCause = "", farbschlag = "" }
});
var first = await new ImportDocxService(db, _dir).RunAsync(execute: true);
Assert.Equal(1, first.Created);
var second = await new ImportDocxService(db, _dir).RunAsync(execute: true);
Assert.Equal(0, second.Created); // ExternalRef path, no dupe
Assert.Equal(1, await db.Gerbils.CountAsync()); // exactly one row
}
}
// ── Test 4: existing main-import animal → enrich only, no duplicate ──────
[Fact]
public async Task Execute_enriches_existing_animal_does_not_duplicate()
{
var (db, conn) = NewSqliteDb();
await using (conn)
await using (db)
{
// Animal already in DB (from main import, ExternalRef ≠ "docx-…")
var existing = new Gerbil
{
Id = Guid.NewGuid(),
Name = "Eddie",
DateOfBirth = new DateOnly(2022, 8, 10),
Gender = Gender.male,
ExternalRef = "main-eddie-xyz", // NOT a "docx-" ref
IsResident = false,
};
db.Gerbils.Add(existing);
await db.SaveChangesAsync();
WriteLitters(Array.Empty<object>());
WriteAnimals(new[]
{
// Same name+dob → enrich, not create
new { wsCode = "", litterDob = "10.08.2022", name = "Eddie", gender = "male",
owner = "Anna Beispiel", abgabeDate = "01.10.2022",
deathDate = "", deathCause = "", farbschlag = "" }
});
var report = await new ImportDocxService(db, _dir).RunAsync(execute: true);
Assert.Equal(0, report.Created);
Assert.Equal(1, await db.Gerbils.CountAsync()); // still exactly one
// GoHomeDate was enriched
var updated = await db.Gerbils.SingleAsync();
Assert.Equal(new DateOnly(2022, 10, 1), updated.GoHomeDate);
}
}
// ── Test 5: Deceased status when deathDate set ───────────────────────────
[Fact]
public async Task Execute_sets_Deceased_status_when_deathDate_provided()
{
var (db, conn) = NewSqliteDb();
await using (conn)
await using (db)
{
WriteLitters(Array.Empty<object>());
WriteAnimals(new[]
{
new { wsCode = "1/5", litterDob = "01.01.2022", name = "Ghost", gender = "male",
owner = "", abgabeDate = "",
deathDate = "15.06.2022", deathCause = "Tumor", farbschlag = "" }
});
await new ImportDocxService(db, _dir).RunAsync(execute: true);
var gerbil = await db.Gerbils.SingleAsync();
Assert.Equal(GerbilStatus.Deceased, gerbil.Status);
Assert.Equal(new DateOnly(2022, 6, 15), gerbil.DateOfDeath);
Assert.Equal("Tumor", gerbil.CauseOfDeath);
}
}
// ── Test 7: P0 REGRESSION — execute works under a retrying execution strategy ──
[Fact]
public async Task Execute_works_under_retrying_execution_strategy()
{
// Regression: NpgsqlRetryingExecutionStrategy (MaxRetryCount>0) calls
// OnFirstExecution() at the start of ExecuteAsync, which throws
// InvalidOperationException when it detects a user-initiated transaction
// that was NOT opened through the strategy. This test wires the same check
// (via FakeRetryingStrategy, MaxRetryCount=1) so the bug would surface in CI
// without a live Npgsql instance.
//
// With the BUG (direct BeginTransactionAsync before strategy.ExecuteAsync):
// → OnFirstExecution sees active user tx → InvalidOperationException
// With the FIX (BeginTransactionAsync inside strategy.ExecuteAsync lambda):
// → OnFirstExecution: no tx yet → OK
var conn = new SqliteConnection("DataSource=:memory:");
conn.Open();
var opts = new DbContextOptionsBuilder<ApplicationContext>()
.UseSqlite(conn)
.ReplaceService<IExecutionStrategyFactory, FakeRetryingStrategyFactory>()
.Options;
var db = new ApplicationContext(opts);
db.Database.EnsureCreated();
await using (conn)
await using (db)
{
WriteLitters(Array.Empty<object>());
WriteAnimals(new[]
{
new { wsCode = "3/3", litterDob = "01.01.2023", name = "Pixie", gender = "female",
owner = "Retry Adopter", abgabeDate = "01.03.2023",
deathDate = "", deathCause = "", farbschlag = "" }
});
// Must NOT throw InvalidOperationException (user-initiated tx rejected)
var report = await new ImportDocxService(db, _dir).RunAsync(execute: true);
Assert.True(report.Executed);
Assert.Equal(1, report.Created);
Assert.Equal(1, await db.Gerbils.CountAsync());
Assert.Equal(1, await db.Contacts.CountAsync());
}
}
// ── Test 6: P0 REGRESSION — same-name siblings get distinct ExternalRefs ─
[Fact]
public async Task Execute_same_name_siblings_created_with_distinct_ExternalRefs()
{
// P0 regression: two animals in the same litter with the same normalized name
// previously caused duplicate ExternalRef → Npgsql/SQLite 23505 unique-key crash.
// Fix: ordinal disambiguation (-2) ensures uniqueness within the batch.
// The unique index on IX_Gerbils_ExternalRef (via EnsureCreated on SQLite) makes
// this test an authoritative regression gate.
var (db, conn) = NewSqliteDb();
await using (conn)
await using (db)
{
WriteLitters(Array.Empty<object>());
WriteAnimals(new[]
{
new { wsCode = "4/4", litterDob = "10.06.2022", name = "Mochi", gender = "female",
owner = "Eva Müller", abgabeDate = "10.08.2022",
deathDate = "", deathCause = "", farbschlag = "" },
// Identical name+wsCode+litterDob → base ExternalRef collision
new { wsCode = "4/4", litterDob = "10.06.2022", name = "Mochi", gender = "female",
owner = "Lena Braun", abgabeDate = "11.08.2022",
deathDate = "", deathCause = "", farbschlag = "" },
});
// Must NOT throw unique-key violation
var report = await new ImportDocxService(db, _dir).RunAsync(execute: true);
Assert.Equal(2, report.Created);
Assert.Equal(2, await db.Gerbils.CountAsync());
var refs = (await db.Gerbils.Select(g => g.ExternalRef!).ToListAsync()).OrderBy(r => r).ToList();
// Both start with the docx- prefix
Assert.All(refs, r => Assert.StartsWith("docx-", r));
// Must be distinct (unique index enforces this in SQLite)
Assert.Equal(2, refs.Distinct().Count());
// Second occurrence gets the -2 suffix
Assert.Single(refs, r => r.EndsWith("-2"));
// Idempotent re-run: zero new, still 2 in DB
var second = await new ImportDocxService(db, _dir).RunAsync(execute: true);
Assert.Equal(0, second.Created);
Assert.Equal(2, await db.Gerbils.CountAsync());
}
}
}
// ── Helpers for Test 7 ────────────────────────────────────────────────────────
/// <summary>
/// Execution strategy with MaxRetryCount=1 so that EF Core's base
/// OnFirstExecution() throws when it detects a user-initiated transaction
/// that was not opened through CreateExecutionStrategy().ExecuteAsync().
/// ShouldRetryOn=false → no actual retry; the check alone is what we need.
/// </summary>
internal sealed class FakeRetryingStrategy(ExecutionStrategyDependencies deps)
: ExecutionStrategy(deps, maxRetryCount: 1, maxRetryDelay: TimeSpan.Zero)
{
protected override bool ShouldRetryOn(Exception exception) => false;
}
internal sealed class FakeRetryingStrategyFactory(ExecutionStrategyDependencies deps)
: IExecutionStrategyFactory
{
public IExecutionStrategy Create() => new FakeRetryingStrategy(deps);
}
}

View File

@@ -261,6 +261,54 @@ namespace GerbilManager.Tests
finally { try { Directory.Delete(dir, recursive: true); } catch { } }
}
[Fact]
public async Task Execute_circular_gerbil_litter_dependency_does_not_throw()
{
// Regression for "Unable to save changes because a circular dependency was detected":
// Gerbil [Added] ← FK{MotherId} Litter [Added] ← FK{LitterId} Gerbil [Added].
// Triggered when a gerbil is both parent (in one synth litter) and offspring
// (LitterId → another synth litter) in the SAME SaveChanges batch — forms a cycle EF
// topo-sort cannot resolve. This test encodes the minimal reproducer: A's mother is B,
// B's mother is A (artificial genealogical cycle, but triggers the EF cycle reliably).
var dir = Path.Combine(Path.GetTempPath(), "cycle-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
using var conn = new SqliteConnection("DataSource=:memory:");
conn.Open();
try
{
File.WriteAllText(Path.Combine(dir, "litters.json"), "[]");
File.WriteAllText(Path.Combine(dir, "animals.json"), """
[
{"id":"alpha","name":"Alpha","dob":"01.01.2020","death":"","farbschlag":"",
"genotype":{"mapped8locus":{},"rawGenotype":"","unmappedTokens":[]},"conflict":false,
"parentRefs":[{"name":"Beta","dob":"01.01.2019","roleGuess":"mother","method":"chart-position","confidence":"medium"}]},
{"id":"beta","name":"Beta","dob":"01.01.2019","death":"","farbschlag":"",
"genotype":{"mapped8locus":{},"rawGenotype":"","unmappedTokens":[]},"conflict":false,
"parentRefs":[{"name":"Alpha","dob":"01.01.2020","roleGuess":"mother","method":"chart-position","confidence":"medium"}]}
]
""");
var opts = new DbContextOptionsBuilder<ApplicationContext>().UseSqlite(conn).Options;
using var db = new ApplicationContext(opts);
await db.Database.EnsureCreatedAsync();
// must NOT throw InvalidOperationException (circular dependency)
var report = await new ImportService(db, dir, dir).RunAsync(execute: true);
Assert.Equal(2, await db.Gerbils.CountAsync());
var alpha = await db.Gerbils.SingleAsync(g => g.ExternalRef == "alpha");
var beta = await db.Gerbils.SingleAsync(g => g.ExternalRef == "beta");
// both should be litter-linked
Assert.NotNull(alpha.LitterId);
Assert.NotNull(beta.LitterId);
// deferred FK update must have set the litter parents correctly
var alphaLitter = await db.Litters.SingleAsync(l => l.Id == alpha.LitterId);
Assert.Equal(beta.Id, alphaLitter.MotherId);
var betaLitter = await db.Litters.SingleAsync(l => l.Id == beta.LitterId);
Assert.Equal(alpha.Id, betaLitter.MotherId);
}
finally { try { Directory.Delete(dir, recursive: true); } catch { } }
}
[Fact]
public async Task Derived_litter_with_quarantined_parent_leaves_FK_null_no_throw()
{
@@ -573,27 +621,32 @@ namespace GerbilManager.Tests
[Fact]
public void SeedGen3g_existing_varieties_preserve_id_name_binding()
{
// SEED-HELL bounce regression: the 61 existing entries must NOT change their
// Id->Name binding after GEN-3g. The 5 new entries (IDs 62-66) are appended.
// A hand-assigned Gerbil.ColorVarietyId pointing to "CP-Fuchs" (ID 58) must
// still map to CP-Fuchs after the migration runs (append-only, no rename-shift).
using var db = NewDb(); // EnsureCreated applies HasData including new 66-entry seed
// CATALOG-RESEED regression: ID->Name bindings for all 66 existing entries must be
// stable. 4 new Dilute Fuchs varieties appended (IDs 67-70). CP-Fuchs (ID 58) and
// the CP-*-Hell entries (IDs 62-66) must survive with their original names intact.
using var db = NewDb(); // EnsureCreated applies HasData including 70-entry seed
// ID 58 (index 57 in old catalog, 0-based) = CP-Fuchs — must still be CP-Fuchs
// ID 58 = CP-Fuchs — must still be CP-Fuchs (no rename-shift from new entries)
var cpFuchsId = new Guid("00000000-0000-0000-0000-000000000058");
var cpFuchs = db.ColorVarieties.Find(cpFuchsId);
Assert.NotNull(cpFuchs);
Assert.Equal("CP-Fuchs", cpFuchs!.Name);
// New entries at IDs 62-66 exist with correct names
// Existing CP-*-Hell entries (IDs 62-66) unchanged
Assert.Equal("CP-Agouti-Hell", db.ColorVarieties.Find(new Guid("00000000-0000-0000-0000-000000000062"))!.Name);
Assert.Equal("CP-Silberagouti-Hell", db.ColorVarieties.Find(new Guid("00000000-0000-0000-0000-000000000063"))!.Name);
Assert.Equal("CP-Algierfuchs-Hell", db.ColorVarieties.Find(new Guid("00000000-0000-0000-0000-000000000064"))!.Name);
Assert.Equal("CP-Polarfuchs-Hell", db.ColorVarieties.Find(new Guid("00000000-0000-0000-0000-000000000065"))!.Name);
Assert.Equal("CP-Orangeschimmel-Hell", db.ColorVarieties.Find(new Guid("00000000-0000-0000-0000-000000000066"))!.Name);
// Total count is exactly 66
Assert.Equal(66, db.ColorVarieties.Count());
// 4 new Dilute Fuchs varieties appended (IDs 67-70)
Assert.Equal("Dilute Algierfuchs", db.ColorVarieties.Find(new Guid("00000000-0000-0000-0000-000000000067"))!.Name);
Assert.Equal("Dilute Goldfuchs", db.ColorVarieties.Find(new Guid("00000000-0000-0000-0000-000000000068"))!.Name);
Assert.Equal("Dilute Rotfuchs", db.ColorVarieties.Find(new Guid("00000000-0000-0000-0000-000000000069"))!.Name);
Assert.Equal("Dilute Polarfuchs", db.ColorVarieties.Find(new Guid("00000000-0000-0000-0000-000000000070"))!.Name);
// Total count is exactly 70
Assert.Equal(70, db.ColorVarieties.Count());
}
[Theory]

View File

@@ -0,0 +1,261 @@
using GerbilManagerWebAPI.Import;
using GerbilManagerWebAPI.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System.Text.Json;
namespace GerbilManager.Tests
{
public class IngestResolvedServiceTests : IDisposable
{
private readonly string _dir;
private readonly string _resolvedJsonPath;
private Guid ContactId { get; set; }
private Guid FatherId { get; set; }
private Guid ContractId { get; set; }
private Guid UnknownGerbilId { get; set; }
public IngestResolvedServiceTests()
{
_dir = Path.Combine(Path.GetTempPath(), "ingest-resolved-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_dir);
_resolvedJsonPath = Path.Combine(_dir, "resolved_import.json");
var contactId = Guid.NewGuid();
var fatherId = Guid.NewGuid();
var motherId = Guid.NewGuid();
var litterId = Guid.NewGuid();
var photoId = Guid.NewGuid();
ContactId = contactId;
FatherId = fatherId;
ContractId = Guid.NewGuid();
UnknownGerbilId = Guid.NewGuid();
var data = new
{
Contacts = new[]
{
new
{
Id = contactId,
Name = "Test Breeder",
ZuchtName = "Test Zucht",
City = "Test City",
Email = "test@example.com",
Homepage = "",
Phone = "",
Address = "",
Provenance = (string?)"{\"sourceFiles\":[\"Stammbaum\"],\"mergedRecordCount\":1,\"notes\":[\"als Züchter erkannt\"]}"
}
},
Litters = new[]
{
new
{
Id = litterId,
Name = "Wurf A",
Date = "2026-01-01",
TotalBorn = 5,
DeathsWithin8Weeks = 0,
FatherId = fatherId,
MotherId = motherId,
ExpectedGoHomeDate = (string?)null,
Notes = "Test litter notes",
PairingCode = "PC01",
ExternalRef = "ext-litter-1",
LitterLetter = "A",
Provenance = (string?)"{\"sourceFiles\":[\"Wurfchronik-Detail.docx\"],\"mergedRecordCount\":1,\"fromWurfchronik\":true,\"notes\":[\"aus Wurfchronik\"]}"
}
},
Gerbils = new[]
{
new
{
Id = fatherId,
Name = "Papa",
Gender = "male",
Status = "Breeding",
LitterId = (Guid?)null,
OriginContactId = contactId,
ReceiverContactId = (Guid?)null,
EnclosureId = (Guid?)null,
ColorVarietyId = new Guid("00000000-0000-0000-0000-000000000006"), // Schwarz
DateOfBirth = "2025-01-01",
DateOfDeath = (string?)null,
CauseOfDeath = (string?)null,
GoHomeDate = (string?)null,
Genotype = "aa CC DD EE GG PP spsp rere",
Notes = "",
ImportSource = "docx-export",
ExternalRef = "ext-papa",
RawImportData = "{}",
OriginBreeder = "Test Zucht",
NameSearch = "papa",
CharacterTraits = new string[] {},
CharacterNote = (string?)null,
IsDeaf = false,
IsResident = true,
Provenance = (string?)"{\"sourceFiles\":[\"Stammbaum von Papa.xlsx\",\"Wurfchronik-Detail.docx\"],\"mergedRecordCount\":2,\"fromWurfchronik\":true,\"notes\":[\"aus 2 Datensätzen zusammengeführt\"],\"history\":[\"In \\u201eStammbaum von Papa.xlsx\\u201c gefunden.\",\"Genotyp aus \\u201eWurfchronik-Detail.docx\\u201c.\"]}"
},
new
{
Id = motherId,
Name = "Mama",
Gender = "female",
Status = "Breeding",
LitterId = (Guid?)null,
OriginContactId = contactId,
ReceiverContactId = (Guid?)null,
EnclosureId = (Guid?)null,
ColorVarietyId = new Guid("00000000-0000-0000-0000-000000000006"), // Schwarz
DateOfBirth = "2025-01-01",
DateOfDeath = (string?)null,
CauseOfDeath = (string?)null,
GoHomeDate = (string?)null,
Genotype = "aa CC DD EE GG PP spsp rere",
Notes = "",
ImportSource = "docx-export",
ExternalRef = "ext-mama",
RawImportData = "{}",
OriginBreeder = "Test Zucht",
NameSearch = "mama",
CharacterTraits = new string[] {},
CharacterNote = (string?)null,
IsDeaf = false,
IsResident = true,
Provenance = (string?)null
}
},
GerbilPhotos = new[]
{
new
{
Id = photoId,
GerbilId = fatherId,
FileName = "photo1.jpg",
SortOrder = 0
}
},
SaleContracts = new[]
{
new
{
Id = ContractId,
ContactId = contactId,
Price = 35.0m,
HandoverDate = "2023-09-29",
ContractDate = "2023-09-29",
FileName = "Zucht der kleinen Chaoten _ (Papa) - Test Breeder_.docx",
// One known animal + one unknown id (must be skipped defensively).
Animals = new[] { fatherId, UnknownGerbilId }
}
}
};
File.WriteAllText(_resolvedJsonPath, JsonSerializer.Serialize(data));
}
public void Dispose()
{
try { Directory.Delete(_dir, recursive: true); } catch { }
}
private ApplicationContext NewDb()
{
var opts = new DbContextOptionsBuilder<ApplicationContext>()
.UseInMemoryDatabase("ingest-resolved-" + Guid.NewGuid().ToString("N"))
.Options;
var db = new ApplicationContext(opts);
db.Database.EnsureCreated();
return db;
}
[Fact]
public async Task IngestResolved_loads_data_and_resolves_all_relations()
{
using var db = NewDb();
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
{ "Import:SourcePath", _dir }
})
.Build();
var service = new IngestResolvedService(db, config, null!);
var result = await service.RunAsync();
Assert.Contains("Ingestion successful!", result);
// Verify counts
Assert.Equal(1, await db.Contacts.CountAsync());
Assert.Equal(1, await db.Litters.CountAsync());
Assert.Equal(2, await db.Gerbils.CountAsync());
Assert.Equal(1, await db.GerbilPhotos.CountAsync());
// Verify relations
var litter = await db.Litters.SingleAsync();
var father = await db.Gerbils.SingleAsync(g => g.Name == "Papa");
var mother = await db.Gerbils.SingleAsync(g => g.Name == "Mama");
var photo = await db.GerbilPhotos.SingleAsync();
Assert.Equal(father.Id, litter.FatherId);
Assert.Equal(mother.Id, litter.MotherId);
Assert.Equal(father.Id, photo.GerbilId);
Assert.Equal(father.OriginContactId, mother.OriginContactId);
// Provenance round-trips verbatim through ingest (and stays null when absent).
Assert.NotNull(father.Provenance);
Assert.Contains("Stammbaum von Papa.xlsx", father.Provenance);
Assert.Contains("mergedRecordCount", father.Provenance);
// The chronological, file-attributed history survives ingest verbatim
// (stored as opaque JSON on the text column — no schema for it).
Assert.Contains("history", father.Provenance);
Assert.Contains("Genotyp aus", father.Provenance);
Assert.Null(mother.Provenance);
// Contact + litter provenance also round-trips through the ingest.
var contact = await db.Contacts.SingleAsync();
Assert.NotNull(contact.Provenance);
Assert.Contains("als Züchter erkannt", contact.Provenance);
Assert.NotNull(litter.Provenance);
Assert.Contains("aus Wurfchronik", litter.Provenance);
Assert.Contains("fromWurfchronik", litter.Provenance);
// SaleContracts are created from the payload, and animal links to
// unknown gerbils are skipped defensively (only the known father links).
Assert.Equal(1, await db.SaleContracts.CountAsync());
var contract = await db.SaleContracts.Include(c => c.Animals).SingleAsync();
Assert.Equal(ContractId, contract.Id);
Assert.Equal(ContactId, contract.ContactId);
Assert.Equal(35.0m, contract.Price);
Assert.Equal(new DateOnly(2023, 9, 29), contract.HandoverDate);
var link = Assert.Single(contract.Animals);
Assert.Equal(FatherId, link.GerbilId);
}
[Fact]
public async Task IngestResolved_recreates_sale_contracts_on_every_ingest()
{
using var db = NewDb();
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
{ "Import:SourcePath", _dir }
})
.Build();
var service = new IngestResolvedService(db, config, null!);
await service.RunAsync();
Assert.Equal(1, await db.SaleContracts.CountAsync());
// Re-ingest wipes then recreates from the (deterministic) payload —
// the contract survives by being part of the payload, no duplicate PK.
await service.RunAsync();
Assert.Equal(1, await db.SaleContracts.CountAsync());
var contract = await db.SaleContracts.Include(c => c.Animals).SingleAsync();
Assert.Equal(ContractId, contract.Id);
Assert.Single(contract.Animals);
}
}
}

View File

@@ -0,0 +1,88 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
namespace GerbilManager.Tests;
/// <summary>LITTER-MORTALITY: deathsWithin8Weeks field — round-trip, validation, null default.</summary>
public class LitterMortalityTests : IClassFixture<ApiFactory>
{
private readonly HttpClient _client;
public LitterMortalityTests(ApiFactory factory) => _client = factory.CreateClient();
private static int? GetInt(JsonElement el, string prop) =>
el.TryGetProperty(prop, out var v) && v.ValueKind == JsonValueKind.Number
? v.GetInt32() : null;
private async Task<JsonElement> CreateAndGet(object body)
{
var post = await _client.PostAsJsonAsync("/litters", body);
post.EnsureSuccessStatusCode();
var idStr = JsonDocument.Parse(await post.Content.ReadAsStringAsync()).RootElement
.GetProperty("id").GetString()!;
return JsonDocument.Parse(await _client.GetStringAsync($"/litters/{idStr}")).RootElement;
}
[Fact]
public async Task DeathsWithin8Weeks_round_trips()
{
var el = await CreateAndGet(new
{
name = "Wurf Mortalitätstest",
date = "2026-05-01",
totalBorn = 6,
deathsWithin8Weeks = 2,
});
Assert.Equal(6, GetInt(el, "totalBorn"));
Assert.Equal(2, GetInt(el, "deathsWithin8Weeks"));
}
[Fact]
public async Task DeathsWithin8Weeks_defaults_null()
{
var el = await CreateAndGet(new { name = "Wurf Kein Mort", date = "2026-05-02" });
Assert.True(el.TryGetProperty("deathsWithin8Weeks", out var v));
Assert.Equal(JsonValueKind.Null, v.ValueKind);
}
[Fact]
public async Task DeathsWithin8Weeks_exceeding_TotalBorn_returns_400()
{
var resp = await _client.PostAsJsonAsync("/litters", new
{
name = "Ungültig",
date = "2026-05-03",
totalBorn = 4,
deathsWithin8Weeks = 5,
});
Assert.Equal(HttpStatusCode.BadRequest, resp.StatusCode);
var body = await resp.Content.ReadAsStringAsync();
Assert.Contains("TotalBorn", body);
}
[Fact]
public async Task Negative_DeathsWithin8Weeks_returns_400()
{
var resp = await _client.PostAsJsonAsync("/litters", new
{
name = "Negativ",
date = "2026-05-04",
deathsWithin8Weeks = -1,
});
Assert.Equal(HttpStatusCode.BadRequest, resp.StatusCode);
var body = await resp.Content.ReadAsStringAsync();
Assert.Contains("negativ", body);
}
[Fact]
public async Task DeathsWithin8Weeks_allowed_when_TotalBorn_null()
{
var el = await CreateAndGet(new
{
name = "Kein TotalBorn",
date = "2026-05-05",
deathsWithin8Weeks = 3,
});
Assert.Equal(3, GetInt(el, "deathsWithin8Weeks"));
}
}

View File

@@ -8,8 +8,8 @@ using Microsoft.Extensions.Options;
namespace GerbilManager.Tests
{
/// <summary>
/// FEAT-NAMEGEN: NameSuggestionService — prompt assembly, JSON parse (incl. Markdown
/// fence strip), 503-not-configured path, upstream-error path.
/// FEAT-NAMEGEN / NAMEGEN-2-BE: NameSuggestionService — prompt assembly, usage-code mapping,
/// JSON parse (incl. Markdown fence strip), 503-not-configured path, upstream-error path.
/// </summary>
public class NameSuggestionTests
{
@@ -26,6 +26,14 @@ namespace GerbilManager.Tests
Assert.Contains("origin", prompt);
}
[Fact]
public void SystemPrompt_erklärt_thematische_Kategorien()
{
var prompt = NameSuggestionService.BuildSystemPrompt();
Assert.Contains("thematischen Kategorien", prompt);
Assert.Contains("Erfinde KEINE Etymologie", prompt);
}
[Fact]
public void UserPrompt_enthält_Anzahl_und_Anfangsbuchstaben()
{
@@ -33,7 +41,10 @@ namespace GerbilManager.Tests
Assert.Contains("6", prompt);
Assert.Contains("\"A\"", prompt);
Assert.Contains("weibliche", prompt);
Assert.Contains("norn,mythg", prompt);
// codes are mapped to German descriptions
Assert.Contains("Nordische/Altnordische Etymologie", prompt);
Assert.Contains("Griechische Mythologie", prompt);
Assert.Contains("Kulturkreisen", prompt);
}
[Fact]
@@ -54,6 +65,67 @@ namespace GerbilManager.Tests
Assert.DoesNotContain("männliche", prompt);
}
// ── NAMEGEN-2-BE: neue Themen-Kategorien ─────────────────────────────
[Theory]
[InlineData("disney", "Disney-Charaktere")]
[InlineData("pokemon", "Pokémon-Namen")]
[InlineData("encities", "Namen englischer Städte")]
[InlineData("hrcities", "Namen kroatischer Städte")]
[InlineData("usstates", "Namen von US-Bundesstaaten")]
public void UsageMap_enthält_alle_fünf_neuen_Codes(string code, string expectedDescription)
{
Assert.True(NameSuggestionService.UsageMap.TryGetValue(code, out var entry));
Assert.Equal(expectedDescription, entry.Description);
Assert.True(entry.Thematic);
}
[Theory]
[InlineData("disney", "Disney-Charaktere")]
[InlineData("pokemon", "Pokémon-Namen")]
[InlineData("encities", "Namen englischer Städte")]
[InlineData("hrcities", "Namen kroatischer Städte")]
[InlineData("usstates", "Namen von US-Bundesstaaten")]
public void UserPrompt_enthält_Themen_Kategorie_Beschreibung(string code, string expectedDescription)
{
var prompt = NameSuggestionService.BuildUserPrompt(null, null, code, 5);
Assert.Contains(expectedDescription, prompt);
Assert.Contains("Themen-Kategorien", prompt);
Assert.DoesNotContain("Kulturkreisen", prompt);
}
[Fact]
public void UserPrompt_trennt_etym_und_thematische_Kategorien()
{
var prompt = NameSuggestionService.BuildUserPrompt("D", null, "norn,disney", 4);
Assert.Contains("Nordische/Altnordische Etymologie", prompt);
Assert.Contains("Kulturkreisen", prompt);
Assert.Contains("Disney-Charaktere", prompt);
Assert.Contains("Themen-Kategorien", prompt);
}
[Fact]
public void UserPrompt_thematisch_enthält_Geschlecht_Hinweis()
{
var prompt = NameSuggestionService.BuildUserPrompt(null, "female", "encities", 3);
Assert.Contains("Geschlecht-Filter kann ignoriert werden", prompt);
}
[Fact]
public async Task SuggestAsync_parst_thematische_Kategorie_Antwort()
{
var payload = """[{"name":"Dumbo","meaning":"Elefant mit großen Ohren aus dem Disney-Film Dumbo (1941)","origin":"Disney"}]""";
var handler = new StubHandler(_ => Canned(payload));
var service = CreateService("https://api.example.com/v1", "k", "m", handler);
var result = await service.SuggestAsync("D", null, "disney", 1);
Assert.Equal(NameSuggestionStatus.Ok, result.Status);
Assert.NotNull(result.Suggestions);
Assert.Equal("Dumbo", result.Suggestions![0].Name);
Assert.Equal("Disney", result.Suggestions[0].Origin);
}
// ── JSON parsing ──────────────────────────────────────────────────────
[Fact]

View File

@@ -36,7 +36,7 @@ public class PartialUpdateTests : IClassFixture<ApiFactory>
name,
gender = "female",
genotype = "aa CC DD ee GG PP spsp rere",
originBreeder = "Zucht der Kleinen Chaoten",
originBreeder = "Zucht der kleinen Chaoten",
isDeaf = false,
characterTraits = new[] { "neugierig", "zutraulich" },
characterNote = "Liebling der Familie",
@@ -67,7 +67,7 @@ public class PartialUpdateTests : IClassFixture<ApiFactory>
Assert.Equal("ForSale-Tier", GetStr(json, "name"));
Assert.Equal("female", GetStr(json, "gender"));
Assert.Equal("aa CC DD ee GG PP spsp rere", GetStr(json, "genotype"));
Assert.Equal("Zucht der Kleinen Chaoten", GetStr(json, "originBreeder"));
Assert.Equal("Zucht der kleinen Chaoten", GetStr(json, "originBreeder"));
Assert.Equal("Eine Notiz", GetStr(json, "notes"));
Assert.NotNull(GetStr(json, "externalRef")); // externalRef set during create, not cleared by partial PUT
Assert.Contains("neugierig", GetNested(json, "characterTraits") ?? "");
@@ -91,11 +91,11 @@ public class PartialUpdateTests : IClassFixture<ApiFactory>
// Assert: name / genotype / originBreeder / status / externalRef all intact
var json = JsonDocument.Parse(await _client.GetStringAsync($"/gerbils/{id}")).RootElement;
Assert.Equal("Active", GetStr(json, "status"));
Assert.Equal("Breeding", GetStr(json, "status"));
Assert.Equal("Charakter-Tier", GetStr(json, "name"));
Assert.Equal("female", GetStr(json, "gender"));
Assert.Equal("aa CC DD ee GG PP spsp rere", GetStr(json, "genotype"));
Assert.Equal("Zucht der Kleinen Chaoten", GetStr(json, "originBreeder"));
Assert.Equal("Zucht der kleinen Chaoten", GetStr(json, "originBreeder"));
Assert.Equal("Eine Notiz", GetStr(json, "notes"));
Assert.NotNull(GetStr(json, "externalRef")); // externalRef set during create, not cleared by partial PUT
Assert.Contains("handzahm", GetNested(json, "characterTraits") ?? "");
@@ -123,7 +123,7 @@ public class PartialUpdateTests : IClassFixture<ApiFactory>
Assert.Equal("EditForm-Tier (umbenannt)", GetStr(json, "name"));
Assert.Equal("Aktualisierte Notiz", GetStr(json, "notes"));
Assert.Equal("Zucht der Kleinen Chaoten", GetStr(json, "originBreeder"));
Assert.Equal("Zucht der kleinen Chaoten", GetStr(json, "originBreeder"));
Assert.NotNull(GetStr(json, "externalRef")); // externalRef set during create, not cleared by partial PUT
Assert.Contains("neugierig", GetNested(json, "characterTraits") ?? "");
Assert.Equal("Liebling der Familie", GetStr(json, "characterNote"));
@@ -138,7 +138,7 @@ public class PartialUpdateTests : IClassFixture<ApiFactory>
var json = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement;
Assert.Equal("Minimal", GetStr(json, "name"));
Assert.Equal("Active", GetStr(json, "status"));
Assert.Equal("Breeding", GetStr(json, "status"));
// characterTraits defaults to [] on create when not provided
Assert.Contains("[]", GetNested(json, "characterTraits") ?? "");
}

View File

@@ -0,0 +1,44 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
namespace GerbilManager.Tests;
/// <summary>
/// WEB-PUSH: VAPID-Public-Key abrufen + Abo speichern/entfernen.
/// (Das tatsächliche Versenden wird nicht getestet — es geht an externe Push-Dienste.)
/// </summary>
public class PushEndpointTests : IClassFixture<ApiFactory>
{
private readonly ApiFactory _factory;
public PushEndpointTests(ApiFactory factory) => _factory = factory;
[Fact]
public async Task Vapid_public_key_is_exposed()
{
var client = _factory.CreateClient();
var doc = JsonDocument.Parse(await client.GetStringAsync("/push/vapid-public-key")).RootElement;
Assert.True(doc.GetProperty("enabled").GetBoolean());
Assert.False(string.IsNullOrWhiteSpace(doc.GetProperty("publicKey").GetString()));
}
[Fact]
public async Task Subscribe_is_idempotent_and_unsubscribe_works()
{
var client = _factory.CreateClient();
var endpoint = $"https://push.example.com/{Guid.NewGuid()}";
var body = new { endpoint, p256dh = "abc123", auth = "def456" };
var first = await client.PostAsJsonAsync("/push/subscribe", body);
Assert.Equal(HttpStatusCode.OK, first.StatusCode);
// Erneutes Abo mit derselben Endpoint-URL -> weiterhin OK (Upsert, kein Duplikat).
var second = await client.PostAsJsonAsync("/push/subscribe", body);
Assert.Equal(HttpStatusCode.OK, second.StatusCode);
var bad = await client.PostAsJsonAsync("/push/subscribe", new { endpoint = "", p256dh = "", auth = "" });
Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode);
var unsub = await client.PostAsJsonAsync("/push/unsubscribe", new { endpoint });
Assert.Equal(HttpStatusCode.NoContent, unsub.StatusCode);
}
}

View File

@@ -0,0 +1,123 @@
using System.Net.Http.Json;
using System.Text.Json;
using GerbilManagerWebAPI.Models;
using Microsoft.Extensions.DependencyInjection;
namespace GerbilManager.Tests;
/// <summary>
/// REFS: POST /refs/resolve löst getippte Kurz-Verweise (tier|kontakt|wurf|gehege) auf.
/// - exakter (volle GUID) und kurzer (Präfix) Treffer je Typ
/// - mehrdeutiges Präfix (mehrere Treffer) => id=null (nicht geraten)
/// - unbekannter Code / unbekannter Typ => id=null
/// Entitäten werden mit deterministischen GUIDs direkt in die SQLite-Test-DB geseedet,
/// damit Präfixe und Mehrdeutigkeit kontrolliert getestet werden können.
/// </summary>
public class RefsEndpointTests : IClassFixture<ApiFactory>
{
private readonly ApiFactory _factory;
public RefsEndpointTests(ApiFactory factory) => _factory = factory;
// Deterministische GUIDs: zwei Tiere mit GEMEINSAMEM 6-Hex-Präfix "abcdef" (mehrdeutig),
// sowie je eine eindeutige Entität pro Typ.
private static readonly Guid TierA = new("abcdef00-0000-0000-0000-000000000001");
private static readonly Guid TierB = new("abcdef00-0000-0000-0000-000000000002");
private static readonly Guid Kontakt = new("11112222-3333-4444-5555-666677778888");
private static readonly Guid Wurf = new("99990000-aaaa-bbbb-cccc-ddddeeeeffff");
private static readonly Guid Gehege = new("12345678-9abc-def0-1234-567890abcdef");
private async Task SeedAsync()
{
using var scope = _factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationContext>();
if (db.Gerbils.Any(g => g.Id == TierA)) return; // einmalig (geteilte Fixture)
db.Gerbils.Add(new Gerbil { Id = TierA, Name = "Krümel", Gender = Gender.female });
db.Gerbils.Add(new Gerbil { Id = TierB, Name = "Möhre", Gender = Gender.male });
db.Contacts.Add(new Contact { Id = Kontakt, Name = "Erika Musterfrau" });
db.Litters.Add(new Litter { Id = Wurf, Name = "Wurf X", Date = new DateOnly(2026, 1, 1) });
db.Enclosures.Add(new Enclosure { Id = Gehege, Name = "Terrarium 1" });
await db.SaveChangesAsync();
}
private async Task<List<JsonElement>> Resolve(params object[] refs)
{
var resp = await _factory.CreateClient()
.PostAsJsonAsync("/refs/resolve", new { refs });
resp.EnsureSuccessStatusCode();
var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync());
return doc.RootElement.EnumerateArray().ToList();
}
[Fact]
public async Task Resolves_full_guid_per_type()
{
await SeedAsync();
var rows = await Resolve(
new { type = "tier", code = TierA.ToString() },
new { type = "kontakt", code = Kontakt.ToString() },
new { type = "wurf", code = Wurf.ToString() },
new { type = "gehege", code = Gehege.ToString() });
Assert.Equal(TierA.ToString(), rows[0].GetProperty("id").GetString());
Assert.Equal("Krümel", rows[0].GetProperty("name").GetString());
Assert.Equal(Kontakt.ToString(), rows[1].GetProperty("id").GetString());
Assert.Equal("Erika Musterfrau", rows[1].GetProperty("name").GetString());
Assert.Equal(Wurf.ToString(), rows[2].GetProperty("id").GetString());
Assert.Equal("Wurf X", rows[2].GetProperty("name").GetString());
Assert.Equal(Gehege.ToString(), rows[3].GetProperty("id").GetString());
Assert.Equal("Terrarium 1", rows[3].GetProperty("name").GetString());
}
[Fact]
public async Task Resolves_short_prefix_when_unique()
{
await SeedAsync();
// 8-Hex-Kurz-ID des Kontakts ("11112222") ist eindeutig.
var rows = await Resolve(new { type = "kontakt", code = "11112222" });
Assert.Equal(Kontakt.ToString(), rows[0].GetProperty("id").GetString());
Assert.Equal("Erika Musterfrau", rows[0].GetProperty("name").GetString());
}
[Fact]
public async Task Tolerates_dashes_and_case_in_code()
{
await SeedAsync();
// Gemischte Schreibweise + Bindestriche im Kurz-Code des Geheges.
var rows = await Resolve(new { type = "gehege", code = "1234-5678" });
Assert.Equal(Gehege.ToString(), rows[0].GetProperty("id").GetString());
Assert.Equal("Terrarium 1", rows[0].GetProperty("name").GetString());
}
[Fact]
public async Task Ambiguous_prefix_resolves_to_null()
{
await SeedAsync();
// "abcdef" trifft TierA UND TierB => mehrdeutig => id/name null.
var rows = await Resolve(new { type = "tier", code = "abcdef" });
Assert.Equal(JsonValueKind.Null, rows[0].GetProperty("id").ValueKind);
Assert.Equal(JsonValueKind.Null, rows[0].GetProperty("name").ValueKind);
Assert.Equal("tier", rows[0].GetProperty("type").GetString());
Assert.Equal("abcdef", rows[0].GetProperty("code").GetString());
}
[Fact]
public async Task Unknown_code_and_unknown_type_resolve_to_null()
{
await SeedAsync();
var rows = await Resolve(
new { type = "tier", code = "fffffffe" }, // unbekannter Code
new { type = "schubladen", code = "11112222" }); // unbekannter Typ
Assert.Equal(JsonValueKind.Null, rows[0].GetProperty("id").ValueKind);
Assert.Equal(JsonValueKind.Null, rows[1].GetProperty("id").ValueKind);
}
[Fact]
public async Task Too_short_code_resolves_to_null()
{
await SeedAsync();
// < 6 Hex-Zeichen wird nicht aufgelöst (auch wenn es eindeutig wäre).
var rows = await Resolve(new { type = "kontakt", code = "1111" });
Assert.Equal(JsonValueKind.Null, rows[0].GetProperty("id").ValueKind);
}
}

View File

@@ -0,0 +1,208 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using GerbilManagerWebAPI.Import;
using GerbilManagerWebAPI.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace GerbilManager.Tests;
/// <summary>
/// RÜCKNAHMEN (getback_tb): zurückgekommene/zurückgenommene Tiere.
/// - Voller CRUD-Round-Trip (POST/GET[?gerbilId=]/PUT/DELETE).
/// - Validierung: ohne Tier (weder GerbilId noch GerbilName) → 400.
/// - CRITICAL: Rücknahme-Zeilen überleben den Import-Re-Ingest-Wipe
/// (lose, FK-freie GerbilId/FromContactId — wie Feedback).
/// </summary>
public class ReturnRecordEndpointTests : IClassFixture<ApiFactory>
{
private readonly ApiFactory _factory;
public ReturnRecordEndpointTests(ApiFactory factory) => _factory = factory;
[Fact]
public async Task Crud_round_trip_create_list_update_delete()
{
var client = _factory.CreateClient();
var gerbilId = Guid.NewGuid();
var contactId = Guid.NewGuid();
// POST
var resp = await client.PostAsJsonAsync("/returns", new
{
gerbilId,
gerbilName = "Krümel",
returnDate = "2026-05-01T00:00:00Z",
returnPrice = 0m,
originalPrice = 15m,
originalSaleDate = "2025-09-01T00:00:00Z",
fromContactId = contactId,
fromContactName = "Familie Meier",
note = "Allergie in der Familie",
});
Assert.Equal(HttpStatusCode.Created, resp.StatusCode);
var created = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement;
var id = created.GetProperty("id").GetString()!;
Assert.Equal("Krümel", created.GetProperty("gerbilName").GetString());
Assert.Equal(gerbilId.ToString(), created.GetProperty("gerbilId").GetString());
Assert.Equal("Familie Meier", created.GetProperty("fromContactName").GetString());
// GET (unfiltered) returns it
var listed = JsonDocument.Parse(await client.GetStringAsync("/returns")).RootElement;
Assert.Contains(listed.EnumerateArray(), r => r.GetProperty("id").GetString() == id);
// GET ?gerbilId= filters
var filtered = JsonDocument.Parse(
await client.GetStringAsync($"/returns?gerbilId={gerbilId}")).RootElement;
Assert.All(filtered.EnumerateArray(),
r => Assert.Equal(gerbilId.ToString(), r.GetProperty("gerbilId").GetString()));
Assert.Contains(filtered.EnumerateArray(), r => r.GetProperty("id").GetString() == id);
var other = JsonDocument.Parse(
await client.GetStringAsync($"/returns?gerbilId={Guid.NewGuid()}")).RootElement;
Assert.Empty(other.EnumerateArray());
// PUT updates
var putResp = await client.PutAsJsonAsync($"/returns/{id}", new
{
gerbilId,
gerbilName = "Krümel",
returnDate = "2026-05-02T00:00:00Z",
returnPrice = 5m,
note = "Korrigierter Grund",
});
Assert.Equal(HttpStatusCode.OK, putResp.StatusCode);
var updated = JsonDocument.Parse(await putResp.Content.ReadAsStringAsync()).RootElement;
Assert.Equal("Korrigierter Grund", updated.GetProperty("note").GetString());
Assert.Equal(5m, updated.GetProperty("returnPrice").GetDecimal());
// DELETE removes
var delResp = await client.DeleteAsync($"/returns/{id}");
Assert.Equal(HttpStatusCode.NoContent, delResp.StatusCode);
var afterDelete = JsonDocument.Parse(await client.GetStringAsync("/returns")).RootElement;
Assert.DoesNotContain(afterDelete.EnumerateArray(), r => r.GetProperty("id").GetString() == id);
// DELETE again → 404
var delAgain = await client.DeleteAsync($"/returns/{id}");
Assert.Equal(HttpStatusCode.NotFound, delAgain.StatusCode);
}
[Fact]
public async Task Post_rejects_record_without_animal()
{
var client = _factory.CreateClient();
var resp = await client.PostAsJsonAsync("/returns", new { note = "irgendwas" });
Assert.Equal(HttpStatusCode.BadRequest, resp.StatusCode);
}
[Fact]
public async Task Put_unknown_id_returns_404()
{
var client = _factory.CreateClient();
var resp = await client.PutAsJsonAsync($"/returns/{Guid.NewGuid()}", new { gerbilName = "X" });
Assert.Equal(HttpStatusCode.NotFound, resp.StatusCode);
}
[Fact]
public async Task ReturnRecord_survives_ingest_wipe()
{
var dir = Path.Combine(Path.GetTempPath(), "returns-ingest-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
try
{
var contactId = Guid.NewGuid();
var fatherId = Guid.NewGuid();
var motherId = Guid.NewGuid();
var litterId = Guid.NewGuid();
var data = new
{
Contacts = new[]
{
new { Id = contactId, Name = "Test Breeder", Email = "t@e.de", Phone = "", Address = "", Notes = (string?)null, IsBreeder = true, IsReceiver = false, NameSuffix = (string?)null, Provenance = (string?)null }
},
Litters = new[]
{
new { Id = litterId, Name = "Wurf A", Date = "2026-01-01", TotalBorn = 5, DeathsWithin8Weeks = 0, FatherId = fatherId, MotherId = motherId, ExpectedGoHomeDate = (string?)null, Notes = "", PairingCode = "PC01", ExternalRef = "ext-litter-1", LitterLetter = "A" }
},
Gerbils = new[]
{
Animal(fatherId, "Papa", "male", contactId),
Animal(motherId, "Mama", "female", contactId),
},
GerbilPhotos = Array.Empty<object>(),
};
File.WriteAllText(Path.Combine(dir, "resolved_import.json"), JsonSerializer.Serialize(data));
var opts = new DbContextOptionsBuilder<ApplicationContext>()
.UseInMemoryDatabase("returns-ingest-" + Guid.NewGuid().ToString("N"))
.Options;
using var db = new ApplicationContext(opts);
db.Database.EnsureCreated();
// A return record referencing the gerbil + contact that the wipe will delete.
var recordId = Guid.NewGuid();
db.ReturnRecords.Add(new ReturnRecord
{
Id = recordId,
GerbilId = fatherId,
GerbilName = "Papa",
ReturnDate = new DateTime(2026, 5, 1, 0, 0, 0, DateTimeKind.Utc),
ReturnPrice = 0m,
FromContactId = contactId,
FromContactName = "Test Breeder",
Note = "kam zurück",
CreatedAt = DateTimeOffset.UtcNow,
});
await db.SaveChangesAsync();
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?> { { "Import:SourcePath", dir } })
.Build();
var result = await new IngestResolvedService(db, config, null!).RunAsync();
Assert.Contains("Ingestion successful!", result);
// The gerbils/contacts were wiped & recreated, but the return record is untouched.
var survivor = await db.ReturnRecords.SingleAsync(r => r.Id == recordId);
Assert.Equal(fatherId, survivor.GerbilId); // loose id preserved even though the gerbil row was deleted/recreated
Assert.Equal(contactId, survivor.FromContactId);
Assert.Equal("Papa", survivor.GerbilName);
Assert.Equal("Test Breeder", survivor.FromContactName);
Assert.Equal(1, await db.ReturnRecords.CountAsync());
}
finally
{
try { Directory.Delete(dir, recursive: true); } catch { /* best effort */ }
}
}
private static object Animal(Guid id, string name, string gender, Guid contactId) => new
{
Id = id,
Name = name,
Gender = gender,
Status = "Breeding",
LitterId = (Guid?)null,
OriginContactId = contactId,
ReceiverContactId = (Guid?)null,
EnclosureId = (Guid?)null,
ColorVarietyId = new Guid("00000000-0000-0000-0000-000000000006"),
DateOfBirth = "2025-01-01",
DateOfDeath = (string?)null,
CauseOfDeath = (string?)null,
GoHomeDate = (string?)null,
Genotype = "aa CC DD EE GG PP spsp rere",
Notes = "",
ImportSource = "docx-export",
ExternalRef = "ext-" + name,
RawImportData = "{}",
OriginBreeder = "Test Zucht",
NameSearch = name.ToLowerInvariant(),
CharacterTraits = Array.Empty<string>(),
CharacterNote = (string?)null,
IsDeaf = false,
IsResident = true,
};
}

View File

@@ -0,0 +1,407 @@
using GerbilManagerWebAPI.Import.Rpro3;
using GerbilManagerWebAPI.Models;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace GerbilManager.Tests
{
/// <summary>
/// Tests für den RennmausPro-III-Importer (Reader + Dedup + Execute).
/// Die meisten Tests bauen eine hermetische Mini-SQLite im RPRO3-Schema; ein optionaler
/// Test gegen die echte entpackte DB läuft nur, wenn sie lokal vorhanden ist.
/// </summary>
public class Rpro3ImportTests
{
static Rpro3ImportTests()
{
// CP1252 für die Tests verfügbar machen (die Produktion registriert es im Reader-Ctor).
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
}
// ── Unit: Decode / JDN / Genotyp ──────────────────────────────
[Fact]
public void JdnToDate_converts_known_julian_day_numbers()
{
// Blacky _BIRTH = 2455036.0 → 2009-07-23 (siehe rpro3-vergleich.md).
Assert.Equal(new DateOnly(2009, 7, 23), Rpro3Reader.JdnToDate(2455036.0));
Assert.Null(Rpro3Reader.JdnToDate(0));
Assert.Null(Rpro3Reader.JdnToDate(null));
}
[Fact]
public void SmartDecode_prefers_utf8_then_cp1252()
{
var utf8 = System.Text.Encoding.UTF8.GetBytes("männlich");
Assert.Equal("männlich", Rpro3Reader.SmartDecode(utf8));
var cp1252 = System.Text.Encoding.GetEncoding(1252).GetBytes("männlich");
// CP1252-Bytes sind kein gültiges UTF-8 → Fallback dekodiert korrekt.
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
Assert.Equal("männlich", Rpro3Reader.SmartDecode(cp1252));
}
[Fact]
public void CleanGenotype_strips_brackets_keeps_dash()
{
Assert.Equal("aa Ccchm DD EE GG Pp spsp", Rpro3Reader_CleanGenotype("aa Cc[chm] DD EE GG Pp spsp"));
Assert.Equal("Kim AA C- Dd", Rpro3Reader_CleanGenotype("Kim AA C- Dd"));
}
private static string? Rpro3Reader_CleanGenotype(string s)
{
// CleanGenotype ist internal in Rpro3ImportService → über InternalsVisibleTo erreichbar.
var m = typeof(Rpro3ImportService).GetMethod("CleanGenotype",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
return (string?)m!.Invoke(null, new object?[] { s });
}
// ── Unit: Dedup ───────────────────────────────────────────────
[Fact]
public void Dedup_merges_compatible_same_name_records()
{
var animals = new List<Rpro3Animal>
{
Ext("u1", "Alice", new DateOnly(2010, 7, 19), "Schimmel", "Clan A"),
Ext("u2", "Alice", new DateOnly(2010, 7, 19), "Schimmel", ""), // kompatibel → merge
Ext("u3", "Alice", null, "Schimmel", "Clan A"), // kompatibel → merge
Ext("u4", "Alice", new DateOnly(2001, 1, 1), "Schwarz", "Clan B"), // Konflikt → eigener Cluster
};
var r = Rpro3Dedup.Run(animals);
// Mind. ein Merge-Cluster (u1/u2/u3), u4 separat → Name "Alice" mehrdeutig.
Assert.Single(r.MergeClusters);
Assert.Equal(3, r.MergeClusters.Values.First().Count);
Assert.Contains(r.Ambiguous, a => a.Name == "Alice");
}
[Fact]
public void Dedup_does_not_merge_placeholder_names()
{
var animals = new List<Rpro3Animal>
{
Ext("u1", "unbekannt", null, "", ""),
Ext("u2", "unbekannt", null, "", ""),
};
var r = Rpro3Dedup.Run(animals);
Assert.Empty(r.MergeClusters);
Assert.Equal(2, r.Placeholders.Count);
}
[Fact]
public void Dedup_force_merges_variants_declared_same_by_breeder()
{
// Zwei Varianten, die der Auto-Dedup wegen Farbkonflikt getrennt lässt …
var animals = new List<Rpro3Animal>
{
Ext("u1", "Akiro", new DateOnly(2008, 2, 5), "Polarfuchs", "Privatzucht"), // Variante B
Ext("u2", "Akiro", new DateOnly(2008, 2, 6), "Polarfuchs, hell", "unbekannt"), // Variante C
};
// ohne Entscheidung: getrennt (Farbe + DOB unterschiedlich → Konflikt)
Assert.Empty(Rpro3Dedup.Run(animals).MergeClusters);
// … werden per „Same"-Entscheidung der Züchterin zusammengelegt.
var decisions = new Rpro3Decisions
{
Decisions = { new Rpro3Decision { Name = "Akiro", Same = { new() { "u1", "u2" } } } }
};
var r = Rpro3Dedup.Run(animals, decisions);
Assert.Single(r.MergeClusters);
Assert.Equal(2, r.MergeClusters.Values.First().Count);
Assert.Equal(r.RidToRoot["u1"], r.RidToRoot["u2"]);
}
[Fact]
public void Dedup_force_splits_variants_declared_different_by_breeder()
{
// Zwei Datensätze, die der Auto-Dedup zusammenlegen würde (kompatibel) …
var animals = new List<Rpro3Animal>
{
Ext("u1", "Max", new DateOnly(2013, 2, 1), "Marder", "Clan A"),
Ext("u2", "Max", new DateOnly(2013, 2, 1), "Marder", "Clan A"),
};
Assert.Single(Rpro3Dedup.Run(animals).MergeClusters);
// … bleiben durch „Different" getrennt.
var decisions = new Rpro3Decisions
{
Decisions = { new Rpro3Decision { Name = "Max", Different = { new() { "u1" }, new() { "u2" } } } }
};
var r = Rpro3Dedup.Run(animals, decisions);
Assert.Empty(r.MergeClusters);
Assert.NotEqual(r.RidToRoot["u1"], r.RidToRoot["u2"]);
}
[Fact]
public void Rpro3Decisions_load_returns_empty_when_file_missing()
{
var d = Rpro3Decisions.Load(Path.Combine(Path.GetTempPath(), "does-not-exist-" + Guid.NewGuid().ToString("N") + ".json"));
Assert.Empty(d.Decisions);
}
[Fact]
public void Rpro3Decisions_roundtrips_through_json()
{
var path = Path.Combine(Path.GetTempPath(), "rpro3-dec-" + Guid.NewGuid().ToString("N") + ".json");
File.WriteAllText(path,
"{\"decisions\":[{\"name\":\"Bura\",\"same\":[[\"228\",\"u2128\"]],\"fields\":{\"228\":{\"origin\":\"Sarah Wörz\"}}}," +
"{\"name\":\"MilkyWay\",\"same\":[[\"u1031\",\"u1019\"]],\"fields\":{\"u1031\":{\"genotype\":\"aa Cc[h] DD ee Gg P- spsp\",\"color\":\"Kohlfuchs-Hell\"}}}]}");
try
{
var d = Rpro3Decisions.Load(path);
Assert.Equal(2, d.Decisions.Count);
Assert.Equal("Sarah Wörz", d.BuildFieldIndex()["228"].Origin);
Assert.Equal(new[] { "228", "u2128" }, d.SameGroups().First());
// Gencode-Override (z. B. MilkyWay: korrektes C-Locus c[h]) muss durch den JSON-Roundtrip kommen.
Assert.Equal("aa Cc[h] DD ee Gg P- spsp", d.BuildFieldIndex()["u1031"].Genotype);
}
finally { File.Delete(path); }
}
// ── Integration: Reader + Execute gegen eine Mini-RPRO3-DB ────
[Fact]
public async Task Execute_imports_animals_litters_contacts_and_is_idempotent()
{
var dbPath = BuildMiniRpro3();
try
{
var data = new Rpro3Reader().ReadFromDbFile(dbPath);
Assert.Equal(2, data.Animals.Count(a => a.Src == Rpro3Src.Stamm));
Assert.True(data.Animals.Count(a => a.Src == Rpro3Src.Fremd) >= 2);
using var efConn = new SqliteConnection("DataSource=:memory:");
efConn.Open();
var opts = new DbContextOptionsBuilder<ApplicationContext>().UseSqlite(efConn).Options;
using var ctx = new ApplicationContext(opts);
ctx.Database.EnsureCreated();
var config = new ConfigurationBuilder().Build();
var service = new Rpro3ImportService(ctx, config, null);
var analyze = await service.AnalyzeAsync(data, photosProvided: false, availablePhotoFiles: null);
Assert.Equal(2, analyze.Counts.OwnAnimals);
Assert.True(analyze.NewVsCurrentNew >= 2);
var first = await service.ExecuteAsync(data, Path.GetTempPath(), photosProvided: false, photoSourcePaths: null);
Assert.True(first.GerbilsImported >= 4); // 2 stamm + ≥2 fremd
Assert.Equal(1, first.LittersImported >= 1 ? 1 : 0); // mind. 1 Wurf importiert
var gerbilCount1 = await ctx.Gerbils.CountAsync();
var litterCount1 = await ctx.Litters.CountAsync();
// Re-Run: idempotent — gleiche Zeilenzahl, keine Dubletten.
var second = await service.ExecuteAsync(data, Path.GetTempPath(), photosProvided: false, photoSourcePaths: null);
Assert.Equal(gerbilCount1, await ctx.Gerbils.CountAsync());
Assert.Equal(litterCount1, await ctx.Litters.CountAsync());
// Pedigree: Wurf hat Mutter + Vater verknüpft (resolved gegen importierte Tiere).
var litter = await ctx.Litters.FirstAsync(l => l.Name!.StartsWith("Wurf"));
Assert.NotNull(litter.MotherId);
Assert.NotNull(litter.FatherId);
// Genotyp wurde aus _FCODE übernommen + Klammern entfernt.
var blacky = await ctx.Gerbils.FirstAsync(g => g.Name == "Blacky");
Assert.Equal("aa Ccchm DD EE GG Pp spsp", blacky.Genotype);
Assert.True(blacky.IsResident);
// Encoding: "männlich" korrekt dekodiert (Latin-1-Quelle).
Assert.Equal(Gender.male, blacky.Gender);
}
finally { try { File.Delete(dbPath); } catch { } }
}
// ── Integration: Feature-Tabellen (Becken/Erwerb/Reservierung/Rücknahme/Warteliste/Ausstellung) ──
[Fact]
public async Task Execute_imports_feature_tables_and_is_idempotent()
{
var dbPath = BuildMiniRpro3();
try
{
var data = new Rpro3Reader().ReadFromDbFile(dbPath);
// Reader hat alle Feature-Tabellen erfasst.
Assert.Equal(2, data.Becken.Count);
Assert.Single(data.Acquisitions);
Assert.Single(data.Abgeben);
Assert.Single(data.Abstat);
Assert.Single(data.Getback);
Assert.Single(data.Nachfrage);
Assert.Single(data.Ausstellungen);
Assert.Equal(1, data.StammBecken["1"]); // Blacky → Becken 1
using var efConn = new SqliteConnection("DataSource=:memory:");
efConn.Open();
var opts = new DbContextOptionsBuilder<ApplicationContext>().UseSqlite(efConn).Options;
using var ctx = new ApplicationContext(opts);
ctx.Database.EnsureCreated();
var service = new Rpro3ImportService(ctx, new ConfigurationBuilder().Build(), null);
var res = await service.ExecuteAsync(data, Path.GetTempPath(), photosProvided: false, photoSourcePaths: null);
Assert.Equal(2, res.EnclosuresImported);
Assert.Equal(1, res.AcquisitionsImported);
Assert.Equal(2, res.ReservationsImported); // abgeben(Blacky, reserviert) + abstat(Kuke, abgegeben)
Assert.Equal(1, res.ReturnsImported);
Assert.Equal(1, res.WaitingListImported);
Assert.Equal(1, res.ExhibitionsImported);
// Becken → Gehege; Blacky ist Becken 1 zugeordnet.
Assert.Equal(2, await ctx.Enclosures.CountAsync());
var kaefig = await ctx.Enclosures.FirstAsync(e => e.Name == "Käfig A");
Assert.Equal("80x35x40", kaefig.Size);
Assert.Equal(3, kaefig.Capacity);
Assert.Equal(60, kaefig.CleaningCycleDays);
var blacky = await ctx.Gerbils.FirstAsync(g => g.Name == "Blacky");
Assert.Equal(kaefig.Id, blacky.EnclosureId);
// Erwerb verknüpft auf Blacky mit Preis/Datum.
var acq = await ctx.AcquisitionRecords.SingleAsync();
Assert.Equal(blacky.Id, acq.GerbilId);
Assert.Equal(9.5m, acq.Price);
Assert.NotNull(acq.Date);
// Reservierung: Blacky reserviert für Lisa M.
var resv = await ctx.SaleReservations.FirstAsync(r => r.GerbilId == blacky.Id);
Assert.Equal("reserviert", resv.Status);
Assert.Equal("Lisa M.", resv.ContactName);
// Abgabe-Abschluss: Kuke → abgegeben.
var kuke = await ctx.Gerbils.FirstAsync(g => g.Name == "Kuke");
var kukeRes = await ctx.SaleReservations.FirstAsync(r => r.GerbilId == kuke.Id);
Assert.Equal("abgegeben", kukeRes.Status);
Assert.Equal(15.0m, kukeRes.Price);
// Rücknahme: Blacky kam zurück.
var ret = await ctx.ReturnRecords.SingleAsync();
Assert.Equal(blacky.Id, ret.GerbilId);
Assert.Equal(15.0m, ret.OriginalPrice);
Assert.Equal("Lisa M.", ret.FromContactName);
// Warteliste: männlicher Schimmel.
var wl = await ctx.WaitingListEntries.SingleAsync();
Assert.Equal("male", wl.WishGender);
Assert.Equal("Schimmel", wl.WishColor);
Assert.Equal("offen", wl.Status);
// Ausstellung: Blacky, 1. Platz, BOB.
var exh = await ctx.ExhibitionResults.SingleAsync();
Assert.Equal(blacky.Id, exh.GerbilId);
Assert.Equal("Schau 2011", exh.EventName);
Assert.Equal("1. Platz", exh.Placement);
Assert.Equal("BOB", exh.Award);
// Re-Run: idempotent — keine Dubletten in den Feature-Tabellen.
await service.ExecuteAsync(data, Path.GetTempPath(), photosProvided: false, photoSourcePaths: null);
Assert.Equal(2, await ctx.Enclosures.CountAsync());
Assert.Equal(1, await ctx.AcquisitionRecords.CountAsync());
Assert.Equal(2, await ctx.SaleReservations.CountAsync()); // Blacky + Kuke
Assert.Equal(1, await ctx.ReturnRecords.CountAsync());
Assert.Equal(1, await ctx.WaitingListEntries.CountAsync());
Assert.Equal(1, await ctx.ExhibitionResults.CountAsync());
}
finally { try { File.Delete(dbPath); } catch { } }
}
// ── Helpers ──
private static Rpro3Animal Ext(string rid, string name, DateOnly? dob, string farbe, string origin) =>
new() { Rid = rid, Src = Rpro3Src.Fremd, Name = name, Dob = dob, Farbe = farbe, Origin = origin };
/// <summary>Baut eine minimale SQLite im RPRO3-Schema (Latin-1-Geschlecht, JDN-Daten).</summary>
private static string BuildMiniRpro3()
{
var path = Path.Combine(Path.GetTempPath(), "mini-rpro3-" + Guid.NewGuid().ToString("N") + ".db");
using var conn = new SqliteConnection($"DataSource={path}");
conn.Open();
void Exec(string sql) { using var c = conn.CreateCommand(); c.CommandText = sql; c.ExecuteNonQuery(); }
Exec("CREATE TABLE herk_tb (id INTEGER, _BEZ, _ANREDE, _VNAME, _NNAME, _CLAN, _STR, _ORT, _PLZ, _TELP, _TELD, _MAIL, _HTTP, _MEMO, _BEM)");
Exec("CREATE TABLE abn_tb (id INTEGER, _BEZ, _ANREDE, _VNAME, _NNAME, _CLAN, _STR, _ORT, _PLZ, _TELP, _TELD, _MAIL, _HTTP, _MEMO, _BEM)");
Exec("CREATE TABLE baum_tb (id, _MID, _PID)");
Exec("CREATE TABLE stamm_tb (id INTEGER, _NAME, _SEX, _BIRTH, _HERKUNFT, _ZB, _STATUS, _FEHLER, _KASTRAT_DATE, _BECKEN)");
Exec("CREATE TABLE fremd_tb (id INTEGER, _NAME, _SEX, _BIRTH, _ZB, _HERK, _MID, _PID, _TODAM, _KASTRAT_DATE)");
Exec("CREATE TABLE wurf_tb (id INTEGER, _MID, _PID, _AM, _BEZ, _BEM)");
Exec("CREATE TABLE wurftier_tb (id, _WID, _NAME, _SEX, _BIRTH, _SID, _TODAM, _WARUM, _ABAM, _ABN, _PRICE, _ZB, _FEHLER)");
Exec("CREATE TABLE color_tb (id, _FARBE, _FCODE)");
Exec("CREATE TABLE wurfcolor_tb (id, _FARBE, _FCODE)");
Exec("CREATE TABLE fremdcolor_tb (id, _FARBE, _FCODE)");
Exec("CREATE TABLE tod_tb (tid, _AM, _WARUM)");
Exec("CREATE TABLE waage_tb (_TID, _GRAMM, _DATE, _BEM)");
Exec("CREATE TABLE jungwaage_tb (_TID, _WID, _GRAMM, _DATE, _BEM)");
Exec("CREATE TABLE krank_tb (_TID, _DATE, _BEM, _MED)");
Exec("CREATE TABLE diary_tb (_TID, _BEZ, _DATE, _DESC)");
Exec("CREATE TABLE photo_tb (id, _P1, _P2, _P3)");
// Feature-Tabellen.
Exec("CREATE TABLE becken_tb (id INTEGER, _BEZ, _SIZE, _MENGE, _CLEANED, _CYCLUS, _NEXT)");
Exec("CREATE TABLE herktier_tb (id INTEGER, _TID, _DATE, _PRICE, _BEM, _ART)");
Exec("CREATE TABLE abgeben_tb (tid, _RES, _BEM, _TERMIN, _ABN, _BEZ)");
Exec("CREATE TABLE abstat_tb (tid, _IDABN, _AM, _PRICE, _ART, _BEM)");
Exec("CREATE TABLE getback_tb (id INTEGER, _TID, _ZAM, _ZPREIS, _AM, _PREIS, _ABN, _BEM)");
Exec("CREATE TABLE nachfrage_tb (id INTEGER, _COLOR, _SEX, _DATE, _ABN, _CODE, _VOM, _STATUS, _ART)");
Exec("CREATE TABLE ausz_tb (id INTEGER, _TID, _VERANSTALTUNG, _DATE, _ORT, _PLATZ, _AUSZ, _EXTRA, _JUROR, _BEM)");
// Kontakte
Exec("INSERT INTO herk_tb (id,_BEZ,_CLAN,_ORT,_MAIL) VALUES (1,'eigene Zucht','','','')");
Exec("INSERT INTO herk_tb (id,_BEZ,_CLAN,_ORT,_MAIL) VALUES (61,'M.Knoss GG','Clan X','Gießen','a@b.de')");
// Geschlecht als Latin-1-Bytes einfügen (BLOB), um den smart_decode-Fallback zu testen.
var maennBytes = System.Text.Encoding.GetEncoding(1252).GetBytes("männlich");
var weibBytes = System.Text.Encoding.UTF8.GetBytes("weiblich");
void InsertStamm(int id, string name, byte[] sex, double birth, int herk, string zb, int becken = 0)
{
using var c = conn.CreateCommand();
c.CommandText = "INSERT INTO stamm_tb (id,_NAME,_SEX,_BIRTH,_HERKUNFT,_ZB,_STATUS,_FEHLER,_BECKEN) VALUES ($id,$n,$s,$b,$h,$z,3,'',$bk)";
c.Parameters.AddWithValue("$id", id);
c.Parameters.AddWithValue("$n", name);
c.Parameters.AddWithValue("$s", sex);
c.Parameters.AddWithValue("$b", birth);
c.Parameters.AddWithValue("$h", herk);
c.Parameters.AddWithValue("$z", zb);
c.Parameters.AddWithValue("$bk", becken);
c.ExecuteNonQuery();
}
InsertStamm(1, "Blacky", maennBytes, 2455036.0, 61, "ZdKC-B.09.2009", becken: 1);
InsertStamm(2, "Kuke", weibBytes, 2455093.0, 61, "ZdKC-B.10.2009");
// Genotyp (Bracket-Notation) für Blacky.
Exec("INSERT INTO color_tb (id,_FARBE,_FCODE) VALUES ('1','Schwarz','aa Cc[chm] DD EE GG Pp spsp')");
// Externe Ahnen (Eltern von Blacky & Kuke via baum_tb).
Exec("INSERT INTO fremd_tb (id,_NAME,_SEX,_BIRTH,_HERK,_MID,_PID) VALUES (1,'Oma','weiblich',0,1,'','')");
Exec("INSERT INTO fremd_tb (id,_NAME,_SEX,_BIRTH,_HERK,_MID,_PID) VALUES (2,'Opa','männlich',0,1,'','')");
Exec("INSERT INTO baum_tb (id,_MID,_PID) VALUES ('1','u1','u2')"); // Blacky Eltern = Oma×Opa
Exec("INSERT INTO baum_tb (id,_MID,_PID) VALUES ('2','u1','u2')"); // Kuke Eltern = Oma×Opa
// Wurf: Mutter Kuke (2) × Vater Blacky (1)
Exec("INSERT INTO wurf_tb (id,_MID,_PID,_AM,_BEZ,_BEM) VALUES (1,'2','1',2455246.0,'Wurf A','Erster Wurf')");
Exec("INSERT INTO wurftier_tb (id,_WID,_NAME,_SEX,_BIRTH,_SID,_TODAM,_ABAM,_ABN,_PRICE,_ZB) VALUES ('1j1','1','Alvin','männlich',2455246.0,'','','',NULL,'','21 A')");
// Gewicht + Krankheit für Blacky.
Exec("INSERT INTO waage_tb (_TID,_GRAMM,_DATE,_BEM) VALUES ('1',55.0,2455083.0,'')");
Exec("INSERT INTO krank_tb (_TID,_DATE,_BEM,_MED) VALUES ('1',2455077.0,'Prellung','')");
// Feature-Tabellen-Daten.
// Abnehmer-Kontakt (für Reservierung/Rücknahme/Warteliste).
Exec("INSERT INTO abn_tb (id,_BEZ,_VNAME,_NNAME) VALUES (5,'Lisa M.','Lisa','Müller')");
// Becken 1 (Blacky wohnt dort, _BECKEN=1), Becken 2 ohne Bewohner.
Exec("INSERT INTO becken_tb (id,_BEZ,_SIZE,_MENGE,_CLEANED,_CYCLUS,_NEXT) VALUES (1,'Käfig A','80x35x40',3,2455595.0,60,2455655.0)");
Exec("INSERT INTO becken_tb (id,_BEZ,_SIZE,_MENGE,_CLEANED,_CYCLUS,_NEXT) VALUES (2,'Terrarium','55x48x110',32,2455638.0,90,2455728.0)");
// Erwerb: Blacky (stamm 1) am JDN für 9.50.
Exec("INSERT INTO herktier_tb (id,_TID,_DATE,_PRICE,_BEM) VALUES (61,'1',2455076.0,9.5,'gekauft')");
// Reservierung: Blacky (stamm 1) reserviert für abn 5.
Exec("INSERT INTO abgeben_tb (tid,_RES,_BEM,_TERMIN,_ABN,_BEZ) VALUES ('1',1,'',2455730.0,5,0)");
// Abgabe-Abschluss: Kuke (stamm 2) abgegeben an abn 5 für 15.
Exec("INSERT INTO abstat_tb (tid,_IDABN,_AM,_PRICE,_BEM) VALUES ('2',5,2455716.0,15.0,'Zog aus.')");
// Rücknahme: Blacky kam zurück von abn 5.
Exec("INSERT INTO getback_tb (id,_TID,_ZAM,_ZPREIS,_AM,_PREIS,_ABN,_BEM) VALUES (2,'1',2455992.0,0.0,2455798.0,15.0,5,'kam zurück')");
// Warteliste: Wunsch nach männlichem Schimmel von abn 5.
Exec("INSERT INTO nachfrage_tb (id,_COLOR,_SEX,_DATE,_ABN,_CODE,_VOM,_STATUS) VALUES (1,'Schimmel','männlich',0.0,5,'egal',2456172.0,'')");
// Ausstellung: ein Ergebnis für Blacky (in echten Backups oft leer).
Exec("INSERT INTO ausz_tb (id,_TID,_VERANSTALTUNG,_DATE,_ORT,_PLATZ,_AUSZ,_JUROR,_BEM) VALUES (1,'1','Schau 2011',2455700.0,'Halle A','1. Platz','BOB','Frau X','schön')");
conn.Close();
SqliteConnection.ClearAllPools();
return path;
}
}
}

View File

@@ -0,0 +1,214 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using GerbilManagerWebAPI.Import;
using GerbilManagerWebAPI.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace GerbilManager.Tests;
/// <summary>
/// ABGABE-STATUS (Reservierungs-/Abgabe-Status): the pre-handover pipeline
/// verfügbar → reserviert → abgegeben.
/// - Full CRUD round-trip via /reservations.
/// - GET ?gerbilId= filters to one animal.
/// - Invalid status falls back to "verfuegbar".
/// - CRITICAL: rows survive the import re-ingest wipe (loose, FK-free GerbilId/ReservedForContactId).
/// </summary>
public class SaleReservationEndpointTests : IClassFixture<ApiFactory>
{
private readonly ApiFactory _factory;
public SaleReservationEndpointTests(ApiFactory factory) => _factory = factory;
[Fact]
public async Task Reservation_crud_lifecycle_create_reserve_handover_delete()
{
var client = _factory.CreateClient();
var gerbilId = Guid.NewGuid();
var contactId = Guid.NewGuid();
// Create -> defaults to verfuegbar.
var create = await client.PostAsJsonAsync("/reservations", new
{
gerbilId,
gerbilName = "Pippa",
});
Assert.Equal(HttpStatusCode.Created, create.StatusCode);
var created = JsonDocument.Parse(await create.Content.ReadAsStringAsync()).RootElement;
var id = created.GetProperty("id").GetString();
Assert.False(string.IsNullOrEmpty(id));
Assert.Equal("verfuegbar", created.GetProperty("status").GetString());
Assert.Equal(gerbilId.ToString(), created.GetProperty("gerbilId").GetString());
Assert.Equal("Pippa", created.GetProperty("gerbilName").GetString());
// List contains it.
var listed = JsonDocument.Parse(await client.GetStringAsync("/reservations")).RootElement;
Assert.Contains(listed.EnumerateArray(), r => r.GetProperty("id").GetString() == id);
// Filter by gerbilId returns exactly this row.
var byGerbil = JsonDocument.Parse(await client.GetStringAsync($"/reservations?gerbilId={gerbilId}")).RootElement;
Assert.All(byGerbil.EnumerateArray(), r => Assert.Equal(gerbilId.ToString(), r.GetProperty("gerbilId").GetString()));
Assert.Contains(byGerbil.EnumerateArray(), r => r.GetProperty("id").GetString() == id);
// PUT -> reserve for a contact with an appointment + price.
var reserve = await client.PutAsJsonAsync($"/reservations/{id}", new
{
status = "reserviert",
reservedForContactId = contactId,
contactName = "Familie Huber",
appointmentDate = "2026-07-01T10:00:00Z",
price = 25.50m,
note = "Käfig wird mitgebracht.",
});
Assert.Equal(HttpStatusCode.OK, reserve.StatusCode);
var reserved = JsonDocument.Parse(await reserve.Content.ReadAsStringAsync()).RootElement;
Assert.Equal("reserviert", reserved.GetProperty("status").GetString());
Assert.Equal(contactId.ToString(), reserved.GetProperty("reservedForContactId").GetString());
Assert.Equal("Familie Huber", reserved.GetProperty("contactName").GetString());
Assert.Equal(25.50m, reserved.GetProperty("price").GetDecimal());
// PUT -> hand over.
var handover = await client.PutAsJsonAsync($"/reservations/{id}", new
{
status = "abgegeben",
reservedForContactId = contactId,
handedOverDate = "2026-07-01T10:30:00Z",
});
Assert.Equal(HttpStatusCode.OK, handover.StatusCode);
var handed = JsonDocument.Parse(await handover.Content.ReadAsStringAsync()).RootElement;
Assert.Equal("abgegeben", handed.GetProperty("status").GetString());
Assert.NotEqual(JsonValueKind.Null, handed.GetProperty("handedOverDate").ValueKind);
// Delete -> 204, then 404.
Assert.Equal(HttpStatusCode.NoContent, (await client.DeleteAsync($"/reservations/{id}")).StatusCode);
Assert.Equal(HttpStatusCode.NotFound, (await client.DeleteAsync($"/reservations/{id}")).StatusCode);
Assert.Equal(HttpStatusCode.NotFound, (await client.PutAsJsonAsync($"/reservations/{id}", new { status = "verfuegbar" })).StatusCode);
}
[Fact]
public async Task Post_with_unknown_status_falls_back_to_verfuegbar()
{
var client = _factory.CreateClient();
var create = await client.PostAsJsonAsync("/reservations", new { gerbilId = Guid.NewGuid(), status = "bananen" });
Assert.Equal(HttpStatusCode.Created, create.StatusCode);
var dto = JsonDocument.Parse(await create.Content.ReadAsStringAsync()).RootElement;
Assert.Equal("verfuegbar", dto.GetProperty("status").GetString());
}
[Fact]
public async Task Post_without_gerbilId_is_rejected()
{
var client = _factory.CreateClient();
var create = await client.PostAsJsonAsync("/reservations", new { gerbilId = Guid.Empty, status = "reserviert" });
Assert.Equal(HttpStatusCode.BadRequest, create.StatusCode);
}
[Fact]
public async Task Reservation_survives_ingest_wipe()
{
// Fresh in-memory DB seeded with a resolved import file (mirrors IngestResolvedServiceTests).
var dir = Path.Combine(Path.GetTempPath(), "reservation-ingest-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
try
{
var contactId = Guid.NewGuid();
var fatherId = Guid.NewGuid();
var motherId = Guid.NewGuid();
var litterId = Guid.NewGuid();
var data = new
{
Contacts = new[]
{
new { Id = contactId, Name = "Test Breeder", Email = "t@e.de", Phone = "", Address = "", Notes = (string?)null, IsBreeder = true, IsReceiver = false, NameSuffix = (string?)null, Provenance = (string?)null }
},
Litters = new[]
{
new { Id = litterId, Name = "Wurf A", Date = "2026-01-01", TotalBorn = 5, DeathsWithin8Weeks = 0, FatherId = fatherId, MotherId = motherId, ExpectedGoHomeDate = (string?)null, Notes = "", PairingCode = "PC01", ExternalRef = "ext-litter-1", LitterLetter = "A" }
},
Gerbils = new[]
{
Animal(fatherId, "Papa", "male", contactId),
Animal(motherId, "Mama", "female", contactId),
},
GerbilPhotos = Array.Empty<object>(),
};
File.WriteAllText(Path.Combine(dir, "resolved_import.json"), JsonSerializer.Serialize(data));
var opts = new DbContextOptionsBuilder<ApplicationContext>()
.UseInMemoryDatabase("reservation-ingest-" + Guid.NewGuid().ToString("N"))
.Options;
using var db = new ApplicationContext(opts);
db.Database.EnsureCreated();
// A reservation referencing the gerbil + contact that the wipe will delete.
var resId = Guid.NewGuid();
db.SaleReservations.Add(new SaleReservation
{
Id = resId,
GerbilId = fatherId,
GerbilName = "Papa",
Status = "reserviert",
ReservedForContactId = contactId,
ContactName = "Test Breeder",
AppointmentDate = new DateTime(2026, 7, 1, 10, 0, 0, DateTimeKind.Utc),
Price = 30m,
Note = "Abholung am Wochenende.",
CreatedAt = DateTimeOffset.UtcNow,
UpdatedAt = DateTimeOffset.UtcNow,
});
await db.SaveChangesAsync();
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?> { { "Import:SourcePath", dir } })
.Build();
// Run the ingest wipe + reload.
var result = await new IngestResolvedService(db, config, null!).RunAsync();
Assert.Contains("Ingestion successful!", result);
// Gerbils/contacts were wiped & re-created, but the reservation is untouched.
var survivor = await db.SaleReservations.SingleAsync(r => r.Id == resId);
Assert.Equal(fatherId, survivor.GerbilId); // loose id preserved
Assert.Equal(contactId, survivor.ReservedForContactId);
Assert.Equal("Papa", survivor.GerbilName);
Assert.Equal("Test Breeder", survivor.ContactName);
Assert.Equal("reserviert", survivor.Status);
Assert.Equal(30m, survivor.Price);
Assert.Equal(1, await db.SaleReservations.CountAsync());
}
finally
{
try { Directory.Delete(dir, recursive: true); } catch { /* best effort */ }
}
}
private static object Animal(Guid id, string name, string gender, Guid contactId) => new
{
Id = id,
Name = name,
Gender = gender,
Status = "Breeding",
LitterId = (Guid?)null,
OriginContactId = contactId,
ReceiverContactId = (Guid?)null,
EnclosureId = (Guid?)null,
ColorVarietyId = new Guid("00000000-0000-0000-0000-000000000006"),
DateOfBirth = "2025-01-01",
DateOfDeath = (string?)null,
CauseOfDeath = (string?)null,
GoHomeDate = (string?)null,
Genotype = "aa CC DD EE GG PP spsp rere",
Notes = "",
ImportSource = "docx-export",
ExternalRef = "ext-" + name,
RawImportData = "{}",
OriginBreeder = "Test Zucht",
NameSearch = name.ToLowerInvariant(),
CharacterTraits = Array.Empty<string>(),
CharacterNote = (string?)null,
IsDeaf = false,
IsResident = true,
};
}

View File

@@ -16,7 +16,7 @@ public class SearchVariationsTests : IClassFixture<ApiFactory>
private readonly HttpClient _client;
public SearchVariationsTests(ApiFactory factory) => _client = factory.CreateClient();
private async Task Create(string name, string? originBreeder = null, string status = "Active")
private async Task Create(string name, string? originBreeder = null, string status = "Breeding")
{
var resp = await _client.PostAsJsonAsync("/gerbils",
new { name, gender = "female", status, originBreeder });
@@ -142,7 +142,7 @@ public class SearchVariationsTests : IClassFixture<ApiFactory>
public async Task Combined_status_and_name_filter()
{
await Create("KombiVerkauf", status: "ForSale");
await Create("KombiAktiv", status: "Active");
await Create("KombiAktiv", status: "Breeding");
var hits = await Names("status==ForSale,nameSearch=*kombi");
Assert.Contains("KombiVerkauf", hits);
Assert.DoesNotContain("KombiAktiv", hits);

View File

@@ -0,0 +1,339 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using GerbilManagerWebAPI.Import;
using GerbilManagerWebAPI.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace GerbilManager.Tests
{
/// <summary>
/// Regression tests for the "Freeze/Override" mechanism (verified key animals + manual work
/// survive the re-ingest). Exercised at the service + ingest level with an InMemory DB, mirroring
/// the harness in <see cref="IngestResolvedServiceTests"/>.
/// </summary>
public class VerifiedGerbilTests : IDisposable
{
private static readonly Guid Schwarz = new("00000000-0000-0000-0000-000000000006");
private readonly List<string> _dirs = new();
public void Dispose()
{
foreach (var d in _dirs)
try { Directory.Delete(d, recursive: true); } catch { }
}
// ── Harness helpers ──────────────────────────────────────────────────
private string NewDir()
{
var dir = Path.Combine(Path.GetTempPath(), "verified-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
_dirs.Add(dir);
return dir;
}
private static ApplicationContext NewDb()
{
var opts = new DbContextOptionsBuilder<ApplicationContext>()
.UseInMemoryDatabase("verified-" + Guid.NewGuid().ToString("N"))
.Options;
var db = new ApplicationContext(opts);
db.Database.EnsureCreated();
return db;
}
private static IngestResolvedService Service(ApplicationContext db, string dir)
{
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
{ "Import:SourcePath", dir },
{ "Photos:RootPath", dir },
})
.Build();
return new IngestResolvedService(db, config, null!);
}
private static void WritePayload(string dir, object[] gerbils, object[]? litters = null, object[]? contacts = null) =>
File.WriteAllText(Path.Combine(dir, "resolved_import.json"), JsonSerializer.Serialize(new
{
Contacts = contacts ?? Array.Empty<object>(),
Litters = litters ?? Array.Empty<object>(),
Gerbils = gerbils,
GerbilPhotos = Array.Empty<object>(),
SaleContracts = Array.Empty<object>(),
}));
private static object ImportGerbil(Guid id, string name, string genotype, string gender = "female", string dob = "2022-01-01") => new
{
Id = id,
Name = name,
Gender = gender,
Status = "Breeding",
DateOfBirth = dob,
Genotype = genotype,
ColorVarietyId = Schwarz,
IsResident = true,
OriginBreeder = "Test Zucht",
};
// ── 1. Manual animal survives the ingest (never wiped) ───────────────
[Fact]
public async Task Manual_animal_survives_ingest_that_omits_it()
{
using var db = NewDb();
var dir = NewDir();
var manualId = Guid.NewGuid();
db.Gerbils.Add(new Gerbil { Id = manualId, Name = "Handmaus", Gender = Gender.female, IsManual = true });
await db.SaveChangesAsync();
var importedId = Guid.NewGuid();
WritePayload(dir, new[] { ImportGerbil(importedId, "Importiert", "aa CC DD EE GG PP spsp") });
var result = await Service(db, dir).RunAsync();
Assert.StartsWith("Ingestion successful!", result);
// Manual row is still there, unchanged.
var manual = await db.Gerbils.FindAsync(manualId);
Assert.NotNull(manual);
Assert.True(manual!.IsManual);
Assert.Equal("Handmaus", manual.Name);
// Imported row was loaded.
Assert.NotNull(await db.Gerbils.FindAsync(importedId));
Assert.Equal(2, await db.Gerbils.CountAsync());
}
// ── 2. Verified freeze forces the golden values over a drifted import ─
[Fact]
public async Task Verified_override_forces_golden_and_records_drift()
{
using var db = NewDb();
var dir = NewDir();
var id = new Guid("11111111-1111-1111-1111-111111111111");
// First ingest: import brings X in with the WRONG genotype/name.
WritePayload(dir, new[] { ImportGerbil(id, "Falschname", "aa dd DD EE GG PP spsp") });
var svc = Service(db, dir);
await svc.RunAsync();
// The breeder corrects X and marks it "vollständig korrekt".
var g = await db.Gerbils.FindAsync(id);
Assert.NotNull(g);
g!.Name = "Korrekt";
g.Genotype = "aa CC DD EE GG PP spsp";
await db.SaveChangesAsync();
var golden = await GerbilSnapshotService.BuildSnapshotAsync(db, id);
db.GerbilOverrides.Add(new GerbilOverride
{
Id = Guid.NewGuid(),
GerbilId = id,
EntityName = g.Name,
IsVerified = true,
OverrideJson = GerbilSnapshotService.BuildFreezeJson(g),
SnapshotJson = GerbilSnapshotService.SerializeSnapshot(golden!),
VerifiedAt = DateTimeOffset.UtcNow,
UpdatedAt = DateTimeOffset.UtcNow,
});
await db.SaveChangesAsync();
// A later import DRIFTS back to wrong values.
WritePayload(dir, new[] { ImportGerbil(id, "Wiederfalsch", "aa dd DD EE GG PP spsp") });
await svc.RunAsync();
// Golden wins (freeze re-applied on top of the fresh import).
var after = await db.Gerbils.FindAsync(id);
Assert.Equal("Korrekt", after!.Name);
Assert.Equal("aa CC DD EE GG PP spsp", after.Genotype);
// Drift was detected and recorded, naming the offending fields.
var ov = await db.GerbilOverrides.SingleAsync();
Assert.False(string.IsNullOrEmpty(ov.LastImportDiffJson));
Assert.Contains("genotype", ov.LastImportDiffJson);
Assert.Contains("name", ov.LastImportDiffJson);
Assert.NotNull(ov.LastImportSnapshotJson);
}
// ── 3. No drift → LastImportDiffJson stays null ──────────────────────
[Fact]
public async Task Verified_override_without_drift_leaves_diff_null()
{
using var db = NewDb();
var dir = NewDir();
var id = new Guid("22222222-2222-2222-2222-222222222222");
WritePayload(dir, new[] { ImportGerbil(id, "Stabil", "aa CC DD EE GG PP spsp") });
var svc = Service(db, dir);
await svc.RunAsync();
var g = await db.Gerbils.FindAsync(id);
var golden = await GerbilSnapshotService.BuildSnapshotAsync(db, id);
db.GerbilOverrides.Add(new GerbilOverride
{
Id = Guid.NewGuid(),
GerbilId = id,
EntityName = g!.Name,
IsVerified = true,
OverrideJson = GerbilSnapshotService.BuildFreezeJson(g),
SnapshotJson = GerbilSnapshotService.SerializeSnapshot(golden!),
VerifiedAt = DateTimeOffset.UtcNow,
UpdatedAt = DateTimeOffset.UtcNow,
});
await db.SaveChangesAsync();
// Re-ingest with the IDENTICAL payload (== golden).
await svc.RunAsync();
var ov = await db.GerbilOverrides.SingleAsync();
Assert.Null(ov.LastImportDiffJson);
}
// ── 4. Removing the override → import-driven again ───────────────────
[Fact]
public async Task Removing_override_restores_import_driven_values()
{
using var db = NewDb();
var dir = NewDir();
var id = new Guid("33333333-3333-3333-3333-333333333333");
WritePayload(dir, new[] { ImportGerbil(id, "Import-Wert", "aa CC DD EE GG PP spsp") });
var svc = Service(db, dir);
await svc.RunAsync();
var g = await db.Gerbils.FindAsync(id);
g!.Genotype = "aa cc DD EE GG PP spsp"; // "golden"
await db.SaveChangesAsync();
var golden = await GerbilSnapshotService.BuildSnapshotAsync(db, id);
var ov = new GerbilOverride
{
Id = Guid.NewGuid(),
GerbilId = id,
IsVerified = true,
OverrideJson = GerbilSnapshotService.BuildFreezeJson(g),
SnapshotJson = GerbilSnapshotService.SerializeSnapshot(golden!),
UpdatedAt = DateTimeOffset.UtcNow,
};
db.GerbilOverrides.Add(ov);
await db.SaveChangesAsync();
// Freeze wins while the override exists.
await svc.RunAsync();
Assert.Equal("aa cc DD EE GG PP spsp", (await db.Gerbils.FindAsync(id))!.Genotype);
// Remove the override → the animal follows the import again.
db.GerbilOverrides.Remove(ov);
await db.SaveChangesAsync();
await svc.RunAsync();
Assert.Equal("aa CC DD EE GG PP spsp", (await db.Gerbils.FindAsync(id))!.Genotype);
}
// ── 5. Per-field protection (pure service level) ─────────────────────
[Fact]
public void PerField_change_pins_only_the_changed_field()
{
var g = new Gerbil { Name = "Quelle", Notes = "alte Notiz", Genotype = "aa CC DD EE GG PP spsp" };
var before = GerbilSnapshotService.BuildFreezeObject(g);
g.Notes = "neue Notiz";
var after = GerbilSnapshotService.BuildFreezeObject(g);
var changed = GerbilSnapshotService.ChangedFields(before, after);
var only = Assert.Single(changed); // ONLY notes changed
Assert.Equal("notes", only.Key);
var merged = GerbilSnapshotService.MergeOverrideJson("{}", changed);
var mergedObj = JsonNode.Parse(merged)!.AsObject();
Assert.True(mergedObj.ContainsKey("notes"));
Assert.False(mergedObj.ContainsKey("genotype")); // untouched fields not pinned
// Applying it onto a different animal overwrites ONLY notes, not the genotype.
var target = new Gerbil { Name = "Ziel", Notes = "Ziel-Notiz", Genotype = "zz ZZ dd ee gg pp spsp" };
GerbilSnapshotService.ApplyOverride(target, merged);
Assert.Equal("neue Notiz", target.Notes);
Assert.Equal("zz ZZ dd ee gg pp spsp", target.Genotype);
}
// ── 6. Dangling reference from a manual row is nulled + warned ────────
[Fact]
public async Task Stale_parent_reference_from_manual_litter_is_nulled_with_warning()
{
using var db = NewDb();
var dir = NewDir();
var fatherId = new Guid("44444444-4444-4444-4444-444444444444");
// Ingest 1 brings in the (imported) father.
WritePayload(dir, new[] { ImportGerbil(fatherId, "Vater", "aa CC DD EE GG PP spsp", gender: "male") });
var svc = Service(db, dir);
await svc.RunAsync();
// The breeder wires a MANUAL litter to that imported father.
var litterId = Guid.NewGuid();
db.Litters.Add(new Litter { Id = litterId, Name = "Manueller Wurf", FatherId = fatherId, IsManual = true });
await db.SaveChangesAsync();
// Ingest 2 no longer contains the father → it becomes stale and is removed.
WritePayload(dir, Array.Empty<object>());
var result = await svc.RunAsync();
// The manual litter survives, but its dangling parent link was nulled...
var litter = await db.Litters.FindAsync(litterId);
Assert.NotNull(litter);
Assert.True(litter!.IsManual);
Assert.Null(litter.FatherId);
// ...and a warning was surfaced.
Assert.Contains("warning", result);
Assert.Contains("nicht mehr existiert", result);
// The stale imported father is gone.
Assert.Null(await db.Gerbils.FindAsync(fatherId));
}
// ── 7. Diff detects ancestry / offspring differences ─────────────────
[Fact]
public void Diff_detects_parent_and_children_differences()
{
var self = new SnapshotSelf(
"Proband", "female", "2022-01-01", null, null, null, "aa CC DD EE GG PP spsp",
null, "Schwarz", true, null, false, null, null, null, null,
new List<string>(), null, null);
var golden = new GerbilSnapshot(
self,
new SnapshotParent("Papa Alt", "2020-01-01", "aa CC"),
null,
new List<SnapshotLitter>
{
new("Wurf1", "2023-01-01", "mother", 3, true, new List<SnapshotChild>
{
new("Kind1", "2023-01-01", "female"),
}),
});
var other = new GerbilSnapshot(
self,
new SnapshotParent("Papa Neu", "2020-01-01", "aa CC"), // different father
null,
new List<SnapshotLitter>
{
new("Wurf1", "2023-01-01", "mother", 3, true, new List<SnapshotChild>
{
new("Kind1", "2023-01-01", "female"),
new("Kind2", "2023-01-02", "male"), // extra child
}),
});
var diffs = GerbilSnapshotService.Diff(golden, other);
Assert.NotEmpty(diffs);
Assert.Contains(diffs, d => d.Path == "father");
Assert.Contains(diffs, d => d.Path.StartsWith("wurf["));
}
}
}

View File

@@ -0,0 +1,151 @@
using System.Text.Json;
using GerbilManagerWebAPI.Import;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Xunit.Abstractions;
namespace GerbilManager.Tests
{
/// <summary>
/// Golden regression fixture: ingests the REAL <c>tools/import/output/resolved_import.json</c>
/// (gitignored, local only) and asserts that every verified key animal's Akte still matches its
/// frozen golden snapshot in <c>tools/import/verified-golden.json</c> (committed fixture).
///
/// Both files are optional: if EITHER is missing the test skips cleanly (no failure), so it is a
/// no-op on CI / fresh clones but a real guard on the breeder's machine once she has verified
/// animals and exported the fixture.
/// </summary>
public class VerifiedGoldenTests
{
private readonly ITestOutputHelper _out;
public VerifiedGoldenTests(ITestOutputHelper output) => _out = output;
private sealed record GoldenEntry(Guid GerbilId, string? Name, DateTimeOffset? VerifiedAt, GerbilSnapshot? Snapshot);
private static readonly JsonSerializerOptions Web = new(JsonSerializerDefaults.Web);
private static string? FindRepoRoot()
{
var dir = new DirectoryInfo(AppContext.BaseDirectory);
while (dir is not null)
{
if (Directory.Exists(Path.Combine(dir.FullName, "tools", "import")))
return dir.FullName;
dir = dir.Parent;
}
return null;
}
[Fact]
public async Task Verified_animals_still_match_their_golden_snapshot()
{
var repoRoot = FindRepoRoot();
if (repoRoot is null)
{
_out.WriteLine("SKIP: repo root (tools/import) not found from the test host.");
return;
}
var goldenPath = Path.Combine(repoRoot, "tools", "import", "verified-golden.json");
var outputDir = Path.Combine(repoRoot, "tools", "import", "output");
var resolvedPath = Path.Combine(outputDir, "resolved_import.json");
if (!File.Exists(goldenPath))
{
_out.WriteLine($"SKIP: golden fixture not present ({goldenPath}).");
return;
}
if (!File.Exists(resolvedPath))
{
_out.WriteLine($"SKIP: resolved_import.json not present ({resolvedPath}) — run the import pipeline.");
return;
}
List<GoldenEntry>? golden;
try
{
golden = JsonSerializer.Deserialize<List<GoldenEntry>>(await File.ReadAllTextAsync(goldenPath), Web);
}
catch (Exception ex)
{
_out.WriteLine($"SKIP: could not parse golden fixture: {ex.Message}");
return;
}
if (golden is null || golden.Count == 0)
{
_out.WriteLine("SKIP: golden fixture is empty.");
return;
}
// Ingest the real resolved_import.json into an InMemory DB.
var opts = new DbContextOptionsBuilder<ApplicationContext>()
.UseInMemoryDatabase("verified-golden-" + Guid.NewGuid().ToString("N"))
.Options;
using var db = new ApplicationContext(opts);
db.Database.EnsureCreated();
var photoDir = Path.Combine(Path.GetTempPath(), "verified-golden-photos-" + Guid.NewGuid().ToString("N"));
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
{ "Import:SourcePath", outputDir },
{ "Photos:RootPath", photoDir },
})
.Build();
try
{
var result = await new IngestResolvedService(db, config, null!).RunAsync();
Assert.StartsWith("Ingestion successful!", result);
}
catch (Exception ex)
{
_out.WriteLine($"SKIP: ingest of the real resolved_import.json failed: {ex.Message}");
return;
}
finally
{
try { Directory.Delete(photoDir, recursive: true); } catch { }
}
var mismatches = new List<string>();
int checkedCount = 0;
foreach (var entry in golden)
{
if (entry.Snapshot is null) continue;
checkedCount++;
GerbilSnapshot? actual;
try
{
actual = await GerbilSnapshotService.BuildSnapshotAsync(db, entry.GerbilId);
}
catch (Exception ex)
{
mismatches.Add($"• {entry.Name ?? entry.GerbilId.ToString()}: Akte konnte nicht gebaut werden — {ex.Message}");
continue;
}
if (actual is null)
{
mismatches.Add($"• {entry.Name ?? entry.GerbilId.ToString()}: fehlt im Import (verifiziertes Tier verschwunden).");
continue;
}
var diffs = GerbilSnapshotService.Diff(entry.Snapshot, actual);
if (diffs.Count > 0)
{
var fields = string.Join("; ", diffs.Select(d => $"{d.Path}: golden='{d.GoldenValue}' ≠ import='{d.OtherValue}'"));
mismatches.Add($"• {entry.Name ?? entry.GerbilId.ToString()}: {diffs.Count} Abweichung(en) — {fields}");
}
}
_out.WriteLine($"Golden-Fixture geprüft: {checkedCount} verifizierte Tiere, {mismatches.Count} abweichend.");
if (mismatches.Count > 0)
{
var report = $"Golden-Regression fehlgeschlagen — {mismatches.Count} von {checkedCount} verifizierten Tieren weichen vom eingefrorenen Snapshot ab:\n"
+ string.Join("\n", mismatches);
Assert.Fail(report);
}
}
}
}

View File

@@ -0,0 +1,204 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using GerbilManagerWebAPI.Import;
using GerbilManagerWebAPI.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace GerbilManager.Tests;
/// <summary>
/// WAITLIST (RennmausPro nachfrage_tb): the prospective-buyer waiting list.
/// - Full CRUD round-trip: POST -> GET (list + by id) -> PUT (status change) -> DELETE.
/// - Validation: an entry with neither contact nor name, and an unknown status, are 400.
/// - CRITICAL: waiting-list rows survive the import re-ingest wipe (loose, FK-free ContactId).
/// </summary>
public class WaitingListEndpointTests : IClassFixture<ApiFactory>
{
private readonly ApiFactory _factory;
public WaitingListEndpointTests(ApiFactory factory) => _factory = factory;
[Fact]
public async Task Crud_round_trip()
{
var client = _factory.CreateClient();
// CREATE
var contactId = Guid.NewGuid();
var create = await client.PostAsJsonAsync("/waiting-list", new
{
contactId,
contactName = "Familie Sonntag",
wishColor = "Schwarz",
wishGender = "female",
requestedAt = "2026-06-01T00:00:00Z",
status = "offen",
note = "möchte zwei Weibchen",
});
Assert.Equal(HttpStatusCode.Created, create.StatusCode);
var created = JsonDocument.Parse(await create.Content.ReadAsStringAsync()).RootElement;
var id = created.GetProperty("id").GetString()!;
Assert.Equal("offen", created.GetProperty("status").GetString());
Assert.Equal("Schwarz", created.GetProperty("wishColor").GetString());
Assert.Equal(contactId.ToString(), created.GetProperty("contactId").GetString());
// GET by id
var byId = JsonDocument.Parse(await client.GetStringAsync($"/waiting-list/{id}")).RootElement;
Assert.Equal("Familie Sonntag", byId.GetProperty("contactName").GetString());
// LIST contains it
var list = JsonDocument.Parse(await client.GetStringAsync("/waiting-list")).RootElement;
Assert.Contains(list.EnumerateArray(), e => e.GetProperty("id").GetString() == id);
// UPDATE: set fulfilled
var update = await client.PutAsJsonAsync($"/waiting-list/{id}", new
{
contactId,
contactName = "Familie Sonntag",
wishColor = "Schwarz",
wishGender = "female",
requestedAt = "2026-06-01T00:00:00Z",
status = "erfuellt",
note = "erledigt",
});
Assert.Equal(HttpStatusCode.OK, update.StatusCode);
var updated = JsonDocument.Parse(await update.Content.ReadAsStringAsync()).RootElement;
Assert.Equal("erfuellt", updated.GetProperty("status").GetString());
// DELETE
var del = await client.DeleteAsync($"/waiting-list/{id}");
Assert.Equal(HttpStatusCode.NoContent, del.StatusCode);
var after = await client.GetAsync($"/waiting-list/{id}");
Assert.Equal(HttpStatusCode.NotFound, after.StatusCode);
}
[Fact]
public async Task Post_rejects_empty_contact_and_name()
{
var client = _factory.CreateClient();
var resp = await client.PostAsJsonAsync("/waiting-list", new { status = "offen", wishColor = "Gold" });
Assert.Equal(HttpStatusCode.BadRequest, resp.StatusCode);
}
[Fact]
public async Task Post_rejects_unknown_status()
{
var client = _factory.CreateClient();
var resp = await client.PostAsJsonAsync("/waiting-list", new { contactName = "Test", status = "irgendwas" });
Assert.Equal(HttpStatusCode.BadRequest, resp.StatusCode);
}
[Fact]
public async Task Empty_status_defaults_to_offen()
{
var client = _factory.CreateClient();
var resp = await client.PostAsJsonAsync("/waiting-list", new { contactName = "Ohne Status" });
Assert.Equal(HttpStatusCode.Created, resp.StatusCode);
var created = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement;
Assert.Equal("offen", created.GetProperty("status").GetString());
}
[Fact]
public async Task WaitingList_survives_ingest_wipe()
{
// Fresh in-memory DB seeded with a resolved import file (mirrors FeedbackEndpointTests).
var dir = Path.Combine(Path.GetTempPath(), "waitlist-ingest-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
try
{
var contactId = Guid.NewGuid();
var fatherId = Guid.NewGuid();
var motherId = Guid.NewGuid();
var litterId = Guid.NewGuid();
var data = new
{
Contacts = new[]
{
new { Id = contactId, Name = "Test Breeder", Email = "t@e.de", Phone = "", Address = "", Notes = (string?)null, IsBreeder = true, IsReceiver = false, NameSuffix = (string?)null, Provenance = (string?)null }
},
Litters = new[]
{
new { Id = litterId, Name = "Wurf A", Date = "2026-01-01", TotalBorn = 5, DeathsWithin8Weeks = 0, FatherId = fatherId, MotherId = motherId, ExpectedGoHomeDate = (string?)null, Notes = "", PairingCode = "PC01", ExternalRef = "ext-litter-1", LitterLetter = "A" }
},
Gerbils = new[]
{
Animal(fatherId, "Papa", "male", contactId),
Animal(motherId, "Mama", "female", contactId),
},
GerbilPhotos = Array.Empty<object>(),
};
File.WriteAllText(Path.Combine(dir, "resolved_import.json"), JsonSerializer.Serialize(data));
var opts = new DbContextOptionsBuilder<ApplicationContext>()
.UseInMemoryDatabase("waitlist-ingest-" + Guid.NewGuid().ToString("N"))
.Options;
using var db = new ApplicationContext(opts);
db.Database.EnsureCreated();
// A waiting-list entry referencing the contact that the wipe will delete.
var entryId = Guid.NewGuid();
db.WaitingListEntries.Add(new WaitingListEntry
{
Id = entryId,
ContactId = contactId,
ContactName = "Test Breeder",
WishColor = "Schwarz",
WishGender = "female",
RequestedAt = DateTime.UtcNow,
Status = "offen",
Note = "wartet",
CreatedAt = DateTimeOffset.UtcNow,
});
await db.SaveChangesAsync();
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?> { { "Import:SourcePath", dir } })
.Build();
// Run the ingest wipe + reload.
var result = await new IngestResolvedService(db, config, null!).RunAsync();
Assert.Contains("Ingestion successful!", result);
// Contacts were wiped & re-created, but the waiting-list entry is untouched.
var survivor = await db.WaitingListEntries.SingleAsync(e => e.Id == entryId);
Assert.Equal(contactId, survivor.ContactId); // loose id preserved even though the contact row was deleted/recreated
Assert.Equal("Test Breeder", survivor.ContactName);
Assert.Equal("offen", survivor.Status);
Assert.Equal(1, await db.WaitingListEntries.CountAsync());
}
finally
{
try { Directory.Delete(dir, recursive: true); } catch { /* best effort */ }
}
}
private static object Animal(Guid id, string name, string gender, Guid contactId) => new
{
Id = id,
Name = name,
Gender = gender,
Status = "Breeding",
LitterId = (Guid?)null,
OriginContactId = contactId,
ReceiverContactId = (Guid?)null,
EnclosureId = (Guid?)null,
ColorVarietyId = new Guid("00000000-0000-0000-0000-000000000006"),
DateOfBirth = "2025-01-01",
DateOfDeath = (string?)null,
CauseOfDeath = (string?)null,
GoHomeDate = (string?)null,
Genotype = "aa CC DD EE GG PP spsp rere",
Notes = "",
ImportSource = "docx-export",
ExternalRef = "ext-" + name,
RawImportData = "{}",
OriginBreeder = "Test Zucht",
NameSearch = name.ToLowerInvariant(),
CharacterTraits = Array.Empty<string>(),
CharacterNote = (string?)null,
IsDeaf = false,
IsResident = true,
};
}

View File

@@ -1,124 +0,0 @@
{
"info": {
"_postman_id": "2b7d1860-b8d4-44d1-8548-be847b925c74",
"name": "GerbilManager",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
"_exporter_id": "19567620"
},
"item": [
{
"name": "Gerbils",
"item": [
{
"name": "Get All Gerbil",
"protocolProfileBehavior": {
"strictSSL": false
},
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "{{base}}/Gerbils",
"host": [
"{{base}}"
],
"path": [
"Gerbils"
]
}
},
"response": []
},
{
"name": "Post random Gerbil",
"protocolProfileBehavior": {
"disabledSystemHeaders": {
"content-type": true
}
},
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\r\n \"name\": \"{{$randomFirstName}}\",\r\n \"gender\": {{randomGender}}\r\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{base}}/Gerbils",
"host": [
"{{base}}"
],
"path": [
"Gerbils"
]
}
},
"response": []
}
]
}
],
"event": [
{
"listen": "prerequest",
"script": {
"type": "text/javascript",
"exec": [
"pm.globals.set('randomGender', Math.floor(Math.random() * 2)+1);"
]
}
},
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
""
]
}
}
],
"variable": [
{
"key": "base_url",
"value": "https://localhost",
"type": "string"
},
{
"key": "portDebug",
"value": "7191",
"type": "string"
},
{
"key": "portProductive",
"value": "80",
"type": "string"
},
{
"key": "rootD",
"value": "http://localhost",
"type": "string"
},
{
"key": "rootR",
"value": "http://localhost",
"type": "string"
},
{
"key": "base",
"value": "{{base_url}}:{{portDebug}}",
"type": "string"
}
]
}

View File

@@ -13,6 +13,7 @@ public class ApplicationContext : DbContext
public DbSet<Enclosure> Enclosures => Set<Enclosure>();
public DbSet<ColorVariety> ColorVarieties => Set<ColorVariety>();
public DbSet<GerbilPhoto> GerbilPhotos => Set<GerbilPhoto>();
public DbSet<EnclosurePhoto> EnclosurePhotos => Set<EnclosurePhoto>();
public DbSet<HealthRecord> HealthRecords => Set<HealthRecord>();
public DbSet<WeightRecord> WeightRecords => Set<WeightRecord>();
public DbSet<SaleContract> SaleContracts => Set<SaleContract>();
@@ -23,6 +24,15 @@ public class ApplicationContext : DbContext
public DbSet<Media> Media => Set<Media>();
public DbSet<Request> Requests => Set<Request>();
public DbSet<MailSettings> MailSettings => Set<MailSettings>();
public DbSet<Feedback> Feedback => Set<Feedback>();
public DbSet<FeedbackAttachment> FeedbackAttachments => Set<FeedbackAttachment>();
public DbSet<WebPushSubscription> WebPushSubscriptions => Set<WebPushSubscription>();
public DbSet<AcquisitionRecord> AcquisitionRecords => Set<AcquisitionRecord>();
public DbSet<SaleReservation> SaleReservations => Set<SaleReservation>();
public DbSet<WaitingListEntry> WaitingListEntries => Set<WaitingListEntry>();
public DbSet<ReturnRecord> ReturnRecords => Set<ReturnRecord>();
public DbSet<ExhibitionResult> ExhibitionResults => Set<ExhibitionResult>();
public DbSet<GerbilOverride> GerbilOverrides => Set<GerbilOverride>();
// Keep Gerbil.NameSearch in sync on every save (separator-insensitive search key),
// so it can never drift from Name regardless of which code path mutates the entity.
@@ -65,6 +75,10 @@ public class ApplicationContext : DbContext
// Residency defaults to true (own stock unless explicitly marked external).
e.Property(g => g.IsResident).HasDefaultValue(true);
// Manual-flag defaults false: every pre-existing / imported row is import-driven.
// Only POST /gerbils sets it true, so the ingest wipe never touches manual animals.
e.Property(g => g.IsManual).HasDefaultValue(false);
// DB-4: German collation on searched/sorted name fields (Npgsql-only).
if (isNpgsql)
{
@@ -116,6 +130,8 @@ public class ApplicationContext : DbContext
e.HasIndex(l => l.ExternalRef)
.IsUnique()
.HasFilter("\"ExternalRef\" IS NOT NULL");
e.Property(l => l.IsManual).HasDefaultValue(false);
});
modelBuilder.Entity<HealthRecord>(e =>
@@ -133,6 +149,10 @@ public class ApplicationContext : DbContext
e.HasOne<Gerbil>().WithMany()
.HasForeignKey(p => p.GerbilId).OnDelete(DeleteBehavior.Cascade));
modelBuilder.Entity<EnclosurePhoto>(e =>
e.HasOne<Enclosure>().WithMany()
.HasForeignKey(p => p.EnclosureId).OnDelete(DeleteBehavior.Cascade));
// FEAT-13: Abgabeverträge + Zuchtprofil.
modelBuilder.Entity<SaleContract>(e =>
{
@@ -197,6 +217,77 @@ public class ApplicationContext : DbContext
modelBuilder.Entity<MailSettings>()
.HasData(new MailSettings { Id = GerbilManagerWebAPI.Models.MailSettings.SingletonId });
// FEEDBACK: deliberately relationship-free. GerbilId/LitterId are plain nullable
// Guid columns (no navigation properties → EF creates NO foreign key), so the
// import re-ingest wipe of Gerbils/Litters never cascades into — or breaks —
// feedback rows. They survive re-ingest, which is the whole point.
modelBuilder.Entity<Feedback>(e =>
{
e.HasIndex(f => f.CreatedAt);
});
// ERWERB: like Feedback, deliberately relationship-free. GerbilId/SourceContactId
// are plain nullable Guid columns (no navigation properties → EF creates NO foreign
// key), so the import re-ingest wipe of Gerbils/Contacts never cascades into — or
// breaks — acquisition rows. They survive re-ingest, which is the whole point.
modelBuilder.Entity<AcquisitionRecord>(e =>
{
e.Property(a => a.Price).HasPrecision(10, 2);
e.HasIndex(a => a.GerbilId);
});
// ABGABE-STATUS: deliberately relationship-free (same rationale as Feedback).
// GerbilId/ReservedForContactId are plain Guid columns (no navigation properties →
// EF creates NO foreign key), so the import re-ingest wipe of Gerbils/Contacts never
// cascades into — or breaks — reservation rows. They survive re-ingest by design.
modelBuilder.Entity<SaleReservation>(e =>
{
e.Property(r => r.Price).HasPrecision(10, 2);
e.HasIndex(r => r.GerbilId);
});
// WAITLIST: same relationship-free pattern as Feedback. ContactId is a plain
// nullable Guid column (no navigation property → EF creates NO foreign key), so
// the import re-ingest wipe of Contacts never cascades into — or breaks —
// waiting-list rows. They survive re-ingest, which is the whole point.
modelBuilder.Entity<WaitingListEntry>(e =>
{
e.HasIndex(w => w.CreatedAt);
});
// RÜCKNAHMEN (getback_tb): wie Feedback bewusst beziehungsfrei. GerbilId/
// FromContactId sind einfache nullable Guid-Spalten (keine Navigation → EF legt
// KEINEN Foreign Key an), damit der Import-Re-Ingest-Wipe von Gerbils/Contacts
// diese Zeilen weder löscht noch bricht. Sie überleben den Re-Ingest.
modelBuilder.Entity<ReturnRecord>(e =>
{
e.Property(r => r.ReturnPrice).HasPrecision(10, 2);
e.Property(r => r.OriginalPrice).HasPrecision(10, 2);
e.HasIndex(r => r.GerbilId);
e.HasIndex(r => r.CreatedAt);
});
// EXHIBITION: deliberately relationship-free (same pattern as Feedback). GerbilId is a
// plain nullable Guid column (no navigation property → EF creates NO foreign key), so the
// import re-ingest wipe of Gerbils never cascades into or breaks exhibition rows.
modelBuilder.Entity<ExhibitionResult>(e =>
{
e.HasIndex(x => x.GerbilId);
});
// VERIFIED/PROTECTED OVERRIDE: deliberately relationship-free (same pattern as Feedback).
// GerbilId is a plain Guid column (no navigation property → EF creates NO foreign key), so
// the import re-ingest wipe of Gerbils never cascades into — or breaks — override rows. They
// survive re-ingest and are re-applied on top of the fresh import (the freeze), which is the
// whole point.
modelBuilder.Entity<GerbilOverride>(e =>
{
e.HasIndex(o => o.GerbilId).IsUnique();
});
// Manual-flag default false for Contact (imported/pre-existing rows are import-driven).
modelBuilder.Entity<Contact>().Property(c => c.IsManual).HasDefaultValue(false);
// DB-4: German collation on remaining searched/sorted text columns (Npgsql-only).
if (isNpgsql)
{
@@ -233,9 +324,9 @@ public class ApplicationContext : DbContext
(int n, string Slug, string Title, string BodyMd)[] legalPages =
{
(7, "impressum", "Impressum",
"**Angaben gemäß § 5 TMG**\\n\\nSeitenbetreiber: [Name und vollständige Adresse eintragen]\\n\\nE-Mail: [E-Mail-Adresse eintragen]\\n\\n---\\n\\n*Diese Seite wird vom Seitenbetreiber noch vervollständigt.*"),
"## Angaben gemäß § 18 Abs. 1 MStV\\n\\n[Vor- und Nachname]\\n[Straße und Hausnummer]\\n[PLZ und Ort]\\n\\n## Kontakt\\n\\nE-Mail: [E-Mail-Adresse]\\nTelefon: [Telefonnummer]\\n\\n---\\n\\nDiese Seite stellt eine private Hobbyzucht mongolischer Rennmäuse ohne Gewinnerzielungsabsicht vor.\\n\\n*Hinweis für den Seitenbetreiber: Name und ladungsfähige Anschrift (kein Postfach) sind Pflicht (§ 18 Abs. 1 MStV). Sollte die Zucht jemals gewerblich bzw. geschäftsmäßig betrieben werden, gelten zusätzlich § 5 DDG (vollständiges Anbieter-Impressum) und ggf. die Erlaubnispflicht nach § 11 TierSchG — dann zuständige Behörde und Aktenzeichen hier ergänzen. Kein Hinweis auf die EU-Streitbeilegungsplattform: diese wurde zum 20.07.2025 abgeschaltet (ein fortbestehender Link wäre irreführend).*"),
(8, "datenschutz", "Datenschutz",
"**Datenschutzerklärung**\\n\\nDiese Webseite dient der Vorstellung unserer Rennmauszucht. Es werden keine personenbezogenen Daten gespeichert oder weitergegeben.\\n\\nBei datenschutzbezogenen Fragen: [E-Mail-Adresse eintragen]\\n\\n---\\n\\n*Diese Seite wird vom Seitenbetreiber noch vervollständigt.*"),
"## Datenschutzerklärung\\n\\n## 1. Verantwortlicher\\n\\nVerantwortlich für die Datenverarbeitung auf dieser Webseite ist:\\n[Vor- und Nachname]\\n[Straße und Hausnummer]\\n[PLZ und Ort]\\nE-Mail: [E-Mail-Adresse]\\n\\n## 2. Hosting und Server-Logfiles\\n\\nDiese Webseite wird auf einem eigenen Server betrieben. Beim Aufruf der Seite verarbeitet der Server automatisch Informationen, die dein Browser übermittelt, in sogenannten Server-Logfiles: IP-Adresse, Datum und Uhrzeit des Zugriffs, die aufgerufene Seite bzw. Datei, die übertragene Datenmenge sowie Browser und Betriebssystem.\\nDiese Verarbeitung ist technisch erforderlich, um die Webseite auszuliefern und ihren sicheren und stabilen Betrieb zu gewährleisten. Rechtsgrundlage ist Art. 6 Abs. 1 lit. f DSGVO (berechtigtes Interesse am störungsfreien Betrieb und an der Sicherheit). Die Logfiles werden nach spätestens [z. B. 7] Tagen gelöscht und nicht mit anderen Daten zusammengeführt.\\n\\n## 3. Cookies, Tracking und externe Dienste\\n\\nDiese Webseite verwendet keine Cookies, kein Tracking und keine Analyse- oder Marketing-Dienste. Es werden keine externen Inhalte Dritter (z. B. Schriftarten, Karten, Videos, CDNs) nachgeladen.\\n\\n## 4. Kontaktaufnahme\\n\\nWenn du uns per E-Mail kontaktierst, verarbeiten wir deine Angaben (z. B. Name, E-Mail-Adresse, Inhalt der Nachricht) ausschließlich zur Bearbeitung deiner Anfrage. Rechtsgrundlage ist Art. 6 Abs. 1 lit. b DSGVO bzw. Art. 6 Abs. 1 lit. f DSGVO. Die Daten werden gelöscht, sobald sie nicht mehr benötigt werden und keine gesetzlichen Aufbewahrungspflichten entgegenstehen.\\n\\n## 5. Empfänger der Daten\\n\\nEine Weitergabe deiner Daten an Dritte findet nicht statt. Eine Datenübermittlung in Länder außerhalb der EU bzw. des EWR erfolgt nicht.\\n\\n## 6. Deine Rechte\\n\\nDu hast jederzeit das Recht auf:\\n- Auskunft über die zu deiner Person gespeicherten Daten (Art. 15 DSGVO)\\n- Berichtigung unrichtiger Daten (Art. 16 DSGVO)\\n- Löschung (Art. 17 DSGVO)\\n- Einschränkung der Verarbeitung (Art. 18 DSGVO)\\n- Datenübertragbarkeit (Art. 20 DSGVO)\\n- Widerspruch gegen die Verarbeitung (Art. 21 DSGVO)\\n\\nZur Ausübung genügt eine formlose Nachricht an die oben genannte E-Mail-Adresse.\\n\\n## 7. Beschwerderecht bei der Aufsichtsbehörde\\n\\nDu hast das Recht, dich bei einer Datenschutz-Aufsichtsbehörde zu beschweren (Art. 77 DSGVO). Zuständig ist die Aufsichtsbehörde deines Bundeslandes bzw. des Seitenbetreibers: [zuständige Landesdatenschutzbehörde eintragen].\\n\\n## 8. Keine automatisierte Entscheidungsfindung\\n\\nEine automatisierte Entscheidungsfindung einschließlich Profiling nach Art. 22 DSGVO findet nicht statt.\\n\\n---\\n\\n*Hinweis für den Seitenbetreiber: Platzhalter in eckigen Klammern ausfüllen. Aufbewahrungsdauer der Logfiles an deinen Server bzw. Reverse-Proxy anpassen. Sobald externe Dienste oder ein Kontaktformular eingebunden werden, diesen Text ergänzen. Stand: [Datum eintragen].*"),
};
var pageRows = new List<Page>();
@@ -282,79 +373,100 @@ public class ApplicationContext : DbContext
/// </summary>
private static void SeedColorVarieties(ModelBuilder modelBuilder)
{
// GEN-3g (Kevin): 5 CP-*-Hell variants appended at the end (IDs 62-66).
// Existing 61 entries are UNCHANGED (same ID->Name binding preserved).
// SortOrder for new entries is appended; Kevin's frontend catalog handles
// the interleaved display order via its own sortOrder values.
(string Name, string Genotype)[] catalog =
// CATALOG-RESEED (AR-5 / colorVarietySeed.backend.json): 70 entries, frozen symbols.
// ID = array_index + 1 (stable, never changes — live FKs safe).
// SortOrder comes from colorVarietySeed.backend.json (decoupled from ID).
// New entries appended at end (IDs 67-70: Dilute Algierfuchs/Goldfuchs/Rotfuchs/Polarfuchs).
// GUARDRAIL: DO NOT reseed from colorVarietySeed.generated.json — it uses bracket display
// notation (e[f]/c[chm]) which breaks CR-11 GenotypePotentiallyMatches() (frozen vs brackets).
(string Name, string Genotype, int SortOrder)[] catalog =
{
("Pink Eyed White (PEW)", "AA chch DD EE GG pp spsp rere"),
("Hermelin", "aa chch DD EE GG PP spsp rere"),
("Himalaya", "AA chch DD EE GG PP spsp rere"),
("Zobel", "aa cchmcchm DD EE gg PP spsp rere"),
("Rotaugenschimmel", "AA CC DD efef GG pp spsp rere"),
("Agouti", "AA CC DD EE GG PP spsp rere"),
("Schwarz", "aa CC DD EE GG PP spsp rere"),
("Silberagouti", "AA CC DD EE gg PP spsp rere"),
("Anthrazit", "aa CC DD EE gg PP spsp rere"),
("Algierfuchs", "AA CC DD ee GG PP spsp rere"),
("Blau", "aa CC dd EE GG PP spsp rere"),
("Gold", "AA CC DD EE GG pp spsp rere"),
("Platin", "aa CC DD EE GG pp spsp rere"),
("Goldfuchs", "AA CC DD ee GG pp spsp rere"),
("Rotfuchs", "aa CC DD ee GG pp spsp rere"),
("dd Gold", "AA CC dd EE GG pp spsp rere"),
("dd Platin", "aa CC dd EE GG pp spsp rere"),
("Altweiss (REW)", "aa CC DD EE gg pp spsp rere"),
("Apricot (Blassfuchs)", "AA CC DD ee gg pp spsp rere"),
("Blaufuchs", "aa CC DD ee gg PP spsp rere"),
("C-Separator", "aa CC DD ee gg pp spsp rere"),
("Elfenbein", "AA CC DD EE gg pp spsp rere"),
("Kohlfuchs", "aa CC DD ee GG PP spsp rere"),
("Polarfuchs", "AA CC DD ee gg PP spsp rere"),
("Saphir", "aa CC DD EE GG pp spsp rere"),
("Orangeschimmel", "AA CC DD efef GG PP spsp rere"),
("Topas", "AA CC DD EE GG pp spsp rere"),
("Platin-Hell", "aa CC DD EE GG pp spsp rere"),
("Agouti dd", "AA CC dd EE GG PP spsp rere"),
("Silberagouti dd", "AA CC dd EE gg PP spsp rere"),
("Kohlfuchs dd", "aa CC dd ee GG PP spsp rere"),
("Anthrazit dd", "aa CC dd EE gg PP spsp rere"),
("Silberschimmel", "AA CC DD efef gg PP spsp rere"),
("Polarfuchsschimmel", "AA CC DD efef gg PP spsp rere"),
("Algierfuchsschimmel", "AA CC DD efef GG PP spsp rere"),
("Kohlfuchsschimmel", "aa CC DD efef GG PP spsp rere"),
("Blaufuchsschimmel", "aa CC DD efef gg PP spsp rere"),
("Kohlfuchs, hell", "aa CC DD ee GG PP spsp rere"),
("Goldfuchs, hell", "AA CC DD ee GG pp spsp rere"),
("Goldfuchsschimmel", "AA CC DD efef GG pp spsp rere"),
("Gold-Hell", "AA CC DD EE GG pp spsp rere"),
("Blaufuchs, hell", "aa CC DD ee gg PP spsp rere"),
("Rotfuchsschimmel", "aa CC DD efef GG pp spsp rere"),
("Polarfuchs, hell", "AA CC DD ee gg PP spsp rere"),
("Kohlfuchsschimmel, hell", "aa CC DD efef GG PP spsp rere"),
("Rotfuchs, hell", "aa CC DD ee GG pp spsp rere"),
("Kohlfuchs-Hell", "aa CC DD ee GG PP spsp rere"),
("Algierfuchs, hell", "AA CC DD ee GG PP spsp rere"),
("Topas dd", "AA CC dd EE GG pp spsp rere"),
("Blaufuchs dd", "aa CC dd ee gg pp spsp rere"),
("Marder", "aa cchmcchm DD EE GG PP spsp rere"),
("Siam", "aa cchmch DD EE GG PP spsp rere"),
("Zobel-Hell", "aa cchmch DD EE gg PP spsp rere"),
("CP-Agouti", "AA cchmcchm DD EE GG PP spsp rere"),
("CP-Silberagouti", "AA cchmcchm DD EE gg PP spsp rere"),
("CP-Algierfuchs", "AA cchmcchm DD ee GG PP spsp rere"),
("CP-Polarfuchs", "AA cchmcchm DD ee gg PP spsp rere"),
("CP-Fuchs", "AA cchmcchm dd ee GG PP spsp rere"),
("CP-Fuchs-Hell", "AA cchmch dd ee GG PP spsp rere"),
("CP-Blaufuchs", "AA cchmcchm dd ee gg PP spsp rere"),
("CP-Orangeschimmel", "AA cchmcchm DD efef GG PP spsp rere"),
// GEN-3g: 5 new CP-*-Hell variants appended (IDs 62-66, no ID->Name drift)
("CP-Agouti-Hell", "AA cchmch DD EE GG PP spsp rere"),
("CP-Silberagouti-Hell", "AA cchmch DD EE gg PP spsp rere"),
("CP-Algierfuchs-Hell", "AA cchmch DD ee GG PP spsp rere"),
("CP-Polarfuchs-Hell", "AA cchmch DD ee gg PP spsp rere"),
("CP-Orangeschimmel-Hell","AA cchmch DD efef GG PP spsp rere"),
// --- C-locus white / partial albino (IDs 1-3) ---
("REW", "AA chch DD EE GG pp spsp rere", 0),
("Hermelin", "aa chch DD EE GG PP spsp rere", 1),
("Himalaya", "AA chch DD EE GG PP spsp rere", 2),
// --- Zobel / colourpoint dark (ID 4) ---
("Zobel", "aa cchmcchm DD EE gg PP spsp rere", 3),
// --- Schimmel family (IDs 5) ---
("Rotaugenschimmel", "AA CC DD efef GG pp spsp rere", 4),
// --- Standard colours (IDs 6-15) ---
("Agouti", "AA CC DD EE GG PP spsp rere", 5),
("Schwarz", "aa CC DD EE GG PP spsp rere", 6),
("Silberagouti","AA CC DD EE gg PP spsp rere", 7),
("Anthrazit", "aa CC DD EE gg PP spsp rere", 8),
("Algierfuchs", "AA CC DD ee GG PP spsp rere", 9),
("Blau", "aa CC dd EE GG PP spsp rere", 10),
("Gold", "AA CC DD EE GG pp spsp rere", 11),
("Platin", "aa CC DD EE GG pp spsp rere", 12),
("Goldfuchs", "AA CC DD ee GG pp spsp rere", 13),
("Rotfuchs", "aa CC DD ee GG pp spsp rere", 14),
// --- Dilute (dd) standard (IDs 16-17) ---
("Dilute Gold", "AA CC dd EE GG pp spsp rere", 15),
("Dilute Platin","aa CC dd EE GG pp spsp rere", 16),
// --- REW / Apricot / misc C-locus (IDs 18-28) ---
("Altweiss (REW)", "aa CC DD EE gg pp spsp rere", 17),
("Apricot (Blassfuchs)","AA CC DD ee gg pp spsp rere", 18),
("Blaufuchs", "aa CC DD ee gg PP spsp rere", 19),
("C-Separator", "aa CC DD ee gg pp spsp rere", 20),
("Elfenbein", "AA CC DD EE gg pp spsp rere", 21),
("Kohlfuchs", "aa CC DD ee GG PP spsp rere", 22),
("Polarfuchs", "AA CC DD ee gg PP spsp rere", 23),
("Saphir", "aa CC DD EE GG pp spsp rere", 24),
("Orangeschimmel","AA CC DD efef GG PP spsp rere", 25),
("Topas", "AA CC DD EE GG pp spsp rere", 26),
("Platin-Hell", "aa CC DD EE GG pp spsp rere", 27),
// --- Dilute (dd) varieties (IDs 29-32) ---
("Dilute Agouti", "AA CC dd EE GG PP spsp rere", 28),
("Dilute Silberagouti","AA CC dd EE gg PP spsp rere", 29),
("Dilute Kohlfuchs", "aa CC dd ee GG PP spsp rere", 30),
("Dilute Anthrazit", "aa CC dd EE gg PP spsp rere", 31),
// --- Schimmel / Fuchsschimmel (IDs 33-37) ---
("Silberschimmel", "AA CC DD efef gg PP spsp rere", 36),
// GEN-5 (ticket 5826e8e2): *Fuchsschimmel = HET ef/e (internal 'efe'),
// not hom ef/ef — a Schimmel-modified Fox. Pure *schimmel stay efef.
("Polarfuchsschimmel", "AA CC DD efe gg PP spsp rere", 37),
("Algierfuchsschimmel", "AA CC DD efe GG PP spsp rere", 38),
("Kohlfuchsschimmel", "aa CC DD efe GG PP spsp rere", 39),
("Blaufuchsschimmel", "aa CC DD efe gg PP spsp rere", 40),
// --- Hell variants (IDs 38-48) ---
("Kohlfuchs, hell", "aa CC DD ee GG PP spsp rere", 41),
("Goldfuchs, hell", "AA CC DD ee GG pp spsp rere", 42),
("Goldfuchsschimmel", "AA CC DD efe GG pp spsp rere", 43),
("Gold-Hell", "AA CC DD EE GG pp spsp rere", 44),
("Blaufuchs, hell", "aa CC DD ee gg PP spsp rere", 45),
("Rotfuchsschimmel", "aa CC DD efe GG pp spsp rere", 46),
("Polarfuchs, hell", "AA CC DD ee gg PP spsp rere", 47),
("Kohlfuchsschimmel, hell","aa CC DD efe GG PP spsp rere", 48),
("Rotfuchs, hell", "aa CC DD ee GG pp spsp rere", 49),
("Kohlfuchs-Hell", "aa CC DD ee GG PP spsp rere", 50),
("Algierfuchs, hell", "AA CC DD ee GG PP spsp rere", 51),
// --- Dilute (dd) renamed variants (IDs 49-50) ---
("Dilute Topas", "AA CC dd EE GG pp spsp rere", 52),
// GEN-5 (ticket 3deab547): Blaufuchs is black-eyed; dilution is P-independent.
("Dilute Blaufuchs","aa CC dd ee gg PP spsp rere", 53),
// --- Marder / Siam / CP- series (IDs 51-66) ---
("Marder", "aa cchmcchm DD EE GG PP spsp rere", 54),
("Siam", "aa cchmch DD EE GG PP spsp rere", 55),
("Zobel-Hell","aa cchmch DD EE gg PP spsp rere", 56),
("CP-Agouti", "AA cchmcchm DD EE GG PP spsp rere", 57),
("CP-Silberagouti","AA cchmcchm DD EE gg PP spsp rere", 59),
("CP-Algierfuchs", "AA cchmcchm DD ee GG PP spsp rere", 61),
("CP-Polarfuchs", "AA cchmcchm DD ee gg PP spsp rere", 63),
("CP-Fuchs", "AA cchmcchm dd ee GG PP spsp rere", 65),
("CP-Fuchs-Hell", "AA cchmch dd ee GG PP spsp rere", 66),
("CP-Blaufuchs", "AA cchmcchm dd ee gg PP spsp rere", 67),
("CP-Orangeschimmel","AA cchmcchm DD efef GG PP spsp rere", 68),
// GEN-3g / CATALOG-RESEED: CP-*-Hell interleaved (IDs 62-66, SortOrders from backend.json)
("CP-Agouti-Hell", "AA cchmch DD EE GG PP spsp rere", 58),
("CP-Silberagouti-Hell", "AA cchmch DD EE gg PP spsp rere", 60),
("CP-Algierfuchs-Hell", "AA cchmch DD ee GG PP spsp rere", 62),
("CP-Polarfuchs-Hell", "AA cchmch DD ee gg PP spsp rere", 64),
("CP-Orangeschimmel-Hell","AA cchmch DD efef GG PP spsp rere", 69),
// CATALOG-RESEED: 4 new Dilute (dd) Fuchs varieties appended (IDs 67-70)
("Dilute Algierfuchs","AA CC dd ee GG PP spsp rere", 32),
("Dilute Goldfuchs", "AA CC dd ee GG pp spsp rere", 33),
("Dilute Rotfuchs", "aa CC dd ee GG pp spsp rere", 34),
("Dilute Polarfuchs", "AA CC dd ee gg PP spsp rere", 35),
};
var rows = new ColorVariety[catalog.Length];
@@ -362,11 +474,11 @@ public class ApplicationContext : DbContext
{
rows[i] = new ColorVariety
{
// Stable, deterministic GUIDs so the HasData seed is migration-stable.
// Stable, deterministic GUIDs — ID = array_index + 1 (never reorder existing entries).
Id = new Guid($"00000000-0000-0000-0000-{(i + 1):D12}"),
Name = catalog[i].Name,
CanonicalGenotype = catalog[i].Genotype,
SortOrder = i,
SortOrder = catalog[i].SortOrder,
};
}
modelBuilder.Entity<ColorVariety>().HasData(rows);

View File

@@ -0,0 +1,16 @@
namespace GerbilManagerWebAPI.Cms
{
/// <summary>
/// WEB-2: path where POST /api/publish writes the rendered static site.
/// Env var: PublicSite__RootPath (empty = publish disabled, returns 503).
/// In production this volume is shared with the publicsite-nginx container.
/// </summary>
public sealed class PublicSiteOptions
{
public const string SectionName = "PublicSite";
public string? RootPath { get; set; }
public bool IsConfigured => !string.IsNullOrWhiteSpace(RootPath);
}
}

View File

@@ -13,11 +13,14 @@ public sealed record ContractBuyer(
/// <param name="Geschlecht">Deutscher Anzeigetext („Weiblich“/„Männlich“) — die
/// Abbildung vom <c>Gender</c>-Enum passiert im Aufrufer (Phase B), der
/// Generator bleibt frei von Modell-Abhängigkeiten.</param>
/// <param name="Photo">Optionales Tierfoto (Rohbytes der Bilddatei) fürs Vertragsbild;
/// nur der PDF-Generator wertet es aus, der .docx-Generator ignoriert es.</param>
public sealed record ContractAnimal(
string Name,
string Geschlecht,
DateOnly? Geburtsdatum = null,
string? Farbschlag = null);
string? Farbschlag = null,
byte[]? Photo = null);
/// <summary>
/// Alle Eingaben des Vertragsgenerators. Reines Daten-Objekt, keine EF-Typen.

View File

@@ -0,0 +1,241 @@
using System.Globalization;
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
namespace GerbilManagerWebAPI.Contracts;
/// <summary>
/// FEAT-13 (PDF): erzeugt den Abgabevertrag als druckfertiges PDF (A4) aus
/// <see cref="ContractData"/> — gleiche Daten wie der .docx-Generator, reiner
/// .NET-Code (QuestPDF), keine externen Konverter. Der Fließtext der Abschnitte
/// 48 entspricht dem Mustervertrag (Vorlage Abgabevertrag.docx).
/// </summary>
public static class ContractPdfGenerator
{
static ContractPdfGenerator()
{
// QuestPDF Community License (kostenlos für Einzelpersonen / kleine Firmen).
QuestPDF.Settings.License = LicenseType.Community;
}
private static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE");
private static string Price(decimal p) => p.ToString("N2", German) + " €";
private static string D(DateOnly d) => d.ToString("dd.MM.yyyy", German);
private static string Or(string? v, string fallback = "—") => string.IsNullOrWhiteSpace(v) ? fallback : v!;
private const string Accent = "#A85F2E";
private const string Ink = "#3D2E23";
private const string Line = "#D9CCB4";
public static byte[] Generate(ContractData data)
{
ArgumentNullException.ThrowIfNull(data);
return Document.Create(doc =>
{
doc.Page(page =>
{
page.Size(PageSizes.A4);
page.Margin(1.8f, Unit.Centimetre);
page.DefaultTextStyle(x => x.FontSize(9.5f).FontColor(Ink).LineHeight(1.25f));
page.Header().PaddingBottom(8).Column(h =>
{
h.Item().Text("Schutzvertrag / Kaufvertrag").FontSize(18).Bold().FontColor(Accent);
h.Item().Text("Mongolische Rennmäuse").FontSize(10).FontColor("#8C7F6E");
});
page.Content().PaddingTop(6).Column(col =>
{
col.Spacing(12);
Parties(col, data);
Animals(col, data);
Subject(col, data);
Clauses(col);
Signatures(col, data);
});
page.Footer().AlignCenter().Text(t =>
{
t.DefaultTextStyle(x => x.FontSize(8).FontColor("#8C7F6E"));
t.Span("Seite ");
t.CurrentPageNumber();
t.Span(" / ");
t.TotalPages();
});
});
}).GeneratePdf();
}
private static void Heading(ColumnDescriptor col, string text) =>
col.Item().PaddingTop(4).Text(text).FontSize(12).Bold().FontColor(Accent);
private static void Kv(ColumnDescriptor col, string label, string value) =>
col.Item().Row(r =>
{
r.ConstantItem(150).Text(label).FontColor("#8C7F6E");
r.RelativeItem().Text(value).SemiBold();
});
private static void Bullet(ColumnDescriptor col, string text) =>
col.Item().Row(r =>
{
r.ConstantItem(14).Text("•").FontColor(Accent);
r.RelativeItem().Text(text);
});
private static void Parties(ColumnDescriptor col, ContractData data)
{
var s = data.Seller;
var b = data.Buyer;
Heading(col, "1. Vertragspartner");
col.Item().Text("Verkäufer / Züchter").SemiBold();
col.Item().Column(c =>
{
c.Spacing(2);
Kv(c, "Zuchtname:", Or(s.ZuchtName));
Kv(c, "Vor- und Nachname:", Or(s.Name));
Kv(c, "Adresse:", Or(s.Address));
Kv(c, "Telefon:", Or(s.Phone, ""));
Kv(c, "E-Mail:", Or(s.Email, ""));
Kv(c, "Homepage:", Or(s.Homepage, ""));
});
col.Item().PaddingTop(4).Text("Käufer / Abnehmer").SemiBold();
col.Item().Column(c =>
{
c.Spacing(2);
Kv(c, "Vor- und Nachname:", Or(b.Name));
Kv(c, "Adresse:", Or(b.Address));
Kv(c, "Telefon:", Or(b.Phone, ""));
Kv(c, "E-Mail:", Or(b.Email, ""));
});
}
private static void Animals(ColumnDescriptor col, ContractData data)
{
Heading(col, "2. Angaben zu den Tieren");
col.Item().Column(list =>
{
list.Spacing(10);
foreach (var a in data.Animals)
{
// Ein Block je Tier: links das (optionale) Foto, rechts die Stammdaten —
// wie im Mustervertrag (das große Rechteck links).
list.Item().Border(1).BorderColor(Line).Row(row =>
{
row.RelativeItem(2f).MinHeight(150).BorderRight(1).BorderColor(Line)
.Padding(4).Element(box =>
{
if (a.Photo is { Length: > 0 } bytes)
box.AlignMiddle().Image(bytes).FitArea();
else
box.AlignMiddle().AlignCenter().Text("Kein Foto")
.FontSize(8).FontColor("#B8AC97");
});
row.RelativeItem(3f).Column(kv =>
{
AnimalRow(kv, "Name:", Or(a.Name, ""));
AnimalRow(kv, "Tierart:", "Mongolische Rennmaus");
AnimalRow(kv, "Geschlecht:", Or(a.Geschlecht));
AnimalRow(kv, "Geburtsdatum:", a.Geburtsdatum is { } born ? D(born) : "—");
AnimalRow(kv, "Farbschlag:", Or(a.Farbschlag, ""), last: true);
});
});
}
});
}
private static void AnimalRow(ColumnDescriptor col, string label, string value, bool last = false)
{
var cell = col.Item();
if (!last) cell = cell.BorderBottom(1).BorderColor(Line);
cell.PaddingVertical(7).PaddingHorizontal(8).Row(r =>
{
r.ConstantItem(100).Text(label).FontColor("#8C7F6E");
r.RelativeItem().Text(value).SemiBold();
});
}
private static void Subject(ColumnDescriptor col, ContractData data)
{
Heading(col, "3. Gegenstand des Vertrages");
col.Item().Text(
$"Der Züchter verkauft dem Käufer mit Unterzeichnung des vorliegenden Vertrages die oben " +
$"erwähnten Tiere zu einem Kaufpreis von {Price(data.Price)}. Der Kaufpreis ist bei Übergabe " +
$"der Tiere vollständig bezahlt worden. Die Tiere wurden am {D(data.HandoverDate)} dem Käufer " +
$"von dem Züchter übergeben.");
}
private static void Clauses(ColumnDescriptor col)
{
Heading(col, "4. Einverständniserklärung zur Erhebung personenbezogener Daten");
col.Item().Text(
"Der Käufer stimmt der Erhebung und der Verarbeitung seiner oben aufgeführten Daten durch den " +
"Verkäufer zu. Diese werden von dem Züchter vertraulich im Rahmen seiner Zucht behandelt. Darüber " +
"hinaus benötigt es für jede weitere Datenerhebung die Zustimmung des Käufers. Der Abnehmer hat das " +
"Recht, diese Einwilligung jederzeit ohne Angabe einer Begründung zu widerrufen. Weiterhin können " +
"erhobene Daten bei Bedarf korrigiert, gelöscht oder deren Erhebung eingeschränkt werden.");
Heading(col, "5. Pflichten des Käufers");
col.Item().Text(
"Tiere sind keine Sache, sondern empfindungs- und leidensfähige Lebewesen. Der Abnehmer ist sich " +
"seiner hohen Verantwortung bewusst und übernimmt folgende Pflichten:");
col.Item().Column(c =>
{
c.Spacing(3);
Bullet(c, "Der Käufer verpflichtet sich, die Tiere artgerecht zu halten, zu füttern und zu pflegen. Er verpflichtet sich, die stets aktuellen Vorschriften des Tierschutzgesetzes einzuhalten. Die schriftlichen Anweisungen des Züchters über Haltung, Pflege und Unterkunft der Tiere sind zu befolgen.");
Bullet(c, "Der Abnehmer verpflichtet sich, die Tiere in Krankheitsfällen oder bei Anzeichen auf diese unverzüglich veterinärmedizinisch behandeln zu lassen. Die Tiere dürfen nicht ohne zwingende veterinärmedizinische Gründe euthanasiert werden.");
Bullet(c, "Dem Käufer ist eine Weitergabe der Tiere ohne die Zustimmung des Züchters nicht gestattet. Eine Abgabe an ein Tierheim oder eine Auffangstation ist ohne vorherige Absprache untersagt.");
Bullet(c, "Der Abnehmer verpflichtet sich, die Tiere niemals zu misshandeln, für Versuchszwecke oder als Zuchttier einzusetzen oder als Futtertier zu verwenden.");
Bullet(c, "Die Einzelhaltung der Tiere ist dem Käufer untersagt. Er verpflichtet sich im Falle eines einzelnen Tieres zur artgerechten Vergesellschaftung mit der Trenngitter-Methode.");
Bullet(c, "Der Käufer setzt den Verkäufer über das Versterben sowie die Todesursache der Tiere in Kenntnis.");
Bullet(c, "Ernsthafte Erkrankungen genetischer Ursache sind nach gestellter Diagnose unverzüglich dem Züchter zu melden.");
});
Heading(col, "6. Rechte des Käufers");
col.Item().Column(c =>
{
c.Spacing(3);
Bullet(c, "Der Käufer hat das Recht, den Züchter für die unentgeltliche Weitervermittlung der Tiere zu beauftragen. Dies schließt jedoch nicht die Aufnahme der Rennmäuse bei dem Züchter ein.");
Bullet(c, "Der Verkäufer steht dem Käufer für Fragen zur Tierhaltung zur Verfügung. Der Käufer kann diese Dienste in beschränktem Umfang unentgeltlich in Anspruch nehmen.");
Bullet(c, "Der Käufer hat das Recht, gegen Vorlage einer aktuellen negativen Kotuntersuchung den kostenpflichtigen Vergesellschaftungsservice für die Rennmaus in Anspruch zu nehmen.");
});
Heading(col, "7. Haftung / Zuwiderhandlung");
col.Item().Column(c =>
{
c.Spacing(3);
Bullet(c, "Bei Vertragsverstoß ist der Züchter berechtigt, den Vertrag fristlos zu kündigen.");
Bullet(c, "Im Falle des Verstoßes ist der Käufer zur entschädigungslosen Rückgabe der Tiere an den Züchter verpflichtet.");
Bullet(c, "Zur Sicherstellung der Käuferpflichten wird eine Vertragsstrafe in Höhe von 200,- € festgelegt.");
});
Heading(col, "8. Besondere Vereinbarungen / Bemerkungen");
col.Item().Text(
"Mündliche Vereinbarungen haben keine Gültigkeit. Jede Änderung oder Ergänzung des Vertrages bedarf " +
"der Schriftform. Die Vertragsparteien verzichten auf jegliche Sachgewährleistungsansprüche. " +
"Gerichtsstand für beide Parteien ist der Wohnort des Züchters. Der Vertrag wird zweifach ausgefertigt " +
"und unterzeichnet. Käufer und Verkäufer erhalten je ein Exemplar. Mit der Unterschrift wird versichert, " +
"den Vertragsinhalt gelesen und akzeptiert zu haben und sich an diesen zu halten.");
}
private static void Signatures(ColumnDescriptor col, ContractData data)
{
var ort = string.IsNullOrWhiteSpace(data.Seller.City) ? "" : data.Seller.City + ", ";
col.Item().PaddingTop(14).Text($"{ort}den {D(data.ContractDate ?? data.HandoverDate)}");
col.Item().PaddingTop(28).Row(r =>
{
r.RelativeItem().Column(c =>
{
c.Item().BorderTop(1).BorderColor(Ink).PaddingTop(4).Text("Unterschrift des Verkäufers");
});
r.ConstantItem(40);
r.RelativeItem().Column(c =>
{
c.Item().BorderTop(1).BorderColor(Ink).PaddingTop(4).Text("Unterschrift des Käufers");
});
});
}
}

View File

@@ -17,6 +17,11 @@ RUN dotnet publish GerbilManagerWebAPI.csproj -c Release -o /app/publish /p:UseA
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final
WORKDIR /app
# curl für den Container-Healthcheck (das Basis-Image bringt weder curl noch wget mit;
# ohne dieses würde der compose-Healthcheck dauerhaft fehlschlagen und api nie "healthy").
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*
# .NET 10 containers default to ASPNETCORE_HTTP_PORTS=8080 bound on all interfaces.
EXPOSE 8080
COPY --from=build /app/publish .

View File

@@ -0,0 +1,20 @@
namespace GerbilManagerWebAPI.Dtos
{
/// <summary>ERWERB: payload for POST/PUT /acquisitions (acquisition data per animal).</summary>
public record AcquisitionInput(
Guid? GerbilId,
Guid? SourceContactId,
DateOnly? Date,
decimal? Price,
string? Note);
/// <summary>ERWERB: response DTO for a stored acquisition record.</summary>
public record AcquisitionDto(
Guid Id,
Guid? GerbilId,
Guid? SourceContactId,
DateOnly? Date,
decimal? Price,
string? Note,
DateTimeOffset CreatedAt);
}

View File

@@ -22,6 +22,7 @@ namespace GerbilManagerWebAPI.Dtos
string? CauseOfDeath,
DateOnly? GoHomeDate,
string? Genotype,
string? SpottingType,
string? Notes,
string? ImportSource,
string? ExternalRef,
@@ -29,21 +30,32 @@ namespace GerbilManagerWebAPI.Dtos
List<string> CharacterTraits,
string? CharacterNote,
bool? IsDeaf,
bool IsResident);
bool IsResident,
string? ProfilePhotoUrl,
bool IsCastrated,
string? Provenance,
int? BirthOrder = null);
public record LitterDto(
Guid Id,
string Name,
DateOnly Date,
DateOnly? Date,
int? TotalBorn,
int? DeathsWithin8Weeks,
int? Stillborn,
Guid? FatherId,
Guid? MotherId,
DateOnly? ExpectedGoHomeDate,
string? Notes);
string? Notes,
string? Provenance,
bool ShowInChronicle);
public record ContactDto(Guid Id, string Name, string? Email, string? Phone, string? Address, string? Notes);
public record ContactDto(Guid Id, string Name, string? Email, string? Phone, string? Address, string? Notes, bool IsBreeder, bool IsReceiver, string? NameSuffix, string? Provenance);
public record EnclosureDto(Guid Id, string Name, string? Notes);
public record EnclosureDto(
Guid Id, string Name, string? Notes,
string? Size, int? Capacity,
DateOnly? LastCleanedDate, int? CleaningCycleDays, DateOnly? NextCleaningDate);
public record ColorVarietyDto(Guid Id, string Name, string? CanonicalGenotype, int SortOrder);
@@ -56,8 +68,33 @@ namespace GerbilManagerWebAPI.Dtos
public record PhotoDto(Guid Id, string FileName, string? Caption, int SortOrder, string Url);
// VERIFIED/PROTECTED OVERRIDE -------------------------------------------
// Status: "unchanged" = raw import agrees with the golden state; "drifted" = the raw import
// differs from the golden state (see ImportDiff — a signal for what the importer might still
// get wrong); "missing" = the verified animal no longer exists in the imported data.
public record VerifiedGerbilDto(
Guid GerbilId,
string? EntityName,
bool IsVerified,
string Status,
DateTimeOffset? VerifiedAt,
DateTimeOffset UpdatedAt,
string? Note,
IReadOnlyList<string> ProtectedFields,
IReadOnlyList<SnapshotDiffDto> ImportDiff);
/// <summary>One field difference between the golden state and the raw import.</summary>
public record SnapshotDiffDto(string Path, string? GoldenValue, string? ImportValue);
/// <summary>Export entry for the committed regression fixture (verified-golden.json).</summary>
public record VerifiedGoldenEntry(
Guid GerbilId, string? Name, DateTimeOffset? VerifiedAt, Import.GerbilSnapshot? Snapshot);
// Request DTOs -----------------------------------------------------------
/// <summary>Body for POST /verified-gerbils/{id} — optional free-text note.</summary>
public record VerifyGerbilInput(string? Note);
public record GerbilInput(
string? Name,
Gender? Gender,
@@ -72,6 +109,7 @@ namespace GerbilManagerWebAPI.Dtos
string? CauseOfDeath,
DateOnly? GoHomeDate,
string? Genotype,
string? SpottingType,
string? Notes,
string? ImportSource,
string? ExternalRef,
@@ -79,20 +117,27 @@ namespace GerbilManagerWebAPI.Dtos
List<string>? CharacterTraits,
string? CharacterNote,
bool? IsDeaf,
bool? IsResident);
bool? IsResident,
bool? IsCastrated);
public record LitterInput(
string Name,
DateOnly Date,
DateOnly? Date,
int? TotalBorn,
int? DeathsWithin8Weeks,
int? Stillborn,
Guid? FatherId,
Guid? MotherId,
DateOnly? ExpectedGoHomeDate,
string? Notes);
string? Notes,
bool? ShowInChronicle = null);
public record ContactInput(string Name, string? Email, string? Phone, string? Address, string? Notes);
public record ContactInput(string Name, string? Email, string? Phone, string? Address, string? Notes, bool IsBreeder, bool IsReceiver, string? NameSuffix);
public record EnclosureInput(string Name, string? Notes);
public record EnclosureInput(
string Name, string? Notes,
string? Size, int? Capacity,
DateOnly? LastCleanedDate, int? CleaningCycleDays);
public record ColorVarietyInput(string Name, string? CanonicalGenotype, int? SortOrder);

View File

@@ -12,14 +12,20 @@ namespace GerbilManagerWebAPI.Dtos
DateTimeOffset CreatedAt,
IReadOnlyList<Guid> GerbilIds,
// Download-URL der .docx ("/contracts/{id}/file").
string Url);
string Url,
// True, wenn die .docx im Vertrags-Dateiroot existiert. Importierte
// Verträge haben KEINE Datei (Word-Download 404) -> Frontend blendet den
// Word-Button aus; das PDF wird ohnehin aus den Daten neu erzeugt.
bool HasFile);
public record SaleContractInput(
Guid ContactId,
List<Guid> GerbilIds,
decimal Price,
DateOnly HandoverDate,
DateOnly? ContractDate);
DateOnly? ContractDate,
// Optionales Tierfoto je Tier (GerbilId -> GerbilPhoto-Id) fürs Vertragsbild.
Dictionary<Guid, Guid>? AnimalPhotos = null);
/// <summary>Zuchtprofil — Antwort UND Request-Body von /settings/breeder-profile.</summary>
public record BreederProfileDto(
@@ -29,5 +35,6 @@ namespace GerbilManagerWebAPI.Dtos
string Phone,
string Email,
string Homepage,
string City);
string City,
string NameSuffix);
}

View File

@@ -0,0 +1,34 @@
namespace GerbilManagerWebAPI.Dtos
{
/// <summary>EXHIBITION: payload for POST /exhibitions.</summary>
public record ExhibitionResultInput(
Guid? GerbilId,
string? EntityName,
string EventName,
DateTime? Date,
string? Placement,
string? Award,
string? Note);
/// <summary>EXHIBITION: payload for PUT /exhibitions/{id} (all fields optional/partial).</summary>
public record ExhibitionResultUpdate(
Guid? GerbilId,
string? EntityName,
string? EventName,
DateTime? Date,
string? Placement,
string? Award,
string? Note);
/// <summary>EXHIBITION: response DTO for a stored exhibition result.</summary>
public record ExhibitionResultDto(
Guid Id,
Guid? GerbilId,
string? EntityName,
string EventName,
DateTime? Date,
string? Placement,
string? Award,
string? Note,
DateTimeOffset CreatedAt);
}

View File

@@ -0,0 +1,93 @@
namespace GerbilManagerWebAPI.Dtos
{
/// <summary>FEEDBACK: payload for POST /feedback (the "Fehler melden" dialog).</summary>
public record FeedbackInput(
string Message,
string Context,
Guid? GerbilId,
Guid? LitterId,
Guid? ContactId,
string? EntityName,
string? Url,
DateTimeOffset? ClientTimestamp);
/// <summary>
/// FEEDBACK: one past Q&A turn in the ticket's thread/history.
/// Role is "maintainer" (Rückfrage) or "breeder" (Antwort).
/// </summary>
public record FeedbackThreadEntry(
string Role,
string Text,
DateTimeOffset? At);
/// <summary>FEEDBACK: lightweight metadata for an attachment (no bytes).</summary>
public record FeedbackAttachmentDto(
Guid Id,
string FileName,
string ContentType,
int Size);
/// <summary>FEEDBACK: payload to upload an attachment (base64-encoded bytes).</summary>
public record FeedbackAttachmentInput(
string FileName,
string ContentType,
string DataBase64);
/// <summary>FEEDBACK: response DTO for a stored report.</summary>
public record FeedbackDto(
Guid Id,
string Message,
string Context,
Guid? GerbilId,
Guid? LitterId,
Guid? ContactId,
string? EntityName,
string? Url,
DateTimeOffset? ClientTimestamp,
string? UserAgent,
DateTimeOffset CreatedAt,
string Status,
DateTimeOffset? ResolvedAt,
string? Question,
string? Answer,
DateTimeOffset? AnsweredAt,
/// <summary>Breeder-friendly changelog written on resolve (shown in the UI).</summary>
string? FixNote,
/// <summary>INTERNAL agent working memory — exposed for tooling, NEVER shown to the breeder.</summary>
string? AgentContext,
/// <summary>Earlier Q&A rounds, oldest first; the current open exchange stays in Question/Answer.</summary>
IReadOnlyList<FeedbackThreadEntry> Thread,
/// <summary>When a genuinely-resolved ticket (no pending Rückfrage) was reopened; else null.</summary>
DateTimeOffset? ReopenedAt = null,
/// <summary>Soft-delete marker: when the ticket was deleted via the UI (recoverable); else null.</summary>
DateTimeOffset? DeletedAt = null,
/// <summary>Optional AI-set category/topic for filtering (e.g. "Genetik", "Import"); null = none.</summary>
string? Category = null,
/// <summary>Was the resolution helpful? true=👍, false=👎, null=no feedback yet.</summary>
bool? Helpful = null,
/// <summary>Attachment metadata (no bytes); fetch bytes via /feedback/attachments/{id}.</summary>
IReadOnlyList<FeedbackAttachmentDto>? Attachments = null);
/// <summary>
/// FEEDBACK: payload for PUT /feedback/{id}. Edit the message and/or toggle status,
/// attach a clarifying question (Rückfrage), submit the breeder's answer, set the
/// breeder-friendly fix note (changelog), or update the internal agent context.
/// </summary>
public record FeedbackUpdate(
string? Message,
string? Status,
string? Question,
string? Answer,
string? FixNote,
string? AgentContext,
/// <summary>Set/clear the ticket category. Empty/whitespace clears it.</summary>
string? Category = null,
/// <summary>👍/👎 on a resolved ticket. null leaves it unchanged.</summary>
bool? Helpful = null,
/// <summary>
/// Wenn true, wird nach dem Update eine Push-Benachrichtigung an die Züchterin gesendet.
/// Nur die KI/der Betreuer setzt das (z. B. neue Rückfrage / Ticket gelöst); das Frontend
/// setzt es NIE — so löst die Züchterin mit eigenen Aktionen keine Selbst-Pushes aus.
/// </summary>
bool? Notify = null);
}

View File

@@ -0,0 +1,19 @@
namespace GerbilManagerWebAPI.Dtos
{
/// <summary>
/// REFS: ein einzelner aufzulösender Kurz-Verweis (Shortlink, git-Stil) aus einem
/// Freitext. <c>Type</c> ist "tier" | "kontakt" | "wurf" | "gehege"; <c>Code</c> ist
/// ein GUID-Präfix (mind. 6 Hex-Zeichen) ODER die volle GUID — Bindestrich-tolerant.
/// </summary>
public record RefRequest(string Type, string Code);
/// <summary>REFS: Body von POST /refs/resolve.</summary>
public record ResolveRefsInput(List<RefRequest> Refs);
/// <summary>
/// REFS: Auflösungsergebnis. <c>Id</c>/<c>Name</c> sind null, wenn der Code unbekannt
/// ODER mehrdeutig ist (mehrere Präfix-Treffer) — es wird bewusst nicht geraten.
/// <c>Type</c>/<c>Code</c> werden gespiegelt, damit der Client zuordnen kann.
/// </summary>
public record RefResolution(string Type, string Code, Guid? Id, string? Name);
}

View File

@@ -0,0 +1,28 @@
namespace GerbilManagerWebAPI.Dtos
{
/// <summary>RÜCKNAHME: Payload für POST/PUT /returns.</summary>
public record ReturnRecordInput(
Guid? GerbilId,
string? GerbilName,
DateTime? ReturnDate,
decimal? ReturnPrice,
decimal? OriginalPrice,
DateTime? OriginalSaleDate,
Guid? FromContactId,
string? FromContactName,
string? Note);
/// <summary>RÜCKNAHME: Antwort-DTO für einen gespeicherten Rücknahme-Datensatz.</summary>
public record ReturnRecordDto(
Guid Id,
Guid? GerbilId,
string? GerbilName,
DateTime? ReturnDate,
decimal? ReturnPrice,
decimal? OriginalPrice,
DateTime? OriginalSaleDate,
Guid? FromContactId,
string? FromContactName,
string? Note,
DateTimeOffset CreatedAt);
}

View File

@@ -0,0 +1,66 @@
namespace GerbilManagerWebAPI.Dtos
{
/// <summary>Zählungen für die Analyse-Übersicht (RennmausPro-III-Import).</summary>
public record Rpro3Counts(
int OwnAnimals, // eigene Tiere (stamm)
int ExternalRaw, // externe Ahnen (fremd, roh, vor Dedup)
int ExternalAfterDedup, // externe Ahnen nach Dedup
int Litters, // Würfe
int Contacts, // Kontakte (Herkunft + Abnehmer)
int Genotypes, // hinterlegte Genotypen (eigen + extern)
int DuplicatesMerged, // weggefallene interne Dubletten
int MergeClusters, // Anzahl zusammengelegter Cluster
int Enclosures, // Gehege/Becken
int Acquisitions, // Erwerbe (herktier_tb)
int Reservations, // Reservierungen/Abgaben (abgeben_tb + abstat_tb)
int Returns, // Rücknahmen (getback_tb)
int WaitingList, // Wartelisten-Einträge (nachfrage_tb)
int Exhibitions); // Ausstellungsergebnisse (ausz_tb)
/// <summary>Eine Variante eines mehrdeutigen Namens (für die Entscheidung der Züchterin).</summary>
public record Rpro3AmbiguousVariant(
int Count,
string Dob,
string Farbe,
string Origin,
bool IsOwn);
public record Rpro3AmbiguousName(
string Name,
IReadOnlyList<Rpro3AmbiguousVariant> Variants,
int BareCount);
/// <summary>Ein großer sicherer Merge-Cluster (zur Veranschaulichung der Dedup-Wirkung).</summary>
public record Rpro3MergeSample(
string Name,
int RecordCount,
string Dob,
string Farbe,
string Origin);
/// <summary>Ergebnis von POST /import/rpro3/analyze — schreibt NICHTS in die DB.</summary>
public record Rpro3AnalyzeResult(
Rpro3Counts Counts,
int NewVsCurrentNew, // wie viele Tiere im aktuellen Stand fehlen würden (neu)
int NewVsCurrentExisting, // wie viele schon vorhanden sind (Match)
IReadOnlyList<Rpro3MergeSample> TopMerges,
IReadOnlyList<Rpro3AmbiguousName> AmbiguousNames,
bool PhotosProvided,
int PhotoFilesAvailable);
/// <summary>Ergebnis von POST /import/rpro3/execute.</summary>
public record Rpro3ExecuteResult(
int GerbilsImported,
int LittersImported,
int ContactsImported,
int HealthRecordsImported,
int WeightRecordsImported,
int PhotosImported,
int EnclosuresImported,
int AcquisitionsImported,
int ReservationsImported,
int ReturnsImported,
int WaitingListImported,
int ExhibitionsImported,
string Message);
}

View File

@@ -0,0 +1,43 @@
namespace GerbilManagerWebAPI.Dtos
{
/// <summary>ABGABE-STATUS: response DTO for a stored reservation/sale status.</summary>
public record SaleReservationDto(
Guid Id,
Guid GerbilId,
string? GerbilName,
string Status,
Guid? ReservedForContactId,
string? ContactName,
DateTime? AppointmentDate,
decimal? Price,
string? Note,
DateTime? HandedOverDate,
DateTimeOffset CreatedAt,
DateTimeOffset UpdatedAt);
/// <summary>ABGABE-STATUS: payload for POST /reservations.</summary>
public record SaleReservationInput(
Guid GerbilId,
string? GerbilName,
string? Status,
Guid? ReservedForContactId,
string? ContactName,
DateTime? AppointmentDate,
decimal? Price,
string? Note,
DateTime? HandedOverDate);
/// <summary>
/// ABGABE-STATUS: payload for PUT /reservations/{id}. All fields optional — only the
/// provided ones are changed. A null/blank Status is ignored.
/// </summary>
public record SaleReservationUpdate(
string? GerbilName,
string? Status,
Guid? ReservedForContactId,
string? ContactName,
DateTime? AppointmentDate,
decimal? Price,
string? Note,
DateTime? HandedOverDate);
}

View File

@@ -0,0 +1,24 @@
namespace GerbilManagerWebAPI.Dtos
{
/// <summary>WAITLIST: payload for POST/PUT /waiting-list.</summary>
public record WaitingListInput(
Guid? ContactId,
string? ContactName,
string? WishColor,
string? WishGender,
DateTime? RequestedAt,
string? Status,
string? Note);
/// <summary>WAITLIST: response DTO for a stored waiting-list entry.</summary>
public record WaitingListDto(
Guid Id,
Guid? ContactId,
string? ContactName,
string? WishColor,
string? WishGender,
DateTime? RequestedAt,
string Status,
string? Note,
DateTimeOffset CreatedAt);
}

View File

@@ -0,0 +1,89 @@
using GerbilManagerWebAPI.Dtos;
using GerbilManagerWebAPI.Models;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
namespace GerbilManagerWebAPI.Endpoints
{
/// <summary>
/// ERWERB: acquisition data per animal (purchase date/price/note).
/// GET /acquisitions?gerbilId=… -> records for one animal (or all), newest date first.
/// GET /acquisitions/{id} -> a single record.
/// POST /acquisitions -> create, returns 201.
/// PUT /acquisitions/{id} -> update, returns 204.
/// DELETE /acquisitions/{id} -> delete, returns 204.
/// Decoupled from gerbils/contacts (loose nullable Guid columns, no FK), so rows survive
/// the import re-ingest wipe (mirrors Feedback).
/// </summary>
public static class AcquisitionEndpoints
{
public static IEndpointRouteBuilder MapAcquisitionEndpoints(this IEndpointRouteBuilder app)
{
var group = app.MapGroup("/acquisitions").WithTags("Acquisitions");
group.MapGet("/", async (ApplicationContext db, Guid? gerbilId) =>
{
var rows = await db.AcquisitionRecords.AsNoTracking()
.Where(a => gerbilId == null || a.GerbilId == gerbilId)
.ToListAsync();
// Order in memory: SQLite (test host) cannot ORDER BY a DateTimeOffset column,
// and DateOnly ordering stays consistent across providers this way.
return TypedResults.Ok(rows
.OrderByDescending(a => a.Date ?? DateOnly.MinValue)
.ThenByDescending(a => a.CreatedAt)
.Select(ToDto)
.ToList());
});
group.MapGet("/{id:guid}", async Task<Results<Ok<AcquisitionDto>, NotFound>> (Guid id, ApplicationContext db) =>
{
var a = await db.AcquisitionRecords.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);
return a is null ? TypedResults.NotFound() : TypedResults.Ok(ToDto(a));
});
group.MapPost("/", async (AcquisitionInput input, ApplicationContext db) =>
{
var a = new AcquisitionRecord
{
Id = Guid.NewGuid(),
GerbilId = input.GerbilId,
SourceContactId = input.SourceContactId,
Date = input.Date,
Price = input.Price,
Note = string.IsNullOrWhiteSpace(input.Note) ? null : input.Note.Trim(),
CreatedAt = DateTimeOffset.UtcNow,
};
db.AcquisitionRecords.Add(a);
await db.SaveChangesAsync();
return TypedResults.Created($"/acquisitions/{a.Id}", ToDto(a));
});
group.MapPut("/{id:guid}", async Task<Results<NoContent, NotFound>> (Guid id, AcquisitionInput input, ApplicationContext db) =>
{
var a = await db.AcquisitionRecords.FirstOrDefaultAsync(x => x.Id == id);
if (a is null) return TypedResults.NotFound();
a.GerbilId = input.GerbilId;
a.SourceContactId = input.SourceContactId;
a.Date = input.Date;
a.Price = input.Price;
a.Note = string.IsNullOrWhiteSpace(input.Note) ? null : input.Note.Trim();
await db.SaveChangesAsync();
return TypedResults.NoContent();
});
group.MapDelete("/{id:guid}", async Task<Results<NoContent, NotFound>> (Guid id, ApplicationContext db) =>
{
var a = await db.AcquisitionRecords.FirstOrDefaultAsync(x => x.Id == id);
if (a is null) return TypedResults.NotFound();
db.AcquisitionRecords.Remove(a);
await db.SaveChangesAsync();
return TypedResults.NoContent();
});
return app;
}
private static AcquisitionDto ToDto(AcquisitionRecord a) =>
new(a.Id, a.GerbilId, a.SourceContactId, a.Date, a.Price, a.Note, a.CreatedAt);
}
}

View File

@@ -1,3 +1,4 @@
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using GerbilManagerWebAPI.Cms;
@@ -5,6 +6,7 @@ using GerbilManagerWebAPI.Dtos;
using GerbilManagerWebAPI.Models;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
namespace GerbilManagerWebAPI.Endpoints
{
@@ -32,6 +34,21 @@ namespace GerbilManagerWebAPI.Endpoints
return TypedResults.Ok(files.Select(kv => new { path = kv.Key, size = kv.Value.Length }).ToList());
});
// ---- WEB-2: publish — rendert Snapshot auf Disk, atomic swap live/ ----
api.MapPost("/publish", async (ApplicationContext db, IOptions<PublicSiteOptions> opts) =>
{
if (!opts.Value.IsConfigured)
return Results.Problem(
detail: "PublicSite__RootPath ist nicht konfiguriert. Setze die Umgebungsvariable.",
statusCode: 503,
title: "PublicSite nicht konfiguriert");
var snapshot = await new SiteSnapshotService(db).BuildAsync();
var files = SiteRenderer.Render(snapshot);
await PublishToDirectoryAsync(files, opts.Value.RootPath!);
return Results.Ok(new { filesPublished = files.Count });
});
// ---- WEB-3: lokale Vorschau — rendert live (nur veröffentlichte Seiten)
// und liefert die Datei mit passendem Content-Type aus. Relative
// Links/CSS der gerenderten Seite funktionieren dadurch im
@@ -169,6 +186,36 @@ namespace GerbilManagerWebAPI.Endpoints
return app;
}
/// <summary>
/// WEB-2: Writes rendered files to <paramref name="rootPath"/>/_staging_new, then
/// atomically swaps to live/ (rename on the same filesystem = one syscall, never partial).
/// </summary>
internal static async Task PublishToDirectoryAsync(
IReadOnlyDictionary<string, string> files, string rootPath)
{
var stagingDir = Path.Combine(rootPath, "_staging_new");
var liveDir = Path.Combine(rootPath, "live");
var oldDir = Path.Combine(rootPath, "_old");
if (Directory.Exists(stagingDir)) Directory.Delete(stagingDir, recursive: true);
Directory.CreateDirectory(stagingDir);
foreach (var (relativePath, content) in files)
{
var normalPath = relativePath.Replace('/', Path.DirectorySeparatorChar);
var fullPath = Path.Combine(stagingDir, normalPath);
Directory.CreateDirectory(Path.GetDirectoryName(fullPath)!);
await File.WriteAllTextAsync(fullPath, content, Encoding.UTF8);
}
// Atomic swap: _staging_new → live
if (Directory.Exists(oldDir)) Directory.Delete(oldDir, recursive: true);
if (Directory.Exists(liveDir)) Directory.Move(liveDir, oldDir);
Directory.Move(stagingDir, liveDir);
try { if (Directory.Exists(oldDir)) Directory.Delete(oldDir, recursive: true); }
catch { /* non-fatal — old dir gone on next publish */ }
}
/// <summary>WEB-3: Content-Type der Vorschau-Dateien (Renderer erzeugt HTML + CSS).</summary>
private static string PreviewContentType(string path) =>
path.EndsWith(".css", StringComparison.OrdinalIgnoreCase) ? "text/css; charset=utf-8"

View File

@@ -24,7 +24,7 @@ namespace GerbilManagerWebAPI.Endpoints
group.MapPost("/", async (ContactInput input, ApplicationContext db) =>
{
var c = new Contact { Id = Guid.NewGuid(), Name = input.Name, Email = input.Email, Phone = input.Phone, Address = input.Address, Notes = input.Notes };
var c = new Contact { Id = Guid.NewGuid(), Name = input.Name, Email = input.Email, Phone = input.Phone, Address = input.Address, Notes = input.Notes, IsBreeder = input.IsBreeder, IsReceiver = input.IsReceiver, NameSuffix = input.NameSuffix, IsManual = true };
db.Contacts.Add(c);
await db.SaveChangesAsync();
return TypedResults.Created($"/contacts/{c.Id}", ToDto(c));
@@ -35,6 +35,7 @@ namespace GerbilManagerWebAPI.Endpoints
var c = await db.Contacts.FirstOrDefaultAsync(x => x.Id == id);
if (c is null) return TypedResults.NotFound();
c.Name = input.Name; c.Email = input.Email; c.Phone = input.Phone; c.Address = input.Address; c.Notes = input.Notes;
c.IsBreeder = input.IsBreeder; c.IsReceiver = input.IsReceiver; c.NameSuffix = input.NameSuffix;
await db.SaveChangesAsync();
return TypedResults.NoContent();
});
@@ -54,6 +55,6 @@ namespace GerbilManagerWebAPI.Endpoints
return app;
}
private static ContactDto ToDto(Contact c) => new(c.Id, c.Name, c.Email, c.Phone, c.Address, c.Notes);
private static ContactDto ToDto(Contact c) => new(c.Id, c.Name, c.Email, c.Phone, c.Address, c.Notes, c.IsBreeder, c.IsReceiver, c.NameSuffix, c.Provenance);
}
}

View File

@@ -2,6 +2,7 @@ using GerbilManagerWebAPI.Common;
using GerbilManagerWebAPI.Contracts;
using GerbilManagerWebAPI.Dtos;
using GerbilManagerWebAPI.Models;
using GerbilManagerWebAPI.Services;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
@@ -22,24 +23,31 @@ namespace GerbilManagerWebAPI.Endpoints
{
private const string DocxContentType =
"application/vnd.openxmlformats-officedocument.wordprocessingml.document";
private const string PdfContentType = "application/pdf";
public static IEndpointRouteBuilder MapContractEndpoints(this IEndpointRouteBuilder app)
{
var group = app.MapGroup("/contracts").WithTags("Contracts");
// GET /contracts (Gridify; GerbilIds via Include mitgeladen)
group.MapGet("/", async ([AsParameters] GridifyParams query, ApplicationContext db) =>
TypedResults.Ok(await db.SaleContracts.AsNoTracking()
// HasFile pro Zeile per File.Exists (nur die Seite, i. d. R. 20 Zeilen).
group.MapGet("/", async ([AsParameters] GridifyParams query, ApplicationContext db,
IConfiguration config, IWebHostEnvironment env) =>
{
var root = ContractRoot(config, env);
return TypedResults.Ok(await db.SaleContracts.AsNoTracking()
.Include(c => c.Animals)
.ToPagedResultAsync(query, ToDto)));
.ToPagedResultAsync(query, c => ToDto(c, root)));
});
// GET /contracts/{id}
group.MapGet("/{id:guid}", async Task<Results<Ok<SaleContractDto>, NotFound>> (Guid id, ApplicationContext db) =>
group.MapGet("/{id:guid}", async Task<Results<Ok<SaleContractDto>, NotFound>> (
Guid id, ApplicationContext db, IConfiguration config, IWebHostEnvironment env) =>
{
var c = await db.SaleContracts.AsNoTracking()
.Include(x => x.Animals)
.FirstOrDefaultAsync(x => x.Id == id);
return c is null ? TypedResults.NotFound() : TypedResults.Ok(ToDto(c));
return c is null ? TypedResults.NotFound() : TypedResults.Ok(ToDto(c, ContractRoot(config, env)));
});
// POST /contracts — der Abgabe-Abschluss.
@@ -49,6 +57,7 @@ namespace GerbilManagerWebAPI.Endpoints
var errors = new Dictionary<string, string[]>();
var gerbilIds = (input.GerbilIds ?? []).Distinct().ToList();
var photoChoice = input.AnimalPhotos ?? [];
if (gerbilIds.Count == 0)
errors["gerbilIds"] = ["Mindestens ein Tier auswählen."];
if (input.Price < 0)
@@ -99,16 +108,21 @@ namespace GerbilManagerWebAPI.Endpoints
ContractDate = contractDate,
FileName = fileName,
CreatedAt = DateTimeOffset.UtcNow,
Animals = gerbilIds.Select(id => new SaleContractAnimal { GerbilId = id }).ToList(),
Animals = gerbilIds.Select(id => new SaleContractAnimal
{
GerbilId = id,
PhotoId = photoChoice.TryGetValue(id, out var pid) ? pid : null,
}).ToList(),
};
db.SaleContracts.Add(entity);
// Abgabe-Abschluss-Semantik: in derselben SaveChanges-Transaktion.
var today = DateOnly.FromDateTime(DateTime.UtcNow);
foreach (var g in gerbils)
{
g.ReceiverContactId = contact.Id;
g.GoHomeDate = input.HandoverDate;
g.Status = GerbilStatus.GivenAway;
GerbilStatusService.Apply(g, today);
}
try
@@ -142,6 +156,49 @@ namespace GerbilManagerWebAPI.Endpoints
return TypedResults.PhysicalFile(path, DocxContentType, download);
});
// GET /contracts/{id}/pdf — druckfertiges PDF, aus den (aktuellen) Daten regeneriert.
group.MapGet("/{id:guid}/pdf", async Task<Results<FileContentHttpResult, NotFound>> (
Guid id, ApplicationContext db, IConfiguration config, IWebHostEnvironment env) =>
{
var c = await db.SaleContracts.AsNoTracking()
.Include(x => x.Contact)
.Include(x => x.Animals)
.FirstOrDefaultAsync(x => x.Id == id);
if (c is null || c.Contact is null) return TypedResults.NotFound();
var gerbilIds = c.Animals.Select(a => a.GerbilId).ToList();
var gerbils = await db.Gerbils.AsNoTracking()
.Include(g => g.ColorVariety)
.Where(g => gerbilIds.Contains(g.Id))
.ToListAsync();
var settings = await db.BreederSettings.AsNoTracking()
.FirstOrDefaultAsync(s => s.Id == BreederSettings.SingletonId)
?? new BreederSettings();
// Gewählte Vertragsfotos nachladen (Foto muss zum Tier gehören und die Datei
// existieren — sonst bleibt das Bild leer statt zu scheitern).
var photoByGerbil = c.Animals
.Where(a => a.PhotoId is not null)
.ToDictionary(a => a.GerbilId, a => a.PhotoId!.Value);
var photoBytes = await LoadAnimalPhotos(db, photoByGerbil, PhotoRoot(config, env));
var data = new ContractData(
Seller: ToSeller(settings),
Buyer: new ContractBuyer(c.Contact.Name, c.Contact.Address ?? "", c.Contact.Phone, c.Contact.Email),
Animals: gerbils
.Select(g => new ContractAnimal(
g.Name, GeschlechtText(g.Gender), g.DateOfBirth, g.ColorVariety?.Name,
photoBytes.GetValueOrDefault(g.Id)))
.ToList(),
Price: c.Price,
HandoverDate: c.HandoverDate,
ContractDate: c.ContractDate);
var pdf = ContractPdfGenerator.Generate(data);
var download = $"Abgabevertrag_{c.ContractDate:yyyy-MM-dd}_{Sanitize(c.Contact.Name)}.pdf";
return TypedResults.File(pdf, PdfContentType, download);
});
// DELETE /contracts/{id} — Zeile + Datei; Tier-Status wird NICHT zurückgedreht
// (das wäre Magie — Status korrigiert man am Tier selbst).
group.MapDelete("/{id:guid}", async Task<Results<NoContent, NotFound>> (
@@ -164,6 +221,34 @@ namespace GerbilManagerWebAPI.Endpoints
private static string ContractRoot(IConfiguration config, IWebHostEnvironment env) =>
config["Contracts:RootPath"] ?? Path.Combine(env.ContentRootPath, "contract-storage");
/// <summary>Foto-Dateiroot (geteilt mit den Foto-Endpoints).</summary>
private static string PhotoRoot(IConfiguration config, IWebHostEnvironment env) =>
config["Photos:RootPath"] ?? Path.Combine(env.ContentRootPath, "photo-storage");
/// <summary>Lädt die gewählten Vertragsfotos als Rohbytes (GerbilId -> Bytes).
/// Überspringt Fotos, die nicht zum Tier gehören oder deren Datei fehlt.</summary>
private static async Task<Dictionary<Guid, byte[]>> LoadAnimalPhotos(
ApplicationContext db, Dictionary<Guid, Guid> photoByGerbil, string photoRoot)
{
var result = new Dictionary<Guid, byte[]>();
if (photoByGerbil.Count == 0) return result;
var photoIds = photoByGerbil.Values.ToList();
var photos = await db.GerbilPhotos.AsNoTracking()
.Where(p => photoIds.Contains(p.Id))
.ToListAsync();
foreach (var (gerbilId, photoId) in photoByGerbil)
{
var photo = photos.FirstOrDefault(p => p.Id == photoId && p.GerbilId == gerbilId);
if (photo is null) continue;
var path = Path.Combine(photoRoot, photo.FileName);
if (File.Exists(path))
result[gerbilId] = await File.ReadAllBytesAsync(path);
}
return result;
}
private static BreederProfile ToSeller(BreederSettings s) => new()
{
ZuchtName = s.ZuchtName,
@@ -193,9 +278,15 @@ namespace GerbilManagerWebAPI.Endpoints
return cleaned.Trim('-');
}
internal static SaleContractDto ToDto(SaleContract c) => new(
internal static SaleContractDto ToDto(SaleContract c, string? contractRoot = null) => new(
c.Id, c.ContactId, c.Price, c.HandoverDate, c.ContractDate, c.FileName, c.CreatedAt,
c.Animals.Select(a => a.GerbilId).ToList(),
$"/contracts/{c.Id}/file");
$"/contracts/{c.Id}/file",
// Imported contracts have no staged .docx -> HasFile=false (Word
// download 404s gracefully). When no root is given (e.g. POST, where
// the file was just written) we assume the file exists.
HasFile: contractRoot is null
|| (!string.IsNullOrEmpty(c.FileName)
&& File.Exists(Path.Combine(contractRoot, c.FileName))));
}
}

View File

@@ -25,6 +25,7 @@ namespace GerbilManagerWebAPI.Endpoints
group.MapPost("/", async (EnclosureInput input, ApplicationContext db) =>
{
var e = new Enclosure { Id = Guid.NewGuid(), Name = input.Name, Notes = input.Notes };
Apply(e, input);
db.Enclosures.Add(e);
await db.SaveChangesAsync();
return TypedResults.Created($"/enclosures/{e.Id}", ToDto(e));
@@ -35,10 +36,21 @@ namespace GerbilManagerWebAPI.Endpoints
var e = await db.Enclosures.FirstOrDefaultAsync(x => x.Id == id);
if (e is null) return TypedResults.NotFound();
e.Name = input.Name; e.Notes = input.Notes;
Apply(e, input);
await db.SaveChangesAsync();
return TypedResults.NoContent();
});
// Reinigung dokumentieren: setzt LastCleanedDate auf heute (NextCleaningDate folgt aus dem Zyklus).
group.MapPost("/{id:guid}/mark-cleaned", async Task<Results<Ok<EnclosureDto>, NotFound>> (Guid id, ApplicationContext db) =>
{
var e = await db.Enclosures.FirstOrDefaultAsync(x => x.Id == id);
if (e is null) return TypedResults.NotFound();
e.LastCleanedDate = DateOnly.FromDateTime(DateTime.Today);
await db.SaveChangesAsync();
return TypedResults.Ok(ToDto(e));
});
// 409 if the enclosure still houses gerbils.
group.MapDelete("/{id:guid}", async Task<Results<NoContent, NotFound, Conflict<string>>> (Guid id, ApplicationContext db) =>
{
@@ -54,6 +66,16 @@ namespace GerbilManagerWebAPI.Endpoints
return app;
}
private static EnclosureDto ToDto(Enclosure e) => new(e.Id, e.Name, e.Notes);
private static void Apply(Enclosure e, EnclosureInput input)
{
e.Size = input.Size;
e.Capacity = input.Capacity;
e.LastCleanedDate = input.LastCleanedDate;
e.CleaningCycleDays = input.CleaningCycleDays;
}
private static EnclosureDto ToDto(Enclosure e) =>
new(e.Id, e.Name, e.Notes, e.Size, e.Capacity,
e.LastCleanedDate, e.CleaningCycleDays, e.NextCleaningDate);
}
}

View File

@@ -0,0 +1,114 @@
using GerbilManagerWebAPI.Dtos;
using GerbilManagerWebAPI.Models;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
namespace GerbilManagerWebAPI.Endpoints
{
/// <summary>
/// EXHIBITION: show/exhibition results &amp; awards per animal (RennmausPro `ausz_tb`).
/// GET /exhibitions[?gerbilId=…] -> list (optionally filtered to one animal), newest first.
/// POST /exhibitions -> create a result, returns 201.
/// PUT /exhibitions/{id} -> edit a result (partial), 404 on missing id.
/// DELETE /exhibitions/{id} -> remove a result, 404 on missing id.
/// Decoupled from gerbils (loose nullable GerbilId, no FK) so rows survive the import re-ingest wipe.
/// </summary>
public static class ExhibitionEndpoints
{
public static IEndpointRouteBuilder MapExhibitionEndpoints(this IEndpointRouteBuilder app)
{
var group = app.MapGroup("/exhibitions").WithTags("Exhibitions");
group.MapGet("/", async (ApplicationContext db, Guid? gerbilId) =>
{
// Filter in the query; order in memory (SQLite test host cannot ORDER BY a
// DateTimeOffset column — mirrors FeedbackEndpoints).
var query = db.ExhibitionResults.AsNoTracking();
if (gerbilId is { } gid)
query = query.Where(x => x.GerbilId == gid);
var rows = await query.ToListAsync();
return TypedResults.Ok(rows
.OrderByDescending(x => x.Date ?? DateTime.MinValue)
.ThenByDescending(x => x.CreatedAt)
.Select(ToDto)
.ToList());
});
group.MapGet("/{id:guid}", async Task<Results<Ok<ExhibitionResultDto>, NotFound>> (
Guid id, ApplicationContext db) =>
{
var r = await db.ExhibitionResults.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);
return r is null ? TypedResults.NotFound() : TypedResults.Ok(ToDto(r));
});
group.MapPost("/", async Task<Results<Created<ExhibitionResultDto>, BadRequest<string>>> (
ExhibitionResultInput input, ApplicationContext db) =>
{
if (string.IsNullOrWhiteSpace(input.EventName))
return TypedResults.BadRequest("EventName darf nicht leer sein.");
var entity = new ExhibitionResult
{
Id = Guid.NewGuid(),
GerbilId = input.GerbilId,
EntityName = Trim(input.EntityName),
EventName = input.EventName.Trim(),
Date = input.Date,
Placement = Trim(input.Placement),
Award = Trim(input.Award),
Note = Trim(input.Note),
CreatedAt = DateTimeOffset.UtcNow,
};
db.ExhibitionResults.Add(entity);
await db.SaveChangesAsync();
return TypedResults.Created($"/exhibitions/{entity.Id}", ToDto(entity));
});
group.MapPut("/{id:guid}", async Task<Results<Ok<ExhibitionResultDto>, NotFound, BadRequest<string>>> (
Guid id, ExhibitionResultUpdate input, ApplicationContext db) =>
{
var entity = await db.ExhibitionResults.FirstOrDefaultAsync(x => x.Id == id);
if (entity is null)
return TypedResults.NotFound();
if (input.EventName is not null)
{
if (string.IsNullOrWhiteSpace(input.EventName))
return TypedResults.BadRequest("EventName darf nicht leer sein.");
entity.EventName = input.EventName.Trim();
}
if (input.GerbilId is not null) entity.GerbilId = input.GerbilId;
if (input.EntityName is not null) entity.EntityName = Trim(input.EntityName);
if (input.Date is not null) entity.Date = input.Date;
if (input.Placement is not null) entity.Placement = Trim(input.Placement);
if (input.Award is not null) entity.Award = Trim(input.Award);
if (input.Note is not null) entity.Note = Trim(input.Note);
await db.SaveChangesAsync();
return TypedResults.Ok(ToDto(entity));
});
group.MapDelete("/{id:guid}", async Task<Results<NoContent, NotFound>> (
Guid id, ApplicationContext db) =>
{
var entity = await db.ExhibitionResults.FirstOrDefaultAsync(x => x.Id == id);
if (entity is null)
return TypedResults.NotFound();
db.ExhibitionResults.Remove(entity);
await db.SaveChangesAsync();
return TypedResults.NoContent();
});
return app;
}
// Empty/whitespace optional strings normalise to null.
private static string? Trim(string? s) =>
string.IsNullOrWhiteSpace(s) ? null : s.Trim();
private static ExhibitionResultDto ToDto(ExhibitionResult r) =>
new(r.Id, r.GerbilId, r.EntityName, r.EventName, r.Date,
r.Placement, r.Award, r.Note, r.CreatedAt);
}
}

View File

@@ -0,0 +1,393 @@
using System.Text.Json;
using GerbilManagerWebAPI.Dtos;
using GerbilManagerWebAPI.Models;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
namespace GerbilManagerWebAPI.Endpoints
{
/// <summary>
/// FEEDBACK: the "Fehler melden" report sink + ticket management ("Meine Tickets").
/// POST /feedback -> persist a user bug report (with captured debug context), returns 201.
/// GET /feedback -> list reports, newest first (for the ticket list).
/// PUT /feedback/{id} -> edit message, toggle status, attach a clarifying question (Rückfrage),
/// or submit the breeder's answer. Question -> NeedsInfo; Answer -> Answered + AnsweredAt.
/// DELETE /feedback/{id} -> remove a report. 404 on missing id.
/// Feedback is decoupled from gerbils/litters (loose nullable Guid columns, no FK), so
/// rows survive the import re-ingest wipe.
/// </summary>
public static class FeedbackEndpoints
{
/// <summary>Aufbewahrungsfrist im Papierkorb: danach werden Tickets endgültig gelöscht.</summary>
private const int TrashRetentionDays = 30;
/// <summary>Maximale Anhang-Größe (10 MB) — Fotos vom Handy passen locker, schützt aber die DB.</summary>
private const int MaxAttachmentBytes = 10 * 1024 * 1024;
public static IEndpointRouteBuilder MapFeedbackEndpoints(this IEndpointRouteBuilder app)
{
var group = app.MapGroup("/feedback").WithTags("Feedback");
group.MapPost("/", async Task<Results<Created<FeedbackDto>, BadRequest<string>>> (
FeedbackInput input, ApplicationContext db, HttpContext http) =>
{
if (string.IsNullOrWhiteSpace(input.Message))
return TypedResults.BadRequest("Message darf nicht leer sein.");
var entity = new Feedback
{
Id = Guid.NewGuid(),
Message = input.Message.Trim(),
Context = string.IsNullOrWhiteSpace(input.Context) ? "unknown" : input.Context.Trim(),
GerbilId = input.GerbilId,
LitterId = input.LitterId,
ContactId = input.ContactId,
EntityName = input.EntityName,
Url = input.Url,
ClientTimestamp = input.ClientTimestamp,
UserAgent = http.Request.Headers.UserAgent.ToString() is { Length: > 0 } ua ? ua : null,
CreatedAt = DateTimeOffset.UtcNow,
Status = "Open",
ResolvedAt = null,
};
db.Feedback.Add(entity);
await db.SaveChangesAsync();
return TypedResults.Created($"/feedback/{entity.Id}", ToDto(entity));
});
group.MapGet("/", async (ApplicationContext db) =>
{
// In memory verarbeiten: SQLite (Test-Host) kann weder ORDER BY noch WHERE-Vergleiche
// auf DateTimeOffset-Spalten übersetzen.
var rows = await db.Feedback.ToListAsync();
// Aufräumen: soft-gelöschte Tickets werden nach TrashRetentionDays endgültig entfernt
// (lazy beim Abruf — genügt für Single-User, kein Hintergrunddienst nötig).
var cutoff = DateTimeOffset.UtcNow.AddDays(-TrashRetentionDays);
var expired = rows.Where(f => f.DeletedAt is { } d && d < cutoff).ToList();
if (expired.Count > 0)
{
db.Feedback.RemoveRange(expired);
await db.SaveChangesAsync();
rows = rows.Except(expired).ToList();
}
// Anhang-Metadaten (OHNE Bytes) laden und je Ticket zuordnen.
var attMeta = await db.FeedbackAttachments
.Select(a => new { a.Id, a.FeedbackId, a.FileName, a.ContentType, a.Size })
.ToListAsync();
var byTicket = attMeta
.GroupBy(a => a.FeedbackId)
.ToDictionary(
g => g.Key,
g => (IReadOnlyList<FeedbackAttachmentDto>)g
.Select(a => new FeedbackAttachmentDto(a.Id, a.FileName, a.ContentType, a.Size))
.ToList());
return TypedResults.Ok(rows
.OrderByDescending(f => f.CreatedAt)
.Select(f => ToDto(f, byTicket.GetValueOrDefault(f.Id)))
.ToList());
});
group.MapPut("/{id:guid}", async Task<Results<Ok<FeedbackDto>, NotFound, BadRequest<string>>> (
Guid id, FeedbackUpdate input, ApplicationContext db, Push.PushNotifier push) =>
{
var entity = await db.Feedback.FirstOrDefaultAsync(f => f.Id == id);
if (entity is null)
return TypedResults.NotFound();
// Zustand VOR den Mutationen merken — für die Wiederöffnen-Erkennung weiter unten.
var wasResolved = entity.Status.Equals("Resolved", StringComparison.OrdinalIgnoreCase);
var hadOpenRueckfrage = !string.IsNullOrWhiteSpace(entity.Question);
if (input.Message is not null)
{
if (string.IsNullOrWhiteSpace(input.Message))
return TypedResults.BadRequest("Message darf nicht leer sein.");
entity.Message = input.Message.Trim();
}
// Attach a clarifying question (Rückfrage). A non-empty question moves the ticket to
// NeedsInfo (waiting on the breeder) unless it is already Resolved. A blank/whitespace
// question clears it. If a PREVIOUS Q&A exchange already exists, archive it into the
// thread (oldest first) before overwriting — so earlier rounds aren't lost — and clear
// the current Answer so the new question starts a fresh open exchange.
if (input.Question is not null)
{
var q = input.Question.Trim();
if (q.Length > 0)
{
ArchiveCurrentExchange(entity);
entity.Question = q;
if (!entity.Status.Equals("Resolved", StringComparison.OrdinalIgnoreCase))
{
entity.Status = "NeedsInfo";
entity.ResolvedAt = null;
}
}
else
{
entity.Question = null;
}
}
// The breeder's answer. A non-empty answer stamps AnsweredAt and moves to Answered.
if (input.Answer is not null)
{
var a = input.Answer.Trim();
if (a.Length == 0)
{
entity.Answer = null;
entity.AnsweredAt = null;
}
else
{
entity.Answer = a;
entity.AnsweredAt = DateTimeOffset.UtcNow;
entity.Status = "Answered";
entity.ResolvedAt = null;
}
}
if (input.Status is not null)
{
// Normalize to a known lifecycle state. Resolving stamps ResolvedAt; any other
// state clears it. Open/NeedsInfo/Answered/Resolved are accepted (case-insensitive),
// anything else falls back to Open.
var status = input.Status.Trim();
var resolved = status.Equals("Resolved", StringComparison.OrdinalIgnoreCase);
var normalized = status switch
{
_ when status.Equals("Resolved", StringComparison.OrdinalIgnoreCase) => "Resolved",
_ when status.Equals("NeedsInfo", StringComparison.OrdinalIgnoreCase) => "NeedsInfo",
_ when status.Equals("Answered", StringComparison.OrdinalIgnoreCase) => "Answered",
_ => "Open",
};
entity.Status = normalized;
entity.ResolvedAt = resolved
? (entity.ResolvedAt ?? DateTimeOffset.UtcNow)
: null;
// Wiederöffnen-Zeitstempel: nur, wenn ein ECHT gelöstes Ticket (ohne offene
// Rückfrage) wieder geöffnet wird. Tickets, die nur eine offene Rückfrage hatten
// und manuell auf gelöst gesetzt wurden, kehren beim Wiederöffnen einfach in
// ihre Rückfrage zurück und bekommen KEINEN Zeitstempel.
if (!resolved && wasResolved && !hadOpenRueckfrage)
entity.ReopenedAt = DateTimeOffset.UtcNow;
}
// FIX-NOTE: breeder-friendly changelog (typically set together with status=Resolved).
// A blank/whitespace value clears it.
if (input.FixNote is not null)
{
var note = input.FixNote.Trim();
entity.FixNote = note.Length == 0 ? null : note;
}
// AGENT-CONTEXT (internal working memory): updated without changing the status.
// A blank/whitespace value clears it.
if (input.AgentContext is not null)
{
var c = input.AgentContext.Trim();
entity.AgentContext = c.Length == 0 ? null : c;
}
// KATEGORIE: frei wählbares Thema für Filter/Übersicht; leer = löschen.
if (input.Category is not null)
{
var cat = input.Category.Trim();
entity.Category = cat.Length == 0 ? null : cat;
}
// HILFREICH (👍/👎): nur setzen, wenn übermittelt (null = unverändert).
if (input.Helpful is not null)
entity.Helpful = input.Helpful;
await db.SaveChangesAsync();
// Push an die Züchterin, wenn die KI das anfordert (notify=true). Nachricht aus dem
// resultierenden Status ableiten. Fehler dürfen die Antwort nicht stören.
if (input.Notify == true && push.Enabled)
{
var name = string.IsNullOrWhiteSpace(entity.EntityName) ? "" : $" ({entity.EntityName})";
var (title, body) = entity.Status switch
{
"NeedsInfo" => ("Neue Rückfrage" + name, Trim(entity.Question) ?? "Bitte schau in deine Tickets."),
"Resolved" => ("Ticket gelöst" + name, Trim(entity.FixNote) ?? Trim(entity.Message) ?? "Erledigt."),
_ => ("Neues zu deinem Ticket" + name, Trim(entity.Message) ?? ""),
};
try
{
await push.NotifyAllAsync(title, body, $"/hilfe/tickets?focus={entity.Id}");
}
catch (Exception)
{
// Push ist best-effort — niemals die API-Antwort daran scheitern lassen.
}
}
return TypedResults.Ok(ToDto(entity));
});
// SOFT-DELETE: das Ticket wird NICHT entfernt, sondern als gelöscht markiert
// (DeletedAt = jetzt) und wandert in die „Gelöscht"-Kategorie. Wiederherstellbar
// über POST /feedback/{id}/restore.
group.MapDelete("/{id:guid}", async Task<Results<NoContent, NotFound>> (
Guid id, ApplicationContext db) =>
{
var entity = await db.Feedback.FirstOrDefaultAsync(f => f.Id == id);
if (entity is null)
return TypedResults.NotFound();
entity.DeletedAt ??= DateTimeOffset.UtcNow;
await db.SaveChangesAsync();
return TypedResults.NoContent();
});
// WIEDERHERSTELLEN: hebt das Soft-Delete auf (DeletedAt → null); das Ticket kehrt in
// seinen vorherigen Status (Offen/Rückfrage/…) zurück.
group.MapPost("/{id:guid}/restore", async Task<Results<Ok<FeedbackDto>, NotFound>> (
Guid id, ApplicationContext db) =>
{
var entity = await db.Feedback.FirstOrDefaultAsync(f => f.Id == id);
if (entity is null)
return TypedResults.NotFound();
entity.DeletedAt = null;
await db.SaveChangesAsync();
return TypedResults.Ok(ToDto(entity));
});
// ANHANG hochladen (base64). Bild/Datei zu einem Ticket. Größenlimit MaxAttachmentBytes.
group.MapPost("/{id:guid}/attachments", async Task<Results<Created<FeedbackAttachmentDto>, NotFound, BadRequest<string>>> (
Guid id, FeedbackAttachmentInput input, ApplicationContext db) =>
{
var ticket = await db.Feedback.FirstOrDefaultAsync(f => f.Id == id);
if (ticket is null)
return TypedResults.NotFound();
if (string.IsNullOrWhiteSpace(input.DataBase64) || string.IsNullOrWhiteSpace(input.FileName))
return TypedResults.BadRequest("FileName und Daten sind erforderlich.");
byte[] bytes;
try
{
// erlaubt sowohl reines base64 als auch eine data:-URL
var raw = input.DataBase64;
var comma = raw.IndexOf(',');
if (raw.StartsWith("data:", StringComparison.OrdinalIgnoreCase) && comma >= 0)
raw = raw[(comma + 1)..];
bytes = Convert.FromBase64String(raw);
}
catch (FormatException)
{
return TypedResults.BadRequest("Daten sind kein gültiges base64.");
}
if (bytes.Length == 0)
return TypedResults.BadRequest("Datei ist leer.");
if (bytes.Length > MaxAttachmentBytes)
return TypedResults.BadRequest($"Datei zu groß (max. {MaxAttachmentBytes / (1024 * 1024)} MB).");
var att = new FeedbackAttachment
{
Id = Guid.NewGuid(),
FeedbackId = id,
FileName = input.FileName.Trim(),
ContentType = string.IsNullOrWhiteSpace(input.ContentType) ? "application/octet-stream" : input.ContentType.Trim(),
Size = bytes.Length,
Data = bytes,
CreatedAt = DateTimeOffset.UtcNow,
};
db.FeedbackAttachments.Add(att);
await db.SaveChangesAsync();
return TypedResults.Created($"/feedback/attachments/{att.Id}",
new FeedbackAttachmentDto(att.Id, att.FileName, att.ContentType, att.Size));
});
// ANHANG-Bytes ausliefern (für <img>/Download).
group.MapGet("/attachments/{attId:guid}", async Task<Results<FileContentHttpResult, NotFound>> (
Guid attId, ApplicationContext db) =>
{
var att = await db.FeedbackAttachments.AsNoTracking().FirstOrDefaultAsync(a => a.Id == attId);
if (att is null)
return TypedResults.NotFound();
return TypedResults.File(att.Data, att.ContentType, att.FileName);
});
// ANHANG löschen.
group.MapDelete("/attachments/{attId:guid}", async Task<Results<NoContent, NotFound>> (
Guid attId, ApplicationContext db) =>
{
var att = await db.FeedbackAttachments.FirstOrDefaultAsync(a => a.Id == attId);
if (att is null)
return TypedResults.NotFound();
db.FeedbackAttachments.Remove(att);
await db.SaveChangesAsync();
return TypedResults.NoContent();
});
return app;
}
private static readonly JsonSerializerOptions ThreadJson = new(JsonSerializerDefaults.Web);
/// <summary>Für Push-Texte: leeren Wert zu null, sonst auf ~140 Zeichen kürzen.</summary>
private static string? Trim(string? s)
{
if (string.IsNullOrWhiteSpace(s)) return null;
var t = s.Trim();
return t.Length > 140 ? t[..139] + "…" : t;
}
/// <summary>
/// Append the ticket's current (Question, Answer) exchange to the thread/history JSON
/// before it gets overwritten by a new round, then clear the current Answer. Only the
/// non-empty parts are archived (a question with no answer yet is still preserved).
/// </summary>
private static void ArchiveCurrentExchange(Feedback entity)
{
var history = DeserializeThread(entity.Thread).ToList();
var archivedAny = false;
if (!string.IsNullOrWhiteSpace(entity.Question))
{
history.Add(new FeedbackThreadEntry("maintainer", entity.Question!, entity.CreatedAt));
archivedAny = true;
}
if (!string.IsNullOrWhiteSpace(entity.Answer))
{
history.Add(new FeedbackThreadEntry("breeder", entity.Answer!, entity.AnsweredAt));
archivedAny = true;
}
if (archivedAny)
entity.Thread = JsonSerializer.Serialize(history, ThreadJson);
// The new question starts a fresh open exchange — clear the prior answer.
entity.Answer = null;
entity.AnsweredAt = null;
}
private static IReadOnlyList<FeedbackThreadEntry> DeserializeThread(string? json)
{
if (string.IsNullOrWhiteSpace(json))
return Array.Empty<FeedbackThreadEntry>();
try
{
return JsonSerializer.Deserialize<List<FeedbackThreadEntry>>(json, ThreadJson)
?? new List<FeedbackThreadEntry>();
}
catch (JsonException)
{
return Array.Empty<FeedbackThreadEntry>();
}
}
private static FeedbackDto ToDto(Feedback f, IReadOnlyList<FeedbackAttachmentDto>? attachments = null) =>
new(f.Id, f.Message, f.Context, f.GerbilId, f.LitterId, f.ContactId, f.EntityName, f.Url,
f.ClientTimestamp, f.UserAgent, f.CreatedAt, f.Status, f.ResolvedAt,
f.Question, f.Answer, f.AnsweredAt, f.FixNote, f.AgentContext,
DeserializeThread(f.Thread), f.ReopenedAt, f.DeletedAt, f.Category, f.Helpful,
attachments ?? Array.Empty<FeedbackAttachmentDto>());
}
}

View File

@@ -1,7 +1,10 @@
using GerbilManagerWebAPI.Common;
using GerbilManagerWebAPI.Dtos;
using GerbilManagerWebAPI.Import;
using GerbilManagerWebAPI.Models;
using GerbilManagerWebAPI.Services;
using Gridify;
using Gridify.EntityFramework;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
@@ -16,8 +19,21 @@ namespace GerbilManagerWebAPI.Endpoints
// GET /gerbils (Gridify: filter/order/page; e.g. status==Active, litterId==…, orderBy=name)
group.MapGet("/", async ([AsParameters] GridifyParams query, ApplicationContext db) =>
TypedResults.Ok(await db.Gerbils.AsNoTracking()
.ToPagedResultAsync(query, ToDto)));
{
var q = query.ToQuery();
var paging = await db.Gerbils.AsNoTracking().GridifyAsync(q);
var ids = paging.Data.Select(g => g.Id).ToList();
var photoMap = ids.Count == 0 ? new Dictionary<Guid, string>() :
await db.GerbilPhotos.AsNoTracking()
.Where(p => ids.Contains(p.GerbilId))
.GroupBy(p => p.GerbilId)
.Select(g => new { GerbilId = g.Key, FileName = g.OrderBy(p => p.SortOrder).First().FileName })
.ToDictionaryAsync(x => x.GerbilId, x => x.FileName);
var items = paging.Data
.Select(g => ToDto(g, photoMap.TryGetValue(g.Id, out var fn) ? $"/photos/files/{fn}" : null))
.ToList();
return TypedResults.Ok(new PagedResult<GerbilDto>(items, paging.Count, q.Page, q.PageSize));
});
// GET /gerbils/breeders — distinct non-empty Herkunft values for the Tiere filter dropdown
group.MapGet("/breeders", async (ApplicationContext db) =>
@@ -30,7 +46,14 @@ namespace GerbilManagerWebAPI.Endpoints
group.MapGet("/{id:guid}", async Task<Results<Ok<GerbilDto>, NotFound>> (Guid id, ApplicationContext db) =>
{
var g = await db.Gerbils.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);
return g is null ? TypedResults.NotFound() : TypedResults.Ok(ToDto(g));
if (g is null) return TypedResults.NotFound();
var photoFileName = await db.GerbilPhotos.AsNoTracking()
.Where(p => p.GerbilId == id)
.OrderBy(p => p.SortOrder)
.Select(p => p.FileName)
.FirstOrDefaultAsync();
var profilePhotoUrl = photoFileName != null ? $"/photos/files/{photoFileName}" : null;
return TypedResults.Ok(ToDto(g, profilePhotoUrl));
});
// POST /gerbils
@@ -39,7 +62,9 @@ namespace GerbilManagerWebAPI.Endpoints
if (string.IsNullOrWhiteSpace(input.Name))
return TypedResults.ValidationProblem(new Dictionary<string, string[]> { ["name"] = ["Name is required."] });
var g = new Gerbil { Id = Guid.NewGuid(), Name = input.Name! };
// Manually created in the UI → IsManual=true, so the import re-ingest never wipes or
// overwrites this animal (and its sub-records).
var g = new Gerbil { Id = Guid.NewGuid(), Name = input.Name!, IsManual = true };
Apply(g, input, isCreate: true);
db.Gerbils.Add(g);
await db.SaveChangesAsync();
@@ -51,8 +76,17 @@ namespace GerbilManagerWebAPI.Endpoints
{
var g = await db.Gerbils.FirstOrDefaultAsync(x => x.Id == id);
if (g is null) return TypedResults.NotFound();
// Capture the own-field values BEFORE the edit so manual changes to an IMPORTED animal
// can be pinned per-field (survive the next ingest). Manual animals need no override —
// they survive the ingest wholesale.
var before = GerbilSnapshotService.BuildFreezeObject(g);
Apply(g, input, isCreate: false);
await db.SaveChangesAsync();
if (!g.IsManual)
await RecordEditOverrideAsync(db, g, before);
return TypedResults.NoContent();
});
@@ -86,7 +120,8 @@ namespace GerbilManagerWebAPI.Endpoints
{
if (!string.IsNullOrWhiteSpace(i.Name)) g.Name = i.Name!;
g.Gender = i.Gender ?? (isCreate ? Gender.unknown : g.Gender);
g.Status = i.Status ?? (isCreate ? GerbilStatus.Active : g.Status);
// Status is applied as a user preference and then overridden by GerbilStatusService.
g.Status = i.Status ?? (isCreate ? GerbilStatus.Breeding : g.Status);
g.LitterId = i.LitterId ?? g.LitterId;
g.OriginContactId = i.OriginContactId ?? g.OriginContactId;
g.ReceiverContactId = i.ReceiverContactId ?? g.ReceiverContactId;
@@ -97,6 +132,7 @@ namespace GerbilManagerWebAPI.Endpoints
g.CauseOfDeath = i.CauseOfDeath ?? g.CauseOfDeath;
g.GoHomeDate = i.GoHomeDate ?? g.GoHomeDate;
g.Genotype = i.Genotype ?? g.Genotype;
g.SpottingType = i.SpottingType ?? g.SpottingType;
g.Notes = i.Notes ?? g.Notes;
g.ImportSource = i.ImportSource ?? g.ImportSource;
g.ExternalRef = i.ExternalRef ?? g.ExternalRef;
@@ -105,12 +141,51 @@ namespace GerbilManagerWebAPI.Endpoints
g.CharacterNote = i.CharacterNote ?? g.CharacterNote;
g.IsDeaf = i.IsDeaf ?? g.IsDeaf;
g.IsResident = i.IsResident ?? (isCreate ? true : g.IsResident);
g.IsCastrated = i.IsCastrated ?? (isCreate ? false : g.IsCastrated);
GerbilStatusService.Apply(g, DateOnly.FromDateTime(DateTime.UtcNow));
}
internal static GerbilDto ToDto(Gerbil g) => new(
// EDIT PROTECTION: after a manual edit to an IMPORTED animal, pin the change so the next
// ingest can't overwrite it. A VERIFIED animal keeps its certification and its whole golden
// is refreshed to the edited state (Frage 5). An unverified animal gets/updates a "geschützt"
// override carrying ONLY the changed fields (per-field) — untouched fields keep receiving
// import improvements. Called after the edit is already persisted.
private static async Task RecordEditOverrideAsync(ApplicationContext db, Gerbil g, System.Text.Json.Nodes.JsonObject before)
{
var ov = await db.GerbilOverrides.FirstOrDefaultAsync(o => o.GerbilId == g.Id);
if (ov is { IsVerified: true })
{
ov.EntityName = g.Name;
ov.OverrideJson = GerbilSnapshotService.BuildFreezeJson(g);
var snap = await GerbilSnapshotService.BuildSnapshotAsync(db, g.Id);
if (snap is not null) ov.SnapshotJson = GerbilSnapshotService.SerializeSnapshot(snap);
ov.LastImportSnapshotJson = null;
ov.LastImportDiffJson = null;
ov.UpdatedAt = DateTimeOffset.UtcNow;
await db.SaveChangesAsync();
return;
}
var after = GerbilSnapshotService.BuildFreezeObject(g);
var changed = GerbilSnapshotService.ChangedFields(before, after);
if (changed.Count == 0) return;
if (ov is null)
{
ov = new GerbilOverride { Id = Guid.NewGuid(), GerbilId = g.Id, IsVerified = false, OverrideJson = "{}" };
db.GerbilOverrides.Add(ov);
}
ov.EntityName = g.Name;
ov.OverrideJson = GerbilSnapshotService.MergeOverrideJson(ov.OverrideJson, changed);
ov.UpdatedAt = DateTimeOffset.UtcNow;
await db.SaveChangesAsync();
}
internal static GerbilDto ToDto(Gerbil g, string? profilePhotoUrl = null) => new(
g.Id, g.Name, g.Gender, g.Status, g.LitterId, g.OriginContactId, g.ReceiverContactId,
g.EnclosureId, g.ColorVarietyId, g.DateOfBirth, g.DateOfDeath, g.CauseOfDeath,
g.GoHomeDate, g.Genotype, g.Notes, g.ImportSource, g.ExternalRef, g.OriginBreeder,
g.CharacterTraits, g.CharacterNote, g.IsDeaf, g.IsResident);
g.GoHomeDate, g.Genotype, g.SpottingType, g.Notes, g.ImportSource, g.ExternalRef, g.OriginBreeder,
g.CharacterTraits, g.CharacterNote, g.IsDeaf, g.IsResident, profilePhotoUrl, g.IsCastrated,
g.Provenance, g.BirthOrder);
}
}

View File

@@ -0,0 +1,28 @@
using GerbilManagerWebAPI.Import;
using Microsoft.AspNetCore.Http.HttpResults;
namespace GerbilManagerWebAPI.Endpoints
{
public static class ImportDocxEndpoints
{
public static IEndpointRouteBuilder MapImportDocxEndpoints(this IEndpointRouteBuilder app)
{
var group = app.MapGroup("/import/docx").WithTags("Import");
// POST /import/docx/dry-run — analyse without writing
group.MapPost("/dry-run",
async Task<Ok<ImportDocxReport>> (
ApplicationContext db, IConfiguration config, IWebHostEnvironment env) =>
TypedResults.Ok(await new ImportDocxService(db, config, env).RunAsync(execute: false)));
// POST /import/docx/execute — GATED: enriches Gerbils with Litter-Link,
// ReceiverContact, GoHomeDate, DateOfDeath, CauseOfDeath (fill-NULL-only).
group.MapPost("/execute",
async Task<Ok<ImportDocxReport>> (
ApplicationContext db, IConfiguration config, IWebHostEnvironment env) =>
TypedResults.Ok(await new ImportDocxService(db, config, env).RunAsync(execute: true)));
return app;
}
}
}

View File

@@ -1,4 +1,7 @@
using System.IO.Compression;
using GerbilManagerWebAPI.Dtos;
using GerbilManagerWebAPI.Import;
using GerbilManagerWebAPI.Import.Rpro3;
using Microsoft.AspNetCore.Http.HttpResults;
namespace GerbilManagerWebAPI.Endpoints
@@ -8,6 +11,11 @@ namespace GerbilManagerWebAPI.Endpoints
/// POST /import/dry-run -> report what WOULD be created/linked/quarantined (no writes)
/// POST /import/execute -> load the conflict-free subset (idempotent). GATED: only run
/// against Julian's DB under god-supervision after he approves the dry-run.
///
/// RPRO3 — vollwertiger RennmausPro-III-Backup-Importer (Upload via "Hilfe"):
/// POST /import/rpro3/analyze -> .backup (+ optional bilder.zip) entpacken, parsen, deduplizieren;
/// schreibt NICHTS. Liefert Zählungen, Top-Merges, mehrdeutige Namen.
/// POST /import/rpro3/execute -> idempotenter Import (deterministische GUIDs).
/// </summary>
public static class ImportEndpoints
{
@@ -29,7 +37,116 @@ namespace GerbilManagerWebAPI.Endpoints
return TypedResults.Ok(report);
});
group.MapPost("/ingest-resolved", async Task<Ok<string>> (
ApplicationContext db, IConfiguration config, IWebHostEnvironment env) =>
{
var result = await new IngestResolvedService(db, config, env).RunAsync();
return TypedResults.Ok(result);
});
// ── RPRO3 ──────────────────────────────────────────────────────────
group.MapPost("/rpro3/analyze", async Task<Results<Ok<Rpro3AnalyzeResult>, BadRequest<string>>> (
IFormFile backup, IFormFile? images,
ApplicationContext db, IConfiguration config, IWebHostEnvironment env) =>
{
try
{
var reader = new Rpro3Reader();
await using var bs = backup.OpenReadStream();
using var seekable = await ToSeekable(bs);
var data = reader.ReadFromBackup(seekable, out var workDir);
try
{
IReadOnlySet<string>? photoFiles = null;
if (images is not null)
{
await using var imgStream = images.OpenReadStream();
using var imgSeekable = await ToSeekable(imgStream);
photoFiles = ListZipImageNames(imgSeekable);
}
var service = new Rpro3ImportService(db, config, env);
var result = await service.AnalyzeAsync(data, images is not null, photoFiles);
return TypedResults.Ok(result);
}
finally { TryDeleteDir(workDir); }
}
catch (Rpro3FormatException ex) { return TypedResults.BadRequest(ex.Message); }
}).WithTags("Import").DisableAntiforgery();
group.MapPost("/rpro3/execute", async Task<Results<Ok<Rpro3ExecuteResult>, BadRequest<string>>> (
IFormFile backup, IFormFile? images,
ApplicationContext db, IConfiguration config, IWebHostEnvironment env) =>
{
try
{
var reader = new Rpro3Reader();
await using var bs = backup.OpenReadStream();
using var seekable = await ToSeekable(bs);
var data = reader.ReadFromBackup(seekable, out var workDir);
try
{
Dictionary<string, string>? photoPaths = null;
if (images is not null)
{
await using var imgStream = images.OpenReadStream();
using var imgSeekable = await ToSeekable(imgStream);
photoPaths = ExtractZipImages(imgSeekable, workDir);
}
var service = new Rpro3ImportService(db, config, env);
var result = await service.ExecuteAsync(data, workDir, images is not null, photoPaths);
return TypedResults.Ok(result);
}
finally { TryDeleteDir(workDir); }
}
catch (Rpro3FormatException ex) { return TypedResults.BadRequest(ex.Message); }
}).WithTags("Import").DisableAntiforgery();
return app;
}
// IFormFile-Streams sind nicht immer seekbar (ZipArchive braucht Seek) → in MemoryStream kopieren.
private static async Task<MemoryStream> ToSeekable(Stream s)
{
var ms = new MemoryStream();
await s.CopyToAsync(ms);
ms.Position = 0;
return ms;
}
private static readonly string[] ImageExts = { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp" };
private static IReadOnlySet<string> ListZipImageNames(Stream zip)
{
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
using var archive = new ZipArchive(zip, ZipArchiveMode.Read, leaveOpen: true);
foreach (var e in archive.Entries)
if (!string.IsNullOrEmpty(e.Name) && ImageExts.Contains(Path.GetExtension(e.Name).ToLowerInvariant()))
set.Add(e.Name);
return set;
}
// Bilder ins workDir entpacken; Rückgabe: lowercase-Dateiname → absoluter Pfad.
private static Dictionary<string, string> ExtractZipImages(Stream zip, string workDir)
{
var map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var imgDir = Path.Combine(workDir, "bilder");
Directory.CreateDirectory(imgDir);
using var archive = new ZipArchive(zip, ZipArchiveMode.Read, leaveOpen: true);
foreach (var e in archive.Entries)
{
if (string.IsNullOrEmpty(e.Name) || !ImageExts.Contains(Path.GetExtension(e.Name).ToLowerInvariant()))
continue;
var dest = Path.Combine(imgDir, Guid.NewGuid().ToString("N") + Path.GetExtension(e.Name));
try { e.ExtractToFile(dest, overwrite: true); map[e.Name] = dest; }
catch { /* defektes Archiv-Entry überspringen */ }
}
return map;
}
private static void TryDeleteDir(string dir)
{
try { if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); }
catch { /* best effort */ }
}
}
}

View File

@@ -23,24 +23,28 @@ namespace GerbilManagerWebAPI.Endpoints
return l is null ? TypedResults.NotFound() : TypedResults.Ok(ToDto(l));
});
group.MapPost("/", async Task<Results<Created<LitterDto>, BadRequest<ParentGenderError>>> (LitterInput input, ApplicationContext db) =>
group.MapPost("/", async Task<Results<Created<LitterDto>, BadRequest<ParentGenderError>, BadRequest<string>>> (LitterInput input, ApplicationContext db) =>
{
var err = await ValidateParents(db, input.FatherId, input.MotherId);
if (err is not null) return TypedResults.BadRequest(err);
var mortalityErr = ValidateMortality(input.DeathsWithin8Weeks, input.TotalBorn);
if (mortalityErr is not null) return TypedResults.BadRequest(mortalityErr);
var l = new Litter { Id = Guid.NewGuid(), Name = input.Name, Date = input.Date };
var l = new Litter { Id = Guid.NewGuid(), Name = input.Name, Date = input.Date, IsManual = true };
Apply(l, input);
db.Litters.Add(l);
await db.SaveChangesAsync();
return TypedResults.Created($"/litters/{l.Id}", ToDto(l));
});
group.MapPut("/{id:guid}", async Task<Results<NoContent, NotFound, BadRequest<ParentGenderError>>> (Guid id, LitterInput input, ApplicationContext db) =>
group.MapPut("/{id:guid}", async Task<Results<NoContent, NotFound, BadRequest<ParentGenderError>, BadRequest<string>>> (Guid id, LitterInput input, ApplicationContext db) =>
{
var l = await db.Litters.FirstOrDefaultAsync(x => x.Id == id);
if (l is null) return TypedResults.NotFound();
var err = await ValidateParents(db, input.FatherId, input.MotherId);
if (err is not null) return TypedResults.BadRequest(err);
var mortalityErr = ValidateMortality(input.DeathsWithin8Weeks, input.TotalBorn);
if (mortalityErr is not null) return TypedResults.BadRequest(mortalityErr);
l.Name = input.Name;
l.Date = input.Date;
Apply(l, input);
@@ -76,14 +80,30 @@ namespace GerbilManagerWebAPI.Endpoints
private static void Apply(Litter l, LitterInput i)
{
l.TotalBorn = i.TotalBorn;
l.DeathsWithin8Weeks = i.DeathsWithin8Weeks;
l.Stillborn = i.Stillborn;
l.FatherId = i.FatherId;
l.MotherId = i.MotherId;
l.ExpectedGoHomeDate = i.ExpectedGoHomeDate;
l.Notes = i.Notes;
// Nur überschreiben, wenn explizit gesetzt — sonst bestehenden Wert / Modell-Default
// (true) behalten, damit ein Edit ohne dieses Feld einen versteckten Wurf nicht
// versehentlich wieder in die Wurfchronik holt.
if (i.ShowInChronicle is bool show) l.ShowInChronicle = show;
}
private static string? ValidateMortality(int? deaths, int? totalBorn)
{
if (deaths is null) return null;
if (deaths < 0) return "DeathsWithin8Weeks darf nicht negativ sein.";
if (totalBorn is not null && deaths > totalBorn)
return "DeathsWithin8Weeks darf nicht größer als TotalBorn sein.";
return null;
}
private static LitterDto ToDto(Litter l) => new(
l.Id, l.Name, l.Date, l.TotalBorn, l.FatherId, l.MotherId, l.ExpectedGoHomeDate, l.Notes);
l.Id, l.Name, l.Date, l.TotalBorn, l.DeathsWithin8Weeks, l.Stillborn,
l.FatherId, l.MotherId, l.ExpectedGoHomeDate, l.Notes, l.Provenance, l.ShowInChronicle);
}
/// <summary>400 body for a father×mother gender mismatch; frontend localises by Code.</summary>

View File

@@ -72,6 +72,62 @@ namespace GerbilManagerWebAPI.Endpoints
return TypedResults.NoContent();
}).WithTags("Photos");
// ── Gehege (enclosure) photos — mirror the gerbil endpoints, shared file store ──
app.MapGet("/enclosures/{id:guid}/photos",
async Task<Results<Ok<List<PhotoDto>>, NotFound>> (Guid id, ApplicationContext db) =>
{
if (!await db.Enclosures.AnyAsync(e => e.Id == id)) return TypedResults.NotFound();
var photos = await db.EnclosurePhotos.AsNoTracking()
.Where(p => p.EnclosureId == id)
.OrderBy(p => p.SortOrder)
.ToListAsync();
return TypedResults.Ok(photos.Select(ToEnclosureDto).ToList());
}).WithTags("Photos");
app.MapPost("/enclosures/{id:guid}/photos",
async Task<Results<Created<PhotoDto>, NotFound, BadRequest<string>>> (
Guid id, IFormFile file, [Microsoft.AspNetCore.Mvc.FromForm] string? caption,
ApplicationContext db, IConfiguration config, IWebHostEnvironment env) =>
{
if (!await db.Enclosures.AnyAsync(e => e.Id == id)) return TypedResults.NotFound();
if (file is null || file.Length == 0) return TypedResults.BadRequest("No file uploaded.");
var ext = Path.GetExtension(file.FileName);
var fileName = $"{Guid.NewGuid():N}{ext}";
var root = PhotoRoot(config, env);
Directory.CreateDirectory(root);
await using (var stream = File.Create(Path.Combine(root, fileName)))
await file.CopyToAsync(stream);
int nextSort = (await db.EnclosurePhotos.Where(p => p.EnclosureId == id)
.Select(p => (int?)p.SortOrder).MaxAsync() ?? -1) + 1;
var photo = new EnclosurePhoto
{
Id = Guid.NewGuid(),
EnclosureId = id,
FileName = fileName,
Caption = caption,
SortOrder = nextSort,
CreatedAt = DateTimeOffset.UtcNow,
};
db.EnclosurePhotos.Add(photo);
await db.SaveChangesAsync();
return TypedResults.Created($"/enclosure-photos/{photo.Id}", ToEnclosureDto(photo));
}).WithTags("Photos").DisableAntiforgery();
app.MapDelete("/enclosure-photos/{id:guid}",
async Task<Results<NoContent, NotFound>> (Guid id, ApplicationContext db, IConfiguration config, IWebHostEnvironment env) =>
{
var photo = await db.EnclosurePhotos.FirstOrDefaultAsync(p => p.Id == id);
if (photo is null) return TypedResults.NotFound();
var path = Path.Combine(PhotoRoot(config, env), photo.FileName);
if (File.Exists(path)) File.Delete(path);
db.EnclosurePhotos.Remove(photo);
await db.SaveChangesAsync();
return TypedResults.NoContent();
}).WithTags("Photos");
app.MapGet("/photos/files/{fileName}",
Results<PhysicalFileHttpResult, NotFound, BadRequest<string>> (string fileName, IConfiguration config, IWebHostEnvironment env) =>
{
@@ -100,5 +156,8 @@ namespace GerbilManagerWebAPI.Endpoints
private static PhotoDto ToDto(GerbilPhoto p) =>
new(p.Id, p.FileName, p.Caption, p.SortOrder, $"/photos/files/{p.FileName}");
private static PhotoDto ToEnclosureDto(EnclosurePhoto p) =>
new(p.Id, p.FileName, p.Caption, p.SortOrder, $"/photos/files/{p.FileName}");
}
}

View File

@@ -0,0 +1,74 @@
using GerbilManagerWebAPI.Models;
using GerbilManagerWebAPI.Push;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
namespace GerbilManagerWebAPI.Endpoints
{
/// <summary>
/// WEB-PUSH: PWA-Benachrichtigungen für die Züchterin.
/// GET /push/vapid-public-key -> öffentlicher VAPID-Schlüssel (für das Abonnieren im Browser).
/// POST /push/subscribe -> Browser-Abo speichern (idempotent über die Endpoint-URL).
/// POST /push/unsubscribe -> Abo entfernen.
/// Das eigentliche Senden passiert über <see cref="PushNotifier"/> (z. B. wenn die KI eine
/// Rückfrage stellt oder ein Ticket löst — gesteuert über das notify-Flag auf PUT /feedback).
/// </summary>
public static class PushEndpoints
{
public record PushSubscriptionInput(string Endpoint, string P256dh, string Auth);
public record PushUnsubscribeInput(string Endpoint);
public static IEndpointRouteBuilder MapPushEndpoints(this IEndpointRouteBuilder app)
{
var group = app.MapGroup("/push").WithTags("Push");
group.MapGet("/vapid-public-key", (PushNotifier push) =>
TypedResults.Ok(new { publicKey = push.PublicKey, enabled = push.Enabled }));
group.MapPost("/subscribe", async Task<Results<Ok, BadRequest<string>>> (
PushSubscriptionInput input, ApplicationContext db) =>
{
if (string.IsNullOrWhiteSpace(input.Endpoint)
|| string.IsNullOrWhiteSpace(input.P256dh)
|| string.IsNullOrWhiteSpace(input.Auth))
return TypedResults.BadRequest("Endpoint, P256dh und Auth sind erforderlich.");
var existing = await db.WebPushSubscriptions
.FirstOrDefaultAsync(s => s.Endpoint == input.Endpoint);
if (existing is null)
{
db.WebPushSubscriptions.Add(new WebPushSubscription
{
Id = Guid.NewGuid(),
Endpoint = input.Endpoint,
P256dh = input.P256dh,
Auth = input.Auth,
CreatedAt = DateTimeOffset.UtcNow,
});
}
else
{
existing.P256dh = input.P256dh;
existing.Auth = input.Auth;
}
await db.SaveChangesAsync();
return TypedResults.Ok();
});
group.MapPost("/unsubscribe", async (PushUnsubscribeInput input, ApplicationContext db) =>
{
var subs = await db.WebPushSubscriptions
.Where(s => s.Endpoint == input.Endpoint)
.ToListAsync();
if (subs.Count > 0)
{
db.WebPushSubscriptions.RemoveRange(subs);
await db.SaveChangesAsync();
}
return TypedResults.NoContent();
});
return app;
}
}
}

View File

@@ -0,0 +1,107 @@
using GerbilManagerWebAPI.Dtos;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
namespace GerbilManagerWebAPI.Endpoints
{
/// <summary>
/// REFS: Auflöser für getippte Kurz-Verweise (Shortlinks, git-Stil) in Freitexten.
/// Tokens im Text: <c>tier:&lt;code&gt;</c>, <c>kontakt:&lt;code&gt;</c>,
/// <c>wurf:&lt;code&gt;</c>, <c>gehege:&lt;code&gt;</c> — <c>&lt;code&gt;</c> ist ein
/// GUID-Präfix (mind. 6 Hex) oder die volle GUID. Das Frontend rendert daraus
/// Name + interner Link.
///
/// POST /refs/resolve -> [{ type, code, id|null, name|null }]
///
/// DB-AGNOSTISCH (Tests: SQLite in-memory, Prod: Postgres): pro Typ eine schlanke
/// {Id,Name}-Projektion laden und im Speicher per Präfix matchen — KEIN ::text-Cast
/// o.ä. Mehrdeutiges Präfix (mehrere Treffer) => id=null (nicht raten).
/// </summary>
public static class RefsEndpoints
{
/// <summary>Schlanke {Id,Name}-Projektion für den In-Memory-Präfix-Match.</summary>
private readonly record struct NamedRow(Guid Id, string Name);
public static IEndpointRouteBuilder MapRefsEndpoints(this IEndpointRouteBuilder app)
{
var group = app.MapGroup("/refs").WithTags("Refs");
group.MapPost("/resolve", async Task<Ok<List<RefResolution>>> (
ResolveRefsInput input, ApplicationContext db) =>
{
var refs = input.Refs ?? new List<RefRequest>();
// Welche Entitätstypen werden überhaupt angefragt? Nur diese Tabellen laden.
var wantedTypes = refs
.Select(r => NormalizeType(r.Type))
.Where(t => t is not null)
.Distinct()
.ToHashSet();
// Pro Typ einmalig eine leichte {Id,Name}-Projektion laden (DB-agnostisch:
// reine Spaltenauswahl, kein ::text-Cast — läuft auf SQLite wie auf Postgres).
var byType = new Dictionary<string, List<NamedRow>>();
if (wantedTypes.Contains("tier"))
byType["tier"] = await db.Gerbils.AsNoTracking()
.Select(x => new NamedRow(x.Id, x.Name)).ToListAsync();
if (wantedTypes.Contains("kontakt"))
byType["kontakt"] = await db.Contacts.AsNoTracking()
.Select(x => new NamedRow(x.Id, x.Name)).ToListAsync();
if (wantedTypes.Contains("wurf"))
byType["wurf"] = await db.Litters.AsNoTracking()
.Select(x => new NamedRow(x.Id, x.Name)).ToListAsync();
if (wantedTypes.Contains("gehege"))
byType["gehege"] = await db.Enclosures.AsNoTracking()
.Select(x => new NamedRow(x.Id, x.Name)).ToListAsync();
var results = new List<RefResolution>(refs.Count);
foreach (var r in refs)
{
var type = NormalizeType(r.Type);
var prefix = NormalizeCode(r.Code);
if (type is null || prefix.Length < 6 || !byType.TryGetValue(type, out var rows))
{
results.Add(new RefResolution(r.Type, r.Code, null, null));
continue;
}
// Präfix-Match auf der bindestrich-losen, klein geschriebenen GUID ("N"-Format).
var matches = rows
.Where(x => x.Id.ToString("N").StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
.Take(2)
.ToList();
// Genau ein Treffer => auflösen; 0 (unbekannt) oder >1 (mehrdeutig) => null.
if (matches.Count == 1)
results.Add(new RefResolution(r.Type, r.Code, matches[0].Id, matches[0].Name));
else
results.Add(new RefResolution(r.Type, r.Code, null, null));
}
return TypedResults.Ok(results);
});
return app;
}
/// <summary>Akzeptiert die vier Typ-Schlüssel (case-insensitive); sonst null.</summary>
private static string? NormalizeType(string? type) => type?.Trim().ToLowerInvariant() switch
{
"tier" => "tier",
"kontakt" => "kontakt",
"wurf" => "wurf",
"gehege" => "gehege",
_ => null,
};
/// <summary>GUID-Code bindestrich-tolerant + Hex-only normalisieren (Kleinschreibung).</summary>
private static string NormalizeCode(string? code)
{
if (string.IsNullOrWhiteSpace(code)) return string.Empty;
var chars = code.Trim().ToLowerInvariant()
.Where(c => (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'));
return new string(chars.ToArray());
}
}
}

View File

@@ -0,0 +1,104 @@
using GerbilManagerWebAPI.Dtos;
using GerbilManagerWebAPI.Models;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
namespace GerbilManagerWebAPI.Endpoints
{
/// <summary>
/// RÜCKNAHMEN (RPRO3 getback_tb): zurückgekommene/zurückgenommene Tiere.
/// GET /returns[?gerbilId=] -> Liste, neueste zuerst (optional nach Tier gefiltert).
/// POST /returns -> Rücknahme erfassen, 201.
/// PUT /returns/{id} -> Rücknahme aktualisieren, 200.
/// DELETE /returns/{id} -> Rücknahme löschen, 204.
/// Entkoppelt von Gerbils/Contacts (lose nullable Guid-Spalten, kein FK), daher
/// überleben Zeilen den Import-Re-Ingest-Wipe — wie Feedback.
/// </summary>
public static class ReturnRecordEndpoints
{
public static IEndpointRouteBuilder MapReturnRecordEndpoints(this IEndpointRouteBuilder app)
{
var group = app.MapGroup("/returns").WithTags("Returns");
group.MapGet("/", async (ApplicationContext db, Guid? gerbilId) =>
{
var query = db.ReturnRecords.AsNoTracking();
if (gerbilId is { } gid)
query = query.Where(r => r.GerbilId == gid);
// In-Memory sortieren: SQLite (Test-Host) kann nicht nach DateTimeOffset ORDER BY-en.
var rows = await query.ToListAsync();
return TypedResults.Ok(rows
.OrderByDescending(r => r.ReturnDate ?? DateTime.MinValue)
.ThenByDescending(r => r.CreatedAt)
.Select(ToDto)
.ToList());
});
group.MapPost("/", async Task<Results<Created<ReturnRecordDto>, BadRequest<string>>> (
ReturnRecordInput input, ApplicationContext db) =>
{
if (input.GerbilId is null && string.IsNullOrWhiteSpace(input.GerbilName))
return TypedResults.BadRequest("Es muss ein Tier (GerbilId oder GerbilName) angegeben werden.");
var entity = new ReturnRecord
{
Id = Guid.NewGuid(),
GerbilId = input.GerbilId,
GerbilName = Trimmed(input.GerbilName),
ReturnDate = input.ReturnDate,
ReturnPrice = input.ReturnPrice,
OriginalPrice = input.OriginalPrice,
OriginalSaleDate = input.OriginalSaleDate,
FromContactId = input.FromContactId,
FromContactName = Trimmed(input.FromContactName),
Note = Trimmed(input.Note),
CreatedAt = DateTimeOffset.UtcNow,
};
db.ReturnRecords.Add(entity);
await db.SaveChangesAsync();
return TypedResults.Created($"/returns/{entity.Id}", ToDto(entity));
});
group.MapPut("/{id:guid}", async Task<Results<Ok<ReturnRecordDto>, NotFound, BadRequest<string>>> (
Guid id, ReturnRecordInput input, ApplicationContext db) =>
{
var entity = await db.ReturnRecords.FirstOrDefaultAsync(r => r.Id == id);
if (entity is null) return TypedResults.NotFound();
if (input.GerbilId is null && string.IsNullOrWhiteSpace(input.GerbilName))
return TypedResults.BadRequest("Es muss ein Tier (GerbilId oder GerbilName) angegeben werden.");
entity.GerbilId = input.GerbilId;
entity.GerbilName = Trimmed(input.GerbilName);
entity.ReturnDate = input.ReturnDate;
entity.ReturnPrice = input.ReturnPrice;
entity.OriginalPrice = input.OriginalPrice;
entity.OriginalSaleDate = input.OriginalSaleDate;
entity.FromContactId = input.FromContactId;
entity.FromContactName = Trimmed(input.FromContactName);
entity.Note = Trimmed(input.Note);
await db.SaveChangesAsync();
return TypedResults.Ok(ToDto(entity));
});
group.MapDelete("/{id:guid}", async Task<Results<NoContent, NotFound>> (
Guid id, ApplicationContext db) =>
{
var entity = await db.ReturnRecords.FirstOrDefaultAsync(r => r.Id == id);
if (entity is null) return TypedResults.NotFound();
db.ReturnRecords.Remove(entity);
await db.SaveChangesAsync();
return TypedResults.NoContent();
});
return app;
}
private static string? Trimmed(string? s) =>
string.IsNullOrWhiteSpace(s) ? null : s.Trim();
private static ReturnRecordDto ToDto(ReturnRecord r) =>
new(r.Id, r.GerbilId, r.GerbilName, r.ReturnDate, r.ReturnPrice, r.OriginalPrice,
r.OriginalSaleDate, r.FromContactId, r.FromContactName, r.Note, r.CreatedAt);
}
}

View File

@@ -0,0 +1,124 @@
using GerbilManagerWebAPI.Dtos;
using GerbilManagerWebAPI.Models;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
namespace GerbilManagerWebAPI.Endpoints
{
/// <summary>
/// ABGABE-STATUS (RPRO3 abgeben_tb / abstat_tb): the pre-handover reservation/sale
/// pipeline — verfügbar → reserviert → abgegeben.
/// GET /reservations -> list all, newest-updated first.
/// GET /reservations?gerbilId= -> the (single) reservation status for one animal, if any.
/// POST /reservations -> create/establish a status, returns 201.
/// PUT /reservations/{id} -> change status / reservation details. 404 on missing id.
/// DELETE /reservations/{id} -> remove. 404 on missing id.
/// Decoupled from gerbils/contacts (loose nullable Guid columns, no FK), so rows survive
/// the import re-ingest wipe — like Feedback.
/// </summary>
public static class SaleReservationEndpoints
{
private static readonly string[] AllowedStatuses = { "verfuegbar", "reserviert", "abgegeben" };
/// <summary>Normalize a status string to one of the three canonical values; default "verfuegbar".</summary>
private static string NormalizeStatus(string? raw)
{
var s = raw?.Trim().ToLowerInvariant();
return AllowedStatuses.Contains(s) ? s! : "verfuegbar";
}
public static IEndpointRouteBuilder MapSaleReservationEndpoints(this IEndpointRouteBuilder app)
{
var group = app.MapGroup("/reservations").WithTags("Reservations");
group.MapGet("/", async (ApplicationContext db, Guid? gerbilId) =>
{
// Order in memory: SQLite (test host) cannot ORDER BY a DateTimeOffset column.
var rows = await db.SaleReservations.AsNoTracking().ToListAsync();
var filtered = gerbilId is { } gid
? rows.Where(r => r.GerbilId == gid)
: rows;
return TypedResults.Ok(filtered
.OrderByDescending(r => r.UpdatedAt)
.Select(ToDto)
.ToList());
});
group.MapPost("/", async Task<Results<Created<SaleReservationDto>, BadRequest<string>>> (
SaleReservationInput input, ApplicationContext db) =>
{
if (input.GerbilId == Guid.Empty)
return TypedResults.BadRequest("GerbilId ist erforderlich.");
var now = DateTimeOffset.UtcNow;
var entity = new SaleReservation
{
Id = Guid.NewGuid(),
GerbilId = input.GerbilId,
GerbilName = Trim(input.GerbilName),
Status = NormalizeStatus(input.Status),
ReservedForContactId = input.ReservedForContactId,
ContactName = Trim(input.ContactName),
AppointmentDate = input.AppointmentDate,
Price = input.Price,
Note = Trim(input.Note),
HandedOverDate = input.HandedOverDate,
CreatedAt = now,
UpdatedAt = now,
};
db.SaleReservations.Add(entity);
await db.SaveChangesAsync();
return TypedResults.Created($"/reservations/{entity.Id}", ToDto(entity));
});
group.MapPut("/{id:guid}", async Task<Results<Ok<SaleReservationDto>, NotFound>> (
Guid id, SaleReservationUpdate input, ApplicationContext db) =>
{
var entity = await db.SaleReservations.FirstOrDefaultAsync(r => r.Id == id);
if (entity is null)
return TypedResults.NotFound();
if (input.Status is not null)
entity.Status = NormalizeStatus(input.Status);
if (input.GerbilName is not null)
entity.GerbilName = Trim(input.GerbilName);
if (input.ContactName is not null)
entity.ContactName = Trim(input.ContactName);
if (input.Note is not null)
entity.Note = Trim(input.Note);
// Value-type/nullable fields are always applied from the payload (a null clears them).
entity.ReservedForContactId = input.ReservedForContactId;
entity.AppointmentDate = input.AppointmentDate;
entity.Price = input.Price;
entity.HandedOverDate = input.HandedOverDate;
entity.UpdatedAt = DateTimeOffset.UtcNow;
await db.SaveChangesAsync();
return TypedResults.Ok(ToDto(entity));
});
group.MapDelete("/{id:guid}", async Task<Results<NoContent, NotFound>> (
Guid id, ApplicationContext db) =>
{
var entity = await db.SaleReservations.FirstOrDefaultAsync(r => r.Id == id);
if (entity is null)
return TypedResults.NotFound();
db.SaleReservations.Remove(entity);
await db.SaveChangesAsync();
return TypedResults.NoContent();
});
return app;
}
private static string? Trim(string? s) =>
string.IsNullOrWhiteSpace(s) ? null : s.Trim();
private static SaleReservationDto ToDto(SaleReservation r) =>
new(r.Id, r.GerbilId, r.GerbilName, r.Status, r.ReservedForContactId, r.ContactName,
r.AppointmentDate, r.Price, r.Note, r.HandedOverDate, r.CreatedAt, r.UpdatedAt);
}
}

View File

@@ -33,6 +33,7 @@ namespace GerbilManagerWebAPI.Endpoints
s.Email = input.Email ?? "";
s.Homepage = input.Homepage ?? "";
s.City = input.City ?? "";
s.NameSuffix = input.NameSuffix ?? "";
await db.SaveChangesAsync();
return TypedResults.NoContent();
});
@@ -55,6 +56,6 @@ namespace GerbilManagerWebAPI.Endpoints
}
internal static BreederProfileDto ToDto(BreederSettings s) =>
new(s.ZuchtName, s.Name, s.Address, s.Phone, s.Email, s.Homepage, s.City);
new(s.ZuchtName, s.Name, s.Address, s.Phone, s.Email, s.Homepage, s.City, s.NameSuffix);
}
}

View File

@@ -0,0 +1,136 @@
using System.Text.Json;
using GerbilManagerWebAPI.Dtos;
using GerbilManagerWebAPI.Import;
using GerbilManagerWebAPI.Models;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
namespace GerbilManagerWebAPI.Endpoints
{
/// <summary>
/// VERIFIED / PROTECTED OVERRIDES — the breeder's hand-curated "this animal is correct" layer.
/// POST /verified-gerbils/{gerbilId} -> mark "vollständig korrekt": snapshot the full Akte,
/// freeze all own fields, apply the freeze immediately. Toggle-on. Optional {note}.
/// DELETE /verified-gerbils/{gerbilId} -> remove the override (un-flag / release protection).
/// Non-destructive: current values stay; the next ingest makes the animal import-driven again.
/// GET /verified-gerbils -> all overrides (verified + protected) with drift status.
/// GET /verified-gerbils/{gerbilId} -> single status (badge on the Rennmausakte).
/// GET /verified-gerbils/export -> canonical golden dump for the committed regression fixture.
/// Overrides are decoupled from gerbils (loose GerbilId, no FK), so they survive the import
/// re-ingest wipe and are re-applied on top of the fresh import (the "freeze").
/// </summary>
public static class VerifiedGerbilEndpoints
{
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
public static IEndpointRouteBuilder MapVerifiedGerbilEndpoints(this IEndpointRouteBuilder app)
{
var group = app.MapGroup("/verified-gerbils").WithTags("VerifiedGerbils");
group.MapPost("/{gerbilId:guid}", async Task<Results<Ok<VerifiedGerbilDto>, NotFound>> (
Guid gerbilId, VerifyGerbilInput? input, ApplicationContext db) =>
{
var g = await db.Gerbils.FirstOrDefaultAsync(x => x.Id == gerbilId);
if (g is null) return TypedResults.NotFound();
var snapshot = await GerbilSnapshotService.BuildSnapshotAsync(db, gerbilId);
var ov = await db.GerbilOverrides.FirstOrDefaultAsync(o => o.GerbilId == gerbilId);
if (ov is null)
{
ov = new GerbilOverride { Id = Guid.NewGuid(), GerbilId = gerbilId, OverrideJson = "{}" };
db.GerbilOverrides.Add(ov);
}
ov.EntityName = g.Name;
ov.IsVerified = true;
ov.OverrideJson = GerbilSnapshotService.BuildFreezeJson(g);
ov.SnapshotJson = snapshot is null ? null : GerbilSnapshotService.SerializeSnapshot(snapshot);
// Reset the drift cache — recomputed on the next ingest against the fresh import.
ov.LastImportSnapshotJson = null;
ov.LastImportDiffJson = null;
ov.Note = string.IsNullOrWhiteSpace(input?.Note) ? ov.Note : input!.Note!.Trim();
ov.VerifiedAt ??= DateTimeOffset.UtcNow;
ov.UpdatedAt = DateTimeOffset.UtcNow;
await db.SaveChangesAsync();
return TypedResults.Ok(await ToDtoAsync(db, ov));
});
group.MapDelete("/{gerbilId:guid}", async Task<Results<NoContent, NotFound>> (
Guid gerbilId, ApplicationContext db) =>
{
var ov = await db.GerbilOverrides.FirstOrDefaultAsync(o => o.GerbilId == gerbilId);
if (ov is null) return TypedResults.NotFound();
db.GerbilOverrides.Remove(ov);
await db.SaveChangesAsync();
return TypedResults.NoContent();
});
group.MapGet("/", async (ApplicationContext db) =>
{
var rows = await db.GerbilOverrides.ToListAsync();
var existingIds = await db.Gerbils.Select(g => g.Id).ToHashSetAsync();
var list = new List<VerifiedGerbilDto>();
foreach (var ov in rows.OrderByDescending(o => o.UpdatedAt))
list.Add(await ToDtoAsync(db, ov, existingIds));
return TypedResults.Ok(list);
});
group.MapGet("/export", async (ApplicationContext db) =>
{
var rows = await db.GerbilOverrides.Where(o => o.IsVerified).ToListAsync();
var export = rows
.OrderBy(o => o.EntityName, StringComparer.Ordinal)
.ThenBy(o => o.GerbilId)
.Select(o => new VerifiedGoldenEntry(
o.GerbilId, o.EntityName, o.VerifiedAt,
GerbilSnapshotService.DeserializeSnapshot(o.SnapshotJson)))
.ToList();
return TypedResults.Ok(export);
});
group.MapGet("/{gerbilId:guid}", async Task<Results<Ok<VerifiedGerbilDto>, NotFound>> (
Guid gerbilId, ApplicationContext db) =>
{
var ov = await db.GerbilOverrides.FirstOrDefaultAsync(o => o.GerbilId == gerbilId);
if (ov is null) return TypedResults.NotFound();
return TypedResults.Ok(await ToDtoAsync(db, ov));
});
return app;
}
private static async Task<VerifiedGerbilDto> ToDtoAsync(
ApplicationContext db, GerbilOverride ov, HashSet<Guid>? existingIds = null)
{
var exists = existingIds?.Contains(ov.GerbilId) ?? await db.Gerbils.AnyAsync(g => g.Id == ov.GerbilId);
var diffs = DeserializeDiff(ov.LastImportDiffJson);
var status = !exists ? "missing" : (diffs.Count > 0 ? "drifted" : "unchanged");
return new VerifiedGerbilDto(
ov.GerbilId, ov.EntityName, ov.IsVerified, status, ov.VerifiedAt, ov.UpdatedAt, ov.Note,
ExtractFieldKeys(ov.OverrideJson), diffs);
}
private static IReadOnlyList<SnapshotDiffDto> DeserializeDiff(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return Array.Empty<SnapshotDiffDto>();
try
{
var raw = JsonSerializer.Deserialize<List<SnapshotDiff>>(json, Json) ?? new();
return raw.Select(d => new SnapshotDiffDto(d.Path, d.GoldenValue, d.OtherValue)).ToList();
}
catch (JsonException) { return Array.Empty<SnapshotDiffDto>(); }
}
private static IReadOnlyList<string> ExtractFieldKeys(string? overrideJson)
{
if (string.IsNullOrWhiteSpace(overrideJson)) return Array.Empty<string>();
try
{
using var doc = JsonDocument.Parse(overrideJson);
if (doc.RootElement.ValueKind != JsonValueKind.Object) return Array.Empty<string>();
return doc.RootElement.EnumerateObject().Select(p => p.Name).ToList();
}
catch (JsonException) { return Array.Empty<string>(); }
}
}
}

View File

@@ -0,0 +1,122 @@
using GerbilManagerWebAPI.Dtos;
using GerbilManagerWebAPI.Models;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
namespace GerbilManagerWebAPI.Endpoints
{
/// <summary>
/// WAITLIST (RennmausPro nachfrage_tb): a standing list of interested parties waiting
/// for a future animal matching their wish criteria (colour, gender).
/// GET /waiting-list -> list entries, newest request first
/// POST /waiting-list -> create an entry (returns 201)
/// PUT /waiting-list/{id} -> update / change status
/// DELETE /waiting-list/{id} -> remove an entry
/// Decoupled from contacts (loose nullable ContactId, no FK), so rows survive the
/// import re-ingest wipe — exactly like Feedback.
/// </summary>
public static class WaitingListEndpoints
{
/// <summary>Allowed workflow statuses (frontend contract).</summary>
private static readonly string[] AllowedStatuses = { "offen", "erfuellt", "storniert" };
private const string DefaultStatus = "offen";
public static IEndpointRouteBuilder MapWaitingListEndpoints(this IEndpointRouteBuilder app)
{
var group = app.MapGroup("/waiting-list").WithTags("WaitingList");
group.MapGet("/", async (ApplicationContext db) =>
{
// Order in memory: SQLite (test host) cannot ORDER BY a DateTimeOffset column,
// and RequestedAt is nullable — sort entries with a date first, newest first.
var rows = await db.WaitingListEntries.AsNoTracking().ToListAsync();
return TypedResults.Ok(rows
.OrderByDescending(e => e.RequestedAt ?? DateTime.MinValue)
.ThenByDescending(e => e.CreatedAt)
.Select(ToDto)
.ToList());
});
group.MapGet("/{id:guid}", async Task<Results<Ok<WaitingListDto>, NotFound>> (
Guid id, ApplicationContext db) =>
{
var entity = await db.WaitingListEntries.AsNoTracking().FirstOrDefaultAsync(e => e.Id == id);
return entity is null ? TypedResults.NotFound() : TypedResults.Ok(ToDto(entity));
});
group.MapPost("/", async Task<Results<Created<WaitingListDto>, BadRequest<string>>> (
WaitingListInput input, ApplicationContext db) =>
{
var status = NormalizeStatus(input.Status);
if (status is null)
return TypedResults.BadRequest("Ungültiger Status.");
if (string.IsNullOrWhiteSpace(input.ContactName) && input.ContactId is null)
return TypedResults.BadRequest("Kontakt oder Name ist erforderlich.");
var entity = new WaitingListEntry
{
Id = Guid.NewGuid(),
ContactId = input.ContactId,
ContactName = Trim(input.ContactName),
WishColor = Trim(input.WishColor),
WishGender = Trim(input.WishGender),
RequestedAt = input.RequestedAt,
Status = status,
Note = Trim(input.Note),
CreatedAt = DateTimeOffset.UtcNow,
};
db.WaitingListEntries.Add(entity);
await db.SaveChangesAsync();
return TypedResults.Created($"/waiting-list/{entity.Id}", ToDto(entity));
});
group.MapPut("/{id:guid}", async Task<Results<Ok<WaitingListDto>, NotFound, BadRequest<string>>> (
Guid id, WaitingListInput input, ApplicationContext db) =>
{
var entity = await db.WaitingListEntries.FirstOrDefaultAsync(e => e.Id == id);
if (entity is null) return TypedResults.NotFound();
var status = NormalizeStatus(input.Status);
if (status is null)
return TypedResults.BadRequest("Ungültiger Status.");
if (string.IsNullOrWhiteSpace(input.ContactName) && input.ContactId is null)
return TypedResults.BadRequest("Kontakt oder Name ist erforderlich.");
entity.ContactId = input.ContactId;
entity.ContactName = Trim(input.ContactName);
entity.WishColor = Trim(input.WishColor);
entity.WishGender = Trim(input.WishGender);
entity.RequestedAt = input.RequestedAt;
entity.Status = status;
entity.Note = Trim(input.Note);
await db.SaveChangesAsync();
return TypedResults.Ok(ToDto(entity));
});
group.MapDelete("/{id:guid}", async Task<Results<NoContent, NotFound>> (
Guid id, ApplicationContext db) =>
{
var entity = await db.WaitingListEntries.FirstOrDefaultAsync(e => e.Id == id);
if (entity is null) return TypedResults.NotFound();
db.WaitingListEntries.Remove(entity);
await db.SaveChangesAsync();
return TypedResults.NoContent();
});
return app;
}
/// <summary>Empty/whitespace status defaults to "offen"; unknown values are rejected (null).</summary>
private static string? NormalizeStatus(string? status)
{
if (string.IsNullOrWhiteSpace(status)) return DefaultStatus;
var trimmed = status.Trim();
return AllowedStatuses.Contains(trimmed) ? trimmed : null;
}
private static string? Trim(string? s) => string.IsNullOrWhiteSpace(s) ? null : s.Trim();
private static WaitingListDto ToDto(WaitingListEntry e) =>
new(e.Id, e.ContactId, e.ContactName, e.WishColor, e.WishGender, e.RequestedAt, e.Status, e.Note, e.CreatedAt);
}
}

View File

@@ -48,9 +48,11 @@ namespace GerbilManagerWebAPI.Export
private static readonly Dictionary<GerbilStatus, string> StatusDe = new()
{
[GerbilStatus.Active] = "Aktiv",
[GerbilStatus.Breeding] = "Zucht",
[GerbilStatus.Deceased] = "Verstorben",
[GerbilStatus.GivenAway] = "Abgegeben",
[GerbilStatus.ForSale] = "Abzugeben",
[GerbilStatus.Pet] = "Liebhaber",
};
private static readonly Dictionary<HealthRecordType, string> HealthTypeDe = new()

View File

@@ -12,6 +12,8 @@
<PackageReference Include="DocumentFormat.OpenXml" Version="3.5.1" />
<PackageReference Include="MailKit" Version="4.17.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.8" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.8" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="10.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.8">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
@@ -20,7 +22,9 @@
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.2" />
<PackageReference Include="Gridify" Version="2.19.1" />
<PackageReference Include="Gridify.EntityFramework" Version="2.19.1" />
<PackageReference Include="QuestPDF" Version="2026.6.0" />
<PackageReference Include="Scalar.AspNetCore" Version="2.14.14" />
<PackageReference Include="WebPush" Version="1.0.13" />
</ItemGroup>
<ItemGroup>
@@ -32,6 +36,12 @@
<EmbeddedResource Include="Contracts\Templates\Abgabevertrag.docx" />
</ItemGroup>
<ItemGroup>
<!-- Manuelle RPRO3-Dubletten-Entscheidungen der Züchterin (Rpro3Decisions) — ins Output kopieren,
damit der Importer sie zur Laufzeit findet. -->
<Content Update="Import\Rpro3\rpro3-decisions.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup>
<!-- FEAT-12a: Tests prüfen interne Bausteine (z. B. die Completions-URL). -->
<InternalsVisibleTo Include="GerbilManager.Tests" />

View File

@@ -0,0 +1,307 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using GerbilManagerWebAPI.Models;
using Microsoft.EntityFrameworkCore;
namespace GerbilManagerWebAPI.Import
{
// ── Canonical, human-readable "Akte" snapshot ────────────────────────────
// Names (not ids) are stored so the golden state stays human-verifiable and robust to
// deterministic-id reseeds. Used for the drift report, the export fixture and the
// regression test. Lists are sorted canonically by the builder so equality is stable.
public sealed record GerbilSnapshot(
SnapshotSelf Self,
SnapshotParent? Father,
SnapshotParent? Mother,
List<SnapshotLitter> Litters);
public sealed record SnapshotSelf(
string Name, string Gender, string? DateOfBirth, string? DateOfDeath, string? CauseOfDeath,
string? GoHomeDate, string? Genotype, string? SpottingType, string? ColorName,
bool IsResident, bool? IsDeaf, bool IsCastrated, string? OriginBreeder,
string? OriginContactName, string? ReceiverContactName, string? Notes,
List<string> CharacterTraits, string? CharacterNote, string? BirthLitterName);
public sealed record SnapshotParent(string Name, string? DateOfBirth, string? Genotype);
public sealed record SnapshotLitter(
string Name, string? Date, string Role, int? TotalBorn, bool ShowInChronicle,
List<SnapshotChild> Children);
public sealed record SnapshotChild(string Name, string? DateOfBirth, string Gender);
/// <summary>One field-level difference between two snapshots (golden ↔ current/raw import).</summary>
public sealed record SnapshotDiff(string Path, string? GoldenValue, string? OtherValue);
/// <summary>
/// Builds the canonical Akte snapshot for a gerbil, the machine-readable freeze map (own fields
/// that "vollständig korrekt" pins), applies an override onto a gerbil, and diffs two snapshots.
/// SHARED by the app (endpoints + ingest freeze) and the regression test so the comparison logic
/// can never drift between the two.
/// </summary>
public static class GerbilSnapshotService
{
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
/// <summary>Own-field keys that the "vollständig korrekt" freeze pins. Deliberately excludes
/// Status (lifecycle, derived) and EnclosureId (current location) and LitterId/lineage
/// (abstammung is detect-only). Keys match the JSON serialised in <see cref="BuildFreezeObject"/>.</summary>
public static readonly IReadOnlyList<string> FreezeFields = new[]
{
"name", "gender", "dateOfBirth", "dateOfDeath", "causeOfDeath", "goHomeDate",
"genotype", "spottingType", "colorVarietyId", "isResident", "isDeaf", "isCastrated",
"originBreeder", "originContactId", "receiverContactId", "notes",
"characterTraits", "characterNote",
};
// ── Snapshot (human-readable Akte) ───────────────────────────────────
public static async Task<GerbilSnapshot?> BuildSnapshotAsync(ApplicationContext db, Guid gerbilId)
{
var g = await db.Gerbils.AsNoTracking().FirstOrDefaultAsync(x => x.Id == gerbilId);
if (g is null) return null;
var colorName = g.ColorVarietyId is { } cv
? await db.ColorVarieties.AsNoTracking().Where(c => c.Id == cv).Select(c => c.Name).FirstOrDefaultAsync()
: null;
var originName = g.OriginContactId is { } oc
? await db.Contacts.AsNoTracking().Where(c => c.Id == oc).Select(c => c.Name).FirstOrDefaultAsync()
: null;
var receiverName = g.ReceiverContactId is { } rc
? await db.Contacts.AsNoTracking().Where(c => c.Id == rc).Select(c => c.Name).FirstOrDefaultAsync()
: null;
// Birth litter → parents.
Litter? birthLitter = g.LitterId is { } lid
? await db.Litters.AsNoTracking().FirstOrDefaultAsync(l => l.Id == lid)
: null;
var father = await BuildParentAsync(db, birthLitter?.FatherId);
var mother = await BuildParentAsync(db, birthLitter?.MotherId);
// Own litters (as parent) + children.
var ownLitters = await db.Litters.AsNoTracking()
.Where(l => l.FatherId == gerbilId || l.MotherId == gerbilId)
.ToListAsync();
var ownLitterIds = ownLitters.Select(l => l.Id).ToList();
var children = ownLitterIds.Count == 0
? new List<Gerbil>()
: await db.Gerbils.AsNoTracking().Where(c => c.LitterId != null && ownLitterIds.Contains(c.LitterId.Value)).ToListAsync();
var litterSnaps = ownLitters
.Select(l => new SnapshotLitter(
l.Name,
Iso(l.Date),
l.FatherId == gerbilId ? "father" : "mother",
l.TotalBorn,
l.ShowInChronicle,
children.Where(c => c.LitterId == l.Id)
.Select(c => new SnapshotChild(c.Name, Iso(c.DateOfBirth), c.Gender.ToString()))
.OrderBy(c => c.DateOfBirth ?? "", StringComparer.Ordinal)
.ThenBy(c => c.Name, StringComparer.Ordinal)
.ThenBy(c => c.Gender, StringComparer.Ordinal)
.ToList()))
.OrderBy(l => l.Date ?? "", StringComparer.Ordinal)
.ThenBy(l => l.Name, StringComparer.Ordinal)
.ToList();
var self = new SnapshotSelf(
g.Name, g.Gender.ToString(), Iso(g.DateOfBirth), Iso(g.DateOfDeath), g.CauseOfDeath,
Iso(g.GoHomeDate), g.Genotype, g.SpottingType, colorName,
g.IsResident, g.IsDeaf, g.IsCastrated, g.OriginBreeder,
originName, receiverName, g.Notes,
(g.CharacterTraits ?? new List<string>()).OrderBy(t => t, StringComparer.Ordinal).ToList(),
g.CharacterNote, birthLitter?.Name);
return new GerbilSnapshot(self, father, mother, litterSnaps);
}
private static async Task<SnapshotParent?> BuildParentAsync(ApplicationContext db, Guid? parentId)
{
if (parentId is not { } pid) return null;
var p = await db.Gerbils.AsNoTracking().Where(x => x.Id == pid)
.Select(x => new { x.Name, x.DateOfBirth, x.Genotype }).FirstOrDefaultAsync();
return p is null ? null : new SnapshotParent(p.Name, Iso(p.DateOfBirth), p.Genotype);
}
public static string SerializeSnapshot(GerbilSnapshot snap) => JsonSerializer.Serialize(snap, Json);
public static GerbilSnapshot? DeserializeSnapshot(string? json) =>
string.IsNullOrWhiteSpace(json) ? null : JsonSerializer.Deserialize<GerbilSnapshot>(json, Json);
// ── Diff (golden ↔ other) ────────────────────────────────────────────
/// <summary>Flat, human-readable field diff between a golden snapshot and another (current
/// DB or raw import) snapshot. Empty = identical.</summary>
public static List<SnapshotDiff> Diff(GerbilSnapshot? golden, GerbilSnapshot? other)
{
var g = golden is null ? new Dictionary<string, string?>() : Flatten(golden);
var o = other is null ? new Dictionary<string, string?>() : Flatten(other);
var diffs = new List<SnapshotDiff>();
foreach (var key in g.Keys.Union(o.Keys).OrderBy(k => k, StringComparer.Ordinal))
{
var gv = g.GetValueOrDefault(key);
var ov = o.GetValueOrDefault(key);
if (!string.Equals(gv, ov, StringComparison.Ordinal))
diffs.Add(new SnapshotDiff(key, gv, ov));
}
return diffs;
}
private static Dictionary<string, string?> Flatten(GerbilSnapshot s)
{
var d = new Dictionary<string, string?>(StringComparer.Ordinal)
{
["name"] = s.Self.Name,
["gender"] = s.Self.Gender,
["dateOfBirth"] = s.Self.DateOfBirth,
["dateOfDeath"] = s.Self.DateOfDeath,
["causeOfDeath"] = s.Self.CauseOfDeath,
["goHomeDate"] = s.Self.GoHomeDate,
["genotype"] = s.Self.Genotype,
["spottingType"] = s.Self.SpottingType,
["colorName"] = s.Self.ColorName,
["isResident"] = s.Self.IsResident.ToString(),
["isDeaf"] = s.Self.IsDeaf?.ToString(),
["isCastrated"] = s.Self.IsCastrated.ToString(),
["originBreeder"] = s.Self.OriginBreeder,
["originContact"] = s.Self.OriginContactName,
["receiverContact"] = s.Self.ReceiverContactName,
["notes"] = s.Self.Notes,
["characterTraits"] = string.Join(", ", s.Self.CharacterTraits),
["characterNote"] = s.Self.CharacterNote,
["birthLitter"] = s.Self.BirthLitterName,
["father"] = FormatParent(s.Father),
["mother"] = FormatParent(s.Mother),
};
foreach (var l in s.Litters)
{
var lk = $"wurf[{l.Name} {l.Date}]";
d[$"{lk}.rolle"] = l.Role;
d[$"{lk}.geboren"] = l.TotalBorn?.ToString();
d[$"{lk}.inChronik"] = l.ShowInChronicle.ToString();
foreach (var c in l.Children)
d[$"{lk}.kind[{c.Name} {c.DateOfBirth}]"] = c.Gender;
}
return d;
}
private static string? FormatParent(SnapshotParent? p) =>
p is null ? null : $"{p.Name} (*{p.DateOfBirth}) {p.Genotype}".Trim();
// ── Freeze map (machine-readable own-field override) ─────────────────
/// <summary>Builds the full own-field freeze object (all <see cref="FreezeFields"/>) from a
/// gerbil's current values. Used by verify (store as OverrideJson) and by the per-field
/// edit-protection diff.</summary>
public static JsonObject BuildFreezeObject(Gerbil g)
{
var o = new JsonObject
{
["name"] = g.Name,
["gender"] = g.Gender.ToString(),
["dateOfBirth"] = Iso(g.DateOfBirth),
["dateOfDeath"] = Iso(g.DateOfDeath),
["causeOfDeath"] = g.CauseOfDeath,
["goHomeDate"] = Iso(g.GoHomeDate),
["genotype"] = g.Genotype,
["spottingType"] = g.SpottingType,
["colorVarietyId"] = g.ColorVarietyId?.ToString(),
["isResident"] = g.IsResident,
["isDeaf"] = g.IsDeaf,
["isCastrated"] = g.IsCastrated,
["originBreeder"] = g.OriginBreeder,
["originContactId"] = g.OriginContactId?.ToString(),
["receiverContactId"] = g.ReceiverContactId?.ToString(),
["notes"] = g.Notes,
["characterTraits"] = new JsonArray((g.CharacterTraits ?? new List<string>()).Select(t => (JsonNode?)JsonValue.Create(t)).ToArray()),
["characterNote"] = g.CharacterNote,
};
return o;
}
public static string BuildFreezeJson(Gerbil g) => BuildFreezeObject(g).ToJsonString(Json);
/// <summary>Per-field change detection for the PUT edit-protection path. Returns the subset of
/// freeze keys whose value differs between <paramref name="before"/> and <paramref name="after"/>,
/// as a JsonObject carrying the AFTER values (the ones to pin). Empty if nothing relevant changed.</summary>
public static JsonObject ChangedFields(JsonObject before, JsonObject after)
{
var changed = new JsonObject();
foreach (var key in FreezeFields)
{
var b = before[key]?.ToJsonString() ?? "null";
var a = after[key]?.ToJsonString() ?? "null";
if (!string.Equals(b, a, StringComparison.Ordinal))
changed[key] = after[key] is { } node ? node.DeepClone() : null;
}
return changed;
}
/// <summary>Merge <paramref name="incoming"/> field values into an existing override JSON
/// object (incoming wins). Returns the merged JSON string.</summary>
public static string MergeOverrideJson(string? existingJson, JsonObject incoming)
{
var baseObj = ParseObject(existingJson) ?? new JsonObject();
foreach (var kv in incoming)
baseObj[kv.Key] = kv.Value is { } n ? n.DeepClone() : null;
return baseObj.ToJsonString(Json);
}
/// <summary>Applies a stored override JSON object onto a gerbil, writing only the keys present
/// (the "freeze"). Unknown keys are ignored.</summary>
public static void ApplyOverride(Gerbil g, string? overrideJson)
{
var o = ParseObject(overrideJson);
if (o is null) return;
foreach (var kv in o)
{
var v = kv.Value;
switch (kv.Key)
{
case "name": if (Str(v) is { Length: > 0 } nm) g.Name = nm; break;
case "gender": if (Str(v) is { } gd && Enum.TryParse<Gender>(gd, out var gender)) g.Gender = gender; break;
case "dateOfBirth": g.DateOfBirth = Date(v); break;
case "dateOfDeath": g.DateOfDeath = Date(v); break;
case "causeOfDeath": g.CauseOfDeath = Str(v); break;
case "goHomeDate": g.GoHomeDate = Date(v); break;
case "genotype": g.Genotype = Str(v); break;
case "spottingType": g.SpottingType = Str(v); break;
case "colorVarietyId": g.ColorVarietyId = Guid_(v); break;
case "isResident": g.IsResident = Bool(v) ?? g.IsResident; break;
case "isDeaf": g.IsDeaf = Bool(v); break;
case "isCastrated": g.IsCastrated = Bool(v) ?? g.IsCastrated; break;
case "originBreeder": g.OriginBreeder = Str(v); break;
case "originContactId": g.OriginContactId = Guid_(v); break;
case "receiverContactId": g.ReceiverContactId = Guid_(v); break;
case "notes": g.Notes = Str(v); break;
case "characterTraits": g.CharacterTraits = StrList(v); break;
case "characterNote": g.CharacterNote = Str(v); break;
}
}
}
// ── JSON helpers ─────────────────────────────────────────────────────
private static JsonObject? ParseObject(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return null;
try { return JsonNode.Parse(json) as JsonObject; }
catch (JsonException) { return null; }
}
private static string? Str(JsonNode? n) => n?.GetValueKind() == JsonValueKind.String ? n.GetValue<string>() : null;
private static bool? Bool(JsonNode? n) => n?.GetValueKind() is JsonValueKind.True or JsonValueKind.False ? n!.GetValue<bool>() : null;
private static Guid? Guid_(JsonNode? n) => Guid.TryParse(Str(n), out var id) ? id : null;
private static DateOnly? Date(JsonNode? n) => DateOnly.TryParse(Str(n), out var d) ? d : null;
private static List<string> StrList(JsonNode? n)
{
if (n is JsonArray arr)
return arr.Where(x => x is not null).Select(x => x!.GetValue<string>()).ToList();
return new List<string>();
}
private static string? Iso(DateOnly? d) => d?.ToString("yyyy-MM-dd");
}
}

View File

@@ -0,0 +1,437 @@
using System.Text.Json;
using GerbilManagerWebAPI.Models;
using GerbilManagerWebAPI.Services;
using Microsoft.EntityFrameworkCore;
namespace GerbilManagerWebAPI.Import
{
/// <summary>
/// FEAT-8d docx loader. Consumes tools/import/output/docx_litters.json +
/// docx_animals.json (produced by extract_docx.py) and enriches OR CREATES animals.
///
/// Load policy (IDEMPOTENT NACHZUG after main WIPE+REIMPORT):
/// Match order per docx row:
/// 1. ExternalRef "docx-…" (previously created by this loader) → enrich (fill-NULL-only)
/// 2. normalize(name)+litterDob in Gerbils (from main import) → enrich (fill-NULL-only)
/// 3. No match → CREATE: abgegebene Jungtiere that never appeared in the pedigree charts.
///
/// Created animals: Status=GivenAway (or Deceased), IsResident=false,
/// OriginBreeder='Zucht der Kleinen Chaoten', ImportSource="docx",
/// ExternalRef = stable "docx-{ws}-{normname}-{litterDob}[-N]" key (idempotent;
/// -N ordinal suffix disambiguates same-name siblings in a litter).
///
/// NEVER overwrites a manually-set non-null value (fill-NULL-only for all fields).
///
/// Idempotent: running multiple times is safe. Re-run finds existing rows via ExternalRef.
/// Execute wraps all writes in a single transaction via CreateExecutionStrategy() so that
/// providers using EnableRetryOnFailure (e.g. NpgsqlRetryingExecutionStrategy) are
/// compatible. The strategy lambda resets all mutable state at the top so it is safe
/// to re-run on transient-failure retry.
/// Execute is gated by the endpoint; this service only acts when asked.
/// </summary>
public sealed class ImportDocxService
{
private static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true };
private readonly ApplicationContext _db;
private readonly string _sourceDir;
public ImportDocxService(ApplicationContext db, IConfiguration config, IWebHostEnvironment env)
: this(db,
config["Import:SourcePath"]
?? Path.GetFullPath(Path.Combine(env.ContentRootPath, "..", "tools", "import", "output")))
{ }
public ImportDocxService(ApplicationContext db, string sourceDir)
{
_db = db;
_sourceDir = sourceDir;
}
public async Task<ImportDocxReport> RunAsync(bool execute)
{
var notes = new List<string>();
var docxLitters = Load<List<DocxLitter>>("docx_litters.json") ?? new();
var docxAnimals = Load<List<DocxAnimal>>("docx_animals.json") ?? new();
var pdfLitters = Load<List<DocxLitter>>("pdf_litters.json") ?? new();
var pdfAnimals = Load<List<DocxAnimal>>("pdf_animals.json") ?? new();
int docxLitCount = docxLitters.Count;
int docxAnimCount = docxAnimals.Count;
int pdfLitCount = pdfLitters.Count;
int pdfAnimCount = pdfAnimals.Count;
docxLitters.AddRange(pdfLitters);
docxAnimals.AddRange(pdfAnimals);
if (docxLitters.Count == 0 && docxAnimals.Count == 0)
{
notes.Add($"Keine Quelldaten in {_sourceDir} (docx_litters.json/docx_animals.json oder pdf_litters.json/pdf_animals.json). " +
"extract_docx.py zuerst ausführen oder PDF-VLM-Daten bereitstellen.");
return new ImportDocxReport(false, 0, 0, 0, 0, 0, 0, 0, notes);
}
// Litter lookup by birth date (DayNumber) → list of matching DB litters.
// NOTE: WsCode in docx is a litter-size fraction ("4/4", "/5") — NOT a PairingCode.
// Date-only lookup with uniqueness guard avoids false links (only link when
// exactly one DB litter falls within ±5 days of the docx litter DOB).
var littersInDb = await _db.Litters
.Select(l => new { l.Id, l.Date })
.ToListAsync();
var littersByDayNumber = littersInDb
.Where(l => l.Date.HasValue)
.GroupBy(l => l.Date!.Value.DayNumber)
.ToDictionary(g => g.Key, g => g.ToList());
// normalize(name)+litterDob → Gerbil snapshot (main-import enrich path)
var gerbilsInDb = await _db.Gerbils
.Select(g => new { g.Id, g.Name, g.DateOfBirth, g.LitterId,
g.ReceiverContactId, g.GoHomeDate, g.DateOfDeath, g.CauseOfDeath,
g.ExternalRef })
.ToListAsync();
var gerbilByKey = gerbilsInDb
.Where(g => g.DateOfBirth is not null)
.GroupBy(g => NameDobKey(g.Name, g.DateOfBirth!.Value))
.ToDictionary(g => g.Key, g => g.ToList());
// ExternalRef → snapshot for previously docx-created animals (idempotency across runs)
var docxExternalRefs = gerbilsInDb
.Where(g => g.ExternalRef?.StartsWith("docx-") == true)
.ToDictionary(g => g.ExternalRef!,
g => new { g.Id, g.LitterId, g.GoHomeDate, g.DateOfDeath, g.ReceiverContactId });
// Contact lookup: normalized name → existing Contact.Id
var contactsInDb = await _db.Contacts
.Select(c => new { c.Id, c.Name })
.ToListAsync();
var contactByNorm = contactsInDb
.GroupBy(c => NormalizeName(c.Name))
.ToDictionary(g => g.Key, g => g.First().Id);
// Snapshot of DB contacts before any writes.
// Used to reset contactByNorm on strategy retry (rolled-back contacts vanish from DB
// but would remain in the in-memory dict without this reset).
var contactByNormBase = new Dictionary<string, Guid>(contactByNorm);
// ColorVariety lookup: normalized name → Id (for CREATE path Farbschlag matching)
var colorVarietyByName = (await _db.ColorVarieties
.Select(cv => new { cv.Id, cv.Name })
.ToListAsync())
.GroupBy(cv => NormalizeName(cv.Name))
.ToDictionary(g => g.Key, g => g.First().Id);
int animalsCreated = 0, litterLinked = 0, goHomeFilled = 0, deathFilled = 0;
int ownerLinked = 0, ownerCreated = 0, skipped = 0;
// Ordinal counter for collision-free ExternalRef within this batch.
var externalRefOrdinals = new Dictionary<string, int>();
// Belt-and-suspenders: guard against adding the same ExternalRef twice in one run.
var batchRefs = new HashSet<string>();
// Inner loop — shared by dry-run and execute paths.
// All local variables above are captured by reference (C# closure), so the strategy
// lambda can reset them before each retry and RunLoopAsync sees the fresh state.
async Task RunLoopAsync()
{
foreach (var da in docxAnimals)
{
if (string.IsNullOrWhiteSpace(da.Name)) { skipped++; continue; }
// Collision-free ExternalRef: ordinal suffix for same-name siblings
var baseRef = DocxExternalRefBase(da);
externalRefOrdinals.TryGetValue(baseRef, out var ord);
ord++;
externalRefOrdinals[baseRef] = ord;
var externalRef = ord == 1 ? baseRef : $"{baseRef}-{ord}";
// Resolve litter: date ±5 days, unambiguous (exactly one candidate)
Guid? litterId = null;
if (!string.IsNullOrWhiteSpace(da.LitterDob))
{
var litterDob = ParseDate(da.LitterDob);
if (litterDob is not null)
{
var candidates = new List<Guid>();
for (int delta = -5; delta <= 5; delta++)
{
if (littersByDayNumber.TryGetValue(litterDob.Value.DayNumber + delta, out var cl))
candidates.AddRange(cl.Select(l => l.Id));
}
if (candidates.Count == 1)
litterId = candidates[0];
// If 0 or >1 candidates: no link (avoid false links)
}
}
// Animal DOB = litter birth date (docx has no per-animal DOB)
var animalDob = litterId is not null
? (await _db.Litters.Where(l => l.Id == litterId).Select(l => (DateOnly?)l.Date).FirstOrDefaultAsync())
: ParseDate(da.LitterDob);
if (animalDob is null) { skipped++; continue; }
var goHomeDate = ParseDate(da.AbgabeDate);
var deathDate = ParseDate(da.DeathDate);
// Resolve receiver contact (lookup-or-create; shared by all paths)
Guid? receiverId = null;
if (!string.IsNullOrWhiteSpace(da.Owner))
{
var normOwner = NormalizeName(da.Owner);
if (contactByNorm.TryGetValue(normOwner, out var existingContactId))
{
receiverId = existingContactId;
ownerLinked++;
}
else
{
ownerCreated++;
if (execute)
{
var newContact = new Contact { Id = Guid.NewGuid(), Name = da.Owner.Trim() };
_db.Contacts.Add(newContact);
await _db.SaveChangesAsync(); // flush within the outer tx
receiverId = newContact.Id;
contactByNorm[normOwner] = receiverId.Value;
}
}
}
// ── PATH 1: previously docx-created animal (idempotent re-run) ──────────
if (docxExternalRefs.TryGetValue(externalRef, out var prevSnap))
{
bool willLink = litterId is not null && prevSnap.LitterId is null;
bool willHome = goHomeDate is not null && prevSnap.GoHomeDate is null;
bool willDeath = deathDate is not null && prevSnap.DateOfDeath is null;
if (willLink) litterLinked++;
if (willHome) goHomeFilled++;
if (willDeath) deathFilled++;
if (execute)
{
var row = await _db.Gerbils.FirstOrDefaultAsync(g => g.Id == prevSnap.Id);
if (row is null) continue;
if (willLink) row.LitterId = litterId;
if (receiverId is not null && row.ReceiverContactId is null) row.ReceiverContactId = receiverId;
if (willHome) row.GoHomeDate = goHomeDate;
if (willDeath)
{
row.DateOfDeath = deathDate;
if (!string.IsNullOrWhiteSpace(da.DeathCause) && row.CauseOfDeath is null)
row.CauseOfDeath = da.DeathCause.Trim();
}
}
continue;
}
// ── PATH 2: main-import animal matched by name+dob ───────────────────────
var nameKey = NameDobKey(da.Name, animalDob.Value);
if (gerbilByKey.TryGetValue(nameKey, out var gerbilCands))
{
var gerbilSnap = gerbilCands.FirstOrDefault(g => g.LitterId == null)
?? gerbilCands.First();
bool willLink = litterId is not null && gerbilSnap.LitterId is null;
bool willHome = goHomeDate is not null && gerbilSnap.GoHomeDate is null;
bool willDeath = deathDate is not null && gerbilSnap.DateOfDeath is null;
if (willLink) litterLinked++;
if (willHome) goHomeFilled++;
if (willDeath) deathFilled++;
if (execute)
{
var row = await _db.Gerbils.FirstOrDefaultAsync(g => g.Id == gerbilSnap.Id);
if (row is null) continue;
if (willLink) row.LitterId = litterId;
if (receiverId is not null && row.ReceiverContactId is null) row.ReceiverContactId = receiverId;
if (willHome) row.GoHomeDate = goHomeDate;
if (willDeath)
{
row.DateOfDeath = deathDate;
if (!string.IsNullOrWhiteSpace(da.DeathCause) && row.CauseOfDeath is null)
row.CauseOfDeath = da.DeathCause.Trim();
}
}
continue;
}
// ── PATH 3: no match → CREATE ────────────────────────────────────────────
// Belt-and-suspenders: ordinal should ensure uniqueness, but guard anyway
if (!batchRefs.Add(externalRef)) { skipped++; continue; }
animalsCreated++;
if (litterId is not null) litterLinked++;
if (goHomeDate is not null) goHomeFilled++;
if (deathDate is not null) deathFilled++;
if (execute)
{
colorVarietyByName.TryGetValue(NormalizeName(da.Farbschlag ?? ""), out var cvId);
_db.Gerbils.Add(new Gerbil
{
Id = Guid.NewGuid(),
Name = da.Name.Trim(),
DateOfBirth = animalDob,
Gender = ParseGender(da.Gender),
Status = GerbilStatusService.Derive(GerbilStatus.GivenAway, animalDob, deathDate, isAbgegeben: receiverId is not null, DateOnly.FromDateTime(DateTime.UtcNow)),
LitterId = litterId,
ReceiverContactId = receiverId,
GoHomeDate = goHomeDate,
DateOfDeath = deathDate,
CauseOfDeath = string.IsNullOrWhiteSpace(da.DeathCause) ? null : da.DeathCause.Trim(),
ColorVarietyId = cvId == default ? null : cvId,
OriginBreeder = "Zucht der kleinen Chaoten",
IsResident = false,
ImportSource = "docx",
ExternalRef = externalRef,
});
}
}
}
if (!execute)
{
// Dry-run: just count, no writes, no transaction needed.
await RunLoopAsync();
}
else
{
// Execute: wrap the entire transaction in the execution strategy so that providers
// with EnableRetryOnFailure (NpgsqlRetryingExecutionStrategy) are compatible.
// The lambda resets all mutable state at the top so retries start clean.
var strategy = _db.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () =>
{
// Reset mutable state — idempotent on strategy retry
_db.ChangeTracker.Clear();
externalRefOrdinals.Clear();
batchRefs.Clear();
animalsCreated = 0; litterLinked = 0; goHomeFilled = 0; deathFilled = 0;
ownerLinked = 0; ownerCreated = 0; skipped = 0;
// Rebuild from DB snapshot: contacts added in a failed attempt were rolled back
contactByNorm = new Dictionary<string, Guid>(contactByNormBase);
await using var tx = await _db.Database.BeginTransactionAsync();
await RunLoopAsync();
if ((animalsCreated + litterLinked + goHomeFilled + deathFilled + ownerCreated) > 0)
await _db.SaveChangesAsync();
await tx.CommitAsync();
});
}
notes.Add($"Quelle: {docxLitCount} Würfe / {docxAnimCount} Tiere aus DOCX. {pdfLitCount} Würfe / {pdfAnimCount} Tiere aus PDF.");
notes.Add($"Neu angelegt: {animalsCreated} Jungtiere (abgegeben, nicht in Stammbäumen).");
notes.Add($"Litter-Links: {litterLinked} Tiere einem Wurf zugeordnet (DOB-Match ±5 Tage, eindeutig).");
notes.Add($"Abnehmer: {ownerLinked} bestehende Kontakte verknüpft, {ownerCreated} neue Kontakte angelegt.");
notes.Add($"GoHomeDate: {goHomeFilled} Abgabe-Daten nachgetragen.");
notes.Add($"Tod-Datum: {deathFilled} Todesdaten nachgetragen.");
notes.Add($"Übersprungen: {skipped} Zeilen (kein Name oder kein Datum).");
if (!execute) notes.Add("DRY-RUN: nichts gespeichert. /import/docx/execute schreibt die Änderungen.");
return new ImportDocxReport(execute, animalsCreated, litterLinked, ownerLinked + ownerCreated,
goHomeFilled, deathFilled, ownerCreated, skipped, notes);
}
private T? Load<T>(string file)
{
var path = Path.Combine(_sourceDir, file);
if (!File.Exists(path)) return default;
using var fs = File.OpenRead(path);
return JsonSerializer.Deserialize<T>(fs, Json);
}
private static DateOnly? ParseDate(string? s)
{
if (string.IsNullOrWhiteSpace(s)) return null;
var m = System.Text.RegularExpressions.Regex.Match(s,
@"(\d{1,2})\.(\d{1,2})\.(\d{2,4})");
if (!m.Success) return null;
int d = int.Parse(m.Groups[1].Value), mo = int.Parse(m.Groups[2].Value);
int y = int.Parse(m.Groups[3].Value);
if (y < 100) y += 2000;
try { return new DateOnly(y, mo, d); } catch { return null; }
}
private static string NameDobKey(string name, DateOnly dob)
{
var n = System.Text.RegularExpressions.Regex.Replace(
(name ?? "").ToLowerInvariant(), @"[^a-z0-9äöüß]", "");
return $"{n}|{dob:yyyy-MM-dd}";
}
private static string NormalizeName(string name)
{
var n = (name ?? "").ToLowerInvariant();
n = System.Text.RegularExpressions.Regex.Replace(n, @"\s+", " ").Trim();
return n;
}
/// <summary>
/// Base ExternalRef key (before ordinal disambiguation). Two animals sharing the same
/// ws+name+litterDob get this same base; the caller appends -2, -3 … for duplicates.
/// </summary>
internal static string DocxExternalRefBase(DocxAnimal da)
{
var ws = (da.WsCode ?? "").Replace(" ", "").ToLowerInvariant();
var name = System.Text.RegularExpressions.Regex.Replace(
(da.Name ?? "").ToLowerInvariant(), @"[^a-z0-9äöüß]", "");
return $"docx-{ws}-{name}-{da.LitterDob}";
}
private static Gender ParseGender(string? s)
{
if (string.IsNullOrWhiteSpace(s)) return Gender.unknown;
var lower = s.ToLowerInvariant();
if (lower == "male" || lower == "m" || lower.Contains("männ")) return Gender.male;
if (lower == "female" || lower == "f" || lower == "w" || lower.Contains("weibl")) return Gender.female;
return Gender.unknown;
}
}
// ---- Source shapes (from extract_docx.py output) ----
public sealed class DocxLitter
{
public string LitterId { get; set; } = "";
public string Dob { get; set; } = "";
public string MotherName { get; set; } = "";
public string FatherName { get; set; } = "";
public string WsCode { get; set; } = "";
public string Note { get; set; } = "";
}
public sealed class DocxAnimal
{
public string WsCode { get; set; } = "";
public string LitterDob { get; set; } = "";
public string Name { get; set; } = "";
public string Farbschlag { get; set; } = "";
public string Gender { get; set; } = "";
public string Owner { get; set; } = "";
public string AbgabeDate { get; set; } = "";
public string AbgabeWeight { get; set; } = "";
public string DeathDate { get; set; } = "";
public string DeathCause { get; set; } = "";
public string PartnerName { get; set; } = "";
public string PartnerDob { get; set; } = "";
}
// ---- Report ----
public sealed record ImportDocxReport(
bool Executed,
int Created,
int LitterLinked,
int OwnerLinked,
int GoHomeFilled,
int DeathFilled,
int ContactsCreated,
int Skipped,
IReadOnlyList<string> Notes);
}

View File

@@ -1,6 +1,7 @@
using System.Text.Json;
using System.Text.RegularExpressions;
using GerbilManagerWebAPI.Models;
using GerbilManagerWebAPI.Services;
using Microsoft.EntityFrameworkCore;
namespace GerbilManagerWebAPI.Import
@@ -82,7 +83,7 @@ namespace GerbilManagerWebAPI.Import
var existingLitterData = await _db.Litters
.Select(l => new { l.Name, l.Date, l.ExternalRef }).ToListAsync();
var existingLitterKeySet = existingLitterData
.Select(x => $"{x.Name}|{x.Date:yyyy-MM-dd}").ToHashSet();
.Select(x => $"{x.Name}|{(x.Date.HasValue ? x.Date.Value.ToString("yyyy-MM-dd") : "")}").ToHashSet();
var existingLitterExtRefSet = existingLitterData
.Where(x => x.ExternalRef != null)
.Select(x => x.ExternalRef!).ToHashSet();
@@ -289,10 +290,15 @@ namespace GerbilManagerWebAPI.Import
litterParents[lid] = (f, m);
}
// PASS 2: stage synthesized litters (parents already guarded above). DO NOT save them
// before the animals — the offspring AND the parent gerbils are created in the loop
// below, so a single SaveChanges at the end lets EF order parents→litters→offspring
// (all FKs are nullable). Saving litters first is exactly what caused the FK fault.
// FIX-IMPORT-CYCLE: track deferred synth litter parent FKs (populated in PASS 2 below).
// Synth litters are added with null FatherId/MotherId to break the Gerbil↔Litter cycle;
// the actual FKs are applied AFTER SaveChanges once all gerbils are persisted.
var synthLitterPendingParents = new Dictionary<Guid, (Guid? Father, Guid? Mother)>();
// PASS 2: stage synthesized litters (parents already guarded above). Litters are added
// with FatherId/MotherId = null (deferred) so that the SaveChanges below has only a
// one-directional Gerbil→Litter dependency — no Litter→Gerbil FKs in the same batch,
// which would cause EF's topo-sort to throw "circular dependency detected".
if (execute)
{
// reuse an existing litter with the same parents+date instead of duplicating.
@@ -301,13 +307,13 @@ namespace GerbilManagerWebAPI.Import
var litterByParentsDate = new Dictionary<string, Guid>();
foreach (var l in existingLitterRows)
{
litterByParentsDate[$"{l.FatherId}|{l.MotherId}|{l.Date:yyyy-MM-dd}"] = l.Id;
litterByParentsDate[$"{l.FatherId}|{l.MotherId}|{(l.Date.HasValue ? l.Date.Value.ToString("yyyy-MM-dd") : "")}"] = l.Id;
litterParents[l.Id] = (l.FatherId, l.MotherId);
}
foreach (var sl in synthLitters.Values.ToList())
{
var reuseKey = $"{sl.Father}|{sl.Mother}|{sl.Date:yyyy-MM-dd}";
var reuseKey = $"{sl.Father}|{sl.Mother}|{(sl.Date.HasValue ? sl.Date.Value.ToString("yyyy-MM-dd") : "")}";
if (litterByParentsDate.TryGetValue(reuseKey, out var existingId))
{
// remap offspring to the existing litter; don't create a duplicate.
@@ -316,13 +322,17 @@ namespace GerbilManagerWebAPI.Import
derivedLitters--;
continue;
}
// Defer FatherId/MotherId: both parent gerbils and offspring gerbils may be [Added]
// in this same batch. Setting them now causes EF circular dependency
// (Gerbil[Added] ← Litter.MotherId [Added] ← Gerbil.LitterId [Added]).
synthLitterPendingParents[sl.Id] = (sl.Father, sl.Mother);
_db.Litters.Add(new Litter
{
Id = sl.Id,
Name = $"Wurf (aus Diagramm) {sl.Date:yyyy-MM-dd}".Trim(),
Date = sl.Date ?? default,
FatherId = sl.Father,
MotherId = sl.Mother,
Name = $"Wurf (aus Diagramm) {(sl.Date.HasValue ? sl.Date.Value.ToString("yyyy-MM-dd") : "")}".Trim(),
Date = sl.Date,
FatherId = null, // deferred — applied after gerbils SaveChanges
MotherId = null, // deferred — applied after gerbils SaveChanges
Notes = $"aus Stammbaum-Diagramm abgeleitet (Konfidenz: {sl.Confidence})",
});
}
@@ -381,12 +391,12 @@ namespace GerbilManagerWebAPI.Import
if (execute)
{
_db.Gerbils.Add(new Gerbil
var importedGerbil = new Gerbil
{
Id = p.Gid,
Name = p.A.Name,
Gender = p.Gender,
Status = GerbilStatus.Active,
Status = GerbilStatus.Breeding,
DateOfBirth = ParseDate(p.A.Dob),
DateOfDeath = ParseDate(p.A.Death),
LitterId = litterId,
@@ -410,7 +420,9 @@ namespace GerbilManagerWebAPI.Import
p.A.SourceFiles,
FarbschlagRaw = p.A.Farbschlag,
}),
});
};
GerbilStatusService.Apply(importedGerbil, DateOnly.FromDateTime(DateTime.UtcNow));
_db.Gerbils.Add(importedGerbil);
}
// photos
@@ -437,6 +449,20 @@ namespace GerbilManagerWebAPI.Import
}
if (execute) await _db.SaveChangesAsync();
// Apply deferred synth litter parent FKs — all new gerbils are now persisted in the DB,
// so no cycle. FK guard already applied above (persisted set); values in the dict are safe.
if (execute && synthLitterPendingParents.Count > 0)
{
foreach (var (litId, (f, m)) in synthLitterPendingParents)
{
var row = await _db.Litters.FindAsync(litId);
if (row is null) continue;
if (f is not null) row.FatherId = f;
if (m is not null) row.MotherId = m;
}
await _db.SaveChangesAsync();
}
// ---- back-link Wurfchronik litter parents by name (best effort) ----
if (execute)
{
@@ -545,7 +571,7 @@ namespace GerbilManagerWebAPI.Import
// HERKUNFT BACKFILL (fill-NULL-only, safe): sweep all resident animals whose
// OriginBreeder is null and fill it with a derived value or 'Zucht der Kleinen Chaoten'.
// NEVER overwrites a non-null OriginBreeder (Julian: "alle Schreibweisen unterstützen").
const string DefaultClanBreeder = "Zucht der Kleinen Chaoten";
const string DefaultClanBreeder = "Zucht der kleinen Chaoten";
int herkunftBackfilled = 0;
{
var needsHerkunft = await _db.Gerbils
@@ -589,9 +615,9 @@ namespace GerbilManagerWebAPI.Import
notes.Add($"FK-Integrität: {litterParentFksDropped} Eltern-Verknüpfung(en) verworfen (Elternteil nicht ladbar), {derivedLittersSkipped} abgeleitete Würfe übersprungen (kein ladbares Elternteil). Bei 0/0 ist /import/execute FK-sicher.");
if (parentFksBackfilled > 0)
notes.Add($"Parent-FK-Backfill: {parentFksBackfilled} bereits importierte Würfe haben jetzt eine Eltern-Verknüpfung (Elternteil war zuvor in Quarantäne, jetzt geladen).");
notes.Add($"Bestand/Herkunft: {residentTotal} im Bestand (Clan Kleine Chaoten), {externalTotal} externe Ahnen ({flippedByParentRule} davon über die Eltern-Regel als Bestand erkannt).");
notes.Add($"Bestand/Herkunft: {residentTotal} im Bestand (Zucht der kleinen Chaoten), {externalTotal} externe Ahnen ({flippedByParentRule} davon über die Eltern-Regel als Bestand erkannt).");
if (herkunftBackfilled > 0)
notes.Add($"Herkunft-Backfill: {herkunftBackfilled} Bestand-Tier(e) mit leerem Herkunft-Feld befüllt (Zucht der Kleinen Chaoten oder von Elternteil abgeleitet). Niemals überschrieben.");
notes.Add($"Herkunft-Backfill: {herkunftBackfilled} Bestand-Tier(e) mit leerem Herkunft-Feld befüllt (Zucht der kleinen Chaoten oder von Elternteil abgeleitet). Niemals überschrieben.");
if (farbschlagWouldRebackfill > 0)
notes.Add($"Farbschlag-Hinweis (kein Overwrite): {farbschlagWouldRebackfill} bereits importierte Tier(e) haben einen veralteten Farbschlag, den der aktuelle Extraktor korrigieren würde — Overwrite-Mechanismus ausstehend (god/Julian Freigabe).");
int conflictsResolvedByDecision = loadable.Count(a => a.ResolvedByDecision);

View File

@@ -0,0 +1,364 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using GerbilManagerWebAPI.Models;
using Microsoft.EntityFrameworkCore;
using GerbilManagerWebAPI.Services;
namespace GerbilManagerWebAPI.Import
{
public sealed class IngestResolvedService
{
private readonly ApplicationContext _db;
private readonly string _resolvedJsonPath;
private readonly string _sourceDir;
private readonly string _photoRoot;
private static readonly JsonSerializerOptions DiffJson = new(JsonSerializerDefaults.Web);
public IngestResolvedService(ApplicationContext db, IConfiguration config, IWebHostEnvironment? env)
{
_db = db;
var contentRoot = env?.ContentRootPath ?? Directory.GetCurrentDirectory();
_sourceDir = config["Import:SourcePath"]
?? Path.GetFullPath(Path.Combine(contentRoot, "..", "tools", "import", "output"));
_resolvedJsonPath = Path.Combine(_sourceDir, "resolved_import.json");
_photoRoot = config["Photos:RootPath"]
?? Path.Combine(contentRoot, "photo-storage");
}
public async Task<string> RunAsync()
{
if (!File.Exists(_resolvedJsonPath))
{
return $"Error: Resolved import file not found at {_resolvedJsonPath}. Run resolve_import.py first.";
}
string jsonContent = await File.ReadAllTextAsync(_resolvedJsonPath);
var jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
jsonOptions.Converters.Add(new JsonStringEnumConverter());
var data = JsonSerializer.Deserialize<ResolvedImportData>(jsonContent, jsonOptions);
if (data == null)
{
return "Error: Failed to deserialize resolved_import.json.";
}
// ── UPSERT-based ingest (no total wipe) ──────────────────────────────────────
// The ingest NO LONGER wipes everything. Imported rows are matched by their
// (deterministic) id and updated in place; manually-created rows (IsManual=true) and
// user-entered sub-records (weights/health/photos) are never deleted, so the breeder's
// work survives the re-import. Only STALE imported rows (IsManual=false, absent from the
// new payload) are removed — after nulling any manual references to them (with a warning).
// Finally, hand-curated GerbilOverrides are re-applied on top (the "freeze").
var payloadContactIds = data.Contacts.Select(c => c.Id).ToHashSet();
var payloadLitterIds = data.Litters.Select(l => l.Id).ToHashSet();
var payloadGerbilIds = data.Gerbils.Select(g => g.Id).ToHashSet();
var warnings = new List<string>();
// 1. Upsert contacts (preserve manual rows + their IsManual flag).
var existingContacts = await _db.Contacts.ToDictionaryAsync(c => c.Id);
int contactsAdded = 0, contactsUpdated = 0;
foreach (var c in data.Contacts)
{
if (existingContacts.TryGetValue(c.Id, out var ec))
{
ec.Name = c.Name; ec.Email = c.Email; ec.Phone = c.Phone; ec.Address = c.Address;
ec.Notes = c.Notes; ec.IsBreeder = c.IsBreeder; ec.IsReceiver = c.IsReceiver;
ec.NameSuffix = c.NameSuffix; ec.Provenance = c.Provenance;
contactsUpdated++;
}
else
{
c.IsManual = false;
_db.Contacts.Add(c);
contactsAdded++;
}
}
await _db.SaveChangesAsync();
// 2. Upsert litters (parent FKs reset to null; set in pass 2 to avoid ordering issues).
var existingLitters = await _db.Litters.ToDictionaryAsync(l => l.Id);
foreach (var l in data.Litters)
{
if (existingLitters.TryGetValue(l.Id, out var el))
{
el.Name = l.Name; el.Date = l.Date; el.TotalBorn = l.TotalBorn;
el.DeathsWithin8Weeks = l.DeathsWithin8Weeks; el.Stillborn = l.Stillborn;
el.ExpectedGoHomeDate = l.ExpectedGoHomeDate; el.Notes = l.Notes;
el.PairingCode = l.PairingCode; el.ExternalRef = l.ExternalRef;
el.LitterLetter = l.LitterLetter; el.Provenance = l.Provenance;
el.ShowInChronicle = l.ShowInChronicle;
el.FatherId = null; el.MotherId = null;
}
else
{
_db.Litters.Add(new Litter
{
Id = l.Id, Name = l.Name, Date = l.Date, TotalBorn = l.TotalBorn,
DeathsWithin8Weeks = l.DeathsWithin8Weeks, Stillborn = l.Stillborn, FatherId = null, MotherId = null,
ExpectedGoHomeDate = l.ExpectedGoHomeDate, Notes = l.Notes, PairingCode = l.PairingCode,
ExternalRef = l.ExternalRef, LitterLetter = l.LitterLetter, Provenance = l.Provenance,
ShowInChronicle = l.ShowInChronicle, IsManual = false,
});
}
}
await _db.SaveChangesAsync();
// 3. Upsert gerbils (LitterId reset to null; set in pass 2). Manual rows keep IsManual=true
// and are never matched here (their random ids never collide with deterministic import ids).
var existingGerbils = await _db.Gerbils.ToDictionaryAsync(g => g.Id);
foreach (var g in data.Gerbils)
{
Gerbil target;
if (existingGerbils.TryGetValue(g.Id, out var eg))
{
eg.Name = g.Name; eg.Gender = g.Gender; eg.Status = g.Status;
eg.OriginContactId = g.OriginContactId; eg.ReceiverContactId = g.ReceiverContactId;
eg.EnclosureId = g.EnclosureId; eg.ColorVarietyId = g.ColorVarietyId;
eg.DateOfBirth = g.DateOfBirth; eg.DateOfDeath = g.DateOfDeath; eg.CauseOfDeath = g.CauseOfDeath;
eg.GoHomeDate = g.GoHomeDate; eg.Genotype = g.Genotype; eg.Notes = g.Notes;
eg.ImportSource = g.ImportSource; eg.ExternalRef = g.ExternalRef; eg.RawImportData = g.RawImportData;
eg.Provenance = g.Provenance; eg.OriginBreeder = g.OriginBreeder;
eg.CharacterTraits = g.CharacterTraits; eg.CharacterNote = g.CharacterNote;
eg.IsDeaf = g.IsDeaf; eg.IsResident = g.IsResident; eg.LitterId = null;
eg.BirthOrder = g.BirthOrder;
target = eg;
}
else
{
var ng = new Gerbil
{
Id = g.Id, Name = g.Name, Gender = g.Gender, Status = g.Status, LitterId = null,
OriginContactId = g.OriginContactId, ReceiverContactId = g.ReceiverContactId,
EnclosureId = g.EnclosureId, ColorVarietyId = g.ColorVarietyId,
DateOfBirth = g.DateOfBirth, DateOfDeath = g.DateOfDeath, CauseOfDeath = g.CauseOfDeath,
GoHomeDate = g.GoHomeDate, Genotype = g.Genotype, Notes = g.Notes,
ImportSource = g.ImportSource, ExternalRef = g.ExternalRef, RawImportData = g.RawImportData,
Provenance = g.Provenance, OriginBreeder = g.OriginBreeder, NameSearch = g.NameSearch,
CharacterTraits = g.CharacterTraits, CharacterNote = g.CharacterNote,
IsDeaf = g.IsDeaf, IsResident = g.IsResident, IsManual = false,
BirthOrder = g.BirthOrder,
};
_db.Gerbils.Add(ng);
target = ng;
}
GerbilStatusService.Apply(target, DateOnly.FromDateTime(DateTime.UtcNow));
}
await _db.SaveChangesAsync();
// 4. Pass 2: set the payload FK relationships (only for payload rows; manual rows untouched).
var littersInDb = await _db.Litters.ToDictionaryAsync(l => l.Id);
foreach (var l in data.Litters)
if (littersInDb.TryGetValue(l.Id, out var dl)) { dl.FatherId = l.FatherId; dl.MotherId = l.MotherId; }
var gerbilsInDb = await _db.Gerbils.ToDictionaryAsync(g => g.Id);
foreach (var g in data.Gerbils)
if (gerbilsInDb.TryGetValue(g.Id, out var dg)) dg.LitterId = g.LitterId;
await _db.SaveChangesAsync();
// 5. Remove STALE imported rows (IsManual=false, no longer in the payload). Null any
// dangling references from surviving rows first; warn when a MANUAL row is affected.
var allGerbils = await _db.Gerbils.ToListAsync();
var allLitters = await _db.Litters.ToListAsync();
var allContacts = await _db.Contacts.ToListAsync();
var gerbilNameById = allGerbils.ToDictionary(x => x.Id, x => x.Name);
var litterNameById = allLitters.ToDictionary(x => x.Id, x => x.Name);
var contactNameById = allContacts.ToDictionary(x => x.Id, x => x.Name);
var staleGerbilIds = allGerbils.Where(g => !g.IsManual && !payloadGerbilIds.Contains(g.Id)).Select(g => g.Id).ToHashSet();
var staleLitterIds = allLitters.Where(l => !l.IsManual && !payloadLitterIds.Contains(l.Id)).Select(l => l.Id).ToHashSet();
var staleContactIds = allContacts.Where(c => !c.IsManual && !payloadContactIds.Contains(c.Id)).Select(c => c.Id).ToHashSet();
if (staleGerbilIds.Count > 0)
{
foreach (var l in allLitters)
{
if (l.FatherId is { } f && staleGerbilIds.Contains(f))
{
if (l.IsManual) warnings.Add($"Manueller Wurf „{l.Name}\" verwies auf importiertes Elterntier {gerbilNameById.GetValueOrDefault(f, "?")}\" (Vater), das im Import nicht mehr existiert — Elternteil entfernt.");
l.FatherId = null;
}
if (l.MotherId is { } m && staleGerbilIds.Contains(m))
{
if (l.IsManual) warnings.Add($"Manueller Wurf „{l.Name}\" verwies auf importiertes Elterntier {gerbilNameById.GetValueOrDefault(m, "?")}\" (Mutter), das im Import nicht mehr existiert — Elternteil entfernt.");
l.MotherId = null;
}
}
}
if (staleContactIds.Count > 0)
{
foreach (var g in allGerbils)
{
if (g.OriginContactId is { } o && staleContactIds.Contains(o))
{
if (g.IsManual) warnings.Add($"Manuelles Tier „{g.Name}\" verwies auf Kontakt {contactNameById.GetValueOrDefault(o, "?")}\" (Herkunft), der im Import nicht mehr existiert — Zuordnung entfernt.");
g.OriginContactId = null;
}
if (g.ReceiverContactId is { } r && staleContactIds.Contains(r))
{
if (g.IsManual) warnings.Add($"Manuelles Tier „{g.Name}\" verwies auf Kontakt {contactNameById.GetValueOrDefault(r, "?")}\" (Abnehmer), der im Import nicht mehr existiert — Zuordnung entfernt.");
g.ReceiverContactId = null;
}
}
}
if (staleLitterIds.Count > 0)
{
// Gerbil.LitterId FK is SetNull on delete → nulled automatically when the litter is
// removed; we only surface a warning for affected MANUAL animals.
foreach (var g in allGerbils)
if (g.IsManual && g.LitterId is { } lid && staleLitterIds.Contains(lid))
warnings.Add($"Manuelles Tier „{g.Name}\" war im Wurf {litterNameById.GetValueOrDefault(lid, "?")}\" geboren, der im Import nicht mehr existiert — Wurf-Zuordnung entfernt.");
}
await _db.SaveChangesAsync();
int gerbilsDeleted = staleGerbilIds.Count, littersDeleted = staleLitterIds.Count, contactsDeleted = staleContactIds.Count;
if (staleGerbilIds.Count > 0) _db.Gerbils.RemoveRange(allGerbils.Where(g => staleGerbilIds.Contains(g.Id)));
if (staleLitterIds.Count > 0) _db.Litters.RemoveRange(allLitters.Where(l => staleLitterIds.Contains(l.Id)));
if (staleContactIds.Count > 0) _db.Contacts.RemoveRange(allContacts.Where(c => staleContactIds.Contains(c.Id)));
await _db.SaveChangesAsync();
// 6. Photos: replace photos of IMPORTED gerbils (manual gerbils' photos survive). Copy files.
var manualGerbilIds = allGerbils.Where(g => g.IsManual).Select(g => g.Id).ToHashSet();
var allPhotos = await _db.GerbilPhotos.ToListAsync();
_db.GerbilPhotos.RemoveRange(allPhotos.Where(p => !manualGerbilIds.Contains(p.GerbilId)));
await _db.SaveChangesAsync();
Directory.CreateDirectory(_photoRoot);
foreach (var p in data.GerbilPhotos)
{
if (!string.IsNullOrEmpty(p.SourcePath))
{
var relPath = p.SourcePath.Replace('/', Path.DirectorySeparatorChar).Replace('\\', Path.DirectorySeparatorChar);
var src = Path.Combine(_sourceDir, relPath);
if (File.Exists(src))
{
var dest = Path.Combine(_photoRoot, p.FileName);
try { File.Copy(src, dest, overwrite: true); }
catch (Exception ex) { Console.WriteLine($"Warning: Failed to copy photo {src} to {dest}: {ex.Message}"); }
}
else
{
Console.WriteLine($"Warning: Source photo file not found at {src}");
}
}
_db.GerbilPhotos.Add(new GerbilPhoto
{
Id = p.Id,
GerbilId = p.GerbilId,
FileName = p.FileName,
Caption = p.Caption,
SortOrder = p.SortOrder,
CreatedAt = DateTimeOffset.UtcNow,
});
}
await _db.SaveChangesAsync();
// 7. Imported Abgabeverträge: recreate from payload (unchanged behaviour — the imported set
// is part of the payload). Manual sale-contract protection is a separate follow-up.
var scToRemove = await _db.SaleContracts.ToListAsync();
_db.SaleContracts.RemoveRange(scToRemove);
await _db.SaveChangesAsync();
int contractsAdded = 0, contractAnimalsSkipped = 0;
if (data.SaleContracts.Count > 0)
{
var contactIds = await _db.Contacts.Select(c => c.Id).ToHashSetAsync();
var gerbilIds = await _db.Gerbils.Select(g => g.Id).ToHashSetAsync();
var seenContractIds = new HashSet<Guid>();
foreach (var sc in data.SaleContracts)
{
if (!seenContractIds.Add(sc.Id)) continue;
if (!contactIds.Contains(sc.ContactId)) continue;
var animals = new List<SaleContractAnimal>();
foreach (var gid in (sc.Animals ?? new List<Guid>()).Distinct())
{
if (!gerbilIds.Contains(gid)) { contractAnimalsSkipped++; continue; }
animals.Add(new SaleContractAnimal { SaleContractId = sc.Id, GerbilId = gid });
}
_db.SaleContracts.Add(new SaleContract
{
Id = sc.Id,
ContactId = sc.ContactId,
Price = sc.Price,
HandoverDate = sc.HandoverDate,
ContractDate = sc.ContractDate,
FileName = sc.FileName,
CreatedAt = DateTimeOffset.UtcNow,
Animals = animals,
});
contractsAdded++;
}
await _db.SaveChangesAsync();
}
// 8. FREEZE: capture the raw-import snapshot for verified overrides (BEFORE applying the
// freeze), then re-apply every override on top of the fresh import so the breeder's
// curated values win. Overrides survive re-ingest by being their own (FK-free) table.
var overrides = await _db.GerbilOverrides.ToListAsync();
foreach (var ov in overrides.Where(o => o.IsVerified))
{
var raw = await GerbilSnapshotService.BuildSnapshotAsync(_db, ov.GerbilId);
if (raw is null) continue; // verified animal vanished from import → surfaced as "missing" in the UI
ov.LastImportSnapshotJson = GerbilSnapshotService.SerializeSnapshot(raw);
var golden = GerbilSnapshotService.DeserializeSnapshot(ov.SnapshotJson);
var diff = GerbilSnapshotService.Diff(golden, raw);
ov.LastImportDiffJson = diff.Count == 0 ? null : JsonSerializer.Serialize(diff, DiffJson);
}
var gerbilsById = await _db.Gerbils.ToDictionaryAsync(g => g.Id);
int overridesApplied = 0;
foreach (var ov in overrides)
{
if (gerbilsById.TryGetValue(ov.GerbilId, out var gg))
{
GerbilSnapshotService.ApplyOverride(gg, ov.OverrideJson);
overridesApplied++;
}
}
await _db.SaveChangesAsync();
var warnPart = warnings.Count > 0 ? $" {warnings.Count} warning(s): {string.Join(" | ", warnings)}" : "";
return $"Ingestion successful! Contacts +{contactsAdded}/~{contactsUpdated} ({contactsDeleted} stale), " +
$"{data.Litters.Count} litters ({littersDeleted} stale), {data.Gerbils.Count} gerbils ({gerbilsDeleted} stale), " +
$"{data.GerbilPhotos.Count} photos, {contractsAdded} sale contracts ({contractAnimalsSkipped} animal links skipped), " +
$"{overridesApplied} override(s) applied (freeze).{warnPart}";
}
}
public class ResolvedImportData
{
public List<Contact> Contacts { get; set; } = new();
public List<Litter> Litters { get; set; } = new();
public List<Gerbil> Gerbils { get; set; } = new();
public List<ResolvedPhoto> GerbilPhotos { get; set; } = new();
public List<ResolvedSaleContract> SaleContracts { get; set; } = new();
}
/// <summary>Eine importierte Abgabevertrag-Zeile aus resolved_import.json.
/// <c>Animals</c> sind die zugeordneten Gerbil-Ids (Join-Zeilen werden beim
/// Ingest gebaut). Die .docx liegt NICHT im Vertrags-Dateiroot — der
/// Word-Download liefert 404, das PDF wird aus den Daten neu erzeugt.</summary>
public class ResolvedSaleContract
{
public Guid Id { get; set; }
public Guid ContactId { get; set; }
public decimal Price { get; set; }
public DateOnly HandoverDate { get; set; }
public DateOnly ContractDate { get; set; }
public required string FileName { get; set; }
public List<Guid> Animals { get; set; } = new();
}
public class ResolvedPhoto
{
public Guid Id { get; set; }
public Guid GerbilId { get; set; }
public required string FileName { get; set; }
public string? Caption { get; set; }
public int SortOrder { get; set; }
[JsonPropertyName("_source_path")]
public string? SourcePath { get; set; }
}
}

View File

@@ -0,0 +1,117 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace GerbilManagerWebAPI.Import.Rpro3
{
/// <summary>
/// Manuelle Entscheidungen der Züchterin zu mehrdeutigen RPRO3-Namensdubletten
/// (aus den „Fehler melden"-Tickets, Kontext „rpro3-import"). Der automatische
/// <see cref="Rpro3Dedup"/> ist konservativ und legt nur bei positiver Evidenz zusammen;
/// diese Overrides erlauben der Züchterin, gezielt zu korrigieren:
///
/// • <c>Same</c> — Gruppen von RPRO3-Nummern (rids), die DASSELBE Tier sind
/// (zwingt ein Merge über Varianten hinweg; ein rid je Variante genügt,
/// der ganze Cluster wird mitgezogen).
/// • <c>Different</c>— Gruppen, die VERSCHIEDENE Tiere sind (verhindert ein automatisches
/// Zusammenlegen über Gruppengrenzen).
/// • <c>Fields</c> — Feld-Korrekturen am resultierenden Tier (Farbe/Geburtsdatum/Herkunft/
/// Bestands-Flag/Zusatznotiz), adressiert über IRGENDEINE rid des Clusters.
///
/// Datenquelle: <c>Import/Rpro3/rpro3-decisions.json</c> (siehe <see cref="Load"/>).
/// Stabiler Schlüssel ist die RPRO3-Nummer (rid), nicht der Variantenbuchstabe — Buchstaben
/// verschieben sich, sobald sich die Clusterbildung ändert.
/// </summary>
public sealed class Rpro3Decisions
{
public List<Rpro3Decision> Decisions { get; set; } = new();
public static Rpro3Decisions Empty { get; } = new();
/// <summary>Lädt die Entscheidungen aus JSON; fehlt die Datei oder ist sie leer/kaputt,
/// kommt eine leere Menge zurück (Import läuft dann mit reinem Auto-Dedup).</summary>
public static Rpro3Decisions Load(string? path)
{
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
return Empty;
try
{
var json = File.ReadAllText(path);
var d = JsonSerializer.Deserialize<Rpro3Decisions>(json, JsonOpts);
return d ?? Empty;
}
catch (JsonException)
{
return Empty;
}
}
private static readonly JsonSerializerOptions JsonOpts = new(JsonSerializerDefaults.Web)
{
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
};
/// <summary>Alle „Same"-rid-Gruppen (für Force-Merge).</summary>
public IEnumerable<IReadOnlyList<string>> SameGroups()
{
foreach (var d in Decisions)
foreach (var g in d.Same)
if (g.Count >= 2) yield return g;
}
/// <summary>rid → numerische Split-Gruppe je Entscheidung. Zwei rids mit unterschiedlicher
/// Split-Gruppe (gleiche Entscheidung) dürfen NICHT automatisch zusammengelegt werden.</summary>
public Dictionary<string, int> BuildSplitGroups()
{
var map = new Dictionary<string, int>(StringComparer.Ordinal);
int gid = 0;
foreach (var d in Decisions)
{
if (d.Different.Count < 2) continue;
foreach (var grp in d.Different)
{
gid++;
foreach (var rid in grp)
map[rid] = gid;
}
}
return map;
}
/// <summary>rid → Feld-Override (jede rid eines Clusters zeigt auf denselben Override).</summary>
public Dictionary<string, Rpro3FieldOverride> BuildFieldIndex()
{
var map = new Dictionary<string, Rpro3FieldOverride>(StringComparer.Ordinal);
foreach (var d in Decisions)
foreach (var (rid, ov) in d.Fields)
map[rid] = ov;
return map;
}
}
public sealed class Rpro3Decision
{
/// <summary>Anzeigename (nur zur Lesbarkeit der JSON; Logik nutzt rids).</summary>
public string? Name { get; set; }
/// <summary>Ticket-Id (Rückverfolgbarkeit).</summary>
public string? Ticket { get; set; }
public List<List<string>> Same { get; set; } = new();
public List<List<string>> Different { get; set; } = new();
public Dictionary<string, Rpro3FieldOverride> Fields { get; set; } = new();
}
public sealed class Rpro3FieldOverride
{
public string? Color { get; set; }
public string? Dob { get; set; } // ISO yyyy-MM-dd
public string? Origin { get; set; }
/// <summary>Roher Gencode (Fcode, z. B. „aa Cc[h] DD ee Gg P- spsp"). Überschreibt den
/// automatisch aus den Cluster-Mitgliedern gewählten Gencode — nötig, wenn sich die
/// Varianten im Gencode unterscheiden (z. B. C-Locus c[h] vs. c[chm]) und die Züchterin
/// den korrekten Genotyp vorgibt.</summary>
public string? Genotype { get; set; }
public bool? Resident { get; set; }
/// <summary>Zusatz, der an die Notizen des Tiers angehängt wird (z. B. abweichendes DOB).</summary>
public string? Note { get; set; }
}
}

View File

@@ -0,0 +1,226 @@
using System.Globalization;
using System.Text;
namespace GerbilManagerWebAPI.Import.Rpro3
{
/// <summary>
/// Port von tools/import/compare_rpro3.py `dedup()`. RennmausPro erkennt beim Import vorhandene
/// Tiere NICHT → dasselbe Tier (v. a. die 7427 externen) kommt mehrfach vor.
///
/// Union-Find INNERHALB gleicher (normalisierter) Namen:
/// merge(a,b) wenn DOB/Farbe/Herkunft kompatibel (gleich ODER eine Seite unbekannt)
/// UND mindestens ein bekanntes Feld positiv übereinstimmt. Konflikt in einem bekannten
/// Feld → NICHT mergen (unsicher → mehrdeutig).
/// Platzhalter-Namen ("unbekannt","-","","?" …) werden nie dedupt.
/// </summary>
public static class Rpro3Dedup
{
private static readonly HashSet<string> PlaceholderNames = new(StringComparer.Ordinal)
{ "", "-", "n", "unbekannt", "unbekannt?", "?", "nn", "n.n.", "na", "namenlos", "." };
private static readonly HashSet<string> UnknownValues = new(StringComparer.Ordinal)
{ "", "unbekannt", "unbek.", "unbek", "unbekannte zucht", "?", "n.n.",
"unbekannter farbschlag", "keine angabe", "k.a.", "na", "unbekannte farbe" };
public sealed class DedupResult
{
/// <summary>Cluster (mehr als ein Datensatz) → die zusammengelegten Tiere. Key = Wurzel-Rid.</summary>
public Dictionary<string, List<Rpro3Animal>> MergeClusters { get; } = new();
/// <summary>Repräsentant-Rid je Cluster (auch Singletons) → Cluster-Wurzel.</summary>
public Dictionary<string, string> RidToRoot { get; } = new();
/// <summary>Mehrdeutige Namen: Name → Varianten (manuelle Entscheidung nötig).</summary>
public List<AmbiguousName> Ambiguous { get; } = new();
/// <summary>Platzhalter-Datensätze (nicht dedupbar) gruppiert nach Name.</summary>
public List<Rpro3Animal> Placeholders { get; } = new();
public int CollapsedRecords { get; set; } // Summe der Datensätze in Merge-Clustern
public int DuplicatesRemoved { get; set; } // CollapsedRecords - Anzahl Cluster
}
public sealed class AmbiguousName
{
public required string Name { get; init; }
public List<Variant> Variants { get; } = new();
public int BareCount { get; set; } // merkmalslose Varianten (nur Name)
}
public sealed class Variant
{
public int Count { get; set; }
public List<string> Dob { get; } = new();
public List<string> Farbe { get; } = new();
public List<string> Origin { get; } = new();
public bool IsOwn { get; set; }
}
public static string NormName(string? s)
{
if (s is null) return "";
var n = s.Normalize(NormalizationForm.FormKC).Trim().ToLowerInvariant();
return string.Join(' ', n.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries));
}
public static string NormValue(string? s)
{
var v = NormName(s);
return UnknownValues.Contains(v) ? "" : v;
}
public static DedupResult Run(IReadOnlyList<Rpro3Animal> animals) => Run(animals, null);
/// <summary>
/// Wie <see cref="Run(IReadOnlyList{Rpro3Animal})"/>, berücksichtigt aber manuelle
/// Entscheidungen der Züchterin (<paramref name="decisions"/>): „Different"-Gruppen
/// verhindern automatisches Zusammenlegen, „Same"-Gruppen erzwingen ein Merge über
/// Varianten hinweg (jede rid zieht ihren ganzen Auto-Cluster mit).
/// </summary>
public static DedupResult Run(IReadOnlyList<Rpro3Animal> animals, Rpro3Decisions? decisions)
{
var result = new DedupResult();
decisions ??= Rpro3Decisions.Empty;
var splitGroup = decisions.BuildSplitGroups();
foreach (var a in animals)
{
a.NameKey = NormName(a.Name);
a.FarbeKey = NormValue(a.Farbe);
a.OriginKey = NormValue(a.Origin);
}
var byName = new Dictionary<string, List<Rpro3Animal>>();
foreach (var a in animals)
{
if (PlaceholderNames.Contains(a.NameKey)) { result.Placeholders.Add(a); continue; }
if (!byName.TryGetValue(a.NameKey, out var list)) byName[a.NameKey] = list = new();
list.Add(a);
}
var parent = new Dictionary<string, string>();
string Find(string x)
{
while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; }
return x;
}
void Union(string x, string y)
{
parent.TryAdd(x, x); parent.TryAdd(y, y);
parent[Find(x)] = Find(y);
}
static int Positive(Rpro3Animal a, Rpro3Animal b)
{
int agree = 0;
if (a.Dob is not null && b.Dob is not null && a.Dob == b.Dob) agree++;
if (a.FarbeKey.Length > 0 && a.FarbeKey == b.FarbeKey) agree++;
if (a.OriginKey.Length > 0 && a.OriginKey == b.OriginKey) agree++;
return agree;
}
static int Conflict(Rpro3Animal a, Rpro3Animal b)
{
int c = 0;
if (a.Dob is not null && b.Dob is not null && a.Dob != b.Dob) c++;
if (a.FarbeKey.Length > 0 && b.FarbeKey.Length > 0 && a.FarbeKey != b.FarbeKey) c++;
if (a.OriginKey.Length > 0 && b.OriginKey.Length > 0 && a.OriginKey != b.OriginKey) c++;
return c;
}
static bool Compat(string? x, string? y) =>
string.IsNullOrEmpty(x) || string.IsNullOrEmpty(y) || x == y;
static bool CompatDob(DateOnly? x, DateOnly? y) => x is null || y is null || x == y;
foreach (var (_, group) in byName)
{
foreach (var a in group) parent.TryAdd(a.Rid, a.Rid);
for (int i = 0; i < group.Count; i++)
for (int j = i + 1; j < group.Count; j++)
{
var a = group[i]; var b = group[j];
// Force-Split: von der Züchterin als verschieden markierte Tiere nie zusammenlegen.
if (splitGroup.TryGetValue(a.Rid, out var ga) && splitGroup.TryGetValue(b.Rid, out var gb) && ga != gb)
continue;
bool comp = CompatDob(a.Dob, b.Dob) && Compat(a.FarbeKey, b.FarbeKey) && Compat(a.OriginKey, b.OriginKey);
if (comp && Positive(a, b) >= 1 && Conflict(a, b) == 0)
Union(a.Rid, b.Rid);
}
}
// Force-Merge: von der Züchterin als dasselbe Tier bestätigte Varianten zusammenlegen
// (eine rid je Variante genügt — Find/Union zieht den ganzen Auto-Cluster mit). Nur rids,
// die es im Datensatz auch gibt, werden berücksichtigt.
var knownRids = new HashSet<string>(animals.Select(a => a.Rid), StringComparer.Ordinal);
foreach (var grp in decisions.SameGroups())
{
string? anchor = null;
foreach (var rid in grp)
{
if (!knownRids.Contains(rid)) continue;
parent.TryAdd(rid, rid);
if (anchor is null) anchor = rid;
else Union(anchor, rid);
}
}
// Cluster sammeln
var clusters = new Dictionary<string, List<Rpro3Animal>>();
foreach (var a in animals)
{
if (PlaceholderNames.Contains(a.NameKey)) continue;
var root = Find(a.Rid);
result.RidToRoot[a.Rid] = root;
if (!clusters.TryGetValue(root, out var list)) clusters[root] = list = new();
list.Add(a);
}
foreach (var (k, v) in clusters)
if (v.Count > 1)
{
result.MergeClusters[k] = v;
result.CollapsedRecords += v.Count;
}
result.DuplicatesRemoved = result.CollapsedRecords - result.MergeClusters.Count;
// Mehrdeutige Namen: Name löst sich nach sicherem Merge in >1 Cluster auf
var nameToRoots = new Dictionary<string, HashSet<string>>();
var disp = new Dictionary<string, string>();
foreach (var a in animals)
{
if (PlaceholderNames.Contains(a.NameKey)) continue;
if (!nameToRoots.TryGetValue(a.NameKey, out var set)) nameToRoots[a.NameKey] = set = new();
set.Add(Find(a.Rid));
disp.TryAdd(a.NameKey, a.Name ?? a.NameKey);
}
foreach (var (nm, roots) in nameToRoots)
{
if (roots.Count <= 1) continue;
var amb = new AmbiguousName { Name = disp.GetValueOrDefault(nm, nm) };
foreach (var root in roots)
{
var recs = clusters[root];
var dob = recs.Where(r => r.Dob is not null).Select(r => r.Dob!.Value.ToString("yyyy-MM-dd")).Distinct().OrderBy(x => x).ToList();
var farbe = recs.Where(r => !string.IsNullOrEmpty(r.Farbe)).Select(r => r.Farbe!).Distinct().OrderBy(x => x).ToList();
var origin = recs.Where(r => NormValue(r.Origin).Length > 0).Select(r => r.Origin!).Distinct().OrderBy(x => x).ToList();
bool bare = dob.Count == 0 && farbe.Count == 0 && origin.Count == 0;
if (bare) { amb.BareCount += recs.Count; continue; }
var v = new Variant { Count = recs.Count, IsOwn = recs.Any(r => r.Src == Rpro3Src.Stamm) };
v.Dob.AddRange(dob); v.Farbe.AddRange(farbe); v.Origin.AddRange(origin);
amb.Variants.Add(v);
}
amb.Variants.Sort((x, y) => y.Count.CompareTo(x.Count));
// Nur Namen mit mind. einer informativen Variante interessieren die Züchterin.
if (amb.Variants.Count >= 1) result.Ambiguous.Add(amb);
}
result.Ambiguous.Sort((x, y) => y.Variants.Count.CompareTo(x.Variants.Count));
return result;
}
/// <summary>Repräsentant eines Clusters: bevorzugt ein stamm-Tier, sonst das mit den meisten
/// bekannten Feldern (DOB/Farbe/Origin), Tiebreak per Rid (stabil).</summary>
public static Rpro3Animal Representative(List<Rpro3Animal> cluster)
{
return cluster
.OrderByDescending(a => a.Src == Rpro3Src.Stamm)
.ThenByDescending(a => (a.Dob is not null ? 1 : 0) + (a.FarbeKey.Length > 0 ? 1 : 0) + (a.OriginKey.Length > 0 ? 1 : 0))
.ThenBy(a => a.Rid, StringComparer.Ordinal)
.First();
}
}
}

View File

@@ -0,0 +1,39 @@
using System.Security.Cryptography;
using System.Text;
namespace GerbilManagerWebAPI.Import.Rpro3
{
/// <summary>
/// Deterministische GUIDs aus stabilen RPRO3-Schlüsseln (analog zum Python `generate_guid`-Muster).
/// Gleicher Schlüssel → gleiche GUID über Re-Imports hinweg → idempotent.
/// MD5-basiert (Namespace-Präfix vermeidet Kollisionen mit anderen Entitätstypen).
/// </summary>
public static class Rpro3Guid
{
public const string ImportSource = "RennmausPro III";
public static Guid For(string @namespace, string key)
{
var bytes = MD5.HashData(Encoding.UTF8.GetBytes($"rpro3:{@namespace}:{key}"));
return new Guid(bytes);
}
public static Guid Gerbil(string clusterRootRid) => For("gerbil", clusterRootRid);
public static Guid Litter(int wurfId) => For("litter", wurfId.ToString());
public static Guid Contact(string ns, int id) => For("contact", $"{ns}:{id}");
public static Guid Health(string tid, string disc, int seq) => For("health", $"{tid}:{seq}:{disc}");
public static Guid Weight(string tid, int seq) => For("weight", $"{tid}:{seq}");
// Feature-Tabellen — deterministische IDs für Idempotenz (Re-Import ersetzt dieselben Zeilen).
public static Guid Enclosure(int beckenId) => For("enclosure", beckenId.ToString());
public static Guid Acquisition(int herktierId) => For("acquisition", herktierId.ToString());
public static Guid Reservation(string tid) => For("reservation", tid);
public static Guid Return(int getbackId) => For("return", getbackId.ToString());
public static Guid WaitingList(int nachfrageId) => For("waitinglist", nachfrageId.ToString());
public static Guid Exhibition(int auszId) => For("exhibition", auszId.ToString());
/// <summary>Stabiler ExternalRef-Wert (Gerbil/Litter Idempotenzschlüssel, UNIQUE-Spalte).</summary>
public static string GerbilRef(string rootRid) => $"rpro3:{rootRid}";
public static string LitterRef(int wurfId) => $"rpro3-wurf:{wurfId}";
}
}

View File

@@ -0,0 +1,887 @@
using System.Text.Json;
using GerbilManagerWebAPI.Dtos;
using GerbilManagerWebAPI.Models;
using GerbilManagerWebAPI.Services;
using Microsoft.EntityFrameworkCore;
namespace GerbilManagerWebAPI.Import.Rpro3
{
/// <summary>
/// „First class" RennmausPro-III-Backup-Importer. Parst die `.backup` (SQLite), dedupliziert
/// RPRO3-interne Dubletten (Port von compare_rpro3.py) und überführt die Daten in unser Modell.
///
/// Zwei Operationen:
/// AnalyzeAsync — schreibt NICHTS; liefert Zählungen, Top-Merges, mehrdeutige Namen, neu/vorhanden.
/// ExecuteAsync — idempotenter Import (deterministische GUIDs + ExternalRef). Re-Run aktualisiert
/// dieselben Zeilen; vorherige RPRO3-Importe (ImportSource="RennmausPro III")
/// werden vor dem Neuladen entfernt. Spreadsheet-Importe bleiben unangetastet.
/// </summary>
public sealed class Rpro3ImportService
{
private readonly ApplicationContext _db;
private readonly string _photoRoot;
private readonly Rpro3Decisions _decisions;
private Dictionary<string, Rpro3FieldOverride>? _fieldIndex;
public Rpro3ImportService(ApplicationContext db, IConfiguration config, IWebHostEnvironment? env)
{
_db = db;
var contentRoot = env?.ContentRootPath ?? Directory.GetCurrentDirectory();
_photoRoot = config["Photos:RootPath"] ?? Path.Combine(contentRoot, "photo-storage");
// Manuelle Dubletten-Entscheidungen der Züchterin (siehe Rpro3Decisions). Pfad
// überschreibbar per Config; Default: neben dem Importer-Code (wird mit ins Output kopiert).
var decPath = config["Rpro3:DecisionsPath"]
?? Path.Combine(contentRoot, "Import", "Rpro3", "rpro3-decisions.json");
_decisions = Rpro3Decisions.Load(decPath);
}
private Dictionary<string, Rpro3FieldOverride> FieldIndex =>
_fieldIndex ??= _decisions.BuildFieldIndex();
// ───────────────────────── ANALYZE ─────────────────────────
public async Task<Rpro3AnalyzeResult> AnalyzeAsync(
Rpro3Data data, bool photosProvided, IReadOnlySet<string>? availablePhotoFiles)
{
var dedup = Rpro3Dedup.Run(data.Animals, _decisions);
var plan = BuildPlan(data, dedup);
// Abgleich gegen Bestand: Match über separator-insensitiven NameSearch + DOB-Toleranz.
var existing = await _db.Gerbils.AsNoTracking()
.Select(g => new { g.NameSearch, g.DateOfBirth, g.ExternalRef })
.ToListAsync();
var existingRefs = existing.Where(e => e.ExternalRef is not null)
.Select(e => e.ExternalRef!).ToHashSet(StringComparer.Ordinal);
var existingByName = existing
.GroupBy(e => e.NameSearch ?? "")
.ToDictionary(g => g.Key, g => g.Select(e => e.DateOfBirth).ToList());
int newCount = 0, existingCount = 0;
foreach (var gp in plan.Gerbils.Values)
{
if (existingRefs.Contains(gp.ExternalRef)) { existingCount++; continue; }
var key = GerbilSearch.Normalize(gp.Name);
if (existingByName.TryGetValue(key, out var dobs) && DobMatch(gp.Dob, dobs)) existingCount++;
else newCount++;
}
var counts = new Rpro3Counts(
OwnAnimals: data.Animals.Count(a => a.Src == Rpro3Src.Stamm),
ExternalRaw: data.Animals.Count(a => a.Src == Rpro3Src.Fremd),
ExternalAfterDedup: plan.Gerbils.Values.Count(g => !g.IsResident),
Litters: data.Litters.Count,
Contacts: data.HerkContacts.Count + data.AbnContacts.Count,
Genotypes: data.ColorStammCount + data.ColorExtCount,
DuplicatesMerged: dedup.DuplicatesRemoved,
MergeClusters: dedup.MergeClusters.Count,
Enclosures: plan.Enclosures.Count,
Acquisitions: plan.Acquisitions.Count,
Reservations: plan.Reservations.Count,
Returns: plan.Returns.Count,
WaitingList: plan.WaitingList.Count,
Exhibitions: plan.Exhibitions.Count);
var topMerges = dedup.MergeClusters.Values
.OrderByDescending(v => v.Count)
.Take(25)
.Select(v =>
{
var rep = Rpro3Dedup.Representative(v);
return new Rpro3MergeSample(
rep.Name ?? "—",
v.Count,
string.Join(", ", v.Where(x => x.Dob is not null).Select(x => x.Dob!.Value.ToString("yyyy-MM-dd")).Distinct()),
Truncate(string.Join(", ", v.Where(x => !string.IsNullOrEmpty(x.Farbe)).Select(x => x.Farbe!).Distinct()), 60),
Truncate(string.Join(", ", v.Where(x => Rpro3Dedup.NormValue(x.Origin).Length > 0).Select(x => x.Origin!).Distinct()), 60));
})
.ToList();
var ambiguous = dedup.Ambiguous
.Take(80)
.Select(a => new Rpro3AmbiguousName(
a.Name,
a.Variants.Select(v => new Rpro3AmbiguousVariant(
v.Count,
v.Dob.Count > 0 ? string.Join(", ", v.Dob) : "—",
v.Farbe.Count > 0 ? Truncate(string.Join(", ", v.Farbe), 40) : "—",
v.Origin.Count > 0 ? Truncate(string.Join(", ", v.Origin), 40) : "—",
v.IsOwn)).ToList(),
a.BareCount))
.ToList();
return new Rpro3AnalyzeResult(
counts, newCount, existingCount, topMerges, ambiguous,
photosProvided, availablePhotoFiles?.Count ?? 0);
}
private static bool DobMatch(DateOnly? rpDob, List<DateOnly?> existing)
{
// Match, wenn ein Bestandstier denselben (oder unbekannten) Geburtstag hat (±14 Tage).
if (rpDob is null) return true;
foreach (var d in existing)
{
if (d is null) return true;
if (Math.Abs((rpDob.Value.ToDateTime(TimeOnly.MinValue) - d.Value.ToDateTime(TimeOnly.MinValue)).TotalDays) <= 14)
return true;
}
return false;
}
// ───────────────────────── EXECUTE ─────────────────────────
public async Task<Rpro3ExecuteResult> ExecuteAsync(
Rpro3Data data, string workDir, bool photosProvided, IReadOnlyDictionary<string, string>? photoSourcePaths)
{
var dedup = Rpro3Dedup.Run(data.Animals, _decisions);
var plan = BuildPlan(data, dedup);
// Change-Tracker leeren: ExecuteDelete/Update umgehen den Tracker; bei wiederholtem
// ExecuteAsync auf derselben DbContext-Instanz würden sonst alte Tracking-Einträge
// mit den neu eingefügten (gleiche deterministische IDs) kollidieren.
_db.ChangeTracker.Clear();
// 1. Vorherigen RPRO3-Import idempotent entfernen (deterministische IDs → Re-Run ok).
// Health/Weight zuerst (FK auf Gerbil), dann FK-Links lösen, dann Gerbils/Litters.
var priorGerbilIds = await _db.Gerbils
.Where(g => g.ImportSource == Rpro3Guid.ImportSource)
.Select(g => g.Id).ToListAsync();
var priorLitterRefs = plan.Litters.Values.Select(l => l.ExternalRef).ToList();
if (priorGerbilIds.Count > 0)
{
await _db.HealthRecords.Where(h => priorGerbilIds.Contains(h.GerbilId)).ExecuteDeleteAsync();
await _db.WeightRecords.Where(w => priorGerbilIds.Contains(w.GerbilId)).ExecuteDeleteAsync();
await _db.GerbilPhotos.Where(p => priorGerbilIds.Contains(p.GerbilId)).ExecuteDeleteAsync();
}
// FK-Schleifen lösen: Litter.Father/Mother + Gerbil.Litter, die auf RPRO3-Tiere zeigen.
await _db.Litters.Where(l => l.ExternalRef != null && priorLitterRefs.Contains(l.ExternalRef))
.ExecuteUpdateAsync(s => s.SetProperty(l => l.FatherId, (Guid?)null).SetProperty(l => l.MotherId, (Guid?)null));
await _db.Gerbils.Where(g => g.ImportSource == Rpro3Guid.ImportSource)
.ExecuteUpdateAsync(s => s.SetProperty(g => g.LitterId, (Guid?)null));
await _db.Litters.Where(l => l.ExternalRef != null && priorLitterRefs.Contains(l.ExternalRef)).ExecuteDeleteAsync();
await _db.Gerbils.Where(g => g.ImportSource == Rpro3Guid.ImportSource).ExecuteDeleteAsync();
// 1b. Feature-Tabellen idempotent leeren. Diese Entities haben KEINE ImportSource-Spalte,
// daher löschen wir gezielt die deterministischen RPRO3-IDs, die dieser Import erzeugt
// (Re-Import desselben Backups → keine Dubletten). Manuell angelegte Einträge mit
// anderen IDs bleiben unangetastet. Enclosures werden NICHT aus Gerbils gelöscht,
// nur die EnclosureId-Verknüpfung gelöschter Tiere fällt mit den Tieren weg.
var acqIds = plan.Acquisitions.Select(a => a.Id).ToList();
var resIds = plan.Reservations.Select(r => r.Id).ToList();
var retIds = plan.Returns.Select(r => r.Id).ToList();
var wlIds = plan.WaitingList.Select(w => w.Id).ToList();
var exhIds = plan.Exhibitions.Select(e => e.Id).ToList();
var encIds = plan.Enclosures.Keys.ToList();
if (acqIds.Count > 0) await _db.AcquisitionRecords.Where(x => acqIds.Contains(x.Id)).ExecuteDeleteAsync();
if (resIds.Count > 0) await _db.SaleReservations.Where(x => resIds.Contains(x.Id)).ExecuteDeleteAsync();
if (retIds.Count > 0) await _db.ReturnRecords.Where(x => retIds.Contains(x.Id)).ExecuteDeleteAsync();
if (wlIds.Count > 0) await _db.WaitingListEntries.Where(x => wlIds.Contains(x.Id)).ExecuteDeleteAsync();
if (exhIds.Count > 0) await _db.ExhibitionResults.Where(x => exhIds.Contains(x.Id)).ExecuteDeleteAsync();
// 2. Kontakte upserten (deterministische IDs; überleben als eigenständige Bestände).
int contactsImported = 0;
var existingContacts = await _db.Contacts.ToDictionaryAsync(c => c.Id);
foreach (var c in plan.Contacts.Values)
{
if (existingContacts.TryGetValue(c.Id, out var ex))
{
ex.Name = c.Name; ex.Email = c.Email; ex.Phone = c.Phone; ex.Address = c.Address;
ex.Notes = c.Notes; ex.IsBreeder = c.IsBreeder; ex.IsReceiver = c.IsReceiver;
ex.NameSuffix = c.NameSuffix; ex.Provenance = c.Provenance;
}
else { _db.Contacts.Add(c); }
contactsImported++;
}
await _db.SaveChangesAsync();
// 2b. Enclosures upserten (deterministische IDs). MUSS vor den Gerbils laufen, da
// Gerbil.EnclosureId ein echter FK ist. Re-Import aktualisiert dieselben Becken.
var existingEnclosures = await _db.Enclosures
.Where(e => plan.Enclosures.Keys.Contains(e.Id)).ToDictionaryAsync(e => e.Id);
foreach (var en in plan.Enclosures.Values)
{
if (existingEnclosures.TryGetValue(en.Id, out var ex))
{
ex.Name = en.Name; ex.Size = en.Size; ex.Capacity = en.Capacity;
ex.LastCleanedDate = en.LastCleanedDate; ex.CleaningCycleDays = en.CleaningCycleDays;
}
else { _db.Enclosures.Add(en); }
}
await _db.SaveChangesAsync();
// 3. Litters (Pass 1: ohne Eltern-FKs).
foreach (var l in plan.Litters.Values)
_db.Litters.Add(new Litter
{
Id = l.Id, Name = l.Name, Date = l.Date, ExternalRef = l.ExternalRef,
Notes = l.Notes, Provenance = l.Provenance, FatherId = null, MotherId = null,
});
await _db.SaveChangesAsync();
// 4. Gerbils (Pass 1: ohne LitterId).
var today = DateOnly.FromDateTime(DateTime.UtcNow);
foreach (var g in plan.Gerbils.Values)
{
var gerbil = new Gerbil
{
Id = g.Id, Name = g.Name, Gender = g.Gender,
DateOfBirth = g.Dob, DateOfDeath = g.DateOfDeath, CauseOfDeath = g.CauseOfDeath,
Genotype = g.Genotype, ColorVarietyId = g.ColorVarietyId, OriginBreeder = g.OriginBreeder,
OriginContactId = g.OriginContactId, ReceiverContactId = g.ReceiverContactId,
GoHomeDate = g.GoHomeDate, IsResident = g.IsResident, IsCastrated = g.IsCastrated,
Notes = g.Notes, ImportSource = Rpro3Guid.ImportSource, ExternalRef = g.ExternalRef,
Provenance = g.Provenance, LitterId = null,
EnclosureId = plan.GerbilEnclosure.TryGetValue(g.Id, out var encId) ? encId : null,
};
GerbilStatusService.Apply(gerbil, today);
_db.Gerbils.Add(gerbil);
}
await _db.SaveChangesAsync();
// 5. Pass 2: FK-Beziehungen setzen (Litter-Eltern + Gerbil-Geburtswurf).
var littersInDb = await _db.Litters.Where(l => l.ExternalRef != null && priorLitterRefs.Contains(l.ExternalRef)).ToDictionaryAsync(l => l.Id);
foreach (var l in plan.Litters.Values)
if (littersInDb.TryGetValue(l.Id, out var dbl))
{
dbl.MotherId = l.MotherId; dbl.FatherId = l.FatherId;
}
var gerbilsInDb = await _db.Gerbils.Where(g => g.ImportSource == Rpro3Guid.ImportSource).ToDictionaryAsync(g => g.Id);
foreach (var g in plan.Gerbils.Values)
if (g.LitterId is not null && gerbilsInDb.TryGetValue(g.Id, out var dbg))
dbg.LitterId = g.LitterId;
await _db.SaveChangesAsync();
// 6. Gesundheits- und Gewichtseinträge.
foreach (var h in plan.Health) _db.HealthRecords.Add(h);
foreach (var w in plan.Weights) _db.WeightRecords.Add(w);
await _db.SaveChangesAsync();
// 7. Fotos (optional, aus bilder.zip).
int photosImported = 0;
if (photosProvided && photoSourcePaths is not null)
{
Directory.CreateDirectory(_photoRoot);
foreach (var (gerbilId, fileNames) in plan.PhotoFiles)
{
int sort = 0;
foreach (var fn in fileNames)
{
if (!photoSourcePaths.TryGetValue(fn.ToLowerInvariant(), out var src) || !File.Exists(src)) continue;
var ext = Path.GetExtension(fn);
var storedName = $"{Guid.NewGuid():N}{ext}";
try { File.Copy(src, Path.Combine(_photoRoot, storedName), overwrite: true); }
catch { continue; }
_db.GerbilPhotos.Add(new GerbilPhoto
{
Id = Guid.NewGuid(), GerbilId = gerbilId, FileName = storedName,
SortOrder = sort++, CreatedAt = DateTimeOffset.UtcNow,
});
photosImported++;
}
}
await _db.SaveChangesAsync();
}
// 8. Feature-Tabellen einfügen (Enclosures schon in 2b erledigt).
foreach (var a in plan.Acquisitions) _db.AcquisitionRecords.Add(a);
foreach (var r in plan.Reservations) _db.SaleReservations.Add(r);
foreach (var r in plan.Returns) _db.ReturnRecords.Add(r);
foreach (var w in plan.WaitingList) _db.WaitingListEntries.Add(w);
foreach (var e in plan.Exhibitions) _db.ExhibitionResults.Add(e);
await _db.SaveChangesAsync();
return new Rpro3ExecuteResult(
plan.Gerbils.Count, plan.Litters.Count, contactsImported,
plan.Health.Count, plan.Weights.Count, photosImported,
plan.Enclosures.Count, plan.Acquisitions.Count, plan.Reservations.Count,
plan.Returns.Count, plan.WaitingList.Count, plan.Exhibitions.Count,
$"Import erfolgreich: {plan.Gerbils.Count} Tiere, {plan.Litters.Count} Würfe, " +
$"{contactsImported} Kontakte, {plan.Health.Count} Gesundheits- und {plan.Weights.Count} Gewichtseinträge, " +
$"{photosImported} Fotos, {plan.Enclosures.Count} Gehege, {plan.Acquisitions.Count} Erwerbe, " +
$"{plan.Reservations.Count} Reservierungen, {plan.Returns.Count} Rücknahmen, " +
$"{plan.WaitingList.Count} Wartelisten-Einträge, {plan.Exhibitions.Count} Ausstellungen.");
}
// ───────────────────────── PLAN-AUFBAU ─────────────────────────
private sealed class GerbilPlan
{
public required Guid Id { get; init; }
public required string ExternalRef { get; init; }
public required string Name { get; set; }
public Gender Gender { get; set; }
public DateOnly? Dob { get; set; }
public DateOnly? DateOfDeath { get; set; }
public string? CauseOfDeath { get; set; }
public string? Genotype { get; set; }
public Guid? ColorVarietyId { get; set; }
public string? OriginBreeder { get; set; }
public Guid? OriginContactId { get; set; }
public Guid? ReceiverContactId { get; set; }
public DateOnly? GoHomeDate { get; set; }
public bool IsResident { get; set; }
public bool IsCastrated { get; set; }
public string? Notes { get; set; }
public string? Provenance { get; set; }
public Guid? LitterId { get; set; }
public string? MotherRid { get; set; }
public string? FatherRid { get; set; }
}
private sealed class LitterPlan
{
public required Guid Id { get; init; }
public required string ExternalRef { get; init; }
public string Name { get; set; } = "Wurf";
public DateOnly? Date { get; set; }
public Guid? MotherId { get; set; }
public Guid? FatherId { get; set; }
public string? Notes { get; set; }
public string? Provenance { get; set; }
}
private sealed class ImportPlan
{
public Dictionary<Guid, GerbilPlan> Gerbils { get; } = new();
public Dictionary<Guid, LitterPlan> Litters { get; } = new();
public Dictionary<Guid, Contact> Contacts { get; } = new();
public List<HealthRecord> Health { get; } = new();
public List<WeightRecord> Weights { get; } = new();
public Dictionary<Guid, List<string>> PhotoFiles { get; } = new();
// Feature-Tabellen.
public Dictionary<Guid, Enclosure> Enclosures { get; } = new();
public Dictionary<Guid, Guid> GerbilEnclosure { get; } = new(); // GerbilId → EnclosureId
public List<AcquisitionRecord> Acquisitions { get; } = new();
public List<SaleReservation> Reservations { get; } = new();
public List<ReturnRecord> Returns { get; } = new();
public List<WaitingListEntry> WaitingList { get; } = new();
public List<ExhibitionResult> Exhibitions { get; } = new();
}
private ImportPlan BuildPlan(Rpro3Data data, Rpro3Dedup.DedupResult dedup)
{
_lastDedup = dedup;
var plan = new ImportPlan();
// 0) Farbschlag-Katalog (Name → Id) für ColorVariety-Verknüpfung.
var colorByName = _db.ColorVarieties.AsNoTracking()
.ToDictionary(c => Rpro3Dedup.NormName(c.Name), c => c.Id);
// 1) Kontakte (herk = Züchter/Herkunft, abn = Abnehmer).
Guid? HerkContactId(int? herkId)
{
if (herkId is null || herkId == 1) return null; // 1 = eigene Zucht → kein Kontakt
if (!data.HerkContacts.TryGetValue(herkId.Value.ToString(), out var c)) return null;
return EnsureContact(plan, c, isBreeder: true, isReceiver: false);
}
Guid? AbnContactId(int? abnId)
{
if (abnId is null) return null;
if (!data.AbnContacts.TryGetValue(abnId.Value.ToString(), out var c)) return null;
return EnsureContact(plan, c, isBreeder: false, isReceiver: true);
}
// 2) Rid → Cluster-Root → Gerbil-GUID. Platzhalter-Tiere bekommen ihren eigenen Root.
string RootOf(string rid) => dedup.RidToRoot.TryGetValue(rid, out var r) ? r : rid;
Guid GerbilIdOfRid(string rid) => Rpro3Guid.Gerbil(RootOf(rid));
// 3) Pup-Index: SID(stamm-id) → pup, und stamm-id → Welpen-Daten (Abgabe/Preis/Tod).
var pupBySid = new Dictionary<string, Rpro3Pup>(StringComparer.Ordinal);
foreach (var p in data.Pups.Values)
if (!string.IsNullOrWhiteSpace(p.Sid) && p.Sid != "0")
pupBySid[p.Sid] = p;
// 4) Ein Gerbil je Cluster (Repräsentant führt; stamm-Tiere machen den Cluster resident).
// Singletons (RidToRoot == self) ebenfalls einbeziehen.
var clusterMembers = new Dictionary<string, List<Rpro3Animal>>(StringComparer.Ordinal);
foreach (var a in data.Animals)
{
var root = RootOf(a.Rid);
if (!clusterMembers.TryGetValue(root, out var list)) clusterMembers[root] = list = new();
list.Add(a);
}
foreach (var (root, members) in clusterMembers)
{
var rep = Rpro3Dedup.Representative(members);
bool resident = members.Any(m => m.Src == Rpro3Src.Stamm);
var id = Rpro3Guid.Gerbil(root);
if (plan.Gerbils.ContainsKey(id)) continue;
// Bestes bekanntes Feld aus allen Cluster-Mitgliedern wählen.
var dob = members.Select(m => m.Dob).FirstOrDefault(d => d is not null) ?? rep.Dob;
var farbe = members.Select(m => m.Farbe).FirstOrDefault(f => !string.IsNullOrWhiteSpace(f)) ?? rep.Farbe;
var fcode = members.Select(m => m.Fcode).FirstOrDefault(f => !string.IsNullOrWhiteSpace(f)) ?? rep.Fcode;
var death = members.FirstOrDefault(m => m.DateOfDeath is not null);
var origin = members.Select(m => m.Origin).FirstOrDefault(o => Rpro3Dedup.NormValue(o).Length > 0) ?? rep.Origin;
var herkId = members.Select(m => m.OriginHerkId).FirstOrDefault(h => h is not null and not 1);
// Manuelle Feld-Korrektur der Züchterin (Rpro3Decisions): adressiert über IRGENDEINE
// rid des Clusters. Überschreibt das automatisch gewählte Feld; "Note" wird angehängt.
Rpro3FieldOverride? ov = null;
foreach (var m in members)
if (FieldIndex.TryGetValue(m.Rid, out ov)) break;
bool? residentOverride = ov?.Resident;
if (ov is not null)
{
if (!string.IsNullOrWhiteSpace(ov.Color)) farbe = ov.Color;
if (!string.IsNullOrWhiteSpace(ov.Origin)) origin = ov.Origin;
if (!string.IsNullOrWhiteSpace(ov.Genotype)) fcode = ov.Genotype;
if (!string.IsNullOrWhiteSpace(ov.Dob) && DateOnly.TryParse(ov.Dob, out var od)) dob = od;
}
var gp = new GerbilPlan
{
Id = id,
ExternalRef = Rpro3Guid.GerbilRef(root),
Name = string.IsNullOrWhiteSpace(rep.Name) ? "Unbenannt" : rep.Name!,
Gender = members.Select(m => m.Gender).FirstOrDefault(g => g != Gender.unknown),
Dob = dob,
DateOfDeath = death?.DateOfDeath,
CauseOfDeath = death?.CauseOfDeath,
Genotype = CleanGenotype(fcode),
OriginBreeder = herkId == 1 ? "eigene Zucht" : (Rpro3Dedup.NormValue(origin).Length > 0 ? origin : null),
OriginContactId = HerkContactId(herkId),
IsResident = residentOverride ?? resident,
IsCastrated = members.Any(m => m.IsCastrated),
MotherRid = rep.MidRaw,
FatherRid = rep.PidRaw,
};
if (!string.IsNullOrWhiteSpace(farbe) && colorByName.TryGetValue(Rpro3Dedup.NormName(farbe), out var cvId))
gp.ColorVarietyId = cvId;
// Welpen-Zusatzdaten (Abgabe/Preis) für residente Tiere, die ein wurftier sind.
foreach (var m in members.Where(m => m.Src == Rpro3Src.Stamm))
if (pupBySid.TryGetValue(m.Rid, out var pup))
{
gp.GoHomeDate = pup.AbgabeDate;
gp.ReceiverContactId = AbnContactId(pup.AbnId);
if (pup.DateOfDeath is not null && gp.DateOfDeath is null)
{
gp.DateOfDeath = pup.DateOfDeath; gp.CauseOfDeath = pup.CauseOfDeath;
}
}
gp.Notes = BuildNotes(members);
if (!string.IsNullOrWhiteSpace(ov?.Note))
gp.Notes = string.IsNullOrWhiteSpace(gp.Notes) ? ov!.Note : $"{gp.Notes}\n{ov!.Note}";
gp.Provenance = BuildProvenance(data, members, dedup);
plan.Gerbils[id] = gp;
}
// 5) Würfe aus wurf_tb (autoritativ). Eltern → Cluster-GUID.
foreach (var (wid, w) in data.Litters)
{
var id = Rpro3Guid.Litter(wid);
var lp = new LitterPlan
{
Id = id,
ExternalRef = Rpro3Guid.LitterRef(wid),
Name = string.IsNullOrWhiteSpace(w.Name) ? $"Wurf {wid}" : w.Name!,
Date = w.Date,
Notes = w.Notes,
MotherId = ResolveParentGuid(w.MotherRid, plan),
FatherId = ResolveParentGuid(w.FatherRid, plan),
Provenance = JsonProvenance("RennmausPro III", new() { ["wurfId"] = wid, ["quelle"] = "wurf_tb" }),
};
plan.Litters[id] = lp;
}
// 6) Welpen → Geburtswurf verknüpfen (pup._SID → resultierendes Gerbil).
foreach (var p in data.Pups.Values)
{
if (string.IsNullOrWhiteSpace(p.Sid) || p.Sid == "0") continue;
var gid = GerbilIdOfRid(p.Sid);
if (!plan.Gerbils.TryGetValue(gid, out var gp)) continue;
var litterId = Rpro3Guid.Litter(p.WurfId);
if (plan.Litters.ContainsKey(litterId)) gp.LitterId = litterId;
}
// 7) Synthetische „Pedigree-Würfe" für Tiere mit baum_tb-Eltern, aber ohne wurf_tb-Geburtswurf.
// So traversiert der Stammbaum (Litter → Father/Mother) auch externe Ahnen-Linien.
foreach (var gp in plan.Gerbils.Values)
{
if (gp.LitterId is not null) continue;
var motherId = ResolveParentGuid(gp.MotherRid, plan);
var fatherId = ResolveParentGuid(gp.FatherRid, plan);
if (motherId is null && fatherId is null) continue;
var key = $"ped:{motherId}:{fatherId}";
var litterId = Rpro3Guid.For("litter", key);
if (!plan.Litters.TryGetValue(litterId, out var lp))
{
lp = new LitterPlan
{
Id = litterId,
ExternalRef = $"rpro3-ped:{motherId}:{fatherId}",
Name = "Abstammung (RennmausPro)",
MotherId = motherId,
FatherId = fatherId,
Provenance = JsonProvenance("RennmausPro III", new() { ["quelle"] = "baum_tb", ["synthetisch"] = true }),
};
plan.Litters[litterId] = lp;
}
gp.LitterId = litterId;
}
// 8) Gesundheit/Gewicht/Tagebuch → stamm-Tiere (tid = stamm-id).
BuildHealthAndWeights(data, plan, GerbilIdOfRid);
// 9) Fotos (photo_tb id = stamm-id).
foreach (var (tid, set) in data.Photos)
{
var gid = GerbilIdOfRid(tid);
if (plan.Gerbils.ContainsKey(gid)) plan.PhotoFiles[gid] = set.FileNames;
}
// 10) Feature-Tabellen (Becken/Erwerb/Reservierung/Rücknahme/Warteliste/Ausstellung).
BuildFeatureTables(data, plan, dedup, pupBySid);
return plan;
}
/// <summary>
/// Baut die 6 Feature-Entities aus den RPRO3-Feature-Tabellen. Alle Referenzen werden über
/// die bereits aufgebauten Gerbil-/Contact-GUIDs aufgelöst; tids können stamm ("N") oder
/// wurftier ("XjY") sein — Welpen-tids werden über _SID auf das resultierende Tier abgebildet.
/// </summary>
private void BuildFeatureTables(
Rpro3Data data, ImportPlan plan, Rpro3Dedup.DedupResult dedup, Dictionary<string, Rpro3Pup> pupBySid)
{
string RootOf(string rid) => dedup.RidToRoot.TryGetValue(rid, out var r) ? r : rid;
// tid ("N" oder "XjY") → (GerbilId?, erfasster Name?). Welpen ohne kept-_SID liefern null-Id.
(Guid? id, string? name) ResolveGerbil(string? tid)
{
if (string.IsNullOrWhiteSpace(tid)) return (null, null);
string rid = tid;
if (tid.Contains('j'))
{
// Welpe: über _SID auf das behaltene stamm-Tier abbilden, falls vorhanden.
if (data.Pups.TryGetValue(tid, out var pup) && !string.IsNullOrWhiteSpace(pup.Sid) && pup.Sid != "0")
rid = pup.Sid!;
else
{
var pupName = data.Pups.TryGetValue(tid, out var p) ? p.Name : null;
return (null, pupName);
}
}
var gid = Rpro3Guid.Gerbil(RootOf(rid));
return plan.Gerbils.TryGetValue(gid, out var gp) ? (gid, gp.Name) : (null, data.ResolveName(rid));
}
// abn-id → (ContactId?, erfasster Name?). Legt den Kontakt bei Bedarf an (als Abnehmer).
(Guid? id, string? name) ResolveAbn(int? abnId)
{
if (abnId is null) return (null, null);
if (!data.AbnContacts.TryGetValue(abnId.Value.ToString(), out var c)) return (null, null);
var id = EnsureContact(plan, c, isBreeder: false, isReceiver: true);
return (id, c.DisplayName);
}
var now = DateTimeOffset.UtcNow;
static DateTime? AsDt(DateOnly? d) => d?.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
// ── Becken → Enclosure (+ stamm._BECKEN → Gerbil-Zuordnung) ──
var beckenById = new Dictionary<int, Guid>();
foreach (var b in data.Becken)
{
var id = Rpro3Guid.Enclosure(b.Id);
beckenById[b.Id] = id;
plan.Enclosures[id] = new Enclosure
{
Id = id,
Name = string.IsNullOrWhiteSpace(b.Name) ? $"Becken {b.Id}" : b.Name!,
Size = string.IsNullOrWhiteSpace(b.Size) ? null : b.Size,
Capacity = b.Capacity is > 0 ? b.Capacity : null,
LastCleanedDate = b.LastCleaned,
CleaningCycleDays = b.CycleDays is > 0 ? b.CycleDays : null,
};
}
foreach (var (rid, beckenId) in data.StammBecken)
{
if (!beckenById.TryGetValue(beckenId, out var encId)) continue;
var gid = Rpro3Guid.Gerbil(RootOf(rid));
if (plan.Gerbils.ContainsKey(gid)) plan.GerbilEnclosure[gid] = encId;
}
// ── herktier_tb → AcquisitionRecord ──
foreach (var a in data.Acquisitions)
{
var (gid, _) = ResolveGerbil(a.Tid);
if (gid is null) continue; // kein Tier → kein Erwerb
// Herkunfts-Kontakt steht bereits auf Gerbil.OriginContactId; hier Datum/Preis/Notiz.
Guid? sourceContactId = plan.Gerbils.TryGetValue(gid.Value, out var gp) ? gp.OriginContactId : null;
plan.Acquisitions.Add(new AcquisitionRecord
{
Id = Rpro3Guid.Acquisition(a.Id),
GerbilId = gid,
SourceContactId = sourceContactId,
Date = a.Date,
Price = a.Price is > 0 ? a.Price : null,
Note = NullIfEmpty(a.Note),
CreatedAt = now,
});
}
// ── abgeben_tb + abstat_tb → SaleReservation (eine Zeile je Tier) ──
// abgeben = Vormerkung/Reservierung (oft Welpen-tid), abstat = Abgabe-Abschluss (stamm-tid).
// Beide werden über das Tier zusammengeführt; ist beides vorhanden, gewinnt „abgegeben".
var reservationByGerbil = new Dictionary<Guid, SaleReservation>();
SaleReservation Res(Guid gid, string? name, string tidKey)
{
if (reservationByGerbil.TryGetValue(gid, out var ex)) return ex;
var res = new SaleReservation
{
Id = Rpro3Guid.Reservation(tidKey),
GerbilId = gid,
GerbilName = name,
Status = "verfuegbar",
CreatedAt = now,
UpdatedAt = now,
};
reservationByGerbil[gid] = res;
plan.Reservations.Add(res);
return res;
}
foreach (var ab in data.Abgeben)
{
var (gid, name) = ResolveGerbil(ab.Tid);
if (gid is null) continue;
var res = Res(gid.Value, name, ab.Tid);
var (cid, cname) = ResolveAbn(ab.AbnId);
if (res.Status != "abgegeben") res.Status = ab.Reserved ? "reserviert" : res.Status;
res.ReservedForContactId ??= cid;
res.ContactName ??= cname;
res.AppointmentDate ??= AsDt(ab.Appointment);
res.Note ??= NullIfEmpty(ab.Note);
}
foreach (var st in data.Abstat)
{
var (gid, name) = ResolveGerbil(st.Tid);
if (gid is null) continue;
var res = Res(gid.Value, name, st.Tid);
var (cid, cname) = ResolveAbn(st.AbnId);
res.Status = "abgegeben";
res.ReservedForContactId ??= cid;
res.ContactName ??= cname;
res.HandedOverDate ??= AsDt(st.HandedOver);
if (st.Price is > 0) res.Price ??= st.Price;
res.Note ??= NullIfEmpty(st.Note);
res.UpdatedAt = now;
}
// ── getback_tb → ReturnRecord ──
foreach (var gb in data.Getback)
{
var (gid, name) = ResolveGerbil(gb.Tid);
var (cid, cname) = ResolveAbn(gb.AbnId);
plan.Returns.Add(new ReturnRecord
{
Id = Rpro3Guid.Return(gb.Id),
GerbilId = gid,
GerbilName = name,
ReturnDate = AsDt(gb.ReturnDate),
ReturnPrice = gb.ReturnPrice is > 0 ? gb.ReturnPrice : null,
OriginalPrice = gb.OriginalPrice is > 0 ? gb.OriginalPrice : null,
OriginalSaleDate = AsDt(gb.OriginalSaleDate),
FromContactId = cid,
FromContactName = cname,
Note = NullIfEmpty(gb.Note),
CreatedAt = now,
});
}
// ── nachfrage_tb → WaitingListEntry ──
foreach (var nf in data.Nachfrage)
{
var (cid, cname) = ResolveAbn(nf.AbnId);
plan.WaitingList.Add(new WaitingListEntry
{
Id = Rpro3Guid.WaitingList(nf.Id),
ContactId = cid,
ContactName = cname,
WishColor = NullIfEmpty(nf.WishColor),
WishGender = nf.WishGender switch
{
Gender.male => "male",
Gender.female => "female",
_ => null,
},
RequestedAt = AsDt(nf.RequestedAt),
Status = MapWaitlistStatus(nf.Status),
Note = NullIfEmpty(nf.Note),
CreatedAt = now,
});
}
// ── ausz_tb → ExhibitionResult (in vielen Backups leer; trotzdem voll verdrahtet) ──
foreach (var ex in data.Ausstellungen)
{
var (gid, name) = ResolveGerbil(ex.Tid);
var noteParts = new[] { ex.Place, ex.Juror is { Length: > 0 } ? $"Juror: {ex.Juror}" : null, ex.Note }
.Where(s => !string.IsNullOrWhiteSpace(s));
var note = string.Join(" · ", noteParts);
plan.Exhibitions.Add(new ExhibitionResult
{
Id = Rpro3Guid.Exhibition(ex.Id),
GerbilId = gid,
EntityName = name,
EventName = string.IsNullOrWhiteSpace(ex.EventName) ? "Ausstellung" : ex.EventName!,
Date = AsDt(ex.Date),
Placement = NullIfEmpty(ex.Placement),
Award = NullIfEmpty(ex.Award),
Note = string.IsNullOrWhiteSpace(note) ? null : note,
CreatedAt = now,
});
}
}
private static string? NullIfEmpty(string? s) => string.IsNullOrWhiteSpace(s) ? null : s.Trim();
/// <summary>RPRO3 nachfrage._STATUS → unser Status (offen | erfuellt | storniert).</summary>
private static string MapWaitlistStatus(string? raw)
{
var s = (raw ?? "").Trim().ToLowerInvariant();
return s switch
{
"" or "offen" or "0" => "offen",
"erfuellt" or "erfüllt" or "1" => "erfuellt",
"storniert" or "2" => "storniert",
_ => "offen",
};
}
private Guid? ResolveParentGuid(string? rid, ImportPlan plan)
{
if (string.IsNullOrWhiteSpace(rid) || rid is "n" or "NULL" or "0") return null;
var gid = Rpro3Guid.Gerbil(_lastDedup!.RidToRoot.TryGetValue(rid, out var r) ? r : rid);
return plan.Gerbils.ContainsKey(gid) ? gid : null;
}
// Kontext-Hack: ResolveParentGuid braucht die RidToRoot-Map des aktuellen Plans.
private Rpro3Dedup.DedupResult? _lastDedup;
private void BuildHealthAndWeights(Rpro3Data data, ImportPlan plan, Func<string, Guid> gerbilIdOfRid)
{
int seq = 0;
foreach (var h in data.Health)
{
var gid = gerbilIdOfRid(h.Tid);
if (!plan.Gerbils.ContainsKey(gid) || h.Date is null) continue;
var desc = string.IsNullOrWhiteSpace(h.Description) ? "Krankheitseintrag" : h.Description!;
if (!string.IsNullOrWhiteSpace(h.Medication)) desc += $" (Medikation: {h.Medication})";
plan.Health.Add(new HealthRecord
{
Id = Rpro3Guid.Health(h.Tid, desc, seq++),
GerbilId = gid, Date = h.Date.Value, Type = HealthRecordType.Treatment,
Description = desc, CreatedAt = DateTimeOffset.UtcNow,
});
}
// Tagebuch als "Other"-Gesundheitseinträge (kein eigenes Tagebuch-Modell vorhanden).
foreach (var d in data.Diary)
{
var gid = gerbilIdOfRid(d.Tid);
if (!plan.Gerbils.ContainsKey(gid) || d.Date is null || string.IsNullOrWhiteSpace(d.Description)) continue;
var desc = (string.IsNullOrWhiteSpace(d.Title) ? "" : d.Title + ": ") + d.Description;
plan.Health.Add(new HealthRecord
{
Id = Rpro3Guid.Health(d.Tid, "diary:" + desc, seq++),
GerbilId = gid, Date = d.Date.Value, Type = HealthRecordType.Other,
Description = "Tagebuch: " + desc, CreatedAt = DateTimeOffset.UtcNow,
});
}
int wseq = 0;
var seen = new HashSet<Guid>();
foreach (var w in data.Weights)
{
var gid = gerbilIdOfRid(w.Tid);
if (!plan.Gerbils.ContainsKey(gid) || w.Date is null || w.Grams <= 0) continue;
var id = Rpro3Guid.Weight(w.Tid + ":" + w.Date.Value.DayNumber, wseq++);
if (!seen.Add(id)) continue;
plan.Weights.Add(new WeightRecord
{
Id = id, GerbilId = gid, Date = w.Date.Value, WeightGrams = w.Grams, Notes = w.Notes,
});
}
}
private Guid EnsureContact(ImportPlan plan, Rpro3Contact c, bool isBreeder, bool isReceiver)
{
var id = Rpro3Guid.Contact(c.Namespace, c.Id);
if (plan.Contacts.TryGetValue(id, out var ex))
{
ex.IsBreeder |= isBreeder; ex.IsReceiver |= isReceiver;
return id;
}
var address = string.Join(", ",
new[] { c.Str, $"{c.Plz} {c.Ort}".Trim() }.Where(s => !string.IsNullOrWhiteSpace(s)));
var notes = string.Join("\n",
new[] { c.Memo, c.Bem, c.Http }.Where(s => !string.IsNullOrWhiteSpace(s)));
plan.Contacts[id] = new Contact
{
Id = id,
Name = c.DisplayName,
Email = string.IsNullOrWhiteSpace(c.Mail) ? null : c.Mail,
Phone = string.IsNullOrWhiteSpace(c.Telp) ? c.Teld : c.Telp,
Address = string.IsNullOrWhiteSpace(address) ? null : address,
Notes = string.IsNullOrWhiteSpace(notes) ? null : notes,
IsBreeder = isBreeder,
IsReceiver = isReceiver,
NameSuffix = string.IsNullOrWhiteSpace(c.Clan) ? null : c.Clan,
Provenance = JsonProvenance("RennmausPro III",
new() { ["quelle"] = c.Namespace == "herk" ? "herk_tb" : "abn_tb", ["rpro3Id"] = c.Id }),
};
return id;
}
// ───────────────────────── Helpers ─────────────────────────
/// <summary>RPRO3 nutzt Bracket-Notation (c[chm], e[f], ee[-]); unser Genotyp-Contract nutzt
/// kompakte Notation (cchm, ef). Klammern entfernen, "-" (unbekannt) bleibt erhalten.</summary>
internal static string? CleanGenotype(string? fcode)
{
if (string.IsNullOrWhiteSpace(fcode)) return null;
var sb = new System.Text.StringBuilder(fcode.Length);
foreach (var ch in fcode)
if (ch != '[' && ch != ']') sb.Append(ch);
var cleaned = sb.ToString().Trim();
return cleaned.Length == 0 ? null : cleaned;
}
private static string? BuildNotes(List<Rpro3Animal> members)
{
var defects = members.Select(m => m.Defects).Where(d => !string.IsNullOrWhiteSpace(d)).Distinct().ToList();
var zb = members.Select(m => m.Zb).FirstOrDefault(z => !string.IsNullOrWhiteSpace(z));
var parts = new List<string>();
if (!string.IsNullOrWhiteSpace(zb)) parts.Add($"Zuchtbuch-Nr.: {zb}");
if (defects.Count > 0) parts.Add("Defekte: " + string.Join("; ", defects));
return parts.Count > 0 ? string.Join("\n", parts) : null;
}
private static string BuildProvenance(Rpro3Data data, List<Rpro3Animal> members, Rpro3Dedup.DedupResult dedup)
{
var rep = Rpro3Dedup.Representative(members);
var obj = new Dictionary<string, object?>
{
["importSource"] = "RennmausPro III",
["mergedRecordCount"] = members.Count,
["rpro3Ids"] = members.Select(m => m.Rid).Take(8).ToList(),
["mother"] = data.ResolveName(rep.MidRaw),
["father"] = data.ResolveName(rep.PidRaw),
};
if (members.Count > 1)
obj["note"] = $"{members.Count} RennmausPro-Datensätze zusammengelegt (Name + Geburtsdatum + Farbe + Herkunft).";
return JsonSerializer.Serialize(obj);
}
private static string JsonProvenance(string source, Dictionary<string, object?> extra)
{
extra["importSource"] = source;
return JsonSerializer.Serialize(extra);
}
private static string Truncate(string s, int max) => s.Length <= max ? s : s[..max];
}
}

View File

@@ -0,0 +1,246 @@
using GerbilManagerWebAPI.Models;
namespace GerbilManagerWebAPI.Import.Rpro3
{
/// <summary>
/// Quelle eines RPRO3-Tier-Datensatzes. „stamm" = eigenes Tier, „fremd" = externer Ahn,
/// „wurftier" = Welpe eines Wurfs (nur relevant, wenn nicht in ein stamm-Tier überführt).
/// </summary>
public enum Rpro3Src { Stamm, Fremd, Wurftier }
/// <summary>Einheitlicher Tier-Datensatz aus der RPRO3-SQLite (vor Dedup).
/// `Rid` ist die RPRO3-ID im jeweiligen Namensraum: "N"=stamm, "uN"=fremd, "XjY"=wurftier.</summary>
public sealed class Rpro3Animal
{
public required string Rid { get; init; }
public Rpro3Src Src { get; init; }
public string? Name { get; set; }
public Gender Gender { get; set; }
public DateOnly? Dob { get; set; }
public string? Farbe { get; set; } // _FARBE Farbschlagname
public string? Fcode { get; set; } // _FCODE 8-Locus-Genotyp
public string? Origin { get; set; } // aufgelöster Herkunfts-Name (herk_tb)
public int? OriginHerkId { get; set; } // herk_tb.id (1 = eigene Zucht)
public string? Zb { get; set; }
public string? MidRaw { get; set; } // Mutter-Ref im RPRO3-Namensraum
public string? PidRaw { get; set; } // Vater-Ref im RPRO3-Namensraum
public DateOnly? DateOfDeath { get; set; }
public string? CauseOfDeath { get; set; }
public string? Defects { get; set; } // _FEHLER
public bool IsCastrated { get; set; }
public int? StatusCode { get; set; } // stamm._STATUS (RPRO3)
// Dedup-Schlüssel (normalisiert), wird von Rpro3Dedup gesetzt.
public string NameKey { get; set; } = "";
public string FarbeKey { get; set; } = "";
public string OriginKey { get; set; } = "";
}
public sealed class Rpro3Litter
{
public required int Id { get; init; }
public string? Name { get; set; } // _BEZ "Wurf A"
public DateOnly? Date { get; set; } // _AM
public string? MotherRid { get; set; } // stamm-id als string
public string? FatherRid { get; set; }
public string? Notes { get; set; } // _BEM
}
public sealed class Rpro3Pup
{
public required string Id { get; init; } // "XjY"
public int WurfId { get; init; }
public string? Name { get; set; }
public Gender Gender { get; set; }
public DateOnly? Dob { get; set; }
public string? Sid { get; set; } // → stamm-id, falls als eigenes Tier behalten
public DateOnly? DateOfDeath { get; set; }
public string? CauseOfDeath { get; set; }
public DateOnly? AbgabeDate { get; set; }
public int? AbnId { get; set; } // → abn_tb
public decimal? Price { get; set; }
public string? Zb { get; set; }
public string? Defects { get; set; }
}
public sealed class Rpro3Contact
{
public required int Id { get; init; }
public required string Namespace { get; init; } // "herk" | "abn"
public string? Bez { get; set; }
public string? Anrede { get; set; }
public string? Vname { get; set; }
public string? Nname { get; set; }
public string? Clan { get; set; }
public string? Str { get; set; }
public string? Ort { get; set; }
public string? Plz { get; set; }
public string? Telp { get; set; }
public string? Teld { get; set; }
public string? Mail { get; set; }
public string? Http { get; set; }
public string? Memo { get; set; }
public string? Bem { get; set; }
/// <summary>Anzeigename: Bezeichnung/Cattery, sonst Clan, sonst Vor+Nachname.</summary>
public string DisplayName =>
FirstNonEmpty(Bez, Clan, $"{Vname} {Nname}".Trim()) ?? "Unbekannt";
private static string? FirstNonEmpty(params string?[] vals) =>
vals.FirstOrDefault(v => !string.IsNullOrWhiteSpace(v));
}
public sealed class Rpro3Weight
{
public required string Tid { get; init; } // stamm-id (waage) bzw. wurftier-id (jungwaage)
public DateOnly? Date { get; set; }
public int Grams { get; set; }
public string? Notes { get; set; }
}
public sealed class Rpro3Health
{
public required string Tid { get; init; }
public DateOnly? Date { get; set; }
public string? Description { get; set; }
public string? Medication { get; set; }
}
public sealed class Rpro3Diary
{
public required string Tid { get; init; }
public DateOnly? Date { get; set; }
public string? Title { get; set; }
public string? Description { get; set; }
}
public sealed class Rpro3PhotoSet
{
public required string Tid { get; init; } // stamm-id
public List<string> FileNames { get; } = new();
}
// ── Feature-Tabellen (becken/herktier/abgeben/abstat/getback/nachfrage/ausz) ──
/// <summary>becken_tb: Gehege/Becken (id, _BEZ Name, _SIZE Maße, _MENGE Kapazität,
/// _CLEANED letzte Reinigung JDN, _CYCLUS Reinigungsintervall Tage).</summary>
public sealed class Rpro3Becken
{
public required int Id { get; init; }
public string? Name { get; set; }
public string? Size { get; set; }
public int? Capacity { get; set; }
public DateOnly? LastCleaned { get; set; }
public int? CycleDays { get; set; }
}
/// <summary>herktier_tb: Erwerb eines Tieres (_TID stamm-id, _DATE Kaufdatum JDN,
/// _PRICE Kaufpreis, _BEM Notiz).</summary>
public sealed class Rpro3Acquisition
{
public required int Id { get; init; }
public string? Tid { get; set; } // stamm-id
public DateOnly? Date { get; set; }
public decimal? Price { get; set; }
public string? Note { get; set; }
}
/// <summary>abgeben_tb: Reservierung/Vormerkung (tid stamm- oder wurftier-id, _RES reserviert?,
/// _TERMIN Abgabetermin JDN, _ABN Abnehmer-Kontakt, _BEM Notiz).</summary>
public sealed class Rpro3Abgeben
{
public required string Tid { get; init; } // stamm-id ("N") oder wurftier-id ("XjY")
public bool Reserved { get; set; }
public DateOnly? Appointment { get; set; }
public int? AbnId { get; set; }
public string? Note { get; set; }
}
/// <summary>abstat_tb: Abgabe-Abschluss (tid stamm-id, _IDABN Abnehmer-Kontakt,
/// _AM Abgabedatum JDN, _PRICE Abgabepreis, _BEM Notiz).</summary>
public sealed class Rpro3Abstat
{
public required string Tid { get; init; } // stamm-id
public int? AbnId { get; set; }
public DateOnly? HandedOver { get; set; }
public decimal? Price { get; set; }
public string? Note { get; set; }
}
/// <summary>getback_tb: Rücknahme (_TID stamm-/wurftier-id, _ZAM Rücknahmedatum JDN,
/// _ZPREIS Rücknahmepreis, _AM ursprüngliches Abgabedatum JDN, _PREIS ursprünglicher Preis,
/// _ABN Kontakt, von dem zurückkam, _BEM Notiz).</summary>
public sealed class Rpro3Getback
{
public required int Id { get; init; }
public string? Tid { get; set; } // stamm- oder wurftier-id
public DateOnly? ReturnDate { get; set; }
public decimal? ReturnPrice { get; set; }
public DateOnly? OriginalSaleDate { get; set; }
public decimal? OriginalPrice { get; set; }
public int? AbnId { get; set; }
public string? Note { get; set; }
}
/// <summary>nachfrage_tb: Warteliste/Nachfrage (_COLOR Wunschfarbe, _SEX Wunschgeschlecht,
/// _ABN Interessenten-Kontakt, _VOM Anfragedatum JDN, _STATUS Status, _BEM/_CODE Notiz).</summary>
public sealed class Rpro3Nachfrage
{
public required int Id { get; init; }
public string? WishColor { get; set; }
public Gender WishGender { get; set; }
public int? AbnId { get; set; }
public DateOnly? RequestedAt { get; set; }
public string? Status { get; set; }
public string? Note { get; set; }
}
/// <summary>ausz_tb: Ausstellungsergebnis (_TID stamm-/wurftier-id, _VERANSTALTUNG Veranstaltung,
/// _DATE Datum JDN, _ORT Ort, _PLATZ Platzierung, _AUSZ Auszeichnung, _JUROR/_EXTRA/_BEM Notiz).</summary>
public sealed class Rpro3Ausstellung
{
public required int Id { get; init; }
public string? Tid { get; set; }
public string? EventName { get; set; }
public DateOnly? Date { get; set; }
public string? Place { get; set; } // _ORT
public string? Placement { get; set; } // _PLATZ
public string? Award { get; set; } // _AUSZ
public string? Juror { get; set; }
public string? Note { get; set; }
}
/// <summary>Vollständig geparster RPRO3-Backup-Inhalt.</summary>
public sealed class Rpro3Data
{
public List<Rpro3Animal> Animals { get; } = new(); // stamm + fremd
public Dictionary<int, Rpro3Litter> Litters { get; } = new();
public Dictionary<string, Rpro3Pup> Pups { get; } = new();
public Dictionary<string, Rpro3Contact> HerkContacts { get; } = new();
public Dictionary<string, Rpro3Contact> AbnContacts { get; } = new();
public List<Rpro3Weight> Weights { get; } = new();
public List<Rpro3Health> Health { get; } = new();
public List<Rpro3Diary> Diary { get; } = new();
public Dictionary<string, Rpro3PhotoSet> Photos { get; } = new();
// Feature-Tabellen.
public List<Rpro3Becken> Becken { get; } = new();
public List<Rpro3Acquisition> Acquisitions { get; } = new();
public List<Rpro3Abgeben> Abgeben { get; } = new();
public List<Rpro3Abstat> Abstat { get; } = new();
public List<Rpro3Getback> Getback { get; } = new();
public List<Rpro3Nachfrage> Nachfrage { get; } = new();
public List<Rpro3Ausstellung> Ausstellungen { get; } = new();
/// <summary>stamm-id (string) → becken_tb.id (Gehege-Zuordnung aus stamm_tb._BECKEN).
/// Nur positive, gültige Becken-IDs.</summary>
public Dictionary<string, int> StammBecken { get; } = new();
// Roh-Zählungen (vor Dedup) für den Report.
public int ColorStammCount { get; set; }
public int ColorExtCount { get; set; }
/// <summary>Löst eine RPRO3-Ref ("N"/"uN"/"XjY") in einen Anzeigenamen auf (für Provenance/Report).</summary>
public Func<string?, string?> ResolveName { get; set; } = _ => null;
}
}

View File

@@ -0,0 +1,613 @@
using System.Globalization;
using System.IO.Compression;
using System.Text;
using GerbilManagerWebAPI.Models;
using Microsoft.Data.Sqlite;
namespace GerbilManagerWebAPI.Import.Rpro3
{
/// <summary>
/// Liest eine RennmausPro-III-`.backup` (ZIP mit `_rpro3.db` + `.mxp`) bzw. eine entpackte
/// `_rpro3.db` direkt und überführt sie in <see cref="Rpro3Data"/>.
///
/// KRITISCHE PARSING-DETAILS (Port von tools/import/compare_rpro3.py):
/// 1. DATUM: _BIRTH/_AM/_DATE/_TODAM/_ABAM sind astronomische Julianische Tageszahlen (REAL).
/// 0/None = unbekannt. date = fromordinal(round(jdn) - 1721425).
/// 2. ENCODING (gemischt!): TEXT teils UTF-8 (neuer), teils CP1252 (älter). Wir lesen jede
/// Spalte als BLOB (Bytes) und dekodieren erst strikt UTF-8, bei Fehler CP1252
/// (siehe smart_decode). Microsoft.Data.Sqlite würde TEXT sonst als UTF-8 erzwingen → Mojibake.
/// 3. ID-NAMENSRÄUME: "N"=stamm_tb, "uN"=fremd_tb, "XjY"=wurftier_tb.
/// </summary>
public sealed class Rpro3Reader
{
private static bool _cp1252Registered;
public Rpro3Reader()
{
// CP1252 ist auf .NET Core nicht ohne CodePagesEncodingProvider verfügbar.
if (!_cp1252Registered)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
_cp1252Registered = true;
}
}
/// <summary>Findet/extrahiert die `_rpro3.db` aus einem Upload-Stream (ZIP/.backup) und
/// parst sie. Wirft <see cref="Rpro3FormatException"/>, wenn keine DB gefunden wurde.
/// Gibt den temporären Arbeitsordner zurück (Caller löscht ihn).</summary>
public Rpro3Data ReadFromBackup(Stream backupStream, out string workDir)
{
workDir = Path.Combine(Path.GetTempPath(), "rpro3-import-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(workDir);
try
{
using var archive = new ZipArchive(backupStream, ZipArchiveMode.Read, leaveOpen: true);
var dbEntry = archive.Entries.FirstOrDefault(e =>
e.Name.Equals("_rpro3.db", StringComparison.OrdinalIgnoreCase))
?? archive.Entries.FirstOrDefault(e =>
e.Name.EndsWith(".db", StringComparison.OrdinalIgnoreCase));
if (dbEntry is null)
throw new Rpro3FormatException(
"In der hochgeladenen Datei wurde keine RennmausPro-Datenbank (_rpro3.db) gefunden.");
var dbPath = Path.Combine(workDir, "_rpro3.db");
dbEntry.ExtractToFile(dbPath, overwrite: true);
return ReadFromDbFile(dbPath);
}
catch (InvalidDataException ex)
{
throw new Rpro3FormatException(
"Die Datei ist kein gültiges RennmausPro-Backup (kein lesbares ZIP-Archiv).", ex);
}
}
/// <summary>Parst eine bereits entpackte `_rpro3.db` direkt (für Tests/Schnellpfad).</summary>
public Rpro3Data ReadFromDbFile(string dbPath)
{
var connectionString = new SqliteConnectionStringBuilder
{
DataSource = dbPath,
Mode = SqliteOpenMode.ReadOnly,
}.ToString();
using var conn = new SqliteConnection(connectionString);
conn.Open();
return Parse(conn);
}
// ---------- Decoding helpers (Port von smart_decode / jdn_to_date) ----------
/// <summary>RPRO3-DB ist gemischt kodiert. Erst UTF-8 strikt versuchen, sonst CP1252.</summary>
internal static string? SmartDecode(byte[]? bytes)
{
if (bytes is null || bytes.Length == 0) return bytes is null ? null : "";
try
{
return new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true)
.GetString(bytes);
}
catch (DecoderFallbackException)
{
return Encoding.GetEncoding(1252).GetString(bytes);
}
}
/// <summary>JDN (REAL) → DateOnly. 0/None/ungültig = null.</summary>
internal static DateOnly? JdnToDate(double? jdn)
{
if (jdn is null || jdn.Value <= 0) return null;
// Python: date.fromordinal(round(jdn) - 1721425). .NET-Ordinaltage zählen ab 0001-01-01
// mit DateOnly.FromDayNumber(n) wobei DayNumber 0 = 0001-01-01 (= Python-ordinal 1).
// → dayNumber = round(jdn) - 1721425 - 1.
long dayNumber = (long)Math.Round(jdn.Value) - 1721425 - 1;
if (dayNumber < 0 || dayNumber > DateOnly.MaxValue.DayNumber) return null;
return DateOnly.FromDayNumber((int)dayNumber);
}
private static Gender ParseGender(string? sex) => (sex ?? "").Trim().ToLowerInvariant() switch
{
"männlich" or "maennlich" or "m" or "male" => Gender.male,
"weiblich" or "w" or "f" or "female" => Gender.female,
_ => Gender.unknown,
};
// ---------- BLOB-aware accessors ----------
private static string? Str(SqliteDataReader r, int ord)
{
if (r.IsDBNull(ord)) return null;
// Als Bytes lesen → smart decode (UTF-8/CP1252).
using var stream = r.GetStream(ord);
using var ms = new MemoryStream();
stream.CopyTo(ms);
return SmartDecode(ms.ToArray());
}
private static double? Real(SqliteDataReader r, int ord)
{
if (r.IsDBNull(ord)) return null;
try { return r.GetDouble(ord); }
catch { return double.TryParse(Str(r, ord), NumberStyles.Any, CultureInfo.InvariantCulture, out var d) ? d : null; }
}
private static int? IntOrNull(SqliteDataReader r, int ord)
{
if (r.IsDBNull(ord)) return null;
try { return (int)r.GetInt64(ord); }
catch
{
var s = Str(r, ord);
return int.TryParse(s, out var v) ? v : null;
}
}
private static decimal? DecimalOrNull(SqliteDataReader r, int ord)
{
if (r.IsDBNull(ord)) return null;
try { return (decimal)r.GetDouble(ord); }
catch
{
var s = Str(r, ord);
return decimal.TryParse(s, NumberStyles.Any, CultureInfo.InvariantCulture, out var v) ? v : null;
}
}
// Map column name → ordinal once per query (RPRO3 column order is stable but we stay safe).
private static Func<SqliteDataReader, string, int> OrdinalLookup(SqliteDataReader r)
{
var map = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < r.FieldCount; i++) map[r.GetName(i)] = i;
return (rr, name) => map.TryGetValue(name, out var o) ? o : -1;
}
// ---------- Parse ----------
private Rpro3Data Parse(SqliteConnection conn)
{
var data = new Rpro3Data();
// herk_tb → Anzeigename + voller Kontakt
var herkName = new Dictionary<int, string>();
foreach (var (id, c) in ReadContacts(conn, "herk_tb", "herk", "_HERK_IGNORED"))
{
data.HerkContacts[c.Id.ToString()] = c;
herkName[id] = c.DisplayName;
}
foreach (var (_, c) in ReadContacts(conn, "abn_tb", "abn", "_ABN_IGNORED"))
data.AbnContacts[c.Id.ToString()] = c;
// baum_tb: master parent table (id → Mutter/Vater im Namensraum)
var baum = new Dictionary<string, (string? mid, string? pid)>();
Query(conn, "SELECT id, _MID, _PID FROM baum_tb", (r, ord) =>
{
var id = Str(r, ord(r, "id"));
if (id is not null) baum[id] = (Str(r, ord(r, "_MID")), Str(r, ord(r, "_PID")));
});
// Farben: color_tb (stamm), wurfcolor_tb (pup), fremdcolor_tb (extern)
var colorStamm = ReadColors(conn, "color_tb");
var colorPup = ReadColors(conn, "wurfcolor_tb");
var colorExt = ReadColors(conn, "fremdcolor_tb");
data.ColorStammCount = colorStamm.Count;
data.ColorExtCount = colorExt.Count;
(string farbe, string fcode) ColorFor(string rid)
{
Dictionary<string, (string, string)> src =
rid.StartsWith('u') ? colorExt : rid.Contains('j') ? colorPup : colorStamm;
return src.TryGetValue(rid, out var v) ? v : ("", "");
}
// Tod (stamm/fremd nutzen tod_tb via tid = stamm-id; fremd hat eigenes _TODAM)
var tod = new Dictionary<string, (DateOnly? am, string? warum)>();
Query(conn, "SELECT tid, _AM, _WARUM FROM tod_tb", (r, ord) =>
{
var tid = Str(r, ord(r, "tid"));
if (tid is not null) tod[tid] = (JdnToDate(Real(r, ord(r, "_AM"))), Str(r, ord(r, "_WARUM")));
});
// stamm_tb: Namen für Eltern-Auflösung
var stammName = new Dictionary<int, string?>();
var fremdName = new Dictionary<int, string?>();
var pupName = new Dictionary<string, string?>();
// stamm_tb (eigene Tiere)
Query(conn,
"SELECT id,_NAME,_SEX,_BIRTH,_HERKUNFT,_ZB,_STATUS,_FEHLER,_KASTRAT_DATE,_BECKEN FROM stamm_tb",
(r, ord) =>
{
var sid = IntOrNull(r, ord(r, "id"));
if (sid is null) return;
var rid = sid.Value.ToString();
var name = Str(r, ord(r, "_NAME"));
stammName[sid.Value] = name;
var beckenId = IntOrNull(r, ord(r, "_BECKEN"));
if (beckenId is > 0) data.StammBecken[rid] = beckenId.Value;
var (farbe, fcode) = ColorFor(rid);
baum.TryGetValue(rid, out var par);
var herkId = IntOrNull(r, ord(r, "_HERKUNFT"));
tod.TryGetValue(rid, out var death);
data.Animals.Add(new Rpro3Animal
{
Rid = rid,
Src = Rpro3Src.Stamm,
Name = name,
Gender = ParseGender(Str(r, ord(r, "_SEX"))),
Dob = JdnToDate(Real(r, ord(r, "_BIRTH"))),
Farbe = farbe,
Fcode = fcode,
Origin = herkId is not null && herkName.TryGetValue(herkId.Value, out var hn) ? hn : "",
OriginHerkId = herkId,
Zb = Str(r, ord(r, "_ZB")),
MidRaw = par.mid,
PidRaw = par.pid,
DateOfDeath = death.am,
CauseOfDeath = death.warum,
Defects = Str(r, ord(r, "_FEHLER")),
IsCastrated = JdnToDate(Real(r, ord(r, "_KASTRAT_DATE"))) is not null,
StatusCode = IntOrNull(r, ord(r, "_STATUS")),
});
});
// fremd_tb (externe Ahnen)
Query(conn,
"SELECT id,_NAME,_SEX,_BIRTH,_ZB,_HERK,_MID,_PID,_TODAM,_KASTRAT_DATE FROM fremd_tb",
(r, ord) =>
{
var fid = IntOrNull(r, ord(r, "id"));
if (fid is null) return;
var rid = "u" + fid.Value;
var name = Str(r, ord(r, "_NAME"));
fremdName[fid.Value] = name;
var (farbe, fcode) = ColorFor(rid);
var herkId = IntOrNull(r, ord(r, "_HERK"));
data.Animals.Add(new Rpro3Animal
{
Rid = rid,
Src = Rpro3Src.Fremd,
Name = name,
Gender = ParseGender(Str(r, ord(r, "_SEX"))),
Dob = JdnToDate(Real(r, ord(r, "_BIRTH"))),
Farbe = farbe,
Fcode = fcode,
Origin = herkId is not null && herkName.TryGetValue(herkId.Value, out var hn) ? hn : "",
OriginHerkId = herkId,
Zb = Str(r, ord(r, "_ZB")),
MidRaw = Str(r, ord(r, "_MID")),
PidRaw = Str(r, ord(r, "_PID")),
DateOfDeath = JdnToDate(Real(r, ord(r, "_TODAM"))),
IsCastrated = JdnToDate(Real(r, ord(r, "_KASTRAT_DATE"))) is not null,
});
});
// wurf_tb (Würfe)
Query(conn, "SELECT id,_MID,_PID,_AM,_BEZ,_BEM FROM wurf_tb", (r, ord) =>
{
var wid = IntOrNull(r, ord(r, "id"));
if (wid is null) return;
data.Litters[wid.Value] = new Rpro3Litter
{
Id = wid.Value,
Name = Str(r, ord(r, "_BEZ")),
Date = JdnToDate(Real(r, ord(r, "_AM"))),
MotherRid = Str(r, ord(r, "_MID")),
FatherRid = Str(r, ord(r, "_PID")),
Notes = Str(r, ord(r, "_BEM")),
};
});
// wurftier_tb (Welpen)
Query(conn,
"SELECT id,_WID,_NAME,_SEX,_BIRTH,_SID,_TODAM,_WARUM,_ABAM,_ABN,_PRICE,_ZB,_FEHLER FROM wurftier_tb",
(r, ord) =>
{
var id = Str(r, ord(r, "id"));
if (id is null) return;
var name = Str(r, ord(r, "_NAME"));
pupName[id] = name;
data.Pups[id] = new Rpro3Pup
{
Id = id,
WurfId = IntOrNull(r, ord(r, "_WID")) ?? 0,
Name = name,
Gender = ParseGender(Str(r, ord(r, "_SEX"))),
Dob = JdnToDate(Real(r, ord(r, "_BIRTH"))),
Sid = Str(r, ord(r, "_SID")),
DateOfDeath = JdnToDate(Real(r, ord(r, "_TODAM"))),
CauseOfDeath = Str(r, ord(r, "_WARUM")),
AbgabeDate = JdnToDate(Real(r, ord(r, "_ABAM"))),
AbnId = IntOrNull(r, ord(r, "_ABN")),
Price = DecimalOrNull(r, ord(r, "_PRICE")),
Zb = Str(r, ord(r, "_ZB")),
Defects = Str(r, ord(r, "_FEHLER")),
};
});
// Eltern-Namen auflösen (für Report / Provenance)
string? NameFor(string? rid)
{
if (string.IsNullOrWhiteSpace(rid) || rid is "n" or "NULL") return null;
if (rid.StartsWith('u'))
return int.TryParse(rid[1..], out var fid) && fremdName.TryGetValue(fid, out var n) ? n : null;
if (rid.Contains('j'))
return pupName.TryGetValue(rid, out var n) ? n : null;
return int.TryParse(rid, out var sid) && stammName.TryGetValue(sid, out var sn) ? sn : null;
}
data.ResolveName = NameFor;
// Gewichte: waage_tb (_TID = stamm-id) + jungwaage_tb (_TID = wurftier-id "XjY" oder via _WID)
Query(conn, "SELECT _TID,_GRAMM,_DATE,_BEM FROM waage_tb", (r, ord) =>
{
var tid = Str(r, ord(r, "_TID"));
if (tid is null) return;
data.Weights.Add(new Rpro3Weight
{
Tid = tid,
Grams = (int)Math.Round(Real(r, ord(r, "_GRAMM")) ?? 0),
Date = JdnToDate(Real(r, ord(r, "_DATE"))),
Notes = Str(r, ord(r, "_BEM")),
});
});
Query(conn, "SELECT _TID,_WID,_GRAMM,_DATE,_BEM FROM jungwaage_tb", (r, ord) =>
{
// _TID ist hier i. d. R. die laufende Pup-Nr im Wurf; _WID der Wurf → "WIDjTID".
var tidRaw = Str(r, ord(r, "_TID"));
var widRaw = IntOrNull(r, ord(r, "_WID"));
string? tid = tidRaw is not null && tidRaw.Contains('j') ? tidRaw
: widRaw is not null && tidRaw is not null ? $"{widRaw}j{tidRaw}" : null;
if (tid is null) return;
data.Weights.Add(new Rpro3Weight
{
Tid = tid,
Grams = (int)Math.Round(Real(r, ord(r, "_GRAMM")) ?? 0),
Date = JdnToDate(Real(r, ord(r, "_DATE"))),
Notes = Str(r, ord(r, "_BEM")),
});
});
// Krankheiten: krank_tb (_TID = stamm-id)
Query(conn, "SELECT _TID,_DATE,_BEM,_MED FROM krank_tb", (r, ord) =>
{
var tid = Str(r, ord(r, "_TID"));
if (tid is null) return;
data.Health.Add(new Rpro3Health
{
Tid = tid,
Date = JdnToDate(Real(r, ord(r, "_DATE"))),
Description = Str(r, ord(r, "_BEM")),
Medication = Str(r, ord(r, "_MED")),
});
});
// Tagebuch: diary_tb (_TID = stamm-id)
Query(conn, "SELECT _TID,_BEZ,_DATE,_DESC FROM diary_tb", (r, ord) =>
{
var tid = Str(r, ord(r, "_TID"));
if (tid is null) return;
data.Diary.Add(new Rpro3Diary
{
Tid = tid,
Title = Str(r, ord(r, "_BEZ")),
Date = JdnToDate(Real(r, ord(r, "_DATE"))),
Description = Str(r, ord(r, "_DESC")),
});
});
// Fotos: photo_tb (id = stamm-id, _P1/_P2/_P3 = Bilddateinamen)
Query(conn, "SELECT id,_P1,_P2,_P3 FROM photo_tb", (r, ord) =>
{
var pid = IntOrNull(r, ord(r, "id"));
if (pid is null) return;
var set = new Rpro3PhotoSet { Tid = pid.Value.ToString() };
foreach (var col in new[] { "_P1", "_P2", "_P3" })
{
var fn = Str(r, ord(r, col));
if (!string.IsNullOrWhiteSpace(fn) && fn != "---")
set.FileNames.Add(Path.GetFileName(fn.Replace('\\', '/')));
}
if (set.FileNames.Count > 0) data.Photos[set.Tid] = set;
});
ParseFeatureTables(conn, data);
return data;
}
/// <summary>Parst die Feature-Tabellen (becken/herktier/abgeben/abstat/getback/nachfrage/ausz).
/// Jede Tabelle ist optional — fehlt sie in einem älteren Backup, wird sie still übersprungen.</summary>
private void ParseFeatureTables(SqliteConnection conn, Rpro3Data data)
{
// becken_tb: Gehege.
QueryOptional(conn, "SELECT id,_BEZ,_SIZE,_MENGE,_CLEANED,_CYCLUS FROM becken_tb", (r, ord) =>
{
var id = IntOrNull(r, ord(r, "id"));
if (id is null) return;
data.Becken.Add(new Rpro3Becken
{
Id = id.Value,
Name = Str(r, ord(r, "_BEZ")),
Size = Str(r, ord(r, "_SIZE")),
Capacity = IntOrNull(r, ord(r, "_MENGE")),
LastCleaned = JdnToDate(Real(r, ord(r, "_CLEANED"))),
CycleDays = IntOrNull(r, ord(r, "_CYCLUS")),
});
});
// herktier_tb: Erwerb.
QueryOptional(conn, "SELECT id,_TID,_DATE,_PRICE,_BEM FROM herktier_tb", (r, ord) =>
{
var id = IntOrNull(r, ord(r, "id"));
if (id is null) return;
data.Acquisitions.Add(new Rpro3Acquisition
{
Id = id.Value,
Tid = Str(r, ord(r, "_TID")),
Date = JdnToDate(Real(r, ord(r, "_DATE"))),
Price = DecimalOrNull(r, ord(r, "_PRICE")),
Note = Str(r, ord(r, "_BEM")),
});
});
// abgeben_tb: Reservierung/Vormerkung.
QueryOptional(conn, "SELECT tid,_RES,_TERMIN,_ABN,_BEM FROM abgeben_tb", (r, ord) =>
{
var tid = Str(r, ord(r, "tid"));
if (string.IsNullOrWhiteSpace(tid)) return;
data.Abgeben.Add(new Rpro3Abgeben
{
Tid = tid,
Reserved = (IntOrNull(r, ord(r, "_RES")) ?? 0) != 0,
Appointment = JdnToDate(Real(r, ord(r, "_TERMIN"))),
AbnId = IntOrNull(r, ord(r, "_ABN")),
Note = Str(r, ord(r, "_BEM")),
});
});
// abstat_tb: Abgabe-Abschluss.
QueryOptional(conn, "SELECT tid,_IDABN,_AM,_PRICE,_BEM FROM abstat_tb", (r, ord) =>
{
var tid = Str(r, ord(r, "tid"));
if (string.IsNullOrWhiteSpace(tid)) return;
data.Abstat.Add(new Rpro3Abstat
{
Tid = tid,
AbnId = IntOrNull(r, ord(r, "_IDABN")),
HandedOver = JdnToDate(Real(r, ord(r, "_AM"))),
Price = DecimalOrNull(r, ord(r, "_PRICE")),
Note = Str(r, ord(r, "_BEM")),
});
});
// getback_tb: Rücknahme.
QueryOptional(conn, "SELECT id,_TID,_ZAM,_ZPREIS,_AM,_PREIS,_ABN,_BEM FROM getback_tb", (r, ord) =>
{
var id = IntOrNull(r, ord(r, "id"));
if (id is null) return;
data.Getback.Add(new Rpro3Getback
{
Id = id.Value,
Tid = Str(r, ord(r, "_TID")),
ReturnDate = JdnToDate(Real(r, ord(r, "_ZAM"))),
ReturnPrice = DecimalOrNull(r, ord(r, "_ZPREIS")),
OriginalSaleDate = JdnToDate(Real(r, ord(r, "_AM"))),
OriginalPrice = DecimalOrNull(r, ord(r, "_PREIS")),
AbnId = IntOrNull(r, ord(r, "_ABN")),
Note = Str(r, ord(r, "_BEM")),
});
});
// nachfrage_tb: Warteliste. _VOM ist das Anfragedatum (_DATE ist hier i. d. R. 0).
// Hat keine eigene _BEM-Spalte; _CODE (z. B. "egal") dient als Zusatznotiz.
QueryOptional(conn, "SELECT id,_COLOR,_SEX,_ABN,_VOM,_DATE,_STATUS,_CODE FROM nachfrage_tb", (r, ord) =>
{
var id = IntOrNull(r, ord(r, "id"));
if (id is null) return;
var code = Str(r, ord(r, "_CODE"));
data.Nachfrage.Add(new Rpro3Nachfrage
{
Id = id.Value,
WishColor = Str(r, ord(r, "_COLOR")),
WishGender = ParseGender(Str(r, ord(r, "_SEX"))),
AbnId = IntOrNull(r, ord(r, "_ABN")),
RequestedAt = JdnToDate(Real(r, ord(r, "_VOM"))) ?? JdnToDate(Real(r, ord(r, "_DATE"))),
Status = Str(r, ord(r, "_STATUS")),
Note = string.IsNullOrWhiteSpace(code) || code == "egal" ? null : code,
});
});
// ausz_tb: Ausstellungsergebnisse (in vielen Backups leer — robust gegen 0 Zeilen).
QueryOptional(conn, "SELECT id,_TID,_VERANSTALTUNG,_DATE,_ORT,_PLATZ,_AUSZ,_JUROR,_BEM FROM ausz_tb", (r, ord) =>
{
var id = IntOrNull(r, ord(r, "id"));
if (id is null) return;
data.Ausstellungen.Add(new Rpro3Ausstellung
{
Id = id.Value,
Tid = Str(r, ord(r, "_TID")),
EventName = Str(r, ord(r, "_VERANSTALTUNG")),
Date = JdnToDate(Real(r, ord(r, "_DATE"))),
Place = Str(r, ord(r, "_ORT")),
Placement = Str(r, ord(r, "_PLATZ")),
Award = Str(r, ord(r, "_AUSZ")),
Juror = Str(r, ord(r, "_JUROR")),
Note = Str(r, ord(r, "_BEM")),
});
});
}
private static Dictionary<string, (string farbe, string fcode)> ReadColors(SqliteConnection conn, string table)
{
var dict = new Dictionary<string, (string, string)>();
Query(conn, $"SELECT id,_FARBE,_FCODE FROM {table}", (r, ord) =>
{
var id = Str(r, ord(r, "id"));
if (id is not null)
dict[id] = (Str(r, ord(r, "_FARBE")) ?? "", Str(r, ord(r, "_FCODE")) ?? "");
});
return dict;
}
private static IEnumerable<(int id, Rpro3Contact c)> ReadContacts(
SqliteConnection conn, string table, string ns, string _)
{
var list = new List<(int, Rpro3Contact)>();
Query(conn,
$"SELECT id,_BEZ,_ANREDE,_VNAME,_NNAME,_CLAN,_STR,_ORT,_PLZ,_TELP,_TELD,_MAIL,_HTTP,_MEMO,_BEM FROM {table}",
(r, ord) =>
{
var id = IntOrNull(r, ord(r, "id"));
if (id is null) return;
list.Add((id.Value, new Rpro3Contact
{
Id = id.Value,
Namespace = ns,
Bez = Str(r, ord(r, "_BEZ")),
Anrede = Str(r, ord(r, "_ANREDE")),
Vname = Str(r, ord(r, "_VNAME")),
Nname = Str(r, ord(r, "_NNAME")),
Clan = Str(r, ord(r, "_CLAN")),
Str = Str(r, ord(r, "_STR")),
Ort = Str(r, ord(r, "_ORT")),
Plz = Str(r, ord(r, "_PLZ")),
Telp = Str(r, ord(r, "_TELP")),
Teld = Str(r, ord(r, "_TELD")),
Mail = Str(r, ord(r, "_MAIL")),
Http = Str(r, ord(r, "_HTTP")),
Memo = Str(r, ord(r, "_MEMO")),
Bem = Str(r, ord(r, "_BEM")),
}));
});
return list;
}
private static void Query(
SqliteConnection conn, string sql,
Action<SqliteDataReader, Func<SqliteDataReader, string, int>> onRow)
{
using var cmd = conn.CreateCommand();
cmd.CommandText = sql;
using var r = cmd.ExecuteReader();
Func<SqliteDataReader, string, int>? ord = null;
while (r.Read())
{
ord ??= OrdinalLookup(r);
onRow(r, ord);
}
}
/// <summary>Wie <see cref="Query"/>, ignoriert aber fehlende Tabellen/Spalten
/// (ältere Backups ohne die Feature-Tabellen). SQLite-Fehler werden geschluckt.</summary>
private static void QueryOptional(
SqliteConnection conn, string sql,
Action<SqliteDataReader, Func<SqliteDataReader, string, int>> onRow)
{
try { Query(conn, sql, onRow); }
catch (SqliteException) { /* Tabelle/Spalte fehlt in diesem Backup → überspringen */ }
}
}
public sealed class Rpro3FormatException : Exception
{
public Rpro3FormatException(string message, Exception? inner = null) : base(message, inner) { }
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,598 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
#pragma warning disable CA1814 // Prefer jagged arrays over multidimensional
namespace GerbilManagerWebAPI.Migrations
{
/// <inheritdoc />
public partial class ReseedColorVarietiesAR5 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000016"),
column: "Name",
value: "Dilute Gold");
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000017"),
column: "Name",
value: "Dilute Platin");
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000029"),
column: "Name",
value: "Dilute Agouti");
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000030"),
column: "Name",
value: "Dilute Silberagouti");
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000031"),
column: "Name",
value: "Dilute Kohlfuchs");
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000032"),
column: "Name",
value: "Dilute Anthrazit");
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000033"),
column: "SortOrder",
value: 36);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000034"),
column: "SortOrder",
value: 37);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000035"),
column: "SortOrder",
value: 38);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000036"),
column: "SortOrder",
value: 39);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000037"),
column: "SortOrder",
value: 40);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000038"),
column: "SortOrder",
value: 41);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000039"),
column: "SortOrder",
value: 42);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000040"),
column: "SortOrder",
value: 43);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000041"),
column: "SortOrder",
value: 44);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000042"),
column: "SortOrder",
value: 45);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000043"),
column: "SortOrder",
value: 46);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000044"),
column: "SortOrder",
value: 47);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000045"),
column: "SortOrder",
value: 48);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000046"),
column: "SortOrder",
value: 49);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000047"),
column: "SortOrder",
value: 50);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000048"),
column: "SortOrder",
value: 51);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000049"),
columns: new[] { "Name", "SortOrder" },
values: new object[] { "Dilute Topas", 52 });
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000050"),
columns: new[] { "Name", "SortOrder" },
values: new object[] { "Dilute Blaufuchs", 53 });
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000051"),
column: "SortOrder",
value: 54);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000052"),
column: "SortOrder",
value: 55);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000053"),
column: "SortOrder",
value: 56);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000054"),
column: "SortOrder",
value: 57);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000055"),
column: "SortOrder",
value: 59);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000056"),
column: "SortOrder",
value: 61);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000057"),
column: "SortOrder",
value: 63);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000058"),
column: "SortOrder",
value: 65);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000059"),
column: "SortOrder",
value: 66);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000060"),
column: "SortOrder",
value: 67);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000061"),
column: "SortOrder",
value: 68);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000062"),
column: "SortOrder",
value: 58);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000063"),
column: "SortOrder",
value: 60);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000064"),
column: "SortOrder",
value: 62);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000066"),
column: "SortOrder",
value: 69);
migrationBuilder.InsertData(
table: "ColorVarieties",
columns: new[] { "Id", "CanonicalGenotype", "Name", "SortOrder" },
values: new object[,]
{
{ new Guid("00000000-0000-0000-0000-000000000067"), "AA CC dd ee GG PP spsp rere", "Dilute Algierfuchs", 32 },
{ new Guid("00000000-0000-0000-0000-000000000068"), "AA CC dd ee GG pp spsp rere", "Dilute Goldfuchs", 33 },
{ new Guid("00000000-0000-0000-0000-000000000069"), "aa CC dd ee GG pp spsp rere", "Dilute Rotfuchs", 34 },
{ new Guid("00000000-0000-0000-0000-000000000070"), "AA CC dd ee gg PP spsp rere", "Dilute Polarfuchs", 35 }
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000067"));
migrationBuilder.DeleteData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000068"));
migrationBuilder.DeleteData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000069"));
migrationBuilder.DeleteData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000070"));
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000016"),
column: "Name",
value: "dd Gold");
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000017"),
column: "Name",
value: "dd Platin");
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000029"),
column: "Name",
value: "Agouti dd");
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000030"),
column: "Name",
value: "Silberagouti dd");
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000031"),
column: "Name",
value: "Kohlfuchs dd");
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000032"),
column: "Name",
value: "Anthrazit dd");
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000033"),
column: "SortOrder",
value: 32);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000034"),
column: "SortOrder",
value: 33);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000035"),
column: "SortOrder",
value: 34);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000036"),
column: "SortOrder",
value: 35);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000037"),
column: "SortOrder",
value: 36);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000038"),
column: "SortOrder",
value: 37);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000039"),
column: "SortOrder",
value: 38);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000040"),
column: "SortOrder",
value: 39);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000041"),
column: "SortOrder",
value: 40);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000042"),
column: "SortOrder",
value: 41);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000043"),
column: "SortOrder",
value: 42);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000044"),
column: "SortOrder",
value: 43);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000045"),
column: "SortOrder",
value: 44);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000046"),
column: "SortOrder",
value: 45);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000047"),
column: "SortOrder",
value: 46);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000048"),
column: "SortOrder",
value: 47);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000049"),
columns: new[] { "Name", "SortOrder" },
values: new object[] { "Topas dd", 48 });
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000050"),
columns: new[] { "Name", "SortOrder" },
values: new object[] { "Blaufuchs dd", 49 });
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000051"),
column: "SortOrder",
value: 50);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000052"),
column: "SortOrder",
value: 51);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000053"),
column: "SortOrder",
value: 52);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000054"),
column: "SortOrder",
value: 53);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000055"),
column: "SortOrder",
value: 54);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000056"),
column: "SortOrder",
value: 55);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000057"),
column: "SortOrder",
value: 56);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000058"),
column: "SortOrder",
value: 57);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000059"),
column: "SortOrder",
value: 58);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000060"),
column: "SortOrder",
value: 59);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000061"),
column: "SortOrder",
value: 60);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000062"),
column: "SortOrder",
value: 61);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000063"),
column: "SortOrder",
value: 62);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000064"),
column: "SortOrder",
value: 63);
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000066"),
column: "SortOrder",
value: 65);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,33 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace GerbilManagerWebAPI.Migrations
{
/// <inheritdoc />
public partial class RenameREW : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000001"),
column: "Name",
value: "REW");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.UpdateData(
table: "ColorVarieties",
keyColumn: "Id",
keyValue: new Guid("00000000-0000-0000-0000-000000000001"),
column: "Name",
value: "Pink Eyed White (PEW)");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,40 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace GerbilManagerWebAPI.Migrations
{
/// <inheritdoc />
public partial class StatusModel : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
// 1) Rename string value 'Active' → 'Breeding'.
migrationBuilder.Sql(@"UPDATE ""Gerbils"" SET ""Status"" = 'Breeding' WHERE ""Status"" = 'Active';");
// 2) DateOfDeath set → Deceased (always takes precedence).
migrationBuilder.Sql(@"UPDATE ""Gerbils"" SET ""Status"" = 'Deceased' WHERE ""DateOfDeath"" IS NOT NULL;");
// 3) ReceiverContactId OR SaleContractAnimal → GivenAway (if not already Deceased).
migrationBuilder.Sql(@"
UPDATE ""Gerbils"" SET ""Status"" = 'GivenAway'
WHERE ""Status"" != 'Deceased'
AND (""ReceiverContactId"" IS NOT NULL
OR EXISTS (SELECT 1 FROM ""SaleContractAnimal"" WHERE ""GerbilId"" = ""Gerbils"".""Id""));");
// 4) Age > 7 years (presumed dead) → Deceased, but NOT overriding GivenAway.
migrationBuilder.Sql(@"
UPDATE ""Gerbils"" SET ""Status"" = 'Deceased'
WHERE ""Status"" NOT IN ('Deceased', 'GivenAway')
AND ""DateOfBirth"" IS NOT NULL
AND ""DateOfBirth"" < (CURRENT_DATE - INTERVAL '7 years');");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(@"UPDATE ""Gerbils"" SET ""Status"" = 'Active' WHERE ""Status"" = 'Breeding';");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,28 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace GerbilManagerWebAPI.Migrations
{
/// <inheritdoc />
public partial class AddLitterMortality : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "DeathsWithin8Weeks",
table: "Litters",
type: "integer",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "DeathsWithin8Weeks",
table: "Litters");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,28 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace GerbilManagerWebAPI.Migrations
{
/// <inheritdoc />
public partial class AddSpottingType : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "SpottingType",
table: "Gerbils",
type: "text",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "SpottingType",
table: "Gerbils");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,40 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace GerbilManagerWebAPI.Migrations
{
/// <inheritdoc />
public partial class AddContactRoles : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsBreeder",
table: "Contacts",
type: "boolean",
nullable: false,
defaultValue: false);
migrationBuilder.AddColumn<bool>(
name: "IsReceiver",
table: "Contacts",
type: "boolean",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsBreeder",
table: "Contacts");
migrationBuilder.DropColumn(
name: "IsReceiver",
table: "Contacts");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace GerbilManagerWebAPI.Migrations
{
/// <inheritdoc />
public partial class AddIsCastrated : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsCastrated",
table: "Gerbils",
type: "boolean",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsCastrated",
table: "Gerbils");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,47 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace GerbilManagerWebAPI.Migrations
{
/// <inheritdoc />
public partial class AddBreedingNameSuffix : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "NameSuffix",
table: "Contacts",
type: "text",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "NameSuffix",
table: "BreederSettings",
type: "text",
nullable: false,
defaultValue: "");
migrationBuilder.UpdateData(
table: "BreederSettings",
keyColumn: "Id",
keyValue: new Guid("11111111-1111-1111-1111-000000000001"),
column: "NameSuffix",
value: "");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "NameSuffix",
table: "Contacts");
migrationBuilder.DropColumn(
name: "NameSuffix",
table: "BreederSettings");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,49 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace GerbilManagerWebAPI.Migrations
{
/// <inheritdoc />
public partial class AddEnclosurePhotos : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "EnclosurePhotos",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
EnclosureId = table.Column<Guid>(type: "uuid", nullable: false),
FileName = table.Column<string>(type: "text", nullable: false),
Caption = table.Column<string>(type: "text", nullable: true),
SortOrder = table.Column<int>(type: "integer", nullable: false),
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_EnclosurePhotos", x => x.Id);
table.ForeignKey(
name: "FK_EnclosurePhotos_Enclosures_EnclosureId",
column: x => x.EnclosureId,
principalTable: "Enclosures",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_EnclosurePhotos_EnclosureId",
table: "EnclosurePhotos",
column: "EnclosureId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "EnclosurePhotos");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,37 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace GerbilManagerWebAPI.Migrations
{
/// <inheritdoc />
public partial class MakeLitterDateNullable : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<DateOnly>(
name: "Date",
table: "Litters",
type: "date",
nullable: true,
oldClrType: typeof(DateOnly),
oldType: "date");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<DateOnly>(
name: "Date",
table: "Litters",
type: "date",
nullable: false,
defaultValue: new DateOnly(1, 1, 1),
oldClrType: typeof(DateOnly),
oldType: "date",
oldNullable: true);
}
}
}

Some files were not shown because too many files have changed in this diff Show More