feat(relationship): editable relationships with LocalDate+DatePrecision dates and notes (#841)
All checks were successful
CI / Unit & Component Tests (push) Successful in 5m10s
CI / OCR Service Tests (push) Successful in 24s
CI / Backend Unit Tests (push) Successful in 5m14s
CI / fail2ban Regex (push) Successful in 50s
CI / Semgrep Security Scan (push) Successful in 27s
CI / Compose Bucket Idempotency (push) Successful in 1m5s

Closes #837

Makes `PersonRelationship` fully editable (type, related person, dates, notes), migrates its dates from `Integer fromYear/toYear` to `LocalDate + DatePrecision` (mirroring the #773 person pattern, ADR-039 / V76), activates the previously-dead `notes` column, and gives the Zeitstrahl's derived **Heirat** events full date precision for free.

Both Open Decisions confirmed as adopted: **no `@Version`** (last-write-wins, single-writer archive) and **`DELETE` ownership-mismatch aligned 403 → 404** (anti-enumeration, matching the new `PUT`).

## What's in it
- **V78** migrates `person_relationships.from_year/to_year` → `from_date`/`to_date` + NOT-NULL `*_date_precision` (default `UNKNOWN`); pre-check abort on corrupt years, `YYYY-01-01`/`YEAR` backfill, 5 named CHECK constraints, year columns dropped.
- **`PUT /api/persons/{id}/relationships/{relId}`** (`@RequirePermission(WRITE_ALL)`) re-runs every create invariant (self / coherence / order / reverse-PARENT_OF / duplicate) and re-flags family membership; orientation preserved per viewpoint.
- New `ErrorCode.INVALID_RELATIONSHIP_DATES` registered in all four sites (§3.6).
- `TimelineEventService` sources the derived marriage date from `SPOUSE_OF.fromDate` + precision.
- Frontend: `RelationshipDateField` (DAY/MONTH/YEAR), upsert-capable `AddRelationshipForm` (pre-fill + notes + in-flight submit lock), `RelationshipChip` Edit affordance, `updateRelationship` server action, read-view date range + notes, `formatRelationshipDateRange` helper. `api.ts` regenerated.
- Docs: ADR-044, db-orm/db-relationships diagrams, DEPLOYMENT §5 deploy note, RTM REQ-001…REQ-019.

## Requirements
All 19 EARS requirements implemented red/green and marked `Done` in `.specify/rtm.md`.

## Test plan
- **Backend** (targeted, green): `RelationshipMigrationTest` (Testcontainers pg16, 8), `RelationshipServiceTest` (22), `RelationshipControllerTest` (15), `RelationshipServiceIntegrationTest` (real DB, 10), `DerivedEventsAssemblyTest` (17), `ArchitectureTest` (14); `clean package` builds.
- **Frontend** (green): `relationshipDates.spec.ts`, `AddRelationshipForm.svelte.spec.ts`, `RelationshipChip.svelte.spec.ts`, `PersonRelationshipsCard.svelte.test.ts`, `page.server.spec.ts`, `messages.spec.ts`. `npm run check` = 798 (below the ~834 baseline); `npm run lint` clean.

## Notes for reviewers
- **Spec deviation:** the edit form was built by making `AddRelationshipForm` upsert-capable rather than a duplicate `EditRelationshipForm` (DRY); RTM rows reference `AddRelationshipForm.svelte.spec.ts`.
- `api.ts` regenerated from the live spec; only relationship-relevant hunks remain (one springdoc `PageableObject` field-reorder pruned).
- **Deploy:** V78 is one-way and not rolling-deploy-safe — stop old JAR → start new JAR (Flyway runs first); targeted `pg_restore -t person_relationships` for rollback. No maintenance window.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Marcel <marcel@familienarchiv>
Reviewed-on: #841
This commit was merged in pull request #841.
This commit is contained in:
2026-06-14 21:17:36 +02:00
parent 6dae4fe428
commit 8558567688
59 changed files with 2196 additions and 580 deletions

View File

@@ -1,6 +1,7 @@
<script lang="ts">
import { m } from '$lib/paraglide/messages.js';
import { chipLabel, otherName, inferredRelationshipLabel } from '$lib/person/relationshipLabels';
import { formatRelationshipDateRange } from '$lib/person/relationshipDates';
import type { components } from '$lib/generated/api';
type RelationshipDTO = components['schemas']['RelationshipDTO'];
@@ -35,18 +36,37 @@ function otherId(rel: RelationshipDTO): string {
{#if relationships.length > 0}
<ul class="mb-4 space-y-2">
{#each relationships as rel (rel.id)}
<li class="flex items-center gap-2">
<span
class="inline-flex shrink-0 items-center rounded-full border border-accent/40 bg-accent/15 px-2 py-0.5 font-sans text-xs font-bold tracking-widest text-ink uppercase"
>
{chipLabel(rel, personId)}
</span>
<a
href="/persons/{otherId(rel)}"
class="min-w-0 flex-1 truncate font-serif text-sm text-ink hover:underline"
>
{otherName(rel, personId)}
</a>
{@const dateRange = formatRelationshipDateRange(
rel.fromDate,
rel.fromDatePrecision,
rel.toDate,
rel.toDatePrecision
)}
<li class="flex flex-col gap-0.5">
<div class="flex items-center gap-2">
<span
class="inline-flex shrink-0 items-center rounded-full border border-accent/40 bg-accent/15 px-2 py-0.5 font-sans text-xs font-bold tracking-widest text-ink uppercase"
>
{chipLabel(rel, personId)}
</span>
<a
href="/persons/{otherId(rel)}"
class="min-w-0 flex-1 truncate font-serif text-sm text-ink hover:underline"
>
{otherName(rel, personId)}
</a>
{#if dateRange}
<span
class="shrink-0 font-sans text-xs text-ink-3"
data-testid="relationship-date-range">{dateRange}</span
>
{/if}
</div>
{#if rel.notes}
<p class="pl-1 font-serif text-xs text-ink-2 italic" data-testid="relationship-notes">
{rel.notes}
</p>
{/if}
</li>
{/each}
</ul>

View File

@@ -18,7 +18,9 @@ describe('PersonRelationshipsCard', () => {
relatedPersonId: SPOUSE_ID,
personDisplayName: 'Anna Müller',
relatedPersonDisplayName: 'Bertha Müller',
relationType: 'SPOUSE_OF'
relationType: 'SPOUSE_OF',
fromDatePrecision: 'UNKNOWN',
toDatePrecision: 'UNKNOWN'
}
],
inferredRelationships: [
@@ -65,7 +67,9 @@ describe('PersonRelationshipsCard', () => {
relatedPersonId: PARENT_ID,
personDisplayName: 'Anna Müller',
relatedPersonDisplayName: 'Kind Müller',
relationType: 'PARENT_OF'
relationType: 'PARENT_OF',
fromDatePrecision: 'UNKNOWN',
toDatePrecision: 'UNKNOWN'
}
],
inferredRelationships: []
@@ -84,7 +88,9 @@ describe('PersonRelationshipsCard', () => {
relatedPersonId: SPOUSE_ID,
personDisplayName: 'Anna',
relatedPersonDisplayName: 'Bertha',
relationType: 'SPOUSE_OF'
relationType: 'SPOUSE_OF',
fromDatePrecision: 'UNKNOWN',
toDatePrecision: 'UNKNOWN'
}
],
inferredRelationships: [
@@ -113,7 +119,9 @@ describe('PersonRelationshipsCard', () => {
relatedPersonId: PERSON_ID,
personDisplayName: 'Eltern Müller',
relatedPersonDisplayName: 'Anna Müller',
relationType: 'PARENT_OF'
relationType: 'PARENT_OF',
fromDatePrecision: 'UNKNOWN',
toDatePrecision: 'UNKNOWN'
}
],
inferredRelationships: []
@@ -121,4 +129,74 @@ describe('PersonRelationshipsCard', () => {
await expect.element(page.getByText('Kind von')).toBeInTheDocument();
});
it('renders the date range at its stored precision', async () => {
render(PersonRelationshipsCard, {
personId: PERSON_ID,
relationships: [
{
id: 'r1',
personId: PERSON_ID,
relatedPersonId: SPOUSE_ID,
personDisplayName: 'Anna Müller',
relatedPersonDisplayName: 'Bertha Müller',
relationType: 'SPOUSE_OF',
fromDate: '1923-05-12',
fromDatePrecision: 'DAY',
toDatePrecision: 'UNKNOWN'
}
],
inferredRelationships: []
});
await expect
.element(page.getByTestId('relationship-date-range'))
.toHaveTextContent('12. Mai 1923');
});
it('shows the notes line', async () => {
render(PersonRelationshipsCard, {
personId: PERSON_ID,
relationships: [
{
id: 'r1',
personId: PERSON_ID,
relatedPersonId: SPOUSE_ID,
personDisplayName: 'Anna Müller',
relatedPersonDisplayName: 'Bertha Müller',
relationType: 'SPOUSE_OF',
fromDatePrecision: 'UNKNOWN',
toDatePrecision: 'UNKNOWN',
notes: 'Hochzeit in Berlin'
}
],
inferredRelationships: []
});
await expect
.element(page.getByTestId('relationship-notes'))
.toHaveTextContent('Hochzeit in Berlin');
});
it('renders no date line when the relationship has no dates', async () => {
render(PersonRelationshipsCard, {
personId: PERSON_ID,
relationships: [
{
id: 'r1',
personId: PERSON_ID,
relatedPersonId: SPOUSE_ID,
personDisplayName: 'Anna Müller',
relatedPersonDisplayName: 'Bertha Müller',
relationType: 'SPOUSE_OF',
fromDatePrecision: 'UNKNOWN',
toDatePrecision: 'UNKNOWN'
}
],
inferredRelationships: []
});
await expect.element(page.getByText('Bertha Müller')).toBeInTheDocument();
expect(document.querySelector('[data-testid="relationship-date-range"]')).toBeNull();
});
});

View File

@@ -2,12 +2,40 @@ import { error, fail, redirect } from '@sveltejs/kit';
import { createApiClient, extractErrorCode } from '$lib/shared/api.server';
import { getErrorMessage } from '$lib/shared/errors';
import type { DatePrecision } from '$lib/shared/utils/documentDate';
import type { components } from '$lib/generated/api';
import {
normalizePersonType,
validatePersonFields,
resolveValidationMessage
} from '$lib/person/person-validation';
type RelationType = NonNullable<components['schemas']['RelationshipUpsertRequest']['relationType']>;
// Parses the shared relationship create/update form into a RelationshipUpsertRequest
// body. An empty date omits date AND precision so the backend normalises the pair to
// null/UNKNOWN — a lone precision would fail the coherence check (INVALID_DATE_PRECISION).
function parseRelationshipForm(formData: FormData) {
const relatedPersonId = formData.get('relatedPersonId')?.toString();
const relationType = formData.get('relationType')?.toString();
const notes = formData.get('notes')?.toString().trim() || undefined;
const fromDate = formData.get('fromDate')?.toString().trim() || undefined;
const fromDatePrecision = fromDate
? (formData.get('fromDatePrecision')?.toString() as DatePrecision)
: undefined;
const toDate = formData.get('toDate')?.toString().trim() || undefined;
const toDatePrecision = toDate
? (formData.get('toDatePrecision')?.toString() as DatePrecision)
: undefined;
const body = {
relatedPersonId: relatedPersonId ?? '',
relationType: (relationType ?? 'OTHER') as RelationType,
...(fromDate ? { fromDate, fromDatePrecision } : {}),
...(toDate ? { toDate, toDatePrecision } : {}),
...(notes ? { notes } : {})
};
return { relatedPersonId, relationType, body };
}
export async function load({ params, fetch, locals }) {
const canWrite =
(locals.user as { groups?: { permissions: string[] }[] } | undefined)?.groups?.some((g) =>
@@ -193,40 +221,45 @@ export const actions = {
addRelationship: async ({ request, params, fetch }) => {
const formData = await request.formData();
const relatedPersonId = formData.get('relatedPersonId')?.toString();
const relationType = formData.get('relationType')?.toString();
const fromYearRaw = formData.get('fromYear')?.toString().trim();
const toYearRaw = formData.get('toYear')?.toString().trim();
const notes = formData.get('notes')?.toString().trim() || undefined;
const fields = parseRelationshipForm(formData);
if (!relatedPersonId || !relationType) {
if (!fields.relatedPersonId || !fields.relationType) {
return fail(400, { relationshipError: getErrorMessage('VALIDATION_ERROR') });
}
if (relatedPersonId === params.id) {
return fail(400, { relationshipError: getErrorMessage('VALIDATION_ERROR') });
}
const fromYear = fromYearRaw ? parseInt(fromYearRaw, 10) : undefined;
const toYear = toYearRaw ? parseInt(toYearRaw, 10) : undefined;
if (
fromYear !== undefined &&
toYear !== undefined &&
!Number.isNaN(fromYear) &&
!Number.isNaN(toYear) &&
toYear < fromYear
) {
if (fields.relatedPersonId === params.id) {
return fail(400, { relationshipError: getErrorMessage('VALIDATION_ERROR') });
}
const api = createApiClient(fetch);
const result = await api.POST('/api/persons/{id}/relationships', {
params: { path: { id: params.id } },
body: {
relatedPersonId,
relationType,
...(fromYear !== undefined && !Number.isNaN(fromYear) ? { fromYear } : {}),
...(toYear !== undefined && !Number.isNaN(toYear) ? { toYear } : {}),
...(notes ? { notes } : {})
}
body: fields.body
});
if (!result.response.ok) {
return fail(result.response.status, {
relationshipError: getErrorMessage(extractErrorCode(result.error))
});
}
return { relationshipSuccess: true };
},
updateRelationship: async ({ request, params, fetch }) => {
const formData = await request.formData();
const relId = formData.get('relId')?.toString();
const fields = parseRelationshipForm(formData);
if (!relId || !fields.relatedPersonId || !fields.relationType) {
return fail(400, { relationshipError: getErrorMessage('VALIDATION_ERROR') });
}
if (fields.relatedPersonId === params.id) {
return fail(400, { relationshipError: getErrorMessage('VALIDATION_ERROR') });
}
const api = createApiClient(fetch);
const result = await api.PUT('/api/persons/{id}/relationships/{relId}', {
params: { path: { id: params.id, relId } },
body: fields.body
});
if (!result.response.ok) {

View File

@@ -97,3 +97,98 @@ describe('persons/[id]/edit update action — generation (#689)', () => {
expect(body).toHaveProperty('generation', 3);
});
});
describe('persons/[id]/edit relationship actions (#837)', () => {
function relForm(overrides: Record<string, string | null> = {}): Request {
const fd = new FormData();
fd.set('relatedPersonId', 'p2');
fd.set('relationType', 'SPOUSE_OF');
for (const [k, v] of Object.entries(overrides)) {
if (v == null) fd.delete(k);
else fd.set(k, v);
}
return new Request('http://localhost/persons/p1/edit', { method: 'POST', body: fd });
}
it('addRelationship posts date + precision + notes', async () => {
const post = vi.fn().mockResolvedValue({ response: { ok: true, status: 200 }, data: {} });
vi.mocked(createApiClient).mockReturnValue({ POST: post } as unknown as ReturnType<
typeof createApiClient
>);
const request = relForm({
fromDate: '1923-05-12',
fromDatePrecision: 'DAY',
notes: 'Hochzeit'
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await actions.addRelationship({ request, params: { id: 'p1' }, fetch: mockFetch } as any);
const [path, opts] = post.mock.calls[0];
expect(path).toBe('/api/persons/{id}/relationships');
expect(opts.body).toMatchObject({
relatedPersonId: 'p2',
relationType: 'SPOUSE_OF',
fromDate: '1923-05-12',
fromDatePrecision: 'DAY',
notes: 'Hochzeit'
});
});
it('addRelationship omits precision when the date is empty (coherence)', async () => {
const post = vi.fn().mockResolvedValue({ response: { ok: true, status: 200 }, data: {} });
vi.mocked(createApiClient).mockReturnValue({ POST: post } as unknown as ReturnType<
typeof createApiClient
>);
const request = relForm({ fromDatePrecision: 'DAY' }); // precision but no date
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await actions.addRelationship({ request, params: { id: 'p1' }, fetch: mockFetch } as any);
const body = post.mock.calls[0][1].body;
expect(body).not.toHaveProperty('fromDate');
expect(body).not.toHaveProperty('fromDatePrecision');
});
it('updateRelationship PUTs to the relId path with the new body', async () => {
const put = vi.fn().mockResolvedValue({ response: { ok: true, status: 200 }, data: {} });
vi.mocked(createApiClient).mockReturnValue({ PUT: put } as unknown as ReturnType<
typeof createApiClient
>);
const request = relForm({ relId: 'rel-9', fromDate: '1923-05-12', fromDatePrecision: 'DAY' });
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await actions.updateRelationship({ request, params: { id: 'p1' }, fetch: mockFetch } as any);
const [path, opts] = put.mock.calls[0];
expect(path).toBe('/api/persons/{id}/relationships/{relId}');
expect(opts.params.path).toMatchObject({ id: 'p1', relId: 'rel-9' });
expect(opts.body).toMatchObject({
relatedPersonId: 'p2',
relationType: 'SPOUSE_OF',
fromDate: '1923-05-12',
fromDatePrecision: 'DAY'
});
});
it('updateRelationship surfaces a backend error as a fail', async () => {
const put = vi.fn().mockResolvedValue({
response: { ok: false, status: 400 },
error: { code: 'INVALID_RELATIONSHIP_DATES' }
});
vi.mocked(createApiClient).mockReturnValue({ PUT: put } as unknown as ReturnType<
typeof createApiClient
>);
const request = relForm({ relId: 'rel-9' });
const result = (await actions.updateRelationship({
request,
params: { id: 'p1' },
fetch: mockFetch
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)) as { status: number; data: { relationshipError: string } };
expect(result.status).toBe(400);
expect(result.data.relationshipError).toBeTruthy();
});
});