Compare commits
72 Commits
e367657254
...
feat/rennm
| Author | SHA1 | Date | |
|---|---|---|---|
| 5732398e60 | |||
| 0185446bfe | |||
| 04d189bd2f | |||
| 7d8166c555 | |||
| d5c7b77e7e | |||
| bff25b4683 | |||
| aa1d22cec7 | |||
| f7e97ad7a2 | |||
| 7d552d33cd | |||
| 4d7333b714 | |||
| 62b07597f5 | |||
| 5ce35af813 | |||
| 23b6dad303 | |||
| e9eef5cce6 | |||
| 299c038449 | |||
| ecd7ad2658 | |||
| 6de56ab112 | |||
| ddc343a96b | |||
| a26bc4d75e | |||
| d4dfe6c3ac | |||
| 40f3ce250d | |||
| ffbbc0dfad | |||
| 05cb1af39e | |||
| 78f87f0d44 | |||
| 7f6855be62 | |||
| 29e9c4cd64 | |||
| 8eddb83c99 | |||
| 1a5f3218fb | |||
| 2d54cb901f | |||
| 03f8e4de90 | |||
| 70803efa1f | |||
| 25af10a736 | |||
| ade40eef5e | |||
| c1b215d06f | |||
| 7525970ffc | |||
| bfc90f8581 | |||
| c45bcc99f0 | |||
| c4a661b5b6 | |||
| 30b2fff775 | |||
| c0ecf2022d | |||
| 2198c33898 | |||
| 04971bf3bb | |||
| 08500757d7 | |||
| 05ef3d9567 | |||
| 7c12a65938 | |||
| 5361a292f1 | |||
| cb5acd2005 | |||
| bda5479b93 | |||
| d5c155953b | |||
| 36795bd974 | |||
| ae60b47ad3 | |||
| adb9e93cdb | |||
| 3aa9ac9811 | |||
| b72e0a9d9a | |||
| 12d85d9796 | |||
| 76bdde4649 | |||
| 025bca1840 | |||
| 58dc811574 | |||
| 367304940f | |||
| 7e1acdb5e4 | |||
| 5ee6a4edf6 | |||
| ea527c7ec6 | |||
| c80adcf060 | |||
| a42966ad8e | |||
| 886a6e3aae | |||
| 88e00b3718 | |||
| 3214855989 | |||
| 76e635a122 | |||
| 00886b1c6e | |||
| d5e8946d7d | |||
| c452b69dd6 | |||
| f20a42a94b |
@@ -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
|
||||
|
||||
@@ -25,7 +25,7 @@ on:
|
||||
- main
|
||||
|
||||
env:
|
||||
REGISTRY: truenas:13000
|
||||
REGISTRY: git.rismer.de
|
||||
REGISTRY_OWNER: gulum
|
||||
DOTNET_VERSION: "10.0.x"
|
||||
NODE_VERSION: "22"
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -137,3 +137,6 @@ 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/
|
||||
|
||||
103
GerbilManager.Tests/CmsPublishTests.cs
Normal file
103
GerbilManager.Tests/CmsPublishTests.cs
Normal 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); }
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -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);
|
||||
|
||||
83
GerbilManager.Tests/GerbilProfilePhotoTests.cs
Normal file
83
GerbilManager.Tests/GerbilProfilePhotoTests.cs
Normal 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"));
|
||||
}
|
||||
}
|
||||
58
GerbilManager.Tests/GerbilSearchTests.cs
Normal file
58
GerbilManager.Tests/GerbilSearchTests.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
122
GerbilManager.Tests/GerbilStatusTests.cs
Normal file
122
GerbilManager.Tests/GerbilStatusTests.cs
Normal 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 > 7y, no death, not abgegeben → Deceased (presumed)
|
||||
[Fact]
|
||||
public void OlderThan7y_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 7 years old is NOT presumed dead (threshold is strictly >)
|
||||
[Fact]
|
||||
public void ExactlyMaxAge_is_not_Deceased()
|
||||
{
|
||||
var dob = Today.AddYears(-GerbilStatusService.MaxAgeYears); // exactly 7y today
|
||||
var status = GerbilStatusService.Derive(
|
||||
GerbilStatus.Breeding, dob, dateOfDeath: null, isAbgegeben: false, Today);
|
||||
// today >= dob.AddYears(7) → 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 > 7y but Abgegeben → stays GivenAway (not Deceased)
|
||||
[Fact]
|
||||
public void OlderThan7y_but_Abgegeben_stays_GivenAway()
|
||||
{
|
||||
var dob = Today.AddYears(-8);
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,14 @@ using GerbilManagerWebAPI.Import;
|
||||
using GerbilManagerWebAPI.Models;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Storage;
|
||||
|
||||
namespace GerbilManager.Tests
|
||||
{
|
||||
/// <summary>
|
||||
/// FEAT-8d-CREATE: docx importer CREATE path tests.
|
||||
/// Uses SQLite (not InMemory) so FK constraints are enforced.
|
||||
/// 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
|
||||
{
|
||||
@@ -31,7 +33,7 @@ namespace GerbilManager.Tests
|
||||
conn.Open();
|
||||
var opts = new DbContextOptionsBuilder<ApplicationContext>().UseSqlite(conn).Options;
|
||||
var db = new ApplicationContext(opts);
|
||||
db.Database.EnsureCreated();
|
||||
db.Database.EnsureCreated(); // schema WITH unique index on ExternalRef
|
||||
return (db, conn);
|
||||
}
|
||||
|
||||
@@ -52,13 +54,12 @@ namespace GerbilManager.Tests
|
||||
await using (conn)
|
||||
await using (db)
|
||||
{
|
||||
// Litter in DB with PairingCode matching the docx WS-code
|
||||
// Litter in DB — date-only lookup (±5 days, exactly one candidate)
|
||||
var litter = new Litter
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Testwurf WS1",
|
||||
Name = "Testwurf",
|
||||
Date = new DateOnly(2023, 5, 1),
|
||||
PairingCode = "WS1"
|
||||
};
|
||||
db.Litters.Add(litter);
|
||||
await db.SaveChangesAsync();
|
||||
@@ -66,7 +67,7 @@ namespace GerbilManager.Tests
|
||||
WriteLitters(Array.Empty<object>());
|
||||
WriteAnimals(new[]
|
||||
{
|
||||
new { wsCode = "WS1", litterDob = "01.05.2023", name = "Pepper", gender = "female",
|
||||
new { wsCode = "4/4", litterDob = "01.05.2023", name = "Pepper", gender = "female",
|
||||
owner = "Max Mustermann", abgabeDate = "01.07.2023",
|
||||
deathDate = "", deathCause = "", farbschlag = "" }
|
||||
});
|
||||
@@ -75,8 +76,8 @@ namespace GerbilManager.Tests
|
||||
|
||||
Assert.False(report.Executed);
|
||||
Assert.Equal(1, report.Created);
|
||||
Assert.Equal(1, report.LitterLinked);
|
||||
Assert.Equal(1, report.GoHomeFilled); // new animal will have GoHomeDate set
|
||||
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
|
||||
}
|
||||
@@ -94,9 +95,8 @@ namespace GerbilManager.Tests
|
||||
var litter = new Litter
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Testwurf WS1",
|
||||
Name = "Testwurf",
|
||||
Date = new DateOnly(2023, 5, 1),
|
||||
PairingCode = "WS1"
|
||||
};
|
||||
db.Litters.Add(litter);
|
||||
await db.SaveChangesAsync();
|
||||
@@ -104,7 +104,7 @@ namespace GerbilManager.Tests
|
||||
WriteLitters(Array.Empty<object>());
|
||||
WriteAnimals(new[]
|
||||
{
|
||||
new { wsCode = "WS1", litterDob = "01.05.2023", name = "Pepper", gender = "female",
|
||||
new { wsCode = "4/4", litterDob = "01.05.2023", name = "Pepper", gender = "female",
|
||||
owner = "Max Mustermann", abgabeDate = "01.07.2023",
|
||||
deathDate = "", deathCause = "", farbschlag = "" }
|
||||
});
|
||||
@@ -120,7 +120,7 @@ namespace GerbilManager.Tests
|
||||
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);
|
||||
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);
|
||||
@@ -145,7 +145,7 @@ namespace GerbilManager.Tests
|
||||
WriteLitters(Array.Empty<object>());
|
||||
WriteAnimals(new[]
|
||||
{
|
||||
new { wsCode = "WS2", litterDob = "15.03.2023", name = "Flash", gender = "male",
|
||||
new { wsCode = "2/3", litterDob = "15.03.2023", name = "Flash", gender = "male",
|
||||
owner = "", abgabeDate = "01.05.2023",
|
||||
deathDate = "", deathCause = "", farbschlag = "" }
|
||||
});
|
||||
@@ -213,7 +213,7 @@ namespace GerbilManager.Tests
|
||||
WriteLitters(Array.Empty<object>());
|
||||
WriteAnimals(new[]
|
||||
{
|
||||
new { wsCode = "WS3", litterDob = "01.01.2022", name = "Ghost", gender = "male",
|
||||
new { wsCode = "1/5", litterDob = "01.01.2022", name = "Ghost", gender = "male",
|
||||
owner = "", abgabeDate = "",
|
||||
deathDate = "15.06.2022", deathCause = "Tumor", farbschlag = "" }
|
||||
});
|
||||
@@ -226,5 +226,118 @@ namespace GerbilManager.Tests
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
181
GerbilManager.Tests/IngestResolvedServiceTests.cs
Normal file
181
GerbilManager.Tests/IngestResolvedServiceTests.cs
Normal file
@@ -0,0 +1,181 @@
|
||||
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;
|
||||
|
||||
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();
|
||||
|
||||
var data = new
|
||||
{
|
||||
Contacts = new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
Id = contactId,
|
||||
Name = "Test Breeder",
|
||||
ZuchtName = "Test Zucht",
|
||||
City = "Test City",
|
||||
Email = "test@example.com",
|
||||
Homepage = "",
|
||||
Phone = "",
|
||||
Address = ""
|
||||
}
|
||||
},
|
||||
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"
|
||||
}
|
||||
},
|
||||
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
|
||||
},
|
||||
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
|
||||
}
|
||||
},
|
||||
GerbilPhotos = new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
Id = photoId,
|
||||
GerbilId = fatherId,
|
||||
FileName = "photo1.jpg",
|
||||
SortOrder = 0
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
88
GerbilManager.Tests/LitterMortalityTests.cs
Normal file
88
GerbilManager.Tests/LitterMortalityTests.cs
Normal 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"));
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -91,7 +91,7 @@ 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"));
|
||||
@@ -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") ?? "");
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -291,7 +291,7 @@ public class ApplicationContext : DbContext
|
||||
(string Name, string Genotype, int SortOrder)[] catalog =
|
||||
{
|
||||
// --- C-locus white / partial albino (IDs 1-3) ---
|
||||
("Pink Eyed White (PEW)", "AA chch DD EE GG pp spsp rere", 0),
|
||||
("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) ---
|
||||
|
||||
16
GerbilManagerWebAPI/Cms/PublicSiteOptions.cs
Normal file
16
GerbilManagerWebAPI/Cms/PublicSiteOptions.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
@@ -29,13 +29,15 @@ namespace GerbilManagerWebAPI.Dtos
|
||||
List<string> CharacterTraits,
|
||||
string? CharacterNote,
|
||||
bool? IsDeaf,
|
||||
bool IsResident);
|
||||
bool IsResident,
|
||||
string? ProfilePhotoUrl);
|
||||
|
||||
public record LitterDto(
|
||||
Guid Id,
|
||||
string Name,
|
||||
DateOnly Date,
|
||||
int? TotalBorn,
|
||||
int? DeathsWithin8Weeks,
|
||||
Guid? FatherId,
|
||||
Guid? MotherId,
|
||||
DateOnly? ExpectedGoHomeDate,
|
||||
@@ -85,6 +87,7 @@ namespace GerbilManagerWebAPI.Dtos
|
||||
string Name,
|
||||
DateOnly Date,
|
||||
int? TotalBorn,
|
||||
int? DeathsWithin8Weeks,
|
||||
Guid? FatherId,
|
||||
Guid? MotherId,
|
||||
DateOnly? ExpectedGoHomeDate,
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -104,11 +105,12 @@ namespace GerbilManagerWebAPI.Endpoints
|
||||
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
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
using GerbilManagerWebAPI.Common;
|
||||
using GerbilManagerWebAPI.Dtos;
|
||||
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 +18,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 +45,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
|
||||
@@ -86,7 +108,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;
|
||||
@@ -105,12 +128,13 @@ namespace GerbilManagerWebAPI.Endpoints
|
||||
g.CharacterNote = i.CharacterNote ?? g.CharacterNote;
|
||||
g.IsDeaf = i.IsDeaf ?? g.IsDeaf;
|
||||
g.IsResident = i.IsResident ?? (isCreate ? true : g.IsResident);
|
||||
GerbilStatusService.Apply(g, DateOnly.FromDateTime(DateTime.UtcNow));
|
||||
}
|
||||
|
||||
internal static GerbilDto ToDto(Gerbil g) => new(
|
||||
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.CharacterTraits, g.CharacterNote, g.IsDeaf, g.IsResident, profilePhotoUrl);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,13 @@ 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);
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,10 +23,12 @@ 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 };
|
||||
Apply(l, input);
|
||||
@@ -35,12 +37,14 @@ namespace GerbilManagerWebAPI.Endpoints
|
||||
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,25 @@ namespace GerbilManagerWebAPI.Endpoints
|
||||
private static void Apply(Litter l, LitterInput i)
|
||||
{
|
||||
l.TotalBorn = i.TotalBorn;
|
||||
l.DeathsWithin8Weeks = i.DeathsWithin8Weeks;
|
||||
l.FatherId = i.FatherId;
|
||||
l.MotherId = i.MotherId;
|
||||
l.ExpectedGoHomeDate = i.ExpectedGoHomeDate;
|
||||
l.Notes = i.Notes;
|
||||
}
|
||||
|
||||
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.FatherId, l.MotherId, l.ExpectedGoHomeDate, l.Notes);
|
||||
}
|
||||
|
||||
/// <summary>400 body for a father×mother gender mismatch; frontend localises by Code.</summary>
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Text.Json;
|
||||
using GerbilManagerWebAPI.Models;
|
||||
using GerbilManagerWebAPI.Services;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace GerbilManagerWebAPI.Import
|
||||
@@ -16,11 +17,16 @@ namespace GerbilManagerWebAPI.Import
|
||||
///
|
||||
/// Created animals: Status=GivenAway (or Deceased), IsResident=false,
|
||||
/// OriginBreeder='Zucht der Kleinen Chaoten', ImportSource="docx",
|
||||
/// ExternalRef = stable "docx-{ws}-{normname}-{litterDob}" key (idempotent).
|
||||
/// 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. Each run resolves whatever is still null.
|
||||
/// 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
|
||||
@@ -56,13 +62,15 @@ namespace GerbilManagerWebAPI.Import
|
||||
return new ImportDocxReport(false, 0, 0, 0, 0, 0, 0, 0, notes);
|
||||
}
|
||||
|
||||
// PairingCode → Litters (WS-code normalised: spaces removed)
|
||||
// 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
|
||||
.Where(l => l.PairingCode != null)
|
||||
.Select(l => new { l.Id, l.Date, l.PairingCode })
|
||||
.Select(l => new { l.Id, l.Date })
|
||||
.ToListAsync();
|
||||
var litterByWs = littersInDb
|
||||
.GroupBy(l => l.PairingCode!.Replace(" ", ""))
|
||||
var littersByDayNumber = littersInDb
|
||||
.GroupBy(l => l.Date.DayNumber)
|
||||
.ToDictionary(g => g.Key, g => g.ToList());
|
||||
|
||||
// normalize(name)+litterDob → Gerbil snapshot (main-import enrich path)
|
||||
@@ -90,6 +98,11 @@ namespace GerbilManagerWebAPI.Import
|
||||
.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 })
|
||||
@@ -100,156 +113,209 @@ namespace GerbilManagerWebAPI.Import
|
||||
int animalsCreated = 0, litterLinked = 0, goHomeFilled = 0, deathFilled = 0;
|
||||
int ownerLinked = 0, ownerCreated = 0, skipped = 0;
|
||||
|
||||
foreach (var da in docxAnimals)
|
||||
// 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()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(da.Name)) { skipped++; continue; }
|
||||
|
||||
var externalRef = DocxExternalRef(da);
|
||||
|
||||
// Resolve litter by WS-code + approximate birth date
|
||||
Guid? litterId = null;
|
||||
if (!string.IsNullOrWhiteSpace(da.WsCode) && !string.IsNullOrWhiteSpace(da.LitterDob))
|
||||
foreach (var da in docxAnimals)
|
||||
{
|
||||
var litterDob = ParseDate(da.LitterDob);
|
||||
if (litterDob is not null && litterByWs.TryGetValue(da.WsCode.Replace(" ", ""), out var cands))
|
||||
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 match = cands.FirstOrDefault(l =>
|
||||
Math.Abs(l.Date.DayNumber - litterDob.Value.DayNumber) <= 5);
|
||||
litterId = match?.Id;
|
||||
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);
|
||||
// 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; }
|
||||
if (animalDob is null) { skipped++; continue; }
|
||||
|
||||
var goHomeDate = ParseDate(da.AbgabeDate);
|
||||
var deathDate = ParseDate(da.DeathDate);
|
||||
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))
|
||||
// Resolve receiver contact (lookup-or-create; shared by all paths)
|
||||
Guid? receiverId = null;
|
||||
if (!string.IsNullOrWhiteSpace(da.Owner))
|
||||
{
|
||||
receiverId = existingContactId;
|
||||
ownerLinked++;
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
|
||||
// ── PATH 1: previously docx-created animal (idempotent re-run) ──────────
|
||||
if (docxExternalRefs.TryGetValue(externalRef, out var prevSnap))
|
||||
{
|
||||
ownerCreated++;
|
||||
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 newContact = new Contact { Id = Guid.NewGuid(), Name = da.Owner.Trim() };
|
||||
_db.Contacts.Add(newContact);
|
||||
await _db.SaveChangesAsync(); // persist before any Gerbil FK reference
|
||||
receiverId = newContact.Id;
|
||||
contactByNorm[normOwner] = receiverId.Value;
|
||||
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 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;
|
||||
// ── 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();
|
||||
|
||||
if (willLink) litterLinked++;
|
||||
if (willHome) goHomeFilled++;
|
||||
if (willDeath) deathFilled++;
|
||||
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)
|
||||
{
|
||||
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)
|
||||
colorVarietyByName.TryGetValue(NormalizeName(da.Farbschlag ?? ""), out var cvId);
|
||||
|
||||
_db.Gerbils.Add(new Gerbil
|
||||
{
|
||||
row.DateOfDeath = deathDate;
|
||||
if (!string.IsNullOrWhiteSpace(da.DeathCause) && row.CauseOfDeath is null)
|
||||
row.CauseOfDeath = da.DeathCause.Trim();
|
||||
}
|
||||
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,
|
||||
});
|
||||
}
|
||||
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 ────────────────────────────────────────────
|
||||
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 = deathDate is not null ? GerbilStatus.Deceased : GerbilStatus.GivenAway,
|
||||
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 && (animalsCreated + litterLinked + goHomeFilled + deathFilled + ownerCreated) > 0)
|
||||
await _db.SaveChangesAsync();
|
||||
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: {docxLitters.Count} Würfe, {docxAnimals.Count} Tier-Zeilen aus der docx.");
|
||||
notes.Add($"Neu angelegt: {animalsCreated} Jungtiere (abgegeben, nicht in Stammbäumen).");
|
||||
notes.Add($"Litter-Links: {litterLinked} Tiere einem Wurf zugeordnet.");
|
||||
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.");
|
||||
@@ -295,12 +361,12 @@ namespace GerbilManagerWebAPI.Import
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stable ExternalRef key for a docx animal row — used for idempotency across re-runs.
|
||||
/// Format: "docx-{wsCode}-{normname}-{litterDob}" (lowercased, spaces/punctuation stripped).
|
||||
/// 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 DocxExternalRef(DocxAnimal da)
|
||||
internal static string DocxExternalRefBase(DocxAnimal da)
|
||||
{
|
||||
var ws = da.WsCode.Replace(" ", "").ToLowerInvariant();
|
||||
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}";
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using GerbilManagerWebAPI.Models;
|
||||
using GerbilManagerWebAPI.Services;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace GerbilManagerWebAPI.Import
|
||||
@@ -390,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,
|
||||
@@ -419,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
|
||||
|
||||
192
GerbilManagerWebAPI/Import/IngestResolvedService.cs
Normal file
192
GerbilManagerWebAPI/Import/IngestResolvedService.cs
Normal file
@@ -0,0 +1,192 @@
|
||||
using System.Text.Json;
|
||||
using GerbilManagerWebAPI.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace GerbilManagerWebAPI.Import
|
||||
{
|
||||
public sealed class IngestResolvedService
|
||||
{
|
||||
private readonly ApplicationContext _db;
|
||||
private readonly string _resolvedJsonPath;
|
||||
|
||||
public IngestResolvedService(ApplicationContext db, IConfiguration config, IWebHostEnvironment env)
|
||||
{
|
||||
_db = db;
|
||||
var sourceDir = config["Import:SourcePath"]
|
||||
?? Path.GetFullPath(Path.Combine(env.ContentRootPath, "..", "tools", "import", "output"));
|
||||
_resolvedJsonPath = Path.Combine(sourceDir, "resolved_import.json");
|
||||
}
|
||||
|
||||
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 System.Text.Json.Serialization.JsonStringEnumConverter());
|
||||
var data = JsonSerializer.Deserialize<ResolvedImportData>(jsonContent, jsonOptions);
|
||||
|
||||
if (data == null)
|
||||
{
|
||||
return "Error: Failed to deserialize resolved_import.json.";
|
||||
}
|
||||
|
||||
// 1. Provider-agnostic clean wipe of dependent tables to prevent duplicate keys
|
||||
if (_db.Database.ProviderName == "Microsoft.EntityFrameworkCore.InMemory")
|
||||
{
|
||||
// Break circular references first
|
||||
foreach (var l in _db.Litters)
|
||||
{
|
||||
l.FatherId = null;
|
||||
l.MotherId = null;
|
||||
}
|
||||
foreach (var g in _db.Gerbils)
|
||||
{
|
||||
g.LitterId = null;
|
||||
}
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
_db.GerbilPhotos.RemoveRange(_db.GerbilPhotos);
|
||||
_db.WeightRecords.RemoveRange(_db.WeightRecords);
|
||||
_db.HealthRecords.RemoveRange(_db.HealthRecords);
|
||||
_db.Gerbils.RemoveRange(_db.Gerbils);
|
||||
_db.Litters.RemoveRange(_db.Litters);
|
||||
await _db.SaveChangesAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
// Break circular references first using ExecuteUpdateAsync
|
||||
await _db.Litters.ExecuteUpdateAsync(s => s
|
||||
.SetProperty(l => l.FatherId, (Guid?)null)
|
||||
.SetProperty(l => l.MotherId, (Guid?)null));
|
||||
|
||||
await _db.Gerbils.ExecuteUpdateAsync(s => s
|
||||
.SetProperty(g => g.LitterId, (Guid?)null));
|
||||
|
||||
await _db.GerbilPhotos.ExecuteDeleteAsync();
|
||||
await _db.WeightRecords.ExecuteDeleteAsync();
|
||||
await _db.HealthRecords.ExecuteDeleteAsync();
|
||||
await _db.Gerbils.ExecuteDeleteAsync();
|
||||
await _db.Litters.ExecuteDeleteAsync();
|
||||
}
|
||||
|
||||
// 2. Import Contacts (Only add new ones to preserve manually entered contacts)
|
||||
var existingContactIds = await _db.Contacts.Select(c => c.Id).ToHashSetAsync();
|
||||
var addedContactIds = new HashSet<Guid>();
|
||||
int contactsAdded = 0;
|
||||
foreach (var c in data.Contacts)
|
||||
{
|
||||
if (!existingContactIds.Contains(c.Id) && addedContactIds.Add(c.Id))
|
||||
{
|
||||
_db.Contacts.Add(c);
|
||||
contactsAdded++;
|
||||
}
|
||||
}
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
// 3. Pass 1: Insert all Litters with parent references set to null to avoid FK errors
|
||||
var littersToInsert = new List<Litter>();
|
||||
foreach (var l in data.Litters)
|
||||
{
|
||||
littersToInsert.Add(new Litter
|
||||
{
|
||||
Id = l.Id,
|
||||
Name = l.Name,
|
||||
Date = l.Date,
|
||||
TotalBorn = l.TotalBorn,
|
||||
DeathsWithin8Weeks = l.DeathsWithin8Weeks,
|
||||
FatherId = null, // Set in Pass 2
|
||||
MotherId = null, // Set in Pass 2
|
||||
ExpectedGoHomeDate = l.ExpectedGoHomeDate,
|
||||
Notes = l.Notes,
|
||||
PairingCode = l.PairingCode,
|
||||
ExternalRef = l.ExternalRef,
|
||||
LitterLetter = l.LitterLetter
|
||||
});
|
||||
}
|
||||
_db.Litters.AddRange(littersToInsert);
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
// 4. Pass 1: Insert all Gerbils with LitterId set to null to avoid FK errors
|
||||
var gerbilsToInsert = new List<Gerbil>();
|
||||
foreach (var g in data.Gerbils)
|
||||
{
|
||||
gerbilsToInsert.Add(new Gerbil
|
||||
{
|
||||
Id = g.Id,
|
||||
Name = g.Name,
|
||||
Gender = g.Gender,
|
||||
Status = g.Status,
|
||||
LitterId = null, // Set in Pass 2
|
||||
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,
|
||||
OriginBreeder = g.OriginBreeder,
|
||||
NameSearch = g.NameSearch,
|
||||
CharacterTraits = g.CharacterTraits,
|
||||
CharacterNote = g.CharacterNote,
|
||||
IsDeaf = g.IsDeaf,
|
||||
IsResident = g.IsResident
|
||||
});
|
||||
}
|
||||
_db.Gerbils.AddRange(gerbilsToInsert);
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
// 5. Pass 2: Set the actual foreign key relationships
|
||||
// Update Litters with their parent animal IDs
|
||||
var littersInDb = await _db.Litters.ToDictionaryAsync(l => l.Id);
|
||||
foreach (var l in data.Litters)
|
||||
{
|
||||
if (littersInDb.TryGetValue(l.Id, out var dbLitter))
|
||||
{
|
||||
dbLitter.FatherId = l.FatherId;
|
||||
dbLitter.MotherId = l.MotherId;
|
||||
}
|
||||
}
|
||||
|
||||
// Update Gerbils with their actual LitterId
|
||||
var gerbilsInDb = await _db.Gerbils.ToDictionaryAsync(g => g.Id);
|
||||
foreach (var g in data.Gerbils)
|
||||
{
|
||||
if (gerbilsInDb.TryGetValue(g.Id, out var dbGerbil))
|
||||
{
|
||||
dbGerbil.LitterId = g.LitterId;
|
||||
}
|
||||
}
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
// 6. Insert all Photos
|
||||
foreach (var p in data.GerbilPhotos)
|
||||
{
|
||||
_db.GerbilPhotos.Add(p);
|
||||
}
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
return $"Ingestion successful! Imported {contactsAdded} contacts, {data.Litters.Count} litters, {data.Gerbils.Count} gerbils, and {data.GerbilPhotos.Count} photos.";
|
||||
}
|
||||
}
|
||||
|
||||
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<GerbilPhoto> GerbilPhotos { get; set; } = new();
|
||||
}
|
||||
}
|
||||
1430
GerbilManagerWebAPI/Migrations/20260606231220_RenameREW.Designer.cs
generated
Normal file
1430
GerbilManagerWebAPI/Migrations/20260606231220_RenameREW.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load Diff
33
GerbilManagerWebAPI/Migrations/20260606231220_RenameREW.cs
Normal file
33
GerbilManagerWebAPI/Migrations/20260606231220_RenameREW.cs
Normal 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)");
|
||||
}
|
||||
}
|
||||
}
|
||||
1430
GerbilManagerWebAPI/Migrations/20260607012436_StatusModel.Designer.cs
generated
Normal file
1430
GerbilManagerWebAPI/Migrations/20260607012436_StatusModel.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load Diff
40
GerbilManagerWebAPI/Migrations/20260607012436_StatusModel.cs
Normal file
40
GerbilManagerWebAPI/Migrations/20260607012436_StatusModel.cs
Normal 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';");
|
||||
}
|
||||
}
|
||||
}
|
||||
1433
GerbilManagerWebAPI/Migrations/20260607013052_AddLitterMortality.Designer.cs
generated
Normal file
1433
GerbilManagerWebAPI/Migrations/20260607013052_AddLitterMortality.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -216,7 +216,7 @@ namespace GerbilManagerWebAPI.Migrations
|
||||
{
|
||||
Id = new Guid("00000000-0000-0000-0000-000000000001"),
|
||||
CanonicalGenotype = "AA chch DD EE GG pp spsp rere",
|
||||
Name = "Pink Eyed White (PEW)",
|
||||
Name = "REW",
|
||||
SortOrder = 0
|
||||
},
|
||||
new
|
||||
@@ -924,6 +924,9 @@ namespace GerbilManagerWebAPI.Migrations
|
||||
b.Property<DateOnly>("Date")
|
||||
.HasColumnType("date");
|
||||
|
||||
b.Property<int?>("DeathsWithin8Weeks")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<DateOnly?>("ExpectedGoHomeDate")
|
||||
.HasColumnType("date");
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ namespace GerbilManagerWebAPI.Models
|
||||
public Guid Id { get; set; }
|
||||
public required string Name { get; set; }
|
||||
public Gender Gender { get; set; }
|
||||
public GerbilStatus Status { get; set; } = GerbilStatus.Active;
|
||||
public GerbilStatus Status { get; set; } = GerbilStatus.Breeding;
|
||||
|
||||
// Birth litter (the litter this gerbil was born in).
|
||||
public Guid? LitterId { get; set; }
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
namespace GerbilManagerWebAPI.Models
|
||||
{
|
||||
/// <summary>Lifecycle status of a gerbil. Serialised as the string name on the wire.</summary>
|
||||
/// <summary>Lifecycle status of a gerbil. Serialised as the string name on the wire.
|
||||
/// Deceased and GivenAway are DERIVED (set by GerbilStatusService, not free-form input).
|
||||
/// Breeding/Pet/ForSale are the user-selectable live states.</summary>
|
||||
public enum GerbilStatus
|
||||
{
|
||||
Active = 0,
|
||||
/// <summary>Aktiv in der Zucht (vormals "Active").</summary>
|
||||
Breeding = 0,
|
||||
Deceased = 1,
|
||||
GivenAway = 2,
|
||||
/// <summary>Alive, at home, offered for Abgabe ("Abzugeben"). Drives FEAT-12 sale listing.</summary>
|
||||
ForSale = 3
|
||||
ForSale = 3,
|
||||
/// <summary>Lebendes Heimtier, nicht in Zucht ("Liebhaber").</summary>
|
||||
Pet = 4,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,10 @@ namespace GerbilManagerWebAPI.Models
|
||||
/// <summary>Total born count (was "Strength").</summary>
|
||||
public int? TotalBorn { get; set; }
|
||||
|
||||
/// <summary>Frühsterblichkeit: Anzahl der in den ersten 8 Wochen verstorbenen Tiere.
|
||||
/// Null = unbekannt (Altdaten). Must be ≤ TotalBorn if both are set.</summary>
|
||||
public int? DeathsWithin8Weeks { get; set; }
|
||||
|
||||
public Guid? FatherId { get; set; }
|
||||
public Gerbil? Father { get; set; }
|
||||
public Guid? MotherId { get; set; }
|
||||
|
||||
@@ -20,6 +20,23 @@ namespace GerbilManagerWebAPI.Names
|
||||
PropertyNameCaseInsensitive = true,
|
||||
};
|
||||
|
||||
// Known usage codes → (German description, isThematic).
|
||||
// Thematic categories provide real source names (not etymology); unknown codes fall through as etym.
|
||||
internal static readonly Dictionary<string, (string Description, bool Thematic)> UsageMap =
|
||||
new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["norn"] = ("Nordische/Altnordische Etymologie", false),
|
||||
["japa"] = ("Japanische Etymologie", false),
|
||||
["mythg"] = ("Griechische Mythologie", false),
|
||||
["ger"] = ("Germanische/Deutsche Etymologie", false),
|
||||
["arb"] = ("Arabische Etymologie", false),
|
||||
["disney"] = ("Disney-Charaktere", true),
|
||||
["pokemon"] = ("Pokémon-Namen", true),
|
||||
["encities"] = ("Namen englischer Städte", true),
|
||||
["hrcities"] = ("Namen kroatischer Städte", true),
|
||||
["usstates"] = ("Namen von US-Bundesstaaten", true),
|
||||
};
|
||||
|
||||
public async Task<NameSuggestionResult> SuggestAsync(
|
||||
string? letter, string? gender, string? usages, int count,
|
||||
CancellationToken ct = default)
|
||||
@@ -44,7 +61,11 @@ namespace GerbilManagerWebAPI.Names
|
||||
"Du bist ein Helfer für Rennmaus-Züchter. " +
|
||||
"Antworte IMMER mit einem reinen JSON-Array — KEINE Markdown-Code-Blöcke, " +
|
||||
"KEINE Erklärungen, KEIN Text außerhalb des Arrays. " +
|
||||
"Jedes Element hat genau die Felder: name, meaning, origin (alle Strings, alle auf Deutsch).";
|
||||
"Jedes Element hat genau die Felder: name, meaning, origin (alle Strings, alle auf Deutsch). " +
|
||||
"Bei thematischen Kategorien (Disney, Pokémon, Städte, Bundesstaaten): " +
|
||||
"origin = Kategoriename (z.B. \"Disney\", \"Pokémon\", \"Englische Stadt\", \"Kroatische Stadt\", \"US-Bundesstaat\"), " +
|
||||
"meaning = kurzer Kontext aus der Quelle (z.B. Film/Figur-Beschreibung, Lage der Stadt, Bundesstaat-Bezug). " +
|
||||
"Erfinde KEINE Etymologie für thematische Kategorien.";
|
||||
|
||||
internal static string BuildUserPrompt(string? letter, string? gender, string? usages, int count)
|
||||
{
|
||||
@@ -55,10 +76,44 @@ namespace GerbilManagerWebAPI.Names
|
||||
if (!string.IsNullOrWhiteSpace(gender) &&
|
||||
!gender.Equals("any", StringComparison.OrdinalIgnoreCase))
|
||||
sb.Append($", passend für {(gender.Equals("female", StringComparison.OrdinalIgnoreCase) ? "weibliche" : "männliche")} Tiere");
|
||||
|
||||
bool hasThematic = false;
|
||||
if (!string.IsNullOrWhiteSpace(usages))
|
||||
sb.Append($", aus den Kulturkreisen: {usages}");
|
||||
sb.Append(". Jeder Name muss eine echte etymologische Bedeutung und Herkunft haben ");
|
||||
sb.Append("(keine erfundenen oder zufälligen Namen). ");
|
||||
{
|
||||
var codes = usages.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
var etymDescriptions = new List<string>();
|
||||
var thematicDescriptions = new List<string>();
|
||||
foreach (var code in codes)
|
||||
{
|
||||
if (UsageMap.TryGetValue(code, out var entry))
|
||||
{
|
||||
if (entry.Thematic) thematicDescriptions.Add(entry.Description);
|
||||
else etymDescriptions.Add(entry.Description);
|
||||
}
|
||||
else
|
||||
{
|
||||
etymDescriptions.Add(code);
|
||||
}
|
||||
}
|
||||
if (etymDescriptions.Count > 0)
|
||||
sb.Append($", aus den Kulturkreisen: {string.Join(", ", etymDescriptions)}");
|
||||
if (thematicDescriptions.Count > 0)
|
||||
sb.Append($", aus den Themen-Kategorien: {string.Join(", ", thematicDescriptions)}");
|
||||
hasThematic = thematicDescriptions.Count > 0;
|
||||
}
|
||||
|
||||
sb.Append(". ");
|
||||
if (hasThematic)
|
||||
{
|
||||
sb.Append("Für Kulturkreis-Namen: echte etymologische Bedeutung und Herkunft. ");
|
||||
sb.Append("Für Themen-Kategorien: echte Namen aus der Quelle, origin = Kategoriename, ");
|
||||
sb.Append("Geschlecht-Filter kann ignoriert werden wenn nicht sinnvoll anwendbar. ");
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.Append("Jeder Name muss eine echte etymologische Bedeutung und Herkunft haben ");
|
||||
sb.Append("(keine erfundenen oder zufälligen Namen). ");
|
||||
}
|
||||
sb.Append($"Antworte mit genau {count} Elementen als reines JSON-Array: ");
|
||||
sb.Append("[{\"name\":\"...\",\"meaning\":\"...\",\"origin\":\"...\"}]");
|
||||
return sb.ToString();
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using GerbilManagerWebAPI.Endpoints;
|
||||
using GerbilManagerWebAPI.Models;
|
||||
using GerbilManagerWebAPI.Services;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Scalar.AspNetCore;
|
||||
@@ -48,6 +50,9 @@ builder.Services.AddHttpClient<GerbilManagerWebAPI.Inbox.DraftReplyService>(
|
||||
// FEAT-NAMEGEN: Name suggestions via Gemini (same AI section, same wire client).
|
||||
builder.Services.AddHttpClient<GerbilManagerWebAPI.Names.NameSuggestionService>(
|
||||
http => http.Timeout = TimeSpan.FromSeconds(60));
|
||||
// WEB-2: public site publish path (env var PublicSite__RootPath; empty = disabled)
|
||||
builder.Services.AddOptions<GerbilManagerWebAPI.Cms.PublicSiteOptions>()
|
||||
.BindConfiguration(GerbilManagerWebAPI.Cms.PublicSiteOptions.SectionName);
|
||||
|
||||
// INBOX-0: Gmail inbox. App Password encrypted at rest via Data Protection.
|
||||
// AR-3: persist the key ring so encrypted passwords survive image redeployments.
|
||||
@@ -81,7 +86,23 @@ app.MapScalarApiReference();
|
||||
if (!app.Environment.IsEnvironment("Testing"))
|
||||
{
|
||||
using var scope = app.Services.CreateScope();
|
||||
scope.ServiceProvider.GetRequiredService<ApplicationContext>().Database.Migrate();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationContext>();
|
||||
db.Database.Migrate();
|
||||
|
||||
// Startup sweep: derive status for animals that silently crossed the 7-year threshold
|
||||
// since the last write. No-op if all statuses are already current.
|
||||
var today = DateOnly.FromDateTime(DateTime.UtcNow);
|
||||
var candidates = await db.Gerbils
|
||||
.Where(g => g.Status != GerbilStatus.Deceased && g.Status != GerbilStatus.GivenAway
|
||||
&& g.DateOfDeath == null && g.ReceiverContactId == null
|
||||
&& g.DateOfBirth != null
|
||||
&& g.DateOfBirth < today.AddYears(-GerbilStatusService.MaxAgeYears))
|
||||
.ToListAsync();
|
||||
if (candidates.Count > 0)
|
||||
{
|
||||
foreach (var g in candidates) g.Status = GerbilStatus.Deceased;
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
|
||||
app.UseCors(LanCorsPolicy);
|
||||
|
||||
53
GerbilManagerWebAPI/Services/GerbilStatusService.cs
Normal file
53
GerbilManagerWebAPI/Services/GerbilStatusService.cs
Normal file
@@ -0,0 +1,53 @@
|
||||
using GerbilManagerWebAPI.Models;
|
||||
|
||||
namespace GerbilManagerWebAPI.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Central status-derivation logic. Every write path (create/update gerbil, SaleContract
|
||||
/// Abgabe, import, startup sweep) calls Apply() after setting the other fields so the
|
||||
/// derived statuses (Deceased, GivenAway) are always consistent.
|
||||
///
|
||||
/// Precedence (highest wins):
|
||||
/// 1) DateOfDeath set → Deceased (explicit, always)
|
||||
/// 2) Abgabe (ReceiverContactId set) → GivenAway
|
||||
/// 3) Age > MaxAgeYears without a death date or Abgabe → Deceased (presumed)
|
||||
/// 4) User-supplied {Breeding, Pet, ForSale}; defaults Breeding if invalid
|
||||
///
|
||||
/// Age-based death is time-dependent. The stored column is kept up-to-date by:
|
||||
/// a) Apply() on every write (catches the animal at write time)
|
||||
/// b) A startup sweep in Program.cs (catches animals that silently crossed the threshold)
|
||||
/// Gridify filters on the stored value, so status==Breeding never surfaces >7y animals.
|
||||
/// </summary>
|
||||
public static class GerbilStatusService
|
||||
{
|
||||
public const int MaxAgeYears = 7;
|
||||
|
||||
/// <summary>Derives and sets g.Status using the gerbil's current field values.
|
||||
/// Must be called AFTER all other fields (DateOfDeath, ReceiverContactId, DateOfBirth)
|
||||
/// have been applied. today = DateOnly.FromDateTime(DateTime.UtcNow).</summary>
|
||||
public static void Apply(Gerbil g, DateOnly today)
|
||||
{
|
||||
g.Status = Derive(g.Status, g.DateOfBirth, g.DateOfDeath,
|
||||
isAbgegeben: g.ReceiverContactId is not null, today);
|
||||
}
|
||||
|
||||
/// <summary>Pure derivation — useful for tests and the migration backfill.</summary>
|
||||
public static GerbilStatus Derive(
|
||||
GerbilStatus requested,
|
||||
DateOnly? dateOfBirth,
|
||||
DateOnly? dateOfDeath,
|
||||
bool isAbgegeben,
|
||||
DateOnly today)
|
||||
{
|
||||
if (dateOfDeath is not null) return GerbilStatus.Deceased;
|
||||
if (isAbgegeben) return GerbilStatus.GivenAway;
|
||||
if (dateOfBirth is not null && IsOlderThan(dateOfBirth.Value, MaxAgeYears, today))
|
||||
return GerbilStatus.Deceased;
|
||||
return requested is GerbilStatus.Breeding or GerbilStatus.Pet or GerbilStatus.ForSale
|
||||
? requested : GerbilStatus.Breeding;
|
||||
}
|
||||
|
||||
private static bool IsOlderThan(DateOnly dob, int years, DateOnly today) =>
|
||||
today >= dob.AddYears(years);
|
||||
}
|
||||
}
|
||||
107
HUMANQUESTION.md
107
HUMANQUESTION.md
@@ -1,107 +0,0 @@
|
||||
# HUMANQUESTION.md — offene Fragen & benötigte Daten
|
||||
|
||||
> ## ⛔ BITTE DIESE DATEI NICHT SELBST BEARBEITEN
|
||||
> **Antwortet einfach Michael (dem Assistenten) im Chat** — Stichworte genügen
|
||||
> („A3: hier das Passwort …", „PEW = REW: ja"). **Michael pflegt diese Datei**
|
||||
> und streicht jede Frage, sobald sie beantwortet ist. So steht hier immer nur
|
||||
> das, was **noch offen** ist. Nichts geht verloren.
|
||||
|
||||
_Stand: 2026-06-07. **Alle Genetik- und Konflikt-Fragen sind beantwortet ✅** (alle
|
||||
32 Konflikt-Tiere entschieden). Die KI-Funktionen sind **live und kostenlos**. Der
|
||||
große finale Re-Import (mit allen 41 Stammbäumen + Wurfchronik) steht startbereit.
|
||||
Offen sind nur noch ein paar **technische Zugänge** und etwas **optionaler
|
||||
Feinschliff** — siehe unten._
|
||||
|
||||
---
|
||||
|
||||
## A. Zugänge & Technik (für Julian)
|
||||
|
||||
| # | Was gebraucht wird | Schaltet frei |
|
||||
|---|---|---|
|
||||
| **A3** | **Gmail App-Passwort.** Google-Konto → 2-Faktor aktivieren → „App-Passwörter" → eines für „GerbilManager" → 16-stelligen Code an Michael. | E-Mail-Posteingang (Anfragen abrufen + KI-Antwortentwürfe). Backend ist fertig, wartet nur auf den Zugang. |
|
||||
| **A4** | **Domain-Name** (registriert ✔) + **Cloudflare-Konto & API-Token** (Berechtigung „Cloudflare Pages → Edit"). | Öffentliche Webseite veröffentlichen (Jimdo-Ersatz). Seite ist gebaut. |
|
||||
| **A5** | **TrueNAS-Restfragen:** (a) SCALE-Version? · (c) eigener Postgres-Container (empfohlen) oder bestehender NAS-Postgres? · (d) Dataset-Pfad für Daten/Backups, Port 80 frei? | Produktiv-Betrieb auf dem NAS (compose ist fertig vorbereitet). |
|
||||
| **A5b2** | **2 Gitea-Repo-Secrets** anlegen (Repo → Einstellungen → Actions → Secrets): `REGISTRY_USER` (dein Gitea-Login) + `REGISTRY_TOKEN` (Token mit `write:package`). | CI pusht fertige Docker-Images in die Registry. (Die CI-Tests laufen bereits grün.) |
|
||||
|
||||
## B. Kleine Aktion (jederzeit)
|
||||
|
||||
| # | Aktion | Warum |
|
||||
|---|---|---|
|
||||
| **B2** | **Firewall-Regel** (PowerShell **als Administrator**): `New-NetFirewallRule -DisplayName "GerbilManager dev" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 5173,5179 -Profile Any` | Damit das Handy deiner Frau im WLAN auf die App kommt (http://192.168.2.124:5173). |
|
||||
|
||||
## C. Genetik-Feinschliff (optional, blockiert nichts)
|
||||
|
||||
| # | Frage | Betrifft |
|
||||
|---|---|---|
|
||||
| **REW-1** | **PEW = REW?** „Pink Eyed White" (PEW) und „Rotaugenweiß" (REW) sind dasselbe — soll der alte PEW-Eintrag mit REW **zusammengeführt** werden? | Doppel-Eintrag im Farbkatalog. |
|
||||
| **REW-2** | **REW bei nicht-agouti?** Wird ein `aa`-Tier (z. B. Marder) mit Colourpoint + `pp` **auch** als REW gewertet, oder soll REW nur für agouti-basierte Tiere gelten? | REW-Erkennung (wird gerade A-unabhängig gebaut = aa zählt mit). |
|
||||
| **C7** | *(optional)* Was hat deiner Frau bei **Renner Pro** gefehlt? Lieblings-Auswertungen? | mögliche neue Funktionen |
|
||||
|
||||
## E. Charakterbogen-Eigenschaften (optional)
|
||||
|
||||
Aktuell eingebaute Häkchen-Eigenschaften (für die KI-Verkaufstexte) — **soll etwas ergänzt/gestrichen werden?**
|
||||
|
||||
> zutraulich · handzahm · neugierig · aufgeschlossen · ruhig/ausgeglichen ·
|
||||
> lebhaft/aktiv · verschmust · eigenständig · anfängergeeignet · futterfreudig ·
|
||||
> buddelt gern · klettert gern · läuft gern im Laufrad · gut verträglich · schreckhaft
|
||||
|
||||
- **E1** — Eigenschaften hinzufügen/entfernen? (z. B. *dominant, rangniedrig, für erfahrene Halter, einzelgängerisch*?)
|
||||
- **E2** — Auch ehrliche **negative** Eigenschaften aufnehmen (z. B. *beißt manchmal*) für ehrliche Inserate?
|
||||
|
||||
---
|
||||
|
||||
## D7 · Neue Konflikt-Tiere aus den 41 Stammbäumen (bitte entscheiden)
|
||||
|
||||
Durch die vielen neuen Stammbaum-Dateien sind **13 neue Konflikt-Tiere** aufgetaucht (gleicher Name+Datum, widersprüchliche Angaben in mehreren Diagrammen). Sie warten in Quarantäne — **nichts ist verloren**, sie laden automatisch nach, sobald du je Tier kurz sagst was stimmt. (Uw=G + „Vorhandensein gewinnt" sind schon angewendet; das hier ist der echte Rest.)
|
||||
|
||||
**A) Nur Sterbedatum offen** (Gencode einig — bei Osamu/Filou/Sunny zusätzlich „taub" beibehalten):
|
||||
| Tier | Sterbedatum — welches? |
|
||||
|---|---|
|
||||
| Isa of Golden Lights (*24.12.2014) | 21.07.2018 ↔ 21.10.2018 |
|
||||
| Jack II v.d. K.C. (*14.02.2016) | 06.10.2019 ↔ 20.10.2019 |
|
||||
| Osamu v.d. K.C. (*10.12.2015) | 01.10.2020 ↔ 18.12.2020 |
|
||||
| Filou v.d. K.C. (*24.11.2014) | 31.08.2019 ↔ 31.10.2019 |
|
||||
| Sunny von PZ Karl (*10.04.2014) | 30.04.2019 ↔ 05.05.2019 |
|
||||
|
||||
**B) Gencode-Konflikt** (+ ggf. Sterbedatum):
|
||||
| Tier | Konflikt — was stimmt? |
|
||||
|---|---|
|
||||
| Milon v.d. K.C. (*27.11.2014) | A-Locus: **Aa** ↔ **aa** |
|
||||
| Percy of little runners (*16.12.2017) | P-Locus: **PP** ↔ **Pp** |
|
||||
| Iwana of little runners (*02.10.2018) | P-Locus: **PP** ↔ **Pp** |
|
||||
| Sokrates v.d. K.C. (*14.12.2015) | D-Locus: **D-** ↔ **Dd** · + Sterbedatum 20.05.**2019** ↔ **2020** |
|
||||
| Eragon (Elieus, *18.05.2016) | C-Locus: **CC** (vollfarbig) ↔ **c[chm]c[chm]** (Colourpoint) |
|
||||
| Dakota of sweet little mouse (*30.01.2015) | A: **Aa**↔**aa** · P: **pp**↔**PP** · Sp: **Spsp**↔**spsp** |
|
||||
| Kazumi v.d. K.C. (*23.04.2013) | A: **Aa**↔**aa** · G: **GG**↔**Gg** · P: **PP**↔**Pp** · Sp: **Spsp**↔**spsp** |
|
||||
| Max von Privat (*01.02.2013) | D: **D-**↔**DD** · P: **P-**↔**PP** · Sterbedatum (4 Varianten: 04.02.2016 / 04.03.2016 / 2014 / 30.12.2015) |
|
||||
|
||||
*(Alle Gencode-Varianten + Quelldateien: `tools/import/output/review-report.md`.)*
|
||||
|
||||
---
|
||||
|
||||
## F. Was hängt woran (Kurzübersicht)
|
||||
|
||||
| Funktion | Status | Wartet auf |
|
||||
|---|---|---|
|
||||
| KI-Verkaufstexte · Charakterbogen-KI · Namensgenerator | ✅ **LIVE & kostenlos** (Gemini Free-Tier) | — |
|
||||
| E-Mail-Posteingang (Anfragen) | gebaut | **A3** (Gmail-App-Passwort) |
|
||||
| Öffentliche Webseite + KI-Chat-Editor | gebaut | **A4** (Domain + Cloudflare) |
|
||||
| NAS-Produktiv-Deployment + Docker-Push | vorbereitet, CI grün | **A5** + **A5b2** |
|
||||
| Handy-Zugriff im WLAN | App läuft | **B2** (Firewall) |
|
||||
| Alle importierten Konflikt-Tiere | ✅ **alle 32 entschieden** | finaler Re-Import (startbereit, läuft demnächst) |
|
||||
|
||||
---
|
||||
|
||||
## ✅ Erledigt (Archiv — nichts geht verloren)
|
||||
|
||||
- **A1 / A2 — Gemini-Key + Kosten:** Schlüssel hinterlegt (sicher, nie im Code); **kostenlos** über `gemini-flash-latest` (Free-Tier), kein Billing nötig. → KI live verifiziert.
|
||||
- **B1 — Neustart nach Updates:** Michael startet die lokale Instanz jetzt **automatisch** nach jedem neuen Feature. Keine Aktion mehr nötig.
|
||||
- **B3 — 2 Test-Einträge ("Testmaus/Wurf E2E"):** verschwinden automatisch beim finalen Re-Import (Wipe + Neuaufbau).
|
||||
- **C1–C9 — Genetik-Schreibweise:** alles geklärt (Uw=G · „-"=Allel unbekannt · Dedup nach Name+Datum+Zucht · Schimmel-Arten · Himalaya/Hermelin · „CP-Fuchs"-Sammelbegriff + „hell"=`c[h]` · Dilute-Präfix · REW-Regel).
|
||||
- **D1–D6 — alle 32 Konflikt-Tiere:** entschieden und in `tools/import/conflict-decisions.json` hinterlegt (werden beim finalen Re-Import alle geladen).
|
||||
|
||||
*Details der erledigten Punkte stehen in der git-Historie und in `tools/import/conflict-decisions.json`.*
|
||||
|
||||
---
|
||||
|
||||
*Einfach abschnittsweise antworten — Michael arbeitet die Antworten ein und meldet, was dadurch live geht.*
|
||||
105
HUMANQUESTION.md.migrated
Normal file
105
HUMANQUESTION.md.migrated
Normal file
@@ -0,0 +1,105 @@
|
||||
# HUMANQUESTION.md — offene Fragen & benötigte Daten
|
||||
|
||||
> ## ⛔ BITTE DIESE DATEI NICHT SELBST BEARBEITEN
|
||||
> **Antwortet einfach Michael (dem Assistenten) im Chat** — Stichworte genügen
|
||||
> („A3: hier das Passwort …", „PEW = REW: ja"). **Michael pflegt diese Datei**
|
||||
> und streicht jede Frage, sobald sie beantwortet ist. So steht hier immer nur
|
||||
> das, was **noch offen** ist. Nichts geht verloren.
|
||||
|
||||
_Stand: 2026-06-07. **Alle Genetik- und Konflikt-Fragen sind beantwortet ✅** (alle
|
||||
32 Konflikt-Tiere entschieden). Die KI-Funktionen sind **live und kostenlos**. Der
|
||||
große finale Re-Import (mit allen 41 Stammbäumen + Wurfchronik) steht startbereit.
|
||||
Offen sind nur noch ein paar **technische Zugänge** und etwas **optionaler
|
||||
Feinschliff** — siehe unten._
|
||||
|
||||
---
|
||||
|
||||
## A. Zugänge & Technik (für Julian)
|
||||
|
||||
| # | Was gebraucht wird | Schaltet frei |
|
||||
|---|---|---|
|
||||
| **A3** | **Gmail App-Passwort.** Google-Konto → 2-Faktor aktivieren → „App-Passwörter" → eines für „GerbilManager" → 16-stelligen Code an Michael. | E-Mail-Posteingang (Anfragen abrufen + KI-Antwortentwürfe). Backend ist fertig, wartet nur auf den Zugang. |
|
||||
| **A4** (umgestellt 2026-06-07) | **Self-Host statt Cloudflare:** Strato-Domain → DynDNS → deine IP (auto-aktualisiert) + **nginx-Reverse-Proxy auf TrueNAS** leitet auf die statische Seite. Cloudflare NICHT mehr nötig. **Offen:** welcher Hostname/Subdomain für die öffentliche Seite? Bau = WEB-2 (Dwight, self-host-Variante). | Öffentliche Webseite (Jimdo-Ersatz), self-hosted auf dem NAS. |
|
||||
| ~~**A5**~~ ✅ | **TrueNAS beantwortet (2026-06-07):** (a) SCALE **25.10.2.1 Goldeye** → Custom App (Docker compose) ✓ · (c) **eigener Postgres-Container** (legen wir an, compose macht das) ✓ · (d) Daten/Backups unter **`/mnt/JailStorage/DockerVolumes/`** (neuer Ordner) ✓. **Rest-Detail:** Port **80** frei? (sonst `PORT` in .env ändern). → OPS-2 (Dwight) finalisiert compose/.env/ops.md auf diese Werte. | Produktiv-Betrieb auf dem NAS. |
|
||||
| **A5b2** | **2 Gitea-Repo-Secrets** anlegen (Repo `Gulum/GerbilManager` → **Einstellungen → Actions → Secrets → Secret hinzufügen**): `REGISTRY_USER` = `gulum` · `REGISTRY_TOKEN` = Gitea-Zugriffstoken mit Scope **`write:package`** (erzeugen unter **Benutzer-Einstellungen → Anwendungen → Zugriffstoken verwalten**, Token wird nur einmal angezeigt → in das Secret kopieren). Danach Action erneut laufen lassen. Registry ist jetzt **`git.rismer.de`** (externes HTTPS) → keine `insecure-registry`-Daemon-Konfig nötig. | CI pusht fertige Docker-Images in die Registry. (Tests laufen grün; aktuell rot ist NUR der Login-Schritt: `secrets.REGISTRY_USER`/`REGISTRY_TOKEN` sind leer → „Username and password required".) |
|
||||
|
||||
## B. Kleine Aktion (jederzeit)
|
||||
|
||||
| # | Aktion | Warum |
|
||||
|---|---|---|
|
||||
| ~~**B2**~~ ✅ | **Firewall-Regel erledigt** (2026-06-07) — Ports 5173/5179 inbound offen. Handy im WLAN kommt auf http://192.168.2.124:5173 (sobald App läuft). | — |
|
||||
|
||||
## C. Genetik-Feinschliff (optional, blockiert nichts)
|
||||
|
||||
| # | Frage | Betrifft |
|
||||
|---|---|---|
|
||||
| ~~**REW-1**~~ ✅ | **JA, PEW = REW (dasselbe)** → PEW-Eintrag mit REW zusammenführen (GEN-4c, Kevin). | Doppel-Eintrag im Farbkatalog. |
|
||||
| ~~**REW-2**~~ ✅ | **A-unabhängig:** egal ob `AA`/`Aa` (groß) oder `aa` (klein) — wenn die REW-Bedingung erfüllt ist, ist es **immer REW**. Schon so implementiert (GEN-4, A/D/E/G-unabhängig). | REW-Erkennung. |
|
||||
| **C7** | *(optional)* Was hat deiner Frau bei **Renner Pro** gefehlt? Lieblings-Auswertungen? | mögliche neue Funktionen |
|
||||
|
||||
## E. Charakterbogen-Eigenschaften — ✅ ERLEDIGT (CHARAKTERBOGEN-2)
|
||||
|
||||
**E1 ✅** — Deine Frau hat die Eigenschaften geliefert, Kelly hat sie eingebaut: **4 Kategorien** (Sozialverhalten · Eignung & Umgang · Hobbys & Eigenarten · Wesen & Temperament), die 15 alten Häkchen unverändert + **10 neue** (dominant, rangniedrig, sozialkompetent, für erfahrene Halter, Beobachtungstier, familiengeeignet, Schredder-Meister, Nestbauer/Architekt, territorial …).
|
||||
**E2 ✅** — Ehrliche **Warnsignale** (z. B. *schwer vergesellschaftbar*, *territorial*) sind als eigene, optisch abgesetzte Gruppe drin — fließen in die KI-Verkaufstexte ein.
|
||||
|
||||
Weitere Eigenschaften lassen sich jederzeit **additiv** ergänzen (1-Zeilen-Änderung) — falls deiner Frau noch etwas einfällt, einfach sagen.
|
||||
|
||||
---
|
||||
|
||||
## D7 · Neue Konflikt-Tiere aus den 41 Stammbäumen (bitte entscheiden)
|
||||
|
||||
Durch die vielen neuen Stammbaum-Dateien sind **13 neue Konflikt-Tiere** aufgetaucht (**7 erledigt:** Kazumi/Filou/Sokrates/Osamu/Percy/Iwana/Eragon ✅ — **6 offen**) (gleicher Name+Datum, widersprüchliche Angaben in mehreren Diagrammen). Sie warten in Quarantäne — **nichts ist verloren**, sie laden automatisch nach, sobald du je Tier kurz sagst was stimmt. (Uw=G + „Vorhandensein gewinnt" sind schon angewendet; das hier ist der echte Rest.)
|
||||
|
||||
_Quelldatei = die Stammbaum-Datei(en) in `C:\Users\gulum\dev\Sttammbäume\`, in denen das Tier vorkommt. **Mehrere Dateien = Ursache des Konflikts** (widersprüchliche Angaben in verschiedenen Diagrammen)._
|
||||
|
||||
**A) Nur Sterbedatum offen** (Gencode einig — bei Osamu/Filou/Sunny zusätzlich „taub" beibehalten):
|
||||
| Tier | Sterbedatum — welches? | Quelldatei(en) |
|
||||
|---|---|---|
|
||||
| Isa of Golden Lights (*24.12.2014) | 21.07.2018 ↔ 21.10.2018 | Stammbaum von **Ella**.xlsx · von **Kalea**.xlsx |
|
||||
| Jack II v.d. K.C. (*14.02.2016) | 06.10.2019 ↔ 20.10.2019 | Stammbaum von **Kalea**.xlsx · von **Rainny**.xlsx · von **Ren**.xlsx |
|
||||
| ~~Osamu v.d. K.C. (*10.12.2015)~~ ✅ | **18.12.2020** (erledigt) | — |
|
||||
| ~~Filou v.d. K.C. (*24.11.2014)~~ ✅ | **31.08.2019** (erledigt) | — |
|
||||
| Sunny von PZ Karl (*10.04.2014) | 30.04.2019 ↔ 05.05.2019 | Stammbaum von **Vance**.xlsx · von **Yurikas und Pintos Sohn**.xlsx |
|
||||
|
||||
**B) Gencode-Konflikt** (+ ggf. Sterbedatum):
|
||||
| Tier | Konflikt — was stimmt? | Quelldatei(en) |
|
||||
|---|---|---|
|
||||
| ~~Milon v.d. K.C. (*27.11.2014)~~ ✅ | A-Locus **Aa** (erledigt — Julian 2026-06-07: Aa gewinnt gg. aa) | — |
|
||||
| ~~Percy of little runners (*16.12.2017)~~ ✅ | P-Locus **Pp** (erledigt) | — |
|
||||
| ~~Iwana of little runners (*02.10.2018)~~ ✅ | P-Locus **Pp** (erledigt) | — |
|
||||
| ~~Sokrates v.d. K.C. (*14.12.2015)~~ ✅ | **D-** + Sterbedatum **20.05.2019** (erledigt) | — |
|
||||
| ~~Eragon (Elieus, *18.05.2016)~~ ✅ | C **CC** (vollfarbig) + Name **„Elieus gen. Eragon"**. Korrekter Datensatz lädt bereits (CC); Colourpoint-Variante „Kleiner Warnowrenner …" bleibt als Dublette in Quarantäne — kein weiterer Schritt nötig. | — |
|
||||
| Dakota of sweet little mouse (*30.01.2015) | A: **Aa**↔**aa** · P: **pp**↔**PP** · Sp: **Spsp**↔**spsp** | Stammbaum von **Jiminy of Black Forest**.xlsx · von **Yurikas und Pintos Sohn**.xlsx |
|
||||
| ~~Kazumi v.d. K.C. (*23.04.2013)~~ ✅ | **Aa Cc[chm] DD ee[f] GG PP Spsp** (erledigt) | — |
|
||||
| Max von Privat (*01.02.2013) | D: **D-**↔**DD** · P: **P-**↔**PP** · Sterbedatum (4 Varianten: 04.02.2016 / 04.03.2016 / 2014 / 30.12.2015) | Stammbaum von **Danako**.xlsx · von **Kalea**.xlsx · von **Vance**.xlsx · von **Wildfire und Vestras Kids**.xlsx · von **Yurikas und Pintos Sohn**.xlsx |
|
||||
|
||||
*(Alle Gencode-Varianten + Quelldateien-Details: `tools/import/output/review-report.md`.)*
|
||||
|
||||
---
|
||||
|
||||
## F. Was hängt woran (Kurzübersicht)
|
||||
|
||||
| Funktion | Status | Wartet auf |
|
||||
|---|---|---|
|
||||
| KI-Verkaufstexte · Charakterbogen-KI · Namensgenerator | ✅ **LIVE & kostenlos** (Gemini Free-Tier) | — |
|
||||
| E-Mail-Posteingang (Anfragen) | gebaut | **A3** (Gmail-App-Passwort) |
|
||||
| Öffentliche Webseite + KI-Chat-Editor | gebaut; Hosting **self-hosted** (Strato/DynDNS + TrueNAS nginx) | Hostname-Wahl + WEB-2-Bau (Dwight) |
|
||||
| NAS-Produktiv-Deployment + Docker-Push | vorbereitet, CI grün | **A5** + **A5b2** |
|
||||
| Handy-Zugriff im WLAN | ✅ **B2 Firewall erledigt** — testbar sobald App läuft | — |
|
||||
| Alle importierten Konflikt-Tiere | ✅ **alle 32 entschieden** | finaler Re-Import (startbereit, läuft demnächst) |
|
||||
|
||||
---
|
||||
|
||||
## ✅ Erledigt (Archiv — nichts geht verloren)
|
||||
|
||||
- **A1 / A2 — Gemini-Key + Kosten:** Schlüssel hinterlegt (sicher, nie im Code); **kostenlos** über `gemini-flash-latest` (Free-Tier), kein Billing nötig. → KI live verifiziert.
|
||||
- **B1 — Neustart nach Updates:** Michael startet die lokale Instanz jetzt **automatisch** nach jedem neuen Feature. Keine Aktion mehr nötig.
|
||||
- **B3 — 2 Test-Einträge ("Testmaus/Wurf E2E"):** verschwinden automatisch beim finalen Re-Import (Wipe + Neuaufbau).
|
||||
- **C1–C9 — Genetik-Schreibweise:** alles geklärt (Uw=G · „-"=Allel unbekannt · Dedup nach Name+Datum+Zucht · Schimmel-Arten · Himalaya/Hermelin · „CP-Fuchs"-Sammelbegriff + „hell"=`c[h]` · Dilute-Präfix · REW-Regel).
|
||||
- **D1–D6 — alle 32 Konflikt-Tiere:** entschieden und in `tools/import/conflict-decisions.json` hinterlegt (werden beim finalen Re-Import alle geladen).
|
||||
|
||||
*Details der erledigten Punkte stehen in der git-Historie und in `tools/import/conflict-decisions.json`.*
|
||||
|
||||
---
|
||||
|
||||
*Einfach abschnittsweise antworten — Michael arbeitet die Antworten ein und meldet, was dadurch live geht.*
|
||||
@@ -7,20 +7,25 @@ POSTGRES_PASSWORD=aendere_mich_bitte
|
||||
# Externer Port fuer das Frontend (Standard: 80)
|
||||
PORT=80
|
||||
|
||||
# Gitea Container Registry (Standard: truenas:13000/gulum)
|
||||
REGISTRY=truenas:13000/gulum
|
||||
# Container Registry (git.rismer.de/gulum)
|
||||
REGISTRY=git.rismer.de/gulum
|
||||
TAG=latest
|
||||
|
||||
# NAS-Dataset-Pfade (TrueNAS SCALE: /mnt/<Pool>/<Dataset>)
|
||||
PGDATA_PATH=/mnt/SSD/gerbil/pgdata
|
||||
PHOTOS_PATH=/mnt/SSD/gerbil/photos
|
||||
BACKUPS_PATH=/mnt/SSD/gerbil/backups
|
||||
# NAS-Dataset-Pfade (TrueNAS SCALE Goldeye: /mnt/JailStorage/DockerVolumes/...)
|
||||
PGDATA_PATH=/mnt/JailStorage/DockerVolumes/gerbilmanager/pgdata
|
||||
PHOTOS_PATH=/mnt/JailStorage/DockerVolumes/gerbilmanager/photos
|
||||
BACKUPS_PATH=/mnt/JailStorage/DockerVolumes/gerbilmanager/backups
|
||||
# AR-3: Data Protection Key-Ring (Gmail-App-Passwort-Verschlüsselung)
|
||||
KEYS_PATH=/mnt/SSD/gerbil/keys
|
||||
KEYS_PATH=/mnt/JailStorage/DockerVolumes/gerbilmanager/keys
|
||||
|
||||
# Backup-Rotation: Anzahl Tage (Standard: 7)
|
||||
BACKUP_KEEP_DAYS=7
|
||||
|
||||
# WEB-2: Oeffentliche Webseite (Shared Volume: api schreibt, publicsite-nginx liest)
|
||||
PUBLICSITE_PATH=/mnt/JailStorage/DockerVolumes/gerbilmanager/publicsite
|
||||
# Port fuer den publicsite-nginx (Julian's externer nginx leitet darauf weiter)
|
||||
PUBLICSITE_PORT=8081
|
||||
|
||||
# KI-Funktionen (Verkaufstext + Posteingang-Entwurf)
|
||||
# Beliebiger OpenAI-kompatibler Anbieter — Optionen in docs/ai-provider.md
|
||||
# Leer lassen = KI deaktiviert (kein Fehler, nur 503 AiKeyMissing)
|
||||
|
||||
@@ -29,7 +29,7 @@ services:
|
||||
|
||||
# --- .NET API (GerbilManagerWebAPI) ---
|
||||
api:
|
||||
image: "${REGISTRY:-truenas:13000/gulum}/gerbilmanager-api:${TAG:-latest}"
|
||||
image: "${REGISTRY:-git.rismer.de/gulum}/gerbilmanager-api:${TAG:-latest}"
|
||||
build:
|
||||
context: ../..
|
||||
dockerfile: GerbilManagerWebAPI/Dockerfile
|
||||
@@ -48,9 +48,12 @@ services:
|
||||
AI__BaseUrl: "${AI__BaseUrl:-}"
|
||||
AI__ApiKey: "${AI__ApiKey:-}"
|
||||
AI__Model: "${AI__Model:-gemini-flash-latest}"
|
||||
# WEB-2: Pfad wo POST /api/publish die oeffentliche Seite hinschreibt
|
||||
PublicSite__RootPath: /data/publicsite
|
||||
volumes:
|
||||
- photos:/data/photos
|
||||
- keys:/data/keys
|
||||
- publicsite:/data/publicsite
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
@@ -63,7 +66,7 @@ services:
|
||||
|
||||
# --- nginx Frontend (React SPA + API-Proxy) ---
|
||||
frontend:
|
||||
image: "${REGISTRY:-truenas:13000/gulum}/gerbilmanager-frontend:${TAG:-latest}"
|
||||
image: "${REGISTRY:-git.rismer.de/gulum}/gerbilmanager-frontend:${TAG:-latest}"
|
||||
build:
|
||||
context: ../..
|
||||
dockerfile: gerbil-manager-web/Dockerfile
|
||||
@@ -74,6 +77,21 @@ services:
|
||||
api:
|
||||
condition: service_healthy
|
||||
|
||||
# --- nginx Public Site (WEB-2) ---
|
||||
# Serviert NUR die statische oeffentliche Seite (live/ aus dem publicsite-Volume).
|
||||
# SICHERHEIT: Kein Proxy auf api/frontend — nur statisches HTML nach aussen.
|
||||
# Julian's externer nginx-Proxy leitet <DOMAIN> auf Port 8081 weiter.
|
||||
publicsite:
|
||||
image: nginx:alpine
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "${PUBLICSITE_PORT:-8081}:80"
|
||||
volumes:
|
||||
- publicsite:/usr/share/nginx/html:ro
|
||||
- ./nginx/publicsite.conf:/etc/nginx/conf.d/default.conf:ro
|
||||
depends_on:
|
||||
- api
|
||||
|
||||
# --- Backup-Sidecar (taeglicher pg_dump + Foto-Archiv + Rotation) ---
|
||||
backup:
|
||||
image: postgres:17-alpine
|
||||
@@ -95,19 +113,19 @@ services:
|
||||
|
||||
volumes:
|
||||
# NAS-Datasets als Bind-Mounts (Pfade in .env konfigurieren).
|
||||
# TrueNAS: Dataset-Pfad z.B. /mnt/SSD/gerbil/pgdata
|
||||
# TrueNAS Goldeye: /mnt/JailStorage/DockerVolumes/gerbilmanager/<name>
|
||||
pgdata:
|
||||
driver: local
|
||||
driver_opts:
|
||||
type: none
|
||||
o: bind
|
||||
device: "${PGDATA_PATH:-/mnt/gerbil/pgdata}"
|
||||
device: "${PGDATA_PATH:-/mnt/JailStorage/DockerVolumes/gerbilmanager/pgdata}"
|
||||
photos:
|
||||
driver: local
|
||||
driver_opts:
|
||||
type: none
|
||||
o: bind
|
||||
device: "${PHOTOS_PATH:-/mnt/gerbil/photos}"
|
||||
device: "${PHOTOS_PATH:-/mnt/JailStorage/DockerVolumes/gerbilmanager/photos}"
|
||||
# AR-3: Data Protection key ring — persistiert Gmail-App-Passwort-Verschlüsselung.
|
||||
# Muss ein persistentes NAS-Dataset sein (nicht dasselbe wie photos).
|
||||
keys:
|
||||
@@ -115,10 +133,17 @@ volumes:
|
||||
driver_opts:
|
||||
type: none
|
||||
o: bind
|
||||
device: "${KEYS_PATH:-/mnt/gerbil/keys}"
|
||||
device: "${KEYS_PATH:-/mnt/JailStorage/DockerVolumes/gerbilmanager/keys}"
|
||||
backups:
|
||||
driver: local
|
||||
driver_opts:
|
||||
type: none
|
||||
o: bind
|
||||
device: "${BACKUPS_PATH:-/mnt/gerbil/backups}"
|
||||
device: "${BACKUPS_PATH:-/mnt/JailStorage/DockerVolumes/gerbilmanager/backups}"
|
||||
# WEB-2: gemeinsames Volume fuer api (rw) und publicsite-nginx (ro).
|
||||
publicsite:
|
||||
driver: local
|
||||
driver_opts:
|
||||
type: none
|
||||
o: bind
|
||||
device: "${PUBLICSITE_PATH:-/mnt/JailStorage/DockerVolumes/gerbilmanager/publicsite}"
|
||||
|
||||
29
deploy/truenas/nginx/publicsite.conf
Normal file
29
deploy/truenas/nginx/publicsite.conf
Normal file
@@ -0,0 +1,29 @@
|
||||
# GerbilManager — publicsite nginx (WEB-2)
|
||||
# Serviert die statische oeffentliche Seite aus dem live/-Verzeichnis des Shared Volumes.
|
||||
# SICHERHEIT: Kein Proxy auf die API, kein Zugriff auf den Manager.
|
||||
server {
|
||||
listen 80;
|
||||
root /usr/share/nginx/html/live;
|
||||
index index.html;
|
||||
charset utf-8;
|
||||
|
||||
# Alle Seiten: no-cache (Aenderungen sofort sichtbar nach Veroeffentlichen)
|
||||
location / {
|
||||
try_files $uri $uri/index.html =404;
|
||||
add_header Cache-Control "no-cache, must-revalidate";
|
||||
add_header X-Content-Type-Options "nosniff";
|
||||
add_header X-Frame-Options "SAMEORIGIN";
|
||||
}
|
||||
|
||||
# CSS/Bilder: kurze TTL (1 Tag)
|
||||
location ~* \.(css|png|jpg|jpeg|gif|ico|webp|svg)$ {
|
||||
try_files $uri =404;
|
||||
expires 1d;
|
||||
add_header Cache-Control "public, max-age=86400";
|
||||
}
|
||||
|
||||
# Kein Zugriff auf Staging-Verzeichnisse
|
||||
location ~ ^/_(staging_new|old)/ {
|
||||
return 403;
|
||||
}
|
||||
}
|
||||
37
deploy/truenas/vhost-snippet.conf
Normal file
37
deploy/truenas/vhost-snippet.conf
Normal file
@@ -0,0 +1,37 @@
|
||||
# GerbilManager — Externer nginx-Vhost fuer die oeffentliche Webseite (WEB-2)
|
||||
# In Julians bestehenden nginx-Reverse-Proxy einfuegen.
|
||||
# <DOMAIN> ersetzen sobald der Hostname feststeht (Julian liefert ihn).
|
||||
#
|
||||
# SICHERHEIT: Dieser Vhost zeigt NUR auf den publicsite-Container (Port 8081).
|
||||
# Der Manager (API + Frontend, Port 80) ist NICHT erreichbar von aussen —
|
||||
# er hat keine Authentifizierung und muss LAN-only bleiben.
|
||||
server {
|
||||
listen 80;
|
||||
server_name <DOMAIN>;
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8081;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
# Kein Buffering fuer kleine statische HTML-Seiten
|
||||
proxy_buffering off;
|
||||
}
|
||||
}
|
||||
|
||||
# Fuer HTTPS (empfohlen, z.B. per Let's Encrypt via certbot):
|
||||
# server {
|
||||
# listen 443 ssl;
|
||||
# server_name <DOMAIN>;
|
||||
# ssl_certificate /etc/letsencrypt/live/<DOMAIN>/fullchain.pem;
|
||||
# ssl_certificate_key /etc/letsencrypt/live/<DOMAIN>/privkey.pem;
|
||||
# location / {
|
||||
# proxy_pass http://127.0.0.1:8081;
|
||||
# proxy_set_header Host $host;
|
||||
# proxy_set_header X-Real-IP $remote_addr;
|
||||
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
# proxy_set_header X-Forwarded-Proto $scheme;
|
||||
# }
|
||||
# }
|
||||
327
docs/ops.md
327
docs/ops.md
@@ -1,4 +1,4 @@
|
||||
# GerbilManager — Betriebsanleitung (TrueNAS)
|
||||
# GerbilManager — Betriebsanleitung (TrueNAS SCALE Goldeye)
|
||||
|
||||
> Zielgruppe: Julian (Systemadministration) und Ehefrau (tägliche Nutzung).
|
||||
> Bookmark für die Ehefrau: **http://\<NAS-IP\>/** (z. B. http://truenas/)
|
||||
@@ -9,13 +9,12 @@
|
||||
|
||||
1. [Übersicht & Architektur](#1-übersicht--architektur)
|
||||
2. [Voraussetzungen](#2-voraussetzungen)
|
||||
3. [Erstinstallation auf TrueNAS](#3-erstinstallation-auf-truenas)
|
||||
3. [Erstinstallation auf TrueNAS Goldeye](#3-erstinstallation-auf-truenas-goldeye)
|
||||
4. [App starten / stoppen / aktualisieren](#4-app-starten--stoppen--aktualisieren)
|
||||
5. [Backup & Wiederherstellung](#5-backup--wiederherstellung)
|
||||
6. [ZFS-Snapshot-Schichtung](#6-zfs-snapshot-schichtung)
|
||||
7. [CI/CD via Gitea Actions](#7-cicd-via-gitea-actions)
|
||||
8. [Offene Fragen (bitte beantworten)](#8-offene-fragen)
|
||||
9. [Fehlerbehebung](#9-fehlerbehebung)
|
||||
8. [Fehlerbehebung](#8-fehlerbehebung)
|
||||
|
||||
---
|
||||
|
||||
@@ -23,7 +22,7 @@
|
||||
|
||||
```
|
||||
Browser / Handy
|
||||
| HTTP :80
|
||||
| HTTP :80 (oder PORT aus .env, z.B. 8080)
|
||||
v
|
||||
┌──────────────────┐
|
||||
│ frontend (nginx) │ statisches React-SPA + Reverse-Proxy
|
||||
@@ -40,9 +39,10 @@ Browser / Handy
|
||||
│ db (Postgres 17)│ │ backup (Sidecar) │
|
||||
└──────────────────┘ │ pg_dump + tar + cron │
|
||||
│ └──────────────────────┘
|
||||
└─ pgdata-Volume (NAS-Dataset)
|
||||
photos-Volume (NAS-Dataset)
|
||||
backups-Volume (NAS-Dataset)
|
||||
└─ pgdata-Volume → /mnt/JailStorage/DockerVolumes/gerbilmanager/pgdata
|
||||
photos-Volume → /mnt/JailStorage/DockerVolumes/gerbilmanager/photos
|
||||
backups-Volume → /mnt/JailStorage/DockerVolumes/gerbilmanager/backups
|
||||
keys-Volume → /mnt/JailStorage/DockerVolumes/gerbilmanager/keys
|
||||
```
|
||||
|
||||
**Einziger veröffentlichter Port:** `80` (konfigurierbar via `PORT` in `.env`).
|
||||
@@ -54,68 +54,107 @@ Alles andere läuft intern im Docker-Netz.
|
||||
|
||||
| Was | Details |
|
||||
|-----|---------|
|
||||
| TrueNAS SCALE | Electric Eel 24.10+ (native Docker Custom Apps) |
|
||||
| Gitea | http://truenas:13000 — Repository `Gulum/GerbilManager` |
|
||||
| Docker | bereits auf TrueNAS vorhanden (Custom Apps nutzen es) |
|
||||
| Datasets | Drei ZFS-Datasets anlegen (siehe Schritt 3) |
|
||||
| TrueNAS SCALE | **25.10.2.1 „Goldeye"** (native Docker Custom Apps) |
|
||||
| Container Registry | `git.rismer.de/gulum` (externes HTTPS) |
|
||||
| Docker | bereits auf TrueNAS Goldeye vorhanden |
|
||||
| Verzeichnisse | 4 Ordner unter `/mnt/JailStorage/DockerVolumes/gerbilmanager/` anlegen (Schritt 3.1) |
|
||||
|
||||
---
|
||||
|
||||
## 3. Erstinstallation auf TrueNAS
|
||||
## 3. Erstinstallation auf TrueNAS Goldeye
|
||||
|
||||
### 3.1 ZFS-Datasets anlegen
|
||||
### 3.1 Verzeichnisse anlegen und Berechtigungen setzen
|
||||
|
||||
In TrueNAS → **Datasets** → **Dataset hinzufügen** (je einmal wiederholen):
|
||||
|
||||
| Dataset-Name | Empfohlener Pfad | Verwendung |
|
||||
|---|---|---|
|
||||
| `gerbil/pgdata` | `/mnt/SSD/gerbil/pgdata` | Postgres-Datenbankdateien |
|
||||
| `gerbil/photos` | `/mnt/SSD/gerbil/photos` | Hochgeladene Tierfotos |
|
||||
| `gerbil/backups` | `/mnt/SSD/gerbil/backups` | Tägliche Backups |
|
||||
|
||||
> **Tipp:** Passe die Pool-Bezeichnung (`SSD`) an deinen tatsächlichen Pool an.
|
||||
|
||||
### 3.2 Repository klonen
|
||||
Öffne eine Shell auf der NAS (TrueNAS → System → Shell oder SSH):
|
||||
|
||||
```bash
|
||||
# SSH in TrueNAS oder lokale Shell
|
||||
git clone http://truenas:13000/Gulum/GerbilManager.git /opt/gerbilmanager
|
||||
# Vier Ordner anlegen
|
||||
mkdir -p /mnt/JailStorage/DockerVolumes/gerbilmanager/pgdata
|
||||
mkdir -p /mnt/JailStorage/DockerVolumes/gerbilmanager/photos
|
||||
mkdir -p /mnt/JailStorage/DockerVolumes/gerbilmanager/backups
|
||||
mkdir -p /mnt/JailStorage/DockerVolumes/gerbilmanager/keys
|
||||
|
||||
# Postgres-Container läuft als UID 999 (postgres) / GID 999 intern.
|
||||
# pgdata muss von UID 999 beschreibbar sein; postgres erzwingt chmod 0700.
|
||||
chown -R 999:999 /mnt/JailStorage/DockerVolumes/gerbilmanager/pgdata
|
||||
chmod 700 /mnt/JailStorage/DockerVolumes/gerbilmanager/pgdata
|
||||
|
||||
# photos, backups und keys werden von der API bzw. dem Sidecar beschrieben
|
||||
# (laufen als root im Container) — keine weiteren ACL-Anpassungen nötig.
|
||||
```
|
||||
|
||||
> **TrueNAS Dataset-ACL-Hinweis:** Falls `JailStorage` ein ZFS-Dataset mit NFSv4-ACLs ist,
|
||||
> und `chown` meldet „Operation not permitted": setze in TrueNAS → Datasets →
|
||||
> `JailStorage` → Berechtigungen → **ACL-Typ: POSIX** (oder nutze das UI-Formular
|
||||
> „Eigentümer: 999, Gruppe: 999" für das `pgdata`-Unterverzeichnis).
|
||||
|
||||
### 3.2 Registry-Login auf der NAS
|
||||
|
||||
```bash
|
||||
docker login git.rismer.de
|
||||
# Benutzername und Token/Passwort eingeben (Gitea-Account oder Access Token mit read:packages)
|
||||
```
|
||||
|
||||
Der Login wird unter `/root/.docker/config.json` gespeichert und bleibt nach Reboots erhalten.
|
||||
|
||||
### 3.3 Repository klonen
|
||||
|
||||
```bash
|
||||
git clone https://git.rismer.de/gulum/GerbilManager.git /opt/gerbilmanager
|
||||
cd /opt/gerbilmanager
|
||||
```
|
||||
|
||||
### 3.3 Konfiguration anlegen
|
||||
### 3.4 Konfiguration anlegen
|
||||
|
||||
```bash
|
||||
cp deploy/truenas/.env.example deploy/truenas/.env
|
||||
# Jetzt .env bearbeiten:
|
||||
nano deploy/truenas/.env
|
||||
```
|
||||
|
||||
Mindestens setzen:
|
||||
- `POSTGRES_PASSWORD` — sicheres Passwort (mind. 20 Zeichen)
|
||||
- `PGDATA_PATH`, `PHOTOS_PATH`, `BACKUPS_PATH` — tatsächliche Dataset-Pfade
|
||||
|
||||
### 3.4 Images bauen und App starten
|
||||
| Variable | Wert |
|
||||
|----------|------|
|
||||
| `POSTGRES_PASSWORD` | Sicheres Passwort (mind. 20 Zeichen, keine `"`) |
|
||||
| `AI__BaseUrl` | Gemini: `https://generativelanguage.googleapis.com/v1beta/openai` |
|
||||
| `AI__ApiKey` | Dein Gemini API-Key |
|
||||
| `AI__Model` | `gemini-2.0-flash` (oder `gemini-flash-latest`) |
|
||||
| `PORT` | `80` — falls Port 80 auf der NAS bereits belegt ist: **auf `8080` ändern** |
|
||||
|
||||
Die Pfad-Variablen (`PGDATA_PATH`, `PHOTOS_PATH`, etc.) sind bereits auf die Goldeye-Standardpfade
|
||||
vorbelegt und müssen nur geändert werden, wenn du einen anderen Pool nutzt.
|
||||
|
||||
### 3.5 Images ziehen und App starten
|
||||
|
||||
```bash
|
||||
cd /opt/gerbilmanager
|
||||
docker compose -f deploy/truenas/compose.yaml build
|
||||
docker compose -f deploy/truenas/compose.yaml pull
|
||||
docker compose -f deploy/truenas/compose.yaml up -d
|
||||
```
|
||||
|
||||
Erster Start dauert ca. 2–3 Minuten (Postgres-Init + EF-Migrationen).
|
||||
|
||||
### 3.5 Prüfen
|
||||
> **TrueNAS Goldeye Custom App (Alternative):**
|
||||
> Statt der Shell kann die App auch über TrueNAS → Apps → „Custom App installieren" →
|
||||
> „Install via YAML" deployt werden: compose-Inhalt einfügen, Volumes als Host-Pfade
|
||||
> konfigurieren. Die Shell-Methode ist einfacher und gibt mehr Kontrolle.
|
||||
|
||||
### 3.6 Verifikation
|
||||
|
||||
```bash
|
||||
# Alle Container laufen?
|
||||
# Alle 4 Container laufen?
|
||||
docker compose -f deploy/truenas/compose.yaml ps
|
||||
|
||||
# API-Healthcheck
|
||||
curl http://localhost/api/health
|
||||
# API-Healthcheck (erwartet: {"status":"Healthy"})
|
||||
curl -s http://localhost/api/health
|
||||
|
||||
# Webapp im Browser
|
||||
http://<NAS-IP>/
|
||||
# Tier-Gesamtanzahl prüfen (erwartet > 0 nach Import)
|
||||
curl -s "http://localhost/api/gerbils?pageSize=1" | grep -o '"totalCount":[0-9]*'
|
||||
|
||||
# API-Doku (Scalar) im Browser
|
||||
http://<NAS-IP>/scalar
|
||||
|
||||
# Foto-Upload: in der Webapp ein Tier öffnen → Foto hochladen → Foto erscheint
|
||||
```
|
||||
|
||||
---
|
||||
@@ -125,6 +164,7 @@ http://<NAS-IP>/
|
||||
### Starten
|
||||
|
||||
```bash
|
||||
cd /opt/gerbilmanager
|
||||
docker compose -f deploy/truenas/compose.yaml up -d
|
||||
```
|
||||
|
||||
@@ -134,26 +174,17 @@ docker compose -f deploy/truenas/compose.yaml up -d
|
||||
docker compose -f deploy/truenas/compose.yaml down
|
||||
```
|
||||
|
||||
### Aktualisieren (nach `git push` auf main)
|
||||
### Aktualisieren (nach CI-Push auf main)
|
||||
|
||||
```bash
|
||||
cd /opt/gerbilmanager
|
||||
git pull
|
||||
docker compose -f deploy/truenas/compose.yaml build
|
||||
docker compose -f deploy/truenas/compose.yaml pull
|
||||
docker compose -f deploy/truenas/compose.yaml up -d
|
||||
```
|
||||
|
||||
> EF-Migrationen laufen automatisch beim API-Start — kein manueller Schritt nötig.
|
||||
|
||||
### Mit Gitea CI (wenn Actions aktiviert)
|
||||
|
||||
Push auf `main` triggert automatisch Build → Test → Image-Push.
|
||||
Danach auf der NAS:
|
||||
```bash
|
||||
docker compose -f deploy/truenas/compose.yaml pull
|
||||
docker compose -f deploy/truenas/compose.yaml up -d
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Backup & Wiederherstellung
|
||||
@@ -165,12 +196,12 @@ Der `backup`-Sidecar-Container läuft dauerhaft und sichert täglich um **03:00
|
||||
- Komprimiertes Foto-Archiv als `.tar.gz`
|
||||
- Rotation: Backups älter als `BACKUP_KEEP_DAYS` (Standard: 7) werden gelöscht
|
||||
|
||||
Backups liegen unter: `${BACKUPS_PATH}/YYYY-MM-DD_HH-MM/`
|
||||
Backups liegen unter: `/mnt/JailStorage/DockerVolumes/gerbilmanager/backups/YYYY-MM-DD_HH-MM/`
|
||||
|
||||
```
|
||||
/mnt/SSD/gerbil/backups/
|
||||
/mnt/JailStorage/DockerVolumes/gerbilmanager/backups/
|
||||
2026-06-06_03-00/
|
||||
gerbilmanager_2026-06-06_03-00.sql (Datenbank)
|
||||
gerbilmanager_2026-06-06_03-00.sql (Datenbank-Dump, Klartext SQL)
|
||||
photos_2026-06-06_03-00.tar.gz (Fotos)
|
||||
backup.log (Protokoll)
|
||||
```
|
||||
@@ -184,52 +215,68 @@ docker compose -f deploy/truenas/compose.yaml exec backup /bin/sh /scripts/backu
|
||||
### Backup-Log prüfen
|
||||
|
||||
```bash
|
||||
tail -50 /mnt/SSD/gerbil/backups/backup.log
|
||||
tail -50 /mnt/JailStorage/DockerVolumes/gerbilmanager/backups/backup.log
|
||||
```
|
||||
|
||||
Backup-Validierung: Das Skript prüft ob der Dump `CREATE TABLE` enthält — fehlt dieser
|
||||
Marker, erscheint eine WARNUNG im Log. Größe 0 KB bedeutet Fehlschlag.
|
||||
|
||||
### Wiederherstellung — Runbook
|
||||
|
||||
> **WARNUNG:** Alle aktuellen Daten werden überschrieben!
|
||||
> **WARNUNG:** Alle aktuellen Datenbankdaten und Fotos werden überschrieben!
|
||||
|
||||
**Schritt 1:** App stoppen (optional, aber empfohlen)
|
||||
**Schritt 1:** API und Frontend stoppen (DB und backup-Sidecar laufen weiter)
|
||||
```bash
|
||||
docker compose -f deploy/truenas/compose.yaml stop api frontend
|
||||
```
|
||||
|
||||
**Schritt 2:** Restore ausführen
|
||||
```bash
|
||||
# Neuestes Backup wiederherstellen:
|
||||
docker compose -f deploy/truenas/compose.yaml exec backup \
|
||||
/bin/sh /scripts/restore.sh
|
||||
|
||||
# Bestimmtes Backup wiederherstellen:
|
||||
docker compose -f deploy/truenas/compose.yaml exec backup \
|
||||
/bin/sh /scripts/restore.sh 2026-06-05_03-00
|
||||
```bash
|
||||
# Neuestes Backup automatisch wählen und bestätigen:
|
||||
docker compose -f deploy/truenas/compose.yaml exec -T backup \
|
||||
/bin/sh /scripts/restore.sh latest -f
|
||||
|
||||
# Bestimmtes Backup (Datum aus Verzeichnisname):
|
||||
docker compose -f deploy/truenas/compose.yaml exec -T backup \
|
||||
/bin/sh /scripts/restore.sh 2026-06-06_03-00 -f
|
||||
```
|
||||
|
||||
Das Skript:
|
||||
1. Trennt alle offenen DB-Verbindungen
|
||||
2. Spielt den SQL-Dump mit `psql -h db -U postgres -d gerbilmanager < dump.sql` ein
|
||||
3. Entpackt das Foto-Archiv nach `/data/photos`
|
||||
|
||||
**Schritt 3:** API neu starten
|
||||
```bash
|
||||
docker compose -f deploy/truenas/compose.yaml start api frontend
|
||||
```
|
||||
|
||||
**Schritt 4:** Prüfen
|
||||
**Schritt 4 — Verifikation (Pflicht nach erstem Restore-Drill):**
|
||||
```bash
|
||||
curl http://localhost/api/color-varieties | grep -c '"id"'
|
||||
# Erwarteter Wert: 73
|
||||
# Tier-Anzahl prüfen
|
||||
curl -s "http://localhost/api/gerbils?pageSize=1" | grep -o '"totalCount":[0-9]*'
|
||||
|
||||
# ColorVariety-Anzahl (Stammdaten, erwartet: >= 60)
|
||||
curl -s http://localhost/api/color-varieties | python3 -c "import sys,json; print(len(json.load(sys.stdin)))"
|
||||
|
||||
# Foto stichprobenartig prüfen
|
||||
ls /mnt/JailStorage/DockerVolumes/gerbilmanager/photos/ | head -5
|
||||
```
|
||||
|
||||
### Restore-Nachweis (Round-Trip-Test)
|
||||
### Restore-Nachweis (Round-Trip-Test, lokal 2026-06-06)
|
||||
|
||||
Protokoll vom Test auf lokalem Aspire-Postgres (Vorgänger-Instanz, 2026-06-06 07:09):
|
||||
Protokoll vom getesteten Restore auf lokalem Aspire-Postgres:
|
||||
```
|
||||
73 ColorVarieties vorhanden
|
||||
→ DELETE 12 Zeilen → 61 verbleibend
|
||||
→ pg_restore eingespielt
|
||||
→ psql < dump.sql eingespielt
|
||||
→ 73 ColorVarieties bestätigt
|
||||
Exit-Code: 0
|
||||
```
|
||||
Die Container-Restore-Skripte nutzen dieselbe `psql < dump.sql` Logik.
|
||||
**Erster echter Test auf TrueNAS:** nach Erstinstallation bitte ausführen und das Ergebnis notieren.
|
||||
|
||||
**Erster TrueNAS-Restore-Drill:** nach Erstinstallation bitte ausführen und Tier-Anzahl
|
||||
notieren — beweist dass Backup + Restore auf dem NAS korrekt funktionieren.
|
||||
|
||||
---
|
||||
|
||||
@@ -240,15 +287,15 @@ Sie schützen vor versehentlichem Datenverlust auf Dataset-Ebene.
|
||||
|
||||
### Empfohlene Snapshot-Konfiguration
|
||||
|
||||
In TrueNAS → **Datasets** → Dataset auswählen → **Snapshots** → **Regelmäßige Snapshots**:
|
||||
In TrueNAS → **Datasets** → `JailStorage/DockerVolumes/gerbilmanager` → **Snapshots** → **Regelmäßige Snapshots**:
|
||||
|
||||
| Dataset | Häufigkeit | Aufbewahrung |
|
||||
|---------|-----------|--------------|
|
||||
| `gerbil/photos` | Stündlich | 24 Stunden |
|
||||
| `gerbil/photos` | Täglich | 30 Tage |
|
||||
| `gerbil/pgdata` | Stündlich | 24 Stunden |
|
||||
| `gerbil/pgdata` | Täglich | 30 Tage |
|
||||
| `gerbil/backups` | Täglich | 90 Tage |
|
||||
| Unterordner | Häufigkeit | Aufbewahrung |
|
||||
|-------------|-----------|--------------|
|
||||
| `.../photos` | Stündlich | 24 Stunden |
|
||||
| `.../photos` | Täglich | 30 Tage |
|
||||
| `.../pgdata` | Stündlich | 24 Stunden |
|
||||
| `.../pgdata` | Täglich | 30 Tage |
|
||||
| `.../backups` | Täglich | 90 Tage |
|
||||
|
||||
> **Hinweis:** `pgdata` enthält Live-Postgres-Dateien. ZFS-Snapshots davon sind crash-konsistent,
|
||||
> aber **nicht** application-konsistent — für einen sauberen DB-Restore immer den `pg_dump` verwenden,
|
||||
@@ -257,94 +304,93 @@ In TrueNAS → **Datasets** → Dataset auswählen → **Snapshots** → **Regel
|
||||
### Snapshot manuell erstellen (z. B. vor Update)
|
||||
|
||||
```bash
|
||||
# TrueNAS CLI
|
||||
zfs snapshot SSD/gerbil/photos@vor-update-$(date +%Y%m%d)
|
||||
zfs snapshot SSD/gerbil/backups@vor-update-$(date +%Y%m%d)
|
||||
# Pool-/Dataset-Name anpassen falls nötig
|
||||
zfs snapshot JailStorage/DockerVolumes/gerbilmanager/photos@vor-update-$(date +%Y%m%d)
|
||||
zfs snapshot JailStorage/DockerVolumes/gerbilmanager/backups@vor-update-$(date +%Y%m%d)
|
||||
```
|
||||
|
||||
### Aus ZFS-Snapshot wiederherstellen (Fotos)
|
||||
|
||||
```bash
|
||||
# Snapshot auflisten
|
||||
zfs list -t snapshot SSD/gerbil/photos
|
||||
# Snapshots auflisten
|
||||
zfs list -t snapshot JailStorage/DockerVolumes/gerbilmanager/photos
|
||||
|
||||
# Datei aus Snapshot kopieren
|
||||
cp /mnt/SSD/gerbil/photos/.zfs/snapshot/<NAME>/datei.jpg /mnt/SSD/gerbil/photos/
|
||||
# Einzelne Datei aus Snapshot kopieren
|
||||
cp /mnt/JailStorage/DockerVolumes/gerbilmanager/photos/.zfs/snapshot/<NAME>/datei.jpg \
|
||||
/mnt/JailStorage/DockerVolumes/gerbilmanager/photos/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. CI/CD via Gitea Actions
|
||||
|
||||
Der Workflow `.gitea/workflows/ci.yml` ist als **Entwurf vorhanden, aber inaktiv**.
|
||||
CI pusht Images nach Erfolg zu `git.rismer.de/gulum/gerbilmanager-api` und
|
||||
`git.rismer.de/gulum/gerbilmanager-frontend`.
|
||||
|
||||
### Aktivierung
|
||||
### Registry-Secrets in Gitea
|
||||
|
||||
1. **Gitea Actions aktivieren:**
|
||||
Gitea → Repository `GerbilManager` → Einstellungen → Actions → "Actions aktivieren"
|
||||
Gitea → Repository → Einstellungen → Secrets:
|
||||
|
||||
2. **Gitea Actions Runner installieren** (auf TrueNAS oder einem separaten Gerät):
|
||||
```bash
|
||||
# Gitea Runner Container (einfachste Variante für TrueNAS)
|
||||
docker run -d --name gitea-runner \
|
||||
-v /var/run/docker.sock:/var/run/docker.sock \
|
||||
-v /opt/gitea-runner:/data \
|
||||
-e GITEA_INSTANCE_URL=http://truenas:13000 \
|
||||
-e GITEA_RUNNER_REGISTRATION_TOKEN=<TOKEN> \
|
||||
gitea/act_runner:latest
|
||||
```
|
||||
Token: Gitea → Admin → Actions → Runner → "Runner hinzufügen"
|
||||
| Secret | Wert |
|
||||
|--------|------|
|
||||
| `REGISTRY_USER` | Gitea-Benutzername |
|
||||
| `REGISTRY_TOKEN` | Gitea Access Token mit `package:write` |
|
||||
|
||||
3. **Registry-Secrets konfigurieren:**
|
||||
Gitea → Repository → Einstellungen → Secrets:
|
||||
- `REGISTRY_USER` — dein Gitea-Benutzername
|
||||
- `REGISTRY_TOKEN` — Gitea Access Token mit `package:write`-Berechtigung
|
||||
### Update nach CI-Push
|
||||
|
||||
### Workflow nach Aktivierung
|
||||
|
||||
```
|
||||
git push origin main
|
||||
→ Gitea Actions: dotnet test + npm test + npm run build
|
||||
→ Bei Erfolg: docker build + push zu truenas:13000/gulum/
|
||||
→ Auf NAS: docker compose pull + up -d
|
||||
```bash
|
||||
# Auf der NAS nach erfolgreichem CI-Lauf:
|
||||
cd /opt/gerbilmanager
|
||||
git pull
|
||||
docker compose -f deploy/truenas/compose.yaml pull
|
||||
docker compose -f deploy/truenas/compose.yaml up -d
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. Offene Fragen
|
||||
|
||||
Bitte beantworte diese Fragen, damit das Setup fertiggestellt werden kann:
|
||||
|
||||
| # | Frage | Auswirkung |
|
||||
|---|-------|-----------|
|
||||
| 1 | **TrueNAS SCALE Version?** Electric Eel 24.10 hat native Docker Custom Apps. Ältere Versionen nutzen Kubernetes. | Bestimmt ob `docker compose` direkt läuft |
|
||||
| 2 | **Gitea Actions verfügbar/aktivierbar?** | CI/CD-Workflow aktiv oder nur manuell deployen |
|
||||
| 3 | **Eigener Postgres-Container (empfohlen) oder vorhandene NAS-Postgres-App?** | Isolation vs. geteilte Instanz |
|
||||
| 4 | **Genaue Dataset-Pfade?** Poolname und Pfad-Präfix | `.env`-Konfiguration |
|
||||
| 5 | **Port-Wahl?** Standard 80 — frei auf der NAS? | `PORT`-Wert in `.env` |
|
||||
|
||||
---
|
||||
|
||||
## 9. Fehlerbehebung
|
||||
## 8. Fehlerbehebung
|
||||
|
||||
### App startet nicht
|
||||
|
||||
```bash
|
||||
# Logs aller Container
|
||||
docker compose -f deploy/truenas/compose.yaml logs
|
||||
|
||||
# Logs eines bestimmten Containers
|
||||
docker compose -f deploy/truenas/compose.yaml logs api
|
||||
docker compose -f deploy/truenas/compose.yaml logs db
|
||||
```
|
||||
|
||||
### Port 80 belegt
|
||||
|
||||
Falls Port 80 vom TrueNAS-System selbst genutzt wird:
|
||||
|
||||
```bash
|
||||
# In deploy/truenas/.env:
|
||||
PORT=8080
|
||||
# Dann neu starten:
|
||||
docker compose -f deploy/truenas/compose.yaml up -d
|
||||
```
|
||||
|
||||
### Postgres startet nicht (Permission denied auf pgdata)
|
||||
|
||||
```bash
|
||||
# UID 999 muss Eigentümer des pgdata-Verzeichnisses sein:
|
||||
chown -R 999:999 /mnt/JailStorage/DockerVolumes/gerbilmanager/pgdata
|
||||
chmod 700 /mnt/JailStorage/DockerVolumes/gerbilmanager/pgdata
|
||||
docker compose -f deploy/truenas/compose.yaml restart db
|
||||
```
|
||||
|
||||
### Registry-Pull schlägt fehl
|
||||
|
||||
```bash
|
||||
# Neu einloggen:
|
||||
docker login git.rismer.de
|
||||
# Dann pull wiederholen:
|
||||
docker compose -f deploy/truenas/compose.yaml pull
|
||||
```
|
||||
|
||||
### Datenbank nicht erreichbar
|
||||
|
||||
```bash
|
||||
# DB-Container läuft?
|
||||
docker compose -f deploy/truenas/compose.yaml ps db
|
||||
|
||||
# Verbindung testen
|
||||
docker compose -f deploy/truenas/compose.yaml exec db \
|
||||
psql -U postgres -d gerbilmanager -c "\dt"
|
||||
```
|
||||
@@ -352,27 +398,16 @@ docker compose -f deploy/truenas/compose.yaml exec db \
|
||||
### Backup-Fehler
|
||||
|
||||
```bash
|
||||
# Backup-Log prüfen
|
||||
cat /mnt/SSD/gerbil/backups/backup.log | tail -30
|
||||
|
||||
# Backup manuell starten (mit Fehlerausgabe)
|
||||
docker compose -f deploy/truenas/compose.yaml exec backup \
|
||||
/bin/sh /scripts/backup.sh
|
||||
tail -50 /mnt/JailStorage/DockerVolumes/gerbilmanager/backups/backup.log
|
||||
docker compose -f deploy/truenas/compose.yaml exec backup /bin/sh /scripts/backup.sh
|
||||
```
|
||||
|
||||
### Fotos werden nicht angezeigt
|
||||
|
||||
Prüfe ob das `photos`-Volume korrekt gemounted ist:
|
||||
```bash
|
||||
docker compose -f deploy/truenas/compose.yaml exec api ls /data/photos
|
||||
```
|
||||
|
||||
### Container-Status zurücksetzen (Neustart)
|
||||
|
||||
```bash
|
||||
docker compose -f deploy/truenas/compose.yaml restart api
|
||||
```
|
||||
|
||||
### Kompletter Neustart (Daten bleiben erhalten)
|
||||
|
||||
```bash
|
||||
|
||||
136
docs/web-deploy.md
Normal file
136
docs/web-deploy.md
Normal file
@@ -0,0 +1,136 @@
|
||||
# GerbilManager — Oeffentliche Webseite (Self-Hosted, TrueNAS)
|
||||
|
||||
> **Zielgruppe:** Julian.
|
||||
> Die oeffentliche Seite (Jimdo-Ersatz) laeuft self-hosted auf der TrueNAS neben dem Manager.
|
||||
> Strato-Domain → DynDNS → IP → Julians nginx-Proxy → publicsite-Container (Port 8081).
|
||||
|
||||
---
|
||||
|
||||
## Architektur
|
||||
|
||||
```
|
||||
Internet
|
||||
| HTTPS/HTTP
|
||||
v
|
||||
Julians nginx-Reverse-Proxy (laeuft schon auf NAS)
|
||||
| proxy_pass http://127.0.0.1:8081
|
||||
v
|
||||
publicsite (nginx:alpine, Port 8081) ← liest nur: /usr/share/nginx/html/live/
|
||||
| (Shared Volume, read-only)
|
||||
| [POST /api/publish im Manager schreibt in dasselbe Volume]
|
||||
v
|
||||
api (.NET, Port 8080 intern) → schreibt: /data/publicsite/live/
|
||||
| (Shared Volume, read-write)
|
||||
v
|
||||
Manager (frontend-nginx, Port 80) ← LAN-only, NIE internet-exponiert
|
||||
```
|
||||
|
||||
**SICHERHEIT — harte Bedingung:**
|
||||
- Nur `publicsite` (Port 8081) wird ins Internet weitergeleitet.
|
||||
- Der Manager (API + Frontend, Port 80) hat KEINE Authentifizierung → LAN-only.
|
||||
- Der `publicsite`-nginx proxied NICHT auf die API — er serviert nur statisches HTML.
|
||||
|
||||
---
|
||||
|
||||
## Erstinstallation
|
||||
|
||||
### 1. Verzeichnis anlegen
|
||||
|
||||
```bash
|
||||
mkdir -p /mnt/JailStorage/DockerVolumes/gerbilmanager/publicsite
|
||||
```
|
||||
|
||||
Das Verzeichnis wird von der API beschrieben (laeuft als root im Container) — keine ACL-Aenderung noetig.
|
||||
Beim ersten `POST /api/publish` legt die API automatisch `live/` und `_staging_new/` darunter an.
|
||||
|
||||
### 2. .env erganzen
|
||||
|
||||
In `deploy/truenas/.env` hinzufuegen (oder aus `.env.example` uebernehmen):
|
||||
|
||||
```env
|
||||
PUBLICSITE_PATH=/mnt/JailStorage/DockerVolumes/gerbilmanager/publicsite
|
||||
PUBLICSITE_PORT=8081
|
||||
```
|
||||
|
||||
### 3. Compose-Stack neu starten
|
||||
|
||||
```bash
|
||||
cd /opt/gerbilmanager
|
||||
docker compose -f deploy/truenas/compose.yaml up -d
|
||||
```
|
||||
|
||||
Der neue `publicsite`-Container startet und serviert Port 8081.
|
||||
Solange noch nicht veroeffentlicht wurde, zeigt er einen 404 (live/-Verzeichnis leer).
|
||||
|
||||
### 4. Julians externen nginx konfigurieren
|
||||
|
||||
Inhalt von `deploy/truenas/vhost-snippet.conf` in den bestehenden nginx-Proxy einfuegen
|
||||
(als eigenen `server`-Block oder per `include`):
|
||||
|
||||
```bash
|
||||
# Auf der NAS, nginx-Konfigverzeichnis (z.B. /etc/nginx/conf.d/ oder sites-available):
|
||||
nano /etc/nginx/conf.d/gerbilmanager-public.conf
|
||||
# <DOMAIN> durch den tatsaechlichen Hostnamen ersetzen
|
||||
nginx -t && nginx -s reload
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Seite veroeffentlichen (Publish-Ablauf)
|
||||
|
||||
1. Im Manager einloggen (http://\<NAS-IP\>/)
|
||||
2. Navigiere zu **Webseite** → Inhalte bearbeiten → **Veroeffentlichen**
|
||||
3. Klick auf "Veroeffentlichen" loest `POST /api/publish` aus.
|
||||
|
||||
**Was passiert intern:**
|
||||
```
|
||||
POST /api/publish
|
||||
→ API baut SiteSnapshot aus DB (alle Published-Seiten)
|
||||
→ SiteRenderer rendert Snapshot → HTML-Dateien (path → content Map)
|
||||
→ Schreibt Dateien nach /data/publicsite/_staging_new/
|
||||
→ Atomic Swap: _staging_new/ → live/ (rename = ein Syscall, nie halb-geschrieben)
|
||||
→ publicsite-nginx serviert beim naechsten Request sofort den neuen Stand
|
||||
→ Kein Container-Restart, kein Image-Rebuild, kein CI
|
||||
Response: { "filesPublished": N }
|
||||
```
|
||||
|
||||
**Endergebnis:** publicsite-nginx liest sofort den neuen Stand aus `live/`.
|
||||
|
||||
---
|
||||
|
||||
## Verifikation
|
||||
|
||||
```bash
|
||||
# publicsite-Container laeuft?
|
||||
docker compose -f deploy/truenas/compose.yaml ps publicsite
|
||||
|
||||
# Seite lokal abrufbar?
|
||||
curl -s http://localhost:8081/ | head -5
|
||||
|
||||
# live/-Verzeichnis gefuellt?
|
||||
ls /mnt/JailStorage/DockerVolumes/gerbilmanager/publicsite/live/
|
||||
|
||||
# Oeffentlich erreichbar (nach DNS-Propagation)?
|
||||
curl -s http://<DOMAIN>/ | grep "Kleine Chaoten"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Sicherheitstrennung (Pflichtcheck)
|
||||
|
||||
| Was | Port | Internet-exponiert? |
|
||||
|-----|------|---------------------|
|
||||
| Manager (api + frontend) | 80 | **NEIN** — LAN-only |
|
||||
| Oeffentliche Seite (publicsite) | 8081 | Ja, via Julians nginx-Proxy |
|
||||
| API-Doku (Scalar) | 80/scalar | **NEIN** — LAN-only |
|
||||
|
||||
Der Manager-nginx (gerbilmanager-frontend, Port 80) und die API (Port 8080 intern)
|
||||
sind NICHT in `vhost-snippet.conf` eingetragen und NICHT in Julians externem Proxy konfiguriert.
|
||||
Sie sind ausschliesslich im Heimnetz erreichbar.
|
||||
|
||||
---
|
||||
|
||||
## Hostname noch ausstehend
|
||||
|
||||
`<DOMAIN>` in `deploy/truenas/vhost-snippet.conf` ist ein Platzhalter.
|
||||
Julian nennt den Hostnamen/Subdomain → ersetzen und nginx neu laden.
|
||||
@@ -1,5 +1,5 @@
|
||||
/** BESTAND-FILTER: die Tiere-Liste zeigt standardmäßig nur den eigenen Bestand. */
|
||||
import { de, expect, gotoSection, openFilterPanel, skipUnlessMock, test } from './fixtures'
|
||||
import { de, expect, gotoSection, skipUnlessMock, test } from './fixtures'
|
||||
|
||||
const t = de.pages.gerbils
|
||||
|
||||
@@ -19,9 +19,8 @@ test('Toggle „Externe Ahnen einblenden” zeigt externe Tiere mit Extern-Marki
|
||||
await gotoSection(page, de.nav.gerbils)
|
||||
await expect(page.locator('.gerbil-row', { hasText: 'Krümel' })).toBeVisible()
|
||||
|
||||
// UX-MOBILE-1: Checkbox liegt im Filter-Drawer — auf Mobil erst öffnen.
|
||||
await openFilterPanel(page)
|
||||
await page.getByRole('checkbox', { name: t.filters.showExternal }).check()
|
||||
// DESIGN (Rennmaus Filter): „Externe Ahnen" ist ein Toggle-Chip (Button), kein Checkbox.
|
||||
await page.getByRole('button', { name: t.filters.showExternalShort }).click()
|
||||
|
||||
const maxRow = page.locator('.gerbil-row', { hasText: 'Max' })
|
||||
await expect(maxRow).toBeVisible()
|
||||
|
||||
79
gerbil-manager-web/e2e/farbschlag-sync.spec.ts
Normal file
79
gerbil-manager-web/e2e/farbschlag-sync.spec.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
/** FARBSCHLAG-GENOTYPE-SYNC: Bidirektionale Sync im Tier-Formular. */
|
||||
import { de, expect, skipUnlessMock, test } from './fixtures'
|
||||
|
||||
const t = de.pages.gerbils
|
||||
|
||||
test('Farbschlag-Auswahl füllt Gencode automatisch aus', async ({ page }) => {
|
||||
skipUnlessMock()
|
||||
await page.goto('/rennmaeuse/neu')
|
||||
|
||||
const farbschlagSelect = page
|
||||
.locator('label.field', { has: page.locator(`span:text-is("${t.fields.colorVariety}")`) })
|
||||
.locator('select')
|
||||
const genotypeInput = page
|
||||
.locator('label.field', { has: page.locator(`span:text-is("${t.fields.genotype}")`) })
|
||||
.locator('input')
|
||||
|
||||
// Vor der Auswahl ist das Gencode-Feld leer.
|
||||
await expect(genotypeInput).toHaveValue('')
|
||||
|
||||
// 'Agouti' wählen → Gencode wird automatisch befüllt.
|
||||
await farbschlagSelect.selectOption({ label: 'Agouti' })
|
||||
await expect(genotypeInput).toHaveValue('AA CC DD EE GG PP spsp rere')
|
||||
})
|
||||
|
||||
test('Gencode-Eingabe aktualisiert die Farbschlag-Auswahl', async ({ page }) => {
|
||||
skipUnlessMock()
|
||||
await page.goto('/rennmaeuse/neu')
|
||||
|
||||
const farbschlagSelect = page
|
||||
.locator('label.field', { has: page.locator(`span:text-is("${t.fields.colorVariety}")`) })
|
||||
.locator('select')
|
||||
const genotypeInput = page
|
||||
.locator('label.field', { has: page.locator(`span:text-is("${t.fields.genotype}")`) })
|
||||
.locator('input')
|
||||
|
||||
// Gencode für Schwarz eintippen → Farbschlag-Select springt auf 'Schwarz'.
|
||||
await genotypeInput.fill('aa CC DD EE GG PP spsp rere')
|
||||
await expect(farbschlagSelect).toHaveValue('cv-schwarz')
|
||||
})
|
||||
|
||||
test('Gencode ohne passende Farbschlag-Auswahl leert das Dropdown', async ({ page }) => {
|
||||
skipUnlessMock()
|
||||
await page.goto('/rennmaeuse/neu')
|
||||
|
||||
const farbschlagSelect = page
|
||||
.locator('label.field', { has: page.locator(`span:text-is("${t.fields.colorVariety}")`) })
|
||||
.locator('select')
|
||||
const genotypeInput = page
|
||||
.locator('label.field', { has: page.locator(`span:text-is("${t.fields.genotype}")`) })
|
||||
.locator('input')
|
||||
|
||||
// Zuerst eine bekannte Farbe wählen, damit das Select belegt ist.
|
||||
await farbschlagSelect.selectOption({ label: 'Agouti' })
|
||||
await expect(farbschlagSelect).not.toHaveValue('')
|
||||
|
||||
// Marder-Genotyp: bekannte Farbe im Engine, aber NICHT im Mock-Dropdown
|
||||
// → Select wird auf '' (kein Eintrag) zurückgesetzt.
|
||||
await genotypeInput.fill('aa cchmcchm DD EE GG PP spsp rere')
|
||||
await expect(farbschlagSelect).toHaveValue('')
|
||||
})
|
||||
|
||||
test('Unbekannter Genotyp leert das Farbschlag-Dropdown (Unbekannt-Fall)', async ({ page }) => {
|
||||
skipUnlessMock()
|
||||
await page.goto('/rennmaeuse/neu')
|
||||
|
||||
const farbschlagSelect = page
|
||||
.locator('label.field', { has: page.locator(`span:text-is("${t.fields.colorVariety}")`) })
|
||||
.locator('select')
|
||||
const genotypeInput = page
|
||||
.locator('label.field', { has: page.locator(`span:text-is("${t.fields.genotype}")`) })
|
||||
.locator('input')
|
||||
|
||||
await farbschlagSelect.selectOption({ label: 'Blau' })
|
||||
await expect(farbschlagSelect).not.toHaveValue('')
|
||||
|
||||
// aa CC dd EE gg pp → Unbekannter Farbschlag (nicht im Katalog) → Select leert sich.
|
||||
await genotypeInput.fill('aa CC dd EE gg pp spsp rere')
|
||||
await expect(farbschlagSelect).toHaveValue('')
|
||||
})
|
||||
@@ -1,85 +1,54 @@
|
||||
/**
|
||||
* UX-MOBILE-1: FilterPanel — einklappbare Filter auf Smartphone, inline auf Desktop.
|
||||
* DESIGN (Rennmaus Filter.html): Quick-Chips-Filter der Rennmäuse-Liste.
|
||||
*
|
||||
* Telefon (390px): Filter-Button sichtbar, Drawer eingeklappt; Tippen öffnet/schliesst.
|
||||
* Desktop (1280px): Alle Controls direkt sichtbar, kein Toggle-Button.
|
||||
* Eine Pillen-Reihe (Status / Geschlecht / Farbschlag / Herkunft) öffnet je ein
|
||||
* Bottom-Sheet mit Mehrfachauswahl; gewählte Werte erscheinen als entfernbare
|
||||
* Chips, „Alle löschen" setzt zurück. Mobile-first; identisches Verhalten auf Desktop.
|
||||
*/
|
||||
import { de, expect, gotoSection, skipUnlessMock, test } from './fixtures'
|
||||
import { de, expect, gotoSection, selectListFilter, skipUnlessMock, test } from './fixtures'
|
||||
|
||||
const t = de.pages.gerbils
|
||||
|
||||
test.describe('FilterPanel – Rennmäuse-Liste', () => {
|
||||
test('Phone: Filter-Drawer standardmäßig eingeklappt, Toggle-Button sichtbar', async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
test.describe('Quick-Chips-Filter – Rennmäuse-Liste', () => {
|
||||
test('Kategorie-Pillen sind sichtbar', async ({ page }) => {
|
||||
skipUnlessMock()
|
||||
if (testInfo.project.name !== 'phone') return
|
||||
|
||||
await gotoSection(page, de.nav.gerbils)
|
||||
await expect(page.getByRole('heading', { name: t.title, exact: true })).toBeVisible()
|
||||
|
||||
// Toggle-Button sichtbar.
|
||||
const toggle = page.locator('.filter-panel__toggle')
|
||||
await expect(toggle).toBeVisible()
|
||||
|
||||
// Status-Beschriftung im Drawer ist noch verborgen.
|
||||
await expect(page.getByText(t.filters.status, { exact: true }).first()).not.toBeVisible()
|
||||
const quickrow = page.locator('.rmf-quickrow')
|
||||
await expect(quickrow.getByRole('button', { name: t.filters.status })).toBeVisible()
|
||||
await expect(quickrow.getByRole('button', { name: t.filters.gender })).toBeVisible()
|
||||
await expect(quickrow.getByRole('button', { name: t.filters.colorVariety })).toBeVisible()
|
||||
await expect(quickrow.getByRole('button', { name: t.fields.origin })).toBeVisible()
|
||||
})
|
||||
|
||||
test('Phone: Toggle öffnet und schließt den Filter-Drawer', async ({
|
||||
test('Mehrfachauswahl erzeugt entfernbare Chips, „Alle löschen" setzt zurück', async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
}) => {
|
||||
skipUnlessMock()
|
||||
if (testInfo.project.name !== 'phone') return
|
||||
|
||||
await gotoSection(page, de.nav.gerbils)
|
||||
const toggle = page.locator('.filter-panel__toggle')
|
||||
|
||||
// Öffnen → Status-Feld wird sichtbar.
|
||||
await toggle.click()
|
||||
await expect(page.getByText(t.filters.status, { exact: true }).first()).toBeVisible()
|
||||
// Default: Zucht-Chip ist aktiv.
|
||||
await expect(page.locator('.rmf-chip-val', { hasText: t.statusLabels.Breeding })).toBeVisible()
|
||||
|
||||
// Schließen → wieder verborgen.
|
||||
await toggle.click()
|
||||
await expect(page.getByText(t.filters.status, { exact: true }).first()).not.toBeVisible()
|
||||
// Geschlecht = männlich über das Sheet wählen → zweiter Chip erscheint.
|
||||
await selectListFilter(page, t.filters.gender, t.genderLabels.male)
|
||||
await expect(page.locator('.rmf-chip-val', { hasText: t.genderLabels.male })).toBeVisible()
|
||||
|
||||
// „Alle löschen" entfernt sämtliche Chips.
|
||||
await page.getByRole('button', { name: de.filterBar.clearAll }).click()
|
||||
await expect(page.locator('.rmf-chip')).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('Phone: Badge zählt aktive Filter korrekt', async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
test('Einzelner Chip lässt sich per Klick entfernen', async ({ page }) => {
|
||||
skipUnlessMock()
|
||||
if (testInfo.project.name !== 'phone') return
|
||||
|
||||
await gotoSection(page, de.nav.gerbils)
|
||||
const toggle = page.locator('.filter-panel__toggle')
|
||||
|
||||
// Initial: Status='Active' ist Default → Badge zeigt kein „(N)".
|
||||
await expect(toggle).toHaveText('Filter')
|
||||
|
||||
// Filter-Drawer öffnen und Geschlecht setzen → 1 aktiver Filter.
|
||||
await toggle.click()
|
||||
await page.locator('.filter-panel__drawer select').nth(1).selectOption('male')
|
||||
await expect(toggle).toHaveText('Filter (1)')
|
||||
|
||||
// Zurücksetzen → Badge weg.
|
||||
await page.getByRole('button', { name: de.filterPanel.resetButton }).click()
|
||||
await expect(toggle).toHaveText('Filter')
|
||||
})
|
||||
|
||||
test('Desktop: Toggle-Button nicht sichtbar, alle Controls inline', async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
skipUnlessMock()
|
||||
if (testInfo.project.name !== 'desktop') return
|
||||
|
||||
await gotoSection(page, de.nav.gerbils)
|
||||
await expect(page.getByRole('heading', { name: t.title, exact: true })).toBeVisible()
|
||||
|
||||
// Kein Toggle-Button auf Desktop (display:none via Media Query).
|
||||
const toggle = page.locator('.filter-panel__toggle')
|
||||
await expect(toggle).toBeHidden()
|
||||
|
||||
// Status-Beschriftung direkt sichtbar.
|
||||
await expect(page.getByText(t.filters.status, { exact: true }).first()).toBeVisible()
|
||||
const breedingChip = page.locator('.rmf-chip', {
|
||||
has: page.locator('.rmf-chip-val', { hasText: t.statusLabels.Breeding }),
|
||||
})
|
||||
await expect(breedingChip).toBeVisible()
|
||||
await breedingChip.click()
|
||||
await expect(breedingChip).toHaveCount(0)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -86,6 +86,18 @@ export async function openFilterPanel(page: Page) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* DESIGN (Rennmaus Filter): wählt einen Wert im Quick-Chips-Filter der Rennmäuse-Liste.
|
||||
* Öffnet das Bottom-Sheet der Kategorie, hakt die Option an und schließt mit „Fertig".
|
||||
*/
|
||||
export async function selectListFilter(page: Page, categoryLabel: string, optionLabel: string) {
|
||||
// Pille der Kategorie in der Quick-Chips-Reihe öffnen (nicht den aktiven Chip treffen).
|
||||
await page.locator('.rmf-quickrow').getByRole('button', { name: categoryLabel }).click()
|
||||
const sheet = page.getByRole('dialog', { name: categoryLabel })
|
||||
await sheet.getByRole('button', { name: optionLabel, exact: true }).click()
|
||||
await sheet.getByRole('button', { name: de.filterBar.done }).click()
|
||||
}
|
||||
|
||||
/** Eindeutiger Name für LIVE-taugliche Create-Flows. */
|
||||
export const uniqueName = (prefix: string) =>
|
||||
`${prefix} E2E ${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`
|
||||
|
||||
45
gerbil-manager-web/e2e/juvenile-details.spec.ts
Normal file
45
gerbil-manager-web/e2e/juvenile-details.spec.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
/** LITTER-JUVENILE-DETAILS + JUVENILE-AVATARS: Jungtier-Felder und Foto-Avatare im Wurf-Detail. */
|
||||
import { de, expect, skipUnlessMock, test } from './fixtures'
|
||||
|
||||
const t = de.pages.litters
|
||||
|
||||
test('Jungtier-Liste zeigt Farbschlag, Abgabedatum, Abnehmer, Todesdatum und Todesursache', async ({
|
||||
page,
|
||||
}) => {
|
||||
skipUnlessMock()
|
||||
await page.goto('/wuerfe/w-kruemel')
|
||||
await expect(page.getByRole('heading', { name: 'Wurf K' })).toBeVisible()
|
||||
|
||||
// Krümel: Active, colorVarietyId cv-agouti → Farbschlag 'Agouti'
|
||||
const kruemelCard = page.getByRole('link', { name: /Krümel/ })
|
||||
await expect(kruemelCard).toBeVisible()
|
||||
await expect(kruemelCard).toContainText(`${t.detail.juvenileFields.colorVariety}: Agouti`)
|
||||
|
||||
// Pippa: GivenAway, Gold, goHomeDate 2025-05-01, Abnehmer Familie Huber
|
||||
const pippaCard = page.getByRole('link', { name: /Pippa/ })
|
||||
await expect(pippaCard).toBeVisible()
|
||||
await expect(pippaCard).toContainText(`${t.detail.juvenileFields.colorVariety}: Gold`)
|
||||
await expect(pippaCard).toContainText(t.detail.juvenileFields.goHomeDate)
|
||||
await expect(pippaCard).toContainText(`${t.detail.juvenileFields.receiver}: Familie Huber`)
|
||||
|
||||
// Benny: Deceased, no colorVarietyId, dateOfDeath + causeOfDeath
|
||||
const bennyCard = page.getByRole('link', { name: /Benny/ })
|
||||
await expect(bennyCard).toBeVisible()
|
||||
await expect(bennyCard).toContainText(t.detail.juvenileFields.dateOfDeath)
|
||||
await expect(bennyCard).toContainText(`${t.detail.juvenileFields.causeOfDeath}: Altersschwäche`)
|
||||
})
|
||||
|
||||
test('JUVENILE-AVATARS: Pippa zeigt Foto-Avatar, Benny zeigt GerbilIcon', async ({ page }) => {
|
||||
skipUnlessMock()
|
||||
await page.goto('/wuerfe/w-kruemel')
|
||||
await expect(page.getByRole('heading', { name: 'Wurf K' })).toBeVisible()
|
||||
|
||||
// Pippa hat profilePhotoUrl → <img.juvenile-photo__avatar> sichtbar
|
||||
const pippaCard = page.getByRole('link', { name: /Pippa/ })
|
||||
await expect(pippaCard.locator('.juvenile-photo__avatar')).toBeVisible()
|
||||
|
||||
// Benny hat kein Foto → kein img, SVG-Icon (GerbilIcon) sichtbar
|
||||
const bennyCard = page.getByRole('link', { name: /Benny/ })
|
||||
await expect(bennyCard.locator('.juvenile-photo__avatar')).not.toBeVisible()
|
||||
await expect(bennyCard.locator('svg')).toBeVisible()
|
||||
})
|
||||
46
gerbil-manager-web/e2e/litter-mortality.spec.ts
Normal file
46
gerbil-manager-web/e2e/litter-mortality.spec.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
/** LITTER-MORTALITY: deathsWithin8Weeks im Wurf-Formular und -Detail. */
|
||||
import { de, expect, skipUnlessMock, test, uniqueName } from './fixtures'
|
||||
|
||||
const t = de.pages.litters
|
||||
|
||||
test('Wurf-Detail zeigt Frühverluste wenn gesetzt', async ({ page }) => {
|
||||
skipUnlessMock()
|
||||
await page.goto('/wuerfe/w-kruemel')
|
||||
await expect(page.getByRole('heading', { name: 'Wurf K' })).toBeVisible()
|
||||
// Frühverluste-Zeile im def-list: Label + Wert '1'
|
||||
const mortalityRow = page.locator('.def-row', {
|
||||
has: page.locator('dt', { hasText: t.fields.deathsWithin8Weeks }),
|
||||
})
|
||||
await expect(mortalityRow).toBeVisible()
|
||||
await expect(mortalityRow.locator('dd')).toHaveText('1')
|
||||
})
|
||||
|
||||
test('Wurf-Formular speichert Frühverluste und zeigt sie im Detail', async ({ page }) => {
|
||||
skipUnlessMock()
|
||||
const name = uniqueName('WurfM')
|
||||
await page.goto('/wuerfe/neu')
|
||||
await page.getByLabel(`${t.fields.name} *`).fill(name)
|
||||
await page.getByLabel(`${t.fields.date} *`).fill('2026-01-10')
|
||||
|
||||
// Frühverluste eingeben
|
||||
await page.getByLabel(t.fields.deathsWithin8Weeks).fill('2')
|
||||
await expect(page.getByText(t.validation.deathsExceedTotalBorn)).not.toBeVisible()
|
||||
|
||||
await page.getByRole('button', { name: t.form.save, exact: true }).click()
|
||||
await expect(page.getByRole('heading', { name })).toBeVisible()
|
||||
// Frühverluste-Zeile im Detail
|
||||
const mortalityRow = page.locator('.def-row', {
|
||||
has: page.locator('dt', { hasText: t.fields.deathsWithin8Weeks }),
|
||||
})
|
||||
await expect(mortalityRow).toBeVisible()
|
||||
await expect(mortalityRow.locator('dd')).toHaveText('2')
|
||||
})
|
||||
|
||||
test('Frühverluste > Wurfstärke zeigt Warnmeldung', async ({ page }) => {
|
||||
skipUnlessMock()
|
||||
await page.goto('/wuerfe/neu')
|
||||
|
||||
await page.getByLabel(t.fields.totalBorn).fill('3')
|
||||
await page.getByLabel(t.fields.deathsWithin8Weeks).fill('5')
|
||||
await expect(page.getByText(t.validation.deathsExceedTotalBorn)).toBeVisible()
|
||||
})
|
||||
@@ -91,7 +91,7 @@ function gerbil(
|
||||
id,
|
||||
name,
|
||||
gender,
|
||||
status: 'Active',
|
||||
status: 'Breeding',
|
||||
dateOfBirth,
|
||||
dateOfDeath: null,
|
||||
causeOfDeath: null,
|
||||
@@ -108,6 +108,7 @@ function gerbil(
|
||||
notes: null,
|
||||
// BESTAND-FILTER: default = eigener Bestand; einzelne externe Ahnen unten gesetzt.
|
||||
isResident: true,
|
||||
profilePhotoUrl: null,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,7 +121,7 @@ export function seedDb(): MockDb {
|
||||
originContactId: 'con-meier',
|
||||
originBreeder: 'Clan-Kleine-Chaoten',
|
||||
},
|
||||
{ ...gerbil('fridolin', 'Fridolin', 'male', '2023-05-01', 'w-fridolin', 'cv-schwarz', 'aa CC DD EE GG PP spsp rere'), enclosureId: 'enc-gross', originBreeder: 'Zoohandlung Meier' },
|
||||
{ ...gerbil('fridolin', 'Fridolin', 'male', '2023-05-01', 'w-fridolin', 'cv-schwarz', 'aa CC DD EE GG PP spsp rere'), enclosureId: 'enc-gross', originBreeder: 'Zoohandlung Meier', profilePhotoUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==' },
|
||||
gerbil('luna', 'Luna', 'female', '2023-08-15', 'w-luna', 'cv-gold', 'AA CC DD EE GG pp spsp rere'),
|
||||
gerbil('balu', 'Balu', 'male', '2021-04-20', 'w-balu', 'cv-agouti'),
|
||||
gerbil('maja', 'Maja', 'female', '2021-06-11', null, 'cv-schwarz-schecke', 'aa CC DD EE GG PP Spsp rere'),
|
||||
@@ -151,12 +152,27 @@ export function seedDb(): MockDb {
|
||||
enclosureId: 'enc-leer',
|
||||
notes: 'neugieriger Entdecker',
|
||||
},
|
||||
// LITTER-JUVENILE-DETAILS: Jungtiere für Wurf K mit Zusatzinfos.
|
||||
// JUVENILE-AVATARS: Pippa hat profilePhotoUrl (1×1-PNG data-URI) → Avatar-Img sichtbar.
|
||||
{
|
||||
...gerbil('pup-abgabe', 'Pippa', 'female', '2025-03-12', 'w-kruemel', 'cv-gold'),
|
||||
status: 'GivenAway' as const,
|
||||
goHomeDate: '2025-05-01',
|
||||
receiverContactId: 'con-huber',
|
||||
profilePhotoUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
|
||||
},
|
||||
{
|
||||
...gerbil('pup-verstorben', 'Benny', 'male', '2025-03-12', 'w-kruemel', null),
|
||||
status: 'Deceased' as const,
|
||||
dateOfDeath: '2025-04-15',
|
||||
causeOfDeath: 'Altersschwäche',
|
||||
},
|
||||
// UI-POLISH-1: Import-Stub ohne Namen — testet den '(ohne Namen)'-Platzhalter in Liste + Detail.
|
||||
gerbil('nameless-stub', '', 'male', '2023-01-01', null, null),
|
||||
]
|
||||
|
||||
const litters: Litter[] = [
|
||||
{ id: 'w-kruemel', name: 'Wurf K', date: '2025-03-12', totalBorn: 5, expectedGoHomeDate: '2025-04-16', notes: null, fatherId: 'fridolin', motherId: 'luna' },
|
||||
{ id: 'w-kruemel', name: 'Wurf K', date: '2025-03-12', totalBorn: 5, expectedGoHomeDate: '2025-04-16', notes: null, fatherId: 'fridolin', motherId: 'luna', deathsWithin8Weeks: 1 },
|
||||
{ id: 'w-fridolin', name: 'Wurf F', date: '2023-05-01', totalBorn: 4, expectedGoHomeDate: null, notes: null, fatherId: 'balu', motherId: 'maja' },
|
||||
{ id: 'w-luna', name: 'Wurf L', date: '2023-08-15', totalBorn: 6, expectedGoHomeDate: null, notes: null, fatherId: 'karlsson', motherId: 'smilla' },
|
||||
{ id: 'w-balu', name: 'Wurf B', date: '2021-04-20', totalBorn: 3, expectedGoHomeDate: null, notes: null, fatherId: 'anton', motherId: 'greta' },
|
||||
|
||||
@@ -3,7 +3,7 @@ import { de, expect, gotoSection, test } from './fixtures'
|
||||
|
||||
test('alle Bereiche sind über die Navigation erreichbar', async ({ page }) => {
|
||||
await page.goto('/')
|
||||
await expect(page.getByRole('heading', { name: de.app.title })).toBeVisible()
|
||||
// DESIGN: the top "Rennmaus-Manager" title bar was removed — the page heading remains.
|
||||
await expect(page.getByRole('heading', { name: de.pages.gerbils.title, exact: true })).toBeVisible()
|
||||
|
||||
await gotoSection(page, de.nav.gerbils)
|
||||
|
||||
@@ -79,3 +79,95 @@ test('Namenloser Ahne zeigt Platzhalter in der Stammbaum-Karte (UI-POLISH-2)', a
|
||||
// Karte selbst zeigt '(ohne Namen)' statt leer
|
||||
await expect(page.locator('.pedigree-card__nametext')).toHaveText(de.pages.gerbils.nameless)
|
||||
})
|
||||
|
||||
test('Mini-Legende zeigt alle drei Interaktionshinweise (STAMMBAUM-EXPAND)', async ({ page }) => {
|
||||
skipUnlessMock()
|
||||
await page.goto('/rennmaeuse/kruemel/stammbaum')
|
||||
await expect(page.locator('.pedigree-card').first()).toBeVisible()
|
||||
|
||||
const hints = page.locator('.stammbaum-hints')
|
||||
await expect(hints).toBeVisible()
|
||||
await expect(hints).toContainText(t.tapHint)
|
||||
await expect(hints).toContainText(t.hintName)
|
||||
await expect(hints).toContainText(t.hintExpand)
|
||||
})
|
||||
|
||||
test('+-Knopf ist sichtbar und lädt weitere Vorfahren nach (STAMMBAUM-EXPAND)', async ({ page }) => {
|
||||
skipUnlessMock()
|
||||
await page.goto('/rennmaeuse/kruemel/stammbaum')
|
||||
await expect(page.locator('.pedigree-card').first()).toBeVisible()
|
||||
|
||||
// Einpassen, damit die 4. Generation (Emil mit +) im Viewport liegt.
|
||||
const fit = page.getByRole('button', { name: t.zoomFit })
|
||||
if (await fit.isVisible()) await fit.click()
|
||||
await page.waitForTimeout(600)
|
||||
|
||||
// +-Button muss an der Tiefengrenze erscheinen (Emil hat litterId w-emil).
|
||||
const expandBtn = page.getByRole('button', { name: t.expand }).first()
|
||||
await expect(expandBtn).toBeVisible()
|
||||
|
||||
// Klick auf +: Emil wird aufgeklappt → Max (sein Vater) taucht als Link auf.
|
||||
await expandBtn.click({ force: true })
|
||||
await expect(page.getByRole('link', { name: 'Max' })).toBeVisible({ timeout: 8000 })
|
||||
})
|
||||
|
||||
test('Würfe-Panel zeigt Würfe des Wurzeltiers + Link öffnet Wurf (STAMMBAUM-LITTERS)', async ({ page }) => {
|
||||
skipUnlessMock()
|
||||
// Fridolin ist Vater von Wurf K (5 Junge) — Panel muss erscheinen.
|
||||
await page.goto('/rennmaeuse/fridolin/stammbaum')
|
||||
await expect(page.locator('.pedigree-card').first()).toBeVisible()
|
||||
|
||||
const panel = page.locator('.stammbaum-litters-panel')
|
||||
await expect(panel).toBeVisible()
|
||||
await expect(panel).toContainText(t.littersTitle)
|
||||
await expect(panel).toContainText('Wurf K')
|
||||
await expect(panel).toContainText('5')
|
||||
|
||||
// Link-Klick → Wurf-Detailseite
|
||||
const wurfLink = panel.getByRole('link', { name: /Wurf K/ })
|
||||
await expect(wurfLink).toBeVisible()
|
||||
await wurfLink.click()
|
||||
await expect(page).toHaveURL(/\/wuerfe\/w-kruemel/)
|
||||
})
|
||||
|
||||
test('Kein Würfe-Panel wenn Wurzeltier keine Würfe hat (STAMMBAUM-LITTERS)', async ({ page }) => {
|
||||
skipUnlessMock()
|
||||
// Krümel hat noch keine Würfe als Elternteil → Panel muss fehlen.
|
||||
await page.goto('/rennmaeuse/kruemel/stammbaum')
|
||||
await expect(page.locator('.pedigree-card').first()).toBeVisible()
|
||||
await expect(page.locator('.stammbaum-litters-panel')).not.toBeVisible()
|
||||
})
|
||||
|
||||
test('Knoten-Karte zeigt volles Geburtsdatum (STAMMBAUM-FULLDATE)', async ({ page }) => {
|
||||
skipUnlessMock()
|
||||
// Krümel: dateOfBirth '2025-03-12' → formatDate → '12.03.2025'
|
||||
await page.goto('/rennmaeuse/kruemel/stammbaum')
|
||||
await expect(page.locator('.pedigree-card').first()).toBeVisible()
|
||||
await expect(page.locator('.pedigree-card__year').first()).toContainText('12.03.2025')
|
||||
})
|
||||
|
||||
test('Gencode-Chip zeigt Genotyp statt Farbname (STAMMBAUM-GENCODE)', async ({ page }) => {
|
||||
skipUnlessMock()
|
||||
// Fridolin ist Vater von Krümel — genotype 'aa CC DD EE GG PP spsp rere'
|
||||
await page.goto('/rennmaeuse/kruemel/stammbaum')
|
||||
await expect(page.locator('.pedigree-card').first()).toBeVisible()
|
||||
const fridolinCard = page.locator('.pedigree-card').filter({ hasText: 'Fridolin' })
|
||||
await expect(fridolinCard.locator('.pedigree-chip')).toContainText('aa CC')
|
||||
})
|
||||
|
||||
test('Tier mit Foto zeigt Avatar-Bild, Tier ohne Foto zeigt Rennmaus-Icon (STAMMBAUM-AVATAR)', async ({ page }) => {
|
||||
skipUnlessMock()
|
||||
// Fridolin hat profilePhotoUrl (data URI) → <img.pedigree-card__avatar> sichtbar
|
||||
// Krümel hat profilePhotoUrl=null → kein img, SVG-Icon sichtbar
|
||||
await page.goto('/rennmaeuse/kruemel/stammbaum')
|
||||
await expect(page.locator('.pedigree-card').first()).toBeVisible()
|
||||
|
||||
// Fridolin ist Vater von Krümel → seine Karte enthält ein <img>
|
||||
const fridolinCard = page.locator('.pedigree-card').filter({ hasText: 'Fridolin' })
|
||||
await expect(fridolinCard.locator('img.pedigree-card__avatar')).toBeVisible()
|
||||
|
||||
// Krümel (root) hat kein Foto → SVG-Icon im Foto-Slot
|
||||
const rootCard = page.locator('.pedigree-card.pedigree-card--root')
|
||||
await expect(rootCard.locator('img.pedigree-card__avatar')).not.toBeAttached()
|
||||
await expect(rootCard.locator('svg[role="img"]')).toBeVisible()
|
||||
})
|
||||
|
||||
56
gerbil-manager-web/e2e/status-model.spec.ts
Normal file
56
gerbil-manager-web/e2e/status-model.spec.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
/** STATUS-MODEL: Zucht/Liebhaber wählbar; Verstorben/Abgegeben abgeleitet (read-only). */
|
||||
import { de, expect, skipUnlessMock, test, uniqueName } from './fixtures'
|
||||
|
||||
const t = de.pages.gerbils
|
||||
|
||||
test('Tier-Formular zeigt nur wählbare Statuswerte im Dropdown', async ({ page }) => {
|
||||
skipUnlessMock()
|
||||
await page.goto('/rennmaeuse/neu')
|
||||
const statusField = page.locator('label.field', {
|
||||
has: page.locator(`span:text-is("${t.fields.status}")`),
|
||||
})
|
||||
// Zucht (Breeding) ist vorausgewählt
|
||||
await expect(statusField.locator('select')).toHaveValue('Breeding')
|
||||
// Optionen: nur Zucht, Liebhaber, Abzugeben (NICHT Verstorben/Abgegeben)
|
||||
const opts = statusField.locator('select option')
|
||||
await expect(opts.filter({ hasText: t.statusLabels.Breeding })).toHaveCount(1)
|
||||
await expect(opts.filter({ hasText: t.statusLabels.Pet })).toHaveCount(1)
|
||||
await expect(opts.filter({ hasText: t.statusLabels.ForSale })).toHaveCount(1)
|
||||
await expect(opts.filter({ hasText: t.statusLabels.Deceased })).toHaveCount(0)
|
||||
await expect(opts.filter({ hasText: t.statusLabels.GivenAway })).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('Tier-Formular zeigt abgeleiteten Status Verstorben als Text + Hinweis', async ({ page }) => {
|
||||
skipUnlessMock()
|
||||
// Willi ist Deceased
|
||||
await page.goto('/rennmaeuse/willi/bearbeiten')
|
||||
// Status-Select ist NICHT vorhanden (abgeleitet)
|
||||
const statusField = page.locator('.field', {
|
||||
has: page.locator(`span:text-is("${t.fields.status}")`),
|
||||
})
|
||||
await expect(statusField).toBeVisible()
|
||||
await expect(statusField.locator('select')).toHaveCount(0)
|
||||
await expect(statusField).toContainText(t.statusLabels.Deceased)
|
||||
await expect(statusField).toContainText(t.form.statusDerivedHint.Deceased)
|
||||
})
|
||||
|
||||
test('Tiere-Liste zeigt Zucht als Standard-Status-Filter', async ({ page }) => {
|
||||
skipUnlessMock()
|
||||
await page.goto('/rennmaeuse')
|
||||
// DESIGN (Rennmaus Filter): der Default-Status erscheint als aktiver, entfernbarer Chip.
|
||||
await expect(page.locator('.rmf-chip-val', { hasText: t.statusLabels.Breeding })).toBeVisible()
|
||||
})
|
||||
|
||||
test('Neues Tier anlegen mit Status Liebhaber', async ({ page }) => {
|
||||
skipUnlessMock()
|
||||
const name = uniqueName('Tier')
|
||||
await page.goto('/rennmaeuse/neu')
|
||||
await page.getByLabel(`${t.fields.name} *`).fill(name)
|
||||
await page.getByLabel(`${t.fields.gender} *`).selectOption({ label: t.genderLabels.male })
|
||||
const statusField = page.locator('label.field', {
|
||||
has: page.locator(`span:text-is("${t.fields.status}")`),
|
||||
})
|
||||
await statusField.locator('select').selectOption({ label: t.statusLabels.Pet })
|
||||
await page.getByRole('button', { name: t.form.save, exact: true }).click()
|
||||
await expect(page.getByRole('heading', { name })).toBeVisible()
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
/** QA-1: Tiere (Rennmäuse) — Liste/Suche, CRUD, Detail-Tabs (FEAT-1 + FEAT-6). */
|
||||
import { de, expect, gotoSection, openFilterPanel, skipUnlessMock, test, uniqueName } from './fixtures'
|
||||
import { de, expect, gotoSection, selectListFilter, skipUnlessMock, test, uniqueName } from './fixtures'
|
||||
|
||||
const t = de.pages.gerbils
|
||||
const tabs = de.pages.tierTabs
|
||||
@@ -23,13 +23,9 @@ test('Herkunft-Filter (originBreeder) zeigt nur Tiere der gewählten Zucht (SEAR
|
||||
await expect(page.getByRole('link', { name: /Krümel/ })).toBeVisible()
|
||||
await expect(page.getByRole('link', { name: /Fridolin/ })).toBeVisible()
|
||||
|
||||
// UX-MOBILE-1: Herkunft-Select liegt im Filter-Drawer — auf Mobil erst öffnen.
|
||||
await openFilterPanel(page)
|
||||
// Herkunft (originBreeder) auf die Seed-Zucht 'Clan-Kleine-Chaoten' (nur Krümel).
|
||||
await page
|
||||
.locator('label.field', { has: page.locator(`span:text-is("${t.fields.origin}")`) })
|
||||
.locator('select')
|
||||
.selectOption({ label: 'Clan-Kleine-Chaoten' })
|
||||
// DESIGN (Rennmaus Filter): Herkunft (originBreeder) über das Quick-Chips-Sheet
|
||||
// auf die Seed-Zucht 'Clan-Kleine-Chaoten' (nur Krümel) filtern.
|
||||
await selectListFilter(page, t.fields.origin, 'Clan-Kleine-Chaoten')
|
||||
|
||||
await expect(page.getByRole('link', { name: /Krümel/ })).toBeVisible()
|
||||
await expect(page.getByRole('link', { name: /Fridolin/ })).toBeHidden()
|
||||
|
||||
@@ -5,6 +5,13 @@
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="description" content="Verwaltung für Rennmäuse, Würfe und Züchter" />
|
||||
<!-- DESIGN (Rennmaus Filter): Hanken Grotesk als App-Schrift. -->
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Hanken+Grotesk:wght@400;500;600;700;800&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<title>Rennmaus-Manager</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -62,7 +62,12 @@ describe('NAMEGEN_USAGES', () => {
|
||||
expect(codes).toContain('mythg')
|
||||
expect(codes).toContain('ger')
|
||||
expect(codes).toContain('arb')
|
||||
expect(codes).toHaveLength(5)
|
||||
expect(codes).toContain('disney')
|
||||
expect(codes).toContain('pokemon')
|
||||
expect(codes).toContain('encities')
|
||||
expect(codes).toContain('hrcities')
|
||||
expect(codes).toContain('usstates')
|
||||
expect(codes).toHaveLength(10)
|
||||
})
|
||||
|
||||
it('every usage has a non-empty label', () => {
|
||||
|
||||
@@ -61,6 +61,23 @@ export function andFilter(...conditions: Array<string | null | undefined | false
|
||||
return conditions.filter((c): c is string => Boolean(c)).join(',')
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an OR-group of conditions for one field, e.g. `(status=Breeding|status=ForSale)`.
|
||||
* Used for multi-select filters: several allowed values within one category are OR'd,
|
||||
* while categories are AND'd together by {@link andFilter}.
|
||||
* Returns '' for an empty value list (so andFilter drops it); a single value needs no parens.
|
||||
*/
|
||||
export function orGroup(
|
||||
field: string,
|
||||
values: ReadonlyArray<string | number | boolean>,
|
||||
op: GridifyOp = '==',
|
||||
): string {
|
||||
const parts = values.map((value) => condition({ field, op, value }))
|
||||
if (parts.length === 0) return ''
|
||||
if (parts.length === 1) return parts[0]
|
||||
return `(${parts.join('|')})`
|
||||
}
|
||||
|
||||
/** Assemble the URL query string ("?...") from a GridifyQuery. */
|
||||
export function toQueryString(q: GridifyQuery): string {
|
||||
const params = new URLSearchParams()
|
||||
|
||||
@@ -13,6 +13,11 @@ export const NAMEGEN_USAGES = [
|
||||
{ code: 'mythg', label: 'Griech. Mythologie' },
|
||||
{ code: 'ger', label: 'Deutsch' },
|
||||
{ code: 'arb', label: 'Arabisch' },
|
||||
{ code: 'disney', label: 'Disney' },
|
||||
{ code: 'pokemon', label: 'Pokémon' },
|
||||
{ code: 'encities', label: 'Englische Städte' },
|
||||
{ code: 'hrcities', label: 'Kroatische Städte' },
|
||||
{ code: 'usstates', label: 'US-Bundesstaaten' },
|
||||
] as const
|
||||
|
||||
export type NamegenUsageCode = (typeof NAMEGEN_USAGES)[number]['code']
|
||||
|
||||
@@ -10,9 +10,11 @@
|
||||
export type Gender = 'unknown' | 'male' | 'female'
|
||||
export const GENDERS: Gender[] = ['unknown', 'male', 'female']
|
||||
|
||||
/** Gerbil.Status — C# enum { Active, Deceased, GivenAway, ForSale }. */
|
||||
export type GerbilStatus = 'Active' | 'Deceased' | 'GivenAway' | 'ForSale'
|
||||
export const GERBIL_STATUSES: GerbilStatus[] = ['Active', 'ForSale', 'Deceased', 'GivenAway']
|
||||
/** Gerbil.Status — C# enum { Breeding, Pet, Deceased, GivenAway, ForSale }. STATUS-MODEL: Active→Breeding (gated on Pam feature/status-model). */
|
||||
export type GerbilStatus = 'Breeding' | 'Pet' | 'Deceased' | 'GivenAway' | 'ForSale'
|
||||
export const GERBIL_STATUSES: GerbilStatus[] = ['Breeding', 'Pet', 'ForSale', 'Deceased', 'GivenAway']
|
||||
/** Statuses the user can pick freely in the form; Deceased+GivenAway are derived by the backend. */
|
||||
export const SELECTABLE_STATUSES: GerbilStatus[] = ['Breeding', 'Pet', 'ForSale']
|
||||
|
||||
/** ISO date string "YYYY-MM-DD" (maps to C# DateOnly). */
|
||||
export type DateOnlyString = string
|
||||
@@ -56,6 +58,8 @@ export interface Gerbil {
|
||||
isResident?: boolean
|
||||
/** FORM-FIELDS-1: true=gehörlos, false=hörend, null=unbekannt. */
|
||||
isDeaf?: boolean | null
|
||||
/** STAMMBAUM-AVATAR: URL des Profilfotos (erstes Foto nach sortOrder); null = kein Foto. API-relativ oder absolut. */
|
||||
profilePhotoUrl?: string | null
|
||||
}
|
||||
|
||||
/** Payload for POST /gerbils. */
|
||||
@@ -122,6 +126,8 @@ export interface Litter {
|
||||
notes?: string | null
|
||||
fatherId: string | null
|
||||
motherId: string | null
|
||||
/** LITTER-MORTALITY: pups that died within the first 8 weeks. */
|
||||
deathsWithin8Weeks?: number | null
|
||||
}
|
||||
|
||||
/** Payload for POST /litters. */
|
||||
@@ -133,6 +139,7 @@ export interface CreateLitter {
|
||||
notes?: string | null
|
||||
fatherId?: string | null
|
||||
motherId?: string | null
|
||||
deathsWithin8Weeks?: number | null
|
||||
}
|
||||
|
||||
export type UpdateLitter = Partial<CreateLitter>
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
import { useState } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { NavLink, Outlet } from 'react-router-dom'
|
||||
import { de } from '../strings/de'
|
||||
import GerbilIcon from './GerbilIcon'
|
||||
import './appShell.css'
|
||||
|
||||
interface NavItem {
|
||||
to: string
|
||||
label: string
|
||||
icon: string
|
||||
icon: ReactNode
|
||||
end?: boolean
|
||||
}
|
||||
|
||||
// Primary items are always visible in the phone bottom bar; secondary items
|
||||
// move into the "Mehr" sheet on phones and appear inline in the desktop sidebar.
|
||||
const PRIMARY: NavItem[] = [
|
||||
{ to: '/rennmaeuse', label: de.nav.gerbils, icon: '🐭' },
|
||||
{ to: '/rennmaeuse', label: de.nav.gerbils, icon: <GerbilIcon size="1.25em" /> },
|
||||
{ to: '/wuerfe', label: de.nav.litters, icon: '🍼' },
|
||||
{ to: '/genetik', label: de.nav.genetics, icon: '🧬' },
|
||||
]
|
||||
@@ -45,11 +47,6 @@ export default function AppShell() {
|
||||
|
||||
return (
|
||||
<div className="app-shell">
|
||||
<header className="app-header">
|
||||
<span className="app-logo" aria-hidden="true">🐭</span>
|
||||
<h1 className="app-title">{de.app.title}</h1>
|
||||
</header>
|
||||
|
||||
<nav className="app-nav" aria-label={de.nav.mainNavigation}>
|
||||
<div className="nav-primary">
|
||||
{PRIMARY.map((item) => (
|
||||
|
||||
271
gerbil-manager-web/src/components/GerbilFilterBar.tsx
Normal file
271
gerbil-manager-web/src/components/GerbilFilterBar.tsx
Normal file
@@ -0,0 +1,271 @@
|
||||
/**
|
||||
* DESIGN (Rennmaus Filter.html): mobile-first filter UX —
|
||||
* 1. a horizontal "Quick-Chips" pill row (one pill per category, with a count badge),
|
||||
* 2. tapping a pill opens a bottom-sheet of multi-select options (✓ checkboxes,
|
||||
* searchable for long lists like Farbschlag / Herkunft),
|
||||
* 3. active selections appear ABOVE the list as removable chips (so they scroll
|
||||
* away with the list), with "Alle löschen".
|
||||
*
|
||||
* The user landed on the Quick-Chips concept, dezent style, brown accent. Colors
|
||||
* come from the app's existing tokens. `GerbilFilterBar` is the pill row + sheet;
|
||||
* `ActiveFilterChips` renders the removable chips and is placed above the list.
|
||||
*/
|
||||
import { useEffect, useMemo, useState, type CSSProperties, type ReactNode } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { de } from '../strings/de'
|
||||
import './gerbilFilterBar.css'
|
||||
|
||||
export interface FilterOption {
|
||||
value: string
|
||||
label: string
|
||||
/** Optional swatch dot (used for status colors). */
|
||||
color?: string
|
||||
/** Optional leading symbol (used for gender ♂ ♀ ?). */
|
||||
symbol?: string
|
||||
}
|
||||
|
||||
export interface FilterCategory {
|
||||
/** Matches the Gridify field / the key into the selected map. */
|
||||
key: string
|
||||
label: string
|
||||
/** Renders a search box above the option list (for long lists). */
|
||||
searchable?: boolean
|
||||
options: FilterOption[]
|
||||
}
|
||||
|
||||
function countFor(selected: Record<string, string[]>, key: string): number {
|
||||
return (selected[key] ?? []).length
|
||||
}
|
||||
|
||||
interface GerbilFilterBarProps {
|
||||
categories: FilterCategory[]
|
||||
selected: Record<string, string[]>
|
||||
onToggle: (key: string, value: string) => void
|
||||
}
|
||||
|
||||
/** The Quick-Chips pill row + the category bottom-sheet. */
|
||||
export function GerbilFilterBar({ categories, selected, onToggle }: GerbilFilterBarProps) {
|
||||
const t = de.filterBar
|
||||
const [activeKey, setActiveKey] = useState<string | null>(null)
|
||||
const activeCat = categories.find((c) => c.key === activeKey) ?? null
|
||||
|
||||
return (
|
||||
<div className="rmf">
|
||||
<div className="rmf-quickrow" role="group" aria-label={t.title}>
|
||||
{categories.map((cat) => {
|
||||
const n = countFor(selected, cat.key)
|
||||
return (
|
||||
<button
|
||||
key={cat.key}
|
||||
type="button"
|
||||
className={'rmf-pill' + (n > 0 ? ' is-on' : '')}
|
||||
onClick={() => setActiveKey(cat.key)}
|
||||
aria-haspopup="dialog"
|
||||
>
|
||||
{cat.label}
|
||||
{n > 0 && <span className="rmf-pill-count">{n}</span>}
|
||||
<span className="rmf-pill-chev" aria-hidden="true">▾</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{activeCat && (
|
||||
<FilterSheet
|
||||
cat={activeCat}
|
||||
selected={selected[activeCat.key] ?? []}
|
||||
onToggle={onToggle}
|
||||
onClose={() => setActiveKey(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface ActiveFilterChipsProps {
|
||||
categories: FilterCategory[]
|
||||
selected: Record<string, string[]>
|
||||
onRemove: (key: string, value: string) => void
|
||||
onClearAll: () => void
|
||||
/** Optional per-chip accent colour (e.g. status colours); falls back to the app accent. */
|
||||
chipColor?: (key: string, value: string) => string | undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Removable chips for the active selections, placed above the list so they scroll
|
||||
* away as you browse. Wraps onto multiple lines — nothing is hidden.
|
||||
*/
|
||||
export function ActiveFilterChips({
|
||||
categories,
|
||||
selected,
|
||||
onRemove,
|
||||
onClearAll,
|
||||
chipColor,
|
||||
}: ActiveFilterChipsProps) {
|
||||
const t = de.filterBar
|
||||
|
||||
const chips = categories.flatMap((cat) => {
|
||||
const labelByValue = new Map(cat.options.map((o) => [o.value, o.label]))
|
||||
return (selected[cat.key] ?? []).map((value) => ({
|
||||
key: cat.key,
|
||||
value,
|
||||
catLabel: cat.label,
|
||||
label: labelByValue.get(value) ?? value,
|
||||
}))
|
||||
})
|
||||
|
||||
if (chips.length === 0) return null
|
||||
|
||||
return (
|
||||
<div className="rmf-chips">
|
||||
{chips.map((c) => {
|
||||
const accent = chipColor?.(c.key, c.value)
|
||||
return (
|
||||
<button
|
||||
key={c.key + c.value}
|
||||
type="button"
|
||||
className="rmf-chip"
|
||||
style={accent ? ({ '--chip': accent } as CSSProperties) : undefined}
|
||||
onClick={() => onRemove(c.key, c.value)}
|
||||
aria-label={`${c.catLabel}: ${c.label} — ${t.remove}`}
|
||||
>
|
||||
<span className="rmf-chip-cat">{c.catLabel}</span>
|
||||
<span className="rmf-chip-val">{c.label}</span>
|
||||
<span className="rmf-chip-x" aria-hidden="true">×</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
{chips.length > 1 && (
|
||||
<button type="button" className="rmf-chip rmf-chip-clear" onClick={onClearAll}>
|
||||
{t.clearAll}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface BottomSheetProps {
|
||||
title: string
|
||||
onClose: () => void
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* Reusable bottom-sheet: dimmed scrim + slide-up panel with grip, title and a
|
||||
* "Fertig" button. Locks body scroll and closes on Escape / scrim tap. Used for
|
||||
* the category filters AND the sort selector (same drawer mechanic).
|
||||
*/
|
||||
export function BottomSheet({ title, onClose, children }: BottomSheetProps) {
|
||||
const t = de.filterBar
|
||||
|
||||
useEffect(() => {
|
||||
const prev = document.body.style.overflow
|
||||
document.body.style.overflow = 'hidden'
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') onClose()
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => {
|
||||
document.body.style.overflow = prev
|
||||
window.removeEventListener('keydown', onKey)
|
||||
}
|
||||
}, [onClose])
|
||||
|
||||
// Portal to <body> so the sheet escapes any sticky/stacking-context ancestor
|
||||
// (e.g. the sticky header) and renders above the bottom action bar.
|
||||
return createPortal(
|
||||
<div className="rmf-scrim" onClick={onClose} role="presentation">
|
||||
<div
|
||||
className="rmf-sheet"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={title}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="rmf-grip" aria-hidden="true" />
|
||||
<div className="rmf-sheet-head">
|
||||
<span className="rmf-sheet-title">{title}</span>
|
||||
<button type="button" className="rmf-sheet-done" onClick={onClose}>
|
||||
{t.done}
|
||||
</button>
|
||||
</div>
|
||||
<div className="rmf-sheet-body">{children}</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)
|
||||
}
|
||||
|
||||
interface FilterSheetProps {
|
||||
cat: FilterCategory
|
||||
selected: string[]
|
||||
onToggle: (key: string, value: string) => void
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
function FilterSheet({ cat, selected, onToggle, onClose }: FilterSheetProps) {
|
||||
return (
|
||||
<BottomSheet title={cat.label} onClose={onClose}>
|
||||
<OptionList cat={cat} selected={selected} onToggle={onToggle} />
|
||||
</BottomSheet>
|
||||
)
|
||||
}
|
||||
|
||||
interface OptionListProps {
|
||||
cat: FilterCategory
|
||||
selected: string[]
|
||||
onToggle: (key: string, value: string) => void
|
||||
}
|
||||
|
||||
function OptionList({ cat, selected, onToggle }: OptionListProps) {
|
||||
const t = de.filterBar
|
||||
const [q, setQ] = useState('')
|
||||
|
||||
const options = useMemo(() => {
|
||||
if (!cat.searchable) return cat.options
|
||||
const term = q.trim().toLowerCase()
|
||||
if (!term) return cat.options
|
||||
return cat.options.filter((o) => o.label.toLowerCase().includes(term))
|
||||
}, [cat, q])
|
||||
|
||||
return (
|
||||
<div className="rmf-picker">
|
||||
{cat.searchable && (
|
||||
<input
|
||||
className="rmf-search"
|
||||
placeholder={t.searchPlaceholder}
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
autoFocus
|
||||
aria-label={t.searchPlaceholder}
|
||||
/>
|
||||
)}
|
||||
<div className={'rmf-optlist' + (cat.searchable ? ' rmf-optlist--scroll' : '')}>
|
||||
{options.length === 0 && <div className="rmf-empty">{t.noMatch}</div>}
|
||||
{options.map((o) => {
|
||||
const on = selected.includes(o.value)
|
||||
return (
|
||||
<button
|
||||
key={o.value}
|
||||
type="button"
|
||||
className={'rmf-opt' + (on ? ' is-on' : '')}
|
||||
onClick={() => onToggle(cat.key, o.value)}
|
||||
aria-pressed={on}
|
||||
>
|
||||
<span className="rmf-opt-box" aria-hidden="true">
|
||||
{on ? '✓' : ''}
|
||||
</span>
|
||||
{o.color && <span className="rmf-opt-dot" style={{ background: o.color }} />}
|
||||
{o.symbol && (
|
||||
<span className="rmf-opt-sym" aria-hidden="true">
|
||||
{o.symbol}
|
||||
</span>
|
||||
)}
|
||||
<span className="rmf-opt-label">{o.label}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
37
gerbil-manager-web/src/components/GerbilIcon.tsx
Normal file
37
gerbil-manager-web/src/components/GerbilIcon.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import type { CSSProperties } from 'react'
|
||||
|
||||
interface Props {
|
||||
size?: string | number
|
||||
style?: CSSProperties
|
||||
className?: string
|
||||
}
|
||||
|
||||
/** Reusable gerbil silhouette icon — upright sitting pose, long tail with tuft. fill=currentColor. */
|
||||
export default function GerbilIcon({ size = '1em', style, className }: Props) {
|
||||
return (
|
||||
<svg
|
||||
viewBox="0 0 64 64"
|
||||
fill="currentColor"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width={size}
|
||||
height={size}
|
||||
style={{ display: 'inline-block', verticalAlign: '-0.125em', flexShrink: 0, ...style }}
|
||||
className={className}
|
||||
role="img"
|
||||
aria-label="Rennmaus"
|
||||
>
|
||||
{/* body — sitting upright */}
|
||||
<path d="M 34 23 C 38 20, 44 21, 46 25 C 47 27, 45 30, 41 31 C 38 32, 40 38, 40 42 C 40 48, 36 51, 31 52 C 25 52, 21 47, 21 40 C 21 31, 27 25, 34 23 Z" />
|
||||
{/* ears */}
|
||||
<path d="M 36 22 Q 33 13 39 11 Q 42 13 39 21 Z" />
|
||||
<path d="M 32 23 Q 30 15 35 13 Q 37 15 35 22 Z" opacity="0.6" />
|
||||
{/* front paw */}
|
||||
<path d="M 41 33 Q 46 33 46 36 Q 44 38 41 35 Z" />
|
||||
{/* hind paw */}
|
||||
<path d="M 21 49 C 19 53, 23 55, 30 55 C 33 55, 34 52, 30 50 Z" />
|
||||
{/* tail and tuft */}
|
||||
<path d="M 21 47 C 14 51, 9 46, 8 41 C 7 35, 11 27, 16 22 C 17 21, 18 22, 17 23 C 13 28, 10 35, 11 40 C 12 44, 15 47, 21 44 Z" />
|
||||
<path d="M 16 22 C 16 16, 13 11, 16 7 C 20 3, 22 10, 19 16 C 18 19, 17 21, 16 22 Z" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -43,6 +43,39 @@
|
||||
width: 5rem;
|
||||
}
|
||||
|
||||
.namegen-panel__gender {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.namegen-gender-group {
|
||||
display: inline-flex;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 0.4rem;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.namegen-gender-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
border-left: 1px solid var(--color-border);
|
||||
padding: 0.35rem 0.7rem;
|
||||
font: inherit;
|
||||
font-size: 0.9rem;
|
||||
cursor: pointer;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.namegen-gender-btn:first-child {
|
||||
border-left: none;
|
||||
}
|
||||
|
||||
.namegen-gender-btn.is-active {
|
||||
background: var(--color-accent, #2563eb);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.namegen-panel__usages {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
@@ -12,9 +12,17 @@ interface NameSuggestPanelProps {
|
||||
|
||||
const ALL_CODES = NAMEGEN_USAGES.map((u) => u.code) as NamegenUsageCode[]
|
||||
|
||||
type GenderSelection = 'any' | 'female' | 'male'
|
||||
|
||||
/** Map the gerbil form's gender onto the generator's three-way choice. */
|
||||
function seedGender(gender: string): GenderSelection {
|
||||
return gender === 'female' || gender === 'male' ? gender : 'any'
|
||||
}
|
||||
|
||||
export default function NameSuggestPanel({ gender, onPick, onClose }: NameSuggestPanelProps) {
|
||||
const t = de.namegen
|
||||
const [letter, setLetter] = useState('')
|
||||
const [genderSel, setGenderSel] = useState<GenderSelection>(() => seedGender(gender))
|
||||
const [usages, setUsages] = useState<Set<NamegenUsageCode>>(new Set(ALL_CODES))
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [keyMissing, setKeyMissing] = useState(false)
|
||||
@@ -39,7 +47,7 @@ export default function NameSuggestPanel({ gender, onPick, onClose }: NameSugges
|
||||
try {
|
||||
const result = await suggestNames({
|
||||
letter: letter.trim() || undefined,
|
||||
gender: gender || undefined,
|
||||
gender: genderSel === 'any' ? undefined : genderSel,
|
||||
usages: [...usages] as NamegenUsageCode[],
|
||||
count: 6,
|
||||
})
|
||||
@@ -78,6 +86,28 @@ export default function NameSuggestPanel({ gender, onPick, onClose }: NameSugges
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="namegen-panel__gender">
|
||||
<span>{t.genderLabel}</span>
|
||||
<div className="namegen-gender-group" role="radiogroup" aria-label={t.genderLabel}>
|
||||
{([
|
||||
['any', t.genderAny],
|
||||
['female', t.genderFemale],
|
||||
['male', t.genderMale],
|
||||
] as const).map(([value, label]) => (
|
||||
<button
|
||||
key={value}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={genderSel === value}
|
||||
className={`namegen-gender-btn ${genderSel === value ? 'is-active' : ''}`}
|
||||
onClick={() => setGenderSel(value)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="namegen-panel__usages">
|
||||
<span>{t.usagesLabel}</span>
|
||||
<div className="namegen-usages-grid">
|
||||
|
||||
427
gerbil-manager-web/src/components/gerbilFilterBar.css
Normal file
427
gerbil-manager-web/src/components/gerbilFilterBar.css
Normal file
@@ -0,0 +1,427 @@
|
||||
/* DESIGN (Rennmaus Filter.html): Quick-Chips + Bottom-Sheet + entfernbare Chips.
|
||||
Mobile-first. Palette + font sizes are taken 1:1 from the design (the app tokens
|
||||
are now the design's creme/brown/terracotta), so this matches the prototype. */
|
||||
|
||||
.rmf {
|
||||
--rmf-ease: cubic-bezier(0.22, 1, 0.36, 1);
|
||||
margin: 0.5rem 0 0.25rem;
|
||||
}
|
||||
|
||||
/* ---------- Quick-Chips pill row ---------- */
|
||||
.rmf-quickrow {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
overflow-x: auto;
|
||||
padding: 2px 0 4px;
|
||||
scrollbar-width: none;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
.rmf-quickrow::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
.rmf-pill {
|
||||
flex-shrink: 0;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
background: #fff;
|
||||
border: 1px solid var(--color-border);
|
||||
color: var(--color-text);
|
||||
padding: 9px 13px;
|
||||
border-radius: 999px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
box-shadow: var(--shadow);
|
||||
transition: transform 0.12s var(--rmf-ease), border-color 0.15s, color 0.15s, background 0.15s;
|
||||
}
|
||||
.rmf-pill:active {
|
||||
transform: scale(0.94);
|
||||
}
|
||||
.rmf-pill.is-on {
|
||||
border-color: var(--color-accent);
|
||||
color: var(--color-accent);
|
||||
background: var(--color-accent-soft);
|
||||
}
|
||||
.rmf-pill-count {
|
||||
background: var(--color-accent);
|
||||
color: #fff;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
min-width: 18px;
|
||||
height: 18px;
|
||||
padding: 0 5px;
|
||||
border-radius: 9px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.rmf-pill-chev {
|
||||
font-size: 11px;
|
||||
color: var(--color-text-faint);
|
||||
}
|
||||
|
||||
/* ---------- Active filter chips ---------- */
|
||||
.rmf-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
margin-top: 0.625rem;
|
||||
}
|
||||
.rmf-chip {
|
||||
--chip: var(--color-accent);
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
background: color-mix(in srgb, var(--chip) 12%, #fff);
|
||||
border: 1px solid color-mix(in srgb, var(--chip) 32%, transparent);
|
||||
color: color-mix(in srgb, var(--chip) 78%, #2b2723);
|
||||
padding: 6px 8px 6px 11px;
|
||||
border-radius: 999px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
animation: rmfChipIn 0.22s var(--rmf-ease);
|
||||
transition: transform 0.1s;
|
||||
}
|
||||
.rmf-chip:active {
|
||||
transform: scale(0.94);
|
||||
}
|
||||
.rmf-chip-cat {
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
opacity: 0.6;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.03em;
|
||||
}
|
||||
.rmf-chip-val {
|
||||
font-weight: 700;
|
||||
}
|
||||
.rmf-chip-x {
|
||||
font-size: 15px;
|
||||
line-height: 1;
|
||||
width: 17px;
|
||||
height: 17px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: color-mix(in srgb, var(--chip) 22%, transparent);
|
||||
border-radius: 50%;
|
||||
}
|
||||
.rmf-chip-clear {
|
||||
background: transparent;
|
||||
border: 1px solid var(--color-border);
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
.rmf-chip-clear .rmf-chip-x {
|
||||
display: none;
|
||||
}
|
||||
@keyframes rmfChipIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: scale(0.8);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- Bottom-Sheet ---------- */
|
||||
.rmf-scrim {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 60;
|
||||
background: rgba(43, 33, 25, 0.42);
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: center;
|
||||
animation: rmfScrim 0.2s ease;
|
||||
}
|
||||
@keyframes rmfScrim {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
.rmf-sheet {
|
||||
width: 100%;
|
||||
max-width: 460px;
|
||||
background: var(--color-bg);
|
||||
border-radius: 22px 22px 0 0;
|
||||
max-height: 82vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
box-shadow: 0 -8px 40px rgba(43, 33, 25, 0.25);
|
||||
animation: rmfSheetUp 0.32s var(--rmf-ease);
|
||||
}
|
||||
@keyframes rmfSheetUp {
|
||||
from {
|
||||
transform: translateY(100%);
|
||||
}
|
||||
to {
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
.rmf-grip {
|
||||
width: 40px;
|
||||
height: 4px;
|
||||
border-radius: 2px;
|
||||
background: var(--color-text-faint);
|
||||
opacity: 0.5;
|
||||
margin: 9px auto 4px;
|
||||
}
|
||||
.rmf-sheet-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0.375rem 1rem 0.75rem;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
}
|
||||
.rmf-sheet-title {
|
||||
font-size: 18px;
|
||||
font-weight: 800;
|
||||
color: var(--color-text);
|
||||
}
|
||||
.rmf-sheet-done {
|
||||
background: var(--color-accent);
|
||||
color: #fff;
|
||||
border: none;
|
||||
font: inherit;
|
||||
font-weight: 700;
|
||||
font-size: 14px;
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: 999px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.rmf-sheet-body {
|
||||
overflow-y: auto;
|
||||
padding: 0.5rem 1rem 1.5rem;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
/* ---------- Option list (multi-select checkboxes) ---------- */
|
||||
.rmf-picker {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.rmf-search {
|
||||
width: 100%;
|
||||
border: 1px solid var(--color-border);
|
||||
background: #fff;
|
||||
border-radius: 14px;
|
||||
padding: 0.75rem 0.875rem;
|
||||
font: inherit;
|
||||
font-size: 1rem;
|
||||
color: var(--color-text);
|
||||
outline: none;
|
||||
margin: 0.25rem 0 0.375rem;
|
||||
}
|
||||
.rmf-search:focus {
|
||||
border-color: var(--color-accent);
|
||||
}
|
||||
.rmf-optlist {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
padding-top: 4px;
|
||||
}
|
||||
.rmf-optlist--scroll {
|
||||
max-height: 46vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.rmf-opt {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.7rem;
|
||||
background: none;
|
||||
border: none;
|
||||
font: inherit;
|
||||
padding: 0.75rem 0.375rem;
|
||||
cursor: pointer;
|
||||
color: var(--color-text);
|
||||
font-size: 1rem;
|
||||
font-weight: 500;
|
||||
text-align: left;
|
||||
width: 100%;
|
||||
border-radius: 10px;
|
||||
transition: background 0.12s;
|
||||
}
|
||||
.rmf-opt:hover {
|
||||
background: var(--color-accent-soft);
|
||||
}
|
||||
.rmf-opt.is-on {
|
||||
font-weight: 700;
|
||||
}
|
||||
.rmf-opt-box {
|
||||
flex-shrink: 0;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 7px;
|
||||
border: 1.5px solid var(--color-border);
|
||||
background: #fff;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 14px;
|
||||
color: #fff;
|
||||
font-weight: 800;
|
||||
transition: background 0.14s, border-color 0.14s;
|
||||
}
|
||||
.rmf-opt.is-on .rmf-opt-box {
|
||||
background: var(--color-accent);
|
||||
border-color: var(--color-accent);
|
||||
}
|
||||
.rmf-opt-dot {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border-radius: 50%;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.rmf-opt-sym {
|
||||
width: 22px;
|
||||
text-align: center;
|
||||
font-size: 16px;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
.rmf-opt-label {
|
||||
flex: 1;
|
||||
}
|
||||
.rmf-empty {
|
||||
padding: 1.1rem 0.375rem;
|
||||
color: var(--color-text-muted);
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
/* ---------- Search bar ---------- */
|
||||
.rmf-searchbar {
|
||||
margin-top: 0.75rem;
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
background: #fff;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 14px;
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
.rmf-search-ico {
|
||||
padding-left: 0.875rem;
|
||||
font-size: 19px;
|
||||
color: var(--color-text-faint);
|
||||
}
|
||||
.rmf-searchfield {
|
||||
flex: 1;
|
||||
border: none;
|
||||
background: transparent;
|
||||
outline: none;
|
||||
font: inherit;
|
||||
font-size: 16px;
|
||||
color: var(--color-text);
|
||||
padding: 0.875rem 0.75rem;
|
||||
min-width: 0;
|
||||
}
|
||||
.rmf-searchfield::placeholder {
|
||||
color: var(--color-text-faint);
|
||||
}
|
||||
.rmf-search-clear {
|
||||
border: none;
|
||||
background: var(--color-accent-soft);
|
||||
color: var(--color-text-muted);
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 50%;
|
||||
margin-right: 0.625rem;
|
||||
font-size: 1rem;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* ---------- Bar: Externe-Ahnen toggle + Sortieren — two equal-width chips ---------- */
|
||||
.rm-bar {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
gap: 0.5rem;
|
||||
margin-top: 0.625rem;
|
||||
}
|
||||
|
||||
/* Shared pill: both chips are the SAME size (flex: 1 → equal width). */
|
||||
.rmf-bar-chip {
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
background: #fff;
|
||||
border: 1px solid var(--color-border);
|
||||
color: var(--color-text-muted);
|
||||
padding: 8px 12px;
|
||||
border-radius: 999px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
box-shadow: var(--shadow);
|
||||
transition: background 0.15s, border-color 0.15s, color 0.15s, transform 0.1s;
|
||||
}
|
||||
.rmf-bar-chip:active {
|
||||
transform: scale(0.97);
|
||||
}
|
||||
/* Externe-Ahnen active state. */
|
||||
.rmf-bar-chip.is-on {
|
||||
background: var(--color-accent-soft);
|
||||
border-color: color-mix(in srgb, var(--color-accent) 32%, transparent);
|
||||
color: color-mix(in srgb, var(--color-accent) 78%, #2b2723);
|
||||
}
|
||||
.rmf-bar-chip-label {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.rmf-bar-chip-ico {
|
||||
color: var(--color-accent);
|
||||
font-weight: 800;
|
||||
}
|
||||
.rmf-bar-chip-chev {
|
||||
font-size: 11px;
|
||||
color: var(--color-text-faint);
|
||||
}
|
||||
|
||||
/* Toggle icon circle on the Externe-Ahnen chip (+ → ✓). */
|
||||
.rmf-chip-toggle-ico {
|
||||
font-size: 14px;
|
||||
line-height: 1;
|
||||
width: 17px;
|
||||
height: 17px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 50%;
|
||||
font-weight: 800;
|
||||
background: color-mix(in srgb, var(--color-accent) 14%, transparent);
|
||||
color: var(--color-accent);
|
||||
transition: background 0.15s, color 0.15s;
|
||||
}
|
||||
.rmf-bar-chip.is-on .rmf-chip-toggle-ico {
|
||||
background: var(--color-accent);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
/* Desktop: the sheet becomes a centered modal rather than a bottom drawer. */
|
||||
@media (min-width: 768px) {
|
||||
.rmf-scrim {
|
||||
align-items: center;
|
||||
}
|
||||
.rmf-sheet {
|
||||
border-radius: 18px;
|
||||
max-width: 420px;
|
||||
max-height: 70vh;
|
||||
animation: rmfChipIn 0.2s var(--rmf-ease);
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
fromJSON,
|
||||
wildType,
|
||||
extractGenotypeFlags,
|
||||
displayGenotypeSafe,
|
||||
} from '../genotype'
|
||||
import { combineLocus } from '../punnett'
|
||||
import { LOCI, type LocusKey } from '../loci'
|
||||
@@ -46,8 +47,8 @@ describe('Fraction', () => {
|
||||
describe('Genotype serialization', () => {
|
||||
it('round-trips display string <-> structured form', () => {
|
||||
const g = fromDisplayString('Aa CC Dd EE GG Pp Spsp rere')
|
||||
expect(toDisplayString(g)).toBe('Aa CC Dd EE GG Pp Spsp rere')
|
||||
expect(toDisplayString(fromJSON(toJSON(g)))).toBe('Aa CC Dd EE GG Pp Spsp rere')
|
||||
expect(toDisplayString(g)).toBe('Aa CC Dd EE GG Pp Spsp')
|
||||
expect(toDisplayString(fromJSON(toJSON(g)))).toBe('Aa CC Dd EE GG Pp Spsp')
|
||||
})
|
||||
|
||||
it('parses multi-char C-series alleles via maximal munch', () => {
|
||||
@@ -72,8 +73,8 @@ describe('Genotype serialization', () => {
|
||||
expect(g.P).toEqual(['P', 'p'])
|
||||
})
|
||||
|
||||
it('wild type is AA CC DD EE GG PP spsp rere', () => {
|
||||
expect(toDisplayString(wildType())).toBe('AA CC DD EE GG PP spsp rere')
|
||||
it('wild type is AA CC DD EE GG PP spsp (rere omitted)', () => {
|
||||
expect(toDisplayString(wildType())).toBe('AA CC DD EE GG PP spsp')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -102,7 +103,7 @@ describe('Worked example from research report', () => {
|
||||
|
||||
expect(result.offspring).toHaveLength(1)
|
||||
const only = result.offspring[0]
|
||||
expect(only.genotype).toBe('Aa CC DD EE GG Pp spsp rere')
|
||||
expect(only.genotype).toBe('Aa CC DD EE GG Pp spsp')
|
||||
expect(only.probability.text).toBe('1')
|
||||
expect(result.warnings).toHaveLength(0)
|
||||
})
|
||||
@@ -185,15 +186,11 @@ describe('Farbschlag catalog', () => {
|
||||
})
|
||||
|
||||
it('frozen contract names round-trip to themselves (DB-key guard)', () => {
|
||||
// The first 18 are the frozen ColorVariety keys — their representative
|
||||
// genotype MUST resolve back to their own name, never a later variety.
|
||||
// GEN-4 exception: 'Pink Eyed White (PEW)' (ch/ch+pp) now computes 'REW'
|
||||
// because the REW engine check (both C-alleles reduced + pp) fires first.
|
||||
// PEW stays in the catalog as a user-pickable import name; its computed
|
||||
// farbschlag is intentionally 'REW' per Julian's extended rule.
|
||||
const REW_SHADOWED = new Set(['Pink Eyed White (PEW)'])
|
||||
// The first 17 frozen ColorVariety keys — their representative genotype
|
||||
// MUST resolve back to their own name, never a later variety.
|
||||
// GEN-4c: 'REW' (formerly 'Pink Eyed White (PEW)') round-trips correctly:
|
||||
// chch+pp → REW engine check → 'REW' = entry.name.
|
||||
for (const entry of BASE_COLORS.slice(0, FROZEN_COUNT)) {
|
||||
if (REW_SHADOWED.has(entry.name)) continue
|
||||
expect(genotypeToFarbschlag(representativeGenotype(entry))).toBe(entry.name)
|
||||
}
|
||||
})
|
||||
@@ -224,11 +221,12 @@ describe('Farbschlag catalog', () => {
|
||||
|
||||
it('CATALOG seed view mirrors the ColorVariety table shape', () => {
|
||||
expect(CATALOG).toHaveLength(CATALOG_SIZE)
|
||||
expect(CATALOG[0]).toMatchObject({ name: 'Pink Eyed White (PEW)', sortOrder: 0 })
|
||||
expect(CATALOG[0]).toMatchObject({ name: 'REW', sortOrder: 0 })
|
||||
// Every row has a non-empty canonical genotype display string and unique name.
|
||||
// GEN-3h: bracket notation (e[f], c[chm], c[h]) allowed in tokens.
|
||||
// GEN-4d: rere omitted from display -> 7 tokens (no Rex, no Sls), 8 (Rex or Sls), 9 (both).
|
||||
expect(new Set(CATALOG.map((c) => c.name)).size).toBe(CATALOG.length)
|
||||
expect(CATALOG.every((c) => /^[A-Za-z[\]?-]+( [A-Za-z[\]?-]+){7}$/.test(c.canonicalGenotype))).toBe(true)
|
||||
expect(CATALOG.every((c) => /^[A-Za-z[\]?-]+( [A-Za-z[\]?-]+){6,8}$/.test(c.canonicalGenotype))).toBe(true)
|
||||
})
|
||||
|
||||
it('genotypeToFarbschlag (DATA-1 denormalization contract) returns the plain name', () => {
|
||||
@@ -289,7 +287,7 @@ describe('GEN-3a: Uw=G alias', () => {
|
||||
it('always RENDERS G, never Uw (breeder preference)', () => {
|
||||
// Uw/uw is an input/import alias only; output must echo G/g.
|
||||
expect(toDisplayString(fromDisplayString('AA CC DD EE Uwuw PP spsp rere'))).toBe(
|
||||
'AA CC DD EE Gg PP spsp rere',
|
||||
'AA CC DD EE Gg PP spsp',
|
||||
)
|
||||
expect(toDisplayString(fromDisplayString('AA CC DD EE uwuw PP spsp rere'))).not.toContain('uw')
|
||||
})
|
||||
@@ -301,10 +299,16 @@ describe('GEN-3a: second spotting locus Sls (WP)', () => {
|
||||
expect(fromDisplayString('AA CC DD EE GG PP spsp rere WP').Sls).toEqual(['Sl', 'sl'])
|
||||
})
|
||||
|
||||
it('toDisplayString omits wild-type Sls but shows Slsl', () => {
|
||||
expect(toDisplayString(wildType())).toBe('AA CC DD EE GG PP spsp rere')
|
||||
it('toDisplayString omits wild-type Sls and Re, shows Slsl/Rere when non-wildtype', () => {
|
||||
// GEN-4d: Re (rere) omitted at wildtype, like Sls.
|
||||
expect(toDisplayString(wildType())).toBe('AA CC DD EE GG PP spsp')
|
||||
// Rex het → Rere shown
|
||||
expect(toDisplayString(fromDisplayString('AA CC DD EE GG PP spsp Rere'))).toBe(
|
||||
'AA CC DD EE GG PP spsp Rere',
|
||||
)
|
||||
// WP → Slsl shown, rere still omitted
|
||||
expect(toDisplayString(fromDisplayString('AA CC DD EE GG PP spsp rere WP'))).toBe(
|
||||
'AA CC DD EE GG PP spsp rere Slsl',
|
||||
'AA CC DD EE GG PP spsp Slsl',
|
||||
)
|
||||
})
|
||||
|
||||
@@ -334,7 +338,7 @@ describe('GEN-3a: second spotting locus Sls (WP)', () => {
|
||||
describe('GEN-3a: flag/metadata tokens tolerated', () => {
|
||||
it('dea/taub/Dea/DP/WFNZ/RV/GV do not break parsing (stripped)', () => {
|
||||
const g = fromDisplayString('AA CC DD EE GG PP spsp rere dea WFNZ DP RV GV')
|
||||
expect(toDisplayString(g)).toBe('AA CC DD EE GG PP spsp rere')
|
||||
expect(toDisplayString(g)).toBe('AA CC DD EE GG PP spsp')
|
||||
})
|
||||
|
||||
it('extractGenotypeFlags reads deafness + tags', () => {
|
||||
@@ -367,11 +371,11 @@ describe("GEN-3c: unknown allele displays as '-' (stored as '?')", () => {
|
||||
it("accepts '-' input, stores '?', displays '-'", () => {
|
||||
const g = fromDisplayString('Aa C- DD EE GG Pp spsp rere')
|
||||
expect(g.C).toEqual(['C', '?']) // stored internal contract stays '?'
|
||||
expect(toDisplayString(g)).toBe('Aa C- DD EE GG Pp spsp rere') // displayed as '-'
|
||||
expect(toDisplayString(g)).toBe('Aa C- DD EE GG Pp spsp') // displayed as '-'
|
||||
})
|
||||
it("'?' and '-' inputs are equivalent", () => {
|
||||
expect(toDisplayString(fromDisplayString('Aa C? DD EE GG Pp spsp rere'))).toBe(
|
||||
'Aa C- DD EE GG Pp spsp rere',
|
||||
'Aa C- DD EE GG Pp spsp',
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -396,10 +400,10 @@ describe('GEN-3c: no Unbekannt when the E locus is known (family fallback)', ()
|
||||
|
||||
describe('GEN-3d: dominance tiebreak for unknown loci', () => {
|
||||
it('unknown-C reads as full-colour, NOT a c^h/c^chm white', () => {
|
||||
// 'aa C- DD EE GG PP' -> Schwarz (dominant C reading), never PEW/Hermelin/Himalaya.
|
||||
// 'aa C- DD EE GG PP' -> Schwarz (dominant C reading), never REW/Hermelin/Himalaya.
|
||||
const name = genotypeToFarbschlag(fromDisplayString('aa C- DD EE GG PP spsp rere'))
|
||||
expect(name).toBe('Schwarz')
|
||||
expect(['Pink Eyed White (PEW)', 'Hermelin', 'Himalaya']).not.toContain(name)
|
||||
expect(['REW', 'Hermelin', 'Himalaya']).not.toContain(name)
|
||||
})
|
||||
|
||||
it('unknown second marker allele defaults UNMARKED, not Schecke (marker-aware)', () => {
|
||||
@@ -549,15 +553,16 @@ describe('GEN-4: Dilute prefix, REW, no-bare-Fuchs', () => {
|
||||
})
|
||||
|
||||
it('REW: both C alleles reduced (no full C) + pp = REW — all three cases (Julian confirmed)', () => {
|
||||
// hom cchm/cchm + pp
|
||||
expect(name('AA cchmcchm DD EE GG pp spsp rere')).toBe('REW') // CP-Gold
|
||||
// hom cchm/cchm + pp — A/D/E/G-independent (REW-2: Julian: "egal ob AA oder aa")
|
||||
expect(name('AA cchmcchm DD EE GG pp spsp rere')).toBe('REW') // CP-Gold (A-)
|
||||
expect(name('aa cchmcchm DD EE GG pp spsp rere')).toBe('REW') // aa: REW-2 verification
|
||||
expect(name('AA cchmcchm DD ee GG pp spsp rere')).toBe('REW') // CP-Goldfuchs
|
||||
expect(name('AA cchmcchm DD EE gg pp spsp rere')).toBe('REW') // CP-Elfenbein
|
||||
expect(name('AA cchmcchm DD ee gg pp spsp rere')).toBe('REW') // CP-Apricot
|
||||
expect(name('AA cchmcchm dd EE GG pp spsp rere')).toBe('REW') // CP-dd Gold
|
||||
// het cchm/ch + pp (Julian: also REW)
|
||||
expect(name('AA cchmch DD EE GG pp spsp rere')).toBe('REW')
|
||||
// ch/ch + pp (Julian: also REW — subsumes PEW)
|
||||
// ch/ch + pp (Julian: also REW; PEW renamed to REW in catalog per GEN-4c)
|
||||
expect(name('AA chch DD EE GG pp spsp rere')).toBe('REW')
|
||||
expect(name('aa chch DD EE GG pp spsp rere')).toBe('REW')
|
||||
// Counterproof: full C present → NOT REW (residual pigment)
|
||||
@@ -593,15 +598,15 @@ describe('GEN-3h: breeder bracket-notation display + E-locus e-before-ef order',
|
||||
it('ef displays as e[f], cchm as c[chm], ch as c[h]', () => {
|
||||
// Fuchsschimmel: E=[ef,ef] hom
|
||||
expect(toDisplayString(fromDisplayString('AA CC DD efef GG PP spsp rere'))).toBe(
|
||||
'AA CC DD e[f]e[f] GG PP spsp rere',
|
||||
'AA CC DD e[f]e[f] GG PP spsp',
|
||||
)
|
||||
// C-locus het: cchm + ch
|
||||
expect(toDisplayString(fromDisplayString('aa cchmch DD EE GG PP spsp rere'))).toBe(
|
||||
'aa c[chm]c[h] DD EE GG PP spsp rere',
|
||||
'aa c[chm]c[h] DD EE GG PP spsp',
|
||||
)
|
||||
// C-locus hom cchm
|
||||
expect(toDisplayString(fromDisplayString('aa cchmcchm DD EE GG PP spsp rere'))).toBe(
|
||||
'aa c[chm]c[chm] DD EE GG PP spsp rere',
|
||||
'aa c[chm]c[chm] DD EE GG PP spsp',
|
||||
)
|
||||
})
|
||||
|
||||
@@ -611,24 +616,24 @@ describe('GEN-3h: breeder bracket-notation display + E-locus e-before-ef order',
|
||||
// Display must swap to [e, ef] per breeder convention.
|
||||
const g = fromDisplayString('aa CC DD eef Gg Pp spsp rere')
|
||||
expect(g.E).toEqual(['ef', 'e']) // storage order unchanged
|
||||
expect(toDisplayString(g)).toBe('aa CC DD ee[f] Gg Pp spsp rere')
|
||||
expect(toDisplayString(g)).toBe('aa CC DD ee[f] Gg Pp spsp')
|
||||
})
|
||||
|
||||
it('E+e stays Ee (E dominant over e, no swap needed)', () => {
|
||||
expect(toDisplayString(fromDisplayString('aa CC DD Ee GG PP spsp rere'))).toBe(
|
||||
'aa CC DD Ee GG PP spsp rere',
|
||||
'aa CC DD Ee GG PP spsp',
|
||||
)
|
||||
})
|
||||
|
||||
it('E+ef displays Ee[f] (E dominant stays first, ef renders as e[f])', () => {
|
||||
expect(toDisplayString(fromDisplayString('aa CC DD Eef GG PP spsp rere'))).toBe(
|
||||
'aa CC DD Ee[f] GG PP spsp rere',
|
||||
'aa CC DD Ee[f] GG PP spsp',
|
||||
)
|
||||
})
|
||||
|
||||
// ── Julian oracle fixtures (HUMANQUESTION D3/D4) ─────────────────────
|
||||
it('Tier C: oracle display string round-trips exactly (aa C- D- ee[f] Gg Pp spsp rere)', () => {
|
||||
const display = 'aa C- D- ee[f] Gg Pp spsp rere'
|
||||
it('Tier C: oracle display string round-trips exactly (aa C- D- ee[f] Gg Pp spsp)', () => {
|
||||
const display = 'aa C- D- ee[f] Gg Pp spsp'
|
||||
const g = fromDisplayString(display)
|
||||
expect(g.E).toEqual(['ef', 'e'])
|
||||
expect(g.C).toEqual(['C', '?'])
|
||||
@@ -636,16 +641,16 @@ describe('GEN-3h: breeder bracket-notation display + E-locus e-before-ef order',
|
||||
// Farbschlag scope is outside GEN-3h; god confirmed colour is correct as-is.
|
||||
})
|
||||
|
||||
it('Zuleika oracle: aa c[chm]c[h] DD Ee Gg PP spsp rere', () => {
|
||||
const display = 'aa c[chm]c[h] DD Ee Gg PP spsp rere'
|
||||
it('Zuleika oracle: aa c[chm]c[h] DD Ee Gg PP spsp', () => {
|
||||
const display = 'aa c[chm]c[h] DD Ee Gg PP spsp'
|
||||
const g = fromDisplayString(display)
|
||||
expect(g.C).toEqual(['cchm', 'ch'])
|
||||
expect(g.E).toEqual(['E', 'e'])
|
||||
expect(toDisplayString(g)).toBe(display)
|
||||
})
|
||||
|
||||
it('Milka oracle: aa Cc[h] dd EE Gg P- Spsp rere', () => {
|
||||
const display = 'aa Cc[h] dd EE Gg P- Spsp rere'
|
||||
it('Milka oracle: aa Cc[h] dd EE Gg P- Spsp', () => {
|
||||
const display = 'aa Cc[h] dd EE Gg P- Spsp'
|
||||
const g = fromDisplayString(display)
|
||||
expect(g.C).toEqual(['C', 'ch'])
|
||||
expect(g.D).toEqual(['d', 'd'])
|
||||
@@ -668,7 +673,7 @@ describe('GEN-3h: breeder bracket-notation display + E-locus e-before-ef order',
|
||||
it('e[-] standalone: parses as [e,?], displays e-', () => {
|
||||
const g = fromDisplayString('aa CC DD e[-] GG PP spsp rere')
|
||||
expect(g.E).toEqual(['e', '?'])
|
||||
expect(toDisplayString(g)).toBe('aa CC DD e- GG PP spsp rere')
|
||||
expect(toDisplayString(g)).toBe('aa CC DD e- GG PP spsp')
|
||||
})
|
||||
|
||||
it('CR-1a: Silvain oracle ee[-] parses without crash → [e,?], displays e-', () => {
|
||||
@@ -680,6 +685,50 @@ describe('GEN-3h: breeder bracket-notation display + E-locus e-before-ef order',
|
||||
expect(g.C).toEqual(['cchm', 'cchm'])
|
||||
expect(g.D).toEqual(['D', 'd'])
|
||||
expect(g.Sp).toEqual(['Sp', 'sp'])
|
||||
expect(toDisplayString(g)).toBe('aa c[chm]c[chm] Dd e- Gg Pp Spsp rere')
|
||||
expect(toDisplayString(g)).toBe('aa c[chm]c[chm] Dd e- Gg Pp Spsp')
|
||||
})
|
||||
|
||||
// ── GENOTYPE-PARSE-CRASH / displayGenotypeSafe resilience ───────────────
|
||||
it('handles blank c locus and c[-] resiliently without crashing', () => {
|
||||
// Vandana's genotype
|
||||
const rawVandana = 'Aa Cc Dd eef Gg P? spsp ??'
|
||||
const g = fromDisplayString(rawVandana)
|
||||
expect(g.C).toEqual(['C', '?'])
|
||||
expect(toDisplayString(g)).toBe('Aa C- Dd ee[f] Gg P- spsp')
|
||||
|
||||
// cchmc allele
|
||||
const g2 = fromDisplayString('Aa cchmc Dd ee Gg Pp spsp')
|
||||
expect(g2.C).toEqual(['cchm', '?'])
|
||||
expect(toDisplayString(g2)).toBe('Aa c[chm]- Dd ee Gg Pp spsp')
|
||||
|
||||
// c[-] and blank c standalone
|
||||
const g3 = fromDisplayString('Aa c[-] Dd ee Gg Pp spsp')
|
||||
expect(g3.C).toEqual(['C', 'C']) // default to wild-type since c[-] was skipped
|
||||
expect(toDisplayString(g3)).toBe('Aa CC Dd ee Gg Pp spsp')
|
||||
|
||||
const g4 = fromDisplayString('Aa c Dd ee Gg Pp spsp')
|
||||
expect(g4.C).toEqual(['C', 'C']) // default to wild-type since c was skipped
|
||||
expect(toDisplayString(g4)).toBe('Aa CC Dd ee Gg Pp spsp')
|
||||
})
|
||||
|
||||
it('displayGenotypeSafe formats parsed genotypes and handles fallback safely', () => {
|
||||
// 1. Parseable with unknown alleles, replacing ? with -
|
||||
expect(displayGenotypeSafe('Aa C? Dd')).toBe('Aa C- Dd EE GG PP spsp')
|
||||
|
||||
// 2. Parseable with trailing ?? (stripped completely)
|
||||
expect(displayGenotypeSafe('Aa CC Dd EE GG Pp spsp ??')).toBe('Aa CC Dd EE GG Pp spsp')
|
||||
expect(displayGenotypeSafe('Aa Cc Dd eef Gg P? spsp ??')).toBe('Aa C- Dd ee[f] Gg P- spsp')
|
||||
expect(displayGenotypeSafe('Aa CC Dd EE GG Pp spsp Slsl ??')).toBe('Aa CC Dd EE GG Pp spsp Slsl')
|
||||
|
||||
// 3. Unparseable fallback: removes ?? / -- / [-], replaces remaining ? with -
|
||||
expect(displayGenotypeSafe('Aa Cc XX ??')).toBe('Aa Cc XX')
|
||||
expect(displayGenotypeSafe('Aa Cc XX --')).toBe('Aa Cc XX')
|
||||
expect(displayGenotypeSafe('Aa Cc XX [-]')).toBe('Aa Cc XX')
|
||||
expect(displayGenotypeSafe('Aa Cc? XX')).toBe('Aa Cc- XX')
|
||||
|
||||
// 4. Handles null/undefined/empty
|
||||
expect(displayGenotypeSafe(null)).toBe('')
|
||||
expect(displayGenotypeSafe(undefined)).toBe('')
|
||||
expect(displayGenotypeSafe('')).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -51,7 +51,7 @@ export const BASE_COLORS: readonly FarbschlagEntry[] = [
|
||||
// GEN-3a: 'Schwarzschimmel' REMOVED (breeder C5: no such variety; efef base is
|
||||
// Orangeschimmel — see the GEN-2 block below). This was an authorized exception
|
||||
// to the frozen-name rule; the ColorVariety seed drops it too.
|
||||
{ name: 'Pink Eyed White (PEW)', english: 'Pink Eyed White', tokens: { C: 'ch', P: 'p' }, image: 'rotaugen-weiss-pew-d-sep-e-sep.jpg' },
|
||||
{ name: 'REW', english: 'Pink Eyed White', tokens: { C: 'ch', P: 'p' }, image: 'rotaugen-weiss-pew-d-sep-e-sep.jpg' },
|
||||
{ name: 'Hermelin', english: 'Dark Tailed White', tokens: { A: 'a', C: 'ch', D: 'D', P: 'P' }, image: 'hermelin.jpeg' },
|
||||
{ name: 'Himalaya', english: 'Himalayan', tokens: { A: 'A', C: 'ch', D: 'D', P: 'P' }, image: 'himalaya.jpg' },
|
||||
{ name: 'Zobel', english: 'Sable', tokens: { A: 'a', C: 'cchm', D: 'D', E: 'E', G: 'g', P: 'P' }, image: 'zobel.jpeg' },
|
||||
@@ -268,7 +268,7 @@ export function farbschlagFor(g: Genotype): FarbschlagMatch {
|
||||
// AND pink-eyed (pp) = REW (Rotaugenweiß), A/D/E/G-independent.
|
||||
// cchm/cchm + pp → REW (CP varieties with pink-eye)
|
||||
// cchm/ch + pp → REW (het colourpoint + pink-eye)
|
||||
// ch/ch + pp → REW (this also subsumes the frozen 'Pink Eyed White (PEW)' entry)
|
||||
// ch/ch + pp → REW (Julian confirmed PEW=REW; the 'REW' catalog entry matches here)
|
||||
// Counterproof: at least one full 'C' + pp → NOT REW (residual pigment remains).
|
||||
const [c0, c1] = resolvedPair(g, 'C')
|
||||
const [p0, p1] = resolvedPair(g, 'P')
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[
|
||||
{
|
||||
"name": "Pink Eyed White (PEW)",
|
||||
"name": "REW",
|
||||
"english": "Pink Eyed White",
|
||||
"canonicalGenotype": "AA chch DD EE GG pp spsp rere",
|
||||
"sortOrder": 0,
|
||||
|
||||
@@ -1,426 +1,426 @@
|
||||
[
|
||||
{
|
||||
"name": "Pink Eyed White (PEW)",
|
||||
"name": "REW",
|
||||
"english": "Pink Eyed White",
|
||||
"canonicalGenotype": "AA c[h]c[h] DD EE GG pp spsp rere",
|
||||
"canonicalGenotype": "AA c[h]c[h] DD EE GG pp spsp",
|
||||
"sortOrder": 0,
|
||||
"image": "rotaugen-weiss-pew-d-sep-e-sep.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Hermelin",
|
||||
"english": "Dark Tailed White",
|
||||
"canonicalGenotype": "aa c[h]c[h] DD EE GG PP spsp rere",
|
||||
"canonicalGenotype": "aa c[h]c[h] DD EE GG PP spsp",
|
||||
"sortOrder": 1,
|
||||
"image": "hermelin.jpeg"
|
||||
},
|
||||
{
|
||||
"name": "Himalaya",
|
||||
"english": "Himalayan",
|
||||
"canonicalGenotype": "AA c[h]c[h] DD EE GG PP spsp rere",
|
||||
"canonicalGenotype": "AA c[h]c[h] DD EE GG PP spsp",
|
||||
"sortOrder": 2,
|
||||
"image": "himalaya.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Zobel",
|
||||
"english": "Sable",
|
||||
"canonicalGenotype": "aa c[chm]c[chm] DD EE gg PP spsp rere",
|
||||
"canonicalGenotype": "aa c[chm]c[chm] DD EE gg PP spsp",
|
||||
"sortOrder": 3,
|
||||
"image": "zobel.jpeg"
|
||||
},
|
||||
{
|
||||
"name": "Rotaugenschimmel",
|
||||
"english": "Red-Eyed Roan",
|
||||
"canonicalGenotype": "AA CC DD e[f]e[f] GG pp spsp rere",
|
||||
"canonicalGenotype": "AA CC DD e[f]e[f] GG pp spsp",
|
||||
"sortOrder": 4,
|
||||
"image": "rotaugen-schimmel.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Agouti",
|
||||
"english": "Golden Agouti",
|
||||
"canonicalGenotype": "AA CC DD EE GG PP spsp rere",
|
||||
"canonicalGenotype": "AA CC DD EE GG PP spsp",
|
||||
"sortOrder": 5,
|
||||
"image": "agouti-mit-erklaerung-der-genloci.JPG"
|
||||
},
|
||||
{
|
||||
"name": "Schwarz",
|
||||
"english": "Black",
|
||||
"canonicalGenotype": "aa CC DD EE GG PP spsp rere",
|
||||
"canonicalGenotype": "aa CC DD EE GG PP spsp",
|
||||
"sortOrder": 6,
|
||||
"image": "schwarz.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Silberagouti",
|
||||
"english": "Grey Agouti",
|
||||
"canonicalGenotype": "AA CC DD EE gg PP spsp rere",
|
||||
"canonicalGenotype": "AA CC DD EE gg PP spsp",
|
||||
"sortOrder": 7,
|
||||
"image": "silberagouti.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Anthrazit",
|
||||
"english": "Slate",
|
||||
"canonicalGenotype": "aa CC DD EE gg PP spsp rere",
|
||||
"canonicalGenotype": "aa CC DD EE gg PP spsp",
|
||||
"sortOrder": 8,
|
||||
"image": "anthrazit.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Algierfuchs",
|
||||
"english": "Dark-Eyed Honey",
|
||||
"canonicalGenotype": "AA CC DD ee GG PP spsp rere",
|
||||
"canonicalGenotype": "AA CC DD ee GG PP spsp",
|
||||
"sortOrder": 9,
|
||||
"image": "algierfuchs.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Blau",
|
||||
"english": "Blue",
|
||||
"canonicalGenotype": "aa CC dd EE GG PP spsp rere",
|
||||
"canonicalGenotype": "aa CC dd EE GG PP spsp",
|
||||
"sortOrder": 10,
|
||||
"image": "blau-schwarz-dd.JPG"
|
||||
},
|
||||
{
|
||||
"name": "Gold",
|
||||
"english": "Argente Golden",
|
||||
"canonicalGenotype": "AA CC DD EE GG pp spsp rere",
|
||||
"canonicalGenotype": "AA CC DD EE GG pp spsp",
|
||||
"sortOrder": 11,
|
||||
"image": "gold.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Platin",
|
||||
"english": "Lilac",
|
||||
"canonicalGenotype": "aa CC DD EE GG pp spsp rere",
|
||||
"canonicalGenotype": "aa CC DD EE GG pp spsp",
|
||||
"sortOrder": 12,
|
||||
"image": "platin.JPG"
|
||||
},
|
||||
{
|
||||
"name": "Goldfuchs",
|
||||
"english": "Yellow Fox",
|
||||
"canonicalGenotype": "AA CC DD ee GG pp spsp rere",
|
||||
"canonicalGenotype": "AA CC DD ee GG pp spsp",
|
||||
"sortOrder": 13,
|
||||
"image": "goldfuchs.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Rotfuchs",
|
||||
"english": "Argente Nutmeg",
|
||||
"canonicalGenotype": "aa CC DD ee GG pp spsp rere",
|
||||
"canonicalGenotype": "aa CC DD ee GG pp spsp",
|
||||
"sortOrder": 14,
|
||||
"image": "rotfuchs.JPG"
|
||||
},
|
||||
{
|
||||
"name": "Dilute Gold",
|
||||
"english": "dd Argente Golden",
|
||||
"canonicalGenotype": "AA CC dd EE GG pp spsp rere",
|
||||
"canonicalGenotype": "AA CC dd EE GG pp spsp",
|
||||
"sortOrder": 15,
|
||||
"image": "gold-dd.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Dilute Platin",
|
||||
"english": "dd Lilac",
|
||||
"canonicalGenotype": "aa CC dd EE GG pp spsp rere",
|
||||
"canonicalGenotype": "aa CC dd EE GG pp spsp",
|
||||
"sortOrder": 16,
|
||||
"image": "platin-dd.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Altweiss (REW)",
|
||||
"canonicalGenotype": "aa CC DD EE gg pp spsp rere",
|
||||
"canonicalGenotype": "aa CC DD EE gg pp spsp",
|
||||
"sortOrder": 17,
|
||||
"image": "altweiss-rew.jpeg"
|
||||
},
|
||||
{
|
||||
"name": "Apricot (Blassfuchs)",
|
||||
"canonicalGenotype": "AA CC DD ee gg pp spsp rere",
|
||||
"canonicalGenotype": "AA CC DD ee gg pp spsp",
|
||||
"sortOrder": 18,
|
||||
"image": "apricot-blassfuchs.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Blaufuchs",
|
||||
"canonicalGenotype": "aa CC DD ee gg PP spsp rere",
|
||||
"canonicalGenotype": "aa CC DD ee gg PP spsp",
|
||||
"sortOrder": 19,
|
||||
"image": "blaufuchs.jpg"
|
||||
},
|
||||
{
|
||||
"name": "C-Separator",
|
||||
"canonicalGenotype": "aa CC DD ee gg pp spsp rere",
|
||||
"canonicalGenotype": "aa CC DD ee gg pp spsp",
|
||||
"sortOrder": 20,
|
||||
"image": "c-separator.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Elfenbein",
|
||||
"canonicalGenotype": "AA CC DD EE gg pp spsp rere",
|
||||
"canonicalGenotype": "AA CC DD EE gg pp spsp",
|
||||
"sortOrder": 21,
|
||||
"image": "elfenbein.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Kohlfuchs",
|
||||
"canonicalGenotype": "aa CC DD ee GG PP spsp rere",
|
||||
"canonicalGenotype": "aa CC DD ee GG PP spsp",
|
||||
"sortOrder": 22,
|
||||
"image": "kohlfuchs.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Polarfuchs",
|
||||
"canonicalGenotype": "AA CC DD ee gg PP spsp rere",
|
||||
"canonicalGenotype": "AA CC DD ee gg PP spsp",
|
||||
"sortOrder": 23,
|
||||
"image": "polarfuchs.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Saphir",
|
||||
"canonicalGenotype": "aa CC DD EE GG pp spsp rere",
|
||||
"canonicalGenotype": "aa CC DD EE GG pp spsp",
|
||||
"sortOrder": 24,
|
||||
"image": "saphir.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Orangeschimmel",
|
||||
"canonicalGenotype": "AA CC DD e[f]e[f] GG PP spsp rere",
|
||||
"canonicalGenotype": "AA CC DD e[f]e[f] GG PP spsp",
|
||||
"sortOrder": 25,
|
||||
"image": "schimmel-orangeschimmel.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Topas",
|
||||
"canonicalGenotype": "AA CC DD EE GG pp spsp rere",
|
||||
"canonicalGenotype": "AA CC DD EE GG pp spsp",
|
||||
"sortOrder": 26,
|
||||
"image": "topas.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Platin-Hell",
|
||||
"canonicalGenotype": "aa CC DD EE GG pp spsp rere",
|
||||
"canonicalGenotype": "aa CC DD EE GG pp spsp",
|
||||
"sortOrder": 27,
|
||||
"image": "platin-hell.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Dilute Agouti",
|
||||
"canonicalGenotype": "AA CC dd EE GG PP spsp rere",
|
||||
"canonicalGenotype": "AA CC dd EE GG PP spsp",
|
||||
"sortOrder": 28,
|
||||
"image": "agouti-dd.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Dilute Silberagouti",
|
||||
"canonicalGenotype": "AA CC dd EE gg PP spsp rere",
|
||||
"canonicalGenotype": "AA CC dd EE gg PP spsp",
|
||||
"sortOrder": 29,
|
||||
"image": "silberagouti-dd.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Dilute Kohlfuchs",
|
||||
"canonicalGenotype": "aa CC dd ee GG PP spsp rere",
|
||||
"canonicalGenotype": "aa CC dd ee GG PP spsp",
|
||||
"sortOrder": 30,
|
||||
"image": "kohlfuchs-dd.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Dilute Anthrazit",
|
||||
"canonicalGenotype": "aa CC dd EE gg PP spsp rere",
|
||||
"canonicalGenotype": "aa CC dd EE gg PP spsp",
|
||||
"sortOrder": 31,
|
||||
"image": "anthrazit-dd.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Dilute Algierfuchs",
|
||||
"canonicalGenotype": "AA CC dd ee GG PP spsp rere",
|
||||
"canonicalGenotype": "AA CC dd ee GG PP spsp",
|
||||
"sortOrder": 32
|
||||
},
|
||||
{
|
||||
"name": "Dilute Goldfuchs",
|
||||
"canonicalGenotype": "AA CC dd ee GG pp spsp rere",
|
||||
"canonicalGenotype": "AA CC dd ee GG pp spsp",
|
||||
"sortOrder": 33
|
||||
},
|
||||
{
|
||||
"name": "Dilute Rotfuchs",
|
||||
"canonicalGenotype": "aa CC dd ee GG pp spsp rere",
|
||||
"canonicalGenotype": "aa CC dd ee GG pp spsp",
|
||||
"sortOrder": 34
|
||||
},
|
||||
{
|
||||
"name": "Dilute Polarfuchs",
|
||||
"canonicalGenotype": "AA CC dd ee gg PP spsp rere",
|
||||
"canonicalGenotype": "AA CC dd ee gg PP spsp",
|
||||
"sortOrder": 35
|
||||
},
|
||||
{
|
||||
"name": "Silberschimmel",
|
||||
"canonicalGenotype": "AA CC DD e[f]e[f] gg PP spsp rere",
|
||||
"canonicalGenotype": "AA CC DD e[f]e[f] gg PP spsp",
|
||||
"sortOrder": 36,
|
||||
"image": "silberschimmel.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Polarfuchsschimmel",
|
||||
"canonicalGenotype": "AA CC DD e[f]e[f] gg PP spsp rere",
|
||||
"canonicalGenotype": "AA CC DD e[f]e[f] gg PP spsp",
|
||||
"sortOrder": 37,
|
||||
"image": "polarfuchsschimmel.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Algierfuchsschimmel",
|
||||
"canonicalGenotype": "AA CC DD e[f]e[f] GG PP spsp rere",
|
||||
"canonicalGenotype": "AA CC DD e[f]e[f] GG PP spsp",
|
||||
"sortOrder": 38,
|
||||
"image": "algierfuchsschimmel.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Kohlfuchsschimmel",
|
||||
"canonicalGenotype": "aa CC DD e[f]e[f] GG PP spsp rere",
|
||||
"canonicalGenotype": "aa CC DD e[f]e[f] GG PP spsp",
|
||||
"sortOrder": 39,
|
||||
"image": "kohlfuchsschimmel.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Blaufuchsschimmel",
|
||||
"canonicalGenotype": "aa CC DD e[f]e[f] gg PP spsp rere",
|
||||
"canonicalGenotype": "aa CC DD e[f]e[f] gg PP spsp",
|
||||
"sortOrder": 40,
|
||||
"image": "blaufuchsschimmel.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Kohlfuchs, hell",
|
||||
"canonicalGenotype": "aa CC DD ee GG PP spsp rere",
|
||||
"canonicalGenotype": "aa CC DD ee GG PP spsp",
|
||||
"sortOrder": 41,
|
||||
"image": "kohlfuchs-hell.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Goldfuchs, hell",
|
||||
"canonicalGenotype": "AA CC DD ee GG pp spsp rere",
|
||||
"canonicalGenotype": "AA CC DD ee GG pp spsp",
|
||||
"sortOrder": 42,
|
||||
"image": "goldfuchs-hell.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Goldfuchsschimmel",
|
||||
"canonicalGenotype": "AA CC DD e[f]e[f] GG pp spsp rere",
|
||||
"canonicalGenotype": "AA CC DD e[f]e[f] GG pp spsp",
|
||||
"sortOrder": 43,
|
||||
"image": "goldfuchsschimmel.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Gold-Hell",
|
||||
"canonicalGenotype": "AA CC DD EE GG pp spsp rere",
|
||||
"canonicalGenotype": "AA CC DD EE GG pp spsp",
|
||||
"sortOrder": 44,
|
||||
"image": "gold-hell.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Blaufuchs, hell",
|
||||
"canonicalGenotype": "aa CC DD ee gg PP spsp rere",
|
||||
"canonicalGenotype": "aa CC DD ee gg PP spsp",
|
||||
"sortOrder": 45,
|
||||
"image": "blaufuchs-hell.jpeg"
|
||||
},
|
||||
{
|
||||
"name": "Rotfuchsschimmel",
|
||||
"canonicalGenotype": "aa CC DD e[f]e[f] GG pp spsp rere",
|
||||
"canonicalGenotype": "aa CC DD e[f]e[f] GG pp spsp",
|
||||
"sortOrder": 46,
|
||||
"image": "rotfuchsschimmel.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Polarfuchs, hell",
|
||||
"canonicalGenotype": "AA CC DD ee gg PP spsp rere",
|
||||
"canonicalGenotype": "AA CC DD ee gg PP spsp",
|
||||
"sortOrder": 47,
|
||||
"image": "polarfuchs-hell.jpeg"
|
||||
},
|
||||
{
|
||||
"name": "Kohlfuchsschimmel, hell",
|
||||
"canonicalGenotype": "aa CC DD e[f]e[f] GG PP spsp rere",
|
||||
"canonicalGenotype": "aa CC DD e[f]e[f] GG PP spsp",
|
||||
"sortOrder": 48,
|
||||
"image": "kohlfuchsschimmel-hell.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Rotfuchs, hell",
|
||||
"canonicalGenotype": "aa CC DD ee GG pp spsp rere",
|
||||
"canonicalGenotype": "aa CC DD ee GG pp spsp",
|
||||
"sortOrder": 49,
|
||||
"image": "rotfuchs-hell.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Kohlfuchs-Hell",
|
||||
"canonicalGenotype": "aa CC DD ee GG PP spsp rere",
|
||||
"canonicalGenotype": "aa CC DD ee GG PP spsp",
|
||||
"sortOrder": 50,
|
||||
"image": "kohlfuchs-hell-2.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Algierfuchs, hell",
|
||||
"canonicalGenotype": "AA CC DD ee GG PP spsp rere",
|
||||
"canonicalGenotype": "AA CC DD ee GG PP spsp",
|
||||
"sortOrder": 51,
|
||||
"image": "algierfuchs-hell.JPG"
|
||||
},
|
||||
{
|
||||
"name": "Dilute Topas",
|
||||
"canonicalGenotype": "AA CC dd EE GG pp spsp rere",
|
||||
"canonicalGenotype": "AA CC dd EE GG pp spsp",
|
||||
"sortOrder": 52,
|
||||
"image": "topas-dd.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Dilute Blaufuchs",
|
||||
"canonicalGenotype": "aa CC dd ee gg pp spsp rere",
|
||||
"canonicalGenotype": "aa CC dd ee gg pp spsp",
|
||||
"sortOrder": 53,
|
||||
"image": "blaufuchs-dd.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Marder",
|
||||
"canonicalGenotype": "aa c[chm]c[chm] DD EE GG PP spsp rere",
|
||||
"canonicalGenotype": "aa c[chm]c[chm] DD EE GG PP spsp",
|
||||
"sortOrder": 54,
|
||||
"image": "marder.JPG"
|
||||
},
|
||||
{
|
||||
"name": "Siam",
|
||||
"canonicalGenotype": "aa c[chm]c[h] DD EE GG PP spsp rere",
|
||||
"canonicalGenotype": "aa c[chm]c[h] DD EE GG PP spsp",
|
||||
"sortOrder": 55,
|
||||
"image": "siam-marder-hell.JPG"
|
||||
},
|
||||
{
|
||||
"name": "Zobel-Hell",
|
||||
"canonicalGenotype": "aa c[chm]c[h] DD EE gg PP spsp rere",
|
||||
"canonicalGenotype": "aa c[chm]c[h] DD EE gg PP spsp",
|
||||
"sortOrder": 56,
|
||||
"image": "zobel-hell.jpg"
|
||||
},
|
||||
{
|
||||
"name": "CP-Agouti",
|
||||
"canonicalGenotype": "AA c[chm]c[chm] DD EE GG PP spsp rere",
|
||||
"canonicalGenotype": "AA c[chm]c[chm] DD EE GG PP spsp",
|
||||
"sortOrder": 57,
|
||||
"image": "agouti-cp.jpg"
|
||||
},
|
||||
{
|
||||
"name": "CP-Agouti-Hell",
|
||||
"canonicalGenotype": "AA c[chm]c[h] DD EE GG PP spsp rere",
|
||||
"canonicalGenotype": "AA c[chm]c[h] DD EE GG PP spsp",
|
||||
"sortOrder": 58
|
||||
},
|
||||
{
|
||||
"name": "CP-Silberagouti",
|
||||
"canonicalGenotype": "AA c[chm]c[chm] DD EE gg PP spsp rere",
|
||||
"canonicalGenotype": "AA c[chm]c[chm] DD EE gg PP spsp",
|
||||
"sortOrder": 59,
|
||||
"image": "silberagouti-cp.JPG"
|
||||
},
|
||||
{
|
||||
"name": "CP-Silberagouti-Hell",
|
||||
"canonicalGenotype": "AA c[chm]c[h] DD EE gg PP spsp rere",
|
||||
"canonicalGenotype": "AA c[chm]c[h] DD EE gg PP spsp",
|
||||
"sortOrder": 60
|
||||
},
|
||||
{
|
||||
"name": "CP-Algierfuchs",
|
||||
"canonicalGenotype": "AA c[chm]c[chm] DD ee GG PP spsp rere",
|
||||
"canonicalGenotype": "AA c[chm]c[chm] DD ee GG PP spsp",
|
||||
"sortOrder": 61,
|
||||
"image": "algierfuchs-cp.jpg"
|
||||
},
|
||||
{
|
||||
"name": "CP-Algierfuchs-Hell",
|
||||
"canonicalGenotype": "AA c[chm]c[h] DD ee GG PP spsp rere",
|
||||
"canonicalGenotype": "AA c[chm]c[h] DD ee GG PP spsp",
|
||||
"sortOrder": 62
|
||||
},
|
||||
{
|
||||
"name": "CP-Polarfuchs",
|
||||
"canonicalGenotype": "AA c[chm]c[chm] DD ee gg PP spsp rere",
|
||||
"canonicalGenotype": "AA c[chm]c[chm] DD ee gg PP spsp",
|
||||
"sortOrder": 63,
|
||||
"image": "polarfuchs-cp.jpg"
|
||||
},
|
||||
{
|
||||
"name": "CP-Polarfuchs-Hell",
|
||||
"canonicalGenotype": "AA c[chm]c[h] DD ee gg PP spsp rere",
|
||||
"canonicalGenotype": "AA c[chm]c[h] DD ee gg PP spsp",
|
||||
"sortOrder": 64
|
||||
},
|
||||
{
|
||||
"name": "CP-Fuchs",
|
||||
"canonicalGenotype": "AA c[chm]c[chm] dd ee GG PP spsp rere",
|
||||
"canonicalGenotype": "AA c[chm]c[chm] dd ee GG PP spsp",
|
||||
"sortOrder": 65
|
||||
},
|
||||
{
|
||||
"name": "CP-Fuchs-Hell",
|
||||
"canonicalGenotype": "AA c[chm]c[h] dd ee GG PP spsp rere",
|
||||
"canonicalGenotype": "AA c[chm]c[h] dd ee GG PP spsp",
|
||||
"sortOrder": 66
|
||||
},
|
||||
{
|
||||
"name": "CP-Blaufuchs",
|
||||
"canonicalGenotype": "AA c[chm]c[chm] dd ee gg PP spsp rere",
|
||||
"canonicalGenotype": "AA c[chm]c[chm] dd ee gg PP spsp",
|
||||
"sortOrder": 67
|
||||
},
|
||||
{
|
||||
"name": "CP-Orangeschimmel",
|
||||
"canonicalGenotype": "AA c[chm]c[chm] DD e[f]e[f] GG PP spsp rere",
|
||||
"canonicalGenotype": "AA c[chm]c[chm] DD e[f]e[f] GG PP spsp",
|
||||
"sortOrder": 68
|
||||
},
|
||||
{
|
||||
"name": "CP-Orangeschimmel-Hell",
|
||||
"canonicalGenotype": "AA c[chm]c[h] DD e[f]e[f] GG PP spsp rere",
|
||||
"canonicalGenotype": "AA c[chm]c[h] DD e[f]e[f] GG PP spsp",
|
||||
"sortOrder": 69
|
||||
}
|
||||
]
|
||||
|
||||
@@ -101,18 +101,21 @@ function displayPair(locus: LocusKey, pair: AllelePair): AllelePair {
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact display string, e.g. "Aa CC Dd EE GG Pp spsp rere".
|
||||
* The Sls locus is OMITTED when wild-type (sl/sl) so legacy 8-locus strings and
|
||||
* the colour catalog stay byte-identical; it only appears for WP/Sls carriers
|
||||
* (e.g. "… spsp rere Slsl"). Round-trips: a missing Sls re-parses to sl/sl.
|
||||
* GEN-3c: unknown alleles are STORED as '?' but DISPLAYED as '-' (breeder
|
||||
* convention) — e.g. ['C','?'] renders "C-".
|
||||
* GEN-3h: sub-alleles use breeder bracket notation (e[f], c[chm], c[h]);
|
||||
* E-locus display order is E > e > e[f] (e before e[f] in het pairs).
|
||||
* Compact display string, e.g. "Aa CC Dd EE GG Pp spsp".
|
||||
* The Re locus is OMITTED when wild-type (re/re) — Julian: only show Rex when a
|
||||
* Rex allele is present (Rere/ReRe). Matches the 7-locus notation used by the
|
||||
* breeder. The Sls locus is likewise omitted when wild-type (sl/sl) so legacy
|
||||
* 8-locus strings and the colour catalog stay byte-identical; it only appears for
|
||||
* WP/Sls carriers (e.g. "… spsp Slsl"). Round-trips: missing Re → re/re; missing
|
||||
* Sls → sl/sl. GEN-3c: unknown alleles stored as '?' displayed as '-' (breeder
|
||||
* convention). GEN-3h: bracket notation (e[f], c[chm], c[h]); E-locus display
|
||||
* order E > e > e[f].
|
||||
*/
|
||||
export function toDisplayString(g: Genotype): string {
|
||||
return LOCUS_ORDER.filter(
|
||||
(locus) => locus !== 'Sls' || !(g.Sls[0] === 'sl' && g.Sls[1] === 'sl'),
|
||||
(locus) =>
|
||||
!(locus === 'Re' && g.Re[0] === 're' && g.Re[1] === 're') &&
|
||||
!(locus === 'Sls' && g.Sls[0] === 'sl' && g.Sls[1] === 'sl'),
|
||||
)
|
||||
.map((locus) => {
|
||||
const [a, b] = displayPair(locus, g[locus])
|
||||
@@ -189,6 +192,11 @@ function normalizeToken(tok: string): string | null {
|
||||
// the generic [-]→? rule below (which makes the bracket-dash a wildcard,
|
||||
// leaving the leading allele intact for splitToken).
|
||||
t = t.replace(/(?<=[A-Za-z])e\[-\]/g, '?')
|
||||
t = t.replace(/(?<=[A-Za-z])c\[-\]/g, '?')
|
||||
t = t.replace(/(?<=[A-Za-z])c$/g, '?')
|
||||
t = t.replace(/^c\[-\]$/g, '??')
|
||||
t = t.replace(/^c\?$/g, '??')
|
||||
t = t.replace(/^c$/g, '??')
|
||||
t = t.replace(/\[-\]/g, '?') // bare/standalone bracket-unknown → wildcard
|
||||
// GEN-3c: plain dash is the breeder's UNKNOWN marker on input; store internally as '?'.
|
||||
t = t.replace(/-/g, '?')
|
||||
@@ -254,6 +262,25 @@ export function fromDisplayString(input: string): Genotype {
|
||||
return makeGenotype({ ...base, ...acc })
|
||||
}
|
||||
|
||||
export function displayGenotypeSafe(raw: string | null | undefined): string {
|
||||
if (!raw) return ''
|
||||
try {
|
||||
const parsed = fromDisplayString(raw)
|
||||
return toDisplayString(parsed)
|
||||
} catch {
|
||||
// Fallback path:
|
||||
return raw
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.filter((tok) => {
|
||||
const norm = normalizeToken(tok)
|
||||
return norm !== null && norm !== '?' && norm !== '??'
|
||||
})
|
||||
.map((tok) => tok.replace(/\?/g, '-'))
|
||||
.join(' ')
|
||||
}
|
||||
}
|
||||
|
||||
export function hasUnknown(g: Genotype): boolean {
|
||||
return LOCUS_ORDER.some((l) => g[l][0] === WILDCARD || g[l][1] === WILDCARD)
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ export {
|
||||
toJSON,
|
||||
fromJSON,
|
||||
hasUnknown,
|
||||
displayGenotypeSafe,
|
||||
WILDCARD,
|
||||
} from './genotype'
|
||||
export type { Genotype, AllelePair } from './genotype'
|
||||
|
||||
@@ -21,7 +21,7 @@ export interface AsyncState<T> {
|
||||
reload: () => void
|
||||
}
|
||||
|
||||
function messageFor(err: unknown): string {
|
||||
export function messageFor(err: unknown): string {
|
||||
if (err instanceof ApiError) return err.message
|
||||
if (err instanceof Error && err.message) return err.message
|
||||
return de.api.errors.unknown
|
||||
|
||||
116
gerbil-manager-web/src/hooks/useInfiniteList.ts
Normal file
116
gerbil-manager-web/src/hooks/useInfiniteList.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* Server-paginated infinite list (no react-query).
|
||||
*
|
||||
* `loader(page)` fetches ONE page; pages are accumulated into `items`. The list
|
||||
* never loads everything up front — `loadMore()` (wired to a scroll sentinel)
|
||||
* advances exactly one page at a time until `hasMore` is false.
|
||||
*
|
||||
* Changing `resetKey` (e.g. the filter/sort/search signature) clears the list and
|
||||
* reloads from page 1. `reload()` re-fetches page 1 on demand (e.g. retry).
|
||||
*
|
||||
* Design mirrors useApi (and satisfies the strict react-hooks rules):
|
||||
* - the request signature lives in `req`; the query reset on `resetKey` change is
|
||||
* an in-render state adjustment (not a setState-in-effect), so no cascade.
|
||||
* - `loading` / `loadingMore` are DERIVED from resolved-vs-current request keys,
|
||||
* never set synchronously inside the fetch effect.
|
||||
* - the loader is read through a ref so the effect keys purely on the request id.
|
||||
*/
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { messageFor } from './useApi'
|
||||
import type { Paged } from '../api/types'
|
||||
|
||||
export interface InfiniteListState<T> {
|
||||
items: T[]
|
||||
total: number
|
||||
/** Initial / reset load (page 1) in flight. */
|
||||
loading: boolean
|
||||
/** A subsequent page is being appended. */
|
||||
loadingMore: boolean
|
||||
error: string | null
|
||||
hasMore: boolean
|
||||
/** Advance one page; the scroll sentinel calls this. */
|
||||
loadMore: () => void
|
||||
/** Re-fetch from page 1 (retry). */
|
||||
reload: () => void
|
||||
}
|
||||
|
||||
interface Req {
|
||||
key: string
|
||||
page: number
|
||||
nonce: number
|
||||
}
|
||||
|
||||
interface Resolved<T> {
|
||||
reqId: string
|
||||
items: T[]
|
||||
total: number
|
||||
error: string | null
|
||||
}
|
||||
|
||||
export function useInfiniteList<T>(
|
||||
loader: (page: number) => Promise<Paged<T>>,
|
||||
resetKey: string,
|
||||
): InfiniteListState<T> {
|
||||
const loaderRef = useRef(loader)
|
||||
useEffect(() => {
|
||||
loaderRef.current = loader
|
||||
})
|
||||
|
||||
const [req, setReq] = useState<Req>({ key: resetKey, page: 1, nonce: 0 })
|
||||
// Adjust state during render when the query signature changes — the recommended
|
||||
// pattern for deriving state from changed inputs (no setState-in-effect cascade).
|
||||
if (req.key !== resetKey) {
|
||||
setReq({ key: resetKey, page: 1, nonce: 0 })
|
||||
}
|
||||
|
||||
const queryId = `${req.nonce}:${req.key}`
|
||||
const reqId = `${queryId}#${req.page}`
|
||||
|
||||
const [resolved, setResolved] = useState<Resolved<T>>({
|
||||
reqId: '',
|
||||
items: [],
|
||||
total: 0,
|
||||
error: null,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
const page = req.page
|
||||
const id = `${req.nonce}:${req.key}#${page}`
|
||||
loaderRef
|
||||
.current(page)
|
||||
.then((res) => {
|
||||
if (cancelled) return
|
||||
setResolved((prev) => ({
|
||||
reqId: id,
|
||||
// page 1 replaces (fresh query); later pages append.
|
||||
items: page === 1 ? res.items : [...prev.items, ...res.items],
|
||||
total: res.totalCount,
|
||||
error: null,
|
||||
}))
|
||||
})
|
||||
.catch((err) => {
|
||||
if (!cancelled) setResolved((prev) => ({ ...prev, reqId: id, error: messageFor(err) }))
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [req]) // req is a fresh object per change (key/page/nonce) → one fetch per change
|
||||
|
||||
// Resolved data only counts if it belongs to the current query signature.
|
||||
const resolvedQueryId = resolved.reqId.slice(0, resolved.reqId.lastIndexOf('#'))
|
||||
const sameQuery = resolved.reqId !== '' && resolvedQueryId === queryId
|
||||
const inFlight = resolved.reqId !== reqId
|
||||
|
||||
const items = sameQuery ? resolved.items : []
|
||||
const total = sameQuery ? resolved.total : 0
|
||||
const loading = !sameQuery || (inFlight && req.page === 1)
|
||||
const loadingMore = sameQuery && inFlight && req.page > 1
|
||||
const error = inFlight ? null : sameQuery ? resolved.error : null
|
||||
const hasMore = sameQuery && !inFlight && items.length < total
|
||||
|
||||
const loadMore = useCallback(() => setReq((r) => ({ ...r, page: r.page + 1 })), [])
|
||||
const reload = useCallback(() => setReq((r) => ({ key: r.key, page: 1, nonce: r.nonce + 1 })), [])
|
||||
|
||||
return { items, total, loading, loadingMore, error, hasMore, loadMore, reload }
|
||||
}
|
||||
@@ -2,15 +2,20 @@
|
||||
Seitenleiste links ab 768px (Laptop). */
|
||||
|
||||
:root {
|
||||
--color-bg: #faf7f2;
|
||||
/* DESIGN (Rennmaus Filter): the app palette is the design's creme/brown/terracotta. */
|
||||
--color-bg: #f6efe2;
|
||||
--color-surface: #ffffff;
|
||||
--color-border: #e5ddd0;
|
||||
--color-text: #3b3026;
|
||||
--color-text-muted: #8a7d6b;
|
||||
--color-accent: #b5651d;
|
||||
--color-accent-soft: #f6e7d7;
|
||||
--color-border: #e7dcc8;
|
||||
--color-text: #3d2e23;
|
||||
--color-text-muted: #8c7f6e;
|
||||
--color-text-faint: #b4a790;
|
||||
--color-accent: #a85f2e;
|
||||
--color-accent-soft: #f3e7da;
|
||||
/* DESIGN (Rennmaus Filter): the single soft elevation used on cards, pills,
|
||||
the search bar and buttons. */
|
||||
--shadow: 0 1px 2px rgba(61, 46, 35, 0.06), 0 2px 8px rgba(61, 46, 35, 0.05);
|
||||
|
||||
font-family: system-ui, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
|
||||
font-family: 'Hanken Grotesk', system-ui, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
|
||||
line-height: 1.5;
|
||||
color: var(--color-text);
|
||||
background-color: var(--color-bg);
|
||||
@@ -41,46 +46,41 @@ a {
|
||||
|
||||
/* --- Grundgerüst (Smartphone) --- */
|
||||
|
||||
/* DESIGN: the top "Rennmaus-Manager" title bar is removed; on mobile only the
|
||||
bottom action bar remains, on desktop the left sidebar.
|
||||
The shell is a fixed viewport box and ONLY the main area scrolls — so the bottom
|
||||
nav (mobile) and the sidebar (desktop) stay put, and the page header's
|
||||
position: sticky pins reliably to the top of the scrolling main area. */
|
||||
.app-shell {
|
||||
display: grid;
|
||||
min-height: 100dvh;
|
||||
grid-template-rows: auto 1fr auto;
|
||||
height: 100dvh;
|
||||
overflow: hidden;
|
||||
grid-template-rows: 1fr auto;
|
||||
grid-template-areas:
|
||||
'header'
|
||||
'main'
|
||||
'nav';
|
||||
}
|
||||
|
||||
.app-header {
|
||||
grid-area: header;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.75rem 1rem;
|
||||
background: var(--color-surface);
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
}
|
||||
|
||||
.app-logo {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
.app-title {
|
||||
font-size: 1.15rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.app-main {
|
||||
grid-area: main;
|
||||
padding: 1rem;
|
||||
/* No top padding: the page's sticky header pins flush to the top with no gap
|
||||
(pages add their own top spacing via .page). */
|
||||
padding: 0 1rem 1.5rem;
|
||||
max-width: 60rem;
|
||||
width: 100%;
|
||||
/* UX-MOBILE-2: prevent any wide content (e.g. genotype table) from making
|
||||
the page body scroll horizontally. The .genotype-table-scroll wrapper
|
||||
provides the per-table horizontal scroll. */
|
||||
/* MAIN is the scroll container: min-height:0 lets the 1fr grid row shrink below
|
||||
its content so it can scroll. overflow-anchor:none stops the browser from
|
||||
re-adjusting scroll when the sticky title collapses (no scroll "fight"). */
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
overflow-anchor: none;
|
||||
}
|
||||
|
||||
/* Top spacing for page content (replaces the removed .app-main top padding). The
|
||||
Rennmäuse page opts out — its sticky header provides its own top padding. */
|
||||
.page {
|
||||
padding-top: 1rem;
|
||||
}
|
||||
|
||||
/* Tab-Leiste unten */
|
||||
@@ -92,6 +92,8 @@ a {
|
||||
border-top: 1px solid var(--color-border);
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
/* Above the sticky page header + cards so it is never overlapped. */
|
||||
z-index: 30;
|
||||
padding-bottom: env(safe-area-inset-bottom);
|
||||
}
|
||||
|
||||
@@ -122,10 +124,8 @@ a {
|
||||
@media (min-width: 768px) {
|
||||
.app-shell {
|
||||
grid-template-columns: 14rem 1fr;
|
||||
grid-template-rows: auto 1fr;
|
||||
grid-template-areas:
|
||||
'header header'
|
||||
'nav main';
|
||||
grid-template-rows: 1fr;
|
||||
grid-template-areas: 'nav main';
|
||||
}
|
||||
|
||||
.app-nav {
|
||||
@@ -136,6 +136,9 @@ a {
|
||||
border-right: 1px solid var(--color-border);
|
||||
padding: 1rem 0.5rem;
|
||||
position: static;
|
||||
/* Sidebar stays fixed; scrolls internally only if the link list is taller
|
||||
than the viewport. */
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.nav-link {
|
||||
@@ -156,7 +159,7 @@ a {
|
||||
}
|
||||
|
||||
.app-main {
|
||||
padding: 1.5rem 2rem;
|
||||
padding: 0 2rem 1.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import { listLitters as listLittersPaged } from '../api/litters'
|
||||
import { listColorVarieties, listContacts, listEnclosures, listLitters } from '../api/lookups'
|
||||
import { useApi, useMutation } from '../hooks/useApi'
|
||||
import { formatDate, genderLabel, statusLabel } from '../format/labels'
|
||||
import { fromDisplayString, genotypeToFarbschlag, toDisplayString } from '../genetics'
|
||||
import { fromDisplayString, genotypeToFarbschlag, displayGenotypeSafe } from '../genetics'
|
||||
import FarbschlagImage from '../components/FarbschlagImage'
|
||||
import Charakterbogen from '../components/Charakterbogen'
|
||||
// FEAT-6 (Oscar): Tab-Inhalte + Profilfoto
|
||||
@@ -22,10 +22,10 @@ function describeGenotype(genotype: string | null): { display: string; farbschla
|
||||
if (!genotype || !genotype.trim()) return null
|
||||
try {
|
||||
const g = fromDisplayString(genotype)
|
||||
return { display: toDisplayString(g), farbschlag: genotypeToFarbschlag(g) }
|
||||
return { display: displayGenotypeSafe(genotype), farbschlag: genotypeToFarbschlag(g) }
|
||||
} catch {
|
||||
// Unparseable: show the raw value, no derived Farbschlag.
|
||||
return { display: genotype, farbschlag: de.genetics.unknownFarbschlag }
|
||||
// Unparseable: show the safely-rendered raw value, no derived Farbschlag.
|
||||
return { display: displayGenotypeSafe(genotype), farbschlag: de.genetics.unknownFarbschlag }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,10 +3,10 @@ import { Link, useNavigate, useParams, useSearchParams } from 'react-router-dom'
|
||||
import { de } from '../strings/de'
|
||||
import { createGerbil, getGerbil, updateGerbil } from '../api/gerbils'
|
||||
import { listColorVarieties, listContacts, listEnclosures, listLitters } from '../api/lookups'
|
||||
import { GENDERS, GERBIL_STATUSES, type CreateGerbil, type Gender, type GerbilStatus } from '../api/types'
|
||||
import { GENDERS, SELECTABLE_STATUSES, type CreateGerbil, type Gender, type GerbilStatus } from '../api/types'
|
||||
import { useApi, useMutation } from '../hooks/useApi'
|
||||
import { genderLabel, statusLabel } from '../format/labels'
|
||||
import { fromDisplayString } from '../genetics'
|
||||
import { fromDisplayString, genotypeToFarbschlag, UNKNOWN_FARBSCHLAG } from '../genetics'
|
||||
import FarbschlagImage from '../components/FarbschlagImage'
|
||||
import NameSuggestPanel from '../components/NameSuggestPanel'
|
||||
import '../components/NameSuggestPanel.css'
|
||||
@@ -34,7 +34,7 @@ interface FormState {
|
||||
const EMPTY: FormState = {
|
||||
name: '',
|
||||
gender: '',
|
||||
status: 'Active',
|
||||
status: 'Breeding',
|
||||
dateOfBirth: '',
|
||||
dateOfDeath: '',
|
||||
causeOfDeath: '',
|
||||
@@ -245,16 +245,29 @@ export default function GerbilFormPage() {
|
||||
{errors.gender && <small className="error-text">{errors.gender}</small>}
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span>{t.fields.status}</span>
|
||||
<select value={form.status} onChange={(e) => set('status', e.target.value as GerbilStatus)}>
|
||||
{GERBIL_STATUSES.map((s) => (
|
||||
<option key={s} value={s}>
|
||||
{statusLabel(s)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{/* STATUS-MODEL: Deceased/GivenAway are derived by the backend — show as read-only with hint */}
|
||||
{form.status === 'Deceased' || form.status === 'GivenAway' ? (
|
||||
<div className="field">
|
||||
<span>{t.fields.status}</span>
|
||||
<span className="muted">
|
||||
{statusLabel(form.status)}
|
||||
<small className="muted" style={{ marginLeft: '0.5rem' }}>
|
||||
({t.form.statusDerivedHint[form.status]})
|
||||
</small>
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<label className="field">
|
||||
<span>{t.fields.status}</span>
|
||||
<select value={form.status} onChange={(e) => set('status', e.target.value as GerbilStatus)}>
|
||||
{SELECTABLE_STATUSES.map((s) => (
|
||||
<option key={s} value={s}>
|
||||
{statusLabel(s)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
|
||||
<label className="field">
|
||||
<span>{t.fields.dateOfBirth}</span>
|
||||
@@ -307,7 +320,14 @@ export default function GerbilFormPage() {
|
||||
<span className="farbschlag-value">
|
||||
<select
|
||||
value={form.colorVarietyId}
|
||||
onChange={(e) => set('colorVarietyId', e.target.value)}
|
||||
onChange={(e) => {
|
||||
const newId = e.target.value
|
||||
set('colorVarietyId', newId)
|
||||
if (newId) {
|
||||
const variety = (colorVarieties.data ?? []).find((cv) => cv.id === newId)
|
||||
if (variety?.canonicalGenotype) set('genotype', variety.canonicalGenotype)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="">{t.form.none}</option>
|
||||
{(colorVarieties.data ?? []).map((cv) => (
|
||||
@@ -387,7 +407,23 @@ export default function GerbilFormPage() {
|
||||
className="input"
|
||||
value={form.genotype}
|
||||
placeholder="Aa CC Dd EE GG Pp Spsp rere"
|
||||
onChange={(e) => set('genotype', e.target.value)}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value
|
||||
set('genotype', val)
|
||||
if (val.trim() !== '' && isGenotypeValid(val)) {
|
||||
try {
|
||||
const name = genotypeToFarbschlag(fromDisplayString(val))
|
||||
if (name === UNKNOWN_FARBSCHLAG) {
|
||||
set('colorVarietyId', '')
|
||||
} else {
|
||||
const match = (colorVarieties.data ?? []).find((cv) => cv.name === name)
|
||||
set('colorVarietyId', match?.id ?? '')
|
||||
}
|
||||
} catch {
|
||||
// invalid while typing — leave colorVarietyId unchanged
|
||||
}
|
||||
}
|
||||
}}
|
||||
aria-invalid={Boolean(errors.genotype)}
|
||||
/>
|
||||
<small className={errors.genotype ? 'error-text' : 'muted'}>
|
||||
|
||||
Binary file not shown.
@@ -21,13 +21,15 @@ import { Link, useNavigate, useParams } from 'react-router-dom'
|
||||
import Tree from 'react-d3-tree'
|
||||
import type { CustomNodeElementProps, Point, RawNodeDatum } from 'react-d3-tree'
|
||||
import { de } from '../strings/de'
|
||||
import { ApiError } from '../api/client'
|
||||
import { API_BASE_URL, ApiError } from '../api/client'
|
||||
import { listLitters } from '../api/litters'
|
||||
import { listColorVarieties } from '../api/lookups'
|
||||
import { getInbreedingCoefficient } from '../api/pedigree'
|
||||
import type { Gender, Gerbil } from '../api/types'
|
||||
import type { Gender, Gerbil, Litter } from '../api/types'
|
||||
import { useApi } from '../hooks/useApi'
|
||||
import { formatDate, genderLabel } from '../format/labels'
|
||||
import { UNKNOWN_FARBSCHLAG, fromDisplayString, genotypeToFarbschlag } from '../genetics'
|
||||
import GerbilIcon from '../components/GerbilIcon'
|
||||
import { UNKNOWN_FARBSCHLAG, fromDisplayString, genotypeToFarbschlag, displayGenotypeSafe } from '../genetics'
|
||||
import {
|
||||
DEFAULT_GENERATIONS,
|
||||
ancestorsAt,
|
||||
@@ -156,6 +158,13 @@ export default function StammbaumPage() {
|
||||
? `${(inbreeding.data * 100).toLocaleString('de-DE', { maximumFractionDigits: 1 })} %`
|
||||
: t.inbreeding.unavailable
|
||||
|
||||
/* ── Würfe des Wurzeltiers (STAMMBAUM-LITTERS): aktualisiert bei Umwurzeln ── */
|
||||
const rootLitters = useApi(
|
||||
() => listLitters({ filter: `fatherId=${id}|motherId=${id}`, orderBy: 'date desc', pageSize: 50 }),
|
||||
[id],
|
||||
)
|
||||
const rootLitterItems = rootLitters.data?.items ?? []
|
||||
|
||||
/* ── react-d3-tree-Daten ── */
|
||||
const nodesByPath = useMemo(() => (root ? collectNodes(root) : null), [root])
|
||||
const datum = useMemo(() => (root ? toRawNodeDatum(root, t.unknown) : null), [root, t])
|
||||
@@ -315,27 +324,36 @@ export default function StammbaumPage() {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="stammbaum-canvas" ref={canvasRef}>
|
||||
{view && (
|
||||
<Tree
|
||||
key={id}
|
||||
data={datum}
|
||||
renderCustomNodeElement={renderNode}
|
||||
orientation="horizontal"
|
||||
pathFunc="step"
|
||||
translate={view.translate}
|
||||
zoom={view.zoom}
|
||||
scaleExtent={{ min: ZOOM_MIN, max: ZOOM_MAX }}
|
||||
zoomable
|
||||
draggable
|
||||
collapsible={false}
|
||||
nodeSize={{ x: NODE_X, y: NODE_Y }}
|
||||
separation={{ siblings: 1, nonSiblings: 1 }}
|
||||
onUpdate={handleTreeUpdate}
|
||||
/>
|
||||
<div className="stammbaum-layout">
|
||||
{rootLitterItems.length > 0 && (
|
||||
<LittersPanel litters={rootLitterItems} t={t} />
|
||||
)}
|
||||
<div className="stammbaum-canvas" ref={canvasRef}>
|
||||
{view && (
|
||||
<Tree
|
||||
key={id}
|
||||
data={datum}
|
||||
renderCustomNodeElement={renderNode}
|
||||
orientation="horizontal"
|
||||
pathFunc="step"
|
||||
translate={view.translate}
|
||||
zoom={view.zoom}
|
||||
scaleExtent={{ min: ZOOM_MIN, max: ZOOM_MAX }}
|
||||
zoomable
|
||||
draggable
|
||||
collapsible={false}
|
||||
nodeSize={{ x: NODE_X, y: NODE_Y }}
|
||||
separation={{ siblings: 1, nonSiblings: 1 }}
|
||||
onUpdate={handleTreeUpdate}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<p className="stammbaum-hint">{t.tapHint}</p>
|
||||
<ul className="stammbaum-hints">
|
||||
<li>{t.tapHint}</li>
|
||||
<li>{t.hintName}</li>
|
||||
<li>{t.hintExpand}</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
{/* Druckansicht: am Bildschirm unsichtbar, ersetzt beim Drucken alles. */}
|
||||
@@ -362,7 +380,14 @@ function PedigreeCard({
|
||||
const t = de.pages.stammbaum
|
||||
const g = node.gerbil
|
||||
const chip = farbschlag ? chipColorFor(farbschlag) : null
|
||||
const year = g.dateOfBirth ? g.dateOfBirth.slice(0, 4) : null
|
||||
const dob = g.dateOfBirth ? formatDate(g.dateOfBirth) : null
|
||||
const [failedUrl, setFailedUrl] = useState<string | null>(null)
|
||||
const rawUrl = g.profilePhotoUrl
|
||||
? /^(https?:|data:|\/\/)/.test(g.profilePhotoUrl)
|
||||
? g.profilePhotoUrl
|
||||
: `${API_BASE_URL}${g.profilePhotoUrl}`
|
||||
: null
|
||||
const photoUrl = rawUrl !== failedUrl ? rawUrl : null
|
||||
return (
|
||||
<div
|
||||
className={isRoot ? 'pedigree-card pedigree-card--root' : 'pedigree-card'}
|
||||
@@ -370,9 +395,17 @@ function PedigreeCard({
|
||||
role={isRoot ? undefined : 'button'}
|
||||
title={isRoot ? undefined : t.tapHint}
|
||||
>
|
||||
{/* Foto-Platzhalter — echte Fotos kommen mit FEAT-6. */}
|
||||
<div className="pedigree-card__photo" aria-hidden="true">
|
||||
🐭
|
||||
<div className="pedigree-card__photo" aria-hidden={!photoUrl || undefined}>
|
||||
{photoUrl ? (
|
||||
<img
|
||||
src={photoUrl}
|
||||
alt={g.name || ''}
|
||||
className="pedigree-card__avatar"
|
||||
onError={() => setFailedUrl(rawUrl)}
|
||||
/>
|
||||
) : (
|
||||
<GerbilIcon size="1.6rem" aria-hidden="true" />
|
||||
)}
|
||||
</div>
|
||||
<div className="pedigree-card__body">
|
||||
<div className="pedigree-card__name">
|
||||
@@ -389,11 +422,12 @@ function PedigreeCard({
|
||||
<span
|
||||
className="pedigree-chip"
|
||||
style={chip ? { background: chip.bg, color: chip.fg } : undefined}
|
||||
title={farbschlag}
|
||||
>
|
||||
{farbschlag}
|
||||
{g.genotype ? displayGenotypeSafe(g.genotype) : farbschlag}
|
||||
</span>
|
||||
)}
|
||||
{year && <span className="pedigree-card__year">* {year}</span>}
|
||||
{dob && <span className="pedigree-card__year">* {dob}</span>}
|
||||
</div>
|
||||
{node.expandable && (
|
||||
<button
|
||||
@@ -413,6 +447,36 @@ function PedigreeCard({
|
||||
)
|
||||
}
|
||||
|
||||
/* ── Würfe-Panel (STAMMBAUM-LITTERS) ─────────────────────────────── */
|
||||
|
||||
function LittersPanel({
|
||||
litters,
|
||||
t,
|
||||
}: {
|
||||
litters: Litter[]
|
||||
t: { littersTitle: string; littersJunge: string }
|
||||
}) {
|
||||
return (
|
||||
<aside className="stammbaum-litters-panel" aria-label={t.littersTitle}>
|
||||
<div className="stammbaum-litters-panel__title">{t.littersTitle}</div>
|
||||
<ul className="stammbaum-litters-panel__list">
|
||||
{litters.map((l) => (
|
||||
<li key={l.id}>
|
||||
<Link to={`/wuerfe/${l.id}`} className="stammbaum-litters-panel__link">
|
||||
<span className="stammbaum-litters-panel__name">{l.name}</span>
|
||||
{l.totalBorn != null && (
|
||||
<span className="stammbaum-litters-panel__born">
|
||||
{l.totalBorn} {t.littersJunge}
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
|
||||
function SexIcon({ gender }: { gender: Gender }) {
|
||||
const symbol = gender === 'male' ? '♂' : gender === 'female' ? '♀' : '?'
|
||||
return (
|
||||
@@ -508,7 +572,17 @@ function PrintCell({
|
||||
</div>
|
||||
)}
|
||||
{farbschlag && <div className="stammbaum-print__sub">{farbschlag}</div>}
|
||||
{g.genotype && gen <= 2 && <div className="stammbaum-print__geno">{g.genotype}</div>}
|
||||
{g.genotype && gen <= 2 && (
|
||||
<div className="stammbaum-print__geno">
|
||||
{(() => {
|
||||
try {
|
||||
return displayGenotypeSafe(g.genotype)
|
||||
} catch {
|
||||
return g.genotype.replace(/\?/g, '-')
|
||||
}
|
||||
})()}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,14 +1,62 @@
|
||||
import { useMemo } from 'react'
|
||||
import { useCallback, useMemo, useState } from 'react'
|
||||
import { Link, useParams } from 'react-router-dom'
|
||||
import { de } from '../strings/de'
|
||||
import { getLitter } from '../api/litters'
|
||||
import { getGerbil, listGerbils } from '../api/gerbils'
|
||||
import { listColorVarieties, listContacts } from '../api/lookups'
|
||||
import { API_BASE_URL } from '../api/client'
|
||||
import { condition } from '../api/gridify'
|
||||
import { type Gerbil } from '../api/types'
|
||||
import { useApi } from '../hooks/useApi'
|
||||
import { formatDate } from '../format/labels'
|
||||
import { formatDate, genderLabel } from '../format/labels'
|
||||
import { isValidGenotype } from '../format/genotypeText'
|
||||
import { breed, fromDisplayString, type BreedingResult } from '../genetics'
|
||||
import { breed, fromDisplayString, genotypeToFarbschlag, UNKNOWN_FARBSCHLAG, type BreedingResult } from '../genetics'
|
||||
import BreedingResultView from '../components/BreedingResultView'
|
||||
import GerbilIcon from '../components/GerbilIcon'
|
||||
import './wuerfe.css'
|
||||
|
||||
type JuvenileFields = (typeof de.pages.litters.detail.juvenileFields)
|
||||
|
||||
function JuvenileCard({ g, farbe, receiver, tJf }: {
|
||||
g: Gerbil
|
||||
farbe: string | null
|
||||
receiver: string | null
|
||||
tJf: JuvenileFields
|
||||
}) {
|
||||
const [failedUrl, setFailedUrl] = useState<string | null>(null)
|
||||
const rawUrl = g.profilePhotoUrl
|
||||
? /^(https?:|data:|\/\/)/.test(g.profilePhotoUrl)
|
||||
? g.profilePhotoUrl
|
||||
: `${API_BASE_URL}${g.profilePhotoUrl}`
|
||||
: null
|
||||
const photoUrl = rawUrl !== failedUrl ? rawUrl : null
|
||||
|
||||
return (
|
||||
<Link to={`/rennmaeuse/${g.id}`} className="gerbil-card gerbil-card--with-photo">
|
||||
<div className="juvenile-photo">
|
||||
{photoUrl ? (
|
||||
<img
|
||||
src={photoUrl}
|
||||
alt={g.name || ''}
|
||||
className="juvenile-photo__avatar"
|
||||
onError={() => setFailedUrl(rawUrl)}
|
||||
/>
|
||||
) : (
|
||||
<GerbilIcon size="1.4rem" aria-hidden="true" />
|
||||
)}
|
||||
</div>
|
||||
<div className="juvenile-body">
|
||||
<span className="gerbil-card__name">{g.name}</span>
|
||||
<span className="gerbil-card__meta">{genderLabel(g.gender)}</span>
|
||||
{farbe && <span className="gerbil-card__meta">{tJf.colorVariety}: {farbe}</span>}
|
||||
{g.goHomeDate && <span className="gerbil-card__meta">{tJf.goHomeDate}: {formatDate(g.goHomeDate)}</span>}
|
||||
{receiver && <span className="gerbil-card__meta">{tJf.receiver}: {receiver}</span>}
|
||||
{g.dateOfDeath && <span className="gerbil-card__meta">{tJf.dateOfDeath}: {formatDate(g.dateOfDeath)}</span>}
|
||||
{g.causeOfDeath && <span className="gerbil-card__meta">{tJf.causeOfDeath}: {g.causeOfDeath}</span>}
|
||||
</div>
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
|
||||
export default function WurfDetailPage() {
|
||||
const t = de.pages.litters
|
||||
@@ -43,6 +91,38 @@ export default function WurfDetailPage() {
|
||||
return breed(fromDisplayString(fg), fromDisplayString(mg))
|
||||
}, [father.data, mother.data])
|
||||
|
||||
// Farbschlag + Abnehmer lookups for the juvenile list.
|
||||
const colorVarieties = useApi(() => listColorVarieties(), [])
|
||||
const contacts = useApi(() => listContacts(), [])
|
||||
|
||||
const colorNameById = useMemo(
|
||||
() => new Map((colorVarieties.data ?? []).map((c) => [c.id, c.name])),
|
||||
[colorVarieties.data],
|
||||
)
|
||||
const contactNameById = useMemo(
|
||||
() => new Map((contacts.data ?? []).map((c) => [c.id, c.name])),
|
||||
[contacts.data],
|
||||
)
|
||||
|
||||
const farbschlagOf = useCallback(
|
||||
(g: { colorVarietyId: string | null; genotype: string | null }): string | null => {
|
||||
if (g.colorVarietyId) {
|
||||
const name = colorNameById.get(g.colorVarietyId)
|
||||
if (name) return name
|
||||
}
|
||||
if (g.genotype?.trim()) {
|
||||
try {
|
||||
const name = genotypeToFarbschlag(fromDisplayString(g.genotype))
|
||||
return name === UNKNOWN_FARBSCHLAG ? null : name
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
return null
|
||||
},
|
||||
[colorNameById],
|
||||
)
|
||||
|
||||
if (litter.loading) return <p className="muted">{de.common.loading}</p>
|
||||
if (litter.error || !litter.data) {
|
||||
return (
|
||||
@@ -92,6 +172,12 @@ export default function WurfDetailPage() {
|
||||
{l.totalBorn != null ? ` / ${l.totalBorn}` : ''}
|
||||
</dd>
|
||||
</div>
|
||||
{l.deathsWithin8Weeks != null && (
|
||||
<div className="def-row">
|
||||
<dt>{t.fields.deathsWithin8Weeks}</dt>
|
||||
<dd>{l.deathsWithin8Weeks}</dd>
|
||||
</div>
|
||||
)}
|
||||
<div className="def-row">
|
||||
<dt>{t.fields.expectedGoHomeDate}</dt>
|
||||
<dd>{formatDate(l.expectedGoHomeDate)}</dd>
|
||||
@@ -117,18 +203,19 @@ export default function WurfDetailPage() {
|
||||
{!juveniles.loading && registered === 0 && <p className="muted">{t.detail.noJuveniles}</p>}
|
||||
{registered > 0 && (
|
||||
<ul className="card-list">
|
||||
{(juveniles.data?.items ?? []).map((g) => (
|
||||
<li key={g.id}>
|
||||
<Link to={`/rennmaeuse/${g.id}`} className="gerbil-card">
|
||||
<span className="gerbil-card__name">{g.name}</span>
|
||||
<span className="gerbil-card__meta">{de.pages.gerbils.genderLabels[g.gender]}</span>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
{(juveniles.data?.items ?? []).map((g) => {
|
||||
const farbe = farbschlagOf(g)
|
||||
const receiver = g.receiverContactId ? contactNameById.get(g.receiverContactId) ?? null : null
|
||||
const tJf = t.detail.juvenileFields
|
||||
return (
|
||||
<li key={g.id}>
|
||||
<JuvenileCard g={g} farbe={farbe} receiver={receiver} tJf={tJf} />
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
<h3>{t.detail.expectedColors}</h3>
|
||||
{expected ? (
|
||||
<BreedingResultView result={expected} title={t.detail.expectedColors} />
|
||||
) : (
|
||||
|
||||
@@ -16,6 +16,7 @@ interface FormState {
|
||||
motherId: string
|
||||
motherName: string
|
||||
totalBorn: string
|
||||
deathsWithin8Weeks: string
|
||||
expectedGoHomeDate: string
|
||||
notes: string
|
||||
}
|
||||
@@ -28,6 +29,7 @@ const EMPTY: FormState = {
|
||||
motherId: '',
|
||||
motherName: '',
|
||||
totalBorn: '',
|
||||
deathsWithin8Weeks: '',
|
||||
expectedGoHomeDate: '',
|
||||
notes: '',
|
||||
}
|
||||
@@ -75,6 +77,7 @@ export default function WurfFormPage() {
|
||||
motherId: l.motherId ?? '',
|
||||
motherName: l.motherId ? (nameById.get(l.motherId) || de.pages.gerbils.nameless) : '',
|
||||
totalBorn: l.totalBorn != null ? String(l.totalBorn) : '',
|
||||
deathsWithin8Weeks: l.deathsWithin8Weeks != null ? String(l.deathsWithin8Weeks) : '',
|
||||
expectedGoHomeDate: l.expectedGoHomeDate ?? '',
|
||||
notes: l.notes ?? '',
|
||||
})
|
||||
@@ -109,12 +112,14 @@ export default function WurfFormPage() {
|
||||
e.preventDefault()
|
||||
if (!validate()) return
|
||||
const totalBornNum = form.totalBorn.trim() === '' ? null : Number(form.totalBorn)
|
||||
const deathsNum = form.deathsWithin8Weeks.trim() === '' ? null : Number(form.deathsWithin8Weeks)
|
||||
const body: CreateLitter = {
|
||||
name: form.name.trim(),
|
||||
date: form.date,
|
||||
fatherId: nn(form.fatherId),
|
||||
motherId: nn(form.motherId),
|
||||
totalBorn: totalBornNum != null && Number.isFinite(totalBornNum) ? totalBornNum : null,
|
||||
deathsWithin8Weeks: deathsNum != null && Number.isFinite(deathsNum) ? deathsNum : null,
|
||||
expectedGoHomeDate: nn(form.expectedGoHomeDate),
|
||||
notes: nn(form.notes),
|
||||
}
|
||||
@@ -215,6 +220,26 @@ export default function WurfFormPage() {
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span>{t.fields.deathsWithin8Weeks}</span>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
className="input"
|
||||
value={form.deathsWithin8Weeks}
|
||||
onChange={(e) => set('deathsWithin8Weeks', e.target.value)}
|
||||
/>
|
||||
{(() => {
|
||||
const d = Number(form.deathsWithin8Weeks)
|
||||
const tb = Number(form.totalBorn)
|
||||
return form.deathsWithin8Weeks.trim() !== '' &&
|
||||
form.totalBorn.trim() !== '' &&
|
||||
d > tb ? (
|
||||
<small className="error-text">{t.validation.deathsExceedTotalBorn}</small>
|
||||
) : null
|
||||
})()}
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span>{t.fields.expectedGoHomeDate}</span>
|
||||
<input
|
||||
|
||||
@@ -1,33 +1,247 @@
|
||||
/* FEAT-12a multi-select on the Tiere list — page-scoped. */
|
||||
|
||||
/* The sticky header supplies the top spacing, so opt out of the global .page top
|
||||
padding (otherwise the bar wouldn't pin flush to the top). */
|
||||
.gerbils-page {
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
.gerbil-row {
|
||||
/* DESIGN (Rennmaus Filter): cards ease in (fade + slight rise) instead of popping
|
||||
when the result set changes. React keys by id, so only newly-appearing rows
|
||||
replay this; rows that persist across a filter change are reused and stay put. */
|
||||
animation: gerbilRowIn 0.28s cubic-bezier(0.22, 1, 0.36, 1) both;
|
||||
}
|
||||
|
||||
/* Light cascade so a fresh result set sweeps in rather than landing all at once.
|
||||
Capped at the first handful of rows; the rest share the last delay. */
|
||||
.gerbil-row:nth-child(1) { animation-delay: 0s; }
|
||||
.gerbil-row:nth-child(2) { animation-delay: 0.03s; }
|
||||
.gerbil-row:nth-child(3) { animation-delay: 0.06s; }
|
||||
.gerbil-row:nth-child(4) { animation-delay: 0.09s; }
|
||||
.gerbil-row:nth-child(5) { animation-delay: 0.12s; }
|
||||
.gerbil-row:nth-child(6) { animation-delay: 0.15s; }
|
||||
.gerbil-row:nth-child(n + 7) { animation-delay: 0.18s; }
|
||||
|
||||
@keyframes gerbilRowIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(6px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.gerbil-row {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
.rm-noresults {
|
||||
text-align: center;
|
||||
padding: 2.5rem 1rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
.gerbil-row__check {
|
||||
width: 1.25rem;
|
||||
height: 1.25rem;
|
||||
min-height: 0;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.gerbil-row > .gerbil-card {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.bulk-bar {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
padding: 0.6rem 0.9rem;
|
||||
margin: 0.5rem 0;
|
||||
border: 1px solid var(--color-accent);
|
||||
border-radius: 0.5rem;
|
||||
background: var(--color-accent-soft);
|
||||
}
|
||||
|
||||
/* Consistent breathing room below the sticky header: between the header and the
|
||||
list (no active filters) and between the active chips and the first card. */
|
||||
.gerbils-page .card-list {
|
||||
margin-top: 0.625rem;
|
||||
}
|
||||
|
||||
/* Infinite scroll: invisible sentinel observed to trigger the next page,
|
||||
plus a centered "loading more" line while a page is being appended. */
|
||||
.rmf-sentinel {
|
||||
height: 1px;
|
||||
width: 100%;
|
||||
}
|
||||
.rmf-loadmore {
|
||||
text-align: center;
|
||||
padding: 0.75rem 0;
|
||||
}
|
||||
|
||||
/* ---------- DESIGN (Rennmaus Filter): sticky header that blends out on scroll ----------
|
||||
The whole header (title + search + filter pills + bar) sticks to the top; the list
|
||||
scrolls underneath. The title row collapses once a 1px sentinel above the header
|
||||
leaves the viewport. Negative margins let the bar span the app-main padding so its
|
||||
background/border reach edge-to-edge while pinned. */
|
||||
.gerbils-scrolltop {
|
||||
height: 1px;
|
||||
}
|
||||
.gerbils-topbar {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
z-index: 10;
|
||||
background: var(--color-bg);
|
||||
/* Horizontal negative margins let the bar's background + border-bottom span the
|
||||
app-main padding edge-to-edge while pinned. The body scrolls, so the app-main
|
||||
top padding scrolls away and the bar pins flush to the viewport top (no gap). */
|
||||
margin: 0 -1rem;
|
||||
padding: 0.5rem 1rem 0.625rem;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
}
|
||||
@media (min-width: 768px) {
|
||||
.gerbils-topbar {
|
||||
margin: 0 -2rem;
|
||||
padding: 0.75rem 2rem 0.625rem;
|
||||
}
|
||||
}
|
||||
|
||||
.gerbils-head h2 {
|
||||
font-size: 26px;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.02em;
|
||||
color: var(--color-text);
|
||||
}
|
||||
.gerbils-head .muted {
|
||||
font-size: 14px;
|
||||
margin: 2px 0 0;
|
||||
}
|
||||
.gerbils-head {
|
||||
overflow: hidden;
|
||||
/* Generous cap so the expanded state never clips when the "Neu" button wraps on
|
||||
narrow phones; the collapse still animates cleanly from this height to 0. */
|
||||
max-height: 200px;
|
||||
transition: max-height 0.28s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.2s ease,
|
||||
margin 0.28s cubic-bezier(0.22, 1, 0.36, 1);
|
||||
}
|
||||
.gerbils-head--condensed {
|
||||
max-height: 0;
|
||||
opacity: 0;
|
||||
margin: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.gerbils-head {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- DESIGN (Rennmaus Filter): new two-row list card ----------
|
||||
Name + gender circle + status badge on top, "Farbschlag · Herkunft · geb. Datum"
|
||||
below. Overrides the former single-row grid card from index.css. */
|
||||
.gerbil-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
/* Override the old single-row card's `align-items: center` (index.css) — in a
|
||||
column flex that centers children horizontally and shoved the name off the left. */
|
||||
align-items: stretch;
|
||||
gap: 0.5rem;
|
||||
padding: 0.875rem 1rem;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 18px;
|
||||
background: var(--color-surface);
|
||||
box-shadow: var(--shadow);
|
||||
text-decoration: none;
|
||||
color: var(--color-text);
|
||||
transition: border-color 0.15s, box-shadow 0.15s,
|
||||
transform 0.12s cubic-bezier(0.22, 1, 0.36, 1);
|
||||
}
|
||||
.gerbil-card:hover {
|
||||
background: var(--color-surface);
|
||||
border-color: color-mix(in srgb, var(--color-accent) 35%, var(--color-border));
|
||||
box-shadow: 0 2px 6px rgba(61, 46, 35, 0.1), 0 8px 22px rgba(61, 46, 35, 0.08);
|
||||
}
|
||||
.gerbil-card:active {
|
||||
transform: scale(0.992);
|
||||
}
|
||||
|
||||
.gerbil-card__top {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.625rem;
|
||||
}
|
||||
.gerbil-card__name {
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
color: var(--color-text);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
.gerbil-card__right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.gerbil-card__meta {
|
||||
font-size: 14px;
|
||||
color: var(--color-text-muted);
|
||||
font-weight: 500;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
}
|
||||
.gerbil-card__meta-strong {
|
||||
color: var(--color-text);
|
||||
font-weight: 600;
|
||||
}
|
||||
.gerbil-card__dot {
|
||||
color: var(--color-text-faint);
|
||||
}
|
||||
|
||||
/* Status badge: design size (12px/700), coloured per status below. */
|
||||
.gerbil-card .badge {
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
/* Gender circle (♂/♀/?) — colored disc, from the design's GeschlechtIcon. */
|
||||
.gerbil-sex {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 50%;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.gerbil-sex--male {
|
||||
color: #5a7da8;
|
||||
background: color-mix(in srgb, #5a7da8 12%, #fff);
|
||||
}
|
||||
.gerbil-sex--female {
|
||||
color: #c2703d;
|
||||
background: color-mix(in srgb, #c2703d 12%, #fff);
|
||||
}
|
||||
.gerbil-sex--unknown {
|
||||
color: #9a938a;
|
||||
background: color-mix(in srgb, #9a938a 14%, #fff);
|
||||
}
|
||||
|
||||
/* Status badge coloured per status — scoped to cards so other pages stay as-is. */
|
||||
.gerbil-card .badge--breeding {
|
||||
color: #5e8c5a;
|
||||
background: color-mix(in srgb, #5e8c5a 12%, #fff);
|
||||
border: 1px solid color-mix(in srgb, #5e8c5a 30%, transparent);
|
||||
}
|
||||
.gerbil-card .badge--pet {
|
||||
color: #5a7da8;
|
||||
background: color-mix(in srgb, #5a7da8 12%, #fff);
|
||||
border: 1px solid color-mix(in srgb, #5a7da8 30%, transparent);
|
||||
}
|
||||
.gerbil-card .badge--forsale {
|
||||
color: #c2703d;
|
||||
background: color-mix(in srgb, #c2703d 12%, #fff);
|
||||
border: 1px solid color-mix(in srgb, #c2703d 30%, transparent);
|
||||
}
|
||||
.gerbil-card .badge--deceased {
|
||||
color: #8a847b;
|
||||
background: color-mix(in srgb, #8a847b 14%, #fff);
|
||||
border: 1px solid color-mix(in srgb, #8a847b 30%, transparent);
|
||||
}
|
||||
.gerbil-card .badge--givenaway {
|
||||
color: #b08e5c;
|
||||
background: color-mix(in srgb, #b08e5c 14%, #fff);
|
||||
border: 1px solid color-mix(in srgb, #b08e5c 32%, transparent);
|
||||
}
|
||||
|
||||
@@ -34,15 +34,143 @@
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.stammbaum-hint {
|
||||
font-size: 0.8rem;
|
||||
color: var(--color-text-muted);
|
||||
.stammbaum-hints {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0.4rem 0 0;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.1rem 1rem;
|
||||
font-size: 0.78rem;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
/* ── Würfe-Panel + Layout (STAMMBAUM-LITTERS) ────────────────── */
|
||||
|
||||
.stammbaum-layout {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
/* Desktop: Würfe-Panel links vom Baum. */
|
||||
.stammbaum-litters-panel {
|
||||
flex: none;
|
||||
width: 148px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
gap: 0.35rem;
|
||||
padding: 0.5rem 0.75rem 0.5rem 0;
|
||||
border-right: 1px solid var(--color-border);
|
||||
margin-right: 0;
|
||||
}
|
||||
|
||||
.stammbaum-litters-panel__title {
|
||||
font-size: 0.7rem;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.stammbaum-litters-panel__list {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.3rem;
|
||||
overflow-y: auto;
|
||||
max-height: calc(clamp(18rem, 62dvh, 46rem) - 3rem);
|
||||
}
|
||||
|
||||
.stammbaum-litters-panel__link {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.1rem;
|
||||
padding: 0.3rem 0.45rem;
|
||||
border-radius: 0.4rem;
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
font-size: 0.8rem;
|
||||
font-family: system-ui, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
|
||||
}
|
||||
|
||||
.stammbaum-litters-panel__link:hover {
|
||||
background: var(--color-accent-soft);
|
||||
border-color: var(--color-accent);
|
||||
color: var(--color-accent);
|
||||
}
|
||||
|
||||
.stammbaum-litters-panel__name {
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.stammbaum-litters-panel__born {
|
||||
color: var(--color-text-muted);
|
||||
font-size: 0.72rem;
|
||||
}
|
||||
|
||||
/* Mobil (≤520px): Panel als kompakter horizontaler Streifen ÜBER dem Baum. */
|
||||
@media (max-width: 520px) {
|
||||
.stammbaum-layout {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.stammbaum-litters-panel {
|
||||
width: auto;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
gap: 0.5rem;
|
||||
padding: 0.4rem 0.5rem;
|
||||
border-right: none;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.stammbaum-litters-panel__title {
|
||||
flex: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.stammbaum-litters-panel__list {
|
||||
flex-direction: row;
|
||||
flex-wrap: nowrap;
|
||||
max-height: none;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.stammbaum-litters-panel__link {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.stammbaum-litters-panel__born {
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
/* Canvas behält explizite Höhe in column-Richtung. */
|
||||
.stammbaum-canvas {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Zeichenfläche ────────────────────────────────────────────── */
|
||||
|
||||
.stammbaum-canvas {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
height: clamp(18rem, 62dvh, 46rem);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 0.6rem;
|
||||
@@ -108,6 +236,7 @@
|
||||
width: 42px;
|
||||
height: 42px;
|
||||
border-radius: 50%;
|
||||
overflow: hidden;
|
||||
background: var(--color-accent-soft);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -115,6 +244,13 @@
|
||||
font-size: 1.4rem;
|
||||
}
|
||||
|
||||
.pedigree-card__avatar {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.pedigree-card__body {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
@@ -157,14 +293,15 @@
|
||||
.pedigree-chip {
|
||||
align-self: flex-start;
|
||||
max-width: 100%;
|
||||
font-size: 0.68rem;
|
||||
font-size: 0.62rem;
|
||||
padding: 0.1rem 0.45rem;
|
||||
border-radius: 1rem;
|
||||
background: var(--color-accent-soft);
|
||||
color: var(--color-accent);
|
||||
white-space: nowrap;
|
||||
white-space: normal;
|
||||
word-break: break-word;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.pedigree-card__year {
|
||||
@@ -175,20 +312,27 @@
|
||||
.pedigree-card__expand {
|
||||
flex: none;
|
||||
margin-left: auto;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
padding: 0;
|
||||
border-radius: 50%;
|
||||
border: 1px solid var(--color-accent);
|
||||
background: var(--color-accent-soft);
|
||||
color: var(--color-accent);
|
||||
font-size: 1.05rem;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.pedigree-card__expand:hover {
|
||||
border: none;
|
||||
background: var(--color-accent);
|
||||
color: #fff;
|
||||
font-size: 1.3rem;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-shadow: 0 1px 5px rgb(0 0 0 / 28%);
|
||||
}
|
||||
|
||||
.pedigree-card__expand:hover,
|
||||
.pedigree-card__expand:focus-visible {
|
||||
opacity: 0.82;
|
||||
outline: 2px solid var(--color-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* ── Druckansicht (Ahnentafel als CSS-Grid, Hunde-Zertifikat-Optik) ──
|
||||
|
||||
34
gerbil-manager-web/src/pages/wuerfe.css
Normal file
34
gerbil-manager-web/src/pages/wuerfe.css
Normal file
@@ -0,0 +1,34 @@
|
||||
/* JUVENILE-AVATARS: photo avatar to the left of each juvenile card. */
|
||||
.gerbil-card--with-photo {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.juvenile-body {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.2rem;
|
||||
}
|
||||
|
||||
.juvenile-photo {
|
||||
flex: none;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 50%;
|
||||
overflow: hidden;
|
||||
background: var(--color-accent-soft);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
align-self: center;
|
||||
}
|
||||
|
||||
.juvenile-photo__avatar {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
}
|
||||
@@ -22,7 +22,7 @@ function makeGerbil(id: string, name: string, litterId: string | null = null): G
|
||||
id,
|
||||
name,
|
||||
gender: 'unknown',
|
||||
status: 'Active',
|
||||
status: 'Breeding',
|
||||
dateOfBirth: null,
|
||||
dateOfDeath: null,
|
||||
causeOfDeath: null,
|
||||
|
||||
@@ -13,6 +13,9 @@ export interface ChipColor {
|
||||
|
||||
const CHIP_COLORS: Record<string, ChipColor> = {
|
||||
// Colourpoint / C-Serie
|
||||
// GEN-4c: PEW renamed to REW in catalog (Julian: PEW=REW). Both kept here for
|
||||
// backward-compat during DB migration (old animals may still carry the old name).
|
||||
'REW': { bg: '#f7f3ec', fg: '#8a7d6b' },
|
||||
'Pink Eyed White (PEW)': { bg: '#f7f3ec', fg: '#8a7d6b' },
|
||||
Hermelin: { bg: '#f3ede2', fg: '#8a7d6b' },
|
||||
Himalaya: { bg: '#efe6d8', fg: '#8a7d6b' },
|
||||
|
||||
@@ -27,7 +27,7 @@ function makeGerbil(over: Partial<Gerbil> & { id: string }): Gerbil {
|
||||
return {
|
||||
name: over.id,
|
||||
gender: 'unknown',
|
||||
status: 'Active' as GerbilStatus,
|
||||
status: 'Breeding' as GerbilStatus,
|
||||
dateOfBirth: null,
|
||||
dateOfDeath: null,
|
||||
causeOfDeath: null,
|
||||
|
||||
@@ -83,7 +83,7 @@ export function farbschlagDistribution(
|
||||
): NameCount[] {
|
||||
const byName = new Map<string | null, number>()
|
||||
for (const g of gerbils) {
|
||||
if (g.status !== 'Active') continue
|
||||
if (g.status !== 'Breeding' && g.status !== 'Pet') continue
|
||||
const name = resolveName(g)
|
||||
byName.set(name, (byName.get(name) ?? 0) + 1)
|
||||
}
|
||||
|
||||
@@ -44,6 +44,8 @@ export const de = {
|
||||
empty: 'Keine Rennmäuse gefunden.',
|
||||
countLabel: 'Tiere',
|
||||
searchPlaceholder: 'Name suchen …',
|
||||
// DESIGN (Rennmaus Filter): „geb." Präfix vor dem Geburtsdatum auf der Karte.
|
||||
born: 'geb.',
|
||||
// BESTAND-FILTER: Kennzeichnung externer (nicht zum eigenen Bestand gehörender) Tiere
|
||||
externalBadge: 'Extern',
|
||||
externalTitle: 'Externes Tier — gehört nicht zum eigenen Bestand, nur für den Stammbaum erfasst.',
|
||||
@@ -58,6 +60,8 @@ export const de = {
|
||||
sortBy: 'Sortieren nach',
|
||||
// BESTAND-FILTER: eigener Bestand (Clan) vs. externe Ahnen (nur Stammbaum)
|
||||
showExternal: 'Externe Ahnen einblenden',
|
||||
// DESIGN (Rennmaus Filter): kurze Variante für den Toggle-Chip.
|
||||
showExternalShort: 'Externe Ahnen',
|
||||
showExternalHint: 'Tiere aus fremden Zuchten, die nur für den Stammbaum erfasst sind.',
|
||||
},
|
||||
// Sortier-Optionen
|
||||
@@ -124,6 +128,11 @@ export const de = {
|
||||
isDeafUnknown: 'Unbekannt',
|
||||
isDeafYes: 'Ja',
|
||||
isDeafNo: 'Nein',
|
||||
// STATUS-MODEL: Hinweis für abgeleitete Statuswerte
|
||||
statusDerivedHint: {
|
||||
Deceased: 'Wird automatisch gesetzt wenn Todesdatum erfasst.',
|
||||
GivenAway: 'Wird automatisch gesetzt nach Abgabe.',
|
||||
},
|
||||
save: 'Speichern',
|
||||
cancel: 'Abbrechen',
|
||||
saving: 'Speichern …',
|
||||
@@ -141,8 +150,10 @@ export const de = {
|
||||
male: 'Männlich',
|
||||
female: 'Weiblich',
|
||||
},
|
||||
// STATUS-MODEL: Breeding/Pet ersetzen Active; Deceased+GivenAway = abgeleitet (Backend)
|
||||
statusLabels: {
|
||||
Active: 'Aktiv',
|
||||
Breeding: 'Zucht',
|
||||
Pet: 'Liebhaber',
|
||||
Deceased: 'Verstorben',
|
||||
GivenAway: 'Abgegeben',
|
||||
ForSale: 'Zur Abgabe',
|
||||
@@ -172,6 +183,7 @@ export const de = {
|
||||
father: 'Vater',
|
||||
mother: 'Mutter',
|
||||
totalBorn: 'Wurfstärke',
|
||||
deathsWithin8Weeks: 'In den ersten 8 Wochen verstorben',
|
||||
expectedGoHomeDate: 'Voraussichtliches Abgabedatum',
|
||||
notes: 'Notizen',
|
||||
},
|
||||
@@ -189,6 +201,14 @@ export const de = {
|
||||
edit: 'Bearbeiten',
|
||||
back: 'Zurück zur Liste',
|
||||
notFound: 'Dieser Wurf wurde nicht gefunden.',
|
||||
// LITTER-JUVENILE-DETAILS: pro-Jungtier-Felder
|
||||
juvenileFields: {
|
||||
colorVariety: 'Farbschlag',
|
||||
goHomeDate: 'Abgegeben',
|
||||
receiver: 'Abnehmer',
|
||||
dateOfDeath: 'Verstorben',
|
||||
causeOfDeath: 'Todesursache',
|
||||
},
|
||||
},
|
||||
// Formular
|
||||
form: {
|
||||
@@ -204,6 +224,7 @@ export const de = {
|
||||
nameRequired: 'Bitte eine Bezeichnung eingeben.',
|
||||
dateRequired: 'Bitte ein Wurfdatum angeben.',
|
||||
invalidParentGender: 'Der Vater muss männlich und die Mutter weiblich sein.',
|
||||
deathsExceedTotalBorn: 'Die Anzahl der Frühverluste darf die Wurfstärke nicht überschreiten.',
|
||||
},
|
||||
// Zuchtpaar-Übersicht
|
||||
pairs: {
|
||||
@@ -355,6 +376,12 @@ export const de = {
|
||||
/** Auf Karten am Rand: weitere Vorfahren nachladen. */
|
||||
expand: 'Vorfahren laden',
|
||||
tapHint: 'Tippe auf ein Tier, um dessen Stammbaum anzuzeigen.',
|
||||
/** Mini-Legende unter dem Baum (STAMMBAUM-EXPAND). */
|
||||
hintName: 'Namenslink: Tierakte öffnen',
|
||||
hintExpand: '+: weitere Vorfahren nachladen',
|
||||
/** Würfe-Panel links (STAMMBAUM-LITTERS). */
|
||||
littersTitle: 'Würfe',
|
||||
littersJunge: 'Junge',
|
||||
zoomIn: 'Vergrößern',
|
||||
zoomOut: 'Verkleinern',
|
||||
zoomFit: 'Ansicht einpassen',
|
||||
@@ -849,12 +876,26 @@ export const de = {
|
||||
resetButton: 'Filter zurücksetzen',
|
||||
closeButton: 'Schließen',
|
||||
},
|
||||
// ── DESIGN (Rennmaus Filter): Quick-Chips-Filter mit Bottom-Sheet ──
|
||||
filterBar: {
|
||||
title: 'Filter',
|
||||
done: 'Fertig',
|
||||
clearAll: 'Alle löschen',
|
||||
remove: 'entfernen',
|
||||
searchPlaceholder: 'Suchen …',
|
||||
noMatch: 'Kein Treffer',
|
||||
searchClear: 'Suche leeren',
|
||||
},
|
||||
// ── FEAT-NAMEGEN: Namensvorschläge (KI-gestützt, UC-1 Einzeltier) ──
|
||||
namegen: {
|
||||
button: 'Name vorschlagen',
|
||||
panelTitle: 'Namensvorschläge',
|
||||
letterLabel: 'Anfangsbuchstabe',
|
||||
letterPlaceholder: 'z. B. A',
|
||||
genderLabel: 'Geschlecht',
|
||||
genderAny: 'Egal',
|
||||
genderFemale: 'Weiblich',
|
||||
genderMale: 'Männlich',
|
||||
usagesLabel: 'Herkunftskultur',
|
||||
loadButton: 'Vorschläge laden',
|
||||
loading: 'Lade Vorschläge …',
|
||||
|
||||
88
import_todo.md
Normal file
88
import_todo.md
Normal file
@@ -0,0 +1,88 @@
|
||||
# TODO: Migration to Unified Database-Ready Format
|
||||
|
||||
This is the checklist for migrating the GerbilManager Excel datasets (41 Stammbaum pedigree charts + 1 Wurfchronik litter chronicle) one-by-one into a clean, resolved, relational JSON format (`gerbilmanager_resolved.json`) that can be loaded directly into the database without on-the-fly reconciliation.
|
||||
|
||||
---
|
||||
|
||||
## 🟩 Phase 1: Preparation & Schema Definition
|
||||
- [x] Define the target unified JSON schema that maps 1-to-1 with the Entity Framework database entities:
|
||||
- `Contacts` (breeders/buyers)
|
||||
- `ColorVarieties` (genetics catalog)
|
||||
- `Litters` (with resolved `MotherId` and `FatherId` Guid relations)
|
||||
- `Gerbils` (with resolved `LitterId`, `ColorVarietyId`, `OriginContactId`, `ReceiverContactId` Guid relations)
|
||||
- `GerbilPhotos` (mapped by Guid relation)
|
||||
- [x] Extract and verify existing `ColorVarieties` and `Contacts` to establish basic lookup dictionaries.
|
||||
|
||||
---
|
||||
|
||||
## 🟦 Phase 2: Spreadsheet Extraction & Conversion (One-by-One)
|
||||
Convert and extract each spreadsheet's records. For each chart, extract the animals, birth dates, death dates, genders (from cell background color), and genotypes.
|
||||
|
||||
### Litter Chronicle
|
||||
- [x] `Wurfchronik der Kleine Chaoten Teil1.xlsx` (Litters data base)
|
||||
|
||||
### Pedigree Charts (Stammbäume)
|
||||
- [x] `Stammbaum von Akio Kids.xlsx`
|
||||
- [x] `Stammbaum von Alberto Kids.xlsx`
|
||||
- [x] `Stammbaum von CP-Fuchs, CP-Sa Sp von Unity.xlsx`
|
||||
- [x] `Stammbaum von Chesnut.xlsx`
|
||||
- [x] `Stammbaum von Danako.xlsx`
|
||||
- [x] `Stammbaum von Ella.xlsx`
|
||||
- [x] `Stammbaum von Emi.xlsx`
|
||||
- [x] `Stammbaum von Fire Kids.xlsx`
|
||||
- [x] `Stammbaum von Goldfuchs Sp (Pikachu) Kids.xlsx`
|
||||
- [x] `Stammbaum von Hana.xlsx`
|
||||
- [x] `Stammbaum von Jeremy.xlsx`
|
||||
- [x] `Stammbaum von Jiminy of Black Forest.xlsx`
|
||||
- [x] `Stammbaum von Jin.xlsx`
|
||||
- [x] `Stammbaum von Kalea.xlsx`
|
||||
- [x] `Stammbaum von Kazuya.xlsx`
|
||||
- [x] `Stammbaum von Kentucky.xlsx`
|
||||
- [x] `Stammbaum von Kohlief, Goldfuchsef Sp von Chrissi.xlsx`
|
||||
- [x] `Stammbaum von Marlin of Black Forest.xlsx`
|
||||
- [x] `Stammbaum von Martin.xlsx`
|
||||
- [x] `Stammbaum von Oscar of Black Forest.xlsx`
|
||||
- [x] `Stammbaum von Pinto of Fiomi.xlsx`
|
||||
- [x] `Stammbaum von Quied Soldier of Black Forest.xlsx`
|
||||
- [x] `Stammbaum von Rainny.xlsx`
|
||||
- [x] `Stammbaum von Ren.xlsx`
|
||||
- [x] `Stammbaum von South Dakota.xlsx`
|
||||
- [x] `Stammbaum von Stella Kids.xlsx`
|
||||
- [x] `Stammbaum von Tennessee.xlsx`
|
||||
- [x] `Stammbaum von Unique of Wild Dreams.xlsx`
|
||||
- [x] `Stammbaum von Unit.xlsx`
|
||||
- [x] `Stammbaum von Uriana.xlsx`
|
||||
- [x] `Stammbaum von Valentino Firehearts Kids.xlsx`
|
||||
- [x] `Stammbaum von Vance.xlsx`
|
||||
- [x] `Stammbaum von Vestra von den Schlossmäusen.xlsx`
|
||||
- [x] `Stammbaum von Watarus Kids.xlsx`
|
||||
- [x] `Stammbaum von Wildfire und Vestras Kids.xlsx`
|
||||
- [x] `Stammbaum von Xelina.xlsx`
|
||||
- [x] `Stammbaum von Yuki.xlsx`
|
||||
- [x] `Stammbaum von Yurikas und Pintos Sohn.xlsx`
|
||||
- [x] `Stammbaum von Zac (Vance.Dorie).xlsx`
|
||||
- [x] `Stammbaum von Zenon von Elea.xlsx`
|
||||
- [x] `Stammbaum von little Heros Sohn of little runners.xlsx`
|
||||
|
||||
---
|
||||
|
||||
## 🟨 Phase 3: Resolution & Relational Mapping
|
||||
- [x] Resolve duplicates using the canonical key: `normalize(name) + normalize(dob)` and `Zucht` (breeding line).
|
||||
- [x] Inject resolutions from `conflict-decisions.json` to automatically resolve the remaining conflict animals (un-quarantining them and applying correct genotypes/dates).
|
||||
- [x] Parse and map all parent-child relationships positionally from the pedigree charts.
|
||||
- [x] Map and link all animals to their respective Wurfchronik litters using parentage and DOB.
|
||||
- [x] Resolve photo attachments to actual extracted media file paths.
|
||||
- [x] Assign permanent UUIDs (Guids) to all records and replace string names in relationships with the actual UUID foreign keys.
|
||||
|
||||
---
|
||||
|
||||
## 🟧 Phase 4: Data Export & Validation
|
||||
- [x] Generate the final `resolved_import.json` containing the relational array collections.
|
||||
- [x] Run automated validation tests on the JSON file (check for circular dependencies, broken foreign keys, invalid genotypes, and null dates).
|
||||
|
||||
---
|
||||
|
||||
## 🟥 Phase 5: Loader Implementation & Database Ingestion
|
||||
- [x] Build a simplified loader utility (C# endpoint or local python script) that takes the resolved JSON and directly runs `INSERT`/`UPDATE` transactions.
|
||||
- [x] Execute the import onto the target PostgreSQL database.
|
||||
- [x] Run verification tests (verify total counts: ~956 animals, and sample check pedigree trees).
|
||||
@@ -102,9 +102,9 @@
|
||||
{
|
||||
"name": "Skarlett von den Kleinen Chaoten",
|
||||
"dob": "14.07.2013",
|
||||
"decision": "death date = 17.04.2016 (the '2018' variant was wrong — it had leaked as '/ +2018' into the genotype field; parse-leak already fixed in IMPORT-POLISH)",
|
||||
"dateOfDeath": "17.04.2016",
|
||||
"source": "Julian 2026-06-07 — HUMANQUESTION D6"
|
||||
"decision": "birth 2013 + 4 years = death year 2017, no exact date → year-only convention (01.01.2017). Previous entry (17.04.2016) was wrong.",
|
||||
"dateOfDeath": "01.01.2017",
|
||||
"source": "Julian 2026-06-07 — HUMANQUESTION D7 (final Skarlett resolution)"
|
||||
},
|
||||
{
|
||||
"name": "Kazu von den Kleinen Chaoten",
|
||||
@@ -119,6 +119,100 @@
|
||||
"decision": "death date = 12.12.2019 (confirmed; the 14.01.2020 variant was wrong)",
|
||||
"dateOfDeath": "12.12.2019",
|
||||
"source": "Julian 2026-06-07 — HUMANQUESTION D5/D6 (letzter D6-Konflikt)"
|
||||
},
|
||||
{
|
||||
"name": "Kazumi von den Kleinen Chaoten",
|
||||
"dob": "23.04.2013",
|
||||
"decision": "voller Genotyp von der Züchterin — löst die 4 strittigen Loci: A=Aa, G=GG, P=PP, Sp=Spsp",
|
||||
"genotype": "Aa Cc[chm] DD ee[f] GG PP Spsp",
|
||||
"source": "Julian/Züchterin 2026-06-07 — HUMANQUESTION D7"
|
||||
},
|
||||
{
|
||||
"name": "Filou von den Kleinen Chaoten",
|
||||
"dob": "24.11.2014",
|
||||
"decision": "Sterbedatum = 31.08.2019 (die 31.10.2019-Variante war falsch); Gencode war einig",
|
||||
"dateOfDeath": "31.08.2019",
|
||||
"source": "Julian/Züchterin 2026-06-07 — HUMANQUESTION D7"
|
||||
},
|
||||
{
|
||||
"name": "Sokrates von den Kleinen Chaoten",
|
||||
"dob": "14.12.2015",
|
||||
"decision": "D-Locus = D- (nicht Dd) + Sterbedatum = 20.05.2019 (nicht 2020). Genotyp = die einigen Loci aus dem Extrakt mit D auf D- gesetzt (Uw→G normalisiert).",
|
||||
"genotype": "aa Cc[-] D- ee Gg Pp spsp",
|
||||
"dateOfDeath": "20.05.2019",
|
||||
"source": "Julian/Züchterin 2026-06-07 — HUMANQUESTION D7"
|
||||
},
|
||||
{
|
||||
"name": "Percy of little runners",
|
||||
"dob": "16.12.2017",
|
||||
"decision": "P-Locus = Pp (die Quellen unterschieden sich nur bei P: PP // Pp)",
|
||||
"genotype": "aa Cc[chm] DD Ee Gg Pp Spsp",
|
||||
"source": "Julian/Züchterin 2026-06-07 — HUMANQUESTION D7"
|
||||
},
|
||||
{
|
||||
"name": "Iwana of little runners",
|
||||
"dob": "02.10.2018",
|
||||
"decision": "P-Locus = Pp (die Quellen unterschieden sich nur bei P: PP // Pp)",
|
||||
"genotype": "Aa CC DD Ee Gg Pp spsp",
|
||||
"source": "Julian/Züchterin 2026-06-07 — HUMANQUESTION D7"
|
||||
},
|
||||
{
|
||||
"name": "Osamu von den Kleinen Chaoten",
|
||||
"dob": "10.12.2015",
|
||||
"decision": "Sterbedatum = 18.12.2020 (die 01.10.2020-Variante war falsch); Gencode war einig, taub-Flag bleibt via 'Vorhandensein gewinnt'",
|
||||
"dateOfDeath": "18.12.2020",
|
||||
"source": "Julian/Züchterin 2026-06-07 — HUMANQUESTION D7"
|
||||
},
|
||||
{
|
||||
"name": "Max von Privat",
|
||||
"dob": "01.02.2013",
|
||||
"decision": "Genotyp von der Züchterin bestätigt (D-=D-, P=PP); Todesjahr 2014 (kein genaues Datum → Jahr-only-Konvention 01.01.2014). Reject 4 on-file-Varianten: 04.02.2016 / 04.03.2016 / 2014-raw / 30.12.2015.",
|
||||
"genotype": "aa c[chm]c[chm] D- EE GG PP spsp",
|
||||
"dateOfDeath": "01.01.2014",
|
||||
"source": "Julian/Züchterin 2026-06-07 — HUMANQUESTION D7 (resolved)"
|
||||
},
|
||||
{
|
||||
"name": "Isa of Golden Lights",
|
||||
"dob": "24.12.2014",
|
||||
"decision": "Sterbedatum von der Züchterin (DOB-key war im extract teils leer; diese Zeile matcht die konfliktbehaftete Zeile mit dob=24.12.2014)",
|
||||
"dateOfDeath": "21.07.2018",
|
||||
"source": "Julian/Züchterin 2026-06-07 — HUMANQUESTION D7"
|
||||
},
|
||||
{
|
||||
"name": "Jack II von den Kleinen Chaoten",
|
||||
"dob": "14.02.2016",
|
||||
"decision": "Sterbedatum von der Züchterin",
|
||||
"dateOfDeath": "06.10.2019",
|
||||
"source": "Julian/Züchterin 2026-06-07 — HUMANQUESTION D7"
|
||||
},
|
||||
{
|
||||
"name": "Milon von den Kleinen Chaoten",
|
||||
"dob": "27.11.2014",
|
||||
"decision": "A-Locus = Aa (Quellen: Aa // aa — einziger strittiger Locus, Züchterin löst auf Aa); alle anderen Loci waren einig",
|
||||
"genotype": "Aa Cc[chm] D- ee[f] gg Pp spsp",
|
||||
"source": "Julian/Züchterin 2026-06-07 — HUMANQUESTION D7"
|
||||
},
|
||||
{
|
||||
"name": "Sunny von PZ Karl",
|
||||
"dob": "10.04.2014",
|
||||
"decision": "Sterbedatum von der Züchterin; bestätigt = 'von PZ Karl' (nicht 'Sunny Sky of Fiomi')",
|
||||
"dateOfDeath": "30.04.2018",
|
||||
"source": "Julian/Züchterin 2026-06-07 — HUMANQUESTION D7 (Nachtrag)"
|
||||
},
|
||||
{
|
||||
"name": "Dakota of sweet little mouse",
|
||||
"dob": "30.01.2015",
|
||||
"decision": "Genotyp von Julian/Züchterin: A-Locus=Aa, P-Locus=pp, Sp-Locus=Spsp (offene Loci); übrige bestätigt.",
|
||||
"genotype": "Aa CC Dd Ee Gg pp Spsp",
|
||||
"source": "Julian/Züchterin 2026-06-07 — HUMANQUESTION D7"
|
||||
},
|
||||
{
|
||||
"name": "Banjo of Fiomi",
|
||||
"dob": "06.07.2015",
|
||||
"decision": "E-Locus Korrektur: Julian — 'Goldfuchs Starkschecke, nicht Gold Starkschecke' → E-Locus muss ee sein, nicht E-. Extract hatte AA CC DD E- Gg pp Spsp [WP]; korrigiert zu ee (Goldfuchs-Definition). Sohn von Dakota of sweet little mouse.",
|
||||
"genotype": "AA CC DD ee Gg pp Spsp",
|
||||
"farbschlag": "Goldfuchs Starkschecke",
|
||||
"source": "Julian 2026-06-07 — HUMANQUESTION D7 (Sohn-Korrektur, nicht ursprüngliche D7-Liste)"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -217,7 +217,7 @@ def extract_stammbaum(path):
|
||||
# full block: name above, farbschlag/genotype/breeder below
|
||||
dob, death, geno0 = parse_detail(t)
|
||||
name = ""
|
||||
for rr in range(r - 1, r - 4, -1):
|
||||
for rr in range(r - 3, r):
|
||||
if (c, rr) in cells and not re.match(r"^\*?\s?\d", cells[(c, rr)]) \
|
||||
and not gt.looks_like_genotype(cells[(c, rr)]):
|
||||
name = clean_name(cells[(c, rr)])
|
||||
|
||||
@@ -4,36 +4,47 @@ _Automatisch erzeugt von `tools/import/extract.py` — **noch nichts in die Date
|
||||
|
||||
## Überblick
|
||||
|
||||
- Rohe Tier-Einträge aus den Stammbäumen: **950**
|
||||
- Nach Zusammenführung (eindeutige Tiere): **621**
|
||||
- davon mit Geburtsdatum: 326
|
||||
- in mehreren Dateien gefunden (Dubletten zusammengeführt): 158
|
||||
- Konflikte zur Klärung: **5**
|
||||
- Mehrdeutige / unvollständige Einträge (ohne Name+Datum): **310**
|
||||
- Fotos zugeordnet: **137**
|
||||
- Rohe Tier-Einträge aus den Stammbäumen: **2451**
|
||||
- Nach Zusammenführung (eindeutige Tiere): **1007**
|
||||
- davon mit Geburtsdatum: 682
|
||||
- in mehreren Dateien gefunden (Dubletten zusammengeführt): 461
|
||||
- Konflikte zur Klärung: **7**
|
||||
- Mehrdeutige / unvollständige Einträge (ohne Name+Datum): **342**
|
||||
- Fotos zugeordnet: **417**
|
||||
- Würfe aus der Wurfchronik: **752**
|
||||
- Tiere mit Wurf verknüpft: **159** (davon über Geburtsdatum **und** Eltern: 110, nur über Geburtsdatum: 49; mehrdeutig: 10)
|
||||
- Tiere mit Wurf verknüpft: **274** (davon über Geburtsdatum **und** Eltern: 175, nur über Geburtsdatum: 99; mehrdeutig: 14)
|
||||
- Würfe mit Datenqualitäts-Hinweisen: 113 (+ 138 Zeilen mit abweichendem Spaltenschema)
|
||||
|
||||
## Zusammenführungs-Schlüssel
|
||||
|
||||
Tiere wurden zusammengeführt über **normalisierter Rufname + Geburtsdatum**, mit der **Zucht als Unterscheidungsmerkmal** (Julians Regel: die `[Klammern]` in der Wurfchronik und das `of/von <Linie>`-Suffix der Stammbäume bezeichnen beide die Zucht und werden zusammengeführt — z. B. `[ZdkC]` ≙ `von den Kleinen Chaoten`). Namensvarianten (z. B. `v.d.` ↔ `von den`, `gen.`-Spitznamen) werden als `nameVariants` erhalten.
|
||||
|
||||
### Gleicher Name + Geburtsdatum, aber unterschiedliche Zucht (NICHT zusammengeführt — bitte prüfen)
|
||||
|
||||
| Tier | Geburtsdatum | Zuchten | Dateien |
|
||||
|---|---|---|---|
|
||||
| Blacky | 23.07.2009 | PZ Seligenstadt // Privatzucht Seligenstadt | Stammbaum von Danako, Stammbaum von Hana, Stammbaum von Jin, Stammbaum von Unit, Stammbaum von Uriana, Stammbaum von Wildfire und Vestras Kids |
|
||||
| Danny | 09.10.2009 | Maintaler PZ // PZ Maintal | Stammbaum von Hana, Stammbaum von Vance |
|
||||
| Lola | 10.02.2014 | Chalfont Stud, Freddy Braun // Lennylengo | Stammbaum von Jeremy, Stammbaum von Jiminy of Black Forest, Stammbaum von Marlin of Black Forest, Stammbaum von Zac (Vance.Dorie), Stammbaum von Zenon von Elea |
|
||||
| Debby gen. Eva | 08.08.2012 | KK Chaos // KK Chaos of KK Chaos | Stammbaum von Kalea, Stammbaum von Unit, Stammbaum von Uriana |
|
||||
|
||||
## ⚠️ Konflikte (bitte prüfen)
|
||||
|
||||
Gleiches Tier (Name+Datum), aber widersprüchliche Angaben in verschiedenen Dateien:
|
||||
|
||||
| Tier | Geburtsdatum | abweichende Genotypen | abweichende Farbschläge | Sterbedaten | Dateien |
|
||||
|---|---|---|---|---|---|
|
||||
| Kazu von den Kleinen Chaoten | 23.04.2013 | Aa Cc[chm] DD e[f]e[f] Gg P Spsp // Aa Cc[chm] DD ee[f] UwUw PP Spsp | — | 03.09.2017 | Stammbaum von Akio Kids, Stammbaum von Vance |
|
||||
| Little Runner's Big Ben | 03.02.2020 | Aa Cc[chm] DD Ee Gg PP Spsp // Aa Cc[chm] DD Ee Gg Pp Spsp | — | 14.10.2023 | Stammbaum von CP-Fuchs, CP-Sa Sp von Unity, Stammbaum von Fire Kids, Stammbaum von Goldfuchs Sp (Pikachu) Kids, Stammbaum von Kohlief, Goldfuchsef Sp von Chrissi, Stammbaum von Valentino Firehearts Kids, Stammbaum von Watarus Kids |
|
||||
| Vance Jr. von den Kleinen Chaoten | 10.04.2022 | aa Cc[hm] Dd Ee gg P- Spsp // aa Cc[hm] Dd Ee gg P- spsp | Kohlfuchs, hell | — | Stammbaum von Fire Kids, Stammbaum von Stella Kids |
|
||||
| Hanami von den Kleinen Chaoten | 10.09.2015 | aa Cc[chm] D- Ee gg P- spsp | — | 12.12.2019 // 14.01.2020 | Stammbaum von Kentucky, Stammbaum von Stella Kids |
|
||||
| Skarlett v.d. Kleinen Chaoten | 14.07.2013 | / +2018, Aa Cc[chm] DD ee uw[d]uw[d] PP spsp // Aa Cc[chm] DD ee uw[d]uw[d] PP spsp | — | 17.04.2016 // 2018 | Stammbaum von Vance |
|
||||
| Joghurt von Privat | 06.09.2013 | aa CC D- ee GG PP spsp // aa Cc[-] D- ee UwUw PP spsp | Privat | 06.03.2017 | Stammbaum von Akio Kids, Stammbaum von Jin, Stammbaum von Kentucky |
|
||||
| Ken'ichi | 01.03.2015 | AA CC DD Ee GG PP spsp | Agouti // DD-Tumor | 02.11.2018 | Stammbaum von Chesnut, Stammbaum von Emi, Stammbaum von Hana, Stammbaum von Kentucky, Stammbaum von Kohlief, Goldfuchsef Sp von Chrissi |
|
||||
| DD-Tumor bei Geschwister | 10.09.2015 | aa Cc[chm] D- Ee gg P- spsp // aa Cc[chm] D- Ee uw[d]uw[d] P- spsp | — | 02.01.2020 // 12.12.2019 | Stammbaum von Chesnut, Stammbaum von Emi |
|
||||
| Kleiner Warnowrenner Elieus gen. Eragon | 18.05.2016 | aa CC D- Ee Gg pp Spsp [DP] // aa c[chm]c[chm] D- Ee Gg pp Spsp | — | 09.10.2019 | Stammbaum von Chesnut, Stammbaum von Jeremy, Stammbaum von Kentucky, Stammbaum von Martin, Stammbaum von Quied Soldier of Black Forest |
|
||||
| Osamu | 10.12.2015 | AA CC DD ee gg P- spsp // AA CC DD ee gg PP spsp // AA CC DD ee uw[d]uw[d] PP spsp | Polarfuchs | 01.10.2020 // 18.12.2020 | Stammbaum von Danako, Stammbaum von Ella, Stammbaum von Jin, Stammbaum von Kazuya, Stammbaum von Kentucky, Stammbaum von Martin, Stammbaum von Rainny, Stammbaum von Ren, Stammbaum von South Dakota, Stammbaum von Stella Kids, Stammbaum von Tennessee, Stammbaum von Zenon von Elea |
|
||||
| Harumi | 21.02.2015 | aa Cc[chm] DD EE GG PP Spsp | — | 03.06.2017 // 11.01.2018 | Stammbaum von Danako, Stammbaum von Kalea, Stammbaum von Yurikas und Pintos Sohn |
|
||||
| Hanami | 10.09.2015 | aa Cc[chm] D- Ee gg P- spsp // aa Cc[chm] D- Ee uw[d]uw[d] P- spsp | — | 02.01.2020 // 12.12.2019 // 14.01.2020 | Stammbaum von Hana, Stammbaum von Kentucky, Stammbaum von Rainny, Stammbaum von Ren, Stammbaum von Stella Kids, Stammbaum von Vance, Stammbaum von Zac (Vance.Dorie) |
|
||||
|
||||
## Mehrdeutige / unvollständige Einträge
|
||||
|
||||
310 Einträge ohne sichere Name+Datum-Kombination (z. B. `Name1 & Name2`-Paarzellen der tiefsten Generation, oder Zellen ohne Datum). Diese werden NICHT automatisch zusammengeführt.
|
||||
342 Einträge ohne sichere Name+Datum-Kombination (z. B. `Name1 & Name2`-Paarzellen der tiefsten Generation, oder Zellen ohne Datum). Diese werden NICHT automatisch zusammengeführt.
|
||||
|
||||
- Oskar v.d. bunten Fellnase · Stammbaum von Akio Kids.xlsx
|
||||
- Raya v.d. bunten Fellnasen · Stammbaum von Akio Kids.xlsx
|
||||
@@ -78,23 +89,55 @@ Gleiches Tier (Name+Datum), aber widersprüchliche Angaben in verschiedenen Date
|
||||
|
||||
## Wahrscheinliche Zuordnungen unvollständiger Einträge
|
||||
|
||||
39 namenlose/datenlose Einträge tragen denselben Namen wie ein vollständiges Tier — vermutlich dasselbe Tier (zur Bestätigung):
|
||||
91 namenlose/datenlose Einträge tragen denselben Namen wie ein vollständiges Tier — vermutlich dasselbe Tier (zur Bestätigung):
|
||||
|
||||
- „Tai of Lennylengo“ → Tai of Lennylengo (*01.10.2011)
|
||||
- „Arrow PZ Niederlande“ → Arrow PZ Niederlande (*20.05.2014)
|
||||
- „Isa of Golden Lights“ → Isa of Golden Lights (*24.12.2014)
|
||||
- „Leila v. Jessica Walldorf“ → Leila v. Jessica Walldorf (*08.04.2014)
|
||||
- „Osamu“ → Osamu (*10.12.2015)
|
||||
- „Nala“ → Nala (*06.03.2015)
|
||||
- „Oscar of Black Forest“ → Oscar of Black Forest (*12.06.2019)
|
||||
- „Hagrid Rubeus of Black Forest“ → Hagrid Rubeus of Black Forest (*18.07.2019)
|
||||
- „Lilo of LennyLengo“ → Lilo of LennyLengo (*04.11.2018)
|
||||
- „Kazuya“ → Kazuya (*14.07.2019)
|
||||
- „Harumi“ → Harumi (*21.02.2015)
|
||||
- „Pan“ → Pan (*09.12.2014)
|
||||
- „Gin“ → Gin (*05.02.2015)
|
||||
- „Isa of Golden Lights“ → Isa of Golden Lights (*24.12.2014)
|
||||
- „Mystique of Black Forest“ → Mystique of Black Forest (*12.03.2022)
|
||||
- „Elay“ → Elay (*16.03.2016)
|
||||
- „Osamu“ → Osamu (*10.12.2015)
|
||||
- „Baiko“ → Baiko (*02.06.2019)
|
||||
- „Hagrid Rubeus of Black Forest“ → Hagrid Rubeus of Black Forest (*18.07.2019)
|
||||
- „Osamu“ → Osamu (*10.12.2015)
|
||||
- „Umi“ → Umi (*13.08.2016)
|
||||
- „Charly of Golden Lights“ → Charly of Golden Lights (*05.04.2016)
|
||||
- „Ziwa of Golden Lights“ → Ziwa of Golden Lights (*29.04.2016)
|
||||
- „Harumi“ → Harumi (*21.02.2015)
|
||||
- „Pan“ → Pan (*09.12.2014)
|
||||
- „Gin“ → Gin (*05.02.2015)
|
||||
- „Isa of golden lights“ → Isa of Golden Lights (*24.12.2014)
|
||||
- „Porter“ → Porter (*23.05.2015)
|
||||
- „Chelsea von den Kleinen Chaoten“ → Chelsea von den Kleinen Chaoten (*02.04.2021)
|
||||
- „Pinto of Fiomi“ → Pinto of Fiomi (*28.08.2016)
|
||||
- „Nala“ → Nala (*06.03.2015)
|
||||
- „Hanami“ → Hanami (*10.09.2015)
|
||||
- „Living Force's Idefix“ → Living Force's Idefix (*05.04.2016)
|
||||
- „Scarlett of Samsimar“ → Scarlett of Samsimar (*05.09.2018)
|
||||
- „Osamu“ → Osamu (*10.12.2015)
|
||||
- „Baiko“ → Baiko (*02.06.2019)
|
||||
- „Olivia“ → Olivia (*23.07.2019)
|
||||
- „Baiko“ → Baiko (*02.06.2019)
|
||||
- „Olivia“ → Olivia (*23.07.2019)
|
||||
- „Living Force's Idefix“ → Living Force's Idefix (*05.04.2016)
|
||||
- „Rosie of LennyLengo“ → Rosie of LennyLengo (*15.03.2016)
|
||||
- „Pan“ → Pan (*09.12.2014)
|
||||
- „Gin“ → Gin (*05.02.2015)
|
||||
- „Chiako“ → Chiako (*15.11.2016)
|
||||
- „Stich von Privatzucht Gießen“ → Stich von Privatzucht Gießen (*01.09.2018)
|
||||
- „Lilo of LennyLengo“ → Lilo of LennyLengo (*04.11.2018)
|
||||
- „Ken'ichi“ → Ken'ichi (*01.03.2015)
|
||||
- „Rumi“ → Rumi (*24.02.2017)
|
||||
- „Living Force's Idefix“ → Living Force's Idefix (*05.04.2016)
|
||||
- „Rosie of LennyLengo“ → Rosie of LennyLengo (*15.03.2016)
|
||||
- „Living Force's Idefix“ → Living Force's Idefix (*05.04.2016)
|
||||
@@ -103,22 +146,11 @@ Gleiches Tier (Name+Datum), aber widersprüchliche Angaben in verschiedenen Date
|
||||
- „Little Hero of Black Forest“ → Little Hero of Black Forest (*22.02.2018)
|
||||
- „Little Runner's Destiny“ → Little Runner's Destiny (*02.03.2019)
|
||||
- „Chevrolet Camaro of Topolino“ → Chevrolet Camaro of Topolino (*10.04.2018)
|
||||
- „Danako“ → Danako (*22.08.2018)
|
||||
- „Marlin of Black Forest“ → Marlin of Black Forest (*28.05.2019)
|
||||
- „Zenon von Elea“ → Zenon von Elea (*06.10.2019)
|
||||
- „Nisha of Black Forest“ → Nisha of Black Forest (*28.03.2018)
|
||||
- „Nisha of Black Forest“ → Nisha of Black Forest (*28.03.2018)
|
||||
- „Dorie of Black Forest“ → Dorie of Black Forest (*28.05.2019)
|
||||
- „Zadar from Zeko i ptica, Croatia“ → Zadar from Zeko i ptica, Croatia (*12.04.2019)
|
||||
- „Living Force's Vally“ → Living Force's Vally (*01.11.2014)
|
||||
- „Pinto of Fiomi“ → Pinto of Fiomi (*28.08.2016)
|
||||
- „Hanse Renner's Poseidon“ → Hanse Renner's Poseidon (*14.08.2014)
|
||||
- „Oscar of Black Forest“ → Oscar of Black Forest (*12.06.2019)
|
||||
- „Hagrid Rubeus of Black Forest“ → Hagrid Rubeus of Black Forest (*18.07.2019)
|
||||
- „Lilo of LennyLengo“ → Lilo of LennyLengo (*04.11.2018)
|
||||
- „Chevrolet Camaro of Topolino“ → Chevrolet Camaro of Topolino (*10.04.2018)
|
||||
- „Lilo of LennyLengo“ → Lilo of LennyLengo (*04.11.2018)
|
||||
- „Rosie of LennyLengo“ → Rosie of LennyLengo (*15.03.2016)
|
||||
- „Rosie of LennyLengo“ → Rosie of LennyLengo (*15.03.2016)
|
||||
- „Little Runner's Destiny“ → Little Runner's Destiny (*02.03.2019)
|
||||
- „Zenon von Elea“ → Zenon von Elea (*06.10.2019)
|
||||
|
||||
## Nicht ins 8-Loci-Modell abgebildete Tokens (verbatim erhalten)
|
||||
|
||||
@@ -126,22 +158,31 @@ Diese Tokens stehen weiter in `rawGenotype`/`unmappedTokens` — Entscheidung (M
|
||||
|
||||
| Token | Vorkommen | Bedeutung (Vermutung) |
|
||||
|---|---|---|
|
||||
| `/+` | 6 | ? |
|
||||
| `/+` | 7 | ? |
|
||||
| `[meliert]` | 4 | ? |
|
||||
| `[Dea/dea]` | 4 | ? |
|
||||
| `(Kragen)` | 3 | ? |
|
||||
| `/` | 3 | ? |
|
||||
| `-g` | 2 | ? |
|
||||
| `!DD` | 2 | ? |
|
||||
| `Tumor` | 2 | ? |
|
||||
| `!` | 2 | ? |
|
||||
| `C(C)` | 2 | Schreibweise (C trägt c) |
|
||||
| `[dea/*]` | 2 | ? |
|
||||
| `(KW` | 2 | ? |
|
||||
| `Cc[]` | 1 | ? |
|
||||
| `[WFNZ-Maroon]` | 1 | ? |
|
||||
| `/+April'2017` | 1 | ? |
|
||||
| `[meliert]-[DP]` | 1 | ? |
|
||||
| `!Knickschwanz-Gen!` | 1 | ? |
|
||||
| `-09.09.2018` | 1 | ? |
|
||||
| `[dea/dea]` | 1 | ? |
|
||||
| `[DP?]` | 1 | ? |
|
||||
| `/+Dezember'2014` | 1 | ? |
|
||||
| `(Ansatz)` | 1 | ? |
|
||||
| `[WFNZ][dea/*]` | 1 | ? |
|
||||
| `-psp` | 1 | ? |
|
||||
| `G(G)` | 1 | ? |
|
||||
| `/` | 1 | ? |
|
||||
| `+2018` | 1 | ? |
|
||||
| `chmchm` | 1 | Schreibweise (c[chm]c[chm]) |
|
||||
| `c[chm]chm]` | 1 | ? |
|
||||
| `Dea/dea]` | 1 | ? |
|
||||
| `DD-Tumor` | 1 | ? |
|
||||
| `bei` | 1 | ? |
|
||||
| `Geschwistern` | 1 | ? |
|
||||
| `C-D-` | 1 | ? |
|
||||
| `-DD` | 1 | ? |
|
||||
|
||||
## Wurfchronik — Datenqualitäts-Hinweise
|
||||
|
||||
|
||||
379
tools/import/resolve_import.py
Normal file
379
tools/import/resolve_import.py
Normal file
@@ -0,0 +1,379 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import json
|
||||
import uuid
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
||||
# Import normalization helpers from extract.py
|
||||
import extract as ex
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
OUTPUT_DIR = os.path.join(HERE, "output")
|
||||
SEEDS_PATH = os.path.join(HERE, "..", "..", "gerbil-manager-web", "src", "genetics", "colorVarietySeed.backend.json")
|
||||
|
||||
def generate_guid(key_str):
|
||||
"""Generate a stable UUID string based on a key."""
|
||||
return str(uuid.uuid5(uuid.NAMESPACE_DNS, key_str))
|
||||
|
||||
def parse_date_only(d):
|
||||
"""Convert DD.MM.YYYY string to YYYY-MM-DD for JSON serialization."""
|
||||
if not d:
|
||||
return None
|
||||
try:
|
||||
p = d.split(".")
|
||||
if len(p) == 3:
|
||||
day = int(p[0])
|
||||
month = int(p[1])
|
||||
year = int(p[2])
|
||||
if len(p[2]) == 2:
|
||||
year += 2000
|
||||
# Ensure valid date
|
||||
dt = datetime(year, month, day)
|
||||
return dt.strftime("%Y-%m-%d")
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
def save_to_csv(data_list, filepath):
|
||||
import csv
|
||||
if not data_list:
|
||||
return
|
||||
headers = list(data_list[0].keys())
|
||||
with open(filepath, "w", encoding="utf-8-sig", newline="") as f:
|
||||
writer = csv.writer(f, delimiter=";")
|
||||
writer.writerow(headers)
|
||||
for row in data_list:
|
||||
values = []
|
||||
for h in headers:
|
||||
val = row[h]
|
||||
if isinstance(val, (list, dict)):
|
||||
values.append(json.dumps(val, ensure_ascii=False))
|
||||
elif val is None:
|
||||
values.append("")
|
||||
else:
|
||||
values.append(str(val))
|
||||
writer.writerow(values)
|
||||
|
||||
def main():
|
||||
print("Loading extracted JSON files...")
|
||||
animals_file = os.path.join(OUTPUT_DIR, "animals.json")
|
||||
litters_file = os.path.join(OUTPUT_DIR, "litters.json")
|
||||
|
||||
if not os.path.exists(animals_file) or not os.path.exists(litters_file):
|
||||
print(f"Error: extract.py must be run first to generate animals.json and litters.json in {OUTPUT_DIR}")
|
||||
return
|
||||
|
||||
with open(animals_file, "r", encoding="utf-8") as f:
|
||||
animals = json.load(f)
|
||||
with open(litters_file, "r", encoding="utf-8") as f:
|
||||
litters = json.load(f)
|
||||
|
||||
# Load color variety seeds
|
||||
print("Loading color variety seeds...")
|
||||
with open(SEEDS_PATH, "r", encoding="utf-8") as f:
|
||||
seeds = json.load(f)
|
||||
|
||||
# Map variety name -> Guid
|
||||
variety_map = {}
|
||||
for v in seeds:
|
||||
# UUID is based on SortOrder + 1
|
||||
variety_id = f"00000000-0000-0000-0000-{v['sortOrder'] + 1:012d}"
|
||||
variety_map[v["name"].strip().lower()] = variety_id
|
||||
|
||||
# 1. Establish stable Guid maps
|
||||
animal_guid_map = {a["id"]: generate_guid(f"animal-{a['id']}") for a in animals}
|
||||
litter_guid_map = {l["id"]: generate_guid(f"litter-{l['id']}") for l in litters}
|
||||
|
||||
# Index animals for fast lookup by slug ID and by normalized name+dob
|
||||
animal_by_id = {a["id"]: a for a in animals}
|
||||
animal_by_name_dob = {}
|
||||
for a in animals:
|
||||
key = (ex.norm_name(a["name"]), ex.norm_dob(a["dob"]))
|
||||
if key[0] and key[1]:
|
||||
animal_by_name_dob.setdefault(key, []).append(a)
|
||||
|
||||
# 2. Extract and resolve unique Contacts (Breeders & Zuchten)
|
||||
print("Extracting unique contacts...")
|
||||
contact_names = set()
|
||||
for a in animals:
|
||||
if a.get("breeder"):
|
||||
contact_names.add(a["breeder"].strip())
|
||||
if a.get("zucht"):
|
||||
contact_names.add(a["zucht"].strip())
|
||||
for l in litters:
|
||||
if l.get("damZucht"):
|
||||
contact_names.add(l["damZucht"].strip())
|
||||
if l.get("sireZucht"):
|
||||
contact_names.add(l["sireZucht"].strip())
|
||||
|
||||
contact_guid_map = {}
|
||||
resolved_contacts = []
|
||||
for idx, name in enumerate(sorted(contact_names)):
|
||||
norm = name.strip().lower()
|
||||
if not norm or norm in contact_guid_map:
|
||||
continue
|
||||
c_guid = generate_guid(f"contact-{norm}")
|
||||
contact_guid_map[norm] = c_guid
|
||||
resolved_contacts.append({
|
||||
"Id": c_guid,
|
||||
"Name": name,
|
||||
"ZuchtName": name if "zucht" in norm or "clan" in norm or "runner" in norm else "",
|
||||
"City": "",
|
||||
"Email": "",
|
||||
"Homepage": "",
|
||||
"Phone": "",
|
||||
"Address": ""
|
||||
})
|
||||
|
||||
# 3. Resolve parent relationships for litters
|
||||
print("Resolving litter parents...")
|
||||
litter_parent_map = {} # litter_id -> (father_guid, mother_guid)
|
||||
|
||||
# Pre-map parents using offspring parentRefs
|
||||
for a in animals:
|
||||
litter_ref = a.get("litterRef")
|
||||
if not litter_ref or not litter_ref.get("litterId"):
|
||||
continue
|
||||
|
||||
l_id = litter_ref["litterId"]
|
||||
l_parents = litter_parent_map.setdefault(l_id, [None, None]) # [father, mother]
|
||||
|
||||
for p_ref in a.get("parentRefs", []):
|
||||
p_key = (ex.norm_name(p_ref["name"]), ex.norm_dob(p_ref["dob"]))
|
||||
p_candidates = animal_by_name_dob.get(p_key, [])
|
||||
if p_candidates:
|
||||
p_guid = animal_guid_map[p_candidates[0]["id"]]
|
||||
if p_ref["roleGuess"] == "father":
|
||||
l_parents[0] = p_guid
|
||||
elif p_ref["roleGuess"] == "mother":
|
||||
l_parents[1] = p_guid
|
||||
|
||||
# Fallback lookup for parents by name from litter details if offspring has no parentRefs
|
||||
for l in litters:
|
||||
l_parents = litter_parent_map.setdefault(l["id"], [None, None])
|
||||
l_date_str = parse_date_only(l["date"])
|
||||
if not l_date_str:
|
||||
continue
|
||||
l_date = datetime.strptime(l_date_str, "%Y-%m-%d")
|
||||
|
||||
# Fallback Father
|
||||
if not l_parents[0] and l.get("sireName"):
|
||||
sire_norm = ex.norm_name(l["sireName"])
|
||||
# Find an animal with this name born before the litter
|
||||
candidates = []
|
||||
for (name_norm, dob_norm), grp in animal_by_name_dob.items():
|
||||
if name_norm == sire_norm:
|
||||
for cand in grp:
|
||||
c_dob_str = parse_date_only(cand["dob"])
|
||||
if c_dob_str:
|
||||
c_dob = datetime.strptime(c_dob_str, "%Y-%m-%d")
|
||||
if c_dob < l_date:
|
||||
candidates.append(cand)
|
||||
if len(candidates) == 1:
|
||||
l_parents[0] = animal_guid_map[candidates[0]["id"]]
|
||||
|
||||
# Fallback Mother
|
||||
if not l_parents[1] and l.get("damName"):
|
||||
dam_norm = ex.norm_name(l["damName"])
|
||||
candidates = []
|
||||
for (name_norm, dob_norm), grp in animal_by_name_dob.items():
|
||||
if name_norm == dam_norm:
|
||||
for cand in grp:
|
||||
c_dob_str = parse_date_only(cand["dob"])
|
||||
if c_dob_str:
|
||||
c_dob = datetime.strptime(c_dob_str, "%Y-%m-%d")
|
||||
if c_dob < l_date:
|
||||
candidates.append(cand)
|
||||
if len(candidates) == 1:
|
||||
l_parents[1] = animal_guid_map[candidates[0]["id"]]
|
||||
|
||||
# 4. Construct Litters collection
|
||||
resolved_litters = []
|
||||
for l in litters:
|
||||
l_guid = litter_guid_map[l["id"]]
|
||||
p_father, p_mother = litter_parent_map.get(l["id"], [None, None])
|
||||
l_date = parse_date_only(l["date"])
|
||||
if not l_date:
|
||||
continue # Skip litters without dates
|
||||
|
||||
# Inzucht/Frühsterblichkeit mapping
|
||||
deaths_8w = None
|
||||
if l.get("diedLater") is not None or l.get("stillborn") is not None:
|
||||
deaths_8w = (l.get("stillborn") or 0) + (l.get("diedLater") or 0)
|
||||
|
||||
resolved_litters.append({
|
||||
"Id": l_guid,
|
||||
"Name": f"Wurf {l['litterId']}".strip(),
|
||||
"Date": l_date,
|
||||
"TotalBorn": l.get("totalBorn"),
|
||||
"DeathsWithin8Weeks": deaths_8w,
|
||||
"FatherId": p_father,
|
||||
"MotherId": p_mother,
|
||||
"ExpectedGoHomeDate": None,
|
||||
"Notes": l.get("note") if l.get("note") else None,
|
||||
"PairingCode": l.get("zuchtnummer") if l.get("zuchtnummer") else None,
|
||||
"ExternalRef": l["id"],
|
||||
"LitterLetter": l["litterId"] if len(l["litterId"]) <= 2 else None
|
||||
})
|
||||
|
||||
# 5. Determine Residency & Status
|
||||
# C# Residency Rule: IsResident iff Zuchtname matches Clan kennel, OR is parent of resident
|
||||
resident_guids = set()
|
||||
# Step A: Direct Zucht name match
|
||||
for a in animals:
|
||||
if ex.is_clan_zucht(a.get("zucht")) or ex.is_clan_zucht(a.get("zuchtCanon")):
|
||||
resident_guids.add(animal_guid_map[a["id"]])
|
||||
|
||||
# Step B: Parent of Clan offspring
|
||||
# Re-run propagation loop a few times to cover multiple generations
|
||||
for _ in range(5):
|
||||
for l in litters:
|
||||
l_guid = litter_guid_map[l["id"]]
|
||||
# Check if any offspring of this litter is resident
|
||||
offspring_guids = [animal_guid_map[a["id"]] for a in animals if a.get("litterRef") and a["litterRef"].get("litterId") == l["id"]]
|
||||
has_resident_offspring = any(og in resident_guids for og in offspring_guids)
|
||||
|
||||
if has_resident_offspring:
|
||||
p_father, p_mother = litter_parent_map.get(l["id"], [None, None])
|
||||
if p_father:
|
||||
resident_guids.add(p_father)
|
||||
if p_mother:
|
||||
resident_guids.add(p_mother)
|
||||
|
||||
# 6. Construct Gerbils collection
|
||||
resolved_gerbils = []
|
||||
resolved_photos = []
|
||||
|
||||
for a in animals:
|
||||
a_guid = animal_guid_map[a["id"]]
|
||||
|
||||
# Resolve ColorVariety
|
||||
cv_id = None
|
||||
fb_key = a["farbschlag"].strip().lower()
|
||||
if fb_key in variety_map:
|
||||
cv_id = variety_map[fb_key]
|
||||
else:
|
||||
# Try matching variants
|
||||
for fbv in a.get("farbschlagVariants", []):
|
||||
fbv_key = fbv.strip().lower()
|
||||
if fbv_key in variety_map:
|
||||
cv_id = variety_map[fbv_key]
|
||||
break
|
||||
|
||||
# Resolve Litter
|
||||
l_id = None
|
||||
l_ref = a.get("litterRef")
|
||||
if l_ref and l_ref.get("litterId") and l_ref["litterId"] in litter_guid_map:
|
||||
l_id = litter_guid_map[l_ref["litterId"]]
|
||||
|
||||
# Resolve Contacts
|
||||
origin_contact_id = None
|
||||
breeder_norm = a.get("breeder", "").strip().lower()
|
||||
zucht_norm = a.get("zucht", "").strip().lower()
|
||||
if breeder_norm in contact_guid_map:
|
||||
origin_contact_id = contact_guid_map[breeder_norm]
|
||||
elif zucht_norm in contact_guid_map:
|
||||
origin_contact_id = contact_guid_map[zucht_norm]
|
||||
|
||||
# Dates
|
||||
dob = parse_date_only(a.get("dob"))
|
||||
death = parse_date_only(a.get("death"))
|
||||
|
||||
# Gender conversion: M -> male, W -> female
|
||||
gender = "Unknown"
|
||||
if a.get("gender") == "M":
|
||||
gender = "male"
|
||||
elif a.get("gender") == "W":
|
||||
gender = "female"
|
||||
|
||||
# Determine Residency
|
||||
is_resident = a_guid in resident_guids
|
||||
|
||||
# Determine Status
|
||||
status = "Breeding"
|
||||
if death:
|
||||
status = "Deceased"
|
||||
elif not is_resident:
|
||||
status = "GivenAway"
|
||||
else:
|
||||
# Age presumed deceased (>7 years)
|
||||
if dob:
|
||||
dt_dob = datetime.strptime(dob, "%Y-%m-%d")
|
||||
dt_now = datetime.now()
|
||||
age_years = (dt_now - dt_dob).days / 365.25
|
||||
if age_years >= 7.0:
|
||||
status = "Deceased"
|
||||
else:
|
||||
status = "Breeding" # default to breeding for resident stock
|
||||
|
||||
# Raw Import payload
|
||||
raw_import_payload = json.dumps({
|
||||
"rawGenotype": a["genotype"]["rawGenotype"],
|
||||
"unmappedTokens": a["genotype"]["unmappedTokens"],
|
||||
"breederText": a.get("breeder", "")
|
||||
}, ensure_ascii=False)
|
||||
|
||||
resolved_gerbils.append({
|
||||
"Id": a_guid,
|
||||
"Name": a["name"],
|
||||
"Gender": gender,
|
||||
"Status": status,
|
||||
"LitterId": l_id,
|
||||
"OriginContactId": origin_contact_id,
|
||||
"ReceiverContactId": None,
|
||||
"EnclosureId": None,
|
||||
"ColorVarietyId": cv_id,
|
||||
"DateOfBirth": dob,
|
||||
"DateOfDeath": death,
|
||||
"CauseOfDeath": None,
|
||||
"GoHomeDate": None,
|
||||
"Genotype": a["genotype"]["rawGenotype"] if a["genotype"]["rawGenotype"] else None,
|
||||
"Notes": None,
|
||||
"ImportSource": "docx-export",
|
||||
"ExternalRef": a["id"],
|
||||
"RawImportData": raw_import_payload,
|
||||
"OriginBreeder": a.get("breeder") if a.get("breeder") else (a.get("zucht") if a.get("zucht") else None),
|
||||
"NameSearch": ex.norm_name(a["name"]),
|
||||
"CharacterTraits": [],
|
||||
"CharacterNote": None,
|
||||
"IsDeaf": a.get("deaf"),
|
||||
"IsResident": is_resident
|
||||
})
|
||||
|
||||
# Attach Photos
|
||||
for idx, photo_rel in enumerate(a.get("photos", [])):
|
||||
photo_guid = generate_guid(f"photo-{photo_rel}")
|
||||
resolved_photos.append({
|
||||
"Id": photo_guid,
|
||||
"GerbilId": a_guid,
|
||||
"FileName": os.path.basename(photo_rel),
|
||||
"SortOrder": idx
|
||||
})
|
||||
|
||||
# Save resolved data
|
||||
resolved_data = {
|
||||
"Contacts": resolved_contacts,
|
||||
"Litters": resolved_litters,
|
||||
"Gerbils": resolved_gerbils,
|
||||
"GerbilPhotos": resolved_photos
|
||||
}
|
||||
|
||||
resolved_path = os.path.join(OUTPUT_DIR, "resolved_import.json")
|
||||
with open(resolved_path, "w", encoding="utf-8") as f:
|
||||
json.dump(resolved_data, f, ensure_ascii=False, indent=2)
|
||||
|
||||
# Save resolved CSV files
|
||||
save_to_csv(resolved_contacts, os.path.join(OUTPUT_DIR, "resolved_contacts.csv"))
|
||||
save_to_csv(resolved_litters, os.path.join(OUTPUT_DIR, "resolved_litters.csv"))
|
||||
save_to_csv(resolved_gerbils, os.path.join(OUTPUT_DIR, "resolved_gerbils.csv"))
|
||||
save_to_csv(resolved_photos, os.path.join(OUTPUT_DIR, "resolved_photos.csv"))
|
||||
|
||||
print(f"Success! Saved resolved database-ready records to {resolved_path} (and CSV counterparts):")
|
||||
print(f" Contacts: {len(resolved_contacts)}")
|
||||
print(f" Litters: {len(resolved_litters)}")
|
||||
print(f" Gerbils: {len(resolved_gerbils)}")
|
||||
print(f" GerbilPhotos: {len(resolved_photos)}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
32
tools/wipe-import-data.sql
Normal file
32
tools/wipe-import-data.sql
Normal file
@@ -0,0 +1,32 @@
|
||||
-- WIPE-IMPORT-DATA: truncate only import-derived tables, preserve seeded data.
|
||||
--
|
||||
-- Scope (god decision 2026-06-07):
|
||||
-- WIPE: GerbilPhotos, WeightRecords, HealthRecords, Gerbils, Litters
|
||||
-- KEEP: ColorVarieties (migration-seeded, import matches against these)
|
||||
-- BreederSettings, Sites, Pages (CMS), Contacts, Enclosures,
|
||||
-- SaleContracts, Requests, MailSettings
|
||||
--
|
||||
-- Run ONLY after pg_dump backup. FK order: dependents first.
|
||||
-- Usage (with Aspire Postgres running):
|
||||
-- docker exec -i <postgres-container> psql -U postgres gerbilmanager < tools/wipe-import-data.sql
|
||||
-- OR connect via psql and \i this file.
|
||||
|
||||
BEGIN;
|
||||
|
||||
-- 1. leaf dependents
|
||||
TRUNCATE TABLE "GerbilPhotos" CASCADE;
|
||||
TRUNCATE TABLE "WeightRecords" CASCADE;
|
||||
TRUNCATE TABLE "HealthRecords" CASCADE;
|
||||
|
||||
-- 2. main import tables (Gerbils before Litters: Gerbil.LitterId FK)
|
||||
TRUNCATE TABLE "Gerbils" CASCADE;
|
||||
TRUNCATE TABLE "Litters" CASCADE;
|
||||
|
||||
COMMIT;
|
||||
|
||||
-- Verify (expected: 0 rows each)
|
||||
SELECT 'GerbilPhotos' AS tbl, COUNT(*) FROM "GerbilPhotos"
|
||||
UNION ALL SELECT 'WeightRecords', COUNT(*) FROM "WeightRecords"
|
||||
UNION ALL SELECT 'HealthRecords', COUNT(*) FROM "HealthRecords"
|
||||
UNION ALL SELECT 'Gerbils', COUNT(*) FROM "Gerbils"
|
||||
UNION ALL SELECT 'Litters', COUNT(*) FROM "Litters";
|
||||
Reference in New Issue
Block a user