feat(enrich): field reordering, required-fields progress bar, and no-PDF upload state #267

Merged
marcel merged 20 commits from feat/issue-261-enrich-field-reorder-progress-bar-upload into main 2026-04-18 23:36:33 +02:00
27 changed files with 1022 additions and 452 deletions

View File

@@ -129,11 +129,25 @@ public class DocumentController {
return ResponseEntity.noContent().build();
}
// --- QUICK UPLOAD ---
// --- ATTACH FILE ---
private static final Set<String> ALLOWED_CONTENT_TYPES = Set.of(
"application/pdf", "image/jpeg", "image/png", "image/tiff");
@PostMapping(value = "/{id}/file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@RequirePermission(Permission.WRITE_ALL)
public Document attachFile(
@PathVariable UUID id,
@RequestPart("file") MultipartFile file) {
String contentType = file.getContentType();
if (contentType == null || !ALLOWED_CONTENT_TYPES.contains(contentType)) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Unsupported file type: " + contentType);
}
return documentService.attachFile(id, file);
}
// --- QUICK UPLOAD ---
public record UploadError(String filename, String code) {}
public record QuickUploadResult(List<Document> created, List<Document> updated, List<UploadError> errors) {}

View File

@@ -286,6 +286,28 @@ public class DocumentService {
return documentRepository.save(doc);
}
@Transactional
public Document attachFile(UUID id, MultipartFile file) {
Document doc = documentRepository.findById(id)
.orElseThrow(() -> DomainException.notFound(ErrorCode.DOCUMENT_NOT_FOUND, "Document not found: " + id));
FileService.UploadResult upload;
try {
upload = fileService.uploadFile(file, file.getOriginalFilename());
} catch (IOException e) {
throw DomainException.internal(ErrorCode.FILE_UPLOAD_FAILED, "Failed to upload file: " + e.getMessage());
}
doc.setFilePath(upload.s3Key());
doc.setFileHash(upload.fileHash());
doc.setOriginalFilename(file.getOriginalFilename());
doc.setContentType(file.getContentType());
if (doc.getStatus() == DocumentStatus.PLACEHOLDER) {
doc.setStatus(DocumentStatus.UPLOADED);
}
Document saved = documentRepository.save(doc);
documentVersionService.recordVersion(saved);
return saved;
}
// 0. Zuletzt aktive Dokumente (sortiert nach updatedAt DESC)
public List<Document> getRecentActivity(int size) {
return documentRepository.findAll(

View File

@@ -4,6 +4,8 @@ import org.junit.jupiter.api.Test;
import org.raddatz.familienarchiv.dto.DocumentSearchResult;
import org.raddatz.familienarchiv.dto.DocumentVersionSummary;
import org.raddatz.familienarchiv.dto.IncompleteDocumentDTO;
import org.raddatz.familienarchiv.exception.DomainException;
import org.raddatz.familienarchiv.exception.ErrorCode;
import org.raddatz.familienarchiv.model.Document;
import org.raddatz.familienarchiv.model.DocumentStatus;
import org.raddatz.familienarchiv.model.DocumentVersion;
@@ -563,6 +565,63 @@ class DocumentControllerTest {
.andExpect(status().isBadRequest());
}
// ─── POST /api/documents/{id}/file ───────────────────────────────────────
@Test
@WithMockUser
void attachFile_returns403_whenMissingWritePermission() throws Exception {
org.springframework.mock.web.MockMultipartFile file =
new org.springframework.mock.web.MockMultipartFile("file", "brief.pdf", "application/pdf", new byte[]{1});
mockMvc.perform(multipart("/api/documents/" + UUID.randomUUID() + "/file").file(file))
.andExpect(status().isForbidden());
}
@Test
@WithMockUser(authorities = "WRITE_ALL")
void attachFile_returns200_withUpdatedDocument_whenHasWritePermission() throws Exception {
UUID id = UUID.randomUUID();
Document doc = Document.builder()
.id(id).title("Brief").originalFilename("brief.pdf")
.filePath("docs/brief.pdf").status(DocumentStatus.UPLOADED).build();
when(documentService.attachFile(eq(id), any())).thenReturn(doc);
org.springframework.mock.web.MockMultipartFile file =
new org.springframework.mock.web.MockMultipartFile("file", "brief.pdf", "application/pdf", new byte[]{1});
mockMvc.perform(multipart("/api/documents/" + id + "/file").file(file))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(id.toString()))
.andExpect(jsonPath("$.status").value("UPLOADED"));
}
@Test
@WithMockUser(authorities = "WRITE_ALL")
void attachFile_returns400_whenContentTypeIsNotWhitelisted() throws Exception {
org.springframework.mock.web.MockMultipartFile htmlFile =
new org.springframework.mock.web.MockMultipartFile(
"file", "evil.html", "text/html", "<script>alert(1)</script>".getBytes());
mockMvc.perform(multipart("/api/documents/" + UUID.randomUUID() + "/file").file(htmlFile))
.andExpect(status().isBadRequest());
}
@Test
@WithMockUser(authorities = "WRITE_ALL")
void attachFile_returns404_whenDocumentDoesNotExist() throws Exception {
UUID id = UUID.randomUUID();
when(documentService.attachFile(eq(id), any()))
.thenThrow(DomainException.notFound(
ErrorCode.DOCUMENT_NOT_FOUND,
"Document not found: " + id));
org.springframework.mock.web.MockMultipartFile file =
new org.springframework.mock.web.MockMultipartFile("file", "brief.pdf", "application/pdf", new byte[]{1});
mockMvc.perform(multipart("/api/documents/" + id + "/file").file(file))
.andExpect(status().isNotFound());
}
// ─── GET /api/documents/{id}/versions/{versionId} ────────────────────────
@Test

View File

@@ -1428,4 +1428,75 @@ class DocumentServiceTest {
new MatchOffset(10, 4) // "Welt"
);
}
// ─── attachFile ───────────────────────────────────────────────────────────
@Test
void attachFile_throwsNotFound_whenDocumentDoesNotExist() {
UUID id = UUID.randomUUID();
when(documentRepository.findById(id)).thenReturn(Optional.empty());
MockMultipartFile file = new MockMultipartFile("file", "brief.pdf", "application/pdf", new byte[]{1});
assertThatThrownBy(() -> documentService.attachFile(id, file))
.isInstanceOf(DomainException.class)
.hasMessageContaining(id.toString());
}
@Test
void attachFile_setsStatusToUploaded_whenDocumentIsPlaceholder() throws Exception {
UUID id = UUID.randomUUID();
Document placeholder = Document.builder().id(id).status(DocumentStatus.PLACEHOLDER).build();
when(documentRepository.findById(id)).thenReturn(Optional.of(placeholder));
when(fileService.uploadFile(any(), any())).thenReturn(new FileService.UploadResult("s3/key.pdf", "abc123"));
when(documentRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
MockMultipartFile file = new MockMultipartFile("file", "brief.pdf", "application/pdf", new byte[]{1});
Document result = documentService.attachFile(id, file);
assertThat(result.getStatus()).isEqualTo(DocumentStatus.UPLOADED);
}
@Test
void attachFile_doesNotChangeStatus_whenAlreadyUploaded() throws Exception {
UUID id = UUID.randomUUID();
Document uploaded = Document.builder().id(id).status(DocumentStatus.UPLOADED).build();
when(documentRepository.findById(id)).thenReturn(Optional.of(uploaded));
when(fileService.uploadFile(any(), any())).thenReturn(new FileService.UploadResult("s3/key.pdf", "abc123"));
when(documentRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
MockMultipartFile file = new MockMultipartFile("file", "brief.pdf", "application/pdf", new byte[]{1});
Document result = documentService.attachFile(id, file);
assertThat(result.getStatus()).isEqualTo(DocumentStatus.UPLOADED);
}
@Test
void attachFile_setsFilePathAndContentType_fromUploadResult() throws Exception {
UUID id = UUID.randomUUID();
Document doc = Document.builder().id(id).status(DocumentStatus.PLACEHOLDER).build();
when(documentRepository.findById(id)).thenReturn(Optional.of(doc));
when(fileService.uploadFile(any(), any()))
.thenReturn(new FileService.UploadResult("s3/brief.pdf", "deadbeef"));
when(documentRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
MockMultipartFile file = new MockMultipartFile("file", "brief.pdf", "application/pdf", new byte[]{1});
Document result = documentService.attachFile(id, file);
assertThat(result.getFilePath()).isEqualTo("s3/brief.pdf");
assertThat(result.getFileHash()).isEqualTo("deadbeef");
assertThat(result.getContentType()).isEqualTo("application/pdf");
assertThat(result.getOriginalFilename()).isEqualTo("brief.pdf");
}
@Test
void attachFile_throwsDomainException_whenFileUploadFails() throws Exception {
UUID id = UUID.randomUUID();
Document doc = Document.builder().id(id).status(DocumentStatus.PLACEHOLDER).build();
when(documentRepository.findById(id)).thenReturn(Optional.of(doc));
when(fileService.uploadFile(any(), any())).thenThrow(new java.io.IOException("storage unavailable"));
MockMultipartFile file = new MockMultipartFile("file", "brief.pdf", "application/pdf", new byte[]{1});
assertThatThrownBy(() -> documentService.attachFile(id, file))
.isInstanceOf(DomainException.class);
}
}

View File

@@ -11,6 +11,7 @@
"error_file_not_found": "Die Datei konnte im Speicher nicht gefunden werden.",
"error_file_upload_failed": "Die Datei konnte nicht hochgeladen werden.",
"error_unsupported_file_type": "Dieses Dateiformat wird nicht unterstützt.",
"error_file_too_large": "Die Datei ist zu groß (max. 50 MB).",
"error_user_not_found": "Der Benutzer wurde nicht gefunden.",
"error_import_already_running": "Ein Import läuft bereits. Bitte warten Sie, bis dieser abgeschlossen ist.",
"error_unauthorized": "Sie sind nicht angemeldet.",
@@ -52,6 +53,8 @@
"form_label_archive_location": "Aufbewahrungsort",
"form_placeholder_archive_location": "z.B. Schrank 3, Mappe B",
"form_helper_archive_location": "Wo befindet sich das Originaldokument?",
"label_optional": "Optional",
"label_required_fields": "Pflichtfelder",
"login_heading": "Anmelden",
"login_label_username": "Benutzername",
"login_label_password": "Passwort",

View File

@@ -11,6 +11,7 @@
"error_file_not_found": "The file could not be found in storage.",
"error_file_upload_failed": "The file could not be uploaded.",
"error_unsupported_file_type": "This file format is not supported.",
"error_file_too_large": "The file is too large (max. 50 MB).",
"error_user_not_found": "User not found.",
"error_import_already_running": "An import is already running. Please wait for it to finish.",
"error_unauthorized": "You are not logged in.",
@@ -52,6 +53,8 @@
"form_label_archive_location": "Storage location",
"form_placeholder_archive_location": "e.g. Cabinet 3, Folder B",
"form_helper_archive_location": "Where is the original document stored?",
"label_optional": "Optional",
"label_required_fields": "Required fields",
"login_heading": "Sign in",
"login_label_username": "Username",
"login_label_password": "Password",

View File

@@ -11,6 +11,7 @@
"error_file_not_found": "El archivo no pudo encontrarse en el almacenamiento.",
"error_file_upload_failed": "No se pudo subir el archivo.",
"error_unsupported_file_type": "Este formato de archivo no está admitido.",
"error_file_too_large": "El archivo es demasiado grande (máx. 50 MB).",
"error_user_not_found": "Usuario no encontrado.",
"error_import_already_running": "Ya hay una importación en curso. Por favor, espere a que finalice.",
"error_unauthorized": "No ha iniciado sesión.",
@@ -52,6 +53,8 @@
"form_label_archive_location": "Ubicación de almacenamiento",
"form_placeholder_archive_location": "p.ej. Armario 3, Carpeta B",
"form_helper_archive_location": "¿Dónde se encuentra el documento original?",
"label_optional": "Opcional",
"label_required_fields": "Campos obligatorios",
"login_heading": "Iniciar sesión",
"login_label_username": "Usuario",
"login_label_password": "Contraseña",

View File

@@ -15,6 +15,8 @@ interface Props {
placeholder?: string;
compact?: boolean;
large?: boolean;
autofocus?: boolean;
required?: boolean;
restrictToCorrespondentsOf?: string;
onchange?: (value: string) => void;
onfocused?: () => void;
@@ -29,6 +31,8 @@ let {
placeholder,
compact = false,
large = false,
autofocus = false,
required = false,
restrictToCorrespondentsOf,
onchange,
onfocused
@@ -112,7 +116,7 @@ function selectPerson(person: Person) {
class={compact
? 'block text-xs font-bold tracking-wide text-ink-3 uppercase'
: 'block text-sm font-medium text-ink-2'}
>{label}</label
>{label}{#if required}*{/if}</label
>
<input type="hidden" name={name} bind:value={value} />
@@ -121,6 +125,7 @@ function selectPerson(person: Person) {
type="text"
id="{name}-search"
autocomplete="off"
autofocus={autofocus}
bind:value={searchTerm}
oninput={handleInput}
onfocus={handleFocus}

View File

@@ -5,6 +5,7 @@ import { m } from '$lib/paraglide/messages.js';
let {
tags = $bindable<Tag[]>([]),
currentTitle = $bindable(''),
initialTitle = '',
initialDocumentLocation = '',
initialSummary = '',
@@ -13,6 +14,7 @@ let {
hideTitle = false
}: {
tags?: Tag[];
currentTitle?: string;
initialTitle?: string;
initialDocumentLocation?: string;
initialSummary?: string;
@@ -22,8 +24,8 @@ let {
} = $props();
let titleDirty = $state(false);
let titleOverride = $state(untrack(() => initialTitle));
let titleValue = $derived(titleDirty ? titleOverride : suggestedTitle || titleOverride);
currentTitle = untrack(() => initialTitle);
const titleValue = $derived(titleDirty ? currentTitle : suggestedTitle || currentTitle);
</script>
<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
@@ -33,7 +35,7 @@ let titleValue = $derived(titleDirty ? titleOverride : suggestedTitle || titleOv
<div class="space-y-5">
{#if !hideTitle}
<!-- Titel -->
<!-- Titel (required) -->
<div>
<label for="title" class="mb-1 block text-sm font-medium text-ink-2"
>{m.form_label_title()}{#if titleRequired}
@@ -45,7 +47,7 @@ let titleValue = $derived(titleDirty ? titleOverride : suggestedTitle || titleOv
name="title"
value={titleValue}
oninput={(e) => {
titleOverride = (e.target as HTMLInputElement).value;
currentTitle = (e.target as HTMLInputElement).value;
titleDirty = true;
}}
required={titleRequired}
@@ -54,7 +56,38 @@ let titleValue = $derived(titleDirty ? titleOverride : suggestedTitle || titleOv
</div>
{/if}
<!-- Aufbewahrungsort -->
<!-- Optional divider -->
<div class="my-3 flex items-center gap-2">
<div class="flex-1 border-t border-line"></div>
<span class="text-xs font-bold tracking-widest text-ink-3 uppercase"
>{m.label_optional()}</span
>
<div class="flex-1 border-t border-line"></div>
</div>
<!-- Schlagworte (optional) -->
<div>
<p class="mb-1 block text-sm font-medium text-ink-2">{m.form_label_tags()}</p>
<TagInput bind:tags={tags} />
<input type="hidden" name="tags" value={tags.map((t) => t.name).join(',')} />
</div>
<!-- Inhalt (optional) -->
<div>
<label for="summary" class="mb-1 block text-sm font-medium text-ink-2"
>{m.form_label_content()}</label
>
<textarea
id="summary"
name="summary"
rows="5"
placeholder={m.form_placeholder_content()}
class="block w-full rounded border border-line p-2 font-serif text-sm shadow-sm focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring"
>{initialSummary}</textarea
>
</div>
<!-- Aufbewahrungsort (optional) -->
<div>
<label for="documentLocation" class="mb-1 block text-sm font-medium text-ink-2"
>{m.form_label_archive_location()}</label
@@ -69,27 +102,5 @@ let titleValue = $derived(titleDirty ? titleOverride : suggestedTitle || titleOv
/>
<p class="mt-1 text-xs text-ink-3">{m.form_helper_archive_location()}</p>
</div>
<!-- Schlagworte -->
<div>
<p class="mb-1 block text-sm font-medium text-ink-2">{m.form_label_tags()}</p>
<TagInput bind:tags={tags} />
<input type="hidden" name="tags" value={tags.map((t) => t.name).join(',')} />
</div>
<!-- Inhalt -->
<div>
<label for="summary" class="mb-1 block text-sm font-medium text-ink-2"
>{m.form_label_content()}</label
>
<textarea
id="summary"
name="summary"
rows="5"
placeholder={m.form_placeholder_content()}
class="block w-full rounded border border-line p-2 font-serif text-sm shadow-sm focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring"
>{initialSummary}</textarea
>
</div>
</div>
</div>

View File

@@ -0,0 +1,222 @@
<script lang="ts">
import { enhance } from '$app/forms';
import { invalidate } from '$app/navigation';
import { onMount, onDestroy, untrack } from 'svelte';
import type { Snippet } from 'svelte';
import { createFileLoader } from '$lib/hooks/useFileLoader.svelte';
import { m } from '$lib/paraglide/messages.js';
import { countRequiredFilled } from '$lib/utils/requiredFields';
import { validateFile } from '$lib/utils/validateFile';
import DocumentViewer from '$lib/components/DocumentViewer.svelte';
import UploadZone from '$lib/components/document/UploadZone.svelte';
import WhoWhenSection from '$lib/components/document/WhoWhenSection.svelte';
import DescriptionSection from '$lib/components/document/DescriptionSection.svelte';
import type { Tag } from '$lib/components/TagInput.svelte';
import type { components } from '$lib/generated/api';
type Person = components['schemas']['Person'];
type Doc = components['schemas']['Document'];
let {
doc,
formId,
formAction,
formError = null,
tags = $bindable<Tag[]>([]),
senderId = $bindable(''),
selectedReceivers = $bindable<Person[]>([]),
dateIso = $bindable(''),
currentTitle = $bindable(''),
topbar,
actionbar
}: {
doc: Doc;
formId: string;
formAction: string;
formError?: string | null;
tags?: Tag[];
senderId?: string;
selectedReceivers?: Person[];
dateIso?: string;
currentTitle?: string;
topbar: Snippet;
actionbar: Snippet;
} = $props();
tags = untrack(() => (doc.tags as Tag[]) ?? []);
senderId = untrack(() => doc.sender?.id ?? '');
selectedReceivers = untrack(() => (doc.receivers as Person[]) ?? []);
dateIso = untrack(() => doc.documentDate ?? '');
currentTitle = untrack(() => doc.title ?? '');
const fileLoader = createFileLoader();
let navHeight = $state(0);
onMount(() => {
navHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 0;
});
let activeAnnotationId = $state<string | null>(null);
$effect(() => {
if (doc?.id && doc?.filePath) {
fileLoader.loadFile(`/api/documents/${doc.id}/file`);
}
});
onDestroy(() => fileLoader.destroy());
const requiredFilled = $derived(countRequiredFilled(currentTitle, dateIso, senderId));
const requiredPct = $derived((requiredFilled / 3) * 100);
let isUploading = $state(false);
let isDragging = $state(false);
let uploadError = $state<string | null>(null);
let abortController = $state<AbortController | null>(null);
async function handleFile(file: File) {
uploadError = null;
isUploading = true;
const controller = new AbortController();
abortController = controller;
try {
const formData = new FormData();
formData.append('file', file);
const res = await fetch(`/api/documents/${doc.id}/file`, {
method: 'POST',
body: formData,
signal: controller.signal
});
if (!res.ok) throw new Error('Upload fehlgeschlagen');
await invalidate('app:document');
} catch (e) {
if ((e as Error).name === 'AbortError') return;
uploadError = m.error_file_upload_failed();
} finally {
isUploading = false;
abortController = null;
}
}
function cancelUpload() {
abortController?.abort();
isUploading = false;
}
async function handleReplaceFile(e: Event) {
const file = (e.currentTarget as HTMLInputElement).files?.[0];
if (!file) return;
const validationError = validateFile(file);
if (validationError === 'type') {
uploadError = m.error_unsupported_file_type();
return;
}
if (validationError === 'size') {
uploadError = m.error_file_too_large();
return;
}
await handleFile(file);
}
</script>
<div class="fixed inset-x-0 bottom-0 flex flex-col" style="top: {navHeight}px">
<!-- Top bar — caller-supplied via snippet -->
<div class="flex items-center justify-between border-b border-line bg-surface px-6 py-3">
{@render topbar()}
</div>
<!-- Required-fields progress bar -->
<div class="flex items-center gap-3 border-b border-line bg-surface px-6 py-1.5">
<span class="text-xs font-bold tracking-widest text-ink-3 uppercase"
>{m.label_required_fields()}</span
>
<div
class="h-0.5 flex-1 rounded-full bg-line"
role="progressbar"
aria-valuenow={requiredFilled}
aria-valuemin={0}
aria-valuemax={3}
aria-label={m.label_required_fields()}
>
<div
class="h-full rounded-full bg-brand-navy transition-all duration-300"
style="width:{requiredPct}%"
></div>
</div>
<span class="text-xs font-bold text-brand-navy">{requiredFilled} / 3</span>
</div>
<!-- Main content -->
<div class="flex flex-1 overflow-hidden">
<!-- Left: PDF preview / upload zone (60%) -->
<div class="relative flex flex-[6] flex-col overflow-hidden border-r border-line">
{#if !doc.filePath}
<UploadZone
filename={doc.originalFilename ?? ''}
isUploading={isUploading}
bind:isDragging={isDragging}
error={uploadError}
onFile={handleFile}
onCancel={cancelUpload}
/>
{:else}
<!-- Datei ersetzen toolbar -->
<div class="flex shrink-0 items-center border-b border-line bg-surface px-4 py-1.5">
<label
class="ml-auto flex min-h-[44px] cursor-pointer items-center text-xs font-bold tracking-widest text-ink-3 uppercase transition-colors hover:text-ink"
>
{m.doc_file_replace_label()}
<input type="file" class="sr-only" onchange={handleReplaceFile} />
</label>
</div>
<div class="relative flex-1 overflow-hidden">
<DocumentViewer
doc={doc}
fileUrl={fileLoader.fileUrl}
isLoading={fileLoader.isLoading}
error={fileLoader.fileError}
bind:activeAnnotationId={activeAnnotationId}
onAnnotationClick={() => {}}
/>
</div>
{/if}
</div>
<!-- Right: form (40%) -->
<div class="flex flex-[4] flex-col overflow-hidden">
{#if formError}
<div class="border-b border-red-200 bg-red-50 px-6 py-3 text-sm text-red-700">
{formError}
</div>
{/if}
<form
id={formId}
method="POST"
action={formAction}
enctype="multipart/form-data"
use:enhance
class="flex-1 space-y-5 overflow-y-auto p-6"
>
<WhoWhenSection
bind:senderId={senderId}
bind:selectedReceivers={selectedReceivers}
bind:dateIso={dateIso}
initialDateIso={doc.documentDate ?? ''}
initialLocation={doc.location ?? ''}
initialSenderName={doc.sender?.displayName ?? ''}
/>
<DescriptionSection
bind:tags={tags}
bind:currentTitle={currentTitle}
initialTitle={doc.title ?? ''}
initialDocumentLocation={doc.documentLocation ?? ''}
initialSummary={doc.summary ?? ''}
titleRequired={true}
/>
</form>
<!-- Action bar — caller-supplied via snippet -->
<div class="flex items-center justify-between gap-3 border-t border-line bg-surface p-4">
{@render actionbar()}
</div>
</div>
</div>
</div>

View File

@@ -0,0 +1,115 @@
<script lang="ts">
const ALLOWED_TYPES = new Set(['application/pdf', 'image/jpeg', 'image/png', 'image/tiff']);
const MAX_SIZE_BYTES = 50 * 1024 * 1024;
let {
filename,
isUploading,
isDragging = $bindable(false),
error,
onFile,
onCancel
}: {
filename: string;
isUploading: boolean;
isDragging?: boolean;
error: string | null;
onFile?: (file: File) => void;
onCancel?: () => void;
} = $props();
let validationError = $state<string | null>(null);
const displayError = $derived(error ?? validationError);
function handleFile(file: File | undefined) {
if (!file) return;
validationError = null;
if (!ALLOWED_TYPES.has(file.type)) {
validationError = 'Dieser Dateityp wird nicht unterstützt (PDF, JPG, PNG, TIFF).';
return;
}
if (file.size > MAX_SIZE_BYTES) {
validationError = 'Die Datei ist zu groß (max. 50 MB).';
return;
}
onFile?.(file);
}
function handleChange(e: Event) {
const input = e.currentTarget as HTMLInputElement;
handleFile(input.files?.[0]);
}
function handleDrop(e: DragEvent) {
e.preventDefault();
isDragging = false;
handleFile(e.dataTransfer?.files[0]);
}
</script>
<div
class="flex flex-1 items-center justify-center bg-pdf-bg"
aria-live="polite"
aria-label={isUploading ? 'Datei wird hochgeladen' : 'Dateiupload-Bereich'}
>
{#if isUploading}
<div role="status" class="flex flex-col items-center gap-3 text-center">
<div class="h-0.5 w-48 overflow-hidden rounded-full bg-white/10">
<div
class="h-full bg-brand-mint/70 motion-safe:animate-[slide_1.4s_ease-in-out_infinite]"
></div>
</div>
<p class="max-w-[200px] truncate text-xs font-medium text-brand-mint/70">{filename}</p>
<p class="text-xs text-white/40">Wird hochgeladen …</p>
<button
class="min-h-[44px] px-3 text-xs text-white/40 transition-colors hover:text-white/60"
onclick={onCancel}
>
Abbrechen
</button>
</div>
{:else}
<div
role="region"
aria-label="Datei ablegen"
class="flex flex-col items-center gap-3 rounded-sm border border-dashed p-8 text-center transition-colors
{isDragging ? 'border-brand-mint bg-brand-mint/5' : 'border-white/20'}"
ondragover={(e) => {
e.preventDefault();
isDragging = true;
}}
ondragleave={() => (isDragging = false)}
ondrop={handleDrop}
>
<div
class="upload-zone-icon flex h-8 w-8 items-center justify-center rounded-full bg-white/10 text-white/40"
>
<svg
width="16"
height="16"
viewBox="0 0 32 32"
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
>
<polygon
fill="currentColor"
points="6 12.5 16 2 26 12.5 24.5714286 14 16.999 6.049 17 30 15 30 14.999 6.051 7.42857143 14"
/>
</svg>
</div>
<p class="max-w-[200px] truncate text-xs font-medium text-white/50">{filename}</p>
<p class="text-xs text-white/30">Noch keine Datei hochgeladen</p>
{#if displayError}
<p class="text-xs text-red-400">{displayError}</p>
{/if}
<label
class="flex min-h-[44px] cursor-pointer items-center rounded-sm bg-brand-navy px-4 py-1.5 text-xs font-bold tracking-widest text-white/90 uppercase"
aria-label="Datei auswählen"
>
Datei auswählen
<input type="file" class="sr-only" onchange={handleChange} />
</label>
<p class="text-xs text-white/20">oder Datei hier ablegen</p>
</div>
{/if}
</div>

View File

@@ -0,0 +1,25 @@
import { describe, it, expect, afterEach } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';
import UploadZone from './UploadZone.svelte';
afterEach(cleanup);
describe('UploadZone', () => {
it('renders an SVG arrow icon (not a Unicode character) in idle state', async () => {
const { container } = render(UploadZone, {
filename: 'test.pdf',
isUploading: false,
error: null
});
// The icon must be an SVG element, not the raw "↑" text
const svg = container.querySelector('.upload-zone-icon svg');
expect(svg).not.toBeNull();
expect(container.textContent).not.toContain('↑');
});
it('shows the filename in idle state', async () => {
render(UploadZone, { filename: 'my-document.pdf', isUploading: false, error: null });
await expect.element(page.getByText('my-document.pdf')).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,115 @@
import { describe, it, expect, vi } from 'vitest';
import { render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';
import UploadZone from './UploadZone.svelte';
describe('UploadZone', () => {
describe('idle state', () => {
it('shows the filename in the upload zone', async () => {
render(UploadZone, {
props: { filename: 'brief_1920.pdf', isUploading: false, isDragging: false, error: null }
});
await expect.element(page.getByText('brief_1920.pdf')).toBeVisible();
});
it('shows "Datei auswählen" button', async () => {
render(UploadZone, {
props: { filename: 'scan.pdf', isUploading: false, isDragging: false, error: null }
});
await expect.element(page.getByText('Datei auswählen')).toBeVisible();
});
it('does not show the uploading animation', async () => {
render(UploadZone, {
props: { filename: 'scan.pdf', isUploading: false, isDragging: false, error: null }
});
expect(document.querySelector('[role="status"]')).toBeNull();
});
});
describe('uploading state', () => {
it('shows the uploading progress region', async () => {
render(UploadZone, {
props: { filename: 'scan.pdf', isUploading: true, isDragging: false, error: null }
});
await expect.element(page.getByRole('status')).toBeVisible();
});
it('shows Abbrechen button during upload', async () => {
render(UploadZone, {
props: { filename: 'scan.pdf', isUploading: true, isDragging: false, error: null }
});
await expect.element(page.getByText('Abbrechen')).toBeVisible();
});
it('calls onCancel when Abbrechen is clicked', async () => {
const onCancel = vi.fn();
render(UploadZone, {
props: { filename: 'scan.pdf', isUploading: true, isDragging: false, error: null, onCancel }
});
// Click the button inside [role="status"] — more specific than querySelector('button')
const btn = document.querySelector('[role="status"] button') as HTMLButtonElement;
btn.dispatchEvent(new MouseEvent('click', { bubbles: true }));
expect(onCancel).toHaveBeenCalledOnce();
});
});
describe('error state', () => {
it('shows the error message', async () => {
render(UploadZone, {
props: {
filename: 'scan.pdf',
isUploading: false,
isDragging: false,
error: 'Dateityp nicht unterstützt'
}
});
await expect.element(page.getByText('Dateityp nicht unterstützt')).toBeVisible();
});
});
describe('file selection', () => {
it('calls onFile for a valid PDF', () => {
const onFile = vi.fn();
render(UploadZone, {
props: { filename: 'scan.pdf', isUploading: false, isDragging: false, error: null, onFile }
});
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
const pdf = new File(['%PDF-1.4'], 'brief.pdf', { type: 'application/pdf' });
Object.defineProperty(input, 'files', { value: [pdf], writable: false });
input.dispatchEvent(new Event('change', { bubbles: true }));
expect(onFile).toHaveBeenCalledWith(pdf);
});
it('does not call onFile for an unsupported MIME type', async () => {
const onFile = vi.fn();
render(UploadZone, {
props: { filename: 'scan.pdf', isUploading: false, isDragging: false, error: null, onFile }
});
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
const docxFile = new File(['x'], 'test.docx', {
type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
});
Object.defineProperty(input, 'files', { value: [docxFile], writable: false });
input.dispatchEvent(new Event('change', { bubbles: true }));
expect(onFile).not.toHaveBeenCalled();
await expect
.element(page.getByText('Dieser Dateityp wird nicht unterstützt (PDF, JPG, PNG, TIFF).'))
.toBeVisible();
});
it('does not call onFile when file exceeds 50 MB', async () => {
const onFile = vi.fn();
render(UploadZone, {
props: { filename: 'scan.pdf', isUploading: false, isDragging: false, error: null, onFile }
});
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
const bigFile = new File(['x'.repeat(1)], 'huge.pdf', { type: 'application/pdf' });
Object.defineProperty(bigFile, 'size', { value: 51 * 1024 * 1024 });
Object.defineProperty(input, 'files', { value: [bigFile], writable: false });
input.dispatchEvent(new Event('change', { bubbles: true }));
expect(onFile).not.toHaveBeenCalled();
await expect.element(page.getByText('Die Datei ist zu groß (max. 50 MB).')).toBeVisible();
});
});
});

View File

@@ -4,16 +4,14 @@ import PersonTypeahead from '$lib/components/PersonTypeahead.svelte';
import PersonMultiSelect from '$lib/components/PersonMultiSelect.svelte';
import { isoToGerman, handleGermanDateInput } from '$lib/utils/date';
import { m } from '$lib/paraglide/messages.js';
import type { components } from '$lib/generated/api';
interface Person {
id: string;
firstName: string;
lastName: string;
}
type Person = components['schemas']['Person'];
let {
senderId = $bindable(''),
selectedReceivers = $bindable<Person[]>([]),
dateIso = $bindable(''),
initialDateIso = '',
initialLocation = '',
initialSenderName = '',
@@ -22,6 +20,7 @@ let {
}: {
senderId?: string;
selectedReceivers?: Person[];
dateIso?: string;
initialDateIso?: string;
initialLocation?: string;
initialSenderName?: string;
@@ -30,7 +29,7 @@ let {
} = $props();
let dateDisplay = $state(untrack(() => isoToGerman(initialDateIso)));
let dateIso = $state(untrack(() => initialDateIso));
dateIso = untrack(() => initialDateIso);
let dateDirty = $state(false);
const dateInvalid = $derived(dateDirty && dateDisplay.length > 0 && dateIso === '');
@@ -57,10 +56,10 @@ $effect(() => {
</h2>
<div class="grid grid-cols-1 gap-5 md:grid-cols-2">
<!-- Datum -->
<!-- Datum (required — row 1, col 1) -->
<div>
<label for="documentDate" class="mb-1 block text-sm font-medium text-ink-2"
>{m.form_label_date()}</label
>{m.form_label_date()}*</label
>
<input
id="documentDate"
@@ -70,6 +69,7 @@ $effect(() => {
oninput={handleDateInput}
placeholder={m.form_placeholder_date()}
maxlength="10"
autofocus={!initialDateIso}
class="block w-full rounded border border-line p-2 text-sm shadow-sm
{dateInvalid ? 'border-red-400 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-500' : 'focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring'}"
aria-describedby={dateInvalid ? 'date-error' : undefined}
@@ -80,7 +80,26 @@ $effect(() => {
{/if}
</div>
<!-- Ort -->
<!-- Absender (required — row 1, col 2) -->
<div>
<PersonTypeahead
name="senderId"
label={m.form_label_sender()}
required={true}
bind:value={senderId}
initialName={initialSenderName}
suggestedName={suggestedSenderName}
autofocus={!!initialDateIso}
/>
</div>
<!-- Empfänger (optional — row 2, col 1) -->
<div>
<p class="mb-1 block text-sm font-medium text-ink-2">{m.form_label_receivers()}</p>
<PersonMultiSelect bind:selectedPersons={selectedReceivers} />
</div>
<!-- Ort (optional — row 2, col 2) -->
<div>
<label for="location" class="mb-1 block text-sm font-medium text-ink-2"
>{m.form_label_location()}</label
@@ -94,22 +113,5 @@ $effect(() => {
class="block w-full rounded border border-line p-2 text-sm shadow-sm focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring"
/>
</div>
<!-- Absender -->
<div>
<PersonTypeahead
name="senderId"
label={m.form_label_sender()}
bind:value={senderId}
initialName={initialSenderName}
suggestedName={suggestedSenderName}
/>
</div>
<!-- Empfänger -->
<div>
<p class="mb-1 block text-sm font-medium text-ink-2">{m.form_label_receivers()}</p>
<PersonMultiSelect bind:selectedPersons={selectedReceivers} />
</div>
</div>
</div>

View File

@@ -0,0 +1,36 @@
import { describe, it, expect } from 'vitest';
import { countRequiredFilled } from './requiredFields';
describe('countRequiredFilled', () => {
it('returns 0 when all three fields are empty', () => {
expect(countRequiredFilled('', '', '')).toBe(0);
});
it('returns 1 when only title is set', () => {
expect(countRequiredFilled('Ein Brief', '', '')).toBe(1);
});
it('returns 1 when only dateIso is set', () => {
expect(countRequiredFilled('', '1920-05-01', '')).toBe(1);
});
it('returns 1 when only senderId is set', () => {
expect(countRequiredFilled('', '', 'person-uuid')).toBe(1);
});
it('returns 2 when title and dateIso are set', () => {
expect(countRequiredFilled('Ein Brief', '1920-05-01', '')).toBe(2);
});
it('returns 2 when title and senderId are set', () => {
expect(countRequiredFilled('Ein Brief', '', 'person-uuid')).toBe(2);
});
it('returns 2 when dateIso and senderId are set', () => {
expect(countRequiredFilled('', '1920-05-01', 'person-uuid')).toBe(2);
});
it('returns 3 when all three fields are set', () => {
expect(countRequiredFilled('Ein Brief', '1920-05-01', 'person-uuid')).toBe(3);
});
});

View File

@@ -0,0 +1,3 @@
export function countRequiredFilled(title: string, dateIso: string, senderId: string): number {
return [title, dateIso, senderId].filter(Boolean).length;
}

View File

@@ -0,0 +1,36 @@
import { describe, it, expect } from 'vitest';
import { validateFile, MAX_SIZE_BYTES } from './validateFile';
function makeFile(type: string, size: number): File {
return new File(['x'.repeat(Math.min(size, 100))], 'test.file', { type });
}
describe('validateFile', () => {
it('returns null for a valid PDF under 50 MB', () => {
const file = makeFile('application/pdf', 1024);
expect(validateFile(file)).toBeNull();
});
it('returns null for a valid JPEG', () => {
expect(validateFile(makeFile('image/jpeg', 1024))).toBeNull();
});
it('returns null for a valid PNG', () => {
expect(validateFile(makeFile('image/png', 1024))).toBeNull();
});
it('returns null for a valid TIFF', () => {
expect(validateFile(makeFile('image/tiff', 1024))).toBeNull();
});
it('returns "type" for an unsupported MIME type', () => {
const file = makeFile('text/plain', 100);
expect(validateFile(file)).toBe('type');
});
it('returns "size" for a file exceeding 50 MB', () => {
const oversized = new File(['x'], 'big.pdf', { type: 'application/pdf' });
Object.defineProperty(oversized, 'size', { value: MAX_SIZE_BYTES + 1 });
expect(validateFile(oversized)).toBe('size');
});
});

View File

@@ -0,0 +1,10 @@
export const ALLOWED_TYPES = new Set(['application/pdf', 'image/jpeg', 'image/png', 'image/tiff']);
export const MAX_SIZE_BYTES = 50 * 1024 * 1024;
export type FileValidationError = 'type' | 'size';
export function validateFile(file: File): FileValidationError | null {
if (!ALLOWED_TYPES.has(file.type)) return 'type';
if (file.size > MAX_SIZE_BYTES) return 'size';
return null;
}

View File

@@ -6,12 +6,15 @@ import { parseBackendError, getErrorMessage } from '$lib/errors';
export async function load({
params,
fetch,
locals
locals,
depends
}: {
params: { id: string };
fetch: typeof globalThis.fetch;
locals: App.Locals;
depends: (dep: string) => void;
}) {
depends('app:document');
const canWrite =
locals.user?.groups?.some((g: { permissions: string[] }) =>
g.permissions.includes('WRITE_ALL')

View File

@@ -1,27 +1,34 @@
<script lang="ts">
import { enhance } from '$app/forms';
import { untrack } from 'svelte';
import { m } from '$lib/paraglide/messages.js';
import WhoWhenSection from '$lib/components/document/WhoWhenSection.svelte';
import DescriptionSection from '$lib/components/document/DescriptionSection.svelte';
import TranscriptionSection from '$lib/components/document/TranscriptionSection.svelte';
import FileSectionEdit from './FileSectionEdit.svelte';
import SaveBar from './SaveBar.svelte';
import { getConfirmService } from '$lib/services/confirm.svelte.js';
import DocumentEditLayout from '$lib/components/document/DocumentEditLayout.svelte';
let { data, form } = $props();
let { document: doc } = untrack(() => data);
let tags = $state(doc.tags ?? []);
let senderId = $state(doc.sender?.id ?? '');
let selectedReceivers = $state(doc.receivers ?? []);
const doc = $derived(data.document);
const { confirm } = getConfirmService();
async function handleDelete() {
const confirmed = await confirm({
title: m.doc_delete_confirm(),
destructive: true
});
if (confirmed) {
(document.getElementById('delete-form') as HTMLFormElement | null)?.requestSubmit();
}
}
</script>
<div class="mx-auto max-w-4xl px-4 py-8">
<!-- Heading -->
<div class="mb-6">
<svelte:head>
<title>{doc.title || doc.originalFilename || 'Dokument'}{m.doc_edit_heading()}</title>
</svelte:head>
<DocumentEditLayout doc={doc} formId="update-form" formAction="?/update" formError={form?.error}>
{#snippet topbar()}
<a
href="/documents/{doc.id}"
class="group mb-4 inline-flex items-center text-xs font-bold tracking-widest text-ink-2 uppercase transition-colors hover:text-ink"
class="group inline-flex items-center font-sans text-xs font-bold tracking-widest text-ink-2 uppercase transition-colors hover:text-ink"
>
<img
src="/degruyter-icons/Simple/Medium-24px/SVG/Action/Arrow/Arrow-Left-MD.svg"
@@ -31,43 +38,65 @@ let selectedReceivers = $state(doc.receivers ?? []);
/>
{m.btn_back_to_document()}
</a>
<h1 class="font-serif text-3xl text-ink">
{m.doc_edit_heading()}
<span class="text-ink/70">{doc.title || doc.originalFilename}</span>
</h1>
</div>
{#if form?.error}
<div class="mb-6 rounded border border-red-200 bg-red-50 p-4 text-red-700">{form.error}</div>
{/if}
<p class="max-w-sm truncate text-center font-serif text-sm font-medium text-ink">
{doc.title || doc.originalFilename}
</p>
<form
id="update-form"
method="POST"
action="?/update"
enctype="multipart/form-data"
use:enhance
class="space-y-6 pb-20"
>
<WhoWhenSection
bind:senderId={senderId}
bind:selectedReceivers={selectedReceivers}
initialDateIso={doc.documentDate ?? ''}
initialLocation={doc.location ?? ''}
initialSenderName={doc.sender ? doc.sender.displayName : ''}
/>
<DescriptionSection
bind:tags={tags}
initialTitle={doc.title ?? ''}
initialDocumentLocation={doc.documentLocation ?? ''}
initialSummary={doc.summary ?? ''}
titleRequired={true}
/>
<TranscriptionSection initialTranscription={doc.transcription ?? ''} />
<FileSectionEdit originalFilename={doc.originalFilename} />
<SaveBar docId={doc.id} />
</form>
<div class="w-40"></div>
{/snippet}
<form id="mark-for-review-form" method="POST" action="?/markForReview" use:enhance></form>
<form id="delete-form" method="POST" action="?/delete" use:enhance></form>
</div>
{#snippet actionbar()}
<button
type="button"
onclick={handleDelete}
class="flex items-center gap-1.5 rounded border border-red-300 px-4 py-1.5 font-sans text-xs font-bold text-red-600 transition-colors hover:border-red-600 hover:bg-red-50"
>
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-4 w-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<polyline points="3 6 5 6 21 6" />
<path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6" />
<path d="M10 11v6M14 11v6" />
<path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2" />
</svg>
{m.btn_delete()}
</button>
<div class="flex items-center gap-3">
<a
href="/documents/{doc.id}"
class="font-sans text-sm font-medium text-ink-2 transition-colors hover:text-ink"
>
{m.btn_cancel()}
</a>
<button
type="submit"
form="mark-for-review-form"
class="rounded-sm border border-gray-300 px-5 py-2 font-sans text-xs font-bold tracking-widest text-gray-600 uppercase transition-colors hover:bg-gray-50"
>
{m.btn_mark_for_review()}
</button>
<button
type="submit"
form="update-form"
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-colors hover:bg-primary/90"
>
{m.btn_save()}
</button>
</div>
{/snippet}
</DocumentEditLayout>
<form id="mark-for-review-form" method="POST" action="?/markForReview" use:enhance></form>
<form id="delete-form" method="POST" action="?/delete" use:enhance></form>

View File

@@ -1,62 +0,0 @@
<script lang="ts">
import { m } from '$lib/paraglide/messages.js';
let { originalFilename }: { originalFilename: string } = $props();
let selectedFilename = $state<string | null>(null);
function handleFileChange(e: Event) {
const file = (e.target as HTMLInputElement).files?.[0];
selectedFilename = file?.name ?? null;
}
</script>
<div class="rounded-sm border border-line bg-surface shadow-sm">
<div class="border-b border-line px-6 py-4">
<h2 class="text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.doc_section_file()}
</h2>
</div>
<!-- Current file -->
<div class="flex items-center gap-3 border-b border-line px-6 py-3 text-sm text-ink-2">
<img
src="/degruyter-icons/Simple/Medium-24px/SVG/Action/PDF-Document-MD.svg"
alt=""
aria-hidden="true"
class="h-4 w-4 flex-shrink-0"
/>
<span
>{m.doc_current_file_label()}
<strong class="font-medium text-ink">{originalFilename}</strong></span
>
</div>
<!-- Replace file upload zone -->
<label
for="file-upload"
class="flex cursor-pointer flex-col items-center gap-3 px-6 py-8 transition-colors hover:bg-muted/40"
>
<svg
class="h-8 w-8 text-ink-3"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="1.5"
d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"
/>
</svg>
{#if selectedFilename}
<span class="text-sm font-medium text-ink">{selectedFilename}</span>
{:else}
<span class="text-sm font-medium text-ink-2">{m.doc_file_replace_label()}</span>
<span class="text-xs text-ink-3">{m.doc_file_replace_note()}</span>
{/if}
</label>
<input id="file-upload" type="file" name="file" onchange={handleFileChange} class="sr-only" />
</div>

View File

@@ -1,76 +0,0 @@
<script lang="ts">
import { m } from '$lib/paraglide/messages.js';
import { getConfirmService } from '$lib/services/confirm.svelte.js';
let { docId }: { docId: string } = $props();
const { confirm } = getConfirmService();
async function handleDelete() {
const confirmed = await confirm({
title: m.doc_delete_confirm(),
destructive: true
});
if (confirmed) {
(document.getElementById('delete-form') as HTMLFormElement | null)?.requestSubmit();
}
}
</script>
<div
class="sticky bottom-0 z-10 -mx-4 border-t border-line bg-surface px-4 py-3 shadow-[0_-2px_8px_rgba(0,0,0,0.06)] sm:px-6 sm:py-4"
>
<!-- Desktop: delete left, cancel+buttons right -->
<!-- Mobile: action buttons stacked full-width, delete+cancel row at bottom -->
<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<!-- Primary actions first (top on mobile, right on desktop) -->
<div class="flex flex-col gap-2 sm:order-last sm:flex-row sm:items-center sm:gap-4">
<button
type="submit"
form="mark-for-review-form"
class="w-full rounded-sm border border-line px-4 py-2.5 font-sans text-xs font-bold tracking-widest text-ink-2 uppercase transition-colors hover:bg-muted sm:w-auto sm:py-2"
>
{m.btn_mark_for_review()}
</button>
<button
type="submit"
class="w-full rounded bg-primary px-6 py-2.5 font-sans text-sm font-bold tracking-widest text-primary-fg uppercase transition-colors hover:bg-primary/80 sm:w-auto sm:py-2"
>
{m.btn_save()}
</button>
</div>
<!-- Secondary: delete + cancel -->
<div class="flex items-center justify-between sm:justify-start sm:gap-4">
<button
type="button"
onclick={handleDelete}
class="flex items-center gap-1.5 rounded border border-red-300 px-4 py-1.5 text-sm font-bold text-red-600 transition-colors hover:border-red-600 hover:bg-red-50"
>
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-4 w-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<polyline points="3 6 5 6 21 6" />
<path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6" />
<path d="M10 11v6M14 11v6" />
<path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2" />
</svg>
{m.btn_delete()}
</button>
<a
href="/documents/{docId}"
class="text-sm font-medium text-ink-2 transition-colors hover:text-ink"
>
{m.btn_cancel()}
</a>
</div>
</div>
</div>

View File

@@ -1,92 +0,0 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';
import SaveBar from './SaveBar.svelte';
import { createConfirmService, CONFIRM_KEY } from '$lib/services/confirm.svelte.js';
let appendedForms: HTMLFormElement[] = [];
afterEach(() => {
cleanup();
appendedForms.forEach((f) => f.remove());
appendedForms = [];
});
function renderSaveBar(docId = 'doc-1') {
const service = createConfirmService();
// Mount a dummy delete form so SaveBar can find it via document.getElementById
const deleteForm = document.createElement('form');
deleteForm.id = 'delete-form';
document.body.appendChild(deleteForm);
appendedForms.push(deleteForm);
const result = render(SaveBar, {
props: { docId },
context: new Map([[CONFIRM_KEY, service]])
});
return { ...result, service, deleteForm };
}
// ─── Rendering ────────────────────────────────────────────────────────────────
describe('SaveBar — rendering', () => {
it('renders save button', async () => {
renderSaveBar();
await expect.element(page.getByRole('button', { name: /Speichern/i })).toBeInTheDocument();
});
it('renders delete button', async () => {
renderSaveBar();
// The delete button should be type="button" (async confirm flow)
const deleteBtn = document.querySelector('button[type="button"]');
expect(deleteBtn).not.toBeNull();
});
it('renders cancel link pointing to /documents/doc-1', async () => {
renderSaveBar();
await expect
.element(page.getByRole('link', { name: /Abbrechen/i }))
.toHaveAttribute('href', '/documents/doc-1');
});
});
// ─── Delete confirmation ──────────────────────────────────────────────────────
describe('SaveBar — delete confirmation', () => {
it('opens confirm dialog when delete button is clicked', async () => {
const { service } = renderSaveBar();
const deleteBtn = document.querySelectorAll<HTMLButtonElement>('button[type="button"]')[0];
deleteBtn.click();
await vi.waitFor(() => expect(service.options).not.toBeNull());
expect(service.options?.destructive).toBe(true);
service.settle(false);
});
it('submits delete form when user confirms', async () => {
const { service, deleteForm } = renderSaveBar();
const requestSubmit = vi.spyOn(deleteForm, 'requestSubmit').mockImplementation(() => {});
const deleteBtn = document.querySelectorAll<HTMLButtonElement>('button[type="button"]')[0];
deleteBtn.click();
await vi.waitFor(() => expect(service.options).not.toBeNull());
service.settle(true);
await vi.waitFor(() => expect(service.options).toBeNull());
expect(requestSubmit).toHaveBeenCalledOnce();
});
it('does not submit delete form when user cancels', async () => {
const { service, deleteForm } = renderSaveBar();
const requestSubmit = vi.spyOn(deleteForm, 'requestSubmit').mockImplementation(() => {});
const deleteBtn = document.querySelectorAll<HTMLButtonElement>('button[type="button"]')[0];
deleteBtn.click();
await vi.waitFor(() => expect(service.options).not.toBeNull());
service.settle(false);
await vi.waitFor(() => expect(service.options).toBeNull());
expect(requestSubmit).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,82 @@
import { vi, describe, it, expect, afterEach } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';
import { createConfirmService, CONFIRM_KEY } from '$lib/services/confirm.svelte.js';
import EditPage from './+page.svelte';
afterEach(cleanup);
function makeDocument(overrides: Record<string, unknown> = {}) {
return {
id: 'doc-1',
title: 'Test Document',
originalFilename: 'test.pdf',
status: 'UPLOADED' as const,
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T00:00:00Z',
metadataComplete: false,
scriptType: 'UNKNOWN' as const,
// No filePath — avoids triggering the file loader fetch in tests
...overrides
};
}
describe('Edit page — delete button', () => {
it('renders the delete button', async () => {
const service = createConfirmService();
render(EditPage, {
props: { data: { document: makeDocument() }, form: null },
context: new Map([[CONFIRM_KEY, service]])
});
await expect.element(page.getByRole('button', { name: /löschen/i })).toBeInTheDocument();
});
it('opens a confirm dialog when the delete button is clicked', async () => {
const service = createConfirmService();
render(EditPage, {
props: { data: { document: makeDocument() }, form: null },
context: new Map([[CONFIRM_KEY, service]])
});
await page.getByRole('button', { name: /löschen/i }).click();
// The confirm service should have received an options object (dialog is open)
expect(service.options).not.toBeNull();
expect(service.options?.destructive).toBe(true);
service.settle(false);
});
it('submits the delete form when the user confirms', async () => {
const service = createConfirmService();
render(EditPage, {
props: { data: { document: makeDocument() }, form: null },
context: new Map([[CONFIRM_KEY, service]])
});
const deleteForm = document.getElementById('delete-form') as HTMLFormElement;
const submitSpy = vi.spyOn(deleteForm, 'requestSubmit').mockImplementation(() => {});
await page.getByRole('button', { name: /löschen/i }).click();
// confirm() has been called synchronously — settle and flush the microtask queue
service.settle(true);
await Promise.resolve();
expect(submitSpy).toHaveBeenCalledOnce();
});
it('does NOT submit the delete form when the user cancels', async () => {
const service = createConfirmService();
render(EditPage, {
props: { data: { document: makeDocument() }, form: null },
context: new Map([[CONFIRM_KEY, service]])
});
const deleteForm = document.getElementById('delete-form') as HTMLFormElement;
const submitSpy = vi.spyOn(deleteForm, 'requestSubmit').mockImplementation(() => {});
await page.getByRole('button', { name: /löschen/i }).click();
service.settle(false);
await Promise.resolve();
expect(submitSpy).not.toHaveBeenCalled();
});
});

View File

@@ -6,11 +6,13 @@ import { getErrorMessage, parseBackendError } from '$lib/errors';
export async function load({
params,
fetch,
locals
locals,
depends
}: {
params: { id: string };
fetch: typeof globalThis.fetch;
locals: App.Locals;
depends: (dep: string) => void;
}) {
const canWrite =
locals.user?.groups?.some((g: { permissions: string[] }) =>
@@ -18,6 +20,8 @@ export async function load({
) ?? false;
if (!canWrite) throw redirect(303, '/');
depends('app:document');
const { id } = params;
const api = createApiClient(fetch);

View File

@@ -1,50 +1,19 @@
<script lang="ts">
import { enhance } from '$app/forms';
import { onMount, onDestroy, untrack } from 'svelte';
import { createFileLoader } from '$lib/hooks/useFileLoader.svelte';
import { m } from '$lib/paraglide/messages.js';
import DocumentViewer from '$lib/components/DocumentViewer.svelte';
import WhoWhenSection from '$lib/components/document/WhoWhenSection.svelte';
import DescriptionSection from '$lib/components/document/DescriptionSection.svelte';
import DocumentEditLayout from '$lib/components/document/DocumentEditLayout.svelte';
let { data, form } = $props();
const doc = $derived(data.document);
// File preview state
const fileLoader = createFileLoader();
let navHeight = $state(0);
onMount(() => {
navHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 0;
});
// Dummy bindable state required by DocumentViewer
let annotateMode = $state(false);
let activeAnnotationId = $state<string | null>(null);
let activeAnnotationPage = $state<number | null>(null);
$effect(() => {
if (doc?.id && doc?.filePath) {
fileLoader.loadFile(`/api/documents/${doc.id}/file`);
}
});
onDestroy(() => fileLoader.destroy());
// Form state
let tags = $state(untrack(() => doc.tags ?? []));
let senderId = $state(untrack(() => doc.sender?.id ?? ''));
let selectedReceivers = $state(untrack(() => doc.receivers ?? []));
</script>
<svelte:head>
<title>{doc.title || doc.originalFilename || 'Dokument'} — Anreicherung</title>
</svelte:head>
<div class="fixed inset-x-0 bottom-0 flex flex-col" style="top: {navHeight}px">
<!-- Top bar -->
<div class="flex items-center justify-between border-b border-line bg-surface px-6 py-3">
<DocumentEditLayout doc={doc} formId="save-form" formAction="?/save" formError={form?.error}>
{#snippet topbar()}
<a
href="/enrich"
class="group inline-flex items-center font-sans text-xs font-bold tracking-widest text-ink-2 uppercase transition-colors hover:text-ink"
@@ -65,88 +34,37 @@ let selectedReceivers = $state(untrack(() => doc.receivers ?? []));
<p class="font-sans text-xs text-ink-3">
{m.enrich_progress({ count: data.incompleteCount })}
</p>
</div>
{/snippet}
<!-- Main content -->
<div class="flex flex-1 overflow-hidden">
<!-- Left: PDF preview (60%) -->
<div class="relative flex-[6] overflow-hidden border-r border-line">
<DocumentViewer
doc={doc}
fileUrl={fileLoader.fileUrl}
isLoading={fileLoader.isLoading}
error={fileLoader.fileError}
bind:annotateMode={annotateMode}
bind:activeAnnotationId={activeAnnotationId}
bind:activeAnnotationPage={activeAnnotationPage}
onAnnotationClick={() => {}}
/>
</div>
{#snippet actionbar()}
<button
type="submit"
form="skip-form"
class="font-sans text-sm font-medium text-ink-2 transition-colors hover:text-ink"
>
{m.enrich_skip()}
</button>
<!-- Right: form (40%) -->
<div class="flex flex-[4] flex-col overflow-hidden">
{#if form?.error}
<div class="border-b border-red-200 bg-red-50 px-6 py-3 text-sm text-red-700">
{form.error}
</div>
{/if}
<form
id="save-form"
method="POST"
action="?/save"
enctype="multipart/form-data"
use:enhance
class="flex-1 space-y-5 overflow-y-auto p-6"
<div class="flex items-center gap-3">
<button
type="submit"
form="save-form"
formaction="?/save"
class="rounded-sm border border-gray-300 px-5 py-2 font-sans text-xs font-bold tracking-widest text-gray-600 uppercase transition-colors hover:bg-gray-50"
>
<WhoWhenSection
bind:senderId={senderId}
bind:selectedReceivers={selectedReceivers}
initialDateIso={doc.documentDate ?? ''}
initialLocation={doc.location ?? ''}
initialSenderName={doc.sender
? doc.sender.displayName
: ''}
/>
<DescriptionSection bind:tags={tags} initialTitle={doc.title ?? ''} titleRequired={true} />
</form>
{m.btn_save()}
</button>
<!-- Skip form (outside main form to avoid nesting) -->
<form id="skip-form" method="POST" action="?/skip" use:enhance></form>
<!-- Action bar -->
<div class="flex items-center justify-between gap-3 border-t border-line bg-surface p-4">
<!-- Skip button linked to skip-form -->
<button
type="submit"
form="skip-form"
class="font-sans text-sm font-medium text-ink-2 transition-colors hover:text-ink"
>
{m.enrich_skip()}
</button>
<div class="flex items-center gap-3">
<!-- Save -->
<button
type="submit"
form="save-form"
formaction="?/save"
class="rounded-sm border border-gray-300 px-5 py-2 font-sans text-xs font-bold tracking-widest text-gray-600 uppercase transition-colors hover:bg-gray-50"
>
{m.btn_save()}
</button>
<!-- Save & mark as reviewed -->
<button
type="submit"
form="save-form"
formaction="?/saveAndReview"
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-colors hover:bg-primary/90"
>
{m.btn_save_and_mark_reviewed()}
</button>
</div>
</div>
<button
type="submit"
form="save-form"
formaction="?/saveAndReview"
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-colors hover:bg-primary/90"
>
{m.btn_save_and_mark_reviewed()}
</button>
</div>
</div>
</div>
{/snippet}
</DocumentEditLayout>
<form id="skip-form" method="POST" action="?/skip" use:enhance></form>

View File

@@ -363,3 +363,12 @@
outline: 3px solid ButtonText;
}
}
@keyframes slide {
0% {
transform: translateX(-100%);
}
100% {
transform: translateX(350%);
}
}