Compare commits
46 Commits
582191d014
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
33c738db3b | ||
|
|
62c807b7fe | ||
|
|
82f0f7b82c | ||
|
|
4994d28a20 | ||
|
|
15d91da174 | ||
|
|
ae6d7a5467 | ||
|
|
24a398a0d8 | ||
|
|
e2632a556d | ||
|
|
be741ff9a2 | ||
|
|
4995c3139e | ||
|
|
0a5d4fb950 | ||
|
|
e4303baa40 | ||
|
|
46c8d4553b | ||
|
|
3fc0ec95ef | ||
|
|
510fa5e398 | ||
|
|
75453bed51 | ||
|
|
78e3acaeb7 | ||
|
|
0f4c844002 | ||
|
|
4dba268a04 | ||
|
|
b0cf35cf06 | ||
|
|
0d934a1b44 | ||
|
|
f4bda546a0 | ||
|
|
b7744667f2 | ||
|
|
3d36c26226 | ||
|
|
375fd3893c | ||
|
|
c5d482bead | ||
|
|
31eacb6d06 | ||
|
|
636900110a | ||
|
|
d78ee4397b | ||
|
|
ebdb36b7d0 | ||
|
|
93ff6cfb67 | ||
|
|
ed4c4a52eb | ||
|
|
2ca8428be4 | ||
|
|
6fffc06c28 | ||
|
|
ffcb901376 | ||
|
|
30469e74c9 | ||
|
|
5646e739c2 | ||
|
|
bbbdf8cd09 | ||
|
|
f727429699 | ||
|
|
e268e2dbca | ||
|
|
3de0d2f0fe | ||
|
|
0abbc147e2 | ||
|
|
6210480952 | ||
|
|
e17f4110f1 | ||
|
|
fa46492759 | ||
|
|
3965541879 |
@@ -2,6 +2,7 @@ name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
@@ -32,6 +33,10 @@ jobs:
|
||||
run: npx @inlang/paraglide-js compile --project ./project.inlang --outdir ./src/lib/paraglide
|
||||
working-directory: frontend
|
||||
|
||||
- name: Sync SvelteKit
|
||||
run: npx svelte-kit sync
|
||||
working-directory: frontend
|
||||
|
||||
- name: Lint
|
||||
run: npm run lint
|
||||
working-directory: frontend
|
||||
@@ -56,6 +61,26 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Assert no (upload|download)-artifact past v3
|
||||
shell: bash
|
||||
run: |
|
||||
# Self-test: verify the regex catches v4+ and does not catch v3.
|
||||
tmp=$(mktemp)
|
||||
printf ' uses: actions/upload-artifact@v5\n' > "$tmp"
|
||||
grep -qP '^\s+uses:\s+actions/(upload|download)-artifact@v[4-9]' "$tmp" \
|
||||
|| { echo "FAIL: guard self-test — regex missed upload-artifact@v5"; rm "$tmp"; exit 1; }
|
||||
printf ' uses: actions/upload-artifact@v3\n' > "$tmp"
|
||||
grep -qvP '^\s+uses:\s+actions/(upload|download)-artifact@v[4-9]' "$tmp" \
|
||||
|| { echo "FAIL: guard self-test — regex incorrectly flagged upload-artifact@v3"; rm "$tmp"; exit 1; }
|
||||
rm "$tmp"
|
||||
# Guard: Gitea Actions (act_runner) does not implement the v4 artifact protocol.
|
||||
# Both upload-artifact and download-artifact share the same incompatibility.
|
||||
# Pin to @v3. See ADR-014 / #557.
|
||||
if grep -RPn '^\s+uses:\s+actions/(upload|download)-artifact@v[4-9]' .gitea/workflows/; then
|
||||
echo "::error::actions/(upload|download)-artifact@v4+ is unsupported on Gitea Actions (act_runner). Pin to @v3. See ADR-014 / #557."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Run unit and component tests with coverage
|
||||
shell: bash
|
||||
run: |
|
||||
@@ -77,9 +102,10 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Gitea Actions (act_runner) does not implement upload-artifact v4 protocol — pinned per ADR-014. Do NOT upgrade. See #557.
|
||||
- name: Upload coverage reports
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: coverage-reports
|
||||
path: |
|
||||
@@ -113,9 +139,10 @@ jobs:
|
||||
|| { echo "FAIL: /hilfe/transkription.html missing from prerender output"; exit 1; }
|
||||
echo "PASS: only /hilfe/transkription.html prerendered."
|
||||
|
||||
# Gitea Actions (act_runner) does not implement upload-artifact v4 protocol — pinned per ADR-014. Do NOT upgrade. See #557.
|
||||
- name: Upload screenshots
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: unit-test-screenshots
|
||||
path: frontend/test-results/screenshots/
|
||||
@@ -170,6 +197,14 @@ jobs:
|
||||
./mvnw clean test
|
||||
working-directory: backend
|
||||
|
||||
- name: Upload surefire reports
|
||||
if: always()
|
||||
# Gitea Actions (act_runner) does not implement upload-artifact v4 protocol — pinned per ADR-014. Do NOT upgrade. See #557.
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: surefire-reports
|
||||
path: backend/target/surefire-reports/
|
||||
|
||||
# ─── fail2ban Regex Regression ────────────────────────────────────────────────
|
||||
# The filter parses Caddy's JSON access log; a Caddy upgrade that reorders
|
||||
# the JSON keys would silently break it (fail2ban-regex would return
|
||||
@@ -269,6 +304,7 @@ jobs:
|
||||
MAIL_HOST=mailpit
|
||||
MAIL_PORT=1025
|
||||
APP_MAIL_FROM=noreply@local
|
||||
IMPORT_HOST_DIR=/tmp/dummy-import
|
||||
EOF
|
||||
|
||||
- name: Bring up minio
|
||||
|
||||
@@ -56,9 +56,10 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Gitea Actions (act_runner) does not implement upload-artifact v4 protocol — pinned per ADR-014. Do NOT upgrade. See #557.
|
||||
- name: Upload coverage log on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: coverage-log-run-${{ matrix.run }}
|
||||
path: /tmp/coverage-test-${{ github.run_id }}-${{ matrix.run }}.log
|
||||
|
||||
@@ -159,7 +159,7 @@ Input DTOs live flat in the domain package. Response types are the model entitie
|
||||
|
||||
→ See [CONTRIBUTING.md §Error handling](./CONTRIBUTING.md#error-handling)
|
||||
|
||||
**LLM reminder:** use `DomainException.notFound/forbidden/conflict/internal()` from service methods — never throw raw exceptions. When adding a new `ErrorCode`: (1) add to `ErrorCode.java`, (2) mirror in `frontend/src/lib/shared/errors.ts`, (3) add i18n keys in `messages/{de,en,es}.json`.
|
||||
**LLM reminder:** use `DomainException.notFound/forbidden/conflict/internal()` from service methods — never throw raw exceptions. When adding a new `ErrorCode`: (1) add to `ErrorCode.java`, (2) add to `ErrorCode` type in `frontend/src/lib/shared/errors.ts`, (3) add a `case` in `getErrorMessage()`, (4) add i18n keys in `messages/{de,en,es}.json`.
|
||||
|
||||
### Security / Permissions
|
||||
|
||||
|
||||
@@ -273,6 +273,16 @@
|
||||
</profiles>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<forkedProcessTimeoutInSeconds>600</forkedProcessTimeoutInSeconds>
|
||||
<systemPropertyVariables>
|
||||
<junit.jupiter.execution.timeout.default>90 s</junit.jupiter.execution.timeout.default>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
@@ -30,6 +30,8 @@ public enum ErrorCode {
|
||||
// --- Users ---
|
||||
/** A user with the given ID or username does not exist. 404 */
|
||||
USER_NOT_FOUND,
|
||||
/** A group with the given ID does not exist. 404 */
|
||||
GROUP_NOT_FOUND,
|
||||
/** The supplied email address is already used by another account. 409 */
|
||||
EMAIL_ALREADY_IN_USE,
|
||||
/** The supplied current password does not match the stored hash. 400 */
|
||||
@@ -52,6 +54,8 @@ public enum ErrorCode {
|
||||
INVITE_REVOKED,
|
||||
/** The invite has passed its expiry date. 410 */
|
||||
INVITE_EXPIRED,
|
||||
/** A group cannot be deleted because one or more active invites reference it. 409 */
|
||||
GROUP_HAS_ACTIVE_INVITES,
|
||||
|
||||
// --- Auth ---
|
||||
/** The request is not authenticated. 401 */
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package org.raddatz.familienarchiv.importing;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
@@ -52,9 +53,9 @@ public class MassImportService {
|
||||
|
||||
public enum State { IDLE, RUNNING, DONE, FAILED }
|
||||
|
||||
public record ImportStatus(State state, String message, int processed, LocalDateTime startedAt) {}
|
||||
public record ImportStatus(State state, String statusCode, @JsonIgnore String message, int processed, LocalDateTime startedAt) {}
|
||||
|
||||
private volatile ImportStatus currentStatus = new ImportStatus(State.IDLE, "Kein Import gestartet.", 0, null);
|
||||
private volatile ImportStatus currentStatus = new ImportStatus(State.IDLE, "IMPORT_IDLE", "Kein Import gestartet.", 0, null);
|
||||
|
||||
public ImportStatus getStatus() {
|
||||
return currentStatus;
|
||||
@@ -116,20 +117,29 @@ public class MassImportService {
|
||||
if (currentStatus.state() == State.RUNNING) {
|
||||
throw DomainException.conflict(ErrorCode.IMPORT_ALREADY_RUNNING, "A mass import is already in progress");
|
||||
}
|
||||
currentStatus = new ImportStatus(State.RUNNING, "Import läuft...", 0, LocalDateTime.now());
|
||||
currentStatus = new ImportStatus(State.RUNNING, "IMPORT_RUNNING", "Import läuft...", 0, LocalDateTime.now());
|
||||
try {
|
||||
File spreadsheet = findSpreadsheetFile();
|
||||
log.info("Starte Massenimport aus: {}", spreadsheet.getAbsolutePath());
|
||||
int processed = processRows(readSpreadsheet(spreadsheet));
|
||||
currentStatus = new ImportStatus(State.DONE,
|
||||
currentStatus = new ImportStatus(State.DONE, "IMPORT_DONE",
|
||||
"Import abgeschlossen. " + processed + " Dokumente verarbeitet.",
|
||||
processed, currentStatus.startedAt());
|
||||
} catch (NoSpreadsheetException e) {
|
||||
log.error("Massenimport fehlgeschlagen: keine Tabellendatei", e);
|
||||
currentStatus = new ImportStatus(State.FAILED, "IMPORT_FAILED_NO_SPREADSHEET",
|
||||
"Fehler: " + e.getMessage(), 0, currentStatus.startedAt());
|
||||
} catch (Exception e) {
|
||||
log.error("Massenimport fehlgeschlagen", e);
|
||||
currentStatus = new ImportStatus(State.FAILED, "Fehler: " + e.getMessage(), 0, currentStatus.startedAt());
|
||||
currentStatus = new ImportStatus(State.FAILED, "IMPORT_FAILED_INTERNAL",
|
||||
"Fehler: " + e.getMessage(), 0, currentStatus.startedAt());
|
||||
}
|
||||
}
|
||||
|
||||
private static class NoSpreadsheetException extends RuntimeException {
|
||||
NoSpreadsheetException(String message) { super(message); }
|
||||
}
|
||||
|
||||
private File findSpreadsheetFile() throws IOException {
|
||||
try (Stream<Path> files = Files.list(Paths.get(importDir))) {
|
||||
return files
|
||||
@@ -138,7 +148,7 @@ public class MassImportService {
|
||||
return name.endsWith(".ods") || name.endsWith(".xlsx") || name.endsWith(".xls");
|
||||
})
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new RuntimeException(
|
||||
.orElseThrow(() -> new NoSpreadsheetException(
|
||||
"Keine Tabellendatei (.ods/.xlsx/.xls) in " + importDir + " gefunden!"))
|
||||
.toFile();
|
||||
}
|
||||
|
||||
@@ -52,7 +52,11 @@ public class InviteService {
|
||||
public InviteToken createInvite(CreateInviteRequest dto, AppUser creator) {
|
||||
Set<UUID> groupIds = new HashSet<>();
|
||||
if (dto.getGroupIds() != null && !dto.getGroupIds().isEmpty()) {
|
||||
List<UserGroup> groups = userService.findGroupsByIds(dto.getGroupIds());
|
||||
Set<UUID> uniqueIds = new HashSet<>(dto.getGroupIds());
|
||||
List<UserGroup> groups = userService.findGroupsByIds(new ArrayList<>(uniqueIds));
|
||||
if (groups.size() != uniqueIds.size()) {
|
||||
throw DomainException.notFound(ErrorCode.GROUP_NOT_FOUND, "One or more group IDs do not exist");
|
||||
}
|
||||
groups.forEach(g -> groupIds.add(g.getId()));
|
||||
}
|
||||
|
||||
|
||||
@@ -24,4 +24,7 @@ public interface InviteTokenRepository extends JpaRepository<InviteToken, UUID>
|
||||
|
||||
@Query("SELECT t FROM InviteToken t ORDER BY t.createdAt DESC")
|
||||
List<InviteToken> findAllOrderedByCreatedAt();
|
||||
|
||||
@Query("SELECT CASE WHEN COUNT(t) > 0 THEN true ELSE false END FROM InviteToken t JOIN t.groupIds g WHERE g = :groupId AND t.revoked = false AND (t.expiresAt IS NULL OR t.expiresAt > CURRENT_TIMESTAMP) AND (t.maxUses IS NULL OR t.useCount < t.maxUses)")
|
||||
boolean existsActiveWithGroupId(@Param("groupId") UUID groupId);
|
||||
}
|
||||
|
||||
@@ -37,6 +37,9 @@ public class UserService {
|
||||
|
||||
private final AppUserRepository userRepository;
|
||||
private final UserGroupRepository groupRepository;
|
||||
// Injected directly (not via InviteService) to avoid a constructor injection cycle:
|
||||
// InviteService → UserService → InviteService. Spring Framework 7 forbids such cycles.
|
||||
private final InviteTokenRepository inviteTokenRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final AuditService auditService;
|
||||
|
||||
@@ -288,6 +291,10 @@ public class UserService {
|
||||
|
||||
@Transactional
|
||||
public void deleteGroup(UUID id) {
|
||||
if (inviteTokenRepository.existsActiveWithGroupId(id)) {
|
||||
throw DomainException.conflict(ErrorCode.GROUP_HAS_ACTIVE_INVITES,
|
||||
"Cannot delete group " + id + " — referenced by one or more active invites");
|
||||
}
|
||||
groupRepository.deleteById(id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
-- The composite PK (invite_token_id, group_id) does not support efficient lookups by group_id alone.
|
||||
-- Add a dedicated index to support existsActiveWithGroupId queries.
|
||||
CREATE INDEX idx_itg_group_id ON invite_token_group_ids (group_id);
|
||||
@@ -20,7 +20,10 @@ import software.amazon.awssdk.core.sync.RequestBody;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
|
||||
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.LocalDate;
|
||||
@@ -70,14 +73,20 @@ class MassImportServiceTest {
|
||||
assertThat(service.getStatus().state()).isEqualTo(MassImportService.State.IDLE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getStatus_hasStatusCode_IMPORT_IDLE_byDefault() {
|
||||
assertThat(service.getStatus().statusCode()).isEqualTo("IMPORT_IDLE");
|
||||
}
|
||||
|
||||
// ─── runImportAsync ───────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void runImportAsync_setsFailedStatus_whenImportDirectoryDoesNotExist() {
|
||||
// /import directory doesn't exist in test environment → findSpreadsheetFile throws
|
||||
// /import directory doesn't exist in test environment → IOException → IMPORT_FAILED_INTERNAL
|
||||
service.runImportAsync();
|
||||
|
||||
assertThat(service.getStatus().state()).isEqualTo(MassImportService.State.FAILED);
|
||||
assertThat(service.getStatus().statusCode()).isEqualTo("IMPORT_FAILED_INTERNAL");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -93,10 +102,35 @@ class MassImportServiceTest {
|
||||
assertThat(service.getStatus().message()).contains(tempDir.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void runImportAsync_setsStatusCode_IMPORT_FAILED_NO_SPREADSHEET_whenDirIsEmpty(@TempDir Path tempDir) {
|
||||
ReflectionTestUtils.setField(service, "importDir", tempDir.toString());
|
||||
|
||||
service.runImportAsync();
|
||||
|
||||
assertThat(service.getStatus().statusCode()).isEqualTo("IMPORT_FAILED_NO_SPREADSHEET");
|
||||
}
|
||||
|
||||
@Test
|
||||
void runImportAsync_setsStatusCode_IMPORT_DONE_whenSpreadsheetHasNoDataRows(@TempDir Path tempDir) throws Exception {
|
||||
Path xlsx = tempDir.resolve("import.xlsx");
|
||||
try (XSSFWorkbook wb = new XSSFWorkbook()) {
|
||||
wb.createSheet("Sheet1");
|
||||
try (OutputStream out = Files.newOutputStream(xlsx)) {
|
||||
wb.write(out);
|
||||
}
|
||||
}
|
||||
ReflectionTestUtils.setField(service, "importDir", tempDir.toString());
|
||||
|
||||
service.runImportAsync();
|
||||
|
||||
assertThat(service.getStatus().statusCode()).isEqualTo("IMPORT_DONE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void runImportAsync_throwsConflict_whenAlreadyRunning() {
|
||||
MassImportService.ImportStatus running = new MassImportService.ImportStatus(
|
||||
MassImportService.State.RUNNING, "Running...", 0, LocalDateTime.now());
|
||||
MassImportService.State.RUNNING, "IMPORT_RUNNING", "Running...", 0, LocalDateTime.now());
|
||||
ReflectionTestUtils.setField(service, "currentStatus", running);
|
||||
|
||||
assertThatThrownBy(() -> service.runImportAsync())
|
||||
|
||||
@@ -40,6 +40,47 @@ class AdminControllerTest {
|
||||
@MockitoBean ThumbnailBackfillService thumbnailBackfillService;
|
||||
@MockitoBean CustomUserDetailsService customUserDetailsService;
|
||||
|
||||
// ─── GET /api/admin/import-status ─────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
@WithMockUser(authorities = "ADMIN")
|
||||
void importStatus_returns200_withStatusCode_whenAdmin() throws Exception {
|
||||
MassImportService.ImportStatus status = new MassImportService.ImportStatus(
|
||||
MassImportService.State.IDLE, "IMPORT_IDLE", "Kein Import gestartet.", 0, null);
|
||||
when(massImportService.getStatus()).thenReturn(status);
|
||||
|
||||
mockMvc.perform(get("/api/admin/import-status"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.state").value("IDLE"))
|
||||
.andExpect(jsonPath("$.statusCode").value("IMPORT_IDLE"))
|
||||
.andExpect(jsonPath("$.processed").value(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(authorities = "ADMIN")
|
||||
void importStatus_messageField_notPresentInApiResponse() throws Exception {
|
||||
MassImportService.ImportStatus status = new MassImportService.ImportStatus(
|
||||
MassImportService.State.IDLE, "IMPORT_IDLE", "Kein Import gestartet.", 0, null);
|
||||
when(massImportService.getStatus()).thenReturn(status);
|
||||
|
||||
mockMvc.perform(get("/api/admin/import-status"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.message").doesNotExist());
|
||||
}
|
||||
|
||||
@Test
|
||||
void importStatus_returns401_whenUnauthenticated() throws Exception {
|
||||
mockMvc.perform(get("/api/admin/import-status"))
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(authorities = "READ_ALL")
|
||||
void importStatus_returns403_whenUserLacksAdminPermission() throws Exception {
|
||||
mockMvc.perform(get("/api/admin/import-status"))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
void backfillVersions_returns401_whenUnauthenticated() throws Exception {
|
||||
mockMvc.perform(post("/api/admin/backfill-versions"))
|
||||
|
||||
@@ -20,10 +20,13 @@ import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -147,6 +150,30 @@ class InviteControllerTest {
|
||||
.andExpect(jsonPath("$.label").value("Für Familie"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "admin@test.com", authorities = {"ADMIN_USER"})
|
||||
void createInvite_forwardsGroupIdsToService() throws Exception {
|
||||
UUID groupId = UUID.randomUUID();
|
||||
AppUser admin = AppUser.builder().id(UUID.randomUUID()).email("admin@test.com").build();
|
||||
when(userService.findByEmail("admin@test.com")).thenReturn(admin);
|
||||
|
||||
InviteToken savedToken = InviteToken.builder()
|
||||
.id(UUID.randomUUID()).code("ABCDE12345").useCount(0).build();
|
||||
when(inviteService.createInvite(any(), eq(admin))).thenReturn(savedToken);
|
||||
when(inviteService.toListItemDTO(any(), anyString()))
|
||||
.thenReturn(makeInviteDTO(savedToken.getId(), "ABCDE12345"));
|
||||
|
||||
String body = "{\"groupIds\":[\"" + groupId + "\"]}";
|
||||
mockMvc.perform(post("/api/invites")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(body))
|
||||
.andExpect(status().isCreated());
|
||||
|
||||
ArgumentCaptor<CreateInviteRequest> captor = ArgumentCaptor.forClass(CreateInviteRequest.class);
|
||||
verify(inviteService).createInvite(captor.capture(), eq(admin));
|
||||
assertThat(captor.getValue().getGroupIds()).containsExactly(groupId);
|
||||
}
|
||||
|
||||
// ─── DELETE /api/invites/{id} ─────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
|
||||
@@ -156,6 +156,35 @@ class InviteServiceTest {
|
||||
assertThat(result.getGroupIds()).contains(g.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createInvite_throwsGroupNotFound_whenSubmittedGroupIdDoesNotExist() {
|
||||
UUID unknownGroupId = UUID.randomUUID();
|
||||
when(userService.findGroupsByIds(anyList())).thenReturn(List.of());
|
||||
|
||||
CreateInviteRequest req = new CreateInviteRequest();
|
||||
req.setGroupIds(List.of(unknownGroupId));
|
||||
|
||||
assertThatThrownBy(() -> inviteService.createInvite(req, admin))
|
||||
.isInstanceOf(DomainException.class)
|
||||
.extracting(e -> ((DomainException) e).getCode())
|
||||
.isEqualTo(ErrorCode.GROUP_NOT_FOUND);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createInvite_doesNotThrowGroupNotFound_whenDuplicateGroupIdsSubmitted() {
|
||||
UUID groupId = UUID.randomUUID();
|
||||
UserGroup group = UserGroup.builder().id(groupId).name("Familie").build();
|
||||
when(inviteTokenRepository.findByCode(anyString())).thenReturn(Optional.empty());
|
||||
when(userService.findGroupsByIds(anyList())).thenReturn(List.of(group));
|
||||
when(inviteTokenRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
CreateInviteRequest req = new CreateInviteRequest();
|
||||
req.setGroupIds(List.of(groupId, groupId)); // same UUID submitted twice
|
||||
|
||||
// before deduplication: size(groups)==1 != size(submitted)==2 → false GROUP_NOT_FOUND
|
||||
assertThatCode(() -> inviteService.createInvite(req, admin)).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
// ─── redeemInvite ─────────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package org.raddatz.familienarchiv.user;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.raddatz.familienarchiv.PostgresContainerConfig;
|
||||
import org.raddatz.familienarchiv.config.FlywayConfig;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabase;
|
||||
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@DataJpaTest
|
||||
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
|
||||
@Import({PostgresContainerConfig.class, FlywayConfig.class})
|
||||
class InviteTokenRepositoryIntegrationTest {
|
||||
|
||||
@Autowired InviteTokenRepository inviteTokenRepository;
|
||||
@Autowired UserGroupRepository userGroupRepository;
|
||||
@Autowired AppUserRepository appUserRepository;
|
||||
|
||||
private UserGroup group;
|
||||
private AppUser admin;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
inviteTokenRepository.deleteAll();
|
||||
userGroupRepository.deleteAll();
|
||||
appUserRepository.deleteAll();
|
||||
admin = appUserRepository.save(AppUser.builder().email("admin@test.com").password("pw").build());
|
||||
group = userGroupRepository.save(UserGroup.builder().name("Familie").build());
|
||||
}
|
||||
|
||||
// ─── existsActiveWithGroupId ──────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void existsActiveWithGroupId_returnsTrueForActiveInviteLinkedToGroup() {
|
||||
inviteTokenRepository.save(token(t -> t));
|
||||
|
||||
assertThat(inviteTokenRepository.existsActiveWithGroupId(group.getId())).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void existsActiveWithGroupId_returnsFalseWhenInviteIsRevoked() {
|
||||
inviteTokenRepository.save(token(t -> t.revoked(true)));
|
||||
|
||||
assertThat(inviteTokenRepository.existsActiveWithGroupId(group.getId())).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void existsActiveWithGroupId_returnsFalseWhenInviteIsExpired() {
|
||||
inviteTokenRepository.save(token(t -> t.expiresAt(LocalDateTime.now().minusDays(1))));
|
||||
|
||||
assertThat(inviteTokenRepository.existsActiveWithGroupId(group.getId())).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void existsActiveWithGroupId_returnsFalseWhenInviteIsExhausted() {
|
||||
inviteTokenRepository.save(token(t -> t.maxUses(1).useCount(1)));
|
||||
|
||||
assertThat(inviteTokenRepository.existsActiveWithGroupId(group.getId())).isFalse();
|
||||
}
|
||||
|
||||
// ─── helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
private InviteToken token(java.util.function.UnaryOperator<InviteToken.InviteTokenBuilder> customizer) {
|
||||
InviteToken.InviteTokenBuilder builder = InviteToken.builder()
|
||||
.code(UUID.randomUUID().toString().replace("-", "").substring(0, 10))
|
||||
.groupIds(new java.util.HashSet<>(Set.of(group.getId())))
|
||||
.createdBy(admin);
|
||||
return customizer.apply(builder).build();
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,7 @@ class UserServiceTest {
|
||||
|
||||
@Mock AppUserRepository userRepository;
|
||||
@Mock UserGroupRepository groupRepository;
|
||||
@Mock InviteTokenRepository inviteTokenRepository;
|
||||
@Mock PasswordEncoder passwordEncoder;
|
||||
@Mock AuditService auditService;
|
||||
@InjectMocks UserService userService;
|
||||
@@ -903,6 +904,29 @@ class UserServiceTest {
|
||||
assertThat(result.getPermissions()).containsExactlyInAnyOrder("READ_ALL", "WRITE_ALL");
|
||||
}
|
||||
|
||||
// ─── deleteGroup ──────────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void deleteGroup_throwsConflict_whenActiveInviteReferencesGroup() {
|
||||
UUID groupId = UUID.randomUUID();
|
||||
when(inviteTokenRepository.existsActiveWithGroupId(groupId)).thenReturn(true);
|
||||
|
||||
assertThatThrownBy(() -> userService.deleteGroup(groupId))
|
||||
.isInstanceOf(DomainException.class)
|
||||
.extracting(e -> ((DomainException) e).getCode())
|
||||
.isEqualTo(ErrorCode.GROUP_HAS_ACTIVE_INVITES);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteGroup_deletesGroup_whenNoActiveInviteReferencesGroup() {
|
||||
UUID groupId = UUID.randomUUID();
|
||||
when(inviteTokenRepository.existsActiveWithGroupId(groupId)).thenReturn(false);
|
||||
|
||||
userService.deleteGroup(groupId);
|
||||
|
||||
verify(groupRepository).deleteById(groupId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createGroup_withNullPermissions_savesGroupWithEmptyPermissionSet() {
|
||||
org.raddatz.familienarchiv.user.GroupDTO dto = new org.raddatz.familienarchiv.user.GroupDTO();
|
||||
|
||||
2
backend/src/test/resources/application.properties
Normal file
2
backend/src/test/resources/application.properties
Normal file
@@ -0,0 +1,2 @@
|
||||
logging.level.root=WARN
|
||||
logging.level.org.raddatz=INFO
|
||||
@@ -63,7 +63,7 @@ Members of the cross-cutting layer have no entity of their own, no user-facing C
|
||||
| `audit` | Append-only event store (`audit_log`) for all domain mutations. Feeds the activity feed and Family Pulse dashboard. | Consumed by 5+ domains; no user-facing CRUD of its own |
|
||||
| `config` | Infrastructure bean definitions: `MinioConfig`, `AsyncConfig`, `WebConfig` | Framework infra; no business logic |
|
||||
| `dashboard` | Stats aggregation for the admin dashboard and Family Pulse widget | Aggregates from 3+ domains; no owned entities |
|
||||
| `exception` | `DomainException`, `ErrorCode` enum, `GlobalExceptionHandler` | Framework infra; consumed by every controller and service |
|
||||
| `exception` | `DomainException`, `ErrorCode` enum, `GlobalExceptionHandler` | Framework infra; consumed by every controller and service. Adding a new `ErrorCode` requires matching updates in `frontend/src/lib/shared/errors.ts` and all three `messages/*.json` locale files. |
|
||||
| `filestorage` | `FileService` — MinIO/S3 upload, download, presigned-URL generation | Generic service; consumed by `document` and `ocr` |
|
||||
| `importing` | `MassImportService` — async ODS/Excel batch import | Orchestrates across `person`, `tag`, `document` |
|
||||
| `security` | `SecurityConfig`, `Permission` enum, `@RequirePermission` annotation, `PermissionAspect` (AOP) | Framework infra; enforced globally across all controllers |
|
||||
|
||||
122
docs/adr/014-upload-artifact-v3-pin.md
Normal file
122
docs/adr/014-upload-artifact-v3-pin.md
Normal file
@@ -0,0 +1,122 @@
|
||||
# ADR 014 — Pin actions/upload-artifact to v3 (Gitea act_runner v4 protocol incompatibility)
|
||||
|
||||
**Status:** Accepted
|
||||
**Date:** 2026-05-14
|
||||
**Issues:** [#557 — re-regression](https://git.raddatz.cloud/marcel/familienarchiv/issues/557) · [#14 — original incident](https://git.raddatz.cloud/marcel/familienarchiv/issues/14)
|
||||
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
`actions/upload-artifact` is available in two incompatible major versions. The v4 client
|
||||
uploads via a GitHub-specific artifact API that is **not implemented** in Gitea's
|
||||
`act_runner` (the self-hosted CI substrate established by ADR-011). When a workflow step
|
||||
uses `actions/upload-artifact@v4` on this runner, `act_runner` returns a non-zero exit
|
||||
code from the v4 client even when all tests pass, producing:
|
||||
|
||||
> green test suite — red job status — no artifact uploaded
|
||||
|
||||
The failure lands in the upload step, _after_ the test output, making it hard to diagnose
|
||||
from the build log.
|
||||
|
||||
### Incident history
|
||||
|
||||
| Date | Commit | Event |
|
||||
|---|---|---|
|
||||
| 2026-03-19 | `9f3f022e` | Original downgrade: `upload-artifact@v4 → v3` |
|
||||
| 2026-03-19 | `4142c7cd` | Rationale committed; closes #14 |
|
||||
| 2026-05-05 | `410b91e2` | Re-regression: upgraded back to v4 without referencing #14 |
|
||||
| 2026-05-14 | this PR | Second downgrade + ADR + grep guard |
|
||||
|
||||
The root cause of the re-regression was institutional-memory failure: the original
|
||||
rationale was captured only in a commit body, invisible at the point of change (the
|
||||
`uses:` line). This ADR, the inline comments, and the grep guard are the three
|
||||
defence layers that replace that missing breadcrumb.
|
||||
|
||||
---
|
||||
|
||||
## Decision
|
||||
|
||||
**Pin all `actions/upload-artifact` and `actions/download-artifact` call sites to `@v3`.**
|
||||
|
||||
Both action families share the same v4 protocol incompatibility with `act_runner`.
|
||||
Pinning to the major tag (`@v3`) keeps us on the latest v3 patch without Renovate noise.
|
||||
|
||||
Three call sites are pinned:
|
||||
- `.gitea/workflows/ci.yml` — "Upload coverage reports" step
|
||||
- `.gitea/workflows/ci.yml` — "Upload screenshots" step
|
||||
- `.gitea/workflows/coverage-flake-probe.yml` — "Upload coverage log on failure" step
|
||||
|
||||
Each pinned `uses:` line carries a load-bearing inline comment:
|
||||
|
||||
```yaml
|
||||
# Gitea Actions (act_runner) does not implement upload-artifact v4 protocol — pinned per ADR-014. Do NOT upgrade. See #557.
|
||||
- uses: actions/upload-artifact@v3
|
||||
```
|
||||
|
||||
A CI grep guard enforces the constraint automatically (see below).
|
||||
|
||||
---
|
||||
|
||||
## Consequences
|
||||
|
||||
### Enforcement layers (defence in depth)
|
||||
|
||||
1. **Inline comments** on every `uses:` line — visible at the point of change.
|
||||
2. **CI grep guard** in `.gitea/workflows/ci.yml` ("Assert no (upload|download)-artifact
|
||||
past v3") — fails the build if a future commit re-introduces `@v4` or higher on any
|
||||
workflow file. Anchored to YAML `uses:` lines to avoid false positives on embedded
|
||||
shell strings. Includes a self-test that proves the regex catches v4+ before scanning
|
||||
the repo.
|
||||
3. **This ADR** — canonical rationale; cross-referenced by comments and guard message.
|
||||
|
||||
### How to spot the symptom
|
||||
|
||||
- Test suite output shows green (vitest, surefire, pytest all exit 0)
|
||||
- CI job status shows red
|
||||
- Artifacts section of the run is empty
|
||||
- Build log shows a non-zero exit from the `Upload …` step immediately after green tests
|
||||
|
||||
### `@v3` maintenance-mode status
|
||||
|
||||
GitHub placed `actions/upload-artifact@v3` in maintenance mode (no new features) but it
|
||||
has not been removed and carries no known unpatched CVE as of this writing. If GitHub
|
||||
publishes a v3-specific security advisory, that is an additional trigger to re-evaluate
|
||||
(see upgrade conditions below).
|
||||
|
||||
### When to remove this pin
|
||||
|
||||
Re-evaluate pinning **when either condition is met:**
|
||||
|
||||
1. `gitea/act_runner` ships a release with v4 artifact protocol support. Track upstream:
|
||||
<https://gitea.com/gitea/act_runner>
|
||||
2. `actions/upload-artifact@v3` acquires an unpatched CVE that cannot be mitigated
|
||||
at the runner level.
|
||||
|
||||
When upgrading: remove the grep guard step, update all three `uses:` lines, remove the
|
||||
inline comments, and update this ADR's status to Superseded.
|
||||
|
||||
---
|
||||
|
||||
## Alternatives
|
||||
|
||||
### SHA pinning (`uses: actions/upload-artifact@<sha>`)
|
||||
|
||||
More secure against action repository compromise, but adds Renovate update friction
|
||||
and is disproportionate for a self-hosted, single-tenant Gitea instance with one
|
||||
trusted contributor (ADR-011). Rejected.
|
||||
|
||||
### Minor/patch pinning (`@v3.4.0`)
|
||||
|
||||
Avoids Renovate PRs but freezes us on a specific patch. The v3 major track is in
|
||||
maintenance mode — minor pinning has no benefit and would require manual updates
|
||||
for any v3 security patches. Rejected.
|
||||
|
||||
### Renovate `packageRules` bypass
|
||||
|
||||
Would prevent automated PRs from proposing v4. Not needed while Renovate is not
|
||||
configured for this repository. Revisit if Renovate is introduced.
|
||||
|
||||
### Migrating the runner to a v4-compatible Gitea release
|
||||
|
||||
Out of scope for this issue. A separate decision; tracked in #557's non-goals.
|
||||
@@ -200,7 +200,7 @@ jobs:
|
||||
working-directory: frontend
|
||||
- name: Upload screenshots
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4 # ← upgraded from v3
|
||||
uses: actions/upload-artifact@v3 # pinned per ADR-014 — Gitea Actions does not implement v4 protocol. Do NOT upgrade.
|
||||
with:
|
||||
name: unit-test-screenshots
|
||||
path: frontend/test-results/screenshots/
|
||||
@@ -227,7 +227,7 @@ jobs:
|
||||
working-directory: backend
|
||||
- name: Upload test results
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4 # ← upgraded from v3
|
||||
uses: actions/upload-artifact@v3 # pinned per ADR-014 — Gitea Actions does not implement v4 protocol. Do NOT upgrade.
|
||||
with:
|
||||
name: backend-test-results
|
||||
path: backend/target/surefire-reports/
|
||||
@@ -329,7 +329,7 @@ jobs:
|
||||
E2E_BACKEND_URL: http://localhost:8080
|
||||
- name: Upload E2E results
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4 # ← upgraded from v3
|
||||
uses: actions/upload-artifact@v3 # pinned per ADR-014 — Gitea Actions does not implement v4 protocol. Do NOT upgrade.
|
||||
with:
|
||||
name: e2e-results
|
||||
path: frontend/test-results/e2e/
|
||||
|
||||
@@ -165,7 +165,7 @@ npm run check # svelte-check (type checking)
|
||||
|
||||
```bash
|
||||
npm run test # Vitest unit + server tests (headless)
|
||||
npm run test:coverage # Coverage report (server project only)
|
||||
npm run test:coverage # Coverage report (server + client)
|
||||
npm run test:e2e # Playwright E2E tests
|
||||
npm run test:e2e:headed # Playwright E2E with visible browser
|
||||
npm run test:e2e:ui # Playwright UI mode
|
||||
|
||||
@@ -29,6 +29,6 @@ ENV NODE_ENV=production
|
||||
COPY --from=build /app/build ./build
|
||||
COPY --from=build /app/package.json ./package.json
|
||||
COPY --from=build /app/package-lock.json ./package-lock.json
|
||||
RUN npm ci --omit=dev
|
||||
RUN npm ci --omit=dev --ignore-scripts
|
||||
EXPOSE 3000
|
||||
CMD ["node", "build"]
|
||||
|
||||
@@ -345,8 +345,11 @@
|
||||
"admin_system_import_btn_retry": "Erneut starten",
|
||||
"admin_system_import_status_idle": "Kein Import gestartet.",
|
||||
"admin_system_import_status_running": "Import läuft…",
|
||||
"admin_system_import_status_done": "Import abgeschlossen – {count} Dokumente verarbeitet.",
|
||||
"admin_system_import_status_failed": "Fehler: {message}",
|
||||
"admin_system_import_status_done": "Import abgeschlossen",
|
||||
"admin_system_import_status_done_label": "Dokumente verarbeitet",
|
||||
"admin_system_import_status_failed": "Import fehlgeschlagen",
|
||||
"admin_system_import_failed_no_spreadsheet": "Keine Tabellendatei gefunden.",
|
||||
"admin_system_import_failed_internal": "Interner Fehler beim Import.",
|
||||
"admin_system_thumbnails_heading": "Thumbnails erzeugen",
|
||||
"admin_system_thumbnails_description": "Erzeugt Vorschaubilder für Dokumente ohne Thumbnail (z. B. nach dem Massenimport).",
|
||||
"admin_system_thumbnails_btn_start": "Thumbnails erzeugen",
|
||||
@@ -703,6 +706,8 @@
|
||||
"error_invite_exhausted": "Dieser Einladungslink wurde bereits vollständig verwendet.",
|
||||
"error_invite_revoked": "Dieser Einladungslink wurde deaktiviert.",
|
||||
"error_invite_expired": "Dieser Einladungslink ist abgelaufen.",
|
||||
"error_group_has_active_invites": "Diese Gruppe kann nicht gelöscht werden, da sie in einer aktiven Einladung verwendet wird.",
|
||||
"error_group_not_found": "Die angegebene Gruppe existiert nicht.",
|
||||
"register_heading": "Konto erstellen",
|
||||
"register_subtext": "Du wurdest eingeladen, dem Familienarchiv beizutreten.",
|
||||
"register_label_first_name": "Vorname",
|
||||
@@ -762,6 +767,9 @@
|
||||
"admin_new_invite_prefill_last": "Nachname vorausfüllen (optional)",
|
||||
"admin_new_invite_prefill_email": "E-Mail vorausfüllen (optional)",
|
||||
"admin_new_invite_expires": "Ablaufdatum (optional)",
|
||||
"admin_new_invite_groups": "Gruppen (optional)",
|
||||
"admin_new_invite_no_groups": "Keine Gruppen vorhanden.",
|
||||
"admin_invite_groups_load_error": "Gruppen konnten nicht geladen werden. Die Einladung kann ohne Gruppenauswahl erstellt werden.",
|
||||
"admin_invite_created_title": "Einladung erstellt",
|
||||
"admin_invite_created_desc": "Teile diesen Link mit der einzuladenden Person:",
|
||||
"admin_invite_revoke_confirm": "Einladung wirklich widerrufen?",
|
||||
|
||||
@@ -345,8 +345,11 @@
|
||||
"admin_system_import_btn_retry": "Start again",
|
||||
"admin_system_import_status_idle": "No import started.",
|
||||
"admin_system_import_status_running": "Import running…",
|
||||
"admin_system_import_status_done": "Import complete – {count} documents processed.",
|
||||
"admin_system_import_status_failed": "Error: {message}",
|
||||
"admin_system_import_status_done": "Import complete",
|
||||
"admin_system_import_status_done_label": "Documents processed",
|
||||
"admin_system_import_status_failed": "Import failed",
|
||||
"admin_system_import_failed_no_spreadsheet": "No spreadsheet file found.",
|
||||
"admin_system_import_failed_internal": "Import failed due to an internal error.",
|
||||
"admin_system_thumbnails_heading": "Generate thumbnails",
|
||||
"admin_system_thumbnails_description": "Generates preview images for documents without a thumbnail (e.g. after the mass import).",
|
||||
"admin_system_thumbnails_btn_start": "Generate thumbnails",
|
||||
@@ -703,6 +706,8 @@
|
||||
"error_invite_exhausted": "This invite link has already been fully used.",
|
||||
"error_invite_revoked": "This invite link has been deactivated.",
|
||||
"error_invite_expired": "This invite link has expired.",
|
||||
"error_group_has_active_invites": "This group cannot be deleted because it is referenced by one or more active invite links.",
|
||||
"error_group_not_found": "The specified group does not exist.",
|
||||
"register_heading": "Create account",
|
||||
"register_subtext": "You've been invited to join Familienarchiv.",
|
||||
"register_label_first_name": "First name",
|
||||
@@ -762,6 +767,9 @@
|
||||
"admin_new_invite_prefill_last": "Pre-fill last name (optional)",
|
||||
"admin_new_invite_prefill_email": "Pre-fill email (optional)",
|
||||
"admin_new_invite_expires": "Expiry date (optional)",
|
||||
"admin_new_invite_groups": "Groups (optional)",
|
||||
"admin_new_invite_no_groups": "No groups exist.",
|
||||
"admin_invite_groups_load_error": "Groups could not be loaded. The invite can still be created without group assignment.",
|
||||
"admin_invite_created_title": "Invite created",
|
||||
"admin_invite_created_desc": "Share this link with the person you are inviting:",
|
||||
"admin_invite_revoke_confirm": "Really revoke this invite?",
|
||||
|
||||
@@ -345,8 +345,11 @@
|
||||
"admin_system_import_btn_retry": "Iniciar de nuevo",
|
||||
"admin_system_import_status_idle": "No hay importación iniciada.",
|
||||
"admin_system_import_status_running": "Importación en curso…",
|
||||
"admin_system_import_status_done": "Importación completada – {count} documentos procesados.",
|
||||
"admin_system_import_status_failed": "Error: {message}",
|
||||
"admin_system_import_status_done": "Importación completada",
|
||||
"admin_system_import_status_done_label": "Documentos procesados",
|
||||
"admin_system_import_status_failed": "Importación fallida",
|
||||
"admin_system_import_failed_no_spreadsheet": "No se encontró ninguna hoja de cálculo.",
|
||||
"admin_system_import_failed_internal": "Error interno durante la importación.",
|
||||
"admin_system_thumbnails_heading": "Generar miniaturas",
|
||||
"admin_system_thumbnails_description": "Genera imágenes de vista previa para documentos sin miniatura (p. ej. tras la importación masiva).",
|
||||
"admin_system_thumbnails_btn_start": "Generar miniaturas",
|
||||
@@ -703,6 +706,8 @@
|
||||
"error_invite_exhausted": "Este enlace de invitación ya ha sido completamente utilizado.",
|
||||
"error_invite_revoked": "Este enlace de invitación ha sido desactivado.",
|
||||
"error_invite_expired": "Este enlace de invitación ha expirado.",
|
||||
"error_group_has_active_invites": "Este grupo no puede eliminarse porque está referenciado por uno o más enlaces de invitación activos.",
|
||||
"error_group_not_found": "El grupo especificado no existe.",
|
||||
"register_heading": "Crear cuenta",
|
||||
"register_subtext": "Has sido invitado a unirte al Familienarchiv.",
|
||||
"register_label_first_name": "Nombre",
|
||||
@@ -762,6 +767,9 @@
|
||||
"admin_new_invite_prefill_last": "Prellenar apellido (opcional)",
|
||||
"admin_new_invite_prefill_email": "Prellenar correo (opcional)",
|
||||
"admin_new_invite_expires": "Fecha de vencimiento (opcional)",
|
||||
"admin_new_invite_groups": "Grupos (opcional)",
|
||||
"admin_new_invite_no_groups": "No hay grupos disponibles.",
|
||||
"admin_invite_groups_load_error": "No se pudieron cargar los grupos. La invitación puede crearse sin asignar grupos.",
|
||||
"admin_invite_created_title": "Invitación creada",
|
||||
"admin_invite_created_desc": "Comparte este enlace con la persona invitada:",
|
||||
"admin_invite_revoke_confirm": "¿Realmente revocar esta invitación?",
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
"lint:boundary-demo": "eslint src/lib/tag/__fixtures__/",
|
||||
"test:unit": "vitest",
|
||||
"test": "npm run test:unit -- --run",
|
||||
"test:coverage": "vitest run --coverage --project=server && vitest run -c vitest.client-coverage.config.ts --coverage",
|
||||
"test:coverage": "vitest run --coverage --project=server; vitest run -c vitest.client-coverage.config.ts --coverage",
|
||||
"test:e2e": "playwright test",
|
||||
"test:e2e:headed": "playwright test --headed",
|
||||
"test:e2e:ui": "playwright test --ui",
|
||||
|
||||
@@ -22,6 +22,8 @@ export type ErrorCode =
|
||||
| 'INVITE_EXHAUSTED'
|
||||
| 'INVITE_REVOKED'
|
||||
| 'INVITE_EXPIRED'
|
||||
| 'GROUP_HAS_ACTIVE_INVITES'
|
||||
| 'GROUP_NOT_FOUND'
|
||||
| 'ANNOTATION_NOT_FOUND'
|
||||
| 'ANNOTATION_UPDATE_FAILED'
|
||||
| 'TRANSCRIPTION_BLOCK_NOT_FOUND'
|
||||
@@ -108,6 +110,10 @@ export function getErrorMessage(code: ErrorCode | string | undefined): string {
|
||||
return m.error_invite_revoked();
|
||||
case 'INVITE_EXPIRED':
|
||||
return m.error_invite_expired();
|
||||
case 'GROUP_HAS_ACTIVE_INVITES':
|
||||
return m.error_group_has_active_invites();
|
||||
case 'GROUP_NOT_FOUND':
|
||||
return m.error_group_not_found();
|
||||
case 'ANNOTATION_NOT_FOUND':
|
||||
return m.error_annotation_not_found();
|
||||
case 'ANNOTATION_UPDATE_FAILED':
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { untrack } from 'svelte';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
|
||||
let {
|
||||
groups,
|
||||
selectedGroupIds = []
|
||||
@@ -7,12 +10,13 @@ let {
|
||||
selectedGroupIds?: string[];
|
||||
} = $props();
|
||||
|
||||
let selected = $derived([...selectedGroupIds]);
|
||||
let selected = $state<string[]>(untrack(() => [...selectedGroupIds]));
|
||||
</script>
|
||||
|
||||
<div class="flex flex-wrap gap-3">
|
||||
<fieldset class="flex flex-wrap gap-3 border-none p-0">
|
||||
<legend class="sr-only">{m.admin_new_invite_groups()}</legend>
|
||||
{#each groups as group (group.id)}
|
||||
<label class="inline-flex items-center gap-2 text-sm text-ink-2">
|
||||
<label class="inline-flex min-h-[44px] items-center gap-2 text-sm text-ink-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
name="groupIds"
|
||||
@@ -23,4 +27,4 @@ let selected = $derived([...selectedGroupIds]);
|
||||
{group.name}
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
<script lang="ts">
|
||||
import { enhance } from '$app/forms';
|
||||
import { beforeNavigate, goto } from '$app/navigation';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
import { createUnsavedWarning } from '$lib/shared/hooks/useUnsavedWarning.svelte';
|
||||
import UnsavedWarningBanner from '$lib/shared/primitives/UnsavedWarningBanner.svelte';
|
||||
|
||||
const availableStandard = $derived([
|
||||
{ value: 'READ_ALL', label: m.admin_perm_read_all() },
|
||||
@@ -18,17 +19,7 @@ const availableAdmin = $derived([
|
||||
|
||||
let { form } = $props();
|
||||
|
||||
let isDirty = $state(false);
|
||||
let showUnsavedWarning = $state(false);
|
||||
let discardTarget: string | null = $state(null);
|
||||
|
||||
beforeNavigate(({ cancel, to }) => {
|
||||
if (isDirty) {
|
||||
cancel();
|
||||
showUnsavedWarning = true;
|
||||
discardTarget = to?.url.href ?? null;
|
||||
}
|
||||
});
|
||||
const unsaved = createUnsavedWarning();
|
||||
</script>
|
||||
|
||||
<div class="flex flex-1 flex-col overflow-hidden">
|
||||
@@ -58,23 +49,8 @@ beforeNavigate(({ cancel, to }) => {
|
||||
|
||||
<!-- Scrollable body -->
|
||||
<div class="flex-1 overflow-y-auto px-5 py-5">
|
||||
{#if showUnsavedWarning}
|
||||
<div
|
||||
class="mb-5 flex items-center justify-between rounded border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-300"
|
||||
>
|
||||
<span>{m.admin_unsaved_warning()}</span>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => {
|
||||
isDirty = false;
|
||||
showUnsavedWarning = false;
|
||||
if (discardTarget) goto(discardTarget);
|
||||
}}
|
||||
class="ml-4 shrink-0 font-sans text-xs font-bold tracking-widest text-amber-800 uppercase hover:text-amber-900 dark:text-amber-300"
|
||||
>
|
||||
{m.person_discard_changes()}
|
||||
</button>
|
||||
</div>
|
||||
{#if unsaved.showUnsavedWarning}
|
||||
<UnsavedWarningBanner onDiscard={unsaved.discard} />
|
||||
{/if}
|
||||
{#if form?.error}
|
||||
<div class="mb-5 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700">
|
||||
@@ -85,11 +61,11 @@ beforeNavigate(({ cancel, to }) => {
|
||||
<form
|
||||
id="new-group-form"
|
||||
method="POST"
|
||||
use:enhance
|
||||
oninput={() => {
|
||||
isDirty = true;
|
||||
showUnsavedWarning = false;
|
||||
use:enhance={() => async ({ result, update }) => {
|
||||
if (result.type === 'redirect') unsaved.clearOnSuccess();
|
||||
await update();
|
||||
}}
|
||||
oninput={unsaved.markDirty}
|
||||
class="space-y-5"
|
||||
>
|
||||
<!-- Name card -->
|
||||
|
||||
125
frontend/src/routes/admin/groups/new/page.svelte.spec.ts
Normal file
125
frontend/src/routes/admin/groups/new/page.svelte.spec.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { cleanup, render } from 'vitest-browser-svelte';
|
||||
import { page } from 'vitest/browser';
|
||||
import Page from './+page.svelte';
|
||||
|
||||
const enhanceCaptureRef = vi.hoisted(() => ({ submitFn: undefined as unknown }));
|
||||
|
||||
vi.mock('$app/forms', () => ({
|
||||
enhance: (_el: HTMLFormElement, fn?: unknown) => {
|
||||
enhanceCaptureRef.submitFn = fn;
|
||||
return { destroy: vi.fn() };
|
||||
}
|
||||
}));
|
||||
vi.mock('$app/navigation', () => ({ beforeNavigate: vi.fn(), goto: vi.fn() }));
|
||||
|
||||
import { beforeNavigate, goto } from '$app/navigation';
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
type SubmitFn = () => Promise<
|
||||
(opts: {
|
||||
result: { type: string; [key: string]: unknown };
|
||||
update: () => Promise<void>;
|
||||
}) => Promise<void>
|
||||
>;
|
||||
|
||||
// ─── Unsaved-changes guard ────────────────────────────────────────────────────
|
||||
|
||||
describe('Admin new group page – unsaved-changes guard', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
enhanceCaptureRef.submitFn = undefined;
|
||||
});
|
||||
|
||||
it('does not show unsaved warning initially', async () => {
|
||||
render(Page, { props: { form: null } });
|
||||
await expect.element(page.getByText(/ungespeicherte Änderungen/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('cancels navigation and shows banner when form is dirty', async () => {
|
||||
render(Page, { props: { form: null } });
|
||||
const [callback] = vi.mocked(beforeNavigate).mock.calls[0];
|
||||
|
||||
document
|
||||
.querySelector<HTMLInputElement>('input[name="name"]')!
|
||||
.dispatchEvent(new InputEvent('input', { bubbles: true }));
|
||||
|
||||
const cancel = vi.fn();
|
||||
callback({ cancel, to: { url: new URL('http://localhost/admin/groups') } });
|
||||
|
||||
expect(cancel).toHaveBeenCalled();
|
||||
await expect.element(page.getByText(/ungespeicherte Änderungen/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not cancel navigation when form is clean', async () => {
|
||||
render(Page, { props: { form: null } });
|
||||
const [callback] = vi.mocked(beforeNavigate).mock.calls[0];
|
||||
|
||||
const cancel = vi.fn();
|
||||
callback({ cancel, to: { url: new URL('http://localhost/admin/groups') } });
|
||||
|
||||
expect(cancel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('discard button calls goto with the target URL', async () => {
|
||||
render(Page, { props: { form: null } });
|
||||
const [callback] = vi.mocked(beforeNavigate).mock.calls[0];
|
||||
|
||||
document
|
||||
.querySelector<HTMLInputElement>('input[name="name"]')!
|
||||
.dispatchEvent(new InputEvent('input', { bubbles: true }));
|
||||
|
||||
callback({ cancel: vi.fn(), to: { url: new URL('http://localhost/admin/groups') } });
|
||||
|
||||
await page.getByRole('button', { name: /verwerfen/i }).click();
|
||||
|
||||
expect(vi.mocked(goto)).toHaveBeenCalledWith('http://localhost/admin/groups');
|
||||
});
|
||||
|
||||
it('clears banner when enhance callback receives a redirect result', async () => {
|
||||
render(Page, { props: { form: null } });
|
||||
const [navCallback] = vi.mocked(beforeNavigate).mock.calls[0];
|
||||
|
||||
document
|
||||
.querySelector<HTMLInputElement>('input[name="name"]')!
|
||||
.dispatchEvent(new InputEvent('input', { bubbles: true }));
|
||||
|
||||
navCallback({ cancel: vi.fn(), to: { url: new URL('http://localhost/admin/groups') } });
|
||||
await expect.element(page.getByText(/ungespeicherte Änderungen/i)).toBeInTheDocument();
|
||||
|
||||
const innerFn = await (enhanceCaptureRef.submitFn as SubmitFn)();
|
||||
await innerFn({
|
||||
result: { type: 'redirect', location: '/admin/groups', status: 303 },
|
||||
update: vi.fn().mockResolvedValue(undefined)
|
||||
});
|
||||
|
||||
await expect.element(page.getByText(/ungespeicherte Änderungen/i)).not.toBeInTheDocument();
|
||||
|
||||
const cancel = vi.fn();
|
||||
navCallback({ cancel, to: { url: new URL('http://localhost/admin/groups') } });
|
||||
expect(cancel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps banner when enhance callback receives a failure result', async () => {
|
||||
render(Page, { props: { form: null } });
|
||||
const [navCallback] = vi.mocked(beforeNavigate).mock.calls[0];
|
||||
|
||||
document
|
||||
.querySelector<HTMLInputElement>('input[name="name"]')!
|
||||
.dispatchEvent(new InputEvent('input', { bubbles: true }));
|
||||
|
||||
navCallback({ cancel: vi.fn(), to: { url: new URL('http://localhost/admin/groups') } });
|
||||
await expect.element(page.getByText(/ungespeicherte Änderungen/i)).toBeInTheDocument();
|
||||
|
||||
const innerFn = await (enhanceCaptureRef.submitFn as SubmitFn)();
|
||||
await innerFn({
|
||||
result: { type: 'failure', status: 400, data: { error: 'Name bereits vergeben' } },
|
||||
update: vi.fn().mockResolvedValue(undefined)
|
||||
});
|
||||
|
||||
const cancel = vi.fn();
|
||||
navCallback({ cancel, to: { url: new URL('http://localhost/admin/groups') } });
|
||||
expect(cancel).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { fail } from '@sveltejs/kit';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { parseBackendError } from '$lib/shared/errors';
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
import type { components } from '$lib/generated/api';
|
||||
|
||||
export interface InviteListItem {
|
||||
id: string;
|
||||
@@ -17,22 +18,37 @@ export interface InviteListItem {
|
||||
shareableUrl: string;
|
||||
}
|
||||
|
||||
export type UserGroup = components['schemas']['UserGroup'];
|
||||
|
||||
export const load: PageServerLoad = async ({ url, fetch }) => {
|
||||
const status = url.searchParams.get('status') ?? 'active';
|
||||
const apiUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
|
||||
const res = await fetch(`${apiUrl}/api/invites?status=${encodeURIComponent(status)}`);
|
||||
|
||||
if (!res.ok) {
|
||||
const backendError = await parseBackendError(res);
|
||||
return {
|
||||
invites: [] as InviteListItem[],
|
||||
status,
|
||||
loadError: backendError?.code ?? 'INTERNAL_ERROR'
|
||||
};
|
||||
const [invitesRes, groupsRes] = await Promise.all([
|
||||
fetch(`${apiUrl}/api/invites?status=${encodeURIComponent(status)}`),
|
||||
fetch(`${apiUrl}/api/groups`)
|
||||
]);
|
||||
|
||||
let invites: InviteListItem[] = [];
|
||||
let loadError: string | null = null;
|
||||
if (!invitesRes.ok) {
|
||||
const backendError = await parseBackendError(invitesRes);
|
||||
loadError = backendError?.code ?? 'INTERNAL_ERROR';
|
||||
} else {
|
||||
invites = await invitesRes.json();
|
||||
}
|
||||
|
||||
const invites: InviteListItem[] = await res.json();
|
||||
return { invites, status, loadError: null };
|
||||
let groups: UserGroup[] = [];
|
||||
let groupsLoadError: string | null = null;
|
||||
if (!groupsRes.ok) {
|
||||
const backendError = await parseBackendError(groupsRes);
|
||||
groupsLoadError = backendError?.code ?? 'INTERNAL_ERROR';
|
||||
} else {
|
||||
const raw: UserGroup[] = await groupsRes.json();
|
||||
groups = [...raw].sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
return { invites, status, loadError, groups, groupsLoadError };
|
||||
};
|
||||
|
||||
export const actions = {
|
||||
@@ -45,6 +61,7 @@ export const actions = {
|
||||
const prefillLastName = (formData.get('prefillLastName') as string) || undefined;
|
||||
const prefillEmail = (formData.get('prefillEmail') as string) || undefined;
|
||||
const expiresAt = (formData.get('expiresAt') as string) || undefined;
|
||||
const groupIds = formData.getAll('groupIds') as string[];
|
||||
|
||||
const apiUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
|
||||
const res = await fetch(`${apiUrl}/api/invites`, {
|
||||
@@ -56,7 +73,8 @@ export const actions = {
|
||||
prefillFirstName,
|
||||
prefillLastName,
|
||||
prefillEmail,
|
||||
expiresAt
|
||||
expiresAt,
|
||||
groupIds
|
||||
})
|
||||
});
|
||||
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
import { enhance } from '$app/forms';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
import { getErrorMessage } from '$lib/shared/errors';
|
||||
import type { InviteListItem } from './+page.server.ts';
|
||||
import UserGroupsSection from '$lib/user/UserGroupsSection.svelte';
|
||||
import type { InviteListItem, UserGroup } from './+page.server.ts';
|
||||
|
||||
let {
|
||||
data,
|
||||
@@ -12,6 +13,8 @@ let {
|
||||
invites: InviteListItem[];
|
||||
status: string;
|
||||
loadError: string | null;
|
||||
groups: UserGroup[];
|
||||
groupsLoadError: string | null;
|
||||
};
|
||||
form?: {
|
||||
createError?: string;
|
||||
@@ -253,6 +256,23 @@ function statusIcon(status: string) {
|
||||
class="block w-full border border-line px-3 py-2 font-serif text-sm text-ink focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring"
|
||||
/>
|
||||
</div>
|
||||
<div class="sm:col-span-2">
|
||||
<p class="mb-2 font-sans text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.admin_new_invite_groups()}
|
||||
</p>
|
||||
{#if data.groupsLoadError}
|
||||
<div
|
||||
role="alert"
|
||||
class="rounded-sm border border-amber-200 bg-amber-50 px-3 py-2 font-sans text-xs text-amber-700"
|
||||
>
|
||||
{m.admin_invite_groups_load_error()}
|
||||
</div>
|
||||
{:else if data.groups.length === 0}
|
||||
<p class="font-sans text-xs text-ink-3 italic">{m.admin_new_invite_no_groups()}</p>
|
||||
{:else}
|
||||
<UserGroupsSection groups={data.groups} />
|
||||
{/if}
|
||||
</div>
|
||||
{#if form?.createError}
|
||||
<div class="font-sans text-xs font-medium text-red-600 sm:col-span-2">
|
||||
{getErrorMessage(form.createError)}
|
||||
|
||||
155
frontend/src/routes/admin/invites/page.server.test.ts
Normal file
155
frontend/src/routes/admin/invites/page.server.test.ts
Normal file
@@ -0,0 +1,155 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
vi.mock('$env/dynamic/private', () => ({
|
||||
env: { API_INTERNAL_URL: 'http://localhost:8080' }
|
||||
}));
|
||||
|
||||
import { load, actions } from './+page.server';
|
||||
import type { UserGroup } from './+page.server';
|
||||
|
||||
// PageServerLoad annotates the return as `void | (...)`. This explicit shape avoids
|
||||
// the void and the Record<string, any> from the generic constraint.
|
||||
type LoadData = {
|
||||
invites: unknown[];
|
||||
status: string;
|
||||
loadError: string | null;
|
||||
groups: UserGroup[];
|
||||
groupsLoadError: string | null;
|
||||
};
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
type AnyFetch = (...args: any[]) => any;
|
||||
|
||||
function mockResponse(ok: boolean, body: unknown, status = 200) {
|
||||
return {
|
||||
ok,
|
||||
status,
|
||||
json: async () => body,
|
||||
text: async () => JSON.stringify(body),
|
||||
headers: new Headers({ 'content-type': 'application/json' })
|
||||
} as unknown as Response;
|
||||
}
|
||||
|
||||
describe('admin/invites load()', () => {
|
||||
const mockFetch = vi.fn<AnyFetch>();
|
||||
|
||||
beforeEach(() => mockFetch.mockReset());
|
||||
|
||||
function event(status = 'active') {
|
||||
return {
|
||||
url: new URL(`http://localhost/admin/invites?status=${status}`),
|
||||
fetch: mockFetch as unknown as typeof fetch
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any;
|
||||
}
|
||||
|
||||
it('returns groups array alongside invites when both succeed', async () => {
|
||||
mockFetch.mockResolvedValueOnce(mockResponse(true, [])).mockResolvedValueOnce(
|
||||
mockResponse(true, [
|
||||
{ id: 'g-1', name: 'Familie', permissions: ['READ_ALL'] },
|
||||
{ id: 'g-2', name: 'Administratoren', permissions: ['ADMIN'] }
|
||||
])
|
||||
);
|
||||
|
||||
const result = (await load(event())) as LoadData;
|
||||
|
||||
expect(result.groups).toHaveLength(2);
|
||||
expect(result.groupsLoadError).toBeNull();
|
||||
});
|
||||
|
||||
it('returns groups sorted alphabetically by name', async () => {
|
||||
mockFetch.mockResolvedValueOnce(mockResponse(true, [])).mockResolvedValueOnce(
|
||||
mockResponse(true, [
|
||||
{ id: 'g-1', name: 'Zebra', permissions: [] },
|
||||
{ id: 'g-2', name: 'Alfa', permissions: [] },
|
||||
{ id: 'g-3', name: 'Mitte', permissions: [] }
|
||||
])
|
||||
);
|
||||
|
||||
const result = (await load(event())) as LoadData;
|
||||
|
||||
expect(result.groups.map((g) => g.name)).toEqual(['Alfa', 'Mitte', 'Zebra']);
|
||||
});
|
||||
|
||||
it('returns groups: [] and non-null groupsLoadError when groups fetch is non-OK', async () => {
|
||||
mockFetch
|
||||
.mockResolvedValueOnce(mockResponse(true, []))
|
||||
.mockResolvedValueOnce(mockResponse(false, { code: 'FORBIDDEN' }, 403));
|
||||
|
||||
const result = (await load(event())) as LoadData;
|
||||
|
||||
expect(result.groups).toEqual([]);
|
||||
expect(result.groupsLoadError).toBe('FORBIDDEN');
|
||||
});
|
||||
|
||||
it('falls back to INTERNAL_ERROR when groups error body has no code', async () => {
|
||||
mockFetch
|
||||
.mockResolvedValueOnce(mockResponse(true, []))
|
||||
.mockResolvedValueOnce(mockResponse(false, null, 500));
|
||||
|
||||
const result = (await load(event())) as LoadData;
|
||||
|
||||
expect(result.groupsLoadError).toBe('INTERNAL_ERROR');
|
||||
});
|
||||
|
||||
it('fetches invites and groups in parallel (both URLs called)', async () => {
|
||||
mockFetch
|
||||
.mockResolvedValueOnce(mockResponse(true, []))
|
||||
.mockResolvedValueOnce(mockResponse(true, []));
|
||||
|
||||
await load(event());
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||
expect(mockFetch).toHaveBeenCalledWith(expect.stringContaining('/api/invites'));
|
||||
expect(mockFetch).toHaveBeenCalledWith(expect.stringContaining('/api/groups'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('admin/invites create action', () => {
|
||||
const mockFetch = vi.fn<AnyFetch>();
|
||||
|
||||
beforeEach(() => mockFetch.mockReset());
|
||||
|
||||
const successBody = {
|
||||
id: 'inv-1',
|
||||
code: 'ABCDE12345',
|
||||
displayCode: 'ABCDE-12345',
|
||||
status: 'active',
|
||||
revoked: false,
|
||||
useCount: 0,
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
shareableUrl: 'http://localhost/register?code=ABCDE12345'
|
||||
};
|
||||
|
||||
it('includes groupIds array in POST body when checkboxes are checked', async () => {
|
||||
const fd = new FormData();
|
||||
fd.append('groupIds', 'g-1');
|
||||
fd.append('groupIds', 'g-2');
|
||||
mockFetch.mockResolvedValueOnce(mockResponse(true, successBody, 201));
|
||||
|
||||
await actions.create({
|
||||
request: new Request('http://localhost', { method: 'POST', body: fd }),
|
||||
fetch: mockFetch as unknown as typeof fetch
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any);
|
||||
|
||||
const [, init] = mockFetch.mock.calls[0] as [string, RequestInit];
|
||||
const sent = JSON.parse(init.body as string);
|
||||
expect(sent.groupIds).toEqual(['g-1', 'g-2']);
|
||||
});
|
||||
|
||||
it('sends groupIds: [] when no checkboxes are checked', async () => {
|
||||
const fd = new FormData();
|
||||
mockFetch.mockResolvedValueOnce(mockResponse(true, successBody, 201));
|
||||
|
||||
await actions.create({
|
||||
request: new Request('http://localhost', { method: 'POST', body: fd }),
|
||||
fetch: mockFetch as unknown as typeof fetch
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any);
|
||||
|
||||
const [, init] = mockFetch.mock.calls[0] as [string, RequestInit];
|
||||
const sent = JSON.parse(init.body as string);
|
||||
expect(sent.groupIds).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -7,12 +7,15 @@ afterEach(cleanup);
|
||||
|
||||
const makeInvite = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 'i-1',
|
||||
code: 'XYZ1234567',
|
||||
displayCode: 'XYZ-1234',
|
||||
label: 'Familie',
|
||||
useCount: 0,
|
||||
maxUses: 5,
|
||||
expiresAt: '2027-01-01T00:00:00Z',
|
||||
revoked: false,
|
||||
status: 'active' as string,
|
||||
createdAt: '2025-01-01T00:00:00Z',
|
||||
shareableUrl: 'http://example.com/i/i-1',
|
||||
...overrides
|
||||
});
|
||||
@@ -22,11 +25,15 @@ const baseData = (
|
||||
invites: ReturnType<typeof makeInvite>[];
|
||||
status: string;
|
||||
loadError: string | null;
|
||||
groups: { id: string; name: string; permissions: string[] }[];
|
||||
groupsLoadError: string | null;
|
||||
}> = {}
|
||||
) => ({
|
||||
invites: [],
|
||||
status: 'active',
|
||||
loadError: null,
|
||||
groups: [],
|
||||
groupsLoadError: null,
|
||||
...overrides
|
||||
});
|
||||
|
||||
@@ -253,4 +260,115 @@ describe('admin/invites page', () => {
|
||||
const banner = document.querySelector('.bg-red-50');
|
||||
expect(banner).not.toBeNull();
|
||||
});
|
||||
|
||||
// ─── groups section ───────────────────────────────────────────────────────
|
||||
|
||||
it('shows a groups-load warning banner when data.groupsLoadError is set', async () => {
|
||||
render(AdminInvitesPage, {
|
||||
props: { data: { ...baseData(), groups: [], groupsLoadError: 'INTERNAL_ERROR' } }
|
||||
});
|
||||
|
||||
await page
|
||||
.getByRole('button', { name: /neue einladung/i })
|
||||
.first()
|
||||
.click();
|
||||
|
||||
const banner = document.querySelector('.bg-amber-50');
|
||||
expect(banner).not.toBeNull();
|
||||
});
|
||||
|
||||
it('renders group checkboxes inside the new-invite form when groups are provided', async () => {
|
||||
render(AdminInvitesPage, {
|
||||
props: {
|
||||
data: {
|
||||
...baseData(),
|
||||
groups: [
|
||||
{ id: 'g-1', name: 'Administratoren', permissions: ['ADMIN'] },
|
||||
{ id: 'g-2', name: 'Familie', permissions: ['READ_ALL'] }
|
||||
],
|
||||
groupsLoadError: null
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await page
|
||||
.getByRole('button', { name: /neue einladung/i })
|
||||
.first()
|
||||
.click();
|
||||
|
||||
await expect.element(page.getByRole('checkbox', { name: 'Administratoren' })).toBeVisible();
|
||||
await expect.element(page.getByRole('checkbox', { name: 'Familie' })).toBeVisible();
|
||||
});
|
||||
|
||||
it('group checkbox stays checked after being clicked', async () => {
|
||||
render(AdminInvitesPage, {
|
||||
props: {
|
||||
data: {
|
||||
...baseData(),
|
||||
groups: [{ id: 'g-1', name: 'Familie', permissions: ['READ_ALL'] }],
|
||||
groupsLoadError: null
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await page
|
||||
.getByRole('button', { name: /neue einladung/i })
|
||||
.first()
|
||||
.click();
|
||||
|
||||
const checkbox = page.getByRole('checkbox', { name: 'Familie' });
|
||||
await checkbox.click();
|
||||
await expect.element(checkbox).toBeChecked();
|
||||
});
|
||||
|
||||
it('amber warning banner has role="alert"', async () => {
|
||||
render(AdminInvitesPage, {
|
||||
props: { data: { ...baseData(), groups: [], groupsLoadError: 'INTERNAL_ERROR' } }
|
||||
});
|
||||
|
||||
await page
|
||||
.getByRole('button', { name: /neue einladung/i })
|
||||
.first()
|
||||
.click();
|
||||
|
||||
const alert = document.querySelector('[role="alert"]');
|
||||
expect(alert).not.toBeNull();
|
||||
});
|
||||
|
||||
it('checkbox group fieldset has accessible name from i18n key (not hardcoded German)', async () => {
|
||||
render(AdminInvitesPage, {
|
||||
props: {
|
||||
data: {
|
||||
...baseData(),
|
||||
groups: [{ id: 'g-1', name: 'Familie', permissions: ['READ_ALL'] }],
|
||||
groupsLoadError: null
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await page
|
||||
.getByRole('button', { name: /neue einladung/i })
|
||||
.first()
|
||||
.click();
|
||||
|
||||
// m.admin_new_invite_groups() returns "Gruppen (optional)" in de locale
|
||||
// The hardcoded legend "Gruppen" would not match this accessible name
|
||||
await expect.element(page.getByRole('group', { name: 'Gruppen (optional)' })).toBeVisible();
|
||||
});
|
||||
|
||||
it('shows no checkboxes and no warning when groups list is empty and no error', async () => {
|
||||
render(AdminInvitesPage, {
|
||||
props: { data: { ...baseData(), groups: [], groupsLoadError: null } }
|
||||
});
|
||||
|
||||
await page
|
||||
.getByRole('button', { name: /neue einladung/i })
|
||||
.first()
|
||||
.click();
|
||||
|
||||
expect(document.querySelectorAll('input[name="groupIds"]')).toHaveLength(0);
|
||||
expect(document.querySelector('.bg-amber-50')).toBeNull();
|
||||
// empty-state message visible — "Keine Gruppen vorhanden." in de locale
|
||||
await expect.element(page.getByText(/keine gruppen/i)).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,19 +1,14 @@
|
||||
<script lang="ts">
|
||||
import { onDestroy } from 'svelte';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
import ImportStatusCard from './ImportStatusCard.svelte';
|
||||
import type { ImportStatus } from './types.js';
|
||||
|
||||
let backfillResult: number | null = $state(null);
|
||||
let backfillLoading = $state(false);
|
||||
let backfillHashesResult: number | null = $state(null);
|
||||
let backfillHashesLoading = $state(false);
|
||||
|
||||
type ImportStatus = {
|
||||
state: 'IDLE' | 'RUNNING' | 'DONE' | 'FAILED';
|
||||
message: string;
|
||||
processed: number;
|
||||
startedAt: string | null;
|
||||
};
|
||||
|
||||
type ThumbnailStatus = {
|
||||
state: 'IDLE' | 'RUNNING' | 'DONE' | 'FAILED';
|
||||
message: string;
|
||||
@@ -177,47 +172,7 @@ async function backfillFileHashes() {
|
||||
</div>
|
||||
|
||||
<!-- Mass import -->
|
||||
<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
|
||||
<h2 class="mb-1 font-sans text-sm font-bold text-ink">{m.admin_system_import_heading()}</h2>
|
||||
<p class="mb-4 text-sm text-ink-2">{m.admin_system_import_description()}</p>
|
||||
|
||||
{#if importStatus?.state === 'RUNNING'}
|
||||
<p class="text-sm text-ink-2">{m.admin_system_import_status_running()}</p>
|
||||
{:else if importStatus?.state === 'DONE'}
|
||||
<p class="mb-4 rounded-sm border border-green-200 bg-green-50 p-3 text-sm text-green-700">
|
||||
{m.admin_system_import_status_done({ count: importStatus.processed })}
|
||||
</p>
|
||||
<button
|
||||
data-import-trigger
|
||||
onclick={triggerImport}
|
||||
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
|
||||
>
|
||||
{m.admin_system_import_btn_retry()}
|
||||
</button>
|
||||
{:else if importStatus?.state === 'FAILED'}
|
||||
<p class="mb-4 rounded-sm border border-red-200 bg-red-50 p-3 text-sm text-red-700">
|
||||
{m.admin_system_import_status_failed({ message: importStatus.message })}
|
||||
</p>
|
||||
<button
|
||||
data-import-trigger
|
||||
onclick={triggerImport}
|
||||
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
|
||||
>
|
||||
{m.admin_system_import_btn_retry()}
|
||||
</button>
|
||||
{:else}
|
||||
{#if importStatus !== null}
|
||||
<p class="mb-4 text-sm text-ink-2">{m.admin_system_import_status_idle()}</p>
|
||||
{/if}
|
||||
<button
|
||||
data-import-trigger
|
||||
onclick={triggerImport}
|
||||
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
|
||||
>
|
||||
{m.admin_system_import_btn_start()}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
<ImportStatusCard importStatus={importStatus} ontrigger={triggerImport} />
|
||||
|
||||
<!-- Thumbnail backfill -->
|
||||
<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
|
||||
|
||||
81
frontend/src/routes/admin/system/ImportStatusCard.svelte
Normal file
81
frontend/src/routes/admin/system/ImportStatusCard.svelte
Normal file
@@ -0,0 +1,81 @@
|
||||
<script lang="ts">
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
import type { ImportStatus } from './types.js';
|
||||
|
||||
let {
|
||||
importStatus,
|
||||
ontrigger
|
||||
}: {
|
||||
importStatus: ImportStatus | null;
|
||||
ontrigger: () => void;
|
||||
} = $props();
|
||||
|
||||
const failureMessage = $derived(
|
||||
importStatus?.statusCode === 'IMPORT_FAILED_NO_SPREADSHEET'
|
||||
? m.admin_system_import_failed_no_spreadsheet()
|
||||
: m.admin_system_import_failed_internal()
|
||||
);
|
||||
</script>
|
||||
|
||||
<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
|
||||
<h2 class="mb-5 font-sans text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.admin_system_import_heading()}
|
||||
</h2>
|
||||
<p class="mb-4 text-sm text-ink-2">{m.admin_system_import_description()}</p>
|
||||
|
||||
{#if importStatus?.state === 'RUNNING'}
|
||||
<div class="mb-4 flex items-center gap-3">
|
||||
<span
|
||||
data-testid="spinner"
|
||||
role="status"
|
||||
aria-label={m.admin_system_import_status_running()}
|
||||
class="inline-block h-5 w-5 animate-spin rounded-full border-2 border-ink-3 border-t-brand-mint motion-reduce:animate-none"
|
||||
></span>
|
||||
<div>
|
||||
<p data-testid="processed-count" class="text-base font-bold text-ink">
|
||||
{importStatus.processed}
|
||||
</p>
|
||||
<p class="font-sans text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.admin_system_import_status_running()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{:else if importStatus?.state === 'DONE'}
|
||||
<div class="mb-4 rounded-sm border border-green-200 bg-green-50 p-4 text-green-700">
|
||||
<p data-testid="processed-count" class="text-base font-bold">{importStatus.processed}</p>
|
||||
<p class="font-sans text-xs font-bold tracking-widest text-green-800 uppercase">
|
||||
{m.admin_system_import_status_done_label()}
|
||||
</p>
|
||||
<p class="mt-1 text-xs text-green-800">{m.admin_system_import_status_done()}</p>
|
||||
</div>
|
||||
<button
|
||||
data-import-trigger
|
||||
onclick={ontrigger}
|
||||
class="min-h-[44px] rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
|
||||
>
|
||||
{m.admin_system_import_btn_retry()}
|
||||
</button>
|
||||
{:else if importStatus?.state === 'FAILED'}
|
||||
<p class="mb-4 rounded-sm border border-red-200 bg-red-50 p-3 text-sm text-red-700">
|
||||
{failureMessage}
|
||||
</p>
|
||||
<button
|
||||
data-import-trigger
|
||||
onclick={ontrigger}
|
||||
class="min-h-[44px] rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
|
||||
>
|
||||
{m.admin_system_import_btn_retry()}
|
||||
</button>
|
||||
{:else}
|
||||
{#if importStatus !== null}
|
||||
<p class="mb-4 text-sm text-ink-2">{m.admin_system_import_status_idle()}</p>
|
||||
{/if}
|
||||
<button
|
||||
data-import-trigger
|
||||
onclick={ontrigger}
|
||||
class="min-h-[44px] rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
|
||||
>
|
||||
{m.admin_system_import_btn_start()}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
131
frontend/src/routes/admin/system/ImportStatusCard.svelte.test.ts
Normal file
131
frontend/src/routes/admin/system/ImportStatusCard.svelte.test.ts
Normal file
@@ -0,0 +1,131 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { render } from 'vitest-browser-svelte';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
import ImportStatusCard from './ImportStatusCard.svelte';
|
||||
import type { ImportStatus } from './types.js';
|
||||
|
||||
const makeStatus = (overrides: Partial<ImportStatus> = {}): ImportStatus => ({
|
||||
state: 'IDLE',
|
||||
statusCode: 'IMPORT_IDLE',
|
||||
processed: 0,
|
||||
startedAt: null,
|
||||
...overrides
|
||||
});
|
||||
|
||||
describe('ImportStatusCard', () => {
|
||||
it('shows spinner while state is RUNNING', async () => {
|
||||
const { getByTestId } = render(ImportStatusCard, {
|
||||
props: {
|
||||
importStatus: makeStatus({ state: 'RUNNING', statusCode: 'IMPORT_RUNNING', processed: 3 }),
|
||||
ontrigger: () => {}
|
||||
}
|
||||
});
|
||||
|
||||
await expect.element(getByTestId('spinner')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows processed count at text-base while RUNNING', async () => {
|
||||
const { getByTestId } = render(ImportStatusCard, {
|
||||
props: {
|
||||
importStatus: makeStatus({ state: 'RUNNING', statusCode: 'IMPORT_RUNNING', processed: 7 }),
|
||||
ontrigger: () => {}
|
||||
}
|
||||
});
|
||||
|
||||
await expect.element(getByTestId('processed-count')).toHaveTextContent('7');
|
||||
});
|
||||
|
||||
it('shows processed count while DONE', async () => {
|
||||
const { getByText } = render(ImportStatusCard, {
|
||||
props: {
|
||||
importStatus: makeStatus({ state: 'DONE', statusCode: 'IMPORT_DONE', processed: 42 }),
|
||||
ontrigger: () => {}
|
||||
}
|
||||
});
|
||||
|
||||
await expect.element(getByText('42')).toBeVisible();
|
||||
});
|
||||
|
||||
it('shows no-spreadsheet message when statusCode is IMPORT_FAILED_NO_SPREADSHEET', async () => {
|
||||
const { getByText } = render(ImportStatusCard, {
|
||||
props: {
|
||||
importStatus: makeStatus({
|
||||
state: 'FAILED',
|
||||
statusCode: 'IMPORT_FAILED_NO_SPREADSHEET'
|
||||
}),
|
||||
ontrigger: () => {}
|
||||
}
|
||||
});
|
||||
|
||||
await expect.element(getByText(m.admin_system_import_failed_no_spreadsheet())).toBeVisible();
|
||||
});
|
||||
|
||||
it('shows internal error message when statusCode is IMPORT_FAILED_INTERNAL', async () => {
|
||||
const { getByText } = render(ImportStatusCard, {
|
||||
props: {
|
||||
importStatus: makeStatus({ state: 'FAILED', statusCode: 'IMPORT_FAILED_INTERNAL' }),
|
||||
ontrigger: () => {}
|
||||
}
|
||||
});
|
||||
|
||||
await expect.element(getByText(m.admin_system_import_failed_internal())).toBeVisible();
|
||||
});
|
||||
|
||||
it('shows idle text when importStatus is non-null and state is IDLE', async () => {
|
||||
const { getByText } = render(ImportStatusCard, {
|
||||
props: {
|
||||
importStatus: makeStatus({ state: 'IDLE', statusCode: 'IMPORT_IDLE' }),
|
||||
ontrigger: () => {}
|
||||
}
|
||||
});
|
||||
|
||||
await expect.element(getByText(m.admin_system_import_status_idle())).toBeVisible();
|
||||
});
|
||||
|
||||
it('shows no spinner when importStatus is null', async () => {
|
||||
const { getByTestId } = render(ImportStatusCard, {
|
||||
props: { importStatus: null, ontrigger: () => {} }
|
||||
});
|
||||
|
||||
await expect.element(getByTestId('spinner')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls ontrigger when retry button is clicked in DONE state', async () => {
|
||||
const ontrigger = vi.fn();
|
||||
const { getByRole } = render(ImportStatusCard, {
|
||||
props: {
|
||||
importStatus: makeStatus({ state: 'DONE', statusCode: 'IMPORT_DONE', processed: 5 }),
|
||||
ontrigger
|
||||
}
|
||||
});
|
||||
|
||||
await getByRole('button').click();
|
||||
expect(ontrigger).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('calls ontrigger when retry button is clicked in FAILED state', async () => {
|
||||
const ontrigger = vi.fn();
|
||||
const { getByRole } = render(ImportStatusCard, {
|
||||
props: {
|
||||
importStatus: makeStatus({ state: 'FAILED', statusCode: 'IMPORT_FAILED_INTERNAL' }),
|
||||
ontrigger
|
||||
}
|
||||
});
|
||||
|
||||
await getByRole('button').click();
|
||||
expect(ontrigger).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('calls ontrigger when start button is clicked in IDLE state', async () => {
|
||||
const ontrigger = vi.fn();
|
||||
const { getByRole } = render(ImportStatusCard, {
|
||||
props: {
|
||||
importStatus: makeStatus({ state: 'IDLE', statusCode: 'IMPORT_IDLE' }),
|
||||
ontrigger
|
||||
}
|
||||
});
|
||||
|
||||
await getByRole('button').click();
|
||||
expect(ontrigger).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -163,7 +163,7 @@ describe('Admin system page — mass import card', () => {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
state: 'FAILED',
|
||||
message: 'Datei nicht gefunden.',
|
||||
statusCode: 'IMPORT_FAILED_NO_SPREADSHEET',
|
||||
processed: 0,
|
||||
startedAt: '2026-01-01T10:00:00'
|
||||
})
|
||||
@@ -182,7 +182,7 @@ describe('Admin system page — mass import card', () => {
|
||||
})
|
||||
);
|
||||
render(Page, {});
|
||||
await expect.element(page.getByText(/Datei nicht gefunden/i)).toBeInTheDocument();
|
||||
await expect.element(page.getByText(/Keine Tabellendatei gefunden/i)).toBeInTheDocument();
|
||||
await expect.element(page.getByRole('button', { name: /Erneut starten/i })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -246,7 +246,7 @@ describe('admin/system page', () => {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
state: 'FAILED',
|
||||
message: 'database error',
|
||||
statusCode: 'IMPORT_FAILED_INTERNAL',
|
||||
processed: 0,
|
||||
startedAt: null
|
||||
}),
|
||||
@@ -262,7 +262,7 @@ describe('admin/system page', () => {
|
||||
render(AdminSystemPage, { props: {} });
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent).toContain('database error');
|
||||
expect(document.body.textContent).toContain('Interner Fehler beim Import');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
6
frontend/src/routes/admin/system/types.ts
Normal file
6
frontend/src/routes/admin/system/types.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export type ImportStatus = {
|
||||
state: 'IDLE' | 'RUNNING' | 'DONE' | 'FAILED';
|
||||
statusCode: string;
|
||||
processed: number;
|
||||
startedAt: string | null;
|
||||
};
|
||||
@@ -1,24 +1,15 @@
|
||||
<script lang="ts">
|
||||
import { enhance } from '$app/forms';
|
||||
import { beforeNavigate, goto } from '$app/navigation';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
import UserProfileSection from '$lib/user/UserProfileSection.svelte';
|
||||
import UserGroupsSection from '$lib/user/UserGroupsSection.svelte';
|
||||
import AccountSection from './AccountSection.svelte';
|
||||
import { createUnsavedWarning } from '$lib/shared/hooks/useUnsavedWarning.svelte';
|
||||
import UnsavedWarningBanner from '$lib/shared/primitives/UnsavedWarningBanner.svelte';
|
||||
|
||||
let { data, form } = $props();
|
||||
|
||||
let isDirty = $state(false);
|
||||
let showUnsavedWarning = $state(false);
|
||||
let discardTarget: string | null = $state(null);
|
||||
|
||||
beforeNavigate(({ cancel, to }) => {
|
||||
if (isDirty) {
|
||||
cancel();
|
||||
showUnsavedWarning = true;
|
||||
discardTarget = to?.url.href ?? null;
|
||||
}
|
||||
});
|
||||
const unsaved = createUnsavedWarning();
|
||||
</script>
|
||||
|
||||
<div class="flex flex-1 flex-col overflow-hidden">
|
||||
@@ -44,23 +35,8 @@ beforeNavigate(({ cancel, to }) => {
|
||||
|
||||
<!-- Scrollable body -->
|
||||
<div class="flex-1 overflow-y-auto px-5 py-5">
|
||||
{#if showUnsavedWarning}
|
||||
<div
|
||||
class="mb-5 flex items-center justify-between rounded border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-300"
|
||||
>
|
||||
<span>{m.admin_unsaved_warning()}</span>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => {
|
||||
isDirty = false;
|
||||
showUnsavedWarning = false;
|
||||
if (discardTarget) goto(discardTarget);
|
||||
}}
|
||||
class="ml-4 shrink-0 font-sans text-xs font-bold tracking-widest text-amber-800 uppercase hover:text-amber-900 dark:text-amber-300"
|
||||
>
|
||||
{m.person_discard_changes()}
|
||||
</button>
|
||||
</div>
|
||||
{#if unsaved.showUnsavedWarning}
|
||||
<UnsavedWarningBanner onDiscard={unsaved.discard} />
|
||||
{/if}
|
||||
{#if form?.error}
|
||||
<div class="mb-5 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700">
|
||||
@@ -71,11 +47,11 @@ beforeNavigate(({ cancel, to }) => {
|
||||
<form
|
||||
id="new-user-form"
|
||||
method="POST"
|
||||
use:enhance
|
||||
oninput={() => {
|
||||
isDirty = true;
|
||||
showUnsavedWarning = false;
|
||||
use:enhance={() => async ({ result, update }) => {
|
||||
if (result.type === 'redirect') unsaved.clearOnSuccess();
|
||||
await update();
|
||||
}}
|
||||
oninput={unsaved.markDirty}
|
||||
class="space-y-5"
|
||||
>
|
||||
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { cleanup, render } from 'vitest-browser-svelte';
|
||||
import { page } from 'vitest/browser';
|
||||
import Page from './+page.svelte';
|
||||
|
||||
vi.mock('$app/forms', () => ({ enhance: () => () => {} }));
|
||||
const enhanceCaptureRef = vi.hoisted(() => ({ submitFn: undefined as unknown }));
|
||||
|
||||
vi.mock('$app/forms', () => ({
|
||||
enhance: (_el: HTMLFormElement, fn?: unknown) => {
|
||||
enhanceCaptureRef.submitFn = fn;
|
||||
return { destroy: vi.fn() };
|
||||
}
|
||||
}));
|
||||
vi.mock('$app/navigation', () => ({ beforeNavigate: vi.fn(), goto: vi.fn() }));
|
||||
|
||||
import { beforeNavigate, goto } from '$app/navigation';
|
||||
|
||||
const groups = [
|
||||
{ id: 'g1', name: 'Editoren', permissions: ['WRITE_ALL'] },
|
||||
@@ -20,6 +30,13 @@ const baseData = {
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
type SubmitFn = () => Promise<
|
||||
(opts: {
|
||||
result: { type: string; [key: string]: unknown };
|
||||
update: () => Promise<void>;
|
||||
}) => Promise<void>
|
||||
>;
|
||||
|
||||
// ─── Rendering ────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('Admin new user page – rendering', () => {
|
||||
@@ -66,3 +83,103 @@ describe('Admin new user page – error display', () => {
|
||||
await expect.element(page.getByText('Ein Fehler ist aufgetreten.')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Unsaved-changes guard ────────────────────────────────────────────────────
|
||||
|
||||
describe('Admin new user page – unsaved-changes guard', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
enhanceCaptureRef.submitFn = undefined;
|
||||
});
|
||||
|
||||
it('does not show unsaved warning initially', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
await expect.element(page.getByText(/ungespeicherte Änderungen/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('cancels navigation and shows banner when form is dirty', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
const [callback] = vi.mocked(beforeNavigate).mock.calls[0];
|
||||
|
||||
document
|
||||
.querySelector<HTMLInputElement>('input[name="email"]')!
|
||||
.dispatchEvent(new InputEvent('input', { bubbles: true }));
|
||||
|
||||
const cancel = vi.fn();
|
||||
callback({ cancel, to: { url: new URL('http://localhost/admin/users') } });
|
||||
|
||||
expect(cancel).toHaveBeenCalled();
|
||||
await expect.element(page.getByText(/ungespeicherte Änderungen/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not cancel navigation when form is clean', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
const [callback] = vi.mocked(beforeNavigate).mock.calls[0];
|
||||
|
||||
const cancel = vi.fn();
|
||||
callback({ cancel, to: { url: new URL('http://localhost/admin/users') } });
|
||||
|
||||
expect(cancel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('discard button calls goto with the target URL', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
const [callback] = vi.mocked(beforeNavigate).mock.calls[0];
|
||||
|
||||
document
|
||||
.querySelector<HTMLInputElement>('input[name="email"]')!
|
||||
.dispatchEvent(new InputEvent('input', { bubbles: true }));
|
||||
|
||||
callback({ cancel: vi.fn(), to: { url: new URL('http://localhost/admin/users') } });
|
||||
|
||||
await page.getByRole('button', { name: /verwerfen/i }).click();
|
||||
|
||||
expect(vi.mocked(goto)).toHaveBeenCalledWith('http://localhost/admin/users');
|
||||
});
|
||||
|
||||
it('clears banner when enhance callback receives a redirect result', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
const [navCallback] = vi.mocked(beforeNavigate).mock.calls[0];
|
||||
|
||||
document
|
||||
.querySelector<HTMLInputElement>('input[name="email"]')!
|
||||
.dispatchEvent(new InputEvent('input', { bubbles: true }));
|
||||
|
||||
navCallback({ cancel: vi.fn(), to: { url: new URL('http://localhost/admin/users') } });
|
||||
await expect.element(page.getByText(/ungespeicherte Änderungen/i)).toBeInTheDocument();
|
||||
|
||||
const innerFn = await (enhanceCaptureRef.submitFn as SubmitFn)();
|
||||
await innerFn({
|
||||
result: { type: 'redirect', location: '/admin/users', status: 303 },
|
||||
update: vi.fn().mockResolvedValue(undefined)
|
||||
});
|
||||
|
||||
await expect.element(page.getByText(/ungespeicherte Änderungen/i)).not.toBeInTheDocument();
|
||||
|
||||
const cancel = vi.fn();
|
||||
navCallback({ cancel, to: { url: new URL('http://localhost/admin/users') } });
|
||||
expect(cancel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps banner when enhance callback receives a failure result', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
const [navCallback] = vi.mocked(beforeNavigate).mock.calls[0];
|
||||
|
||||
document
|
||||
.querySelector<HTMLInputElement>('input[name="email"]')!
|
||||
.dispatchEvent(new InputEvent('input', { bubbles: true }));
|
||||
|
||||
navCallback({ cancel: vi.fn(), to: { url: new URL('http://localhost/admin/users') } });
|
||||
await expect.element(page.getByText(/ungespeicherte Änderungen/i)).toBeInTheDocument();
|
||||
|
||||
const innerFn = await (enhanceCaptureRef.submitFn as SubmitFn)();
|
||||
await innerFn({
|
||||
result: { type: 'failure', status: 400, data: { error: 'E-Mail bereits vergeben' } },
|
||||
update: vi.fn().mockResolvedValue(undefined)
|
||||
});
|
||||
|
||||
const cancel = vi.fn();
|
||||
navCallback({ cancel, to: { url: new URL('http://localhost/admin/users') } });
|
||||
expect(cancel).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { cleanup, render } from 'vitest-browser-svelte';
|
||||
import { page, userEvent } from 'vitest/browser';
|
||||
import { page } from 'vitest/browser';
|
||||
import { createRawSnippet } from 'svelte';
|
||||
|
||||
vi.mock('$env/static/public', () => ({ PUBLIC_NOTIFICATION_POLL_MS: '60000' }));
|
||||
@@ -96,13 +96,13 @@ describe('Layout – user dropdown', () => {
|
||||
|
||||
it('opens dropdown on button click', async () => {
|
||||
render(Layout, { data: makeData(), children: emptySnippet });
|
||||
await page.getByRole('button', { name: /MM/ }).click();
|
||||
((await page.getByRole('button', { name: /MM/ }).element()) as HTMLElement).click();
|
||||
await expect.element(page.getByRole('link', { name: /Profil/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('profile link points to /profile', async () => {
|
||||
render(Layout, { data: makeData(), children: emptySnippet });
|
||||
await page.getByRole('button', { name: /MM/ }).click();
|
||||
((await page.getByRole('button', { name: /MM/ }).element()) as HTMLElement).click();
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /Profil/i }))
|
||||
.toHaveAttribute('href', '/profile');
|
||||
@@ -110,16 +110,16 @@ describe('Layout – user dropdown', () => {
|
||||
|
||||
it('logout button is in the dropdown', async () => {
|
||||
render(Layout, { data: makeData(), children: emptySnippet });
|
||||
await page.getByRole('button', { name: /MM/ }).click();
|
||||
((await page.getByRole('button', { name: /MM/ }).element()) as HTMLElement).click();
|
||||
await expect.element(page.getByRole('button', { name: /Abmelden/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('closes dropdown when Escape is pressed', async () => {
|
||||
render(Layout, { data: makeData(), children: emptySnippet });
|
||||
const btn = page.getByRole('button', { name: /MM/ });
|
||||
await btn.click();
|
||||
const btnEl = (await page.getByRole('button', { name: /MM/ }).element()) as HTMLElement;
|
||||
btnEl.click();
|
||||
await expect.element(page.getByRole('link', { name: /Profil/i })).toBeInTheDocument();
|
||||
await userEvent.keyboard('{Escape}');
|
||||
btnEl.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
|
||||
await tick();
|
||||
await expect.element(page.getByRole('link', { name: /Profil/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -24,6 +24,8 @@ export default defineConfig({
|
||||
})
|
||||
],
|
||||
test: {
|
||||
testTimeout: 30_000,
|
||||
hookTimeout: 15_000,
|
||||
expect: { requireAssertions: true },
|
||||
browser: {
|
||||
enabled: true,
|
||||
|
||||
Reference in New Issue
Block a user