diff --git a/backend/src/main/java/org/raddatz/familienarchiv/controller/DocumentController.java b/backend/src/main/java/org/raddatz/familienarchiv/controller/DocumentController.java index 8b17a0ef..ea943163 100644 --- a/backend/src/main/java/org/raddatz/familienarchiv/controller/DocumentController.java +++ b/backend/src/main/java/org/raddatz/familienarchiv/controller/DocumentController.java @@ -18,6 +18,7 @@ import jakarta.validation.constraints.Min; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.validation.annotation.Validated; +import org.raddatz.familienarchiv.dto.DocumentBatchMetadataDTO; import org.raddatz.familienarchiv.dto.DocumentSearchResult; import org.raddatz.familienarchiv.dto.DocumentUpdateDTO; import org.raddatz.familienarchiv.dto.TagOperator; @@ -193,6 +194,7 @@ public class DocumentController { @RequirePermission(Permission.WRITE_ALL) public QuickUploadResult quickUpload( @RequestPart(value = "files", required = false) List files, + @RequestPart(value = "metadata", required = false) DocumentBatchMetadataDTO metadata, Authentication authentication) { List created = new ArrayList<>(); List updated = new ArrayList<>(); @@ -202,14 +204,21 @@ public class DocumentController { return new QuickUploadResult(created, updated, errors); } + documentService.validateBatch(files.size(), metadata); + UUID actorId = requireUserId(authentication); - for (MultipartFile file : files) { + long totalBytes = files.stream().mapToLong(MultipartFile::getSize).sum(); + + for (int i = 0; i < files.size(); i++) { + MultipartFile file = files.get(i); if (!ALLOWED_CONTENT_TYPES.contains(file.getContentType())) { errors.add(new UploadError(file.getOriginalFilename(), "UNSUPPORTED_FILE_TYPE")); continue; } try { - DocumentService.StoreResult result = documentService.storeDocument(file, actorId); + DocumentService.StoreResult result = metadata != null + ? documentService.storeDocumentWithBatchMetadata(file, metadata, i, actorId) + : documentService.storeDocument(file, actorId); if (result.isNew()) { created.add(result.document()); } else { @@ -221,6 +230,10 @@ public class DocumentController { } } + log.info("quickUpload actor={} files={} totalBytes={} withMetadata={} created={} updated={} errors={}", + actorId, files.size(), totalBytes, metadata != null, + created.size(), updated.size(), errors.size()); + return new QuickUploadResult(created, updated, errors); } diff --git a/backend/src/main/java/org/raddatz/familienarchiv/dto/DocumentBatchMetadataDTO.java b/backend/src/main/java/org/raddatz/familienarchiv/dto/DocumentBatchMetadataDTO.java new file mode 100644 index 00000000..399105d9 --- /dev/null +++ b/backend/src/main/java/org/raddatz/familienarchiv/dto/DocumentBatchMetadataDTO.java @@ -0,0 +1,18 @@ +package org.raddatz.familienarchiv.dto; + +import lombok.Data; + +import java.time.LocalDate; +import java.util.List; +import java.util.UUID; + +@Data +public class DocumentBatchMetadataDTO { + private List titles; + private UUID senderId; + private List receiverIds; + private LocalDate documentDate; + private String location; + private List tagNames; + private Boolean metadataComplete; +} diff --git a/backend/src/main/java/org/raddatz/familienarchiv/exception/ErrorCode.java b/backend/src/main/java/org/raddatz/familienarchiv/exception/ErrorCode.java index 85cd7d2c..686c8627 100644 --- a/backend/src/main/java/org/raddatz/familienarchiv/exception/ErrorCode.java +++ b/backend/src/main/java/org/raddatz/familienarchiv/exception/ErrorCode.java @@ -109,6 +109,8 @@ public enum ErrorCode { // --- Generic --- /** Request validation failed (missing or malformed fields). 400 */ VALIDATION_ERROR, + /** Batch upload exceeds the maximum allowed file count per request. 400 */ + BATCH_TOO_LARGE, /** An unexpected server-side error occurred. 500 */ INTERNAL_ERROR, } diff --git a/backend/src/main/java/org/raddatz/familienarchiv/service/DocumentService.java b/backend/src/main/java/org/raddatz/familienarchiv/service/DocumentService.java index fbdec954..b7d50f99 100644 --- a/backend/src/main/java/org/raddatz/familienarchiv/service/DocumentService.java +++ b/backend/src/main/java/org/raddatz/familienarchiv/service/DocumentService.java @@ -7,6 +7,7 @@ import org.raddatz.familienarchiv.audit.ActivityActorDTO; import org.raddatz.familienarchiv.audit.AuditKind; import org.raddatz.familienarchiv.audit.AuditLogQueryService; import org.raddatz.familienarchiv.audit.AuditService; +import org.raddatz.familienarchiv.dto.DocumentBatchMetadataDTO; import org.raddatz.familienarchiv.dto.DocumentSearchItem; import org.raddatz.familienarchiv.dto.DocumentSearchResult; import org.raddatz.familienarchiv.dto.DocumentSort; @@ -132,6 +133,52 @@ public class DocumentService { return new StoreResult(saved, isNew); } + public void validateBatch(int fileCount, DocumentBatchMetadataDTO metadata) { + // 50-file hard cap keeps FormData requests at a manageable size and protects against runaway bulk uploads. + if (fileCount > 50) { + throw DomainException.badRequest(ErrorCode.BATCH_TOO_LARGE, "Batch exceeds maximum of 50 files per request"); + } + if (metadata != null && metadata.getTitles() != null && metadata.getTitles().size() > fileCount) { + throw DomainException.badRequest(ErrorCode.VALIDATION_ERROR, "titles count must not exceed files count"); + } + } + + @Transactional + public StoreResult storeDocumentWithBatchMetadata( + MultipartFile file, DocumentBatchMetadataDTO metadata, int fileIndex, UUID actorId) throws IOException { + StoreResult base = storeDocument(file, actorId); + Document doc = applyBatchMetadata(base.document(), metadata, fileIndex); + return new StoreResult(documentRepository.save(doc), base.isNew()); + } + + private Document applyBatchMetadata(Document doc, DocumentBatchMetadataDTO metadata, int fileIndex) { + if (metadata.getTitles() != null && fileIndex < metadata.getTitles().size()) { + doc.setTitle(metadata.getTitles().get(fileIndex)); + } + if (metadata.getSenderId() != null) { + doc.setSender(personService.getById(metadata.getSenderId())); + } + if (metadata.getReceiverIds() != null && !metadata.getReceiverIds().isEmpty()) { + doc.setReceivers(new HashSet<>(personService.getAllById(metadata.getReceiverIds()))); + } + if (metadata.getDocumentDate() != null) { + doc.setDocumentDate(metadata.getDocumentDate()); + } + if (metadata.getLocation() != null) { + doc.setLocation(metadata.getLocation()); + } + if (metadata.getMetadataComplete() != null) { + doc.setMetadataComplete(metadata.getMetadataComplete()); + } + if (metadata.getTagNames() != null && !metadata.getTagNames().isEmpty()) { + UUID docId = doc.getId(); + updateDocumentTags(docId, metadata.getTagNames()); + doc = documentRepository.findById(docId) + .orElseThrow(() -> DomainException.notFound(ErrorCode.DOCUMENT_NOT_FOUND, "Not found after batch metadata: " + docId)); + } + return doc; + } + @Transactional public Document createDocument(DocumentUpdateDTO dto, MultipartFile file) throws IOException { String filename = (file != null && !file.isEmpty()) diff --git a/backend/src/main/resources/application.yaml b/backend/src/main/resources/application.yaml index d9bbe9d0..1cdd7673 100644 --- a/backend/src/main/resources/application.yaml +++ b/backend/src/main/resources/application.yaml @@ -23,7 +23,8 @@ spring: servlet: multipart: max-file-size: 50MB - max-request-size: 50MB + max-request-size: 500MB # supports 10-file chunk at max per-file size; see #317 + file-size-threshold: 2KB mail: host: ${MAIL_HOST:} diff --git a/backend/src/test/java/org/raddatz/familienarchiv/controller/DocumentControllerTest.java b/backend/src/test/java/org/raddatz/familienarchiv/controller/DocumentControllerTest.java index eb4c6873..b80ed173 100644 --- a/backend/src/test/java/org/raddatz/familienarchiv/controller/DocumentControllerTest.java +++ b/backend/src/test/java/org/raddatz/familienarchiv/controller/DocumentControllerTest.java @@ -1,15 +1,17 @@ package org.raddatz.familienarchiv.controller; import org.junit.jupiter.api.Test; +import org.raddatz.familienarchiv.dto.DocumentBatchMetadataDTO; import org.raddatz.familienarchiv.dto.DocumentSearchResult; import org.raddatz.familienarchiv.dto.DocumentVersionSummary; import org.raddatz.familienarchiv.exception.DomainException; import org.raddatz.familienarchiv.exception.ErrorCode; +import org.raddatz.familienarchiv.model.AppUser; import org.raddatz.familienarchiv.model.Document; import org.raddatz.familienarchiv.model.DocumentStatus; import org.raddatz.familienarchiv.model.DocumentVersion; +import org.raddatz.familienarchiv.model.Person; import org.raddatz.familienarchiv.security.PermissionAspect; -import org.raddatz.familienarchiv.model.AppUser; import org.raddatz.familienarchiv.service.CustomUserDetailsService; import org.raddatz.familienarchiv.service.DocumentService; import org.raddatz.familienarchiv.service.DocumentVersionService; @@ -766,4 +768,165 @@ class DocumentControllerTest { .andExpect(status().isOk()) .andExpect(jsonPath("$.editorName").value("Otto")); } + + // ─── POST /api/documents/quick-upload — metadata part ──────────────────── + + @Test + @WithMockUser(authorities = "WRITE_ALL") + void quickUpload_withMetadata_appliesSharedFieldsToAllCreatedDocuments() throws Exception { + UUID senderId = UUID.randomUUID(); + Person sender = Person.builder().id(senderId).lastName("Müller").build(); + + Document doc1 = Document.builder().id(UUID.randomUUID()).title("Brief 1").originalFilename("a.pdf").sender(sender).build(); + Document doc2 = Document.builder().id(UUID.randomUUID()).title("Brief 2").originalFilename("b.pdf").sender(sender).build(); + Document doc3 = Document.builder().id(UUID.randomUUID()).title("Brief 3").originalFilename("c.pdf").sender(sender).build(); + + when(userService.findByEmail(any())).thenReturn(AppUser.builder().id(UUID.randomUUID()).build()); + when(documentService.storeDocumentWithBatchMetadata(any(), any(), eq(0), any())) + .thenReturn(new DocumentService.StoreResult(doc1, true)); + when(documentService.storeDocumentWithBatchMetadata(any(), any(), eq(1), any())) + .thenReturn(new DocumentService.StoreResult(doc2, true)); + when(documentService.storeDocumentWithBatchMetadata(any(), any(), eq(2), any())) + .thenReturn(new DocumentService.StoreResult(doc3, true)); + + org.springframework.mock.web.MockMultipartFile f1 = + new org.springframework.mock.web.MockMultipartFile("files", "a.pdf", "application/pdf", new byte[]{1}); + org.springframework.mock.web.MockMultipartFile f2 = + new org.springframework.mock.web.MockMultipartFile("files", "b.pdf", "application/pdf", new byte[]{1}); + org.springframework.mock.web.MockMultipartFile f3 = + new org.springframework.mock.web.MockMultipartFile("files", "c.pdf", "application/pdf", new byte[]{1}); + org.springframework.mock.web.MockMultipartFile metadata = + new org.springframework.mock.web.MockMultipartFile("metadata", "metadata", "application/json", + ("{\"senderId\":\"" + senderId + "\"}").getBytes()); + + mockMvc.perform(multipart("/api/documents/quick-upload").file(f1).file(f2).file(f3).file(metadata)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.created.length()").value(3)) + .andExpect(jsonPath("$.created[0].sender.id").value(senderId.toString())) + .andExpect(jsonPath("$.created[1].sender.id").value(senderId.toString())) + .andExpect(jsonPath("$.created[2].sender.id").value(senderId.toString())) + .andExpect(jsonPath("$.updated").isEmpty()) + .andExpect(jsonPath("$.errors").isEmpty()); + } + + @Test + @WithMockUser(authorities = "WRITE_ALL") + void quickUpload_withMetadata_appliesSharedFieldsToUpdatedDocuments() throws Exception { + UUID senderId = UUID.randomUUID(); + Person sender = Person.builder().id(senderId).lastName("Müller").build(); + Document existing = Document.builder().id(UUID.randomUUID()).title("Alt").originalFilename("alt.pdf").sender(sender).build(); + + when(userService.findByEmail(any())).thenReturn(AppUser.builder().id(UUID.randomUUID()).build()); + when(documentService.storeDocumentWithBatchMetadata(any(), any(), eq(0), any())) + .thenReturn(new DocumentService.StoreResult(existing, false)); + + org.springframework.mock.web.MockMultipartFile file = + new org.springframework.mock.web.MockMultipartFile("files", "alt.pdf", "application/pdf", new byte[]{1}); + org.springframework.mock.web.MockMultipartFile metadata = + new org.springframework.mock.web.MockMultipartFile("metadata", "metadata", "application/json", + ("{\"senderId\":\"" + senderId + "\"}").getBytes()); + + mockMvc.perform(multipart("/api/documents/quick-upload").file(file).file(metadata)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.created").isEmpty()) + .andExpect(jsonPath("$.updated[0].sender.id").value(senderId.toString())) + .andExpect(jsonPath("$.errors").isEmpty()); + } + + @Test + @WithMockUser(authorities = "WRITE_ALL") + void quickUpload_withMetadata_mapsTitlesByIndex() throws Exception { + Document docA = Document.builder().id(UUID.randomUUID()).title("Alpha").originalFilename("a.pdf").build(); + Document docB = Document.builder().id(UUID.randomUUID()).title("Beta").originalFilename("b.pdf").build(); + Document docC = Document.builder().id(UUID.randomUUID()).title("Gamma").originalFilename("c.pdf").build(); + + when(userService.findByEmail(any())).thenReturn(AppUser.builder().id(UUID.randomUUID()).build()); + when(documentService.storeDocumentWithBatchMetadata(any(), any(), eq(0), any())) + .thenReturn(new DocumentService.StoreResult(docA, true)); + when(documentService.storeDocumentWithBatchMetadata(any(), any(), eq(1), any())) + .thenReturn(new DocumentService.StoreResult(docB, true)); + when(documentService.storeDocumentWithBatchMetadata(any(), any(), eq(2), any())) + .thenReturn(new DocumentService.StoreResult(docC, true)); + + org.springframework.mock.web.MockMultipartFile f1 = + new org.springframework.mock.web.MockMultipartFile("files", "a.pdf", "application/pdf", new byte[]{1}); + org.springframework.mock.web.MockMultipartFile f2 = + new org.springframework.mock.web.MockMultipartFile("files", "b.pdf", "application/pdf", new byte[]{1}); + org.springframework.mock.web.MockMultipartFile f3 = + new org.springframework.mock.web.MockMultipartFile("files", "c.pdf", "application/pdf", new byte[]{1}); + org.springframework.mock.web.MockMultipartFile metadata = + new org.springframework.mock.web.MockMultipartFile("metadata", "metadata", "application/json", + "{\"titles\":[\"Alpha\",\"Beta\",\"Gamma\"]}".getBytes()); + + mockMvc.perform(multipart("/api/documents/quick-upload").file(f1).file(f2).file(f3).file(metadata)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.created[0].title").value("Alpha")) + .andExpect(jsonPath("$.created[1].title").value("Beta")) + .andExpect(jsonPath("$.created[2].title").value("Gamma")); + } + + @Test + @WithMockUser(authorities = "WRITE_ALL") + void quickUpload_withMetadata_rejects400_whenTitlesSizeExceedsFilesSize() throws Exception { + when(userService.findByEmail(any())).thenReturn(AppUser.builder().id(UUID.randomUUID()).build()); + org.mockito.Mockito.doThrow( + org.raddatz.familienarchiv.exception.DomainException.badRequest( + org.raddatz.familienarchiv.exception.ErrorCode.VALIDATION_ERROR, "titles count must not exceed files count")) + .when(documentService).validateBatch(eq(2), any()); + + org.springframework.mock.web.MockMultipartFile f1 = + new org.springframework.mock.web.MockMultipartFile("files", "a.pdf", "application/pdf", new byte[]{1}); + org.springframework.mock.web.MockMultipartFile f2 = + new org.springframework.mock.web.MockMultipartFile("files", "b.pdf", "application/pdf", new byte[]{1}); + org.springframework.mock.web.MockMultipartFile metadata = + new org.springframework.mock.web.MockMultipartFile("metadata", "metadata", "application/json", + "{\"titles\":[\"A\",\"B\",\"C\"]}".getBytes()); + + mockMvc.perform(multipart("/api/documents/quick-upload").file(f1).file(f2).file(metadata)) + .andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser(authorities = "WRITE_ALL") + void quickUpload_withMetadata_tagNamesJsonArray_parsedCorrectly() throws Exception { + Document doc = Document.builder().id(UUID.randomUUID()).title("brief").originalFilename("brief.pdf").build(); + when(userService.findByEmail(any())).thenReturn(AppUser.builder().id(UUID.randomUUID()).build()); + + org.mockito.ArgumentCaptor captor = + org.mockito.ArgumentCaptor.forClass(DocumentBatchMetadataDTO.class); + when(documentService.storeDocumentWithBatchMetadata(any(), captor.capture(), anyInt(), any())) + .thenReturn(new DocumentService.StoreResult(doc, true)); + + org.springframework.mock.web.MockMultipartFile file = + new org.springframework.mock.web.MockMultipartFile("files", "brief.pdf", "application/pdf", new byte[]{1}); + org.springframework.mock.web.MockMultipartFile metadata = + new org.springframework.mock.web.MockMultipartFile("metadata", "metadata", "application/json", + "{\"tagNames\":[\"Briefwechsel\",\"Krieg\"]}".getBytes()); + + mockMvc.perform(multipart("/api/documents/quick-upload").file(file).file(metadata)) + .andExpect(status().isOk()); + + org.assertj.core.api.Assertions.assertThat(captor.getValue().getTagNames()) + .containsExactly("Briefwechsel", "Krieg"); + } + + @Test + @WithMockUser(authorities = "WRITE_ALL") + void quickUpload_returns400_whenBatchExceedsCap() throws Exception { + when(userService.findByEmail(any())).thenReturn(AppUser.builder().id(UUID.randomUUID()).build()); + org.mockito.Mockito.doThrow( + org.raddatz.familienarchiv.exception.DomainException.badRequest( + org.raddatz.familienarchiv.exception.ErrorCode.BATCH_TOO_LARGE, "Batch exceeds maximum of 50 files per request")) + .when(documentService).validateBatch(eq(51), any()); + + var builder = multipart("/api/documents/quick-upload"); + for (int i = 0; i < 51; i++) { + builder.file(new org.springframework.mock.web.MockMultipartFile( + "files", "f" + i + ".pdf", "application/pdf", new byte[]{1})); + } + + mockMvc.perform(builder) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("BATCH_TOO_LARGE")); + } } diff --git a/backend/src/test/java/org/raddatz/familienarchiv/service/DocumentServiceTest.java b/backend/src/test/java/org/raddatz/familienarchiv/service/DocumentServiceTest.java index 0e46196f..4c34862b 100644 --- a/backend/src/test/java/org/raddatz/familienarchiv/service/DocumentServiceTest.java +++ b/backend/src/test/java/org/raddatz/familienarchiv/service/DocumentServiceTest.java @@ -1813,4 +1813,108 @@ class DocumentServiceTest { verify(auditService).logAfterCommit(eq(AuditKind.FILE_UPLOADED), isNull(), eq(id), isNull()); } + + // ─── storeDocumentWithBatchMetadata ────────────────────────────────────── + + private MockMultipartFile pdfFile(String name) { + return new MockMultipartFile("file", name, "application/pdf", new byte[]{1}); + } + + private void stubStoreDocument(String filename) throws Exception { + when(documentRepository.findFirstByOriginalFilename(filename)).thenReturn(Optional.empty()); + when(fileService.uploadFile(any(), any())).thenReturn(new FileService.UploadResult("key", "hash")); + } + + @Test + void storeDocumentWithBatchMetadata_appliesTitleByIndex() throws Exception { + stubStoreDocument("scan01.pdf"); + when(documentRepository.save(any())).thenAnswer(inv -> inv.getArgument(0)); + + org.raddatz.familienarchiv.dto.DocumentBatchMetadataDTO meta = new org.raddatz.familienarchiv.dto.DocumentBatchMetadataDTO(); + meta.setTitles(List.of("Erster Brief", "Zweiter Brief")); + + DocumentService.StoreResult result = documentService.storeDocumentWithBatchMetadata(pdfFile("scan01.pdf"), meta, 0, null); + + assertThat(result.document().getTitle()).isEqualTo("Erster Brief"); + } + + @Test + void storeDocumentWithBatchMetadata_resolvesSenderViaPersonService() throws Exception { + UUID senderId = UUID.randomUUID(); + stubStoreDocument("scan02.pdf"); + when(documentRepository.save(any())).thenAnswer(inv -> inv.getArgument(0)); + Person sender = Person.builder().id(senderId).firstName("Anna").build(); + when(personService.getById(senderId)).thenReturn(sender); + + org.raddatz.familienarchiv.dto.DocumentBatchMetadataDTO meta = new org.raddatz.familienarchiv.dto.DocumentBatchMetadataDTO(); + meta.setSenderId(senderId); + + DocumentService.StoreResult result = documentService.storeDocumentWithBatchMetadata(pdfFile("scan02.pdf"), meta, 0, null); + + assertThat(result.document().getSender()).isEqualTo(sender); + } + + @Test + void storeDocumentWithBatchMetadata_appliesTagsViaUpdateDocumentTags() throws Exception { + UUID docId = UUID.randomUUID(); + when(documentRepository.findFirstByOriginalFilename("scan03.pdf")).thenReturn(Optional.empty()); + when(fileService.uploadFile(any(), any())).thenReturn(new FileService.UploadResult("key", "hash")); + when(documentRepository.save(any())).thenAnswer(inv -> { + Document d = inv.getArgument(0); + if (d.getId() == null) d.setId(docId); + return d; + }); + when(documentRepository.findById(docId)).thenAnswer(inv -> { + Document d = new Document(); + d.setId(docId); + return Optional.of(d); + }); + Tag tag = Tag.builder().id(UUID.randomUUID()).name("Familie").build(); + when(tagService.findOrCreate("Familie")).thenReturn(tag); + + org.raddatz.familienarchiv.dto.DocumentBatchMetadataDTO meta = new org.raddatz.familienarchiv.dto.DocumentBatchMetadataDTO(); + meta.setTagNames(List.of("Familie")); + + documentService.storeDocumentWithBatchMetadata(pdfFile("scan03.pdf"), meta, 0, null); + + verify(tagService).findOrCreate("Familie"); + } + + @Test + void storeDocumentWithBatchMetadata_leavesTitle_whenIndexExceedsTitlesList() throws Exception { + stubStoreDocument("scan04.pdf"); + when(documentRepository.save(any())).thenAnswer(inv -> inv.getArgument(0)); + + org.raddatz.familienarchiv.dto.DocumentBatchMetadataDTO meta = new org.raddatz.familienarchiv.dto.DocumentBatchMetadataDTO(); + meta.setTitles(List.of("Only One Title")); + + DocumentService.StoreResult result = documentService.storeDocumentWithBatchMetadata(pdfFile("scan04.pdf"), meta, 5, null); + + assertThat(result.document().getTitle()).isEqualTo("scan04"); + } + + // ─── validateBatch ─────────────────────────────────────────────────────── + + @Test + void validateBatch_throwsBatchTooLarge_whenFileCountExceedsCap() { + assertThatThrownBy(() -> documentService.validateBatch(51, null)) + .isInstanceOf(DomainException.class) + .hasMessageContaining("50"); + } + + @Test + void validateBatch_doesNotThrow_whenFileCountEqualsCapExactly() { + documentService.validateBatch(50, null); + } + + @Test + void validateBatch_throwsValidationError_whenTitlesSizeExceedsFileCount() { + org.raddatz.familienarchiv.dto.DocumentBatchMetadataDTO metadata = + new org.raddatz.familienarchiv.dto.DocumentBatchMetadataDTO(); + metadata.setTitles(java.util.List.of("A", "B", "C")); + + assertThatThrownBy(() -> documentService.validateBatch(2, metadata)) + .isInstanceOf(DomainException.class) + .hasMessageContaining("titles"); + } } diff --git a/frontend/messages/de.json b/frontend/messages/de.json index 1b90d913..0ef4cb8e 100644 --- a/frontend/messages/de.json +++ b/frontend/messages/de.json @@ -850,5 +850,29 @@ "richtlinien_klaer_umbrueche": "Originale Zeilenumbrüche", "richtlinien_klaer_caps": "Alte Groß-/Kleinschreibung", "richtlinien_closing_title": "Fehlt eine Regel?", - "richtlinien_closing_body": "Stolpern Sie beim Transkribieren über eine Situation, die hier nicht steht — schreiben Sie einen Kommentar beim betreffenden Block. Wir sammeln sie und besprechen sie beim nächsten Familientreffen." + "richtlinien_closing_body": "Stolpern Sie beim Transkribieren über eine Situation, die hier nicht steht — schreiben Sie einen Kommentar beim betreffenden Block. Wir sammeln sie und besprechen sie beim nächsten Familientreffen.", + "error_batch_too_large": "Zu viele Dateien auf einmal — bitte in Blöcken hochladen.", + "bulk_drop_hint": "Eine oder mehrere Dateien ablegen", + "bulk_drop_sub": "PDF · bis zu 50 MB pro Datei", + "bulk_count_pill": "{count} werden erstellt", + "bulk_save_cta_one": "Speichern →", + "bulk_save_cta": "{count} speichern →", + "bulk_discard_all": "Alle verwerfen", + "bulk_discard_confirm": "Alle Dateien und eingegebenen Daten verwerfen? Diese Aktion kann nicht rückgängig gemacht werden.", + "bulk_add_more": "Weitere hinzufügen", + "bulk_scope_per_file_label": "Nur diese Datei", + "bulk_scope_shared_label": "Gilt für alle {count}", + "bulk_title_suggested_hint": "Vorschlag aus Dateiname — zum Bearbeiten anklicken", + "bulk_switcher_prev": "Vorherige Datei", + "bulk_switcher_next": "Nächste Datei", + "bulk_file_error_chip_label": "Fehler beim Hochladen", + "bulk_upload_progress": "{done} von {total} hochgeladen", + "bulk_partial_success": "{created} erstellt, {failed} fehlgeschlagen", + "bulk_all_failed": "Alle Uploads fehlgeschlagen", + "bulk_drop_desc": "Für jede Datei wird ein eigenes Dokument erstellt. Der Titel wird aus dem Dateinamen vorausgefüllt — alle anderen Felder gelten für alle gemeinsam.", + "bulk_select_files": "Dateien auswählen", + "bulk_drop_zone_label": "Dateien ablegen", + "bulk_remove_file": "Entfernen", + "bulk_title_single": "Neues Dokument", + "bulk_title_multi": "Neue Dokumente" } diff --git a/frontend/messages/en.json b/frontend/messages/en.json index f5862f0f..032e7bb5 100644 --- a/frontend/messages/en.json +++ b/frontend/messages/en.json @@ -850,5 +850,29 @@ "richtlinien_klaer_umbrueche": "Original line breaks", "richtlinien_klaer_caps": "Old capitalisation", "richtlinien_closing_title": "Missing a rule?", - "richtlinien_closing_body": "If you hit a situation while transcribing that isn't listed here — leave a comment on the relevant block. We collect them and discuss them at the next family gathering." + "richtlinien_closing_body": "If you hit a situation while transcribing that isn't listed here — leave a comment on the relevant block. We collect them and discuss them at the next family gathering.", + "error_batch_too_large": "Too many files at once — please upload in smaller batches.", + "bulk_drop_hint": "Drop one or more files here", + "bulk_drop_sub": "PDF · up to 50 MB per file", + "bulk_count_pill": "{count} will be created", + "bulk_save_cta_one": "Save →", + "bulk_save_cta": "Save {count} →", + "bulk_discard_all": "Discard all", + "bulk_discard_confirm": "Discard all files and entered data? This action cannot be undone.", + "bulk_add_more": "Add more", + "bulk_scope_per_file_label": "This file only", + "bulk_scope_shared_label": "Applies to all {count}", + "bulk_title_suggested_hint": "Suggested from filename — click to edit", + "bulk_switcher_prev": "Previous file", + "bulk_switcher_next": "Next file", + "bulk_file_error_chip_label": "Upload failed", + "bulk_upload_progress": "{done} of {total} uploaded", + "bulk_partial_success": "{created} created, {failed} failed", + "bulk_all_failed": "All uploads failed", + "bulk_drop_desc": "A separate document is created for each file. The title is pre-filled from the filename — all other fields apply to all documents.", + "bulk_select_files": "Select files", + "bulk_drop_zone_label": "Drop files here", + "bulk_remove_file": "Remove", + "bulk_title_single": "New Document", + "bulk_title_multi": "New Documents" } diff --git a/frontend/messages/es.json b/frontend/messages/es.json index c949ce2c..7e328905 100644 --- a/frontend/messages/es.json +++ b/frontend/messages/es.json @@ -850,5 +850,29 @@ "richtlinien_klaer_umbrueche": "Saltos de línea originales", "richtlinien_klaer_caps": "Mayúsculas antiguas", "richtlinien_closing_title": "¿Falta una regla?", - "richtlinien_closing_body": "Si al transcribir encuentras una situación que no está aquí — deja un comentario en el bloque. Las recogemos y las discutimos en la próxima reunión familiar." + "richtlinien_closing_body": "Si al transcribir encuentras una situación que no está aquí — deja un comentario en el bloque. Las recogemos y las discutimos en la próxima reunión familiar.", + "error_batch_too_large": "Demasiados archivos a la vez — sube en lotes más pequeños.", + "bulk_drop_hint": "Suelta uno o varios archivos aquí", + "bulk_drop_sub": "PDF · hasta 50 MB por archivo", + "bulk_count_pill": "Se crearán {count}", + "bulk_save_cta_one": "Guardar →", + "bulk_save_cta": "Guardar {count} →", + "bulk_discard_all": "Descartar todo", + "bulk_discard_confirm": "¿Descartar todos los archivos y datos introducidos? Esta acción no se puede deshacer.", + "bulk_add_more": "Añadir más", + "bulk_scope_per_file_label": "Solo este archivo", + "bulk_scope_shared_label": "Para todos los {count}", + "bulk_title_suggested_hint": "Sugerencia del nombre de archivo — haz clic para editar", + "bulk_switcher_prev": "Archivo anterior", + "bulk_switcher_next": "Archivo siguiente", + "bulk_file_error_chip_label": "Error al subir", + "bulk_upload_progress": "{done} de {total} subidos", + "bulk_partial_success": "{created} creados, {failed} fallidos", + "bulk_all_failed": "Todos los uploads fallaron", + "bulk_drop_desc": "Se crea un documento separado por archivo. El título se rellena desde el nombre del archivo — el resto de campos se aplican a todos.", + "bulk_select_files": "Seleccionar archivos", + "bulk_drop_zone_label": "Soltar archivos aquí", + "bulk_remove_file": "Eliminar", + "bulk_title_single": "Nuevo Documento", + "bulk_title_multi": "Nuevos Documentos" } diff --git a/frontend/src/lib/components/PersonMultiSelect.svelte b/frontend/src/lib/components/PersonMultiSelect.svelte index 7847787f..6ff453c9 100644 --- a/frontend/src/lib/components/PersonMultiSelect.svelte +++ b/frontend/src/lib/components/PersonMultiSelect.svelte @@ -67,7 +67,7 @@ function removePerson(id: string | undefined) {
(showDropdown = false)}>
{#each selectedPersons as person (person.id)} {#if typeahead.isOpen && (typeahead.results.length > 0 || typeahead.loading)} diff --git a/frontend/src/lib/components/document/BulkDocumentEditLayout.svelte b/frontend/src/lib/components/document/BulkDocumentEditLayout.svelte new file mode 100644 index 00000000..6ce93a07 --- /dev/null +++ b/frontend/src/lib/components/document/BulkDocumentEditLayout.svelte @@ -0,0 +1,320 @@ + + +
+ +
+ + + {m.btn_back_to_overview()} + + + + {isMulti ? m.bulk_title_multi() : m.bulk_title_single()} + + {#if isMulti} + + + {m.bulk_count_pill({ count: files.size })} + + + + {/if} +
+ + +
+ +
+ {#if files.size === 0} + + + {:else} + +
+ {#if activeFile} + + {/if} +
+ {#if isMulti} + + (activeId = id)} + onRemove={removeFile} + /> + {/if} + {/if} +
+ + +
+ +
+ {#if isMulti} + + + {#if activeFile} + + {/if} + + + + + + + {:else} + +
+ +
+ + + + {/if} +
+ + + +
+
+
diff --git a/frontend/src/lib/components/document/BulkDocumentEditLayout.svelte.spec.ts b/frontend/src/lib/components/document/BulkDocumentEditLayout.svelte.spec.ts new file mode 100644 index 00000000..1b24627d --- /dev/null +++ b/frontend/src/lib/components/document/BulkDocumentEditLayout.svelte.spec.ts @@ -0,0 +1,314 @@ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { goto } from '$app/navigation'; +import { cleanup, render } from 'vitest-browser-svelte'; +import { page, userEvent } from 'vitest/browser'; +import BulkDocumentEditLayout from './BulkDocumentEditLayout.svelte'; + +vi.mock('$app/navigation', () => ({ goto: vi.fn() })); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.clearAllMocks(); +}); + +function makeFile(name: string): File { + return new File(['content'], name, { type: 'application/pdf' }); +} + +async function addFilesViaInput(container: HTMLElement, files: File[]): Promise { + const input = container.querySelector('input[type="file"]') as HTMLInputElement; + if (!input) throw new Error('No file input found — is BulkDropZone visible?'); + await userEvent.upload(input, files); +} + +describe('BulkDocumentEditLayout', () => { + it('N=0: shows BulkDropZone', async () => { + render(BulkDocumentEditLayout, {}); + await expect.element(page.getByTestId('bulk-drop-zone')).toBeInTheDocument(); + }); + + it('N=1: file-switcher-strip and per-file scope card are absent', async () => { + const { container } = render(BulkDocumentEditLayout, {}); + await addFilesViaInput(container, [makeFile('doc.pdf')]); + expect(container.querySelector('[data-testid="file-switcher-strip"]')).toBeNull(); + expect(container.querySelector('[data-variant="per-file"]')).toBeNull(); + }); + + it('N=5: file-switcher-strip and per-file scope card are both present', async () => { + const { container } = render(BulkDocumentEditLayout, {}); + await addFilesViaInput(container, [ + makeFile('a.pdf'), + makeFile('b.pdf'), + makeFile('c.pdf'), + makeFile('d.pdf'), + makeFile('e.pdf') + ]); + expect(container.querySelector('[data-testid="file-switcher-strip"]')).not.toBeNull(); + expect(container.querySelector('[data-variant="per-file"]')).not.toBeNull(); + }); + + it('removing middle file preserves order of remaining files', async () => { + const { container } = render(BulkDocumentEditLayout, {}); + await addFilesViaInput(container, [ + makeFile('file0.pdf'), + makeFile('file1.pdf'), + makeFile('file2.pdf') + ]); + + // Remove the chip for file1 via its remove button (identified by data-remove-id) + const removeButtons = container.querySelectorAll( + '[data-testid="file-switcher-strip"] button[data-remove-id]' + ); + expect(removeButtons.length).toBe(3); + removeButtons[1].click(); // remove file1 + + // Wait for Svelte to flush the DOM update + await vi.waitFor( + () => { + const chips = container.querySelectorAll( + '[data-testid="file-switcher-strip"] [data-chip-id]' + ); + expect(chips.length).toBe(2); + expect(chips[0].textContent?.trim()).toContain('file0'); + expect(chips[1].textContent?.trim()).toContain('file2'); + }, + { timeout: 1000 } + ); + }); + + it('save calls fetch twice for 12 files (2 chunks of 10)', async () => { + const mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ created: [], updated: [], errors: [] }) + }); + vi.stubGlobal('fetch', mockFetch); + + const { container } = render(BulkDocumentEditLayout, {}); + const files = Array.from({ length: 12 }, (_, i) => makeFile(`f${i}.pdf`)); + await addFilesViaInput(container, files); + + const saveBtn = container.querySelector( + 'button[data-testid="bulk-save-btn"]' + ) as HTMLButtonElement; + expect(saveBtn).not.toBeNull(); + saveBtn.click(); + + // Wait for async save to complete + await vi.waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(2), { timeout: 3000 }); + }); + + it('save marks file as error when server returns non-ok response', async () => { + const mockFetch = vi.fn().mockResolvedValue({ + ok: false, + json: async () => ({ errors: [{ filename: 'f0.pdf', code: 'FILE_UPLOAD_FAILED' }] }) + }); + vi.stubGlobal('fetch', mockFetch); + + const { container } = render(BulkDocumentEditLayout, {}); + await addFilesViaInput(container, [makeFile('f0.pdf')]); + + const saveBtn = container.querySelector( + 'button[data-testid="bulk-save-btn"]' + ) as HTMLButtonElement; + saveBtn.click(); + + await vi.waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(1), { timeout: 3000 }); + }); + + it('save() includes tagNames in metadata payload', async () => { + let capturedFormData: FormData | undefined; + const mockFetch = vi.fn().mockImplementation(async (_url: string, init: RequestInit) => { + capturedFormData = init?.body as FormData; + return { ok: true, json: async () => ({ created: [], updated: [], errors: [] }) }; + }); + vi.stubGlobal('fetch', mockFetch); + + const { container } = render(BulkDocumentEditLayout, {}); + await addFilesViaInput(container, [makeFile('doc.pdf')]); + + const saveBtn = container.querySelector( + 'button[data-testid="bulk-save-btn"]' + ) as HTMLButtonElement; + saveBtn.click(); + + await vi.waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(1), { timeout: 3000 }); + + expect(capturedFormData).toBeDefined(); + const metadataBlob = capturedFormData!.get('metadata') as Blob; + const metadataJson = JSON.parse(await metadataBlob.text()); + expect(metadataJson).toHaveProperty('tagNames'); + }); + + it('save() navigates to /documents when all chunks succeed', async () => { + const mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ created: [], updated: [], errors: [] }) + }); + vi.stubGlobal('fetch', mockFetch); + + const { container } = render(BulkDocumentEditLayout, {}); + await addFilesViaInput(container, [makeFile('doc.pdf')]); + + const saveBtn = container.querySelector( + 'button[data-testid="bulk-save-btn"]' + ) as HTMLButtonElement; + saveBtn.click(); + + await vi.waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(1), { timeout: 3000 }); + await vi.waitFor(() => expect(goto).toHaveBeenCalledWith('/documents'), { timeout: 3000 }); + }); + + it('save() does not navigate when chunk returns non-ok response', async () => { + const mockFetch = vi.fn().mockResolvedValue({ + ok: false, + json: async () => ({ errors: [{ filename: 'f0.pdf', code: 'FILE_UPLOAD_FAILED' }] }) + }); + vi.stubGlobal('fetch', mockFetch); + + const { container } = render(BulkDocumentEditLayout, {}); + await addFilesViaInput(container, [makeFile('f0.pdf')]); + + const saveBtn = container.querySelector( + 'button[data-testid="bulk-save-btn"]' + ) as HTMLButtonElement; + saveBtn.click(); + + await vi.waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(1), { timeout: 3000 }); + expect(goto).not.toHaveBeenCalled(); + }); + + it('save marks only the file whose filename matches the backend error, not adjacent files', async () => { + // backend returns error keyed to b.pdf — only b.pdf chip should get data-status="error" + const mockFetch = vi.fn().mockResolvedValue({ + ok: false, + json: async () => ({ errors: [{ filename: 'b.pdf', code: 'FILE_UPLOAD_FAILED' }] }) + }); + vi.stubGlobal('fetch', mockFetch); + + const { container } = render(BulkDocumentEditLayout, {}); + await addFilesViaInput(container, [makeFile('a.pdf'), makeFile('b.pdf'), makeFile('c.pdf')]); + + const saveBtn = container.querySelector( + 'button[data-testid="bulk-save-btn"]' + ) as HTMLButtonElement; + saveBtn.click(); + + await vi.waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(1), { timeout: 3000 }); + + await vi.waitFor( + () => { + const errorChips = container.querySelectorAll('[data-chip-id][data-status="error"]'); + expect(errorChips.length).toBe(1); + expect(errorChips[0].textContent).toContain('b'); + }, + { timeout: 1000 } + ); + }); + + it('save() marks only the failed file when server returns HTTP 200 with a partial errors array', async () => { + // Backend can return 200 OK while reporting individual file failures + const mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ + created: [{ id: '1' }], + updated: [], + errors: [{ filename: 'b.pdf', code: 'FILE_UPLOAD_FAILED' }] + }) + }); + vi.stubGlobal('fetch', mockFetch); + + const { container } = render(BulkDocumentEditLayout, {}); + await addFilesViaInput(container, [makeFile('a.pdf'), makeFile('b.pdf'), makeFile('c.pdf')]); + + const saveBtn = container.querySelector( + 'button[data-testid="bulk-save-btn"]' + ) as HTMLButtonElement; + saveBtn.click(); + + await vi.waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(1), { timeout: 3000 }); + + await vi.waitFor( + () => { + const errorChips = container.querySelectorAll('[data-chip-id][data-status="error"]'); + expect(errorChips.length).toBe(1); + expect(errorChips[0].textContent).toContain('b'); + }, + { timeout: 1000 } + ); + // Navigation should be suppressed because hadErrors is true + expect(goto).not.toHaveBeenCalled(); + }); + + it('save() marks all chunk files as errored when fetch throws a network error', async () => { + vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('network error'))); + + const { container } = render(BulkDocumentEditLayout, {}); + await addFilesViaInput(container, [makeFile('a.pdf'), makeFile('b.pdf')]); + + const saveBtn = container.querySelector( + 'button[data-testid="bulk-save-btn"]' + ) as HTMLButtonElement; + saveBtn.click(); + + await vi.waitFor( + () => { + const errorChips = container.querySelectorAll('[data-chip-id][data-status="error"]'); + expect(errorChips.length).toBe(2); + }, + { timeout: 3000 } + ); + expect(goto).not.toHaveBeenCalled(); + }); + + it('save() does not call fetch a second time when already saving', async () => { + let resolveFirst: (() => void) | undefined; + const mockFetch = vi.fn().mockImplementation( + () => + new Promise((resolve) => { + resolveFirst = () => + resolve({ + ok: true, + json: async () => ({ created: [], updated: [], errors: [] }) + } as Response); + }) + ); + vi.stubGlobal('fetch', mockFetch); + + const { container } = render(BulkDocumentEditLayout, {}); + await addFilesViaInput(container, [makeFile('a.pdf')]); + + const saveBtn = container.querySelector( + 'button[data-testid="bulk-save-btn"]' + ) as HTMLButtonElement; + saveBtn.click(); // first click — fetch is in-flight + saveBtn.click(); // second click — should be a no-op + + resolveFirst?.(); + await vi.waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(1), { timeout: 3000 }); + expect(mockFetch).toHaveBeenCalledTimes(1); + }); + + it('discard-all resets to N=0 state and shows drop zone', async () => { + const { container } = render(BulkDocumentEditLayout, {}); + await addFilesViaInput(container, [makeFile('a.pdf'), makeFile('b.pdf')]); + + // Confirm N=2 state — switcher is visible + expect(container.querySelector('[data-testid="file-switcher-strip"]')).not.toBeNull(); + + // Click the topbar discard-all button (only visible in isMulti state) + const discardBtn = container.querySelector( + 'button[data-testid="discard-all-btn"]' + ) as HTMLButtonElement; + expect(discardBtn).not.toBeNull(); + discardBtn.click(); + + await vi.waitFor( + () => { + expect(container.querySelector('[data-testid="bulk-drop-zone"]')).not.toBeNull(); + expect(container.querySelector('[data-testid="file-switcher-strip"]')).toBeNull(); + }, + { timeout: 1000 } + ); + }); +}); diff --git a/frontend/src/lib/components/document/BulkDropZone.svelte b/frontend/src/lib/components/document/BulkDropZone.svelte new file mode 100644 index 00000000..204b12fc --- /dev/null +++ b/frontend/src/lib/components/document/BulkDropZone.svelte @@ -0,0 +1,80 @@ + + +
{ + e.preventDefault(); + isDragging = true; + }} + ondragleave={() => (isDragging = false)} + ondrop={(e) => { + e.preventDefault(); + isDragging = false; + if (e.dataTransfer && e.dataTransfer.files.length > 0) { + onFilesAdded(Array.from(e.dataTransfer.files)); + } + }} +> +
+ +
+ +
+ + +

{m.bulk_drop_hint()}

+ + +

{m.bulk_drop_desc()}

+ + + + + +

{m.bulk_drop_sub()}

+
+
diff --git a/frontend/src/lib/components/document/BulkDropZone.svelte.spec.ts b/frontend/src/lib/components/document/BulkDropZone.svelte.spec.ts new file mode 100644 index 00000000..139933b6 --- /dev/null +++ b/frontend/src/lib/components/document/BulkDropZone.svelte.spec.ts @@ -0,0 +1,39 @@ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { cleanup, render } from 'vitest-browser-svelte'; +import { page, userEvent } from 'vitest/browser'; +import BulkDropZone from './BulkDropZone.svelte'; + +afterEach(cleanup); + +describe('BulkDropZone', () => { + it('file input has multiple attribute', async () => { + const { container } = render(BulkDropZone, { onFilesAdded: vi.fn() }); + const input = container.querySelector('input[type="file"]'); + expect(input).not.toBeNull(); + expect(input?.hasAttribute('multiple')).toBe(true); + }); + + it('fires onFilesAdded with selected files when 3 files are picked via input', async () => { + const onFilesAdded = vi.fn(); + render(BulkDropZone, { onFilesAdded }); + + const files = [ + new File(['a'], 'a.pdf', { type: 'application/pdf' }), + new File(['b'], 'b.pdf', { type: 'application/pdf' }), + new File(['c'], 'c.pdf', { type: 'application/pdf' }) + ]; + + const input = page.getByRole('button', { name: /Dateien auswählen/i }); + await userEvent.upload(input, files); + + expect(onFilesAdded).toHaveBeenCalledOnce(); + const received: File[] = onFilesAdded.mock.calls[0][0]; + expect(received).toHaveLength(3); + expect(received.map((f) => f.name)).toEqual(['a.pdf', 'b.pdf', 'c.pdf']); + }); + + it('shows drop hint text', async () => { + render(BulkDropZone, { onFilesAdded: vi.fn() }); + await expect.element(page.getByText(/hier ablegen/i)).toBeInTheDocument(); + }); +}); diff --git a/frontend/src/lib/components/document/FileSwitcherStrip.svelte b/frontend/src/lib/components/document/FileSwitcherStrip.svelte new file mode 100644 index 00000000..8816d1a1 --- /dev/null +++ b/frontend/src/lib/components/document/FileSwitcherStrip.svelte @@ -0,0 +1,150 @@ + + +
{activeAnnouncement}
+
+ + + +
+
+
+
+
    + {#each files as entry, i (entry.id)} +
  • + + +
  • + {/each} +
+
+
+ + +
diff --git a/frontend/src/lib/components/document/FileSwitcherStrip.svelte.spec.ts b/frontend/src/lib/components/document/FileSwitcherStrip.svelte.spec.ts new file mode 100644 index 00000000..c45550c8 --- /dev/null +++ b/frontend/src/lib/components/document/FileSwitcherStrip.svelte.spec.ts @@ -0,0 +1,145 @@ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { cleanup, render } from 'vitest-browser-svelte'; +import { page, userEvent } from 'vitest/browser'; +import FileSwitcherStrip from './FileSwitcherStrip.svelte'; +import type { FileEntry } from './FileSwitcherStrip.svelte'; + +afterEach(cleanup); + +function makeFiles(n: number): FileEntry[] { + return Array.from({ length: n }, (_, i) => ({ + id: `id-${i}`, + file: new File([''], `file${i}.pdf`), + title: `File ${i}`, + status: 'idle' as const, + previewUrl: '' + })); +} + +describe('FileSwitcherStrip', () => { + it('renders N chips for N files', async () => { + const files = makeFiles(4); + render(FileSwitcherStrip, { + files, + activeId: files[0].id, + onSelect: vi.fn(), + onRemove: vi.fn() + }); + const chips = page.getByRole('listitem'); + await expect.element(chips.nth(0)).toBeInTheDocument(); + await expect.element(chips.nth(3)).toBeInTheDocument(); + }); + + it('active chip has aria-current="true"', async () => { + const files = makeFiles(3); + const { container } = render(FileSwitcherStrip, { + files, + activeId: files[1].id, + onSelect: vi.fn(), + onRemove: vi.fn() + }); + const activeBtn = container.querySelector('[aria-current="true"]'); + expect(activeBtn).not.toBeNull(); + expect(activeBtn?.textContent).toContain('File 1'); + }); + + it('clicking a chip fires onSelect with its id', async () => { + const files = makeFiles(3); + const onSelect = vi.fn(); + const { container } = render(FileSwitcherStrip, { + files, + activeId: files[0].id, + onSelect, + onRemove: vi.fn() + }); + const chip = container.querySelector('[data-chip-id="id-2"]') as HTMLElement; + expect(chip).not.toBeNull(); + chip.click(); + expect(onSelect).toHaveBeenCalledWith('id-2'); + }); + + it('error chip has aria-label containing warning indicator', async () => { + const files: FileEntry[] = [ + { + id: 'e1', + file: new File([''], 'bad.pdf'), + title: 'Bad file', + status: 'error', + previewUrl: '' + } + ]; + const { container } = render(FileSwitcherStrip, { + files, + activeId: 'e1', + onSelect: vi.fn(), + onRemove: vi.fn() + }); + const errBtn = container.querySelector('[data-status="error"]'); + expect(errBtn).not.toBeNull(); + }); + + it('error chip contains a screen-reader-only error label', async () => { + const files: FileEntry[] = [ + { + id: 'e1', + file: new File([''], 'bad.pdf'), + title: 'Bad file', + status: 'error', + previewUrl: '' + } + ]; + const { container } = render(FileSwitcherStrip, { + files, + activeId: 'e1', + onSelect: vi.fn(), + onRemove: vi.fn() + }); + const errBtn = container.querySelector('[data-status="error"]'); + const srOnly = errBtn?.querySelector('.sr-only'); + expect(srOnly).not.toBeNull(); + }); + + it('focus moves to the previous chip after the middle chip is removed', async () => { + const files = makeFiles(3); // id-0, id-1, id-2 + const onRemove = vi.fn(); + const { container } = render(FileSwitcherStrip, { + files, + activeId: files[1].id, + onSelect: vi.fn(), + onRemove + }); + + const removeBtn = container.querySelector('[data-remove-id="id-1"]') as HTMLButtonElement; + expect(removeBtn).not.toBeNull(); + removeBtn.click(); + expect(onRemove).toHaveBeenCalledWith('id-1'); + + // After removal, focus should be on the chip for id-0 (the previous chip) + await vi.waitFor( + () => { + const prevChip = container.querySelector('[data-chip-id="id-0"]') as HTMLElement | null; + expect(prevChip).not.toBeNull(); + expect(document.activeElement).toBe(prevChip); + }, + { timeout: 1000 } + ); + }); + + it('ArrowRight moves focus to next chip without leaving strip', async () => { + const files = makeFiles(3); + const { container } = render(FileSwitcherStrip, { + files, + activeId: files[0].id, + onSelect: vi.fn(), + onRemove: vi.fn() + }); + const firstBtn = container.querySelectorAll('[data-chip-id]')[0] as HTMLElement; + firstBtn.focus(); + await userEvent.keyboard('{ArrowRight}'); + const focused = document.activeElement; + expect(focused).not.toBe(firstBtn); + // The new focused element should still be inside the strip + const strip = container.querySelector('[data-testid="file-switcher-strip"]'); + expect(strip?.contains(focused)).toBe(true); + }); +}); diff --git a/frontend/src/lib/components/document/ScopeCard.svelte b/frontend/src/lib/components/document/ScopeCard.svelte new file mode 100644 index 00000000..6fb79f96 --- /dev/null +++ b/frontend/src/lib/components/document/ScopeCard.svelte @@ -0,0 +1,40 @@ + + +
+ {#if variant === 'shared'} +
+ + {m.bulk_scope_shared_label({ count })} + + + {count} + +
+ {:else} +

+ {m.bulk_scope_per_file_label()} +

+ {/if} + {@render children?.()} +
diff --git a/frontend/src/lib/components/document/ScopeCard.svelte.spec.ts b/frontend/src/lib/components/document/ScopeCard.svelte.spec.ts new file mode 100644 index 00000000..9a04b7d9 --- /dev/null +++ b/frontend/src/lib/components/document/ScopeCard.svelte.spec.ts @@ -0,0 +1,32 @@ +import { describe, it, expect, afterEach } from 'vitest'; +import { cleanup, render } from 'vitest-browser-svelte'; +import { page } from 'vitest/browser'; +import ScopeCard from './ScopeCard.svelte'; + +afterEach(cleanup); + +describe('ScopeCard', () => { + it('per-file variant has accent background class', async () => { + const { container } = render(ScopeCard, { variant: 'per-file', count: 1 }); + const card = container.querySelector('[data-testid="scope-card"]'); + expect(card?.className).toMatch(/bg-accent-bg/); + }); + + it('shared variant does not have accent background', async () => { + const { container } = render(ScopeCard, { variant: 'shared', count: 3 }); + const card = container.querySelector('[data-testid="scope-card"]'); + expect(card?.className).not.toMatch(/bg-accent-bg/); + }); + + it('shared variant renders count badge with file count', async () => { + render(ScopeCard, { variant: 'shared', count: 5 }); + await expect.element(page.getByText('5', { exact: true })).toBeInTheDocument(); + }); + + it('per-file variant renders slot content', async () => { + // ScopeCard is a container — verify it renders children + render(ScopeCard, { variant: 'per-file', count: 1 }); + const card = await page.getByTestId('scope-card'); + await expect.element(card).toBeInTheDocument(); + }); +}); diff --git a/frontend/src/lib/components/document/UploadSaveBar.svelte b/frontend/src/lib/components/document/UploadSaveBar.svelte new file mode 100644 index 00000000..d404e864 --- /dev/null +++ b/frontend/src/lib/components/document/UploadSaveBar.svelte @@ -0,0 +1,49 @@ + + +
+ {#if chunkProgress} + + {/if} +
+ + +
+
diff --git a/frontend/src/lib/components/document/UploadSaveBar.svelte.spec.ts b/frontend/src/lib/components/document/UploadSaveBar.svelte.spec.ts new file mode 100644 index 00000000..4516a831 --- /dev/null +++ b/frontend/src/lib/components/document/UploadSaveBar.svelte.spec.ts @@ -0,0 +1,48 @@ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { cleanup, render } from 'vitest-browser-svelte'; +import { page } from 'vitest/browser'; +import UploadSaveBar from './UploadSaveBar.svelte'; + +afterEach(cleanup); + +describe('UploadSaveBar', () => { + it('shows plural label for multiple files', async () => { + render(UploadSaveBar, { fileCount: 5, onSave: vi.fn(), onDiscard: vi.fn() }); + // "5 speichern →" or similar plural form + await expect.element(page.getByText(/5/)).toBeInTheDocument(); + }); + + it('shows singular label for one file', async () => { + render(UploadSaveBar, { fileCount: 1, onSave: vi.fn(), onDiscard: vi.fn() }); + // "Speichern →" singular form + await expect.element(page.getByText(/Speichern/i)).toBeInTheDocument(); + }); + + it('progress bar is visible when chunkProgress is provided', async () => { + const { container } = render(UploadSaveBar, { + fileCount: 3, + chunkProgress: { done: 1, total: 3 }, + onSave: vi.fn(), + onDiscard: vi.fn() + }); + const progress = container.querySelector('progress'); + expect(progress).not.toBeNull(); + expect(progress?.getAttribute('value')).toBe('1'); + expect(progress?.getAttribute('max')).toBe('3'); + }); + + it('progress bar is not rendered when no chunkProgress', async () => { + const { container } = render(UploadSaveBar, { + fileCount: 2, + onSave: vi.fn(), + onDiscard: vi.fn() + }); + const progress = container.querySelector('progress'); + expect(progress).toBeNull(); + }); + + it('discard link is rendered', async () => { + render(UploadSaveBar, { fileCount: 2, onSave: vi.fn(), onDiscard: vi.fn() }); + await expect.element(page.getByText(/verwerfen/i)).toBeInTheDocument(); + }); +}); diff --git a/frontend/src/lib/components/document/WhoWhenSection.svelte b/frontend/src/lib/components/document/WhoWhenSection.svelte index b5d85a56..679ecc84 100644 --- a/frontend/src/lib/components/document/WhoWhenSection.svelte +++ b/frontend/src/lib/components/document/WhoWhenSection.svelte @@ -69,8 +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 + class="block w-full rounded border border-line px-2 py-3 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} /> @@ -89,7 +88,6 @@ $effect(() => { bind:value={senderId} initialName={initialSenderName} suggestedName={suggestedSenderName} - autofocus={!!initialDateIso} />
@@ -110,7 +108,7 @@ $effect(() => { name="location" value={initialLocation} placeholder={m.form_placeholder_location()} - 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" + class="block w-full rounded border border-line px-2 py-3 text-sm shadow-sm focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring" />
diff --git a/frontend/src/lib/errors.ts b/frontend/src/lib/errors.ts index d9ec385d..1a1d1551 100644 --- a/frontend/src/lib/errors.ts +++ b/frontend/src/lib/errors.ts @@ -41,6 +41,7 @@ export type ErrorCode = | 'UNAUTHORIZED' | 'FORBIDDEN' | 'VALIDATION_ERROR' + | 'BATCH_TOO_LARGE' | 'INTERNAL_ERROR'; export interface BackendError { @@ -139,6 +140,8 @@ export function getErrorMessage(code: ErrorCode | string | undefined): string { return m.error_forbidden(); case 'VALIDATION_ERROR': return m.error_validation_error(); + case 'BATCH_TOO_LARGE': + return m.error_batch_too_large(); default: return m.error_internal_error(); } diff --git a/frontend/src/lib/generated/api.ts b/frontend/src/lib/generated/api.ts index aafb9c78..3c2e8036 100644 --- a/frontend/src/lib/generated/api.ts +++ b/frontend/src/lib/generated/api.ts @@ -548,6 +548,22 @@ export interface paths { patch?: never; trace?: never; }; + "/api/admin/generate-thumbnails": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + post: operations["generateThumbnails"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/admin/backfill-versions": { parameters: { query?: never; @@ -1028,6 +1044,22 @@ export interface paths { patch?: never; trace?: never; }; + "/api/documents/{id}/thumbnail": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: operations["getDocumentThumbnail"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/documents/{documentId}/transcription-blocks/{blockId}/history": { parameters: { query?: never; @@ -1204,6 +1236,22 @@ export interface paths { patch?: never; trace?: never; }; + "/api/admin/thumbnail-status": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: operations["thumbnailStatus"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/admin/import-status": { parameters: { query?: never; @@ -1390,7 +1438,6 @@ export interface components { thumbnailAspect?: "PORTRAIT" | "LANDSCAPE"; /** Format: int32 */ pageCount?: number; - thumbnailUrl?: string; originalFilename: string; /** @enum {string} */ status: "PLACEHOLDER" | "UPLOADED" | "TRANSCRIBED" | "REVIEWED" | "ARCHIVED"; @@ -1413,6 +1460,7 @@ export interface components { sender?: components["schemas"]["Person"]; tags?: components["schemas"]["Tag"][]; trainingLabels?: ("KURRENT_RECOGNITION" | "KURRENT_SEGMENTATION")[]; + thumbnailUrl?: string; }; UpdateTranscriptionBlockDTO: { text?: string; @@ -1639,6 +1687,17 @@ export interface components { /** Format: date-time */ createdAt: string; }; + DocumentBatchMetadataDTO: { + titles?: string[]; + /** Format: uuid */ + senderId?: string; + receiverIds?: string[]; + /** Format: date */ + documentDate?: string; + location?: string; + tagNames?: string[]; + metadataComplete?: boolean; + }; QuickUploadResult: { created?: components["schemas"]["Document"][]; updated?: components["schemas"]["Document"][]; @@ -1673,6 +1732,21 @@ export interface components { /** Format: date-time */ startedAt?: string; }; + BackfillStatus: { + /** @enum {string} */ + state?: "IDLE" | "RUNNING" | "DONE" | "FAILED"; + message?: string; + /** Format: int32 */ + total?: number; + /** Format: int32 */ + processed?: number; + /** Format: int32 */ + skipped?: number; + /** Format: int32 */ + failed?: number; + /** Format: date-time */ + startedAt?: string; + }; BackfillResult: { /** Format: int32 */ count: number; @@ -1837,10 +1911,10 @@ export interface components { timeout?: number; }; PageNotificationDTO: { - /** Format: int32 */ - totalPages?: number; /** Format: int64 */ totalElements?: number; + /** Format: int32 */ + totalPages?: number; pageable?: components["schemas"]["PageableObject"]; first?: boolean; last?: boolean; @@ -3152,6 +3226,7 @@ export interface operations { content: { "multipart/form-data": { files?: string[]; + metadata?: components["schemas"]["DocumentBatchMetadataDTO"]; }; }; }; @@ -3255,6 +3330,26 @@ export interface operations { }; }; }; + generateThumbnails: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "*/*": components["schemas"]["BackfillStatus"]; + }; + }; + }; + }; backfillVersions: { parameters: { query?: never; @@ -3975,6 +4070,28 @@ export interface operations { }; }; }; + getDocumentThumbnail: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "*/*": string; + }; + }; + }; + }; getBlockHistory: { parameters: { query?: never; @@ -4038,15 +4155,9 @@ export interface operations { dir?: string; /** @description Tag operator: AND (default) or OR */ tagOp?: string; - /** - * @description Page number (0-indexed) - * @default 0 - */ + /** @description Page number (0-indexed) */ page?: number; - /** - * @description Page size (max 100) - * @default 50 - */ + /** @description Page size (max 100) */ size?: number; }; header?: never; @@ -4245,6 +4356,26 @@ export interface operations { }; }; }; + thumbnailStatus: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "*/*": components["schemas"]["BackfillStatus"]; + }; + }; + }; + }; importStatus: { parameters: { query?: never; diff --git a/frontend/src/lib/utils/filename.spec.ts b/frontend/src/lib/utils/filename.spec.ts index 297c8a1e..77b3fbdd 100644 --- a/frontend/src/lib/utils/filename.spec.ts +++ b/frontend/src/lib/utils/filename.spec.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { parseFilename, stripExtension } from './filename'; +import { parseFilename, stripExtension, bulkTitleFromFilename } from './filename'; describe('parseFilename', () => { describe('date-first patterns', () => { @@ -86,6 +86,24 @@ describe('parseFilename', () => { }); }); +describe('bulkTitleFromFilename', () => { + it('replaces underscores with spaces', () => { + expect(bulkTitleFromFilename('hello_world.pdf')).toBe('hello world'); + }); + + it('replaces hyphens with spaces', () => { + expect(bulkTitleFromFilename('2024-01-01_Max.pdf')).toBe('2024 01 01 Max'); + }); + + it('collapses multiple separators', () => { + expect(bulkTitleFromFilename('foo__bar--baz.pdf')).toBe('foo bar baz'); + }); + + it('strips extension', () => { + expect(bulkTitleFromFilename('document.pdf')).toBe('document'); + }); +}); + describe('stripExtension', () => { it('removes the extension', () => { expect(stripExtension('document.pdf')).toBe('document'); diff --git a/frontend/src/lib/utils/filename.ts b/frontend/src/lib/utils/filename.ts index 101fdd1c..582060aa 100644 --- a/frontend/src/lib/utils/filename.ts +++ b/frontend/src/lib/utils/filename.ts @@ -81,3 +81,7 @@ export function parseFilename(filename: string): FilenameParseResult { export function stripExtension(filename: string): string { return filename.replace(/\.[^/.]+$/, ''); } + +export function bulkTitleFromFilename(filename: string): string { + return stripExtension(filename).replace(/[_-]+/g, ' ').trim(); +} diff --git a/frontend/src/routes/documents/new/+page.svelte b/frontend/src/routes/documents/new/+page.svelte index 36da0ec3..c4cb69f8 100644 --- a/frontend/src/routes/documents/new/+page.svelte +++ b/frontend/src/routes/documents/new/+page.svelte @@ -1,154 +1,11 @@ -
- -
- - - - - {m.btn_back_to_overview()} - -

{m.doc_new_heading()}

-
- - {#if form?.error} -
{form.error}
- {/if} - -
- - (parsedSuggestion = r)} /> - - -
- - { - titleOverride = (e.target as HTMLInputElement).value; - titleDirty = true; - }} - 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" - placeholder="Titel eingeben…" - /> -
- - -
- - {m.doc_more_details()} - -
- - - -
-
- - -
-
- - {m.btn_cancel()} - -
- - -
-
-
- -
+ diff --git a/frontend/src/routes/documents/new/page.svelte.spec.ts b/frontend/src/routes/documents/new/page.svelte.spec.ts index dcdfbdef..b22028bf 100644 --- a/frontend/src/routes/documents/new/page.svelte.spec.ts +++ b/frontend/src/routes/documents/new/page.svelte.spec.ts @@ -21,15 +21,14 @@ const baseData = { describe('New document page – sender prefill', () => { it('shows an empty sender input when no senderId is in the URL', async () => { - render(Page, { data: baseData, form: null }); + render(Page, { data: baseData }); const input = document.querySelector('#senderId-search'); expect(input?.value).toBe(''); }); it('shows the sender name in the typeahead input when initialSenderName is set', async () => { render(Page, { - data: { ...baseData, initialSenderId: 'p1', initialSenderName: 'Hans Müller' }, - form: null + data: { ...baseData, initialSenderId: 'p1', initialSenderName: 'Hans Müller' } }); const input = document.querySelector('#senderId-search'); expect(input?.value).toBe('Hans Müller'); @@ -37,8 +36,7 @@ describe('New document page – sender prefill', () => { it('sets the hidden senderId input to the prefilled ID', async () => { render(Page, { - data: { ...baseData, initialSenderId: 'p1', initialSenderName: 'Hans Müller' }, - form: null + data: { ...baseData, initialSenderId: 'p1', initialSenderName: 'Hans Müller' } }); const hidden = document.querySelector( 'input[type="hidden"][name="senderId"]' @@ -51,7 +49,7 @@ describe('New document page – sender prefill', () => { describe('New document page – receiver prefill', () => { it('shows no receiver chips when initialReceivers is empty', async () => { - render(Page, { data: baseData, form: null }); + render(Page, { data: baseData }); await expect.element(page.getByText('Anna Schmidt')).not.toBeInTheDocument(); }); @@ -62,7 +60,7 @@ describe('New document page – receiver prefill', () => { { id: 'p2', firstName: 'Anna', lastName: 'Schmidt', displayName: 'Anna Schmidt' } ] }; - render(Page, { data, form: null }); + render(Page, { data }); await expect.element(page.getByText('Anna Schmidt')).toBeInTheDocument(); }); @@ -73,7 +71,7 @@ describe('New document page – receiver prefill', () => { { id: 'p2', firstName: 'Anna', lastName: 'Schmidt', displayName: 'Anna Schmidt' } ] }; - render(Page, { data, form: null }); + render(Page, { data }); const hidden = document.querySelector('input[name="receiverIds"]'); expect(hidden?.value).toBe('p2'); });