feat(admin): add OCR training card to admin/system page

- TrainingHistory.svelte: responsive table with status badges
  (green/red/animated pulse), keyed iteration, empty-state row
- OcrTrainingCard.svelte: shows available blocks/docs, disabled states
  (< 5 blocks, service down), in-flight "…" state, 5s success message,
  embeds TrainingHistory
- Wired into admin/system/+page.svelte via fetchTrainingInfo() in $effect
- Regenerated api.ts with OcrTrainingRun + TrainingInfoResponse types
- TRAINING_ALREADY_RUNNING error code in errors.ts + de/en/es translations
- 7 OcrTrainingCard Vitest tests

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Marcel
2026-04-13 14:58:13 +02:00
parent 88e005eb49
commit 4e08d31e01
10 changed files with 473 additions and 4 deletions

View File

@@ -0,0 +1,91 @@
<script lang="ts">
import TrainingHistory from './TrainingHistory.svelte';
interface Run {
id: string;
status: 'RUNNING' | 'DONE' | 'FAILED';
blockCount: number;
documentCount: number;
modelName: string;
errorMessage?: string;
triggeredBy?: string;
createdAt: string;
completedAt?: string;
}
interface TrainingInfo {
availableBlocks?: number;
totalOcrBlocks?: number;
availableDocuments?: number;
ocrServiceAvailable?: boolean;
lastRun?: Run | null;
runs?: Run[];
}
interface Props {
trainingInfo: TrainingInfo | null;
}
let { trainingInfo }: Props = $props();
let training = $state(false);
let successMessage = $state<string | null>(null);
const available = $derived(trainingInfo?.availableBlocks ?? 0);
const tooFewBlocks = $derived(available < 5);
const serviceDown = $derived(trainingInfo?.ocrServiceAvailable === false);
const disabled = $derived(training || tooFewBlocks || serviceDown);
async function startTraining() {
training = true;
successMessage = null;
try {
const res = await fetch('/api/ocr/train', { method: 'POST' });
if (res.ok) {
successMessage = 'Training wurde gestartet und abgeschlossen.';
setTimeout(() => {
successMessage = null;
}, 5000);
}
} finally {
training = false;
}
}
</script>
<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
<h2 class="mb-1 font-sans text-sm font-bold text-ink">Kurrent-Erkennung trainieren</h2>
<p class="mb-4 text-sm text-ink-2">
Starte ein neues Training mit den bisher geprüften OCR-Blöcken, um die Erkennungsgenauigkeit für
Kurrentschrift zu verbessern.
</p>
<p class="mb-3 text-sm text-ink">
<strong>{available}</strong> geprüfte Blöcke bereit /
<strong>{trainingInfo?.availableDocuments ?? 0}</strong> Dokumente
<span class="text-ink-2">(von {trainingInfo?.totalOcrBlocks ?? 0} OCR-Blöcken gesamt)</span>
</p>
<button
onclick={startTraining}
disabled={disabled}
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80 focus-visible:ring-2 focus-visible:ring-brand-navy disabled:cursor-not-allowed disabled:opacity-50"
>
{training ? '…' : 'Training starten'}
</button>
{#if tooFewBlocks}
<p class="mt-2 text-xs text-ink-3">
Mindestens 5 geprüfte Blöcke erforderlich (aktuell: {available}).
</p>
{:else if serviceDown}
<p class="mt-2 text-xs text-orange-600">OCR-Dienst ist nicht erreichbar.</p>
{/if}
{#if successMessage}
<p class="mt-2 text-xs text-green-700">{successMessage}</p>
{/if}
<h3 class="mt-6 mb-3 text-xs font-bold tracking-widest text-ink-3 uppercase">Verlauf</h3>
<TrainingHistory runs={trainingInfo?.runs ?? []} />
</div>

View File

@@ -0,0 +1,96 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';
import OcrTrainingCard from './OcrTrainingCard.svelte';
afterEach(cleanup);
afterEach(() => vi.restoreAllMocks());
const baseInfo = {
availableBlocks: 10,
totalOcrBlocks: 20,
availableDocuments: 3,
ocrServiceAvailable: true,
lastRun: null,
runs: []
};
describe('OcrTrainingCard — disabled states', () => {
it('disables button and shows hint when availableBlocks is 0', async () => {
render(OcrTrainingCard, { trainingInfo: { ...baseInfo, availableBlocks: 0 } });
const btn = page.getByRole('button', { name: /Training starten/i });
await expect.element(btn).toBeDisabled();
await expect
.element(page.getByText(/Mindestens 5 geprüfte Blöcke erforderlich/i))
.toBeInTheDocument();
});
it('disables button and shows hint when availableBlocks is less than 5', async () => {
render(OcrTrainingCard, { trainingInfo: { ...baseInfo, availableBlocks: 3 } });
const btn = page.getByRole('button', { name: /Training starten/i });
await expect.element(btn).toBeDisabled();
await expect.element(page.getByText(/Mindestens 5/i)).toBeInTheDocument();
});
it('disables button and shows service-down warning when ocrServiceAvailable is false', async () => {
render(OcrTrainingCard, { trainingInfo: { ...baseInfo, ocrServiceAvailable: false } });
const btn = page.getByRole('button', { name: /Training starten/i });
await expect.element(btn).toBeDisabled();
await expect.element(page.getByText(/OCR-Dienst ist nicht erreichbar/i)).toBeInTheDocument();
});
it('does not show service-down warning when blocks are insufficient', async () => {
// tooFewBlocks hint takes priority over serviceDown hint
render(OcrTrainingCard, {
trainingInfo: { ...baseInfo, availableBlocks: 2, ocrServiceAvailable: false }
});
await expect.element(page.getByText(/Mindestens 5/i)).toBeInTheDocument();
// serviceDown text should NOT appear because tooFewBlocks branch hides it
const serviceMsg = document.querySelector('.text-orange-600');
expect(serviceMsg).toBeNull();
});
});
describe('OcrTrainingCard — enabled state', () => {
it('enables button when availableBlocks >= 5 and service is up', async () => {
render(OcrTrainingCard, { trainingInfo: baseInfo });
const btn = page.getByRole('button', { name: /Training starten/i });
await expect.element(btn).not.toBeDisabled();
});
it('shows block count info text', async () => {
render(OcrTrainingCard, {
trainingInfo: { ...baseInfo, availableBlocks: 7, totalOcrBlocks: 15 }
});
await expect.element(page.getByText(/7/)).toBeInTheDocument();
await expect.element(page.getByText(/von 15 OCR-Blöcken/i)).toBeInTheDocument();
});
});
describe('OcrTrainingCard — in-flight state', () => {
it('shows "…" while POST is in-flight', async () => {
let resolveFetch!: (v: unknown) => void;
const pendingFetch = new Promise((resolve) => {
resolveFetch = resolve;
});
vi.stubGlobal('fetch', vi.fn().mockReturnValue(pendingFetch));
render(OcrTrainingCard, { trainingInfo: baseInfo });
const btn = page.getByRole('button', { name: /Training starten/i });
await btn.click();
// While fetch is still pending the button label becomes "…"
await expect.element(page.getByRole('button', { name: '…' })).toBeInTheDocument();
// Cleanup: resolve the pending promise
resolveFetch({ ok: false });
});
});

View File

@@ -0,0 +1,76 @@
<script lang="ts">
interface Run {
id: string;
status: 'RUNNING' | 'DONE' | 'FAILED';
blockCount: number;
documentCount: number;
modelName: string;
errorMessage?: string;
triggeredBy?: string;
createdAt: string;
completedAt?: string;
}
interface Props {
runs: Run[];
}
let { runs }: Props = $props();
const dateFormatter = new Intl.DateTimeFormat('de-DE', {
day: 'numeric',
month: 'short',
year: 'numeric'
});
function formatDate(iso: string): string {
return dateFormatter.format(new Date(iso));
}
</script>
<table class="w-full text-sm">
<thead>
<tr class="border-b border-line text-xs font-bold tracking-widest text-ink-3 uppercase">
<th class="pb-2 text-left">Datum</th>
<th class="pb-2 text-left">Status</th>
<th class="pb-2 text-right">Blöcke</th>
<th class="hidden pb-2 text-right md:table-cell">Dokumente</th>
</tr>
</thead>
<tbody>
{#if runs.length === 0}
<tr>
<td colspan="4" class="py-4 text-center text-sm text-ink-2">
Noch keine Trainings-Läufe.
</td>
</tr>
{:else}
{#each runs as run (run.id)}
<tr class="border-b border-line/50 last:border-0">
<td class="py-2 text-ink-2">{formatDate(run.createdAt)}</td>
<td class="py-2">
{#if run.status === 'DONE'}
<span
class="inline-flex items-center gap-1 rounded-sm bg-green-100 px-1.5 py-0.5 text-xs font-medium text-green-700"
>✓ Fertig</span
>
{:else if run.status === 'FAILED'}
<span
class="inline-flex items-center gap-1 rounded-sm bg-red-100 px-1.5 py-0.5 text-xs font-medium text-red-700"
title={run.errorMessage}> Fehler</span
>
{:else}
<span
class="inline-flex items-center gap-1 rounded-sm bg-yellow-100 px-1.5 py-0.5 text-xs font-medium text-yellow-700"
><span class="h-1.5 w-1.5 animate-pulse rounded-full bg-yellow-500"
></span>Läuft…</span
>
{/if}
</td>
<td class="py-2 text-right text-ink-2">{run.blockCount}</td>
<td class="hidden py-2 text-right text-ink-2 md:table-cell">{run.documentCount}</td>
</tr>
{/each}
{/if}
</tbody>
</table>