diff --git a/.gitignore b/.gitignore index c7e78a5c6..d713fbe8d 100644 --- a/.gitignore +++ b/.gitignore @@ -45,6 +45,9 @@ local-scripts/ ### Dev config, books, and data ### booklore-ui/test-results/ frontend/test-results/ +frontend/output/ +frontend/playwright-report/ +frontend/.playwright-browsers/ frontend/node_modules/ booklore-api/src/main/resources/application-local.yaml /shared/ @@ -54,3 +57,4 @@ booklore-api/src/main/resources/application-local.yaml /frontend/.yarn/ /tools/release/node_modules /tools/release/.yarn/ +.worktrees/ diff --git a/dev.docker-compose.yml b/dev.docker-compose.yml index 713bbfd25..114fe53eb 100644 --- a/dev.docker-compose.yml +++ b/dev.docker-compose.yml @@ -29,7 +29,19 @@ services: - ./shared/data:/app/data - ./shared/books:/books - ./shared/bookdrop:/bookdrop - + frontend: + image: node:24-alpine + command: sh -c "cd /angular-app && corepack enable && corepack yarn install --immutable && corepack yarn ng serve --host 0.0.0.0 --watch --configuration development" + environment: + - NODE_ENV=development + stdin_open: true + tty: true + restart: unless-stopped + volumes: + - './frontend:/angular-app' + - node_modules:/angular-app/node_modules + ports: + - "${FRONTEND_PORT:-4200}:4200" backend_db: image: mariadb:11.4 container_name: backend_db @@ -44,28 +56,10 @@ services: ports: - "${DB_PORT:-3366}:3306" healthcheck: - test: [ "CMD", "mariadb-admin", "ping", "-h", "localhost", "-uroot", "-pgrimmory" ] + test: ["CMD", "mariadb-admin", "ping", "-h", "localhost", "-uroot", "-pgrimmory"] interval: 10s timeout: 5s retries: 5 - - ui: - image: node:24-alpine - command: sh -c "cd /angular-app && corepack enable && corepack yarn install --immutable && corepack yarn ng serve --host 0.0.0.0 --watch --configuration development" - environment: - - NODE_ENV=development - stdin_open: true - tty: true - restart: unless-stopped - volumes: - - './frontend:/angular-app' - - # you can have node_modules in a volume. however, if you enable this, expect trouble in some IDEs, as the deps are not available anymore - # - node_modules:/angular-app/node_modules - - ports: - - "${FRONTEND_PORT:-4200}:4200" - volumes: node_modules: backend_db: diff --git a/docs/plans/frontend-90-coverage-plan.md b/docs/plans/frontend-90-coverage-plan.md new file mode 100644 index 000000000..320823ded --- /dev/null +++ b/docs/plans/frontend-90-coverage-plan.md @@ -0,0 +1,506 @@ +# Frontend 90% Coverage Controller Plan + +## Summary + +Drive the frontend to an honest `>=90%` on statements, branches, functions, and lines by attacking the coldest branch-deficit areas first. + +Current baseline on `chore/expand-frontend-tests` after `just ui typecheck`, `just ui lint`, `just ui test`, `just ui coverage`, and `just ui coverage-summary`: +- Global: statements `19.98%`, branches `15.25%`, functions `16.57%`, lines `36.00%` +- Lane ranking by uncovered branches: + - `metadata + settings + stats`: `3200` + - `book + author + series + notebook`: `2194` + - `readers`: `904` + - `shared`: `640` + - `core/auth/routes`: `51` + +Operating rules: +- No Playwright during the main coverage push +- No runtime code changes unless explicitly escalated as a narrow exception +- Test workers do not perform Git operations +- A dedicated Git/integration worker owns all Git and plan-doc mutations +- A dedicated notifier agent owns Pushover notifications +- The controller is orchestration-only: it does not generate tests, edit code, commit, integrate changes, or send notifications +- Progress toward branch coverage is the primary metric; low-yield churn is grounds for stopping and reassigning work + +## Roles + +### Controller +Owns orchestration only: +- run pre-flight checks +- spawn workers +- assign or reassign lanes and target files +- poll status +- detect anomalies +- order stop-all reviews +- decide whether a bucket is accepted, narrowed, restarted, or discarded +- set coordination flags consumed by the notifier agent + +The controller does not: +- edit tests +- edit runtime code +- update the plan doc directly +- run Git commands +- salvage large weak buckets by hand +- call the Pushover helper directly + +### Git/Integration Worker +Owns all repo mutations outside test generation: +- create and maintain `.worktrees/` +- create worker branches and worktrees +- keep `.worktrees/` ignored if needed +- update `docs/plans/frontend-90-coverage-plan.md` +- inspect `git status`, `git diff --stat`, and worktree health across all worker trees +- integrate accepted buckets one at a time +- create controller-approved commits with Conventional Commit messages and grouped markdown bodies +- prune or recreate discarded worktrees when instructed + +### Notifier Agent +Owns all watch/phone notifications through the `pushover-notify` skill: +- validate Pushover delivery in pre-flight +- send a periodic high-level status summary every 5 minutes +- send immediate human-needed alerts only when the controller explicitly marks the run as requiring the user to return +- never send noisy per-test spam +- never inspect or mutate Git state directly +- repeating summary and escalation behavior should be driven by one controller-owned loop, not repeated per-agent commands; use a temporary local script under `local-scripts/` when a cadence is needed + +### Test Workers +Own one lane each and only touch tests plus test-local helpers within owned paths unless explicitly escalated: +1. `core/auth/routes` +2. `book + author + series + notebook` +3. `metadata + settings + stats` +4. `readers` +5. `shared` + +Test workers do not: +- run Git commands +- edit the plan doc +- integrate other workers’ work +- drift into Playwright or harness churn + +## Pre-Flight Phase + +Before any worker launch, the controller must prove the run can proceed unattended. + +### Pre-flight checks +1. Confirm the branch and repo state are readable and sane. +- `git -C /Users/james/Projects/grimmory/grimmory status --short --branch` +- `git -C /Users/james/Projects/grimmory/grimmory worktree list` +- record any pre-existing untracked or unrelated files so they are not mistaken for worker drift + +2. Confirm the durable plan path exists. +- `docs/plans/frontend-90-coverage-plan.md` must be present and writable by the Git/integration worker + +3. Confirm worktree support is usable. +- `.gitignore` must contain `.worktrees/` +- if `.worktrees/` does not yet exist, that is acceptable; the Git worker creates it later + +4. Confirm Git capabilities are available without interactive approval. +- repo-local `git -C /Users/james/Projects/grimmory/grimmory ...` commands must succeed +- if branch creation or worktree creation requires approval, do not launch workers + +5. Confirm the frontend command surface is usable. +- `just ui typecheck` +- `just ui lint` +- `just ui test` +- `just ui coverage` +- `just ui coverage-summary` +- any failure here blocks launch until the controller re-baselines and updates the plan + +6. Confirm coordination transport is available. +- preferred: `valkey-cli ping` must return `PONG` +- fallback: if Valkey is unavailable, switch to controller polling via agent messages only +- if neither Valkey nor reliable agent polling is available, do not launch unattended + +7. Confirm notifier capability is available and working. +- `PUSHOVER_APP_TOKEN` and `PUSHOVER_USER_KEY` must be present +- notifier agent runs the skill-local helper once with `--dry-run` +- notifier agent then sends one real low-noise pre-flight notification +- if real delivery cannot be confirmed, unattended launch is blocked + +8. Confirm worker lanes are disjoint and target lists are current. +- regenerate the branch-deficit ranking from current coverage output +- verify each initial target file belongs to exactly one lane + +9. Confirm the Git/integration worker can own the repo-mutating path end to end. +- create worktrees +- inspect diffs +- update plan doc +- commit accepted buckets +- if any of these are uncertain, do not start the swarm + +### Pre-flight output +The controller must produce a launch record in the plan doc via the Git/integration worker containing: +- timestamp +- baseline coverage totals +- lane ranking by uncovered branches +- capability results for Git, Just, Valkey, and Pushover +- known pre-existing repo noise +- explicit `launch approved` or `launch blocked` + +### Launch blockers +Do not launch workers if any of the following are true: +- Git repo-local commands are not usable without approval +- the plan doc cannot be updated +- frontend baseline commands are failing +- coordination transport is unavailable +- Pushover delivery cannot be validated +- lane ownership is ambiguous +- current repo state is too noisy to distinguish worker drift from pre-existing changes + +## Launch Record + +- Status: pre-flight completed, swarm narrowed after incident review +- Branch: `chore/expand-frontend-tests` +- Repo state: root currently carries the metadata-viewer integration checkpoint and this plan-doc refresh draft +- Current HEAD: `97019536` +- Prior metadata checkpoint HEAD: `d3f05207` +- Worktree list: + - `/Users/james/Projects/grimmory/grimmory` + - `/Users/james/Projects/grimmory/grimmory/.worktrees/f90-book-author-series-notebook` + - `/Users/james/Projects/grimmory/grimmory/.worktrees/f90-core-auth-routes` + - `/Users/james/Projects/grimmory/grimmory/.worktrees/f90-metadata-settings-stats` + - `/Users/james/Projects/grimmory/grimmory/.worktrees/f90-readers` + - `/Users/james/Projects/grimmory/grimmory/.worktrees/f90-shared` +- `.worktrees/` ignore rule: present in `.gitignore` +- Historical pre-existing repo noise to record: `booklore-ui-migration-prompt.md` +- Notification state: paused pending the single local loop restart; the loop uses `/tmp/f90-status-loop.lock` and `local-scripts/.f90-status-loop.pid` +- Root integration state: + - HEAD `97019536` + - ahead of `origin/chore/expand-frontend-tests` by 11 commits + - integrated buckets: `core/auth/routes`, `bookdrop`, `readers(selection-service only)`, `metadata-viewer`, `book-card`, `shared(url-helper)`, `author-browser` +- Current combined root coverage checkpoint: + - global: statements `24.75%`, branches `19.73%`, functions `20.24%`, lines `38.79%` +- Recent root-side batch: + - `bedcc3b0` `test(readers): stabilize ebook event service spec` + - `9e20879e` `test(book): cover book card decision paths` + - `e4a37866` `test(shared): cover url helper routing fallbacks` +- Current coverage-summary highlights: + - `features/metadata`: statements `42.87%`, branches `23.68%`, functions `34.48%`, lines `45.4%` + - `features/readers`: statements `33.5%`, branches `26.88%`, functions `31.74%`, lines `44.37%` + - `features/book`: statements `21.86%`, branches `19%`, functions `15.3%`, lines `51.63%` + - `shared`: statements `22.96%`, branches `13.28%`, functions `19.9%`, lines `54.75%` + - `features/author-browser`: statements `7.86%`, branches `2.96%`, functions `7.59%`, lines `8.58%` +- Metadata batch acceptance: + - accepted file: `frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.spec.ts` + - measured lane branch movement: `metadata + settings + stats` to `13.08%` branches (`464/3548`), `3084` uncovered + - measured file branch movement: `metadata-viewer.component.ts` to `38.28%` branches (`116/303`) +- Restart lanes available for the next wave: + - `metadata + settings + stats` + - `readers` + - `shared` + +### Incident Log + +- A nonstandard initial worktree setup was detected during launch prep. +- The root checkout remained normal throughout the incident and was not modified outside standard repo-local git operations. +- Malformed `.worktrees/` admin copies were removed safely. +- The lane worktrees were recreated successfully with standard `git worktree add` flows under `/Users/james/Projects/grimmory/grimmory/.worktrees/`. +- The first notifier path generated false-positive "return to machine" alerts; notifications are paused until the single local loop is restarted. +- The shared lane polluted the root checkout with untracked shared specs, so that batch was discarded. +- The broken `metadata`, `readers`, and `shared` lane worktrees were cleaned and recreated from the current root HEAD for restart. +- The preserved `core/auth` worktree edits remain available for later integration. +- The accepted metadata viewer batch was then integrated directly in the root checkout and recorded as the current integration checkpoint. +- The root-side readers/book/shared batch was then committed in sequence from the root checkout and the plan checkpoint refreshed again afterward. + +### Stop-All Review + +- Malformed initial worktree setup incident: nonstandard `.worktrees/` admin copies were detected and repaired before lane launch continued. +- Second incident: shared lane edits landed in the root checkout instead of the shared worktree, which polluted the root with untracked shared specs. +- Decision: + - discard the shared batch + - preserve the core/auth worktree edits for later integration + - keep the broken metadata/readers/shared worktrees cleaned and recreated for restart + - restart later only with stricter worktree-path instructions, tighter drift checks, and the notifier still paused unless the local loop is explicitly started + +## Current Integration Checkpoint + +- Root HEAD: `97019536` +- Root branch status: ahead of `origin/chore/expand-frontend-tests` by 11 commits +- Integrated and validated buckets so far: + - `core/auth/routes` + - `bookdrop` + - `readers(selection-service only)` + - `metadata-viewer` +- Recent root-side commits: + - `bedcc3b0` `test(readers): stabilize ebook event service spec` + - `9e20879e` `test(book): cover book card decision paths` + - `e4a37866` `test(shared): cover url helper routing fallbacks` +- Root tip also includes: + - `97019536` `test(author-browser): cover author service control flow` +- Accepted metadata batch checkpoint: + - commit: `d3f05207` `test(metadata-viewer): cover metadata viewer branches` + - changed file: `frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.spec.ts` + - validation already completed in root: focused spec, typecheck, lint, test, coverage, coverage-summary +- Measured metadata movement: + - global: statements `23.00%`, branches `17.94%`, functions `19.49%`, lines `38.37%` + - `metadata-viewer.component.ts`: branches `38.28%` (`116/303`) + - `metadata/settings/stats`: branches `13.08%` (`464/3548`), uncovered `3084` +- Current combined root coverage checkpoint: + - statements `24.75%` + - branches `19.73%` + - functions `20.24%` + - lines `38.79%` +- Recreated restart lanes: + - `metadata + settings + stats` + - `readers` + - `shared` +- Notification state: + - single local loop is the only allowed status/notification driver + - lock file: `/tmp/f90-status-loop.lock` + - pid file: `local-scripts/.f90-status-loop.pid` + - notifications remain paused until the loop is deliberately restarted +- Next immediate action: + - restart the `book + author + series + notebook` lane on `author-browser` next, since coverage-summary still shows that bucket as the coldest branch surface; if that proves too broad, fall back to `metadata + settings + stats` starting at `metadata-searcher.component.ts` + +## Lane Ownership And First Targets + +### `metadata + settings + stats` +Highest-yield first wave. +Primary targets: +- `features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts` +- `features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts` +- `features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.ts` +- `features/metadata/component/book-metadata-center/metadata-picker/metadata-picker.component.ts` +- `features/settings/task-management/task-management.component.ts` +- `features/stats/component/user-stats/charts/series-progress-chart/series-progress-chart.component.ts` +- `features/stats/component/library-stats/charts/author-universe-chart/author-universe-chart.component.ts` +- `features/settings/view-preferences-parent/view-preferences/view-preferences.component.ts` + +### `book + author + series + notebook` +Includes book-adjacent cold areas. +Primary targets: +- `features/bookdrop/component/bookdrop-file-review/bookdrop-file-review.component.ts` +- `features/book/components/book-browser/book-card/book-card.component.ts` +- `features/author-browser/components/author-browser/author-browser.component.ts` +- `features/book/components/book-browser/book-browser.component.ts` +- `features/book/components/series-page/series-page.component.ts` +- `features/book/components/book-browser/book-table/book-table.component.ts` +- `features/library-creator/library-creator.component.ts` + +### `readers` +Prioritize control-flow-heavy reader surfaces before shallow shells. +Primary targets: +- `features/readers/cbx-reader/cbx-reader.component.ts` +- `features/readers/audiobook-player/audiobook-player.component.ts` +- `features/readers/ebook-reader/core/event.service.ts` +- `features/readers/ebook-reader/ebook-reader.component.ts` +- `features/readers/ebook-reader/features/selection/selection.service.ts` +- `features/readers/pdf-reader/pdf-reader.component.ts` + +### `shared` +Keep as an explicit lane because it is still materially behind. +Primary targets: +- `shared/components/file-mover/file-mover-component.ts` +- `shared/components/book-uploader/book-uploader.component.ts` +- `shared/layout/component/layout-menu/app.menu.component.ts` +- `shared/service/url-helper.service.ts` +- `shared/components/icon-picker/icon-picker-component.ts` +- `shared/service/reading-session.service.ts` +- `shared/service/audiobook-session.service.ts` + +### `core/auth/routes` +Smallest lane, good candidate for an early clean win. +Primary targets: +- `core/security/oauth2-management/authentication-settings.component.ts` +- any remaining branch gaps in `core/custom-reuse-strategy.ts` +- any remaining branch gaps in `core/services/loading.service.ts` +- any remaining branch gaps in `core/security/auth-interceptor.service.ts` +- any remaining branch gaps in `core/security/secure-src.directive.ts` + +## Status And Communication Protocol + +Use a controller-visible heartbeat protocol so unattended runs can be supervised without passive waiting. + +### Status transport +Default: +- each test worker writes heartbeat and progress records to Valkey using a finite TTL namespace like `codex:grimmory:f90::status` +- the Git/integration worker writes per-worktree Git snapshots to `codex:grimmory:f90:git:` +- the controller writes orchestration state to keys like: + - `codex:grimmory:f90:controller:summary` + - `codex:grimmory:f90:controller:human_needed` + - `codex:grimmory:f90:controller:launch_state` +- the notifier agent reads only those shared coordination keys plus lane summaries +- if periodic polling or notification must run continuously, prefer a single controller-owned temporary script over repeated agent shell calls + +Fallback if Valkey is unavailable: +- workers send progress messages to the controller thread and the controller relays summary state to the notifier agent through direct agent messages + +### Test worker heartbeat payload +Emit on start, after target selection, after each meaningful test batch, after each validation run, on block, and before handoff. +Required fields: +- `lane` +- `owned_paths` +- `current_targets` +- `state`: one of `surveying`, `writing_tests`, `running_targeted`, `running_validation`, `ready_for_handoff`, `blocked`, `aborted` +- `spec_files_touched` +- `last_targeted_command` +- `last_targeted_result` +- `last_validation_commands` +- `last_validation_results` +- `latest_observed_coverage_signal` +- `residual_risks` +- `updated_at` + +Coverage signal should be lightweight and frequent: +- at minimum, report target-file count and targeted-test pass/fail +- after any substantial batch, report owned-file coverage movement from local coverage output if available +- do not run expensive full coverage repeatedly just to emit heartbeats + +### Git worker snapshot payload +Emit on a fixed polling cadence for every worktree. +Required fields: +- `lane` +- `worktree_path` +- `branch` +- `git_status_short` +- `diff_stat` +- `changed_files` +- `plan_doc_state` +- `updated_at` + +### Notifier behavior +Periodic summary: +- every 5 minutes +- low-noise, high-level only +- include current global coverage if available, active lanes, lanes ready for handoff, stalled lanes, and whether the run is healthy or in review +- prefer compact multiline messages through stdin; use `--title "Codex"` and `--monospace` when formatting helps + +Immediate human-needed alerts: +- send only when the controller explicitly marks `human_needed=true` +- examples: + - pre-flight blocked + - notification path broken + - Git/worktree operations unexpectedly require approval + - ambiguous repo state needs human judgment + - all viable lanes stalled after stop-all review + - a runtime-code exception appears necessary +- use a more attention-grabbing notification than the periodic summary, but do not use emergency retry mode unless absolutely necessary + +### Polling cadence +- Controller polls heartbeats every 5 minutes +- Git worker snapshots each worktree every 3 to 5 minutes +- Notifier agent sends a periodic summary every 5 minutes +- Any worker heartbeat older than 10 minutes is stale +- Any lane with repeated stale heartbeats triggers review + +## Acceptance Criteria Per Test Worker Bucket + +A bucket is handoff-ready only if all conditions hold: +- touched files stay within owned lane +- no runtime code change unless explicitly escalated and isolated +- targeted tests for the owned area pass via the Just command surface +- `just ui typecheck` passes +- `just ui lint` passes +- `just ui test` passes +- worker emits final handoff payload including: + - changed files + - commands run and results + - residual risks or known gaps + - proposed Conventional Commit subject + - proposed grouped markdown commit body + +Test workers should prefer root commands: +- `just ui ...` +Or, when working inside the frontend subtree: +- `just --justfile frontend/Justfile --working-directory frontend ...` + +No direct Yarn commands in worker instructions. + +## Controller Intervention Rules + +The controller should over-index on intervention rather than waiting for an unobtainable goal. + +Trigger a stop-all review when any of these occur: +- a worker heartbeat goes stale +- Git snapshot shows cross-lane file drift +- a worker accumulates a large diff without passing validation +- a worker reports repeated validation failures on the same bucket +- a worker has multiple test batches with no credible coverage movement +- Git state looks anomalous or inconsistent across worktrees +- a worker starts chasing decorative render coverage instead of branch-bearing logic + +Default low-yield threshold: +- if two successive meaningful batches do not materially reduce the lane’s target-file branch deficit, stop and review +- “materially” means visible improvement in the current target cluster, not just more tests added + +Stop-all review sequence: +1. Controller interrupts all test workers. +2. Git worker captures final status and diff snapshots for every worktree. +3. Controller classifies each lane as: + - `keep and integrate` + - `keep but narrow` + - `restart with new targets` + - `discard` +4. Git worker updates the plan doc with the review outcome. +5. Controller updates the shared summary state. +6. Notifier agent sends the next periodic summary reflecting the review outcome. +7. If human judgment is required, controller sets `human_needed=true` and notifier sends an immediate alert. +8. Controller restarts only the lanes that still have a defensible next move. + +Throwing away weak progress is acceptable. Avoid salvage rabbit holes. + +## Integration Workflow + +The Git/integration worker, under controller direction, performs all integration. + +Per accepted bucket: +1. verify handoff payload completeness +2. inspect worktree Git state and changed-file scope +3. integrate one bucket only +4. create one Conventional Commit for that bucket +5. run: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +6. after every two integrations, or sooner for a large bucket, run: + - `just ui coverage` + - `just ui coverage-summary` +7. update `docs/plans/frontend-90-coverage-plan.md` with: + - current totals + - lane totals + - accepted bucket + - discarded or restarted buckets + - next target shortlist +8. publish the updated high-level status for the notifier agent + +Default integration order by expected branch gain: +1. `metadata + settings + stats` +2. `book + author + series + notebook` +3. `readers` +4. `shared` +5. `core/auth/routes` + +## Plan Doc Requirements + +The plan doc is durable session state and must always be resumable without ambiguity. + +After baseline, after pre-flight, and after every accepted integration or stop-all review, it must contain: +- latest global coverage numbers +- latest lane ranking by uncovered branches +- active workers and owned paths +- current top target files per lane +- accepted buckets and commit subjects +- rejected buckets and why they were rejected +- open blockers and whether any runtime exception was approved +- latest launch record +- latest notification state +- next immediate actions + +The Git/integration worker owns these updates. The controller decides the content. + +## Next Immediate Actions + +1. Restart the `book + author + series + notebook` lane on `author-browser` next, since coverage-summary still shows that bucket as the coldest branch surface; if that proves too broad, fall back to `metadata + settings + stats` starting at `metadata-searcher.component.ts`. +2. Keep the notifier paused until the single local loop is deliberately restarted with tighter incident-only thresholds. +3. Re-rank the remaining cold lanes from the current coverage totals, still prioritizing branch deficit first. +4. Preserve the clean worktrees as the new controller baseline and keep the discarded shared batch out of rotation. +5. Commit this durable plan checkpoint after the metadata batch integration so later sessions can resume from the updated root truth. + +## Assumptions + +- The new `default.rules` entries are sufficient for repo-local Git operations under `git -C /Users/james/Projects/grimmory/grimmory` +- No escalated privileges will be available during the unattended run +- Test workers can rely on Just-based validation only +- Valkey is preferred for transient coordination and is currently available +- The `pushover-notify` skill helper is available and Pushover credentials are present in the environment +- The controller remains orchestration-only for the full run, including during failures and reviews diff --git a/docs/plans/frontend-coverage-phase-2-supervised-swarm.md b/docs/plans/frontend-coverage-phase-2-supervised-swarm.md new file mode 100644 index 000000000..aa2d863dd --- /dev/null +++ b/docs/plans/frontend-coverage-phase-2-supervised-swarm.md @@ -0,0 +1,266 @@ +# Frontend Coverage Phase 2: Harness-First Supervised Swarm + +## Summary + +Drive the next frontend coverage phase from reusable test harnesses instead of one-off spec rescue work. + +Validated baseline on `chore/expand-frontend-tests`: +- `just ui typecheck` +- `just ui lint` +- `just ui test` +- `just ui coverage-summary` + +Current baseline: +- statements `32.84%` +- branches `24.95%` +- functions `28.56%` +- lines `48.10%` + +Current skipped-spec distribution: +- `features/stats`: `32` +- `features/settings`: `26` +- `features/book`: `25` +- `features/readers`: `15` +- `shared`: `12` +- `features/metadata`: `7` +- `features/author-browser`: `6` + +Operating rules for this phase: +- no runtime code changes without explicit approval +- solve the next wave in the test harness first +- git operations stay in one thread only +- the controller is orchestration-only +- branch coverage gain is the primary metric +- mature packages are preferred when they clearly replace bespoke harness code + +## Step 0 + +This file is the new execution plan for the phase. + +Do not mutate `docs/plans/frontend-90-coverage-plan.md` except for cross-reference or historical context. + +Each execution checkpoint appended here must record: +- timestamp +- current branch totals from `just ui coverage-summary` +- accepted harness families +- worker roster and lane ownership +- accepted bucket list +- blocked seam list + +## Checkpoints + +### 2026-03-27 16:36:07 CDT + +Current branch totals from `just ui coverage-summary`: +- statements `33.60%` +- branches `25.28%` +- functions `29.59%` +- lines `48.65%` + +Accepted harness families: +- query/auth/signal bootstrap via `createQueryClientHarness()` and `createAuthServiceStub(...)` +- non-rendering chart bootstrap via `nextChartEmission(...)` and `fakeChartTooltipContext(...)` +- dialog/form bootstrap via `createDynamicDialogHarness(...)` and message-service helpers + +Worker roster and lane ownership for this bootstrap run: +- controller: local single-owner execution only +- harness lane: `frontend/src/app/core/testing/{query-testing,chart-testing,dialog-testing}.ts` +- query/service canaries: `AppSettingsService`, `LibraryService` +- chart canary: `GenreStatsChartComponent` +- dialog canary: `AuthorPhotoSearchComponent` + +Accepted bucket list: +- add `ng-mocks` +- publish shared bootstrap helpers for query, chart, and dialog seams +- convert four skipped canaries into active specs +- validate with `just ui typecheck`, `just ui lint`, `just ui test`, `just ui coverage`, and `just ui coverage-summary` + +Blocked seam list: +- none in the accepted bootstrap set + +## Harness Families + +### 1. Query/Auth/Signal Harness + +Purpose: +- cover eager `injectQuery(...)` +- control auth-token enablement +- assert computed loading and error state +- assert cache invalidation and token-cleared removal + +Shared helpers: +- `createQueryClientHarness()` +- `createAuthServiceStub(initialToken)` +- `flushSignalAndQueryEffects()` +- `createSignalFacade(...)` + +First canaries: +- `AppSettingsService` +- `LibraryService` + +### 2. Non-Rendering Chart Harness + +Purpose: +- assert derived chart datasets +- assert summary fields +- assert tooltip and label callbacks +- avoid live chart rendering as the main assertion surface + +Shared helpers: +- `createChartTranslocoStub()` +- `nextChartEmission(...)` +- `fakeChartTooltipContext(...)` + +First canary: +- `GenreStatsChartComponent` + +### 3. Dialog/Form Harness + +Purpose: +- standardize `DynamicDialogConfig` and `DynamicDialogRef` +- standardize message and confirmation spies +- standardize PrimeNG event payload stubs +- standardize fake-timer flows for dialog lifecycle + +Shared helpers: +- `createDynamicDialogHarness(data)` +- `createMessageServiceSpy()` +- `createConfirmServiceSpy()` + +First canary: +- `AuthorPhotoSearchComponent` + +### 4. Route/Timer/Host-Event Harness + +Purpose: +- query-param syncing +- router navigation doubles +- debounced search +- document click and host-listener control + +### 5. Reader Wrapper Harness + +Purpose: +- cover reader header, sidebar, panel, quick-settings, and settings wrappers +- explicitly exclude full reader runtimes + +## Package Posture + +Default package stance: +- use mature libraries when they directly match the seam and reduce bespoke mocking +- use repo-local helpers only for repo-specific state wiring and tiny adapter glue + +Immediate package decisions: +- standardize `@testing-library/angular` +- standardize `@testing-library/user-event` +- keep `jsdom` +- keep `vitest-canvas-mock` +- keep `msw` as secondary, not primary, for Angular service flows +- add `ng-mocks` early for standalone and PrimeNG-heavy shell work + +## Attack Order + +1. `features/stats` + - highest branch upside with one reusable chart family + - hold plugin and imperative canvas outliers until later +2. query-backed services across `shared`, `features/settings`, `features/book`, and `features/magic-shelf` +3. dialog and form specs across `features/book`, `features/bookdrop`, `features/author-browser`, and selected `features/metadata` +4. reader wrapper specs only +5. settings and shared shells that can reuse the proven signal and route harnesses + +Deferred hold bucket: +- shared layout and menu shells +- author-browser page shell +- full reader runtimes +- view-manager and similar runtime seams + +## Worker Model + +Phase 0: +- one harness owner only +- no swarm until the controller accepts the shared conventions + +Phase 1: +- one controller +- one git and integration lieutenant +- one notify lieutenant +- one harness-generation worker +- up to three spec-generation workers + +Hard rules: +- only git and integration runs git commands +- only notify uses Pushover +- only harness-generation edits shared helper files +- spec workers consume published harnesses and do not invent competing ones + +## Communication Spec + +The controller is assertive and supervises every worker, including git and notify. + +Worker heartbeat: +- target every `2-3` minutes +- absolute maximum `5` minutes +- immediate extra message on `start`, `blocked`, `handoff`, `needs-decision`, `done`, or `drift-detected` + +Worker status format: +- `state | owned_paths | current_target | last_result | blocker | next_10m` + +Allowed `state` values: +- `bootstrapping` +- `implementing` +- `validating` +- `blocked` +- `handoff-ready` +- `stopped` + +Controller reply format: +- `decision | scope | priority | continue_until | stop_condition` + +The controller interrupts immediately when: +- a heartbeat exceeds `5` minutes +- a status report is vague +- a worker touches unowned paths +- a worker proposes runtime edits without approval +- a worker continues low-yield work after a stop signal + +## Stop and Recovery Rules + +Harness canary window: +- `15-20` minutes maximum per family + +Stop a harness spike when: +- it does not unlock one real spec and one near-neighbor candidate inside the window + +Stop a lane when: +- two consecutive specs need bespoke lane-only mocks +- the worker edits outside the owned write set +- the worker reports no branch-relevant progress for one heartbeat cycle +- the worker proposes runtime changes without escalation + +Recovery: +- classify the blocker as `blocked-by-harness`, `blocked-by-runtime-seam`, or `blocked-by-package-gap` +- record the exact seam here +- let git and integration quarantine or discard the batch +- do not let the controller salvage the bucket by doing implementation work + +## Validation + +Per bootstrap canary: +- focused spec +- `just ui typecheck` + +Per accepted bucket: +- focused spec slice +- `just ui typecheck` +- `just ui lint` +- `just ui coverage-summary` + +Checkpoint gates: +- `just ui test` + +Phase close: +- `just ui coverage` +- `just ui coverage-summary` +- `just ui typecheck` +- `just ui lint` +- `just ui test` diff --git a/docs/plans/frontend-coverage-phase-3-lieutenants-swarm.md b/docs/plans/frontend-coverage-phase-3-lieutenants-swarm.md new file mode 100644 index 000000000..9815afc73 --- /dev/null +++ b/docs/plans/frontend-coverage-phase-3-lieutenants-swarm.md @@ -0,0 +1,383 @@ +# Frontend Coverage Phase 3: Lieutenants Swarm + +## Summary + +This phase moves from bootstrap into supervised multi-lane execution. + +Operating model: +- controller: orchestration only +- gitops lieutenant: all git, worktrees, staging, commits, and integration +- notify lieutenant: all Pushover communication through `$pushover-notify` +- workers: tightly bounded lane work only + +Current baseline at phase start on `chore/expand-frontend-tests` (`HEAD 111466b5`): +- statements `33.60%` +- branches `25.28%` +- functions `29.59%` +- lines `48.65%` + +Current skipped-spec distribution: +- `features/stats`: `31` +- `features/settings`: `26` +- `features/book`: `24` +- `features/readers`: `15` +- `shared`: `11` +- `features/metadata`: `7` +- `features/author-browser`: `5` +- `features/bookdrop`: `4` + +Hard constraints: +- no runtime code changes without explicit approval +- git operations stay in one thread only +- notifications are mandatory and plain English +- workers may do seam work, but only within a short, high-yield budget +- branch coverage gain is the primary metric + +## Step 0 + +This file is the execution artifact for the lieutenants swarm phase. + +Do not reuse: +- `docs/plans/frontend-90-coverage-plan.md` +- `docs/plans/frontend-coverage-phase-2-supervised-swarm.md` + +Every checkpoint appended here must record: +- timestamp +- active lanes +- accepted batch +- coverage totals +- bucket-level movement +- worker stop or replacement events +- blocked seams + +## Worktree Model + +Use a new worktree prefix for this phase: +- `.worktrees/covswarm-stats` +- `.worktrees/covswarm-query` +- `.worktrees/covswarm-dialog` +- `.worktrees/covswarm-harness` only if a dedicated shared-helper lane becomes necessary + +Legacy `f90-*` worktrees: +- preserve and ignore +- snapshot their status once during pre-flight +- do not edit them +- do not clean them up during this phase + +## Role Contract + +### Controller + +Responsibilities: +- launch and stop agents +- assign lanes and write scopes +- enforce heartbeats +- accept or reject worker batches +- tell gitops when to integrate +- tell notify when to send normal and urgent messages + +Not allowed: +- no code edits +- no git +- no notifications + +### Gitops Lieutenant + +Responsibilities: +- verify git write access before lane launch +- create and manage `covswarm-*` branches and worktrees +- snapshot root and legacy worktree state +- stage accepted lane changes +- create conventional commits +- integrate accepted lane commits into the root branch +- quarantine or discard failed lane worktrees + +Not allowed: +- no test implementation +- no runtime code edits +- no notifications + +### Notify Lieutenant + +Responsibilities: +- verify Pushover credentials +- run `$pushover-notify --dry-run` pre-flight +- send all progress and escalation messages + +Normal-priority events: +- swarm launch +- bootstrap handoff +- lane launch +- worker stopped or replaced +- checkpoint update +- integration complete +- coverage moved +- final completion + +Urgent events: +- blocker requiring a decision +- runtime change would be needed +- permission problem stops the swarm +- repeated worker-runtime failure +- controller halts the swarm + +Cadence: +- never more often than every `2` minutes +- target every `2-3` minutes when meaningful progress exists +- always at least once every `5` minutes while work is ongoing +- urgent alerts break through immediately + +### Workers + +Responsibilities: +- operate only inside assigned lane paths +- consume existing shared harnesses and packages +- run targeted tests only for touched specs +- report on cadence + +Not allowed: +- no git +- no notifications +- no package changes +- no docs changes +- no shared harness edits unless explicitly assigned as a harness worker + +Required status line: +- `state | owned_paths | current_target | last_result | blocker | next_10m` + +Allowed states: +- `bootstrapping` +- `implementing` +- `validating` +- `blocked` +- `handoff-ready` +- `stopped` + +## Pre-Flight + +Gitops pre-flight: +- confirm root checkout is clean except accepted baseline commits +- confirm `.worktrees/` exists and remains ignored +- snapshot root `git status` +- snapshot `git worktree list` +- snapshot status for each legacy `f90-*` worktree +- create fresh `covswarm-*` worktrees from current root `HEAD` + +Notify pre-flight: +- confirm `PUSHOVER_APP_TOKEN` and `PUSHOVER_USER_KEY` +- run `$pushover-notify --dry-run` +- send one real normal-priority launch update after dry-run success + +Worker runtime health gate: +- first useful status required within `2-3` minutes +- no heartbeat may exceed `5` minutes +- prompt contamination or silent workers fail the gate + +Failure handling: +1. interrupt once for status +2. replace once with a stronger model if needed +3. if replacement also fails, pause that lane and either narrow it or run it locally +4. notify sends normal replacement update and urgent alert only if the swarm is blocked + +## Lane Order + +### Lane 1: Stats + +Scope: +- `frontend/src/app/features/stats/**` spec files only + +Goal: +- convert the next `2-4` high-yield stats specs using the non-rendering chart harness + +Acceptance gate before opening lane 2: +- targeted Vitest for touched stats specs +- gitops integrates the accepted lane batch +- `just ui typecheck` +- `just ui lint` +- `just ui test` +- `just ui coverage-summary` +- controller confirms real `features/stats` branch movement + +### Lane 2: Query/Signal + +Start as soon as lane 1 passes its first acceptance gate. + +Priority order: +1. `frontend/src/app/features/book/service/shelf.service.spec.ts` +2. `frontend/src/app/features/settings/user-management/user.service.spec.ts` +3. `frontend/src/app/features/magic-shelf/service/magic-shelf.service.spec.ts` + +Deferred: +- `frontend/src/app/shared/service/custom-font.service.spec.ts` + - needs a separate browser-font seam family + +### Lane 3: Dialog/Overlay + +Start once either: +- lane 1 reaches its second healthy checkpoint, or +- lane 2 reaches its first healthy checkpoint after launch + +Priority order: +1. `frontend/src/app/features/bookdrop/component/bookdrop-bulk-edit-dialog/bookdrop-bulk-edit-dialog.component.spec.ts` +2. `frontend/src/app/features/book/components/book-browser/lock-unlock-metadata-dialog/lock-unlock-metadata-dialog.component.spec.ts` +3. `frontend/src/app/features/book/components/shelf-edit-dialog/shelf-edit-dialog.component.spec.ts` + +Deferred: +- full reader runtimes +- mixed query-heavy dialog seams until the relevant lane is ready + +Concurrency rule: +- start with lane 1 only +- expand to two active implementation lanes immediately after the first accepted stats batch +- expand to three only if heartbeat discipline and gitops throughput remain healthy + +## Seam Valuation + +Good seam work: +- reusing an existing shared harness +- small lane-local adapters that stay inside a spec file +- thin glue around an approved helper +- mature package usage instead of custom mocking + +Borderline seam work: +- one lane-local helper reused across `2+` specs in the same lane +- one small signal/effect flush or callback adapter +- one thin branch-enabling stub that does not spill into other lanes + +Bad seam work: +- inventing a new shared harness inside a worker lane +- reproducing package behavior with custom test infrastructure +- broad browser-runtime emulation for one spec +- `15-20` minutes of seam work without unlocking a real spec +- two consecutive candidate specs requiring bespoke seam rescue + +Rule: +- each lane gets one short seam spike +- if it does not unlock a real spec, stop and escalate +- if the helper would serve multiple lanes, it becomes a dedicated harness task rather than silent worker drift + +## Validation + +Per worker batch: +- targeted Vitest on touched files + +Per integrated lane batch: +- `just ui typecheck` +- `just ui lint` +- `just ui test` +- `just ui coverage-summary` + +Major checkpoints: +- `just ui coverage` + +## Checkpoints + +### 2026-03-27 bootstrap handoff + +Accepted baseline: +- bootstrap commit `111466b5` +- shared query/chart/dialog helpers landed +- `ng-mocks` added +- four canary specs activated + +Current coverage totals: +- statements `33.60%` +- branches `25.28%` +- functions `29.59%` +- lines `48.65%` + +Current blocked seams: +- browser-font-specific service testing +- full reader runtime seams + +### 2026-03-28 replay window 1 + +Accepted replay batches: +- `2a3b82b6` `test(author-browser): cover author match component flows` +- `152ee9a0` `test(book): cover book notes component flows` +- `fadf732a` `test(author-browser): cover author editor component flows` +- `bf3c5fc0` `test(book): cover shelf creator component flows` +- `6fc5a42d` `test(book): cover book file service flows` +- `32c1de1d` `test(stats): cover page count chart bucketing` + +Replay status: +- deferred queue drained into root +- root frontend gates passing after replay: + - `just ui typecheck` + - `just ui lint` + - `just ui test` + - `just ui coverage` + - `just ui coverage-summary` + +Current coverage totals: +- statements `37.50%` +- branches `27.59%` +- functions `34.66%` +- lines `51.74%` + +Highest-value bucket movement this cycle: +- `features/author-browser` branches `5.19% -> 14.81%` +- `features/book` branches `27.62% -> 29.68%` +- `features/stats` branches `8.40% -> 9.44%` + +Current queued accumulation batches: +- `covswarm-author3` + - file: `frontend/src/app/features/author-browser/components/author-card/author-card.component.spec.ts` + - targeted validation: `env YARN_ENABLE_GLOBAL_CACHE=0 YARN_CACHE_FOLDER=../.yarn/cache corepack yarn vitest run src/app/features/author-browser/components/author-card/author-card.component.spec.ts` + - result: `1` file passed, `8` tests passed + - proposed subject: `test(author-browser): cover author card component flows` +- `covswarm-bookcomp3` + - file: `frontend/src/app/features/book/components/shelf-assigner/shelf-assigner.component.spec.ts` + - targeted validation: `env YARN_ENABLE_GLOBAL_CACHE=0 YARN_CACHE_FOLDER=../.yarn/cache corepack yarn vitest run src/app/features/book/components/shelf-assigner/shelf-assigner.component.spec.ts` + - result: `1` file passed, `7` tests passed + - proposed subject: `test(book): cover shelf assigner component flows` +- `covswarm-author4` + - file: `frontend/src/app/features/author-browser/components/author-detail/author-detail.component.spec.ts` + - targeted validation: `env YARN_ENABLE_GLOBAL_CACHE=0 YARN_CACHE_FOLDER=../.yarn/cache corepack yarn vitest run src/app/features/author-browser/components/author-detail/author-detail.component.spec.ts` + - result: `1` file passed, `8` tests passed + - proposed subject: `test(author-browser): cover author detail component flows` +- `covswarm-bookcomp4` + - file: `frontend/src/app/features/book/components/add-physical-book-dialog/add-physical-book-dialog.component.spec.ts` + - targeted validation: `env YARN_ENABLE_GLOBAL_CACHE=0 YARN_CACHE_FOLDER=../.yarn/cache corepack yarn --cwd frontend vitest run src/app/features/book/components/add-physical-book-dialog/add-physical-book-dialog.component.spec.ts --config vitest.config.ts` + - result: `1` file passed, `10` tests passed + - proposed subject: `test(book): cover add physical book dialog flows` +- `covswarm-bookcomp5` + - file: `frontend/src/app/features/book/components/book-sender/book-sender.component.spec.ts` + - targeted validation: `env YARN_ENABLE_GLOBAL_CACHE=0 YARN_CACHE_FOLDER=../.yarn/cache corepack yarn ng test --watch=false --include src/app/features/book/components/book-sender/book-sender.component.spec.ts` + - result: `1` file passed, `6` tests passed + - proposed subject: `test(book): cover book sender component flows` +- `covswarm-stats2` + - file: `frontend/src/app/features/stats/component/library-stats/charts/language-chart/language-chart.component.spec.ts` + - targeted validation: `env YARN_ENABLE_GLOBAL_CACHE=0 YARN_CACHE_FOLDER=../.yarn/cache corepack yarn vitest run src/app/features/stats/component/library-stats/charts/language-chart/language-chart.component.spec.ts` + - result: `1` file passed, `4` tests passed + - proposed subject: `test(stats): cover language chart aggregation` +- `covswarm-stats3` + - file: `frontend/src/app/features/stats/component/library-stats/charts/metadata-score-chart/metadata-score-chart.component.spec.ts` + - targeted validation: `env YARN_ENABLE_GLOBAL_CACHE=0 YARN_CACHE_FOLDER=../.yarn/cache corepack yarn vitest run src/app/features/stats/component/library-stats/charts/metadata-score-chart/metadata-score-chart.component.spec.ts --config vitest.config.ts` + - result: `1` file passed, `4` tests passed + - proposed subject: `test(stats): cover metadata score chart states` +- `covswarm-bookcomp6` + - file: `frontend/src/app/features/book/components/book-reviews/book-reviews.component.spec.ts` + - targeted validation: `env YARN_ENABLE_GLOBAL_CACHE=0 YARN_CACHE_FOLDER=../.yarn/cache corepack yarn vitest run src/app/features/book/components/book-reviews/book-reviews.component.spec.ts --config vitest.config.ts` + - result: `1` file passed, `10` tests passed + - proposed subject: `test(book): cover book reviews component flows` +- `covswarm-bookcomp7` + - file: `frontend/src/app/features/book/components/book-file-attacher/book-file-attacher.component.spec.ts` + - targeted validation: `yarn vitest run src/app/features/book/components/book-file-attacher/book-file-attacher.component.spec.ts` + - result: `1` file passed, `8` tests passed + - proposed subject: `test(book): cover book file attacher flows` +- `covswarm-stats4` + - file: `frontend/src/app/features/stats/component/user-stats/charts/reading-progress-chart/reading-progress-chart.component.spec.ts` + - targeted validation: `env YARN_ENABLE_GLOBAL_CACHE=0 YARN_CACHE_FOLDER=../.yarn/cache corepack yarn vitest run src/app/features/stats/component/user-stats/charts/reading-progress-chart/reading-progress-chart.component.spec.ts` + - result: `1` file passed, `5` tests passed + - proposed subject: `test(stats): cover reading progress chart bucketing` + +Next accumulation lanes: +- `features/stats/component/user-stats/charts/read-status-chart/read-status-chart.component.spec.ts` +- `features/stats/component/library-stats/charts/publication-trend-chart/publication-trend-chart.component.spec.ts` +- `features/book/components/duplicate-merger/duplicate-merger.component.spec.ts` + +Current blocked seams: +- full `author-browser.component` shell remains high-risk and deferred +- browser-font-specific service testing remains deferred +- full reader runtime seams remain deferred diff --git a/docs/plans/frontend-stub-fill-log.md b/docs/plans/frontend-stub-fill-log.md new file mode 100644 index 000000000..b18d3a244 --- /dev/null +++ b/docs/plans/frontend-stub-fill-log.md @@ -0,0 +1,799 @@ +# Frontend Stub Fill Log + +Single-threaded pass to replace generic TODO spec stubs under `frontend/src/app`. + +Rules for this pass: +- No runtime code changes. +- Replace generic stubs with real specs where possible. +- If a real spec would need a new runtime seam, keep the spec skipped and state the seam explicitly. +- Commits are optional; this log is the durable grouping record. + +## 2026-03-26 + +### Batch 1 +- Scope: initial pure/type-bearing frontend files. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/core/config/api-config.spec.ts` + - `frontend/src/app/features/author-browser/model/author.model.spec.ts` + - `frontend/src/app/features/author-browser/service/author-query-keys.spec.ts` + - `frontend/src/app/features/book/components/book-browser/book-filter/book-filter.config.spec.ts` + - `frontend/src/app/features/book/components/book-browser/sorting/BookSorter.spec.ts` + - `frontend/src/app/features/book/model/library.model.spec.ts` + - `frontend/src/app/features/book/service/library-query-keys.spec.ts` + - `frontend/src/app/features/metadata/model/request/metadata-refresh-type.enum.spec.ts` + - `frontend/src/app/features/readers/ebook-reader/state/themes.constant.spec.ts` + - `frontend/src/app/shared/constants/reset-progress-type.spec.ts` + - `frontend/src/app/shared/model/app-state.model.spec.ts` + - `frontend/src/app/shared/websocket/model/log-notification.model.spec.ts` + +### Batch 2 +- Scope: additional pure models, enums, and type-only request payloads. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/features/book/model/sort.model.spec.ts` + - `frontend/src/app/features/book/model/shelf.model.spec.ts` + - `frontend/src/app/features/metadata/model/request/fetch-metadata-request.model.spec.ts` + - `frontend/src/app/features/metadata/model/request/metadata-refresh-options.model.spec.ts` + - `frontend/src/app/features/metadata/model/request/metadata-refresh-request.model.spec.ts` + - `frontend/src/app/features/notebook/model/notebook.model.spec.ts` + - `frontend/src/app/features/readers/audiobook-player/audiobook.model.spec.ts` + - `frontend/src/app/features/series-browser/model/series.model.spec.ts` + - `frontend/src/app/shared/layout/api/menuchangeevent.spec.ts` + - `frontend/src/app/shared/model/oidc-group-mapping.model.spec.ts` + - `frontend/src/app/shared/models/api-exception.model.spec.ts` + +### Batch 3 +- Scope: remaining pure query keys, settings/email contracts, and light index exports. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/shared/service/app-settings-query-keys.spec.ts` + - `frontend/src/app/features/settings/user-management/user-query-keys.spec.ts` + - `frontend/src/app/features/settings/email-v2/email-provider.model.spec.ts` + - `frontend/src/app/features/settings/email-v2/email-recipient.model.spec.ts` + - `frontend/src/app/features/settings/user-management/content-restriction.model.spec.ts` + - `frontend/src/app/shared/metadata/metadata-field.config.spec.ts` + - `frontend/src/app/shared/metadata/embeddable-fields.config.spec.ts` + - `frontend/src/app/shared/metadata/index.spec.ts` + - `frontend/src/app/features/readers/audiobook-player/index.spec.ts` + +### Batch 4 +- Scope: larger pure models and default config exports. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/shared/model/app-settings.model.spec.ts` + - `frontend/src/app/features/dashboard/models/dashboard-config.model.spec.ts` + - `frontend/src/app/features/book/model/book.model.spec.ts` + +### Batch 5 +- Scope: guards, setup flows, and small websocket/helper utilities that do not need runtime seams. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/core/testing/transloco-testing.spec.ts` + - `frontend/src/app/core/security/guards/manage-library.guard.spec.ts` + - `frontend/src/app/core/security/guards/bookdrop.guard.spec.ts` + - `frontend/src/app/core/security/guards/library-stats.guard.spec.ts` + - `frontend/src/app/core/security/guards/user-stats.guard.spec.ts` + - `frontend/src/app/core/security/guards/edit-metdata.guard.spec.ts` + - `frontend/src/app/shared/components/setup/setup.service.spec.ts` + - `frontend/src/app/shared/components/setup/setup.guard.spec.ts` + - `frontend/src/app/shared/components/setup/login.guard.spec.ts` + - `frontend/src/app/shared/components/setup/setup-redirect.guard.spec.ts` + - `frontend/src/app/shared/websocket/rx-stomp.config.spec.ts` + - `frontend/src/app/shared/websocket/rx-stomp-service-factory.spec.ts` + - `frontend/src/app/features/book/components/book-browser/filter-label.helper.spec.ts` + +### Batch 6 +- Scope: lightweight services and observables that can be exercised without runtime code seams. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/shared/service/page-title.service.spec.ts` + - `frontend/src/app/shared/service/settings-helper.service.spec.ts` + - `frontend/src/app/shared/service/icon-picker.service.spec.ts` + - `frontend/src/app/shared/service/metadata-match-weights.service.spec.ts` + - `frontend/src/app/shared/websocket/notification-event.service.spec.ts` + +### Batch 7 +- Scope: shared HTTP-wrapper services with straightforward request/response contracts. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/shared/service/oidc-group-mapping.service.spec.ts` + - `frontend/src/app/shared/service/book-note.service.spec.ts` + - `frontend/src/app/shared/service/book-note-v2.service.spec.ts` + - `frontend/src/app/shared/service/book-mark.service.spec.ts` + - `frontend/src/app/shared/service/annotation.service.spec.ts` + - `frontend/src/app/shared/service/reading-session-api.service.spec.ts` + - `frontend/src/app/shared/service/file-download.service.spec.ts` + - `frontend/src/app/shared/websocket/rx-stomp.service.spec.ts` + - `frontend/src/app/shared/services/dialog-launcher.service.spec.ts` + - `frontend/src/app/shared/service/app-settings.service.spec.ts` + +### Batch 8 +- Scope: metadata utilities and lightweight shared/book HTTP services. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/shared/services/book-cover.service.spec.ts` + - `frontend/src/app/shared/service/file-operations.service.spec.ts` + - `frontend/src/app/features/book/service/metadata-task.spec.ts` + - `frontend/src/app/shared/metadata/metadata-utils.service.spec.ts` + - `frontend/src/app/shared/metadata/metadata-form.builder.spec.ts` + - `frontend/src/app/shared/service/metadata-progress.service.spec.ts` + +### Batch 9 +- Scope: shared utility services, theme helpers, and seam-documented runtime-heavy specs. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/shared/layout/component/theme-palette-extend.spec.ts` + - `frontend/src/app/shared/layout/component/theme-configurator/favicon-service.spec.ts` + - `frontend/src/app/shared/service/pdf-annotation.service.spec.ts` + - `frontend/src/app/shared/service/audiobook-session.service.spec.ts` + - `frontend/src/app/shared/service/custom-font.service.spec.ts` + - `frontend/src/app/shared/service/app-config.service.spec.ts` + +### Batch 10 +- Scope: shared layout, upload, icon, and reader-session services with real browser/service coverage. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/shared/layout/component/layout-main/service/app.layout.service.spec.ts` + - `frontend/src/app/shared/layout/component/theme-configurator/background-upload.service.spec.ts` + - `frontend/src/app/features/readers/audiobook-player/audiobook.service.spec.ts` + - `frontend/src/app/shared/services/icon.service.spec.ts` + - `frontend/src/app/shared/service/reading-session.service.spec.ts` + +### Batch 11 +- Scope: low-friction shared/settings service wrappers plus one explicit dynamic-component seam. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/shared/components/directory-picker/utility.service.spec.ts` + - `frontend/src/app/features/settings/audit-logs/audit-log.service.spec.ts` + - `frontend/src/app/features/library-creator/library-loading.service.spec.ts` + +### Batch 12 +- Scope: book service control-flow surfaces and a query-heavy user-service seam note. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/features/book/service/cbx-reader.service.spec.ts` + - `frontend/src/app/features/book/service/book-patch.service.spec.ts` + - `frontend/src/app/features/settings/user-management/user.service.spec.ts` + +### Batch 13 +- Scope: small shared standalone components with direct behavior or render assertions. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/shared/components/external-doc-link/external-doc-link.component.spec.ts` + - `frontend/src/app/shared/components/empty/empty.component.spec.ts` + - `frontend/src/app/shared/components/tag/tag.component.spec.ts` + +### Batch 14 +- Scope: one pure library-loading component plus local shared components with mocked dialog and websocket behavior. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/features/library-creator/library-loading/library-loading.component.spec.ts` + - `frontend/src/app/shared/components/live-notification-box/live-notification-box.component.spec.ts` + - `frontend/src/app/shared/components/directory-picker/directory-picker.component.spec.ts` + +### Batch 15 +- Scope: runtime-heavy shared and library flows converted from generic placeholders to seam-specific skipped specs. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/features/magic-shelf/service/magic-shelf.service.spec.ts` + - `frontend/src/app/features/library-creator/library-creator.component.spec.ts` + +### Batch 28 +- Scope: next settings, book, metadata, and stats shells converted from generic TODO stubs to explicit seam-documented specs. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Remaining generic TODO stubs: `59` +- Files: + - `frontend/src/app/features/settings/library-metadata-settings/library-metadata-settings.component.spec.ts` + - `frontend/src/app/features/settings/view-preferences-parent/filter-preferences/filter-preferences.component.spec.ts` + - `frontend/src/app/features/book/service/book-menu.service.spec.ts` + - `frontend/src/app/features/book/service/book-file.service.spec.ts` + - `frontend/src/app/features/settings/settings.component.spec.ts` + - `frontend/src/app/features/settings/device-settings/device-settings-component.spec.ts` + - `frontend/src/app/features/bookdrop/component/bookdrop-file-metadata-picker/bookdrop-file-metadata-picker.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/charts/reading-dna-chart/reading-dna-chart.component.spec.ts` + - `frontend/src/app/features/metadata/component/cover-search/cover-search.component.spec.ts` + - `frontend/src/app/features/book/components/book-notes/book-notes-component.spec.ts` + +### Batch 29 +- Scope: KOReader and metadata settings received real coverage where the surfaces were deterministic; the remaining dialog/query-heavy files were converted to explicit seam notes. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Remaining generic TODO stubs: `49` +- Files: + - `frontend/src/app/features/settings/metadata-settings/metadata-persistence-settings/metadata-persistence-settings-component.spec.ts` + - `frontend/src/app/features/settings/device-settings/component/koreader-settings/koreader.service.spec.ts` + - `frontend/src/app/features/settings/device-settings/component/koreader-settings/koreader-settings-component.spec.ts` + - `frontend/src/app/features/metadata/component/multi-book-metadata-editor/multi-book-metadata-editor-component.spec.ts` + - `frontend/src/app/features/metadata/component/bulk-metadata-update/bulk-metadata-update-component.spec.ts` + - `frontend/src/app/features/book/components/book-sender/book-sender.component.spec.ts` + - `frontend/src/app/features/book/components/series-page/series-page.component.spec.ts` + - `frontend/src/app/features/settings/metadata-settings/metadata-settings-component.spec.ts` + - `frontend/src/app/features/bookdrop/component/bookdrop-pattern-extract-dialog/bookdrop-pattern-extract-dialog.component.spec.ts` + - `frontend/src/app/features/settings/user-profile-dialog/user-profile-dialog.component.spec.ts` + +### Batch 30 +- Scope: simple dialog, reader footer, kobo settings, public review settings, and book-card-lite now have real tests; the surrounding shell-heavy reader/email/file-attach surfaces were converted to explicit seam notes. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Remaining generic TODO stubs: `39` +- Files: + - `frontend/src/app/features/bookdrop/component/bookdrop-finalize-result-dialog/bookdrop-finalize-result-dialog.component.spec.ts` + - `frontend/src/app/features/readers/cbx-reader/layout/footer/cbx-footer.component.spec.ts` + - `frontend/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo.service.spec.ts` + - `frontend/src/app/features/settings/metadata-settings/public-reviews-settings/public-reviews-settings-component.spec.ts` + - `frontend/src/app/features/book/components/book-card-lite/book-card-lite-component.spec.ts` + - `frontend/src/app/features/readers/cbx-reader/layout/sidebar/cbx-sidebar.component.spec.ts` + - `frontend/src/app/features/readers/ebook-reader/dialogs/settings-dialog.component.spec.ts` + - `frontend/src/app/features/settings/email-v2/email-v2-recipient/email-v2-recipient.component.spec.ts` + - `frontend/src/app/features/settings/email-v2/email-v2-provider/email-v2-provider.component.spec.ts` + - `frontend/src/app/features/book/components/book-file-attacher/book-file-attacher.component.spec.ts` + - `frontend/src/app/shared/layout/component/layout-topbar/app.topbar.component.spec.ts` + - `frontend/src/app/shared/components/book-uploader/book-uploader.component.spec.ts` + - `frontend/src/app/features/settings/custom-fonts/custom-fonts.component.spec.ts` + +### Batch 16 +- Scope: layout-heavy shells converted from generic placeholders to seam-specific skipped specs. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/shared/layout/component/theme-configurator/theme-configurator.component.spec.ts` + - `frontend/src/app/shared/layout/component/layout-main/app.layout.component.spec.ts` + - `frontend/src/app/shared/layout/component/layout-sidebar/app.sidebar.component.spec.ts` + - `frontend/src/app/shared/layout/component/layout-menu/app.menu.component.spec.ts` + - `frontend/src/app/shared/layout/component/layout-menu/app.menuitem.component.spec.ts` + +### Batch 17 +- Scope: real coverage for shared standalone form and dialog components with direct control-flow assertions. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/shared/components/change-password/change-password.component.spec.ts` + - `frontend/src/app/shared/components/icon-display/icon-display.component.spec.ts` + - `frontend/src/app/shared/components/setup/setup.component.spec.ts` + - `frontend/src/app/shared/layout/component/theme-configurator/upload-dialog/upload-dialog.component.spec.ts` + - `frontend/src/app/shared/layout/component/layout-menu/version-changelog-dialog/version-changelog-dialog.component.spec.ts` + +### Batch 18 +- Scope: one real shared progress widget, one real stats HTTP wrapper, and seam-specific replacements for query-runtime-heavy services/components. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/shared/components/metadata-progress-widget/metadata-progress-widget-component.spec.ts` + - `frontend/src/app/features/settings/user-management/user-stats.service.spec.ts` + - `frontend/src/app/features/book/service/shelf.service.spec.ts` + - `frontend/src/app/features/book/service/library.service.spec.ts` + - `frontend/src/app/shared/components/icon-picker/icon-picker-component.spec.ts` + +### Batch 19 +- Scope: bookdrop API/control-flow coverage plus one seam-specific replacement for a menu-command-heavy service. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/features/bookdrop/service/bookdrop-file-api.service.spec.ts` + - `frontend/src/app/features/bookdrop/service/bookdrop-file.service.spec.ts` + - `frontend/src/app/features/bookdrop/service/bookdrop.service.spec.ts` + - `frontend/src/app/features/book/service/book-metadata.service.spec.ts` + - `frontend/src/app/features/book/service/library-shelf-menu.service.spec.ts` + +### Batch 20 +- Scope: shared utility components with real coverage plus seam-specific replacements for reader/chart-heavy surfaces that still lack clean injectable seams. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/shared/components/cover-generator/cover-generator.component.spec.ts` + - `frontend/src/app/shared/components/unified-notification-popover/unified-notification-popover-component.spec.ts` + - `frontend/src/app/shared/components/file-mover/file-mover-component.spec.ts` + - `frontend/src/app/features/readers/pdf-reader/pdf-reader.component.spec.ts` + - `frontend/src/app/features/readers/cbx-reader/cbx-reader.component.spec.ts` + - `frontend/src/app/features/readers/audiobook-player/audiobook-player.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/charts/genre-stats-chart/genre-stats-chart.component.spec.ts` + +### Batch 21 +- Scope: book cache/control-flow services with real coverage, one real series-card component spec, and seam-specific replacements for query-runtime and invalid-template surfaces. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/features/book/service/book-socket.service.spec.ts` + - `frontend/src/app/features/book/service/book-metadata-manage.service.spec.ts` + - `frontend/src/app/features/series-browser/components/series-card/series-card.component.spec.ts` + - `frontend/src/app/features/book/service/book.service.spec.ts` + - `frontend/src/app/features/series-browser/components/series-scroller/series-scroller.component.spec.ts` + +### Batch 22 +- Scope: reader-preference and naming settings with real control-flow coverage, plus seam-specific replacements for browser-heavy settings shells and dialogs. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/features/settings/reader-preferences/cbx-reader-preferences/cbx-reader-preferences-component.spec.ts` + - `frontend/src/app/features/settings/global-preferences/metadata-match-weights/metadata-match-weights-component.spec.ts` + - `frontend/src/app/features/settings/file-naming-pattern/file-naming-pattern.component.spec.ts` + - `frontend/src/app/features/settings/reader-preferences/pdf-reader-preferences/pdf-reader-preferences-component.spec.ts` + - `frontend/src/app/features/settings/view-preferences-parent/sidebar-sorting-preferences/sidebar-sorting-preferences.component.spec.ts` + - `frontend/src/app/features/settings/global-preferences/global-preferences.component.spec.ts` + - `frontend/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.spec.ts` + - `frontend/src/app/features/settings/audit-logs/audit-logs.component.spec.ts` + - `frontend/src/app/features/settings/view-preferences-parent/view-preferences/view-preferences.component.spec.ts` + - `frontend/src/app/features/settings/global-preferences/metadata-provider-settings/metadata-provider-settings.component.spec.ts` + +### Batch 23 +- Scope: dashboard and stats visualization surfaces converted from generic placeholders to explicit seam notes where real coverage would require chart, canvas, scroll, or dashboard orchestration adapters. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/features/dashboard/components/dashboard-scroller/dashboard-scroller.component.spec.ts` + - `frontend/src/app/features/dashboard/components/dashboard-settings/dashboard-settings.component.spec.ts` + - `frontend/src/app/features/dashboard/components/main-dashboard/main-dashboard.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/charts/reading-session-timeline/reading-session-timeline.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/charts/session-archetypes-chart/session-archetypes-chart.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/charts/favorite-days-chart/favorite-days-chart.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/charts/book-flow-chart/book-flow-chart.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/charts/completion-timeline-chart/completion-timeline-chart.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/charts/peak-hours-chart/peak-hours-chart.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/charts/reading-session-heatmap/reading-session-heatmap.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/charts/read-status-chart/read-status-chart.component.spec.ts` + - `frontend/src/app/features/notebook/components/notebook/notebook.component.spec.ts` + +### Batch 24 +- Scope: additional user-stats chart placeholders converted into explicit seam notes for chart-runtime, effect, callback, and aggregation boundaries instead of generic TODO stubs. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/features/stats/component/user-stats/charts/page-turner-chart/page-turner-chart.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/charts/reading-progress-chart/reading-progress-chart.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/charts/completion-race-chart/completion-race-chart.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/charts/rating-taste-chart/rating-taste-chart.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/charts/reading-clock-chart/reading-clock-chart.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/charts/personal-rating-chart/personal-rating-chart.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/charts/reading-heatmap-chart/reading-heatmap-chart.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/charts/reading-habits-chart/reading-habits-chart.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/charts/series-progress-chart/series-progress-chart.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/charts/book-length-chart/book-length-chart.component.spec.ts` + +### Batch 25 +- Scope: author-browser, book dialog, user-management, and additional stats surfaces converted from generic placeholders into explicit seam notes where real coverage would require routed dialog stacks, Prime widget runtime, or chart adapters. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/features/author-browser/components/author-photo-search/author-photo-search.component.spec.ts` + - `frontend/src/app/features/author-browser/components/author-card/author-card.component.spec.ts` + - `frontend/src/app/features/author-browser/components/author-browser/author-browser.component.spec.ts` + - `frontend/src/app/features/author-browser/components/author-detail/author-detail.component.spec.ts` + - `frontend/src/app/features/author-browser/components/author-editor/author-editor.component.spec.ts` + - `frontend/src/app/features/author-browser/components/author-match/author-match.component.spec.ts` + - `frontend/src/app/features/book/components/book-searcher/book-searcher.component.spec.ts` + - `frontend/src/app/features/book/components/duplicate-merger/duplicate-merger.component.spec.ts` + - `frontend/src/app/features/book/components/add-physical-book-dialog/add-physical-book-dialog.component.spec.ts` + - `frontend/src/app/features/book/components/shelf-assigner/shelf-assigner.component.spec.ts` + - `frontend/src/app/features/settings/user-management/user-management.component.spec.ts` + - `frontend/src/app/features/settings/user-management/create-user-dialog/create-user-dialog.component.spec.ts` + - `frontend/src/app/features/settings/user-management/content-restrictions-editor/content-restrictions-editor.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/charts/publication-era-chart/publication-era-chart.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/charts/reading-debt-chart/reading-debt-chart.component.spec.ts` + +### Batch 26 +- Scope: simple reader dialogs and header upgraded to real specs, while library-stats, reader-shell, and bookdrop orchestration placeholders were replaced with seam-specific notes. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/features/readers/cbx-reader/dialogs/cbx-shortcuts-help.component.spec.ts` + - `frontend/src/app/features/readers/cbx-reader/dialogs/cbx-note-dialog.component.spec.ts` + - `frontend/src/app/features/readers/ebook-reader/dialogs/note-dialog.component.spec.ts` + - `frontend/src/app/features/readers/ebook-reader/dialogs/metadata-dialog.component.spec.ts` + - `frontend/src/app/features/readers/cbx-reader/layout/header/cbx-header.component.spec.ts` + - `frontend/src/app/features/stats/component/library-stats/library-stats.component.spec.ts` + - `frontend/src/app/features/bookdrop/component/bookdrop-bulk-edit-dialog/bookdrop-bulk-edit-dialog.component.spec.ts` + - `frontend/src/app/features/series-browser/components/series-browser/series-browser.component.spec.ts` + - `frontend/src/app/features/stats/component/library-stats/charts/metadata-score-chart/metadata-score-chart.component.spec.ts` + - `frontend/src/app/features/bookdrop/component/bookdrop-files-widget/bookdrop-files-widget.component.spec.ts` + - `frontend/src/app/features/readers/ebook-reader/ebook-reader.component.spec.ts` + - `frontend/src/app/features/stats/component/library-stats/charts/book-formats-chart/book-formats-chart.component.spec.ts` + +### Batch 27 +- Scope: remaining library-stats chart placeholders plus ebook and CBX shell surfaces converted from generic TODO stubs into explicit chart/runtime seam notes. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Files: + - `frontend/src/app/features/stats/component/library-stats/charts/top-items-chart/top-items-chart.component.spec.ts` + - `frontend/src/app/features/stats/component/library-stats/charts/page-count-chart/page-count-chart.component.spec.ts` + - `frontend/src/app/features/stats/component/library-stats/charts/language-chart/language-chart.component.spec.ts` + - `frontend/src/app/features/stats/component/library-stats/charts/publication-timeline-chart/publication-timeline-chart.component.spec.ts` + - `frontend/src/app/features/stats/component/library-stats/charts/reading-journey-chart/reading-journey-chart.component.spec.ts` + - `frontend/src/app/features/stats/component/library-stats/charts/author-universe-chart/author-universe-chart.component.spec.ts` + - `frontend/src/app/features/stats/component/library-stats/charts/publication-trend-chart/publication-trend-chart.component.spec.ts` + - `frontend/src/app/features/readers/ebook-reader/dialogs/shortcuts-help.component.spec.ts` + - `frontend/src/app/features/readers/ebook-reader/layout/header/header.component.spec.ts` + - `frontend/src/app/features/readers/cbx-reader/layout/quick-settings/cbx-quick-settings.component.spec.ts` + +### Batch 31 +- Scope: branch-heavy book helper/services upgraded to real specs, while book filter/table and upload dialog placeholders were replaced with explicit component seam notes. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Remaining generic TODO stubs after batch: `29` +- Files: + - `frontend/src/app/features/book/components/book-reviews/book-review-service.spec.ts` + - `frontend/src/app/features/book/components/book-browser/book-dialog-helper.service.spec.ts` + - `frontend/src/app/features/book/components/book-browser/book-filter-orchestration.service.spec.ts` + - `frontend/src/app/features/book/components/book-browser/book-card-overlay-preference.service.spec.ts` + - `frontend/src/app/features/book/components/book-browser/book-filter/book-filter.service.spec.ts` + - `frontend/src/app/features/book/components/book-browser/book-filter/book-filter.component.spec.ts` + - `frontend/src/app/features/book/components/book-browser/book-table/book-table.component.spec.ts` + - `frontend/src/app/features/book/components/book-reviews/book-reviews.component.spec.ts` + - `frontend/src/app/features/book/components/additional-file-uploader/additional-file-uploader.component.spec.ts` + - `frontend/src/app/features/book/components/bulk-isbn-import-dialog/bulk-isbn-import-dialog.component.spec.ts` + +### Batch 32 +- Scope: finished the remaining generic frontend coverage stubs by adding direct class or HTTP tests for the cheap service surfaces and replacing the heavy Angular or PrimeNG or reader-shell placeholders with explicit seam-noted skipped specs. +- Status: completed. +- Validation: + - `just ui typecheck` + - `just ui lint` + - `just ui test` +- Remaining generic TODO stubs after batch: `0` +- Files: + - `frontend/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-sync-settings.service.spec.ts` + - `frontend/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.spec.ts` + - `frontend/src/app/features/readers/ebook-reader/features/annotations/annotation.service.spec.ts` + - `frontend/src/app/features/readers/ebook-reader/index.spec.ts` + - `frontend/src/app/features/readers/ebook-reader/shared/icon.component.spec.ts` + - `frontend/src/app/features/settings/reader-preferences/reader-preferences.component.spec.ts` + - `frontend/src/app/features/stats/component/user-stats/user-stats.component.spec.ts` + - `frontend/src/app/features/book/components/book-browser/book-browser.component.spec.ts` + - `frontend/src/app/features/book/components/book-browser/lock-unlock-metadata-dialog/lock-unlock-metadata-dialog.component.spec.ts` + - `frontend/src/app/features/book/components/book-browser/sorting/multi-sort-popover/multi-sort-popover.component.spec.ts` + - `frontend/src/app/features/book/components/shelf-creator/shelf-creator.component.spec.ts` + - `frontend/src/app/features/book/components/shelf-edit-dialog/shelf-edit-dialog.component.spec.ts` + - `frontend/src/app/features/metadata/component/book-metadata-center/book-metadata-center.component.spec.ts` + - `frontend/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.spec.ts` + - `frontend/src/app/features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.spec.ts` + - `frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.spec.ts` + - `frontend/src/app/features/readers/ebook-reader/core/view-manager.service.spec.ts` + - `frontend/src/app/features/readers/ebook-reader/layout/footer/footer.component.spec.ts` + - `frontend/src/app/features/readers/ebook-reader/layout/header/quick-settings.component.spec.ts` + - `frontend/src/app/features/readers/ebook-reader/layout/panel/panel.component.spec.ts` + - `frontend/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.component.spec.ts` + - `frontend/src/app/features/readers/ebook-reader/shared/selection-popup.component.spec.ts` + - `frontend/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-settings-component.spec.ts` + - `frontend/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo-sync-settings-component.spec.ts` + - `frontend/src/app/features/settings/email-v2/create-email-provider-dialog/create-email-provider-dialog.component.spec.ts` + - `frontend/src/app/features/settings/email-v2/create-email-recipient-dialog/create-email-recipient-dialog.component.spec.ts` + - `frontend/src/app/features/settings/email-v2/email-v2.component.spec.ts` + - `frontend/src/app/features/settings/opds-settings/opds-settings.spec.ts` + - `frontend/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.spec.ts` + +## Proposed Commit Shapes + +These are controller-friendly Conventional Commit shapes for the logged batches. Each body is grouped markdown that can be used directly or merged into larger follow-up commits. + +### Batch 1 +- Subject: `test(frontend): cover pure models and config contracts` +- Body: + - `- Coverage: add type-level specs for pure frontend config, model, and enum surfaces under core, author-browser, book, metadata, readers, and shared.` + - `- Intent: replace placeholder specs with cheap deterministic assertions that lock down static contract behavior without runtime seams.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 2 +- Subject: `test(frontend): cover request payload and contract models` +- Body: + - `- Coverage: add specs for additional book, metadata, notebook, readers, series-browser, and shared request or model contracts.` + - `- Intent: keep the stub-replacement pass moving through deterministic type-bearing files before shifting into heavier service and component surfaces.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 3 +- Subject: `test(frontend): cover query keys and barrel exports` +- Body: + - `- Coverage: add tests for shared and settings query keys, email contracts, metadata exports, and audiobook barrel exports.` + - `- Intent: close out low-risk placeholder specs where real value comes from locking contract shape and export stability.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 4 +- Subject: `test(frontend): cover larger model defaults and dashboard contracts` +- Body: + - `- Coverage: add specs for the main app-settings, dashboard, and book models.` + - `- Intent: finish the remaining pure model stubs before shifting toward control-flow and service behavior.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 5 +- Subject: `test(frontend): cover setup and guard utilities` +- Body: + - `- Coverage: add deterministic tests for setup services, setup guards, security guards, websocket helpers, and small filter helpers.` + - `- Intent: replace placeholder coverage with branch-bearing guard and bootstrap assertions that do not require runtime code changes.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 6 +- Subject: `test(frontend): cover lightweight shared services` +- Body: + - `- Coverage: add tests for page title, settings helper, icon picker, metadata-match weights, and notification event services.` + - `- Intent: convert low-friction service placeholders into real control-flow coverage before moving to HTTP-heavy wrappers.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 7 +- Subject: `test(frontend): cover shared HTTP service wrappers` +- Body: + - `- Coverage: add request and response tests for shared annotation, note, bookmark, reading-session, websocket, and group-mapping services.` + - `- Intent: replace generic HTTP-wrapper stubs with real endpoint-shape coverage that can fail honestly when request contracts drift.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 8 +- Subject: `test(frontend): cover metadata utilities and book HTTP helpers` +- Body: + - `- Coverage: add tests for metadata form and utility services, file operations, book cover helpers, metadata progress, and metadata-task behavior.` + - `- Intent: push coverage into utility and helper layers that affect metadata control flow without needing heavy component harnesses.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 9 +- Subject: `test(frontend): cover shared utilities and document seam-heavy specs` +- Body: + - `- Coverage: add real tests for theme, PDF annotation, audiobook session, and config helpers while converting the remaining runtime-heavy shared stubs into explicit seam notes.` + - `- Intent: separate deterministic coverage wins from surfaces that still need browser or runtime harnesses later.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 10 +- Subject: `test(frontend): cover layout upload and reader-session services` +- Body: + - `- Coverage: add real tests for layout service, background upload, audiobook service, icon service, and reading-session behavior.` + - `- Intent: grow coverage through shared layout and reader utilities without changing runtime code.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 11 +- Subject: `test(frontend): cover lightweight settings wrappers` +- Body: + - `- Coverage: add tests for directory-picker utilities, audit-log service behavior, and the low-friction library-loading path.` + - `- Intent: keep the pass focused on cheap deterministic seams while documenting the remaining dynamic component seam explicitly.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 12 +- Subject: `test(frontend): cover book service control flow` +- Body: + - `- Coverage: add real service tests for CBX reader and book patch flows and replace the user-service placeholder with a seam-aware spec.` + - `- Intent: increase branch coverage in book service layers while acknowledging the query-heavy user-service runtime boundary.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 13 +- Subject: `test(frontend): cover small shared standalone components` +- Body: + - `- Coverage: add direct component behavior tests for external links, empty states, and tag rendering.` + - `- Intent: clear straightforward standalone component stubs without spending time on decorative template-only churn.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 14 +- Subject: `test(frontend): cover library loading and local shared components` +- Body: + - `- Coverage: add tests for library-loading, live-notification, and directory-picker components using mocked local dependencies.` + - `- Intent: pick off component surfaces that have real behavior but do not require heavy application orchestration.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 15 +- Subject: `test(frontend): document shared runtime seams` +- Body: + - `- Coverage: replace remaining shared and library runtime-heavy placeholders with explicit seam-noted skipped specs.` + - `- Intent: make the remaining blocker surfaces auditable instead of leaving generic TODO stubs behind.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 16 +- Subject: `test(frontend): document layout shell seams` +- Body: + - `- Coverage: convert layout-heavy shell placeholders into seam-specific skipped specs.` + - `- Intent: record the need for mounted layout harnesses without spending time on brittle shallow shell tests.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 17 +- Subject: `test(frontend): cover shared forms and dialogs` +- Body: + - `- Coverage: add real tests for shared standalone form and dialog components with direct control-flow assertions.` + - `- Intent: capture meaningful component behavior where the harness cost is still low enough to justify real tests.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 18 +- Subject: `test(frontend): cover progress and stats wrappers` +- Body: + - `- Coverage: add real tests for a shared progress widget and a stats HTTP wrapper while documenting heavier query-driven seams.` + - `- Intent: keep coverage growth honest by splitting easy wrappers from runtime-heavy component and service surfaces.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 19 +- Subject: `test(frontend): cover bookdrop API branches` +- Body: + - `- Coverage: add bookdrop API and control-flow coverage and replace the remaining menu-command-heavy service stub with a seam note.` + - `- Intent: grow branch coverage in bookdrop services while avoiding low-yield template churn.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 20 +- Subject: `test(frontend): cover shared utility components` +- Body: + - `- Coverage: add real tests for shared utility components and convert heavier reader or chart placeholders into explicit seam-noted skips.` + - `- Intent: continue replacing generic placeholders while keeping runtime-heavy chart and reader shells out of the main path.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 21 +- Subject: `test(frontend): cover book cache and series card behavior` +- Body: + - `- Coverage: add real tests for book cache and control-flow services plus the series-card component, and document the remaining query-runtime seams.` + - `- Intent: prioritize behavior-bearing book surfaces instead of spreading effort over decorative render-only coverage.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 22 +- Subject: `test(frontend): cover reader preference settings flows` +- Body: + - `- Coverage: add real tests for reader-preference and naming settings while replacing browser-heavy settings shells and dialogs with seam notes.` + - `- Intent: move settings coverage upward without inventing runtime seams for the stubborn UI-heavy surfaces.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 23 +- Subject: `test(frontend): document dashboard and stats visualization seams` +- Body: + - `- Coverage: replace dashboard and stats visualization placeholders with explicit chart, canvas, scroll, and orchestration seam notes.` + - `- Intent: make the expensive visualization blockers explicit instead of keeping them as generic unowned TODO stubs.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 24 +- Subject: `test(frontend): document remaining user stats chart seams` +- Body: + - `- Coverage: convert another wave of user-stats chart placeholders into explicit runtime seam notes.` + - `- Intent: keep the coverage pass honest by documenting chart-runtime blockers without pretending that render smoke tests would help.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 25 +- Subject: `test(frontend): document author-browser and dialog seams` +- Body: + - `- Coverage: replace author-browser, book-dialog, user-management, and additional stats placeholders with routed dialog or widget seam notes.` + - `- Intent: record the real blocker surfaces cleanly and avoid low-yield retries on complex dialog stacks.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 26 +- Subject: `test(frontend): cover reader dialogs and note library-stats seams` +- Body: + - `- Coverage: add real tests for simple reader dialogs and header behavior and document the remaining library-stats, reader-shell, and bookdrop orchestration seams.` + - `- Intent: combine cheap reader wins with explicit notes for surfaces that still need mounted runtime harnesses.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 27 +- Subject: `test(frontend): document remaining library stats and reader shell seams` +- Body: + - `- Coverage: replace the remaining library-stats chart placeholders and ebook or CBX shell stubs with explicit chart and runtime seam notes.` + - `- Intent: finish the chart-heavy placeholder cleanup in a durable, auditable way.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 28 +- Subject: `test(frontend): document settings and metadata shell seams` +- Body: + - `- Coverage: convert another wave of settings, book, metadata, and stats shells from generic TODO stubs into explicit seam-documented specs.` + - `- Intent: keep the pass moving through high-friction surfaces without faking useful coverage.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 29 +- Subject: `test(frontend): cover deterministic settings services` +- Body: + - `- Coverage: add real tests for KOReader and metadata settings surfaces where the behavior is deterministic, and document the remaining dialog-heavy seams.` + - `- Intent: take the cheap service and settings wins while isolating the harder modal and query-driven blockers.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 30 +- Subject: `test(frontend): cover selected reader and settings widgets` +- Body: + - `- Coverage: add real tests for a simple dialog, the CBX footer, kobo settings service behavior, public review settings, and book-card-lite.` + - `- Intent: harvest another set of low-friction component and service wins while documenting the surrounding reader and email shell seams.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 31 +- Subject: `test(frontend): cover book helper and review services` +- Body: + - `- Coverage: add real tests for book review, dialog helper, orchestration, and overlay-preference services, and convert the remaining book browser and upload shells into explicit seam notes.` + - `- Intent: push branch coverage into real book control flow instead of spreading effort over decorative component smoke tests.` + - `- Validation: run just ui typecheck, just ui lint, and just ui test.` + +### Batch 32 +- Subject: `test(frontend): finish replacing generic spec stubs` +- Body: + - `- Coverage: close out the remaining generic TODO stubs with real HTTP or class-level specs where cheap, and explicit seam-noted skipped specs where heavier Angular, PrimeNG, or reader-shell harnesses are still required.` + - `- Result: bring the generic TODO stub count under frontend src app to zero while preserving the no-runtime-change rule.` + - `- Validation: run just ui typecheck, just ui lint, just ui test, and finish with just ui check.` diff --git a/frontend/Justfile b/frontend/Justfile index 25325174e..67db52f38 100644 --- a/frontend/Justfile +++ b/frontend/Justfile @@ -36,7 +36,31 @@ test: # Run the frontend tests with a coverage report. coverage: - {{ yarn }} ng test --coverage + {{ yarn }} coverage + +# Summarize the latest frontend coverage report by global and feature buckets. +coverage-summary: + {{ yarn }} coverage:summary + +# Install the Chromium browser used by the frontend Playwright suite. +e2e-install: + {{ yarn }} e2e:install + +# Run the frontend Playwright suite. +e2e: + {{ yarn }} e2e + +# Run a single frontend Playwright spec file. +e2e-file spec: + {{ yarn }} e2e {{ spec }} + +# List the tests contained in a single frontend Playwright spec file. +e2e-list spec: + {{ yarn }} e2e {{ spec }} --list + +# Start the Angular dev server for Playwright against a fixed host and port. +e2e-dev host='127.0.0.1' port='4301': + {{ yarn }} ng serve --host {{ host }} --port {{ port }} --configuration development --watch=false # Run the frontend linter. lint: diff --git a/frontend/package.json b/frontend/package.json index ce6a74069..d82dbef06 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -9,7 +9,11 @@ "build:prod": "ng build --configuration production", "dev": "ng serve --open --watch --configuration development", "watch": "ng build --watch --configuration development", - "test": "ng test", + "test": "ng test --watch=false", + "coverage": "ng test --watch=false --coverage", + "coverage:summary": "node ./scripts/coverage-summary.mjs", + "e2e": "playwright test", + "e2e:install": "playwright install chromium", "typecheck": "tsc --noEmit -p tsconfig.app.json", "lint": "yarn lint:eslint && yarn lint:styles", "lint:eslint": "ng lint", @@ -18,28 +22,28 @@ }, "private": true, "dependencies": { - "@angular/animations": "^21.2.4", - "@angular/cdk": "^21.2.0", - "@angular/common": "^21.2.4", - "@angular/compiler": "^21.2.4", - "@angular/core": "^21.2.4", - "@angular/forms": "^21.2.4", - "@angular/platform-browser": "^21.2.4", - "@angular/platform-browser-dynamic": "^21.2.4", - "@angular/router": "^21.2.4", - "@angular/service-worker": "^21.2.4", + "@angular/animations": "^21.2.6", + "@angular/cdk": "^21.2.4", + "@angular/common": "^21.2.6", + "@angular/compiler": "^21.2.6", + "@angular/core": "^21.2.6", + "@angular/forms": "^21.2.6", + "@angular/platform-browser": "^21.2.6", + "@angular/platform-browser-dynamic": "^21.2.6", + "@angular/router": "^21.2.6", + "@angular/service-worker": "^21.2.6", "@iharbeck/ngx-virtual-scroller": "^20.0.0", "@jsverse/transloco": "^8.2.1", "@primeuix/themes": "^2.0.3", "@stomp/rx-stomp": "^2.3.0", "@stomp/stompjs": "^7.3.0", - "@tanstack/angular-query-experimental": "5.90.26", + "@tanstack/angular-query-experimental": "5.95.2", "@tweenjs/tween.js": "^25.0.0", "chart.js": "^4.5.1", "chartjs-chart-matrix": "^3.0.0", "chartjs-plugin-datalabels": "^2.2.0", "date-fns": "^4.1.0", - "dompurify": "^3.3.1", + "dompurify": "^3.3.3", "jwt-decode": "^4.0.0", "ng-lazyload-image": "^9.1.3", "ng2-charts": "^8.0.0", @@ -47,35 +51,44 @@ "ngx-infinite-scroll": "^21.0.0", "ngx-sse-client": "^20.0.1", "primeicons": "^7.0.0", - "primeng": "^21.1.1", + "primeng": "^21.1.3", "rxjs": "^7.8.2", "showdown": "^2.1.0", "tslib": "^2.8.1", "uuid": "^11.0.0", - "ws": "^8.19.0", + "ws": "^8.20.0", "zone.js": "^0.16.1" }, "devDependencies": { - "@analogjs/vite-plugin-angular": "^2.3.0", - "@analogjs/vitest-angular": "^2.3.0", - "@angular-devkit/architect": "0.2102.0", - "@angular-devkit/schematics": "21.2.0", - "@angular/build": "^21.2.0", - "@angular/cli": "^21.2.0", - "@angular/compiler-cli": "^21.2.4", + "@analogjs/vite-plugin-angular": "^2.3.1", + "@analogjs/vitest-angular": "^2.3.1", + "@angular-devkit/architect": "0.2102.4", + "@angular-devkit/schematics": "21.2.4", + "@angular/build": "^21.2.4", + "@angular/cli": "^21.2.4", + "@angular/compiler-cli": "^21.2.6", + "@eslint/js": "^10.0.1", + "@playwright/test": "^1.58.2", + "@testing-library/angular": "^19.2.1", + "@testing-library/dom": "^10.4.1", + "@testing-library/jest-dom": "^6.9.1", + "@testing-library/user-event": "^14.6.1", "@types/dompurify": "^3.2.0", - "@types/node": "^25.3.2", + "@types/node": "^25.5.0", "@types/showdown": "^2.0.6", - "@vitest/coverage-v8": "^4.0.17", + "@vitest/coverage-v8": "^4.1.2", "angular-eslint": "^21.3.1", - "eslint": "^9.39.3", - "jsdom": "^28.1.0", - "postcss": "^8.5.6", - "stylelint": "^16.25.0", - "stylelint-config-standard-scss": "^16.0.0", + "eslint": "^10.1.0", + "jsdom": "^29.0.1", + "msw": "^2.12.14", + "ng-mocks": "^14.15.2", + "postcss": "^8.5.8", + "stylelint": "^17.6.0", + "stylelint-config-standard-scss": "^17.0.0", "typescript": "~5.9.3", - "typescript-eslint": "^8.56.1", - "vitest": "^4.0.17" + "typescript-eslint": "^8.57.2", + "vitest": "^4.1.2", + "vitest-canvas-mock": "^1.1.4" }, "overrides": { "minimatch": "^10.2.1", diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts new file mode 100644 index 000000000..3ba19e423 --- /dev/null +++ b/frontend/playwright.config.ts @@ -0,0 +1,36 @@ +import {defineConfig, devices} from '@playwright/test'; + +const host = process.env.PLAYWRIGHT_HOST ?? '127.0.0.1'; +const port = Number(process.env.PLAYWRIGHT_PORT ?? '4301'); +const baseURL = process.env.PLAYWRIGHT_BASE_URL ?? `http://${host}:${port}`; +const startServer = process.env.PLAYWRIGHT_START_SERVER !== 'false'; +const reuseExistingServer = process.env.PLAYWRIGHT_REUSE_SERVER === 'true'; +const outputDir = process.env.PLAYWRIGHT_OUTPUT_DIR ?? `output/playwright-${port}`; +const workers = Number(process.env.PLAYWRIGHT_WORKERS ?? '1'); + +export default defineConfig({ + testDir: './playwright', + fullyParallel: false, + workers, + outputDir, + reporter: [['list']], + retries: process.env.CI ? 1 : 0, + use: { + baseURL, + trace: 'on-first-retry', + screenshot: 'only-on-failure', + video: 'retain-on-failure', + }, + webServer: startServer ? { + command: `just e2e-dev ${host} ${port}`, + url: baseURL, + reuseExistingServer, + timeout: 180000, + } : undefined, + projects: [ + { + name: 'chromium', + use: {...devices['Desktop Chrome']}, + }, + ], +}); diff --git a/frontend/playwright/README.md b/frontend/playwright/README.md new file mode 100644 index 000000000..2f14b6c87 --- /dev/null +++ b/frontend/playwright/README.md @@ -0,0 +1,37 @@ +## Playwright Harness Rules + +This directory is the browser-test harness for the frontend. Treat it as a +strictly controlled surface. + +### Execution rules + +- Never hard-code port `4200` in specs or fixtures. +- In parallel runs, every worker must set a unique `PLAYWRIGHT_PORT`. +- Use `PLAYWRIGHT_BASE_URL` only when attaching to an already-running app. +- Default local command: + +```bash +PLAYWRIGHT_PORT=4301 just --justfile frontend/Justfile --working-directory frontend e2e-file playwright/login-and-books.spec.ts +``` + +### Authoring rules + +- Start from the existing scenario fixture instead of creating ad hoc route + handlers inside a spec. +- Keep one scenario fixture per spec file. Do not build one giant catch-all fake + backend for unrelated areas. +- Mock only the endpoints required by the scenario. Unexpected API calls should + fail fast. +- Prefer role, label, placeholder, and stable text selectors. Use CSS classes + only when the UI has no better semantic hook. +- Do not add reader/browser flows until they have their own dedicated scenario + fixture and port-safe validation command. + +### Agent rules + +- Do not invent a new Playwright config per worker. +- Do not change the web server port in code for one-off runs; use env vars. +- Do not add browser specs that depend on broad route shims copied from other + scenarios. +- Use the `frontend/Justfile` entrypoints for browser install, server startup, + and spec execution. Do not invoke Yarn directly from docs or ad hoc commands. diff --git a/frontend/playwright/login-and-books.fixture.ts b/frontend/playwright/login-and-books.fixture.ts new file mode 100644 index 000000000..740e0d76f --- /dev/null +++ b/frontend/playwright/login-and-books.fixture.ts @@ -0,0 +1,245 @@ +import type {Page, Route} from '@playwright/test'; + +const tinyPng = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4//8/AwAI/AL+Nf8zAAAAAElFTkSuQmCC', + 'base64' +); + +type LoginAndBooksScenario = { + publicSettings: Record; + appSettings: Record; + user: Record; + libraries: Array>; + shelves: Array>; + magicShelves: Array>; + books: Array>; +}; + +function createJwt(expSeconds = 4_102_444_800): string { + const header = Buffer.from(JSON.stringify({alg: 'none', typ: 'JWT'})).toString('base64url'); + const payload = Buffer.from(JSON.stringify({exp: expSeconds, sub: '1'})).toString('base64url'); + return `${header}.${payload}.`; +} + +function asJson(route: Route, body: unknown, status = 200): Promise { + return route.fulfill({ + status, + contentType: 'application/json', + body: JSON.stringify(body), + }); +} + +function isThumbnailRequest(pathname: string): boolean { + return pathname.startsWith('/api/v1/media/book/') && pathname.includes('/thumbnail'); +} + +export function createLoginAndBooksScenario(): LoginAndBooksScenario { + return { + publicSettings: { + oidcEnabled: false, + remoteAuthEnabled: false, + oidcProviderDetails: null, + oidcForceOnlyMode: false, + }, + appSettings: { + remoteAuthEnabled: false, + oidcEnabled: false, + oidcProviderDetails: null, + oidcForceOnlyMode: false, + opdsServerEnabled: false, + komgaApiEnabled: false, + metadataProviderSettings: {}, + metadataMatchWeights: {}, + maxFileUploadSizeInMb: 128, + }, + user: { + id: 1, + username: 'tester', + name: 'Test Reader', + email: 'tester@example.com', + assignedLibraries: [{id: 1, name: 'Main Library'}], + permissions: { + admin: true, + canManageLibrary: true, + canUpload: true, + canAccessBookdrop: true, + canAccessLibraryStats: true, + canAccessUserStats: true, + canManageGlobalPreferences: true, + demoUser: false, + }, + userSettings: { + sidebarLibrarySorting: {field: 'name', order: 'ASC'}, + sidebarShelfSorting: {field: 'name', order: 'ASC'}, + sidebarMagicShelfSorting: {field: 'name', order: 'ASC'}, + entityViewPreferences: { + global: { + sortKey: 'title', + sortDir: 'ASC', + view: 'GRID', + coverSize: 100, + seriesCollapsed: false, + overlayBookType: false, + }, + overrides: [], + }, + tableColumnPreference: [{field: 'title', visible: true, order: 0}], + dashboardConfig: {scrollers: []}, + visibleFilters: ['author', 'series', 'bookType'], + visibleSortFields: ['title', 'addedOn', 'lastReadTime'], + filterMode: 'and', + }, + }, + libraries: [], + shelves: [], + magicShelves: [], + books: [ + { + id: 1, + libraryId: 1, + libraryName: 'Main Library', + fileName: 'the-mock-epub.epub', + primaryFile: { + id: 11, + bookId: 1, + bookType: 'EPUB', + fileName: 'the-mock-epub.epub', + filePath: '/books/the-mock-epub.epub', + }, + metadata: { + bookId: 1, + title: 'The Mock EPUB', + authors: ['A. Author'], + seriesName: 'Smoke Series', + seriesNumber: 1, + language: 'en', + }, + shelves: [{id: 101, name: 'Featured'}], + readStatus: 'UNREAD', + addedOn: '2025-01-01T00:00:00Z', + }, + { + id: 2, + libraryId: 1, + libraryName: 'Main Library', + fileName: 'the-mock-comic.cbz', + primaryFile: { + id: 21, + bookId: 2, + bookType: 'CBX', + fileName: 'the-mock-comic.cbz', + filePath: '/books/the-mock-comic.cbz', + }, + metadata: { + bookId: 2, + title: 'The Mock Comic', + authors: ['B. Artist'], + seriesName: 'Comic Smoke Series', + seriesNumber: 7, + language: 'en', + }, + shelves: [], + readStatus: 'READING', + addedOn: '2025-01-03T00:00:00Z', + }, + ], + }; +} + +export async function seedAuthenticatedSession(page: Page): Promise { + const accessToken = createJwt(); + const refreshToken = 'refresh-token'; + + await page.addInitScript( + ({accessTokenValue, refreshTokenValue}) => { + localStorage.setItem('accessToken_Internal', accessTokenValue); + localStorage.setItem('refreshToken_Internal', refreshTokenValue); + }, + {accessTokenValue: accessToken, refreshTokenValue: refreshToken} + ); +} + +export async function installLoginAndBooksRoutes( + page: Page, + scenario = createLoginAndBooksScenario() +): Promise { + await page.route('**/api/**', async route => { + const request = route.request(); + const url = new URL(request.url()); + const {pathname} = url; + const method = request.method(); + + if (pathname === '/api/public/settings' && method === 'HEAD') { + await route.fulfill({status: 200, body: ''}); + return; + } + + if (pathname === '/api/v1/setup/status' && method === 'GET') { + await asJson(route, {data: true}); + return; + } + + if (pathname === '/api/v1/public-settings' && method === 'GET') { + await asJson(route, scenario.publicSettings); + return; + } + + if (pathname === '/api/v1/settings' && method === 'GET') { + await asJson(route, scenario.appSettings); + return; + } + + if (pathname === '/api/v1/auth/login' && method === 'POST') { + await asJson(route, { + accessToken: createJwt(), + refreshToken: 'refresh-token', + isDefaultPassword: 'false', + }); + return; + } + + if (pathname === '/api/v1/auth/refresh' && method === 'POST') { + await asJson(route, { + accessToken: createJwt(), + refreshToken: 'refresh-token', + }); + return; + } + + if (pathname === '/api/v1/users/me' && method === 'GET') { + await asJson(route, scenario.user); + return; + } + + if (pathname === '/api/v1/libraries' && method === 'GET') { + await asJson(route, scenario.libraries); + return; + } + + if (pathname === '/api/v1/shelves' && method === 'GET') { + await asJson(route, scenario.shelves); + return; + } + + if (pathname === '/api/magic-shelves' && method === 'GET') { + await asJson(route, scenario.magicShelves); + return; + } + + if (pathname === '/api/v1/books' && method === 'GET') { + await asJson(route, scenario.books); + return; + } + + if (isThumbnailRequest(pathname) && method === 'GET') { + await route.fulfill({ + status: 200, + contentType: 'image/png', + body: tinyPng, + }); + return; + } + + throw new Error(`Unhandled login-and-books route: ${method} ${pathname}`); + }); +} diff --git a/frontend/playwright/login-and-books.spec.ts b/frontend/playwright/login-and-books.spec.ts new file mode 100644 index 000000000..7abfbfabd --- /dev/null +++ b/frontend/playwright/login-and-books.spec.ts @@ -0,0 +1,34 @@ +import {expect, test} from '@playwright/test'; +import { + createLoginAndBooksScenario, + installLoginAndBooksRoutes, + seedAuthenticatedSession +} from './login-and-books.fixture'; + +test.describe('login and book browser smoke', () => { + test('local login reaches the dashboard welcome state', async ({page}) => { + await installLoginAndBooksRoutes(page, createLoginAndBooksScenario()); + + await page.goto('/login'); + await expect(page.locator('#username')).toBeVisible(); + await page.locator('#username').fill('tester'); + await page.locator('#password input').fill('secret-password'); + await page.getByRole('button', {name: /sign in/i}).click(); + + await expect(page).toHaveURL(/\/dashboard$/); + await expect(page.getByRole('button', {name: /create library/i})).toBeVisible(); + }); + + test('authenticated users can open the all books browser', async ({page}) => { + const scenario = createLoginAndBooksScenario(); + await seedAuthenticatedSession(page); + await installLoginAndBooksRoutes(page, scenario); + + await page.goto('/all-books'); + + await expect(page).toHaveURL(/\/all-books$/); + await expect(page.getByText('The Mock EPUB')).toBeVisible(); + await expect(page.getByText('The Mock Comic')).toBeVisible(); + await expect(page.locator('input[placeholder]')).toBeVisible(); + }); +}); diff --git a/frontend/scripts/coverage-summary.mjs b/frontend/scripts/coverage-summary.mjs new file mode 100644 index 000000000..fdda692b3 --- /dev/null +++ b/frontend/scripts/coverage-summary.mjs @@ -0,0 +1,129 @@ +import {readFileSync} from 'node:fs'; +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; + +const scriptDir = path.dirname(fileURLToPath(import.meta.url)); +const frontendRoot = path.resolve(scriptDir, '..'); +const reportPath = path.resolve(frontendRoot, 'coverage/grimmory/coverage-final.json'); +const rootPrefix = path.resolve(frontendRoot, 'src/app') + path.sep; +const report = JSON.parse(readFileSync(reportPath, 'utf8')); + +function summarizeCounts(counts) { + if (!counts) { + return {covered: 0, total: 0, pct: 100}; + } + const values = Object.values(counts); + const covered = values.filter(value => value > 0).length; + const total = values.length; + + return {covered, total, pct: total === 0 ? 100 : Number(((covered / total) * 100).toFixed(2))}; +} + +function summarizeBranches(branches) { + if (!branches) { + return {covered: 0, total: 0, pct: 100}; + } + + const values = Object.values(branches).flatMap(branchHits => Array.isArray(branchHits) ? branchHits : []); + const covered = values.filter(value => value > 0).length; + const total = values.length; + + return {covered, total, pct: total === 0 ? 100 : Number(((covered / total) * 100).toFixed(2))}; +} + +function summarizeLines(entry) { + const lineKeys = new Set(); + const coveredLineKeys = new Set(); + + for (const [statementId, location] of Object.entries(entry.statementMap ?? {})) { + for (let line = location.start.line; line <= location.end.line; line += 1) { + lineKeys.add(line); + if ((entry.s?.[statementId] ?? 0) > 0) { + coveredLineKeys.add(line); + } + } + } + + const total = lineKeys.size; + const covered = coveredLineKeys.size; + + return {covered, total, pct: total === 0 ? 100 : Number(((covered / total) * 100).toFixed(2))}; +} + +function summarizeFile(entry) { + return { + statements: summarizeCounts(entry.s), + branches: summarizeBranches(entry.b), + functions: summarizeCounts(entry.f), + lines: summarizeLines(entry), + }; +} + +const buckets = new Map(); +const worstFiles = []; +let totals = { + statements: {covered: 0, total: 0}, + branches: {covered: 0, total: 0}, + functions: {covered: 0, total: 0}, + lines: {covered: 0, total: 0}, +}; + +for (const [absolutePath, entry] of Object.entries(report)) { + if (!absolutePath.startsWith(rootPrefix) || absolutePath.endsWith('.spec.ts')) { + continue; + } + + const relativePath = absolutePath.slice(rootPrefix.length).replaceAll(path.sep, '/'); + const [topLevel, featureName] = relativePath.split('/'); + const bucketName = topLevel === 'features' + ? `features/${featureName}` + : ['core', 'shared'].includes(topLevel) + ? topLevel + : 'app-root'; + const fileSummary = summarizeFile(entry); + + worstFiles.push({path: relativePath, branchPct: fileSummary.branches.pct}); + + for (const metric of ['statements', 'branches', 'functions', 'lines']) { + totals[metric].covered += fileSummary[metric].covered; + totals[metric].total += fileSummary[metric].total; + } + + const bucket = buckets.get(bucketName) ?? { + statements: {covered: 0, total: 0}, + branches: {covered: 0, total: 0}, + functions: {covered: 0, total: 0}, + lines: {covered: 0, total: 0}, + files: 0, + }; + + for (const metric of ['statements', 'branches', 'functions', 'lines']) { + bucket[metric].covered += fileSummary[metric].covered; + bucket[metric].total += fileSummary[metric].total; + } + bucket.files += 1; + + buckets.set(bucketName, bucket); +} + +function toPct({covered, total}) { + return total === 0 ? 100 : Number(((covered / total) * 100).toFixed(2)); +} + +console.log('Global coverage'); +for (const metric of ['statements', 'branches', 'functions', 'lines']) { + console.log(`- ${metric}: ${toPct(totals[metric])}% (${totals[metric].covered}/${totals[metric].total})`); +} + +console.log('\nCoverage by bucket'); +for (const [bucketName, bucket] of [...buckets.entries()].sort((a, b) => toPct(a[1].branches) - toPct(b[1].branches))) { + console.log( + `- ${bucketName}: statements ${toPct(bucket.statements)}%, branches ${toPct(bucket.branches)}%, functions ${toPct(bucket.functions)}% across ${bucket.files} files` + + `, lines ${toPct(bucket.lines)}%` + ); +} + +console.log('\nWorst files by branch coverage'); +for (const file of worstFiles.sort((a, b) => a.branchPct - b.branchPct).slice(0, 15)) { + console.log(`- ${file.path}: ${file.branchPct}%`); +} diff --git a/frontend/src/app/app.component.spec.ts b/frontend/src/app/app.component.spec.ts index c7cba6658..0038a648f 100644 --- a/frontend/src/app/app.component.spec.ts +++ b/frontend/src/app/app.component.spec.ts @@ -1,111 +1,247 @@ -import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; -import {ComponentFixture, TestBed} from '@angular/core/testing'; -import {signal} from '@angular/core'; -import {AppComponent} from './app.component'; -import {AuthInitializationService} from './core/security/auth-initialization-service'; -import {of} from 'rxjs'; -import {RxStompService} from './shared/websocket/rx-stomp.service'; -import {BookService} from './features/book/service/book.service'; -import {NotificationEventService} from './shared/websocket/notification-event.service'; -import {AppConfigService} from './shared/service/app-config.service'; -import {MetadataProgressService} from './shared/service/metadata-progress.service'; -import {BookdropFileService} from './features/bookdrop/service/bookdrop-file.service'; -import {TaskService} from './features/settings/task-management/task.service'; -import {LibraryService} from './features/book/service/library.service'; -import {LibraryHealthService} from './features/book/service/library-health.service'; -import {LibraryLoadingService} from './features/library-creator/library-loading.service'; -import {TranslocoTestingModule} from '@jsverse/transloco'; -import {AuthService} from './shared/service/auth.service'; +import { signal } from "@angular/core"; +import { ComponentFixture, TestBed } from "@angular/core/testing"; +import { TranslocoTestingModule } from "@jsverse/transloco"; +import { Subject } from "rxjs"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -describe('AppComponent offline detection', () => { +import { AppComponent } from "./app.component"; +import { AuthInitializationService } from "./core/security/auth-initialization-service"; +import { RxStompService } from "./shared/websocket/rx-stomp.service"; +import { BookService } from "./features/book/service/book.service"; +import { NotificationEventService } from "./shared/websocket/notification-event.service"; +import { AppConfigService } from "./shared/service/app-config.service"; +import { MetadataProgressService } from "./shared/service/metadata-progress.service"; +import { BookdropFileService } from "./features/bookdrop/service/bookdrop-file.service"; +import { TaskService } from "./features/settings/task-management/task.service"; +import { LibraryService } from "./features/book/service/library.service"; +import { LibraryHealthService } from "./features/book/service/library-health.service"; +import { LibraryLoadingService } from "./features/library-creator/library-loading.service"; +import { AuthService } from "./shared/service/auth.service"; +import { ConfirmationService } from "primeng/api"; +import { MessageService } from "primeng/api"; + +interface StompMessage { + body: string; +} + +describe("AppComponent", () => { let fixture: ComponentFixture; let component: AppComponent; + let topics: Map>; + let rxStompService: { watch: ReturnType }; + let bookService: { + handleNewlyCreatedBook: ReturnType; + handleBookUpdate: ReturnType; + handleMultipleBookCoverPatches: ReturnType; + handleRemovedBookIds: ReturnType; + handleMultipleBookUpdates: ReturnType; + }; + let notificationEventService: { + handleNewNotification: ReturnType; + }; + let metadataProgressService: { + handleIncomingProgress: ReturnType; + }; + let bookdropFileService: { handleIncomingFile: ReturnType }; + let taskService: { handleTaskProgress: ReturnType }; + let libraryHealthService: { initialize: ReturnType }; + let libraryLoadingService: { + showBookLoadingProgress: ReturnType; + hide: ReturnType; + }; + let authService: { forceLogout: ReturnType }; + let libraryService: { + largeLibraryLoading: ReturnType; + setLargeLibraryLoading: ReturnType; + }; + + function createTopicStream(topic: string): Subject { + const stream = new Subject(); + topics.set(topic, stream); + return stream; + } + + function configureComponent( + authReady = true, + largeLibraryLoading = { isLoading: false, expectedCount: 0 }, + ): void { + topics = new Map(); + rxStompService = { + watch: vi.fn((topic: string) => + (topics.get(topic) ?? createTopicStream(topic)).asObservable(), + ), + }; + bookService = { + handleNewlyCreatedBook: vi.fn(), + handleBookUpdate: vi.fn(), + handleMultipleBookCoverPatches: vi.fn(), + handleRemovedBookIds: vi.fn(), + handleMultipleBookUpdates: vi.fn(), + }; + notificationEventService = { handleNewNotification: vi.fn() }; + metadataProgressService = { handleIncomingProgress: vi.fn() }; + bookdropFileService = { handleIncomingFile: vi.fn() }; + taskService = { handleTaskProgress: vi.fn() }; + libraryHealthService = { initialize: vi.fn() }; + libraryLoadingService = { + showBookLoadingProgress: vi.fn(), + hide: vi.fn(), + }; + authService = { forceLogout: vi.fn() }; + libraryService = { + largeLibraryLoading: signal(largeLibraryLoading), + setLargeLibraryLoading: vi.fn(), + }; - beforeEach(() => { TestBed.configureTestingModule({ - imports: [TranslocoTestingModule.forRoot({langs: {}})], + imports: [TranslocoTestingModule.forRoot({ langs: {} })], providers: [ - {provide: AuthInitializationService, useValue: {initialized: signal(false)}}, - {provide: RxStompService, useValue: {watch: vi.fn(() => of())}}, - {provide: BookService, useValue: {}}, - {provide: NotificationEventService, useValue: {}}, - {provide: AppConfigService, useValue: {}}, - {provide: MetadataProgressService, useValue: {}}, - {provide: BookdropFileService, useValue: {}}, - {provide: TaskService, useValue: {}}, - {provide: LibraryService, useValue: {largeLibraryLoading: signal({isLoading: false, expectedCount: 0})}}, - {provide: LibraryHealthService, useValue: {initialize: vi.fn()}}, - {provide: LibraryLoadingService, useValue: {hide: vi.fn()}}, - {provide: AuthService, useValue: {token: signal(null)}}, - ] + { + provide: AuthInitializationService, + useValue: { initialized: signal(authReady) }, + }, + { provide: RxStompService, useValue: rxStompService }, + { provide: BookService, useValue: bookService }, + { + provide: NotificationEventService, + useValue: notificationEventService, + }, + { provide: AppConfigService, useValue: {} }, + { provide: MetadataProgressService, useValue: metadataProgressService }, + { provide: BookdropFileService, useValue: bookdropFileService }, + { provide: TaskService, useValue: taskService }, + { provide: LibraryService, useValue: libraryService }, + { provide: LibraryHealthService, useValue: libraryHealthService }, + { provide: LibraryLoadingService, useValue: libraryLoadingService }, + { provide: AuthService, useValue: authService }, + ConfirmationService, + MessageService, + ], }); fixture = TestBed.createComponent(AppComponent); component = fixture.componentInstance; fixture.detectChanges(); - }); + } - afterEach(() => { + beforeEach(() => { vi.restoreAllMocks(); }); - it('should initialize with offline set to false', () => { - expect(component.offline).toBe(false); + afterEach(() => { + fixture?.destroy(); + TestBed.resetTestingModule(); + vi.restoreAllMocks(); }); - it('should set offline to false when online event fires', () => { - component.offline = true; - window.dispatchEvent(new Event('online')); - expect(component.offline).toBe(false); + it("boots the websocket wiring when auth initialization is ready", () => { + configureComponent(true); + + expect(component.loading).toBe(false); + expect(libraryHealthService.initialize).toHaveBeenCalledOnce(); + expect(rxStompService.watch).toHaveBeenCalledWith("/user/queue/book-add"); + expect(rxStompService.watch).toHaveBeenCalledWith( + "/user/queue/session-revoked", + ); }); - it('should not show offline when server is reachable despite browser offline event', async () => { - vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, {status: 200})); + it("routes websocket book notifications through the large library loading branch", () => { + configureComponent(true, { isLoading: true, expectedCount: 2 }); - window.dispatchEvent(new Event('offline')); + topics + .get("/user/queue/book-add") + ?.next({ body: JSON.stringify({ metadata: { title: "First" } }) }); + topics + .get("/user/queue/book-add") + ?.next({ body: JSON.stringify({ metadata: { title: "Second" } }) }); - await vi.waitFor(() => { - expect(component.offline).toBe(false); + expect(bookService.handleNewlyCreatedBook).toHaveBeenCalledTimes(2); + expect( + libraryLoadingService.showBookLoadingProgress, + ).toHaveBeenNthCalledWith(1, "First", 1, 2); + expect( + libraryLoadingService.showBookLoadingProgress, + ).toHaveBeenNthCalledWith(2, "Second", 2, 2); + expect(libraryService.setLargeLibraryLoading).toHaveBeenCalledWith( + false, + 0, + ); + }); + + it("forwards websocket updates to the matching root services", () => { + configureComponent(true); + + topics + .get("/user/queue/book-update") + ?.next({ body: JSON.stringify({ id: 1 }) }); + topics + .get("/user/queue/books-cover-update") + ?.next({ body: JSON.stringify([{ id: 1 }]) }); + topics + .get("/user/queue/books-remove") + ?.next({ body: JSON.stringify([1, 2]) }); + topics + .get("/user/queue/book-metadata-update") + ?.next({ body: JSON.stringify({ id: 2 }) }); + topics + .get("/user/queue/book-metadata-batch-update") + ?.next({ body: JSON.stringify([{ id: 3 }]) }); + topics + .get("/user/queue/book-metadata-batch-progress") + ?.next({ body: JSON.stringify({ taskId: "task-1" }) }); + topics + .get("/user/queue/log") + ?.next({ body: JSON.stringify({ message: "info", severity: "INFO" }) }); + topics + .get("/user/queue/bookdrop-file") + ?.next({ body: JSON.stringify({ pendingCount: 1, totalCount: 2 }) }); + topics + .get("/user/queue/task-progress") + ?.next({ body: JSON.stringify({ taskId: "task-2" }) }); + + expect(bookService.handleBookUpdate).toHaveBeenCalledWith({ id: 1 }); + expect(bookService.handleMultipleBookCoverPatches).toHaveBeenCalledWith([ + { id: 1 }, + ]); + expect(bookService.handleRemovedBookIds).toHaveBeenCalledWith([1, 2]); + expect(bookService.handleMultipleBookUpdates).toHaveBeenCalledWith([ + { id: 3 }, + ]); + expect(metadataProgressService.handleIncomingProgress).toHaveBeenCalledWith( + { taskId: "task-1" }, + ); + expect(notificationEventService.handleNewNotification).toHaveBeenCalledWith( + { + message: "info", + severity: "INFO", + }, + ); + expect(bookdropFileService.handleIncomingFile).toHaveBeenCalledWith({ + pendingCount: 1, + totalCount: 2, + }); + expect(taskService.handleTaskProgress).toHaveBeenCalledWith({ + taskId: "task-2", }); }); - it('should show offline when server is unreachable on browser offline event', async () => { - vi.spyOn(globalThis, 'fetch').mockRejectedValue(new TypeError('Failed to fetch')); + it("forces logout when the session is revoked", () => { + configureComponent(true); - window.dispatchEvent(new Event('offline')); + topics.get("/user/queue/session-revoked")?.next({ body: "" }); - await vi.waitFor(() => { - expect(component.offline).toBe(true); - }); + expect(authService.forceLogout).toHaveBeenCalledWith("session_revoked"); }); - it('should ping server with HEAD method and no-store cache', async () => { - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, {status: 200})); + it("unsubscribes and hides the loading overlay when destroyed", () => { + configureComponent(true); - window.dispatchEvent(new Event('offline')); + component.ngOnDestroy(); - await vi.waitFor(() => { - expect(fetchSpy).toHaveBeenCalledWith('/api/public/settings', {method: 'HEAD', cache: 'no-store'}); - }); - }); - - it('should treat server errors as reachable', async () => { - vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, {status: 500})); - - window.dispatchEvent(new Event('offline')); - - await vi.waitFor(() => { - expect(component.offline).toBe(false); - }); - }); - - it('should treat network timeout as unreachable', async () => { - vi.spyOn(globalThis, 'fetch').mockRejectedValue(new TypeError('network timeout')); - - window.dispatchEvent(new Event('offline')); - - await vi.waitFor(() => { - expect(component.offline).toBe(true); - }); + expect(libraryLoadingService.hide).toHaveBeenCalledOnce(); + topics + .get("/user/queue/book-update") + ?.next({ body: JSON.stringify({ id: 99 }) }); + expect(bookService.handleBookUpdate).not.toHaveBeenCalled(); }); }); diff --git a/frontend/src/app/app.routes.spec.ts b/frontend/src/app/app.routes.spec.ts new file mode 100644 index 000000000..fa18f8a7c --- /dev/null +++ b/frontend/src/app/app.routes.spec.ts @@ -0,0 +1,63 @@ +import {describe, expect, it} from 'vitest'; + +import {routes} from './app.routes'; +import {AuthGuard} from './core/security/auth.guard'; +import {BookdropGuard} from './core/security/guards/bookdrop.guard'; +import {EditMetadataGuard} from './core/security/guards/edit-metdata.guard'; +import {LibraryStatsGuard} from './core/security/guards/library-stats.guard'; +import {UserStatsGuard} from './core/security/guards/user-stats.guard'; +import {LoginGuard} from './shared/components/setup/login.guard'; +import {SetupGuard} from './shared/components/setup/setup.guard'; +import {SetupRedirectGuard} from './shared/components/setup/setup-redirect.guard'; + +describe('app routes', () => { + it('defines the setup and auth entry routes', () => { + const rootRedirect = routes.find(route => route.path === '' && route.pathMatch === 'full'); + const setupRoute = routes.find(route => route.path === 'setup'); + const loginRoute = routes.find(route => route.path === 'login'); + const wildcardRoute = routes.find(route => route.path === '**'); + + expect(rootRedirect?.canActivate).toEqual([SetupRedirectGuard]); + expect(setupRoute?.canActivate).toEqual([SetupGuard]); + expect(loginRoute?.canActivate).toEqual([LoginGuard]); + expect(wildcardRoute?.redirectTo).toBe('login'); + }); + + it('defines the authenticated shell routes behind the auth guard', () => { + const shellRoute = routes.find(route => route.path === '' && Array.isArray(route.children)); + const children = shellRoute?.children ?? []; + + expect(children).toHaveLength(17); + expect(children.find(route => route.path === 'dashboard')?.canActivate).toEqual([AuthGuard]); + expect(children.find(route => route.path === 'all-books')?.canActivate).toEqual([AuthGuard]); + expect(children.find(route => route.path === 'magic-shelf/:magicShelfId/books')?.canActivate).toEqual([AuthGuard]); + expect(children.find(route => route.path === 'notebook')?.canActivate).toEqual([AuthGuard]); + }); + + it('defines guarded lazy routes for metadata, stats, and bookdrop', () => { + const shellRoute = routes.find(route => route.path === '' && Array.isArray(route.children)); + const children = shellRoute?.children ?? []; + + expect(children.find(route => route.path === 'bookdrop')?.canActivate).toEqual([BookdropGuard]); + expect(children.find(route => route.path === 'metadata-manager')?.canActivate).toEqual([EditMetadataGuard]); + expect(children.find(route => route.path === 'library-stats')?.canActivate).toEqual([LibraryStatsGuard]); + expect(children.find(route => route.path === 'reading-stats')?.canActivate).toEqual([UserStatsGuard]); + + expect(typeof children.find(route => route.path === 'settings')?.loadComponent).toBe('function'); + expect(typeof children.find(route => route.path === 'series')?.loadComponent).toBe('function'); + expect(typeof children.find(route => route.path === 'book/:bookId')?.loadComponent).toBe('function'); + }); + + it('defines the dedicated reader routes outside the shell', () => { + expect(routes.find(route => route.path === 'pdf-reader/book/:bookId')?.canActivate).toEqual([AuthGuard]); + expect(routes.find(route => route.path === 'ebook-reader/book/:bookId')?.canActivate).toEqual([AuthGuard]); + expect(routes.find(route => route.path === 'cbx-reader/book/:bookId')?.canActivate).toEqual([AuthGuard]); + expect(routes.find(route => route.path === 'audiobook-player/book/:bookId')?.canActivate).toEqual([AuthGuard]); + }); + + it('keeps the callback and password routes outside the authenticated shell', () => { + expect(routes.find(route => route.path === 'oauth2-callback')?.component).toBeDefined(); + expect(routes.find(route => route.path === 'change-password')?.component).toBeDefined(); + expect(routes.find(route => route.path === 'change-password')?.canActivate).toBeUndefined(); + }); +}); diff --git a/frontend/src/app/core/config/api-config.spec.ts b/frontend/src/app/core/config/api-config.spec.ts new file mode 100644 index 000000000..e02c23517 --- /dev/null +++ b/frontend/src/app/core/config/api-config.spec.ts @@ -0,0 +1,14 @@ +import {describe, expect, it} from 'vitest'; + +import {environment} from '../../../environments/environment'; +import {API_CONFIG} from './api-config'; + +describe('API_CONFIG', () => { + it('re-exports the environment API config object', () => { + expect(API_CONFIG).toBe(environment.API_CONFIG); + }); + + it('exposes a defined config value', () => { + expect(API_CONFIG).toBeDefined(); + }); +}); diff --git a/frontend/src/app/core/config/language-initializer.spec.ts b/frontend/src/app/core/config/language-initializer.spec.ts new file mode 100644 index 000000000..f32873f7a --- /dev/null +++ b/frontend/src/app/core/config/language-initializer.spec.ts @@ -0,0 +1,90 @@ +import {TestBed} from '@angular/core/testing'; +import {of} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {TranslocoService} from '@jsverse/transloco'; + +import {initializeLanguage, LANG_STORAGE_KEY, LEGACY_LANG_STORAGE_KEY} from './language-initializer'; + +describe('initializeLanguage', () => { + const translocoService = { + setActiveLang: vi.fn(), + load: vi.fn(), + }; + + beforeEach(() => { + vi.restoreAllMocks(); + localStorage.clear(); + translocoService.setActiveLang.mockReset(); + translocoService.load.mockReset(); + translocoService.load.mockReturnValue(of({})); + + TestBed.configureTestingModule({ + providers: [ + {provide: TranslocoService, useValue: translocoService}, + ] + }); + }); + + afterEach(() => { + localStorage.clear(); + TestBed.resetTestingModule(); + }); + + it('uses the current persisted language when it is available', async () => { + localStorage.setItem(LANG_STORAGE_KEY, 'de'); + + const initializer = TestBed.runInInjectionContext(() => initializeLanguage()); + + await TestBed.runInInjectionContext(() => initializer()); + + expect(translocoService.setActiveLang).toHaveBeenCalledWith('de'); + expect(translocoService.load).toHaveBeenCalledWith('de'); + expect(localStorage.getItem(LANG_STORAGE_KEY)).toBe('de'); + }); + + it('migrates the legacy persisted language key', async () => { + localStorage.setItem(LEGACY_LANG_STORAGE_KEY, 'fr'); + + const initializer = TestBed.runInInjectionContext(() => initializeLanguage()); + + await TestBed.runInInjectionContext(() => initializer()); + + expect(translocoService.setActiveLang).toHaveBeenCalledWith('fr'); + expect(localStorage.getItem(LANG_STORAGE_KEY)).toBe('fr'); + }); + + it('prefers the exact browser locale when it is available', async () => { + vi.spyOn(window.navigator, 'language', 'get').mockReturnValue('pt'); + + const initializer = TestBed.runInInjectionContext(() => initializeLanguage()); + + await TestBed.runInInjectionContext(() => initializer()); + + expect(translocoService.setActiveLang).toHaveBeenCalledWith('pt'); + expect(localStorage.getItem(LANG_STORAGE_KEY)).toBe('pt'); + }); + + it('falls back to the browser base language when the full locale is unavailable', async () => { + vi.spyOn(window.navigator, 'language', 'get').mockReturnValue('pt-BR'); + + const initializer = TestBed.runInInjectionContext(() => initializeLanguage()); + + await TestBed.runInInjectionContext(() => initializer()); + + expect(translocoService.setActiveLang).toHaveBeenCalledWith('pt'); + expect(localStorage.getItem(LANG_STORAGE_KEY)).toBe('pt'); + }); + + it('falls back to english when there is no supported saved or browser language', async () => { + localStorage.setItem(LANG_STORAGE_KEY, 'zz'); + vi.spyOn(window.navigator, 'language', 'get').mockReturnValue('zz-ZZ'); + + const initializer = TestBed.runInInjectionContext(() => initializeLanguage()); + + await TestBed.runInInjectionContext(() => initializer()); + + expect(translocoService.setActiveLang).toHaveBeenCalledWith('en'); + expect(translocoService.load).toHaveBeenCalledWith('en'); + expect(localStorage.getItem(LANG_STORAGE_KEY)).toBe('en'); + }); +}); diff --git a/frontend/src/app/core/config/transloco-loader.spec.ts b/frontend/src/app/core/config/transloco-loader.spec.ts new file mode 100644 index 000000000..e03798f0b --- /dev/null +++ b/frontend/src/app/core/config/transloco-loader.spec.ts @@ -0,0 +1,39 @@ +import {firstValueFrom} from 'rxjs'; +import {describe, expect, it} from 'vitest'; + +import en from '../../../i18n/en'; +import de from '../../../i18n/de'; +import {AVAILABLE_LANGS, EN_TRANSLATIONS, LANG_LABELS, TranslocoInlineLoader} from './transloco-loader'; + +describe('TranslocoInlineLoader', () => { + it('returns the english translations for the default language', async () => { + const loader = new TranslocoInlineLoader(); + const translation = await firstValueFrom(loader.getTranslation('en')); + + expect(translation).toBe(EN_TRANSLATIONS); + expect(translation['auth']['login']['sessionRevoked']).toBe(en['auth']['login']['sessionRevoked']); + }); + + it('falls back to english for unsupported languages', async () => { + const loader = new TranslocoInlineLoader(); + const translation = await firstValueFrom(loader.getTranslation('xx')); + + expect(translation).toBe(EN_TRANSLATIONS); + }); + + it('loads and merges a lazy language bundle over english', async () => { + const loader = new TranslocoInlineLoader(); + const translation = await firstValueFrom(loader.getTranslation('de')); + + expect(translation['auth']['login']['oidcInitError']).toBe(de['auth']['login']['oidcInitError']); + expect(translation['auth']['login']['sessionRevoked']).toBe(de['auth']['login']['sessionRevoked']); + expect(translation['auth']['login']['oidcErrors']['providerUnreachable']).toBe(de['auth']['login']['oidcErrors']['providerUnreachable']); + }); + + it('exposes the available language metadata', () => { + expect(AVAILABLE_LANGS).toContain('en'); + expect(AVAILABLE_LANGS).toContain('de'); + expect(LANG_LABELS['en']).toBe('English'); + expect(LANG_LABELS['de']).toBe('Deutsch'); + }); +}); diff --git a/frontend/src/app/core/custom-reuse-strategy.spec.ts b/frontend/src/app/core/custom-reuse-strategy.spec.ts new file mode 100644 index 000000000..4c32f6aa6 --- /dev/null +++ b/frontend/src/app/core/custom-reuse-strategy.spec.ts @@ -0,0 +1,125 @@ +import {Injector, runInInjectionContext} from '@angular/core'; +import {ActivatedRouteSnapshot, DetachedRouteHandle} from '@angular/router'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {BookBrowserScrollService} from '../features/book/components/book-browser/book-browser-scroll.service'; +import {BookSelectionService} from '../features/book/components/book-browser/book-selection.service'; +import {CustomReuseStrategy} from './custom-reuse-strategy'; + +function createRoute(path: string, params: Record = {}): ActivatedRouteSnapshot { + return { + routeConfig: {path}, + params + } as ActivatedRouteSnapshot; +} + +describe('CustomReuseStrategy', () => { + const handle = {componentRef: {} as never} as DetachedRouteHandle; + + let strategy: CustomReuseStrategy; + let scrollService: BookBrowserScrollService; + let selectionService: BookSelectionService; + + beforeEach(() => { + vi.restoreAllMocks(); + + scrollService = new BookBrowserScrollService(); + selectionService = new BookSelectionService(); + const injector = Injector.create({ + providers: [ + {provide: BookBrowserScrollService, useValue: scrollService}, + {provide: BookSelectionService, useValue: selectionService}, + ] + }); + strategy = runInInjectionContext(injector, () => new CustomReuseStrategy()); + }); + + afterEach(() => { + vi.useRealTimers(); + document.body.innerHTML = ''; + }); + + it('stores and reattaches book browser routes with their saved scroll position', async () => { + vi.useFakeTimers(); + const route = createRoute('all-books', {libraryId: '42'}); + const scrollElement = document.createElement('div'); + scrollElement.className = 'virtual-scroller'; + const querySelectorSpy = vi.spyOn(document, 'querySelector').mockReturnValue(scrollElement); + const deselectSpy = vi.spyOn(selectionService, 'deselectAll'); + + scrollService.savePosition('all-books:42', 321); + strategy.store(route, handle); + + expect(strategy.shouldDetach(route)).toBe(true); + expect(strategy.shouldAttach(route)).toBe(true); + expect(deselectSpy).toHaveBeenCalledTimes(1); + + const restored = strategy.retrieve(route); + await vi.runAllTimersAsync(); + + expect(restored).toBe(handle); + expect(querySelectorSpy).toHaveBeenCalledWith('.virtual-scroller'); + expect(scrollElement.scrollTop).toBe(321); + }); + + it('ignores non-book routes when storing or attaching', () => { + const route = createRoute('login'); + const deselectSpy = vi.spyOn(selectionService, 'deselectAll'); + + strategy.store(route, handle); + + expect(strategy.shouldDetach(route)).toBe(false); + expect(strategy.shouldAttach(route)).toBe(false); + expect(strategy.retrieve(route)).toBeNull(); + expect(deselectSpy).not.toHaveBeenCalled(); + }); + + it('ignores null handles for book browser routes', () => { + const route = createRoute('series', {seriesId: '77'}); + const deselectSpy = vi.spyOn(selectionService, 'deselectAll'); + + strategy.store(route, null); + + expect(strategy.shouldDetach(route)).toBe(true); + expect(strategy.shouldAttach(route)).toBe(false); + expect(strategy.retrieve(route)).toBeNull(); + expect(deselectSpy).not.toHaveBeenCalled(); + }); + + it('returns a stored handle without touching the DOM when no scroll position was saved', () => { + const route = createRoute('authors'); + const querySelectorSpy = vi.spyOn(document, 'querySelector'); + const deselectSpy = vi.spyOn(selectionService, 'deselectAll'); + + strategy.store(route, handle); + + expect(deselectSpy).toHaveBeenCalledOnce(); + expect(strategy.shouldAttach(route)).toBe(true); + expect(strategy.retrieve(route)).toBe(handle); + expect(querySelectorSpy).not.toHaveBeenCalled(); + }); + + it('reuses routes only when the route config and params both match', () => { + const routeConfig = {path: 'series'}; + const current = { + routeConfig, + params: {seriesId: '12'} + } as unknown as ActivatedRouteSnapshot; + const same = { + routeConfig, + params: {seriesId: '12'} + } as unknown as ActivatedRouteSnapshot; + const differentParams = { + routeConfig, + params: {seriesId: '99'} + } as unknown as ActivatedRouteSnapshot; + const differentConfig = { + routeConfig: {path: 'authors'}, + params: {seriesId: '12'} + } as unknown as ActivatedRouteSnapshot; + + expect(strategy.shouldReuseRoute(same, current)).toBe(true); + expect(strategy.shouldReuseRoute(differentParams, current)).toBe(false); + expect(strategy.shouldReuseRoute(differentConfig, current)).toBe(false); + }); +}); diff --git a/frontend/src/app/core/security/auth-initialization-service.spec.ts b/frontend/src/app/core/security/auth-initialization-service.spec.ts new file mode 100644 index 000000000..2255db83f --- /dev/null +++ b/frontend/src/app/core/security/auth-initialization-service.spec.ts @@ -0,0 +1,20 @@ +import {TestBed} from '@angular/core/testing'; +import {describe, expect, it} from 'vitest'; + +import {AuthInitializationService} from './auth-initialization-service'; + +describe('AuthInitializationService', () => { + it('starts in an uninitialized state and can be marked as initialized', () => { + TestBed.configureTestingModule({ + providers: [AuthInitializationService], + }); + + const service = TestBed.inject(AuthInitializationService); + + expect(service.initialized()).toBe(false); + + service.markAsInitialized(); + + expect(service.initialized()).toBe(true); + }); +}); diff --git a/frontend/src/app/core/security/auth-initializer.spec.ts b/frontend/src/app/core/security/auth-initializer.spec.ts index abd4a5586..7b3a99094 100644 --- a/frontend/src/app/core/security/auth-initializer.spec.ts +++ b/frontend/src/app/core/security/auth-initializer.spec.ts @@ -1,71 +1,149 @@ +import {Injector, runInInjectionContext} from '@angular/core'; import {beforeEach, describe, expect, it, vi} from 'vitest'; -import {signal} from '@angular/core'; -import {TestBed} from '@angular/core/testing'; -import {initializeAuthFactory} from './auth-initializer'; +import {of, throwError} from 'rxjs'; +import {QueryClient} from '@tanstack/angular-query-experimental'; + import {AuthInitializationService} from './auth-initialization-service'; import {AuthService} from '../../shared/service/auth.service'; import {AppSettingsService, PublicAppSettings} from '../../shared/service/app-settings.service'; -import {QueryClient, queryOptions} from '@tanstack/angular-query-experimental'; +import {initializeAuthFactory} from './auth-initializer'; describe('initializeAuthFactory', () => { - let authInitService: AuthInitializationService; - let mockQueryClient: { fetchQuery: ReturnType }; + const authInitService = { + markAsInitialized: vi.fn(), + }; - const defaultPublicSettings: PublicAppSettings = { - oidcEnabled: false, + const authService = { + getInternalAccessToken: vi.fn<() => string | null>(), + remoteLogin: vi.fn(), + initializeWebSocketConnection: vi.fn(), + }; + + const queryClient = { + fetchQuery: vi.fn(), + }; + + const appSettingsService = { + getPublicSettingsQueryOptions: vi.fn(() => ({queryKey: ['public-settings']})), + }; + + const settingsBase: PublicAppSettings = { + oidcEnabled: true, remoteAuthEnabled: false, oidcProviderDetails: null!, oidcForceOnlyMode: false, }; beforeEach(() => { - mockQueryClient = { - fetchQuery: vi.fn().mockResolvedValue(defaultPublicSettings), - }; + vi.restoreAllMocks(); + authInitService.markAsInitialized.mockReset(); + authService.getInternalAccessToken.mockReset(); + authService.remoteLogin.mockReset(); + authService.initializeWebSocketConnection.mockReset(); + queryClient.fetchQuery.mockReset(); + appSettingsService.getPublicSettingsQueryOptions.mockClear(); + }); - TestBed.configureTestingModule({ + it('marks auth initialized when public settings are unavailable', async () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + queryClient.fetchQuery.mockResolvedValue(null); + + const injector = Injector.create({ providers: [ - {provide: AuthService, useValue: {token: signal(null), getInternalAccessToken: vi.fn()}}, - { - provide: AppSettingsService, - useValue: { - publicAppSettings: signal(null), - getPublicSettingsQueryOptions: () => queryOptions({queryKey: ['public-settings'], queryFn: async () => defaultPublicSettings}), - }, - }, - {provide: QueryClient, useValue: mockQueryClient}, - AuthInitializationService, + {provide: AuthInitializationService, useValue: authInitService}, + {provide: AuthService, useValue: authService}, + {provide: AppSettingsService, useValue: appSettingsService}, + {provide: QueryClient, useValue: queryClient}, ] }); - authInitService = TestBed.inject(AuthInitializationService); + await runInInjectionContext(injector, () => initializeAuthFactory()()); + + expect(appSettingsService.getPublicSettingsQueryOptions).toHaveBeenCalledOnce(); + expect(authInitService.markAsInitialized).toHaveBeenCalledOnce(); + expect(warnSpy).toHaveBeenCalledOnce(); }); - it('should proceed with auth initialization when navigator.onLine is false', async () => { - const markSpy = vi.spyOn(authInitService, 'markAsInitialized'); + it('initializes websocket auth when local auth is active and a token exists', async () => { + queryClient.fetchQuery.mockResolvedValue({...settingsBase, remoteAuthEnabled: false}); + authService.getInternalAccessToken.mockReturnValue('access-token'); - Object.defineProperty(navigator, 'onLine', {value: false, configurable: true}); + const injector = Injector.create({ + providers: [ + {provide: AuthInitializationService, useValue: authInitService}, + {provide: AuthService, useValue: authService}, + {provide: AppSettingsService, useValue: appSettingsService}, + {provide: QueryClient, useValue: queryClient}, + ] + }); - const factory = TestBed.runInInjectionContext(() => initializeAuthFactory()); - const initPromise = TestBed.runInInjectionContext(() => factory()); + await runInInjectionContext(injector, () => initializeAuthFactory()()); - await initPromise; - - expect(markSpy).toHaveBeenCalled(); - - Object.defineProperty(navigator, 'onLine', {value: true, configurable: true}); + expect(authService.initializeWebSocketConnection).toHaveBeenCalledOnce(); + expect(authInitService.markAsInitialized).toHaveBeenCalledOnce(); }); - it('should initialize normally when navigator.onLine is true', async () => { - const markSpy = vi.spyOn(authInitService, 'markAsInitialized'); + it('skips websocket initialization when local auth is active and no token exists', async () => { + queryClient.fetchQuery.mockResolvedValue({...settingsBase, remoteAuthEnabled: false}); + authService.getInternalAccessToken.mockReturnValue(null); - Object.defineProperty(navigator, 'onLine', {value: true, configurable: true}); + const injector = Injector.create({ + providers: [ + {provide: AuthInitializationService, useValue: authInitService}, + {provide: AuthService, useValue: authService}, + {provide: AppSettingsService, useValue: appSettingsService}, + {provide: QueryClient, useValue: queryClient}, + ] + }); - const factory = TestBed.runInInjectionContext(() => initializeAuthFactory()); - const initPromise = TestBed.runInInjectionContext(() => factory()); + await runInInjectionContext(injector, () => initializeAuthFactory()()); - await initPromise; + expect(authService.initializeWebSocketConnection).not.toHaveBeenCalled(); + expect(authInitService.markAsInitialized).toHaveBeenCalledOnce(); + }); - expect(markSpy).toHaveBeenCalled(); + it('performs remote login when remote auth is enabled', async () => { + queryClient.fetchQuery.mockResolvedValue({...settingsBase, remoteAuthEnabled: true}); + authService.remoteLogin.mockReturnValue(of({ + accessToken: 'access', + refreshToken: 'refresh', + isDefaultPassword: 'false', + })); + + const injector = Injector.create({ + providers: [ + {provide: AuthInitializationService, useValue: authInitService}, + {provide: AuthService, useValue: authService}, + {provide: AppSettingsService, useValue: appSettingsService}, + {provide: QueryClient, useValue: queryClient}, + ] + }); + + await runInInjectionContext(injector, () => initializeAuthFactory()()); + + expect(authService.remoteLogin).toHaveBeenCalledOnce(); + expect(authInitService.markAsInitialized).toHaveBeenCalledOnce(); + }); + + it('marks auth initialized even when remote login fails', async () => { + const error = new Error('remote login failed'); + queryClient.fetchQuery.mockResolvedValue({...settingsBase, remoteAuthEnabled: true}); + authService.remoteLogin.mockReturnValue(throwError(() => error)); + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined); + + const injector = Injector.create({ + providers: [ + {provide: AuthInitializationService, useValue: authInitService}, + {provide: AuthService, useValue: authService}, + {provide: AppSettingsService, useValue: appSettingsService}, + {provide: QueryClient, useValue: queryClient}, + ] + }); + + await runInInjectionContext(injector, () => initializeAuthFactory()()); + + expect(authService.remoteLogin).toHaveBeenCalledOnce(); + expect(authInitService.markAsInitialized).toHaveBeenCalledOnce(); + expect(errorSpy).toHaveBeenCalledWith('[Remote Login] failed:', error); }); }); diff --git a/frontend/src/app/core/security/auth-interceptor.service.spec.ts b/frontend/src/app/core/security/auth-interceptor.service.spec.ts new file mode 100644 index 000000000..0509c4a23 --- /dev/null +++ b/frontend/src/app/core/security/auth-interceptor.service.spec.ts @@ -0,0 +1,179 @@ +import {HttpErrorResponse, HttpHandlerFn, HttpRequest, HttpResponse} from '@angular/common/http'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {Observable, Subject, firstValueFrom, of, throwError} from 'rxjs'; + +import {API_CONFIG} from '../config/api-config'; +import {AuthService} from '../../shared/service/auth.service'; +import {AuthInterceptorService} from './auth-interceptor.service'; + +describe('AuthInterceptorService', () => { + const authService = { + getInternalAccessToken: vi.fn<() => string | null>(), + internalRefreshToken: vi.fn<() => Observable<{accessToken: string; refreshToken: string}>>(), + saveInternalTokens: vi.fn<(accessToken: string, refreshToken: string) => void>(), + logout: vi.fn<() => void>(), + }; + + const apiUrl = `${API_CONFIG.BASE_URL}/api/v1`; + let interceptor: (request: HttpRequest, next: HttpHandlerFn) => Observable; + + beforeEach(() => { + vi.restoreAllMocks(); + authService.getInternalAccessToken.mockReset(); + authService.internalRefreshToken.mockReset(); + authService.saveInternalTokens.mockReset(); + authService.logout.mockReset(); + + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + {provide: AuthService, useValue: authService}, + ] + }); + + interceptor = (request, next) => TestBed.runInInjectionContext( + () => AuthInterceptorService(request, next) + ); + }); + + afterEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + it('adds the bearer token to API requests', async () => { + authService.getInternalAccessToken.mockReturnValue('token-123'); + const next = vi.fn((request: HttpRequest) => of(new HttpResponse({status: 200, body: request.headers.get('Authorization')}))); + + const response = await firstValueFrom(interceptor( + new HttpRequest('GET', `${apiUrl}/books`), + next + )); + + expect(next).toHaveBeenCalledOnce(); + expect((response as HttpResponse).body).toBe('Bearer token-123'); + }); + + it('does not add auth headers to non-api requests', async () => { + authService.getInternalAccessToken.mockReturnValue('token-123'); + const next = vi.fn((request: HttpRequest) => of(new HttpResponse({status: 200, body: request.headers.has('Authorization')}))); + + const response = await firstValueFrom(interceptor( + new HttpRequest('GET', `${API_CONFIG.BASE_URL}/assets/logo.svg`), + next + )); + + expect((response as HttpResponse).body).toBe(false); + }); + + it('forwards api requests unchanged when no token is available', async () => { + authService.getInternalAccessToken.mockReturnValue(null); + const next = vi.fn((request: HttpRequest) => of(new HttpResponse({status: 200, body: request.headers.has('Authorization')}))); + + const response = await firstValueFrom(interceptor( + new HttpRequest('GET', `${apiUrl}/books`), + next + )); + + expect(next).toHaveBeenCalledOnce(); + expect((response as HttpResponse).body).toBe(false); + }); + + it('retries a 401 request after a successful refresh', async () => { + authService.getInternalAccessToken.mockReturnValue('expired-token'); + authService.internalRefreshToken.mockReturnValue(of({accessToken: 'fresh-token', refreshToken: 'refresh-token'})); + + const next = vi.fn((request: HttpRequest) => { + const authHeader = request.headers.get('Authorization'); + if (authHeader === 'Bearer fresh-token') { + return of(new HttpResponse({status: 200, body: authHeader})); + } + return throwError(() => new HttpErrorResponse({status: 401})); + }); + + const response = await firstValueFrom(interceptor( + new HttpRequest('GET', `${apiUrl}/books`), + next + )); + + expect(authService.internalRefreshToken).toHaveBeenCalledOnce(); + expect(authService.saveInternalTokens).toHaveBeenCalledWith('fresh-token', 'refresh-token'); + expect((response as HttpResponse).body).toBe('Bearer fresh-token'); + }); + + it('retries a 401 request without persisting tokens when the refresh response is incomplete', async () => { + authService.getInternalAccessToken.mockReturnValue('expired-token'); + authService.internalRefreshToken.mockReturnValue(of({accessToken: 'fresh-token', refreshToken: ''})); + + const next = vi.fn((request: HttpRequest) => { + if (request.headers.get('Authorization') === 'Bearer fresh-token') { + return of(new HttpResponse({status: 200, body: request.headers.get('Authorization')})); + } + return throwError(() => new HttpErrorResponse({status: 401})); + }); + + const response = await firstValueFrom(interceptor( + new HttpRequest('GET', `${apiUrl}/books`), + next + )); + + expect(authService.saveInternalTokens).not.toHaveBeenCalled(); + expect((response as HttpResponse).body).toBe('Bearer fresh-token'); + }); + + it('logs out when the refresh request fails', async () => { + authService.getInternalAccessToken.mockReturnValue('expired-token'); + authService.internalRefreshToken.mockReturnValue( + throwError(() => new HttpErrorResponse({status: 500})) + ); + + const next = vi.fn(() => throwError(() => new HttpErrorResponse({status: 401}))); + + await expect(firstValueFrom(interceptor( + new HttpRequest('GET', `${apiUrl}/books`), + next + ))).rejects.toBeInstanceOf(HttpErrorResponse); + + expect(authService.logout).toHaveBeenCalledOnce(); + }); + + it('rethrows non-401 errors without logging out', async () => { + authService.getInternalAccessToken.mockReturnValue('token-123'); + const next = vi.fn(() => throwError(() => new HttpErrorResponse({status: 500}))); + + await expect(firstValueFrom(interceptor( + new HttpRequest('GET', `${apiUrl}/books`), + next + ))).rejects.toBeInstanceOf(HttpErrorResponse); + + expect(authService.internalRefreshToken).not.toHaveBeenCalled(); + expect(authService.logout).not.toHaveBeenCalled(); + }); + + it('queues concurrent 401s behind a single refresh operation', async () => { + authService.getInternalAccessToken.mockReturnValue('expired-token'); + const refreshSubject = new Subject<{accessToken: string; refreshToken: string}>(); + authService.internalRefreshToken.mockReturnValue(refreshSubject.asObservable()); + + const next = vi.fn((request: HttpRequest) => { + const authHeader = request.headers.get('Authorization'); + if (authHeader === 'Bearer refreshed-token') { + return of(new HttpResponse({status: 200, body: authHeader})); + } + return throwError(() => new HttpErrorResponse({status: 401})); + }); + + const firstRequest = firstValueFrom(interceptor(new HttpRequest('GET', `${apiUrl}/books`), next)); + const secondRequest = firstValueFrom(interceptor(new HttpRequest('GET', `${apiUrl}/libraries`), next)); + + refreshSubject.next({accessToken: 'refreshed-token', refreshToken: 'refresh-token'}); + refreshSubject.complete(); + + const [firstResponse, secondResponse] = await Promise.all([firstRequest, secondRequest]); + + expect(authService.internalRefreshToken).toHaveBeenCalledOnce(); + expect((firstResponse as HttpResponse).body).toBe('Bearer refreshed-token'); + expect((secondResponse as HttpResponse).body).toBe('Bearer refreshed-token'); + }); +}); diff --git a/frontend/src/app/core/security/auth.guard.spec.ts b/frontend/src/app/core/security/auth.guard.spec.ts new file mode 100644 index 000000000..7628114a2 --- /dev/null +++ b/frontend/src/app/core/security/auth.guard.spec.ts @@ -0,0 +1,97 @@ +import {TestBed} from '@angular/core/testing'; +import {ActivatedRouteSnapshot, Router, RouterStateSnapshot, UrlTree} from '@angular/router'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {AuthService} from '../../shared/service/auth.service'; +import {AuthGuard} from './auth.guard'; + +function buildToken(payload: Record): string { + return `header.${btoa(JSON.stringify(payload))}.signature`; +} + +describe('AuthGuard', () => { + const route = {} as ActivatedRouteSnapshot; + const state = {} as RouterStateSnapshot; + const router = { + createUrlTree: vi.fn((commands: string[]) => ({commands}) as unknown as UrlTree), + navigate: vi.fn(() => Promise.resolve(true)), + }; + + const authService = { + getInternalAccessToken: vi.fn<() => string | null>(), + }; + + beforeEach(() => { + vi.restoreAllMocks(); + localStorage.clear(); + router.createUrlTree.mockClear(); + router.navigate.mockClear(); + authService.getInternalAccessToken.mockReset(); + + TestBed.configureTestingModule({ + providers: [ + {provide: Router, useValue: router}, + {provide: AuthService, useValue: authService}, + ] + }); + }); + + afterEach(() => { + localStorage.clear(); + }); + + it('allows navigation for a valid non-default-password token', () => { + authService.getInternalAccessToken.mockReturnValue( + buildToken({exp: Math.floor(Date.now() / 1000) + 3600}) + ); + + const result = TestBed.runInInjectionContext(() => AuthGuard(route, state)); + + expect(result).toBe(true); + expect(router.navigate).not.toHaveBeenCalled(); + }); + + it('redirects to login when there is no token', () => { + authService.getInternalAccessToken.mockReturnValue(null); + + const result = TestBed.runInInjectionContext(() => AuthGuard(route, state)); + + expect(result).toBe(false); + expect(router.navigate).toHaveBeenCalledWith(['/login']); + }); + + it('returns a login UrlTree for expired tokens', () => { + localStorage.setItem('accessToken_Internal', 'stale-token'); + authService.getInternalAccessToken.mockReturnValue( + buildToken({exp: Math.floor(Date.now() / 1000) - 10}) + ); + + const result = TestBed.runInInjectionContext(() => AuthGuard(route, state)); + + expect(router.createUrlTree).toHaveBeenCalledWith(['/login']); + expect(result).toEqual({commands: ['/login']}); + expect(localStorage.getItem('accessToken_Internal')).toBeNull(); + }); + + it('redirects to the change-password flow for default-password tokens', () => { + authService.getInternalAccessToken.mockReturnValue( + buildToken({exp: Math.floor(Date.now() / 1000) + 3600, isDefaultPassword: true}) + ); + + const result = TestBed.runInInjectionContext(() => AuthGuard(route, state)); + + expect(result).toBe(false); + expect(router.navigate).toHaveBeenCalledWith(['/change-password']); + }); + + it('clears the token and redirects to login for malformed tokens', () => { + localStorage.setItem('accessToken_Internal', 'bad-token'); + authService.getInternalAccessToken.mockReturnValue('bad-token'); + + const result = TestBed.runInInjectionContext(() => AuthGuard(route, state)); + + expect(result).toBe(false); + expect(router.navigate).toHaveBeenCalledWith(['/login']); + expect(localStorage.getItem('accessToken_Internal')).toBeNull(); + }); +}); diff --git a/frontend/src/app/core/security/auth.guard.ts b/frontend/src/app/core/security/auth.guard.ts index af1bae7d7..282a44d9d 100644 --- a/frontend/src/app/core/security/auth.guard.ts +++ b/frontend/src/app/core/security/auth.guard.ts @@ -1,8 +1,10 @@ import {inject} from '@angular/core'; -import {CanActivateFn, Router} from '@angular/router'; +import {ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot} from '@angular/router'; import {AuthService} from '../../shared/service/auth.service'; -export const AuthGuard: CanActivateFn = () => { +export const AuthGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => { + void route; + void state; const router = inject(Router); const authService = inject(AuthService); diff --git a/frontend/src/app/core/security/guards/bookdrop.guard.spec.ts b/frontend/src/app/core/security/guards/bookdrop.guard.spec.ts new file mode 100644 index 000000000..57e2ebeab --- /dev/null +++ b/frontend/src/app/core/security/guards/bookdrop.guard.spec.ts @@ -0,0 +1,54 @@ +import {TestBed} from '@angular/core/testing'; +import {ActivatedRouteSnapshot, Router, RouterStateSnapshot} from '@angular/router'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; + +import {UserService} from '../../../features/settings/user-management/user.service'; +import {BookdropGuard} from './bookdrop.guard'; + +describe('BookdropGuard', () => { + const route = {} as ActivatedRouteSnapshot; + const state = {} as RouterStateSnapshot; + const router = { + navigate: vi.fn(() => Promise.resolve(true)), + }; + const userService = { + currentUser: vi.fn<() => {permissions: {admin: boolean; canAccessBookdrop: boolean}} | null>(), + }; + + beforeEach(() => { + vi.restoreAllMocks(); + router.navigate.mockClear(); + userService.currentUser.mockReset(); + + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + {provide: Router, useValue: router}, + {provide: UserService, useValue: userService}, + ] + }); + }); + + it('allows admins even without the explicit bookdrop permission', () => { + userService.currentUser.mockReturnValue({ + permissions: { + admin: true, + canAccessBookdrop: false, + } + }); + + const result = TestBed.runInInjectionContext(() => BookdropGuard(route, state)); + + expect(result).toBe(true); + expect(router.navigate).not.toHaveBeenCalled(); + }); + + it('redirects anonymous users to the dashboard', () => { + userService.currentUser.mockReturnValue(null); + + const result = TestBed.runInInjectionContext(() => BookdropGuard(route, state)); + + expect(result).toBe(false); + expect(router.navigate).toHaveBeenCalledWith(['/dashboard']); + }); +}); diff --git a/frontend/src/app/core/security/guards/bookdrop.guard.ts b/frontend/src/app/core/security/guards/bookdrop.guard.ts index 13c2ee428..cc3adb2ec 100644 --- a/frontend/src/app/core/security/guards/bookdrop.guard.ts +++ b/frontend/src/app/core/security/guards/bookdrop.guard.ts @@ -1,8 +1,10 @@ import {inject} from '@angular/core'; -import {CanActivateFn, Router} from '@angular/router'; +import {ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot} from '@angular/router'; import {UserService} from '../../../features/settings/user-management/user.service'; -export const BookdropGuard: CanActivateFn = () => { +export const BookdropGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => { + void route; + void state; const userService = inject(UserService); const router = inject(Router); const user = userService.currentUser(); diff --git a/frontend/src/app/core/security/guards/edit-metdata.guard.spec.ts b/frontend/src/app/core/security/guards/edit-metdata.guard.spec.ts new file mode 100644 index 000000000..d4a85dc49 --- /dev/null +++ b/frontend/src/app/core/security/guards/edit-metdata.guard.spec.ts @@ -0,0 +1,59 @@ +import {TestBed} from '@angular/core/testing'; +import {ActivatedRouteSnapshot, Router, RouterStateSnapshot} from '@angular/router'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; + +import {UserService} from '../../../features/settings/user-management/user.service'; +import {EditMetadataGuard} from './edit-metdata.guard'; + +describe('EditMetadataGuard', () => { + const route = {} as ActivatedRouteSnapshot; + const state = {} as RouterStateSnapshot; + const router = { + navigate: vi.fn(() => Promise.resolve(true)), + }; + const userService = { + currentUser: vi.fn<() => {permissions: {admin: boolean; canEditMetadata: boolean}} | null>(), + }; + + beforeEach(() => { + vi.restoreAllMocks(); + router.navigate.mockClear(); + userService.currentUser.mockReset(); + + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + {provide: Router, useValue: router}, + {provide: UserService, useValue: userService}, + ] + }); + }); + + it('allows users with metadata-edit permissions', () => { + userService.currentUser.mockReturnValue({ + permissions: { + admin: false, + canEditMetadata: true, + } + }); + + const result = TestBed.runInInjectionContext(() => EditMetadataGuard(route, state)); + + expect(result).toBe(true); + expect(router.navigate).not.toHaveBeenCalled(); + }); + + it('redirects users who lack metadata-edit permissions', () => { + userService.currentUser.mockReturnValue({ + permissions: { + admin: false, + canEditMetadata: false, + } + }); + + const result = TestBed.runInInjectionContext(() => EditMetadataGuard(route, state)); + + expect(result).toBe(false); + expect(router.navigate).toHaveBeenCalledWith(['/dashboard']); + }); +}); diff --git a/frontend/src/app/core/security/guards/edit-metdata.guard.ts b/frontend/src/app/core/security/guards/edit-metdata.guard.ts index f81ed7c41..01b5e8e3d 100644 --- a/frontend/src/app/core/security/guards/edit-metdata.guard.ts +++ b/frontend/src/app/core/security/guards/edit-metdata.guard.ts @@ -1,8 +1,10 @@ import {inject} from '@angular/core'; -import {CanActivateFn, Router} from '@angular/router'; +import {ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot} from '@angular/router'; import {UserService} from '../../../features/settings/user-management/user.service'; -export const EditMetadataGuard: CanActivateFn = () => { +export const EditMetadataGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => { + void route; + void state; const userService = inject(UserService); const router = inject(Router); const user = userService.currentUser(); diff --git a/frontend/src/app/core/security/guards/library-stats.guard.spec.ts b/frontend/src/app/core/security/guards/library-stats.guard.spec.ts new file mode 100644 index 000000000..28445a366 --- /dev/null +++ b/frontend/src/app/core/security/guards/library-stats.guard.spec.ts @@ -0,0 +1,59 @@ +import {TestBed} from '@angular/core/testing'; +import {ActivatedRouteSnapshot, Router, RouterStateSnapshot} from '@angular/router'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; + +import {UserService} from '../../../features/settings/user-management/user.service'; +import {LibraryStatsGuard} from './library-stats.guard'; + +describe('LibraryStatsGuard', () => { + const route = {} as ActivatedRouteSnapshot; + const state = {} as RouterStateSnapshot; + const router = { + navigate: vi.fn(() => Promise.resolve(true)), + }; + const userService = { + currentUser: vi.fn<() => {permissions: {admin: boolean; canAccessLibraryStats: boolean}} | null>(), + }; + + beforeEach(() => { + vi.restoreAllMocks(); + router.navigate.mockClear(); + userService.currentUser.mockReset(); + + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + {provide: Router, useValue: router}, + {provide: UserService, useValue: userService}, + ] + }); + }); + + it('allows users with the library-stats permission', () => { + userService.currentUser.mockReturnValue({ + permissions: { + admin: false, + canAccessLibraryStats: true, + } + }); + + const result = TestBed.runInInjectionContext(() => LibraryStatsGuard(route, state)); + + expect(result).toBe(true); + expect(router.navigate).not.toHaveBeenCalled(); + }); + + it('redirects users without the library-stats permission', () => { + userService.currentUser.mockReturnValue({ + permissions: { + admin: false, + canAccessLibraryStats: false, + } + }); + + const result = TestBed.runInInjectionContext(() => LibraryStatsGuard(route, state)); + + expect(result).toBe(false); + expect(router.navigate).toHaveBeenCalledWith(['/dashboard']); + }); +}); diff --git a/frontend/src/app/core/security/guards/library-stats.guard.ts b/frontend/src/app/core/security/guards/library-stats.guard.ts index 9521d4352..a27c73c54 100644 --- a/frontend/src/app/core/security/guards/library-stats.guard.ts +++ b/frontend/src/app/core/security/guards/library-stats.guard.ts @@ -1,8 +1,10 @@ import {inject} from '@angular/core'; -import {CanActivateFn, Router} from '@angular/router'; +import {ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot} from '@angular/router'; import {UserService} from '../../../features/settings/user-management/user.service'; -export const LibraryStatsGuard: CanActivateFn = () => { +export const LibraryStatsGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => { + void route; + void state; const userService = inject(UserService); const router = inject(Router); const user = userService.currentUser(); diff --git a/frontend/src/app/core/security/guards/manage-library.guard.spec.ts b/frontend/src/app/core/security/guards/manage-library.guard.spec.ts new file mode 100644 index 000000000..b5c1545a6 --- /dev/null +++ b/frontend/src/app/core/security/guards/manage-library.guard.spec.ts @@ -0,0 +1,59 @@ +import {TestBed} from '@angular/core/testing'; +import {ActivatedRouteSnapshot, Router, RouterStateSnapshot} from '@angular/router'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; + +import {UserService} from '../../../features/settings/user-management/user.service'; +import {ManageLibraryGuard} from './manage-library.guard'; + +describe('ManageLibraryGuard', () => { + const route = {} as ActivatedRouteSnapshot; + const state = {} as RouterStateSnapshot; + const router = { + navigate: vi.fn(() => Promise.resolve(true)), + }; + const userService = { + currentUser: vi.fn<() => {permissions: {admin: boolean; canManageLibrary: boolean}} | null>(), + }; + + beforeEach(() => { + vi.restoreAllMocks(); + router.navigate.mockClear(); + userService.currentUser.mockReset(); + + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + {provide: Router, useValue: router}, + {provide: UserService, useValue: userService}, + ] + }); + }); + + it('allows users with the manage-library permission', () => { + userService.currentUser.mockReturnValue({ + permissions: { + admin: false, + canManageLibrary: true, + } + }); + + const result = TestBed.runInInjectionContext(() => ManageLibraryGuard(route, state)); + + expect(result).toBe(true); + expect(router.navigate).not.toHaveBeenCalled(); + }); + + it('redirects users who lack access', () => { + userService.currentUser.mockReturnValue({ + permissions: { + admin: false, + canManageLibrary: false, + } + }); + + const result = TestBed.runInInjectionContext(() => ManageLibraryGuard(route, state)); + + expect(result).toBe(false); + expect(router.navigate).toHaveBeenCalledWith(['/dashboard']); + }); +}); diff --git a/frontend/src/app/core/security/guards/manage-library.guard.ts b/frontend/src/app/core/security/guards/manage-library.guard.ts index 659921d5c..15af37d45 100644 --- a/frontend/src/app/core/security/guards/manage-library.guard.ts +++ b/frontend/src/app/core/security/guards/manage-library.guard.ts @@ -1,8 +1,10 @@ import {inject} from '@angular/core'; -import {CanActivateFn, Router} from '@angular/router'; +import {ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot} from '@angular/router'; import {UserService} from '../../../features/settings/user-management/user.service'; -export const ManageLibraryGuard: CanActivateFn = () => { +export const ManageLibraryGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => { + void route; + void state; const userService = inject(UserService); const router = inject(Router); const user = userService.currentUser(); diff --git a/frontend/src/app/core/security/guards/user-stats.guard.spec.ts b/frontend/src/app/core/security/guards/user-stats.guard.spec.ts new file mode 100644 index 000000000..870da2cf4 --- /dev/null +++ b/frontend/src/app/core/security/guards/user-stats.guard.spec.ts @@ -0,0 +1,59 @@ +import {TestBed} from '@angular/core/testing'; +import {ActivatedRouteSnapshot, Router, RouterStateSnapshot} from '@angular/router'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; + +import {UserService} from '../../../features/settings/user-management/user.service'; +import {UserStatsGuard} from './user-stats.guard'; + +describe('UserStatsGuard', () => { + const route = {} as ActivatedRouteSnapshot; + const state = {} as RouterStateSnapshot; + const router = { + navigate: vi.fn(() => Promise.resolve(true)), + }; + const userService = { + currentUser: vi.fn<() => {permissions: {admin: boolean; canAccessUserStats: boolean}} | null>(), + }; + + beforeEach(() => { + vi.restoreAllMocks(); + router.navigate.mockClear(); + userService.currentUser.mockReset(); + + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + {provide: Router, useValue: router}, + {provide: UserService, useValue: userService}, + ] + }); + }); + + it('allows admins through the guard', () => { + userService.currentUser.mockReturnValue({ + permissions: { + admin: true, + canAccessUserStats: false, + } + }); + + const result = TestBed.runInInjectionContext(() => UserStatsGuard(route, state)); + + expect(result).toBe(true); + expect(router.navigate).not.toHaveBeenCalled(); + }); + + it('redirects users who cannot access user stats', () => { + userService.currentUser.mockReturnValue({ + permissions: { + admin: false, + canAccessUserStats: false, + } + }); + + const result = TestBed.runInInjectionContext(() => UserStatsGuard(route, state)); + + expect(result).toBe(false); + expect(router.navigate).toHaveBeenCalledWith(['/dashboard']); + }); +}); diff --git a/frontend/src/app/core/security/guards/user-stats.guard.ts b/frontend/src/app/core/security/guards/user-stats.guard.ts index 165a1f549..4965ff95a 100644 --- a/frontend/src/app/core/security/guards/user-stats.guard.ts +++ b/frontend/src/app/core/security/guards/user-stats.guard.ts @@ -1,8 +1,10 @@ import {inject} from '@angular/core'; -import {CanActivateFn, Router} from '@angular/router'; +import {ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot} from '@angular/router'; import {UserService} from '../../../features/settings/user-management/user.service'; -export const UserStatsGuard: CanActivateFn = () => { +export const UserStatsGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => { + void route; + void state; const userService = inject(UserService); const router = inject(Router); const user = userService.currentUser(); diff --git a/frontend/src/app/core/security/oauth2-management/authentication-settings.component.spec.ts b/frontend/src/app/core/security/oauth2-management/authentication-settings.component.spec.ts new file mode 100644 index 000000000..eea1d87c2 --- /dev/null +++ b/frontend/src/app/core/security/oauth2-management/authentication-settings.component.spec.ts @@ -0,0 +1,480 @@ +import {HttpErrorResponse} from '@angular/common/http'; +import {TestBed} from '@angular/core/testing'; +import {signal} from '@angular/core'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {of, throwError} from 'rxjs'; + +import {AppSettingKey, AppSettings, OidcProviderDetails} from '../../../shared/model/app-settings.model'; +import {OidcGroupMapping} from '../../../shared/model/oidc-group-mapping.model'; +import {AppSettingsService} from '../../../shared/service/app-settings.service'; +import {OidcGroupMappingService} from '../../../shared/service/oidc-group-mapping.service'; +import {LibraryService} from '../../../features/book/service/library.service'; +import {MessageService} from 'primeng/api'; +import {TranslocoService} from '@jsverse/transloco'; +import {AuthenticationSettingsComponent} from './authentication-settings.component'; + +function createSettings(overrides: Partial = {}): AppSettings { + return { + oidcEnabled: false, + oidcAutoProvisionDetails: undefined, + oidcProviderDetails: undefined, + oidcSessionDurationHours: null, + oidcGroupSyncMode: null, + oidcForceOnlyMode: false, + ...overrides, + } as AppSettings; +} + +function completeProvider(overrides: Partial = {}): OidcProviderDetails { + return { + providerName: 'Example IdP', + clientId: 'client-id', + clientSecret: 'secret', + issuerUri: 'https://issuer.example', + scopes: 'openid profile email', + claimMapping: { + username: 'preferred_username', + email: 'email', + name: 'given_name', + groups: 'groups', + }, + ...overrides, + }; +} + +describe('AuthenticationSettingsComponent', () => { + const appSettingsSignal = signal(null); + const librariesSignal = signal([{id: 1, name: 'Main Library'}, {id: 2, name: 'Overflow'}]); + + const appSettingsService = { + appSettings: appSettingsSignal, + toggleOidcEnabled: vi.fn(), + saveSettings: vi.fn(), + testOidcConnection: vi.fn(), + }; + + const groupMappingService = { + getAll: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + }; + + const messageService = { + add: vi.fn(), + }; + + const translocoService = { + translate: vi.fn((key: string) => key), + }; + + const libraryService = { + libraries: librariesSignal, + }; + + let component: AuthenticationSettingsComponent; + + beforeEach(() => { + vi.restoreAllMocks(); + appSettingsSignal.set(null); + librariesSignal.set([{id: 1, name: 'Main Library'}, {id: 2, name: 'Overflow'}]); + appSettingsService.toggleOidcEnabled.mockReset(); + appSettingsService.saveSettings.mockReset(); + appSettingsService.testOidcConnection.mockReset(); + groupMappingService.getAll.mockReset(); + groupMappingService.create.mockReset(); + groupMappingService.update.mockReset(); + groupMappingService.delete.mockReset(); + messageService.add.mockReset(); + translocoService.translate.mockClear(); + + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + {provide: AppSettingsService, useValue: appSettingsService}, + {provide: LibraryService, useValue: libraryService}, + {provide: OidcGroupMappingService, useValue: groupMappingService}, + {provide: MessageService, useValue: messageService}, + {provide: TranslocoService, useValue: translocoService}, + ] + }); + + component = TestBed.runInInjectionContext(() => new AuthenticationSettingsComponent()); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('loads defaults when OIDC is disabled and skips group mapping refresh', () => { + component.loadSettings(createSettings({ + oidcEnabled: false, + oidcAutoProvisionDetails: undefined, + oidcProviderDetails: undefined, + oidcSessionDurationHours: null, + oidcGroupSyncMode: null, + oidcForceOnlyMode: false, + })); + + expect(component.oidcEnabled).toBe(false); + expect(component.autoUserProvisioningEnabled).toBe(false); + expect(component.allowLocalAccountLinking).toBe(true); + expect(component.selectedPermissions).toEqual([]); + expect(component.editingLibraryIds).toEqual([]); + expect(component.oidcProvider.claimMapping).toEqual({ + username: 'preferred_username', + email: 'email', + name: 'given_name', + groups: '', + }); + expect(groupMappingService.getAll).not.toHaveBeenCalled(); + }); + + it('applies loaded OIDC settings and refreshes group mappings when enabled', () => { + const mappings: OidcGroupMapping[] = [ + {id: 1, oidcGroupClaim: 'admins', isAdmin: true, permissions: ['permissionUpload'], libraryIds: [1], description: 'Admins'}, + ]; + groupMappingService.getAll.mockReturnValue(of(mappings)); + + component.loadSettings(createSettings({ + oidcEnabled: true, + oidcAutoProvisionDetails: { + enableAutoProvisioning: true, + allowLocalAccountLinking: false, + defaultPermissions: ['permissionUpload', 'permissionEmailBook'], + defaultLibraryIds: [1, 2], + }, + oidcProviderDetails: completeProvider({ + claimMapping: { + username: 'sub', + email: 'mail', + name: 'displayName', + groups: 'memberOf', + }, + }), + oidcSessionDurationHours: 12, + oidcGroupSyncMode: 'ON_LOGIN', + oidcForceOnlyMode: true, + })); + + expect(component.oidcEnabled).toBe(true); + expect(component.autoUserProvisioningEnabled).toBe(true); + expect(component.allowLocalAccountLinking).toBe(false); + expect(component.selectedPermissions).toEqual(['permissionUpload', 'permissionEmailBook']); + expect(component.availablePermissions.find(p => p.value === 'permissionUpload')?.selected).toBe(true); + expect(component.availablePermissions.find(p => p.value === 'permissionDeleteBook')?.selected).toBe(false); + expect(component.editingLibraryIds).toEqual([1, 2]); + expect(component.sessionDurationHours).toBe(12); + expect(component.groupSyncMode).toBe('ON_LOGIN'); + expect(component.oidcForceOnlyMode).toBe(true); + expect(component.oidcProvider.providerName).toBe('Example IdP'); + expect(component.oidcProvider.claimMapping).toEqual({ + username: 'sub', + email: 'mail', + name: 'displayName', + groups: 'memberOf', + }); + expect(component.groupMappings).toEqual(mappings); + expect(groupMappingService.getAll).toHaveBeenCalledOnce(); + }); + + it('keeps OIDC disabled when the provider form is incomplete', () => { + component.oidcEnabled = true; + + component.toggleOidcEnabled(); + + expect(appSettingsService.toggleOidcEnabled).not.toHaveBeenCalled(); + expect(messageService.add).not.toHaveBeenCalled(); + }); + + it('opens a new group mapping dialog with blank state', () => { + component.editingGroupMapping = { + oidcGroupClaim: 'existing', + isAdmin: true, + permissions: ['permissionUpload'], + libraryIds: [1], + description: 'Existing', + }; + component.editingGroupMappingPerms = component.availablePermissions.map(permission => ({ + ...permission, + selected: true, + })); + component.editingGroupMappingLibraryIds = [1]; + + component.openNewGroupMapping(); + + expect(component.showGroupMappingDialog).toBe(true); + expect(component.editingGroupMapping).toEqual({ + oidcGroupClaim: '', + isAdmin: false, + permissions: [], + libraryIds: [], + description: '', + }); + expect(component.editingGroupMappingPerms.every(permission => !permission.selected)).toBe(true); + expect(component.editingGroupMappingLibraryIds).toEqual([]); + }); + + it('opens an existing group mapping dialog with cloned state and selected permissions', () => { + const mapping: OidcGroupMapping = { + id: 42, + oidcGroupClaim: 'admins', + isAdmin: true, + permissions: ['permissionRead', 'permissionUpload'], + libraryIds: [1, 2], + description: 'Administrators', + }; + + component.openEditGroupMapping(mapping); + + expect(component.showGroupMappingDialog).toBe(true); + expect(component.editingGroupMapping).toEqual(mapping); + expect(component.editingGroupMapping).not.toBe(mapping); + expect(component.editingGroupMappingPerms.find(permission => permission.value === 'permissionUpload')?.selected).toBe(true); + expect(component.editingGroupMappingPerms.find(permission => permission.value === 'permissionDeleteBook')?.selected).toBe(false); + expect(component.editingGroupMappingLibraryIds).toEqual([1, 2]); + }); + + it('toggles OIDC enablement and reports persistence failures', () => { + component.oidcProvider = completeProvider(); + appSettingsService.toggleOidcEnabled.mockReturnValueOnce(of(void 0)); + component.oidcEnabled = true; + + component.toggleOidcEnabled(); + + expect(appSettingsService.toggleOidcEnabled).toHaveBeenCalledWith(true); + expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'success', + detail: 'settingsAuth.toast.oidcUpdated', + })); + + appSettingsService.toggleOidcEnabled.mockReturnValueOnce( + throwError(() => new HttpErrorResponse({status: 500})) + ); + component.oidcEnabled = false; + + component.toggleOidcEnabled(); + + expect(messageService.add).toHaveBeenLastCalledWith(expect.objectContaining({ + severity: 'error', + detail: 'settingsAuth.toast.oidcError', + })); + }); + + it('copies the backchannel URI using the helper method', () => { + const copySpy = vi.spyOn(component, 'copyToClipboard').mockImplementation(() => undefined); + + component.copyBackchannelUri(); + + expect(copySpy).toHaveBeenCalledWith(component.backchannelLogoutUri); + }); + + it('saves OIDC provider settings with the session duration only when OIDC is enabled', () => { + appSettingsService.saveSettings.mockReturnValue(of(void 0)); + component.oidcProvider = completeProvider(); + component.oidcEnabled = false; + component.sessionDurationHours = 24; + + component.saveOidcProvider(); + + expect(appSettingsService.saveSettings).toHaveBeenCalledWith([ + { + key: AppSettingKey.OIDC_PROVIDER_DETAILS, + newValue: component.oidcProvider, + } + ]); + + component.oidcEnabled = true; + component.saveOidcProvider(); + + expect(appSettingsService.saveSettings).toHaveBeenLastCalledWith([ + { + key: AppSettingKey.OIDC_PROVIDER_DETAILS, + newValue: component.oidcProvider, + }, + { + key: AppSettingKey.OIDC_SESSION_DURATION_HOURS, + newValue: 24, + } + ]); + }); + + it('saves the group sync mode and reports failures', () => { + appSettingsService.saveSettings.mockReturnValueOnce(of(void 0)); + component.groupSyncMode = 'ON_LOGIN_ADDITIVE'; + + component.saveGroupSyncMode(); + + expect(appSettingsService.saveSettings).toHaveBeenCalledWith([ + { + key: AppSettingKey.OIDC_GROUP_SYNC_MODE, + newValue: 'ON_LOGIN_ADDITIVE', + } + ]); + expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'success', + detail: 'settingsAuth.toast.syncModeSaved', + })); + + appSettingsService.saveSettings.mockReturnValueOnce( + throwError(() => new HttpErrorResponse({status: 500})) + ); + + component.saveGroupSyncMode(); + + expect(messageService.add).toHaveBeenLastCalledWith(expect.objectContaining({ + severity: 'error', + detail: 'settingsAuth.toast.syncModeError', + })); + }); + + it('saves the auto-provisioning payload with the selected permissions and library ids', () => { + appSettingsService.saveSettings.mockReturnValue(of(void 0)); + component.autoUserProvisioningEnabled = true; + component.allowLocalAccountLinking = false; + component.availablePermissions.find(p => p.value === 'permissionUpload')!.selected = true; + component.availablePermissions.find(p => p.value === 'permissionDeleteBook')!.selected = true; + component.editingLibraryIds = [1, 2]; + + component.saveOidcAutoProvisionSettings(); + + expect(appSettingsService.saveSettings).toHaveBeenCalledWith([ + { + key: AppSettingKey.OIDC_AUTO_PROVISION_DETAILS, + newValue: { + enableAutoProvisioning: true, + allowLocalAccountLinking: false, + defaultPermissions: ['permissionRead', 'permissionUpload', 'permissionDeleteBook'], + defaultLibraryIds: [1, 2], + }, + } + ]); + }); + + it('creates and updates group mappings, and ignores delete requests without an id', () => { + const createdMapping = {id: 9, oidcGroupClaim: 'readers', isAdmin: false, permissions: ['permissionRead'], libraryIds: [1], description: 'Readers'}; + appSettingsService.saveSettings.mockReturnValue(of(void 0)); + groupMappingService.create.mockReturnValue(of(createdMapping)); + groupMappingService.update.mockReturnValue(of(createdMapping)); + groupMappingService.delete.mockReturnValue(of(void 0)); + groupMappingService.getAll.mockReturnValue(of([createdMapping])); + component.editingGroupMapping = {oidcGroupClaim: 'readers', isAdmin: false, permissions: [], libraryIds: [], description: ''}; + component.editingGroupMappingPerms = component.availablePermissions.map(permission => ({ + ...permission, + selected: permission.value === 'permissionUpload', + })); + component.editingGroupMappingLibraryIds = [1]; + + component.saveGroupMapping(); + + expect(groupMappingService.create).toHaveBeenCalledWith({ + oidcGroupClaim: 'readers', + isAdmin: false, + permissions: ['permissionRead', 'permissionUpload'], + libraryIds: [1], + description: '', + }); + + component.editingGroupMapping = createdMapping; + component.editingGroupMappingPerms = component.availablePermissions.map(permission => ({ + ...permission, + selected: false, + })); + component.editingGroupMappingLibraryIds = [2]; + component.saveGroupMapping(); + + expect(groupMappingService.update).toHaveBeenCalledWith(9, { + ...createdMapping, + permissions: ['permissionRead'], + libraryIds: [2], + }); + + component.deleteGroupMapping({oidcGroupClaim: 'no-id', isAdmin: false, permissions: [], libraryIds: [], description: ''}); + expect(groupMappingService.delete).not.toHaveBeenCalledWith(undefined); + }); + + it('surfaces failures when deleting a mapped group with an id', () => { + const mapping = {id: 11, oidcGroupClaim: 'errors', isAdmin: false, permissions: [], libraryIds: [], description: ''}; + groupMappingService.delete.mockReturnValue(throwError(() => new HttpErrorResponse({status: 500}))); + + component.deleteGroupMapping(mapping); + + expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'error', + detail: 'settingsAuth.toast.groupMappingError', + })); + }); + + it('deletes mappings with an id and reloads after success', () => { + const mapping = {id: 3, oidcGroupClaim: 'managers', isAdmin: false, permissions: [], libraryIds: [], description: ''}; + groupMappingService.delete.mockReturnValue(of(void 0)); + groupMappingService.getAll.mockReturnValue(of([])); + + component.deleteGroupMapping(mapping); + + expect(groupMappingService.delete).toHaveBeenCalledWith(3); + expect(groupMappingService.getAll).toHaveBeenCalledOnce(); + expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'})); + }); + + it('re-enables the force-only toggle when persistence succeeds', () => { + appSettingsService.saveSettings.mockReturnValue(of(void 0)); + component.oidcForceOnlyMode = true; + + component.toggleOidcForceOnlyMode(); + + expect(component.oidcForceOnlyMode).toBe(true); + expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'success', + detail: 'settingsAuth.oidcOnly.saved', + })); + }); + + it('tests the OIDC connection and surfaces both success and failure states', () => { + appSettingsService.testOidcConnection.mockReturnValueOnce(of({ + success: true, + checks: [{name: 'issuer', status: 'PASS', message: 'ok'}], + })); + + component.testConnection(); + + expect(component.isTestingConnection).toBe(false); + expect(component.testConnectionResult).toEqual({ + success: true, + checks: [{name: 'issuer', status: 'PASS', message: 'ok'}], + }); + expect(component.showTestDetails).toBe(true); + + appSettingsService.testOidcConnection.mockReturnValueOnce( + throwError(() => new HttpErrorResponse({status: 500})) + ); + + component.testConnection(); + + expect(component.isTestingConnection).toBe(false); + expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'error', + detail: 'settingsAuth.testConnection.error', + })); + }); + + it('reverts the force-only toggle when persistence fails', () => { + component.oidcForceOnlyMode = true; + appSettingsService.saveSettings.mockReturnValue( + throwError(() => ({error: {message: 'backend rejected'}})) + ); + + component.toggleOidcForceOnlyMode(); + + expect(component.oidcForceOnlyMode).toBe(false); + expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'error', + detail: 'backend rejected', + })); + }); + + it('returns library names when present and falls back to the numeric id when missing', () => { + expect(component.getLibraryName(1)).toBe('Main Library'); + expect(component.getLibraryName(999)).toBe('#999'); + }); +}); diff --git a/frontend/src/app/core/security/oidc-callback/oidc-callback.component.spec.ts b/frontend/src/app/core/security/oidc-callback/oidc-callback.component.spec.ts new file mode 100644 index 000000000..5a3e4a10b --- /dev/null +++ b/frontend/src/app/core/security/oidc-callback/oidc-callback.component.spec.ts @@ -0,0 +1,158 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {Router} from '@angular/router'; +import {of, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {getTranslocoModule} from '../../testing/transloco-testing'; +import {AuthService} from '../../../shared/service/auth.service'; +import {OidcService} from '../oidc.service'; +import {OidcCallbackComponent} from './oidc-callback.component'; + +describe('OidcCallbackComponent', () => { + let fixture: ComponentFixture; + + const router = { + navigate: vi.fn(() => Promise.resolve(true)), + }; + const oidcService = { + retrievePkceState: vi.fn(), + exchangeCode: vi.fn(), + }; + const authService = { + saveInternalTokens: vi.fn(), + initializeWebSocketConnection: vi.fn(), + }; + + function configureComponent(search = ''): void { + window.history.replaceState({}, '', `/oauth2-callback${search}`); + + TestBed.configureTestingModule({ + imports: [ + OidcCallbackComponent, + getTranslocoModule(), + ], + providers: [ + {provide: Router, useValue: router}, + {provide: OidcService, useValue: oidcService}, + {provide: AuthService, useValue: authService}, + ] + }); + + fixture = TestBed.createComponent(OidcCallbackComponent); + fixture.detectChanges(); + } + + beforeEach(() => { + vi.restoreAllMocks(); + sessionStorage.clear(); + router.navigate.mockClear(); + oidcService.retrievePkceState.mockReset(); + oidcService.exchangeCode.mockReset(); + authService.saveInternalTokens.mockReset(); + authService.initializeWebSocketConnection.mockReset(); + TestBed.resetTestingModule(); + }); + + afterEach(() => { + window.history.replaceState({}, '', '/'); + sessionStorage.clear(); + TestBed.resetTestingModule(); + }); + + it('redirects to login when the provider returns an error', () => { + configureComponent('?error=access_denied&error_description=denied'); + + expect(router.navigate).toHaveBeenCalledWith(['/login'], { + queryParams: {oidcError: 'denied'}, + }); + }); + + it('redirects to login when code or state is missing', () => { + configureComponent('?state=missing-code'); + + expect(router.navigate).toHaveBeenCalledWith(['/login'], { + queryParams: {oidcError: 'missing_code'}, + }); + }); + + it('redirects to login when there is no stored PKCE state', () => { + oidcService.retrievePkceState.mockReturnValue(null); + + configureComponent('?code=code-123&state=state-123'); + + expect(oidcService.retrievePkceState).toHaveBeenCalledWith('state-123'); + expect(router.navigate).toHaveBeenCalledWith(['/login'], { + queryParams: {oidcError: 'missing_pkce_state'}, + }); + }); + + it('redirects to login when the returned state does not match the stored PKCE state', () => { + oidcService.retrievePkceState.mockReturnValue({ + codeVerifier: 'verifier', + nonce: 'nonce', + state: 'other-state', + }); + + configureComponent('?code=code-123&state=state-123'); + + expect(router.navigate).toHaveBeenCalledWith(['/login'], { + queryParams: {oidcError: 'state_mismatch'}, + }); + }); + + it('saves tokens and redirects to change-password when the backend flags a default password', () => { + sessionStorage.setItem('oidc_redirect_count', '2'); + oidcService.retrievePkceState.mockReturnValue({ + codeVerifier: 'verifier', + nonce: 'nonce', + state: 'state-123', + }); + oidcService.exchangeCode.mockReturnValue(of({ + accessToken: 'access', + refreshToken: 'refresh', + isDefaultPassword: 'true', + })); + + configureComponent('?code=code-123&state=state-123'); + + expect(authService.saveInternalTokens).toHaveBeenCalledWith('access', 'refresh'); + expect(authService.initializeWebSocketConnection).toHaveBeenCalledOnce(); + expect(sessionStorage.getItem('oidc_redirect_count')).toBeNull(); + expect(router.navigate).toHaveBeenCalledWith(['/change-password']); + }); + + it('saves tokens and redirects to the dashboard after a successful exchange', () => { + oidcService.retrievePkceState.mockReturnValue({ + codeVerifier: 'verifier', + nonce: 'nonce', + state: 'state-123', + }); + oidcService.exchangeCode.mockReturnValue(of({ + accessToken: 'access', + refreshToken: 'refresh', + isDefaultPassword: 'false', + })); + + configureComponent('?code=code-123&state=state-123'); + + expect(authService.saveInternalTokens).toHaveBeenCalledWith('access', 'refresh'); + expect(router.navigate).toHaveBeenCalledWith(['/dashboard']); + }); + + it('redirects to login with the backend error message when the exchange fails', () => { + oidcService.retrievePkceState.mockReturnValue({ + codeVerifier: 'verifier', + nonce: 'nonce', + state: 'state-123', + }); + oidcService.exchangeCode.mockReturnValue( + throwError(() => ({error: {message: 'exchange_failed'}})) + ); + + configureComponent('?code=code-123&state=state-123'); + + expect(router.navigate).toHaveBeenCalledWith(['/login'], { + queryParams: {oidcError: 'exchange_failed'}, + }); + }); +}); diff --git a/frontend/src/app/core/security/oidc.service.spec.ts b/frontend/src/app/core/security/oidc.service.spec.ts new file mode 100644 index 000000000..4aa82c44c --- /dev/null +++ b/frontend/src/app/core/security/oidc.service.spec.ts @@ -0,0 +1,168 @@ +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {of} from 'rxjs'; + +import {AppSettingsService} from '../../shared/service/app-settings.service'; +import {API_CONFIG} from '../config/api-config'; +import {OidcService} from './oidc.service'; + +describe('OidcService', () => { + interface OidcServiceInternals { + http: { + get: ReturnType; + post: ReturnType; + }; + appSettingsService: AppSettingsService; + } + + const createService = () => { + const service = Object.create(OidcService.prototype) as OidcService; + const internals = service as unknown as OidcServiceInternals; + internals.http = { + get: vi.fn(), + post: vi.fn(), + }; + internals.appSettingsService = {} as AppSettingsService; + return {service, http: internals.http}; + }; + + beforeEach(() => { + vi.restoreAllMocks(); + sessionStorage.clear(); + }); + + afterEach(() => { + sessionStorage.clear(); + }); + + it('generates PKCE verifier and challenge pairs', async () => { + const {service} = createService(); + const digestSpy = vi.fn(async (_algorithm: string, value: Uint8Array) => value); + const getRandomValuesSpy = vi.fn((array: Uint8Array) => { + array.set(Uint8Array.from({length: array.length}, (_, index) => index + 1)); + return array; + }); + vi.stubGlobal('crypto', { + getRandomValues: getRandomValuesSpy, + subtle: {digest: digestSpy}, + }); + + const result = await service.generatePkce(); + + expect(getRandomValuesSpy).toHaveBeenCalledOnce(); + expect(digestSpy).toHaveBeenCalledOnce(); + expect(result.codeVerifier).toBeTruthy(); + expect(result.codeChallenge).toBeTruthy(); + }); + + it('generates random URL-safe strings', () => { + const {service} = createService(); + vi.stubGlobal('crypto', { + getRandomValues: (array: Uint8Array) => { + array.set(Uint8Array.from({length: array.length}, (_, index) => index + 10)); + return array; + }, + subtle: {digest: vi.fn()}, + }); + + const value = service.generateRandomString(); + + expect(value).toMatch(/^[A-Za-z0-9_-]+$/); + }); + + it('builds an auth url directly when the authorization endpoint is provided', async () => { + const {service} = createService(); + const authUrl = await service.buildAuthUrl( + 'https://issuer.example', + 'client-id', + 'challenge', + 'state-token', + 'nonce-token', + 'https://issuer.example/authorize', + 'openid profile' + ); + + expect(authUrl).toContain('https://issuer.example/authorize?'); + expect(authUrl).toContain('client_id=client-id'); + expect(authUrl).toContain('scope=openid+profile'); + expect(authUrl).toContain('state=state-token'); + }); + + it('builds an auth url from the OIDC discovery document when the endpoint is omitted', async () => { + const {service} = createService(); + vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ + json: async () => ({authorization_endpoint: 'https://issuer.example/discovered-authorize'}) + })); + + const authUrl = await service.buildAuthUrl( + 'https://issuer.example/', + 'client-id', + 'challenge', + 'state-token', + 'nonce-token' + ); + + expect(fetch).toHaveBeenCalledWith('https://issuer.example/.well-known/openid-configuration'); + expect(authUrl).toContain('https://issuer.example/discovered-authorize?'); + }); + + it('throws when the discovery document does not expose an authorization endpoint', async () => { + const {service} = createService(); + vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ + json: async () => ({issuer: 'https://issuer.example'}) + })); + + await expect(service.buildAuthUrl( + 'https://issuer.example/', + 'client-id', + 'challenge', + 'state-token', + 'nonce-token' + )).rejects.toThrow('authorization_endpoint not found in discovery document'); + }); + + it('fetches the backend-generated OIDC state token', async () => { + const {service, http} = createService(); + http.get.mockReturnValue(of({state: 'server-state'})); + + const statePromise = service.fetchState(); + + await expect(statePromise).resolves.toBe('server-state'); + expect(http.get).toHaveBeenCalledWith(`${API_CONFIG.BASE_URL}/api/v1/auth/oidc/state`); + }); + + it('posts the callback payload to exchange an OIDC code for tokens', () => { + const {service, http} = createService(); + http.post.mockReturnValue(of({accessToken: 'access', refreshToken: 'refresh', isDefaultPassword: 'false'})); + + service.exchangeCode('code-123', 'verifier', 'nonce', 'state').subscribe(); + + expect(http.post).toHaveBeenCalledWith(`${API_CONFIG.BASE_URL}/api/v1/auth/oidc/callback`, { + code: 'code-123', + codeVerifier: 'verifier', + redirectUri: `${window.location.origin}/oauth2-callback`, + nonce: 'nonce', + state: 'state', + }); + }); + + it('stores, retrieves, and removes pkce state entries', () => { + const {service} = createService(); + service.storePkceState({codeVerifier: 'verifier', state: 'state', nonce: 'nonce'}); + + expect(service.retrievePkceState('state')).toEqual({ + codeVerifier: 'verifier', + state: 'state', + nonce: 'nonce', + }); + expect(service.retrievePkceState('state')).toBeNull(); + }); + + it('returns null when stored PKCE state is missing or malformed', () => { + const {service} = createService(); + expect(service.retrievePkceState('missing')).toBeNull(); + + sessionStorage.setItem('oidc_pkce_bad', '{not-json'); + + expect(service.retrievePkceState('bad')).toBeNull(); + }); +}); diff --git a/frontend/src/app/core/security/secure-pipe.spec.ts b/frontend/src/app/core/security/secure-pipe.spec.ts new file mode 100644 index 000000000..3031d2736 --- /dev/null +++ b/frontend/src/app/core/security/secure-pipe.spec.ts @@ -0,0 +1,48 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {DomSanitizer} from '@angular/platform-browser'; +import {firstValueFrom} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {SecurePipe} from './secure-pipe'; + +describe('SecurePipe', () => { + let pipe: SecurePipe; + let httpTestingController: HttpTestingController; + let sanitizer: DomSanitizer; + + beforeEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + SecurePipe, + ] + }); + + pipe = TestBed.inject(SecurePipe); + httpTestingController = TestBed.inject(HttpTestingController); + sanitizer = TestBed.inject(DomSanitizer); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('fetches the blob and returns a sanitized object URL', async () => { + const objectUrlSpy = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:cover'); + const sanitizerSpy = vi.spyOn(sanitizer, 'bypassSecurityTrustUrl').mockReturnValue('safe:cover' as never); + + const resultPromise = firstValueFrom(pipe.transform('/covers/1')); + const request = httpTestingController.expectOne('/covers/1'); + request.flush(new Blob(['cover'])); + + await expect(resultPromise).resolves.toBe('safe:cover'); + expect(objectUrlSpy).toHaveBeenCalledOnce(); + expect(sanitizerSpy).toHaveBeenCalledWith('blob:cover'); + }); +}); diff --git a/frontend/src/app/core/security/secure-src.directive.spec.ts b/frontend/src/app/core/security/secure-src.directive.spec.ts new file mode 100644 index 000000000..a2a7b1f98 --- /dev/null +++ b/frontend/src/app/core/security/secure-src.directive.spec.ts @@ -0,0 +1,155 @@ +import {Component} from '@angular/core'; +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {By} from '@angular/platform-browser'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {SecureSrcDirective} from './secure-src.directive'; + +@Component({ + standalone: true, + imports: [SecureSrcDirective], + template: `test cover` +}) +class TestHostComponent { + src = ''; +} + +@Component({ + standalone: true, + imports: [SecureSrcDirective], + template: `test cover` +}) +class DefaultFallbackHostComponent { + src = ''; +} + +describe('SecureSrcDirective', () => { + let fixture: ComponentFixture; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + imports: [TestHostComponent], + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + ] + }); + + fixture = TestBed.createComponent(TestHostComponent); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + function image(): HTMLImageElement { + return fixture.debugElement.query(By.css('img')).nativeElement as HTMLImageElement; + } + + it('loads a secure blob URL into the host image', () => { + vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:secure-cover'); + + fixture.componentInstance.src = '/covers/1'; + fixture.detectChanges(); + + const request = httpTestingController.expectOne('/covers/1'); + request.flush(new Blob(['cover'])); + + expect(image().src).toContain('blob:secure-cover'); + }); + + it('skips loading when the source is empty', () => { + fixture.detectChanges(); + + httpTestingController.expectNone(() => true); + expect(image().getAttribute('src')).toBeNull(); + }); + + it('uses the fallback image and suppresses CORS-style console noise for status 0 and 403', () => { + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined); + + fixture.componentInstance.src = '/covers/2'; + fixture.detectChanges(); + + const firstRequest = httpTestingController.expectOne('/covers/2'); + firstRequest.error(new ProgressEvent('error'), {status: 0, statusText: 'Unknown Error'}); + + expect(image().src).toContain('/fallback.png'); + expect(errorSpy).not.toHaveBeenCalled(); + + fixture.componentInstance.src = '/covers/3'; + fixture.detectChanges(); + + const secondRequest = httpTestingController.expectOne('/covers/3'); + secondRequest.flush(new Blob(['forbidden']), {status: 403, statusText: 'Forbidden'}); + + expect(image().src).toContain('/fallback.png'); + expect(errorSpy).not.toHaveBeenCalled(); + }); + + it('logs unexpected failures and revokes prior object URLs during cleanup', () => { + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined); + const revokeSpy = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined); + vi.spyOn(URL, 'createObjectURL').mockReturnValueOnce('blob:first').mockReturnValueOnce('blob:second'); + + fixture.componentInstance.src = '/covers/4'; + fixture.detectChanges(); + httpTestingController.expectOne('/covers/4').flush(new Blob(['first'])); + + fixture.componentInstance.src = '/covers/5'; + fixture.detectChanges(); + + expect(revokeSpy).toHaveBeenCalledWith('blob:first'); + + httpTestingController.expectOne('/covers/5').flush(new Blob(['boom']), {status: 500, statusText: 'Server Error'}); + + expect(image().src).toContain('/fallback.png'); + expect(errorSpy).toHaveBeenCalledOnce(); + + fixture.destroy(); + }); + + it('revokes the active object URL when the directive is destroyed after a successful load', () => { + const revokeSpy = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined); + vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:destroyed'); + + fixture.componentInstance.src = '/covers/7'; + fixture.detectChanges(); + + const request = httpTestingController.expectOne('/covers/7'); + request.flush(new Blob(['cover'])); + + fixture.destroy(); + + expect(revokeSpy).toHaveBeenCalledWith('blob:destroyed'); + }); + + it('uses the default fallback image when no fallback attribute is provided', () => { + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + imports: [DefaultFallbackHostComponent], + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + ] + }); + + const defaultFixture = TestBed.createComponent(DefaultFallbackHostComponent); + const defaultHttpTestingController = TestBed.inject(HttpTestingController); + defaultFixture.componentInstance.src = '/covers/6'; + defaultFixture.detectChanges(); + + const request = defaultHttpTestingController.expectOne('/covers/6'); + request.error(new ProgressEvent('error'), {status: 500, statusText: 'Server Error'}); + + expect(defaultFixture.debugElement.query(By.css('img')).nativeElement.src).toContain('assets/images/missing-cover.jpg'); + defaultHttpTestingController.verify(); + }); +}); diff --git a/frontend/src/app/core/security/security-guards.spec.ts b/frontend/src/app/core/security/security-guards.spec.ts new file mode 100644 index 000000000..848a656b4 --- /dev/null +++ b/frontend/src/app/core/security/security-guards.spec.ts @@ -0,0 +1,136 @@ +import {TestBed} from '@angular/core/testing'; +import {ActivatedRouteSnapshot, Router, RouterStateSnapshot} from '@angular/router'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; + +import {UserService} from '../../features/settings/user-management/user.service'; +import {BookdropGuard} from './guards/bookdrop.guard'; +import {EditMetadataGuard} from './guards/edit-metdata.guard'; +import {LibraryStatsGuard} from './guards/library-stats.guard'; +import {ManageLibraryGuard} from './guards/manage-library.guard'; +import {UserStatsGuard} from './guards/user-stats.guard'; + +type PermissionFlag = + | 'canAccessBookdrop' + | 'canEditMetadata' + | 'canAccessLibraryStats' + | 'canManageLibrary' + | 'canAccessUserStats'; + +function createUser(permissionFlag: PermissionFlag, value: boolean, admin = false) { + return { + permissions: { + admin, + canAccessBookdrop: permissionFlag === 'canAccessBookdrop' ? value : false, + canEditMetadata: permissionFlag === 'canEditMetadata' ? value : false, + canAccessLibraryStats: permissionFlag === 'canAccessLibraryStats' ? value : false, + canManageLibrary: permissionFlag === 'canManageLibrary' ? value : false, + canAccessUserStats: permissionFlag === 'canAccessUserStats' ? value : false, + } + }; +} + +describe('security guards', () => { + const route = {} as ActivatedRouteSnapshot; + const state = {} as RouterStateSnapshot; + const router = { + navigate: vi.fn(() => Promise.resolve(true)), + }; + const userService = { + currentUser: vi.fn(), + }; + + beforeEach(() => { + vi.restoreAllMocks(); + router.navigate.mockClear(); + userService.currentUser.mockReset(); + + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + {provide: Router, useValue: router}, + {provide: UserService, useValue: userService}, + ] + }); + }); + + function expectGuardAllows( + permissionFlag: PermissionFlag, + guard: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => unknown + ): void { + userService.currentUser.mockReturnValue(createUser(permissionFlag, true)); + + const result = TestBed.runInInjectionContext(() => guard(route, state)); + + expect(result).toBe(true); + expect(router.navigate).not.toHaveBeenCalled(); + } + + function expectGuardAllowsAdmin( + permissionFlag: PermissionFlag, + guard: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => unknown + ): void { + userService.currentUser.mockReturnValue(createUser(permissionFlag, false, true)); + + const result = TestBed.runInInjectionContext(() => guard(route, state)); + + expect(result).toBe(true); + expect(router.navigate).not.toHaveBeenCalled(); + } + + function expectGuardRedirects( + permissionFlag: PermissionFlag, + guard: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => unknown + ): void { + userService.currentUser.mockReturnValue(createUser(permissionFlag, false)); + + const result = TestBed.runInInjectionContext(() => guard(route, state)); + + expect(result).toBe(false); + expect(router.navigate).toHaveBeenCalledWith(['/dashboard']); + } + + it('allows bookdrop access for admins and users with the explicit permission', () => { + expectGuardAllows('canAccessBookdrop', BookdropGuard); + expectGuardAllowsAdmin('canAccessBookdrop', BookdropGuard); + }); + + it('redirects bookdrop access when the user lacks permission', () => { + expectGuardRedirects('canAccessBookdrop', BookdropGuard); + }); + + it('allows metadata editing for admins and users with the explicit permission', () => { + expectGuardAllows('canEditMetadata', EditMetadataGuard); + expectGuardAllowsAdmin('canEditMetadata', EditMetadataGuard); + }); + + it('redirects metadata editing when the user lacks permission', () => { + expectGuardRedirects('canEditMetadata', EditMetadataGuard); + }); + + it('allows library stats for admins and users with the explicit permission', () => { + expectGuardAllows('canAccessLibraryStats', LibraryStatsGuard); + expectGuardAllowsAdmin('canAccessLibraryStats', LibraryStatsGuard); + }); + + it('redirects library stats when the user lacks permission', () => { + expectGuardRedirects('canAccessLibraryStats', LibraryStatsGuard); + }); + + it('allows library management for admins and users with the explicit permission', () => { + expectGuardAllows('canManageLibrary', ManageLibraryGuard); + expectGuardAllowsAdmin('canManageLibrary', ManageLibraryGuard); + }); + + it('redirects library management when the user lacks permission', () => { + expectGuardRedirects('canManageLibrary', ManageLibraryGuard); + }); + + it('allows user stats for admins and users with the explicit permission', () => { + expectGuardAllows('canAccessUserStats', UserStatsGuard); + expectGuardAllowsAdmin('canAccessUserStats', UserStatsGuard); + }); + + it('redirects user stats when the user lacks permission', () => { + expectGuardRedirects('canAccessUserStats', UserStatsGuard); + }); +}); diff --git a/frontend/src/app/core/services/loading.service.spec.ts b/frontend/src/app/core/services/loading.service.spec.ts new file mode 100644 index 000000000..1f877b8d3 --- /dev/null +++ b/frontend/src/app/core/services/loading.service.spec.ts @@ -0,0 +1,69 @@ +import {afterEach, describe, expect, it} from 'vitest'; + +import {LoadingService} from './loading.service'; + +describe('LoadingService', () => { + afterEach(() => { + document.body.innerHTML = ''; + document.body.style.cursor = ''; + }); + + it('shows the default loading overlay and restores the cursor when hidden', () => { + const service = new LoadingService(); + + const loader = service.show(); + + expect(document.body.contains(loader)).toBe(true); + expect(loader.querySelector('.loader-content')?.textContent).toContain('Loading...'); + expect(document.body.style.cursor).toBe('wait'); + + service.hide(loader); + + expect(document.body.contains(loader)).toBe(false); + expect(document.body.style.cursor).toBe('default'); + }); + + it('renders a custom loading message', () => { + const service = new LoadingService(); + + const loader = service.show('Syncing metadata'); + + expect(loader.querySelector('.loader-content')?.textContent).toContain('Syncing metadata'); + + service.hide(loader); + }); + + it('removes all active overlays and ignores detached loaders', () => { + const service = new LoadingService(); + + const first = service.show('First'); + const second = service.show('Second'); + const detached = document.createElement('div'); + + expect(() => service.hide(detached)).not.toThrow(); + + service.hideAll(); + + expect(document.body.contains(first)).toBe(false); + expect(document.body.contains(second)).toBe(false); + expect(document.body.style.cursor).toBe('default'); + }); + + it('keeps the wait cursor active until the final loader is hidden', () => { + const service = new LoadingService(); + + const first = service.show('First'); + const second = service.show('Second'); + + service.hide(first); + + expect(document.body.contains(first)).toBe(false); + expect(document.body.contains(second)).toBe(true); + expect(document.body.style.cursor).toBe('wait'); + + service.hide(second); + + expect(document.body.contains(second)).toBe(false); + expect(document.body.style.cursor).toBe('default'); + }); +}); diff --git a/frontend/src/app/core/services/post-login-initializer.service.spec.ts b/frontend/src/app/core/services/post-login-initializer.service.spec.ts new file mode 100644 index 000000000..b5d88d510 --- /dev/null +++ b/frontend/src/app/core/services/post-login-initializer.service.spec.ts @@ -0,0 +1,17 @@ +import {TestBed} from '@angular/core/testing'; +import {firstValueFrom} from 'rxjs'; +import {describe, expect, it} from 'vitest'; + +import {PostLoginInitializerService} from './post-login-initializer.service'; + +describe('PostLoginInitializerService', () => { + it('completes successfully', async () => { + TestBed.configureTestingModule({ + providers: [PostLoginInitializerService], + }); + + const service = TestBed.inject(PostLoginInitializerService); + + await expect(firstValueFrom(service.initialize())).resolves.toBeUndefined(); + }); +}); diff --git a/frontend/src/app/core/testing/chart-testing.ts b/frontend/src/app/core/testing/chart-testing.ts new file mode 100644 index 000000000..a8edf5520 --- /dev/null +++ b/frontend/src/app/core/testing/chart-testing.ts @@ -0,0 +1,26 @@ +import {Observable, firstValueFrom} from 'rxjs'; +import {skip, take} from 'rxjs/operators'; + +interface ChartTooltipContextInput { + data: number[]; + labels: string[]; + dataIndex: number; +} + +export function nextChartEmission(source$: Observable): Promise { + return firstValueFrom(source$.pipe(skip(1), take(1))); +} + +export function fakeChartTooltipContext(input: ChartTooltipContextInput) { + return { + dataIndex: input.dataIndex, + dataset: { + data: input.data, + }, + chart: { + data: { + labels: input.labels, + }, + }, + }; +} diff --git a/frontend/src/app/core/testing/dialog-testing.ts b/frontend/src/app/core/testing/dialog-testing.ts new file mode 100644 index 000000000..a605207d2 --- /dev/null +++ b/frontend/src/app/core/testing/dialog-testing.ts @@ -0,0 +1,38 @@ +import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; +import {MessageService, ConfirmationService} from 'primeng/api'; +import {vi} from 'vitest'; +import {MockProvider} from 'ng-mocks'; + +export function createDynamicDialogHarness(data: T) { + const dialogRef = { + close: vi.fn(), + }; + + return { + dialogRef, + providers: [ + MockProvider(DynamicDialogConfig, {data}), + MockProvider(DynamicDialogRef, dialogRef), + ], + }; +} + +export function createMessageServiceSpy() { + return { + add: vi.fn(), + }; +} + +export function createConfirmServiceSpy() { + return { + confirm: vi.fn(), + }; +} + +export function createMessageServiceProvider(messageService: ReturnType) { + return MockProvider(MessageService, messageService); +} + +export function createConfirmServiceProvider(confirmationService: ReturnType) { + return MockProvider(ConfirmationService, confirmationService); +} diff --git a/frontend/src/app/core/testing/query-testing.ts b/frontend/src/app/core/testing/query-testing.ts new file mode 100644 index 000000000..a06be7b54 --- /dev/null +++ b/frontend/src/app/core/testing/query-testing.ts @@ -0,0 +1,40 @@ +import {signal, type EnvironmentProviders, type Provider, type WritableSignal} from '@angular/core'; +import {provideHttpClient} from '@angular/common/http'; +import {provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {provideTanStackQuery, QueryClient} from '@tanstack/angular-query-experimental'; + +interface AuthServiceStub { + token: WritableSignal; + getInternalAccessToken: () => string | null; +} + +export interface QueryClientHarness { + providers: (Provider | EnvironmentProviders)[]; + queryClient: QueryClient; +} + +export function createAuthServiceStub(initialToken: string | null = 'token-123'): AuthServiceStub { + const token = signal(initialToken); + return { + token, + getInternalAccessToken: () => token(), + }; +} + +export function createQueryClientHarness(): QueryClientHarness { + const queryClient = new QueryClient(); + + return { + queryClient, + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + provideTanStackQuery(queryClient), + ], + }; +} + +export function flushSignalAndQueryEffects(): void { + TestBed.flushEffects(); +} diff --git a/frontend/src/app/core/testing/transloco-testing.spec.ts b/frontend/src/app/core/testing/transloco-testing.spec.ts new file mode 100644 index 000000000..c10ae3f0e --- /dev/null +++ b/frontend/src/app/core/testing/transloco-testing.spec.ts @@ -0,0 +1,33 @@ +import {TranslocoTestingModule} from '@jsverse/transloco'; +import {describe, expect, it} from 'vitest'; + +import {getTranslocoModule} from './transloco-testing'; + +describe('getTranslocoModule', () => { + it('returns a Transloco testing module wrapper', () => { + const moduleWithProviders = getTranslocoModule(); + + expect(moduleWithProviders.ngModule).toBe(TranslocoTestingModule); + expect(moduleWithProviders.providers?.length ?? 0).toBeGreaterThan(0); + }); + + it('creates a fresh module wrapper when callers provide overrides', () => { + const baseModule = getTranslocoModule(); + const customModule = getTranslocoModule({ + langs: { + fr: { + custom: { + greeting: 'Bonjour', + } + }, + }, + translocoConfig: { + availableLangs: ['en', 'fr'], + defaultLang: 'fr', + }, + }); + + expect(customModule.ngModule).toBe(TranslocoTestingModule); + expect(customModule).not.toBe(baseModule); + }); +}); diff --git a/frontend/src/app/features/author-browser/components/author-browser/author-browser.component.spec.ts b/frontend/src/app/features/author-browser/components/author-browser/author-browser.component.spec.ts new file mode 100644 index 000000000..d4ffcb0e5 --- /dev/null +++ b/frontend/src/app/features/author-browser/components/author-browser/author-browser.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around signal/effect synchronization, +// virtual-scroller behavior, router/route query-param state, and cross-service selection logic so +// author browsing can be tested without a full browser shell harness. +describe.skip('AuthorBrowserComponent', () => { + it('needs state-sync seams to verify author enrichment, filtering, sorting, and active-filter counting', () => { + // TODO(seam): Cover enrichAuthors, applyFilters, and applySort once the reactive service graph is isolated for deterministic assertions. + }); + + it('needs browser-shell seams to verify selection, scroll restoration, route state, and thumbnail cache-busting behavior', () => { + // TODO(seam): Cover the virtual-scroller and router orchestration after extracting those concerns behind testable adapters. + }); +}); diff --git a/frontend/src/app/features/author-browser/components/author-card/author-card.component.spec.ts b/frontend/src/app/features/author-browser/components/author-card/author-card.component.spec.ts new file mode 100644 index 000000000..b0291f79a --- /dev/null +++ b/frontend/src/app/features/author-browser/components/author-card/author-card.component.spec.ts @@ -0,0 +1,283 @@ +import {ChangeDetectorRef, SimpleChange} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {TranslocoService} from '@jsverse/transloco'; +import {MessageService} from 'primeng/api'; +import {Subject, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import type {AuthorDetails, AuthorSummary} from '../../model/author.model'; +import {AuthorService} from '../../service/author.service'; +import {AuthorCardComponent} from './author-card.component'; + +describe('AuthorCardComponent', () => { + let getAuthorThumbnailUrl: ReturnType; + let quickMatchAuthor: ReturnType; + let messageService: Pick; + let translate: ReturnType; + let markForCheck: ReturnType; + + const baseAuthor: AuthorSummary = { + id: 9, + name: 'Ada Lovelace', + asin: 'B00ADA', + bookCount: 12, + hasPhoto: true, + }; + + const createComponent = (overrides?: { + author?: Partial; + canQuickMatch?: boolean; + canDelete?: boolean; + isSelected?: boolean; + index?: number; + cacheBuster?: number; + }) => { + const component = TestBed.runInInjectionContext(() => new AuthorCardComponent()); + component.author = { + ...baseAuthor, + ...overrides?.author, + }; + component.canQuickMatch = overrides?.canQuickMatch ?? false; + component.canDelete = overrides?.canDelete ?? false; + component.isSelected = overrides?.isSelected ?? false; + component.index = overrides?.index ?? 0; + component.cacheBuster = overrides?.cacheBuster ?? 0; + return component; + }; + + beforeEach(() => { + getAuthorThumbnailUrl = vi.fn((authorId: number, cacheBuster?: number) => `/authors/${authorId}/thumbnail?t=${cacheBuster ?? 'none'}`); + quickMatchAuthor = vi.fn(); + messageService = { + add: vi.fn(), + }; + translate = vi.fn((key: string) => key); + markForCheck = vi.fn(); + + TestBed.configureTestingModule({ + providers: [ + { + provide: AuthorService, + useValue: { + getAuthorThumbnailUrl, + quickMatchAuthor, + }, + }, + { + provide: MessageService, + useValue: messageService, + }, + { + provide: TranslocoService, + useValue: { + translate, + }, + }, + { + provide: ChangeDetectorRef, + useValue: { + markForCheck, + }, + }, + ], + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('resets photo state only for meaningful author changes and later cache busters', () => { + const component = createComponent(); + + component.hasPhoto = false; + component.ngOnChanges({ + author: new SimpleChange(baseAuthor, {...baseAuthor, name: 'Augusta Ada'}, false), + }); + + expect(component.hasPhoto).toBe(false); + + component.ngOnChanges({ + author: new SimpleChange(baseAuthor, {...baseAuthor, asin: 'B00NEW', hasPhoto: false}, false), + }); + + expect(component.hasPhoto).toBe(false); + + component.hasPhoto = false; + component.ngOnChanges({ + cacheBuster: new SimpleChange(0, 1, false), + }); + + expect(component.hasPhoto).toBe(true); + }); + + it('short-circuits clicks that start inside the menu button container', () => { + const component = createComponent(); + const emitSpy = vi.spyOn(component.cardClick, 'emit'); + + const menuContainer = document.createElement('div'); + menuContainer.className = 'menu-button-container'; + const button = document.createElement('button'); + menuContainer.appendChild(button); + + const event = new Event('click'); + const stopPropagationSpy = vi.spyOn(event, 'stopPropagation'); + Object.defineProperty(event, 'target', { + configurable: true, + value: button, + }); + + component.onCardClick(event); + + expect(stopPropagationSpy).not.toHaveBeenCalled(); + expect(emitSpy).not.toHaveBeenCalled(); + }); + + it('treats modifier clicks as selection toggles instead of opening the author', () => { + const component = createComponent({isSelected: false, index: 3}); + const checkboxEmitSpy = vi.spyOn(component.checkboxClick, 'emit'); + const cardEmitSpy = vi.spyOn(component.cardClick, 'emit'); + + const target = document.createElement('div'); + const event = new MouseEvent('click', {ctrlKey: true}); + const preventDefaultSpy = vi.spyOn(event, 'preventDefault'); + const stopPropagationSpy = vi.spyOn(event, 'stopPropagation'); + Object.defineProperty(event, 'target', { + configurable: true, + value: target, + }); + + component.onCardClick(event); + + expect(preventDefaultSpy).toHaveBeenCalledOnce(); + expect(stopPropagationSpy).toHaveBeenCalledOnce(); + expect(cardEmitSpy).not.toHaveBeenCalled(); + expect(checkboxEmitSpy).toHaveBeenCalledWith({ + index: 3, + author: component.author, + selected: true, + shiftKey: false, + }); + }); + + it('emits cardClick for normal clicks outside the menu controls', () => { + const component = createComponent(); + const emitSpy = vi.spyOn(component.cardClick, 'emit'); + + const event = new Event('click'); + const stopPropagationSpy = vi.spyOn(event, 'stopPropagation'); + Object.defineProperty(event, 'target', { + configurable: true, + value: document.createElement('div'), + }); + + component.onCardClick(event); + + expect(stopPropagationSpy).toHaveBeenCalledOnce(); + expect(emitSpy).toHaveBeenCalledWith(component.author); + }); + + it('captures shift state from checkbox clicks and reuses it for selection events', () => { + const component = createComponent({index: 5}); + const emitSpy = vi.spyOn(component.checkboxClick, 'emit'); + + const mouseEvent = new MouseEvent('click', {shiftKey: true}); + const stopPropagationSpy = vi.spyOn(mouseEvent, 'stopPropagation'); + + component.captureMouseEvent(mouseEvent); + component.toggleSelection({checked: true} as never); + + expect(stopPropagationSpy).toHaveBeenCalledOnce(); + expect(emitSpy).toHaveBeenCalledWith({ + index: 5, + author: component.author, + selected: true, + shiftKey: true, + }); + }); + + it('lazily initializes the menu once, marks for check, and toggles the Prime menu each time', () => { + const component = createComponent({canQuickMatch: true, canDelete: true}); + const menu = { + toggle: vi.fn(), + }; + const event = new Event('click'); + + component.onMenuToggle(event, menu as never); + component.onMenuToggle(event, menu as never); + + expect(markForCheck).toHaveBeenCalledOnce(); + expect(menu.toggle).toHaveBeenCalledTimes(2); + expect(component.items.map(item => item.label)).toEqual([ + 'authorBrowser.card.menu.viewAuthor', + 'authorBrowser.card.menu.editAuthor', + 'authorBrowser.card.menu.quickMatch', + 'authorBrowser.card.menu.deleteAuthor', + ]); + }); + + it('quick-matches through the lazy menu command and reports success state', () => { + const quickMatch$ = new Subject(); + quickMatchAuthor.mockReturnValue(quickMatch$); + + const component = createComponent({canQuickMatch: true}); + const emitSpy = vi.spyOn(component.quickMatched, 'emit'); + + component.onMenuToggle(new Event('click'), {toggle: vi.fn()} as never); + const quickMatchItem = component.items.find(item => item.label === 'authorBrowser.card.menu.quickMatch'); + + quickMatchItem?.command?.({originalEvent: new Event('click'), item: quickMatchItem}); + + expect(quickMatchAuthor).toHaveBeenCalledWith(9); + expect(component.quickMatching).toBe(true); + + quickMatch$.next({ + id: 9, + name: 'Ada Lovelace', + asin: 'B00MATCH', + nameLocked: false, + descriptionLocked: false, + asinLocked: true, + photoLocked: false, + }); + quickMatch$.complete(); + + expect(component.quickMatching).toBe(false); + expect(component.author).toEqual({ + ...baseAuthor, + asin: 'B00MATCH', + hasPhoto: true, + }); + expect(component.hasPhoto).toBe(true); + expect(emitSpy).toHaveBeenCalledWith(component.author); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'authorBrowser.toast.quickMatchSuccessSummary', + detail: 'authorBrowser.toast.quickMatchSuccessDetail', + }); + + component.onMenuToggle(new Event('click'), {toggle: vi.fn()} as never); + expect(markForCheck).toHaveBeenCalledTimes(2); + }); + + it('clears quickMatching and reports an error toast when quick match fails', () => { + quickMatchAuthor.mockReturnValue(throwError(() => new Error('boom'))); + + const component = createComponent({canQuickMatch: true}); + const emitSpy = vi.spyOn(component.quickMatched, 'emit'); + + component.onMenuToggle(new Event('click'), {toggle: vi.fn()} as never); + const quickMatchItem = component.items.find(item => item.label === 'authorBrowser.card.menu.quickMatch'); + + quickMatchItem?.command?.({originalEvent: new Event('click'), item: quickMatchItem}); + + expect(component.quickMatching).toBe(false); + expect(emitSpy).not.toHaveBeenCalled(); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'authorBrowser.toast.quickMatchFailedSummary', + detail: 'authorBrowser.toast.quickMatchFailedDetail', + }); + }); +}); diff --git a/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.spec.ts b/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.spec.ts new file mode 100644 index 000000000..1a9c71257 --- /dev/null +++ b/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.spec.ts @@ -0,0 +1,307 @@ +import {ElementRef, signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {TranslocoService} from '@jsverse/transloco'; +import {MessageService} from 'primeng/api'; +import {ActivatedRoute, convertToParamMap, Router} from '@angular/router'; +import {Subject, of, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {BookService} from '../../../book/service/book.service'; +import {BookCardOverlayPreferenceService} from '../../../book/components/book-browser/book-card-overlay-preference.service'; +import {CoverScalePreferenceService} from '../../../book/components/book-browser/cover-scale-preference.service'; +import {UserService} from '../../../settings/user-management/user.service'; +import type {AuthorDetails} from '../../model/author.model'; +import {AuthorService} from '../../service/author.service'; +import {PageTitleService} from '../../../../shared/service/page-title.service'; +import {AuthorDetailComponent} from './author-detail.component'; + +describe('AuthorDetailComponent', () => { + let getAuthorDetails: ReturnType; + let getAuthorPhotoUrl: ReturnType; + let patchAuthorInCache: ReturnType; + let quickMatchAuthor: ReturnType; + let getCurrentUser: ReturnType; + let setPageTitle: ReturnType; + let translate: ReturnType; + let messageService: Pick; + let route: { + snapshot: { + paramMap: ReturnType; + queryParamMap: ReturnType; + }; + }; + + const baseAuthor: AuthorDetails = { + id: 9, + name: 'Ada Lovelace', + description: 'Analytical engine pioneer', + asin: 'B00ADA', + nameLocked: false, + descriptionLocked: false, + asinLocked: false, + photoLocked: false, + }; + + const setRouteState = (authorId = 9, tab?: string) => { + route.snapshot.paramMap = convertToParamMap({authorId: String(authorId)}); + route.snapshot.queryParamMap = convertToParamMap(tab ? {tab} : {}); + }; + + const createComponent = () => TestBed.runInInjectionContext(() => new AuthorDetailComponent()); + + beforeEach(() => { + getAuthorDetails = vi.fn(); + getAuthorPhotoUrl = vi.fn((authorId: number) => `/api/authors/${authorId}/photo`); + patchAuthorInCache = vi.fn(); + quickMatchAuthor = vi.fn(); + getCurrentUser = vi.fn(() => null); + setPageTitle = vi.fn(); + translate = vi.fn((key: string) => key); + messageService = { + add: vi.fn(), + }; + route = { + snapshot: { + paramMap: convertToParamMap({authorId: '9'}), + queryParamMap: convertToParamMap({}), + }, + }; + + TestBed.configureTestingModule({ + providers: [ + { + provide: ActivatedRoute, + useValue: route, + }, + { + provide: Router, + useValue: {}, + }, + { + provide: AuthorService, + useValue: { + getAuthorDetails, + getAuthorPhotoUrl, + patchAuthorInCache, + quickMatchAuthor, + }, + }, + { + provide: BookService, + useValue: { + books: signal([]), + }, + }, + { + provide: MessageService, + useValue: messageService, + }, + { + provide: CoverScalePreferenceService, + useValue: { + currentCardSize: vi.fn(() => 'medium'), + gridColumnMinWidth: vi.fn(() => '12rem'), + }, + }, + { + provide: BookCardOverlayPreferenceService, + useValue: {}, + }, + { + provide: UserService, + useValue: { + getCurrentUser, + }, + }, + { + provide: PageTitleService, + useValue: { + setPageTitle, + }, + }, + { + provide: TranslocoService, + useValue: { + translate, + }, + }, + ], + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('loads the author from the route, honors the tab query param, and updates page title on success', () => { + setRouteState(42, 'series'); + getAuthorDetails.mockReturnValue(of({...baseAuthor, id: 42, name: 'Grace Hopper'})); + + const component = createComponent(); + + component.ngOnInit(); + + expect(getAuthorDetails).toHaveBeenCalledWith(42); + expect(component.tab).toBe('series'); + expect(component.loading).toBe(false); + expect(component.author()).toEqual({...baseAuthor, id: 42, name: 'Grace Hopper'}); + expect(setPageTitle).toHaveBeenCalledWith('Grace Hopper'); + }); + + it('keeps the default tab and clears loading when author load fails', () => { + setRouteState(9); + getAuthorDetails.mockReturnValue(throwError(() => new Error('load failed'))); + + const component = createComponent(); + + component.ngOnInit(); + + expect(component.tab).toBe('books'); + expect(component.loading).toBe(false); + expect(component.author()).toBeNull(); + expect(setPageTitle).not.toHaveBeenCalled(); + }); + + it('derives photoUrl from the loaded author state and gates canEditMetadata from user permissions', () => { + const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(321); + const component = createComponent(); + + expect(component.photoUrl).toBe(''); + expect(component.canEditMetadata).toBe(false); + + component.onAuthorUpdated(baseAuthor); + + expect(nowSpy).toHaveBeenCalled(); + expect(component.photoUrl).toBe('/api/authors/9/photo&t=321'); + + getCurrentUser.mockReturnValue({permissions: {admin: false, canEditMetadata: true}}); + expect(component.canEditMetadata).toBe(true); + + getCurrentUser.mockReturnValue({permissions: {admin: true, canEditMetadata: false}}); + expect(component.canEditMetadata).toBe(true); + }); + + it('detects description overflow from the assigned element ref only while collapsed', () => { + const component = createComponent(); + + component.descriptionContentRef = { + nativeElement: { + scrollHeight: 120, + clientHeight: 60, + }, + } as unknown as ElementRef; + + component.ngAfterViewChecked(); + + expect(component.isOverflowing).toBe(true); + + component.isExpanded = true; + component.descriptionContentRef = { + nativeElement: { + scrollHeight: 20, + clientHeight: 80, + }, + } as unknown as ElementRef; + + component.ngAfterViewChecked(); + + expect(component.isOverflowing).toBe(true); + }); + + it('patches the cached author summary and refreshes photo state when the author is updated', () => { + const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(777); + const component = createComponent(); + + component.hasPhoto = false; + component.photoTimestamp = 10; + + component.onAuthorUpdated({ + ...baseAuthor, + asin: 'B00UPDATED', + }); + + expect(component.author()).toEqual({ + ...baseAuthor, + asin: 'B00UPDATED', + }); + expect(component.hasPhoto).toBe(true); + expect(component.photoTimestamp).toBe(777); + expect(patchAuthorInCache).toHaveBeenCalledWith(9, { + name: 'Ada Lovelace', + asin: 'B00UPDATED', + hasPhoto: true, + }); + expect(nowSpy).toHaveBeenCalled(); + }); + + it('guards quickMatch when there is no author loaded or a match is already in flight', () => { + const component = createComponent(); + + component.quickMatch(); + expect(quickMatchAuthor).not.toHaveBeenCalled(); + + component.onAuthorUpdated(baseAuthor); + vi.clearAllMocks(); + component.quickMatching = true; + + component.quickMatch(); + + expect(quickMatchAuthor).not.toHaveBeenCalled(); + }); + + it('quick-matches the loaded author, patches state, and reports a translated success toast', () => { + const quickMatch$ = new Subject(); + const matchedAuthor: AuthorDetails = { + ...baseAuthor, + asin: 'B00MATCH', + }; + quickMatchAuthor.mockReturnValue(quickMatch$); + + const component = createComponent(); + component.onAuthorUpdated(baseAuthor); + vi.clearAllMocks(); + + component.quickMatch(); + + expect(quickMatchAuthor).toHaveBeenCalledWith(9); + expect(component.quickMatching).toBe(true); + + quickMatch$.next(matchedAuthor); + quickMatch$.complete(); + + expect(component.quickMatching).toBe(false); + expect(component.author()).toEqual(matchedAuthor); + expect(patchAuthorInCache).toHaveBeenCalledWith(9, { + name: 'Ada Lovelace', + asin: 'B00MATCH', + hasPhoto: true, + }); + expect(translate).toHaveBeenCalledWith('authorBrowser.toast.quickMatchSuccessSummary'); + expect(translate).toHaveBeenCalledWith('authorBrowser.toast.quickMatchSuccessDetail'); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'authorBrowser.toast.quickMatchSuccessSummary', + detail: 'authorBrowser.toast.quickMatchSuccessDetail', + }); + }); + + it('clears the in-flight quick-match flag and reports a translated error toast on failure', () => { + quickMatchAuthor.mockReturnValue(throwError(() => new Error('quick match failed'))); + + const component = createComponent(); + component.onAuthorUpdated(baseAuthor); + vi.clearAllMocks(); + + component.quickMatch(); + + expect(component.quickMatching).toBe(false); + expect(translate).toHaveBeenCalledWith('authorBrowser.toast.quickMatchFailedSummary'); + expect(translate).toHaveBeenCalledWith('authorBrowser.toast.quickMatchFailedDetail'); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'authorBrowser.toast.quickMatchFailedSummary', + detail: 'authorBrowser.toast.quickMatchFailedDetail', + }); + }); +}); diff --git a/frontend/src/app/features/author-browser/components/author-editor/author-editor.component.spec.ts b/frontend/src/app/features/author-browser/components/author-editor/author-editor.component.spec.ts new file mode 100644 index 000000000..7fea59991 --- /dev/null +++ b/frontend/src/app/features/author-browser/components/author-editor/author-editor.component.spec.ts @@ -0,0 +1,257 @@ +import {SimpleChange} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {TranslocoService} from '@jsverse/transloco'; +import {MessageService} from 'primeng/api'; +import {DialogService} from 'primeng/dynamicdialog'; +import {Subject, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import type {AuthorDetails} from '../../model/author.model'; +import {AuthorService} from '../../service/author.service'; +import {AuthorPhotoSearchComponent} from '../author-photo-search/author-photo-search.component'; +import {AuthorEditorComponent} from './author-editor.component'; + +describe('AuthorEditorComponent', () => { + let updateAuthor: ReturnType; + let dialogOpen: ReturnType; + let dialogClose$: Subject; + let messageService: Pick; + let translate: ReturnType; + + const baseAuthor: AuthorDetails = { + id: 9, + name: 'Ada Lovelace', + description: 'Analytical engine pioneer', + asin: 'B00ADA', + nameLocked: false, + descriptionLocked: false, + asinLocked: false, + photoLocked: false, + }; + + const createComponent = (overrides?: {authorId?: number; author?: Partial}) => { + const component = TestBed.runInInjectionContext(() => new AuthorEditorComponent()); + component.authorId = overrides?.authorId ?? 9; + component.author = { + ...baseAuthor, + ...overrides?.author, + }; + return component; + }; + + beforeEach(() => { + updateAuthor = vi.fn(); + dialogClose$ = new Subject(); + dialogOpen = vi.fn(() => ({onClose: dialogClose$})); + messageService = { + add: vi.fn(), + }; + translate = vi.fn((key: string) => key); + + TestBed.configureTestingModule({ + providers: [ + { + provide: AuthorService, + useValue: { + updateAuthor, + getAuthorPhotoUrl: vi.fn((authorId: number) => `/api/authors/${authorId}/photo`), + getUploadAuthorPhotoUrl: vi.fn((authorId: number) => `/api/authors/${authorId}/photo/upload`), + }, + }, + { + provide: MessageService, + useValue: messageService, + }, + { + provide: DialogService, + useValue: { + open: dialogOpen, + }, + }, + { + provide: TranslocoService, + useValue: { + translate, + }, + }, + ], + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('initializes the form and disables controls whose lock flags start enabled', () => { + const component = createComponent({ + author: { + nameLocked: true, + asinLocked: true, + }, + }); + + component.ngOnInit(); + + expect(component.form.get('name')?.value).toBe('Ada Lovelace'); + expect(component.form.get('description')?.value).toBe('Analytical engine pioneer'); + expect(component.form.get('asin')?.value).toBe('B00ADA'); + expect(component.form.get('name')?.disabled).toBe(true); + expect(component.form.get('description')?.disabled).toBe(false); + expect(component.form.get('asin')?.disabled).toBe(true); + expect(component.form.get('photoLocked')?.value).toBe(false); + }); + + it('restores photo state when a later author input change arrives', () => { + const component = createComponent(); + const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(777); + + component.hasPhoto = false; + component.photoTimestamp = 10; + component.ngOnChanges({ + author: new SimpleChange(baseAuthor, {...baseAuthor, name: 'Updated Ada'}, false), + }); + + expect(component.hasPhoto).toBe(true); + expect(component.photoTimestamp).toBe(777); + expect(nowSpy).toHaveBeenCalled(); + }); + + it('shapes the save request from raw form values, emits the updated author, and reports success', () => { + const updatedAuthor: AuthorDetails = { + ...baseAuthor, + description: 'Updated description', + asin: 'B00NEW', + nameLocked: true, + asinLocked: true, + photoLocked: true, + }; + const save$ = new Subject(); + updateAuthor.mockReturnValue(save$); + + const component = createComponent(); + const emitSpy = vi.spyOn(component.authorUpdated, 'emit'); + + component.ngOnInit(); + component.form.patchValue({ + name: ' ', + description: ' Updated description ', + asin: ' B00NEW ', + nameLocked: true, + descriptionLocked: false, + asinLocked: true, + photoLocked: true, + }); + + component.onSave(); + + expect(component.isSaving).toBe(true); + expect(updateAuthor).toHaveBeenCalledWith(9, { + name: undefined, + description: 'Updated description', + asin: 'B00NEW', + nameLocked: true, + descriptionLocked: false, + asinLocked: true, + photoLocked: true, + }); + + save$.next(updatedAuthor); + save$.complete(); + + expect(component.isSaving).toBe(false); + expect(emitSpy).toHaveBeenCalledWith(updatedAuthor); + expect(translate).toHaveBeenCalledWith('authorBrowser.editor.toast.successSummary'); + expect(translate).toHaveBeenCalledWith('authorBrowser.editor.toast.successDetail'); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'authorBrowser.editor.toast.successSummary', + detail: 'authorBrowser.editor.toast.successDetail', + }); + }); + + it('clears the saving flag and reports an error toast when saveMetadata fails', () => { + updateAuthor.mockReturnValue(throwError(() => new Error('boom'))); + + const component = createComponent(); + const emitSpy = vi.spyOn(component.authorUpdated, 'emit'); + component.ngOnInit(); + + component.onSave(); + + expect(component.isSaving).toBe(false); + expect(emitSpy).not.toHaveBeenCalled(); + expect(translate).toHaveBeenCalledWith('authorBrowser.editor.toast.errorSummary'); + expect(translate).toHaveBeenCalledWith('authorBrowser.editor.toast.errorDetail'); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'authorBrowser.editor.toast.errorSummary', + detail: 'authorBrowser.editor.toast.errorDetail', + }); + }); + + it('opens the photo search dialog and refreshes photo state when it closes with success', () => { + const component = createComponent({authorId: 42}); + const emitSpy = vi.spyOn(component.authorUpdated, 'emit'); + const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(888); + + component.hasPhoto = false; + component.photoTimestamp = 12; + + component.openPhotoSearch(); + + expect(dialogOpen).toHaveBeenCalledWith(AuthorPhotoSearchComponent, { + data: {authorId: 42, authorName: 'Ada Lovelace'}, + header: 'authorBrowser.editor.searchPhotoTitle', + width: '70vw', + height: '80vh', + modal: true, + closable: true, + dismissableMask: true, + contentStyle: {'overflow': 'hidden', 'padding': '0', 'display': 'flex', 'flex-direction': 'column'}, + }); + + dialogClose$.next(true); + + expect(component.hasPhoto).toBe(true); + expect(component.photoTimestamp).toBe(888); + expect(emitSpy).toHaveBeenCalledWith(component.author); + expect(nowSpy).toHaveBeenCalled(); + }); + + it('marks upload success, refreshes the photo timestamp, and shows a success toast', () => { + const component = createComponent(); + const emitSpy = vi.spyOn(component.authorUpdated, 'emit'); + const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(999); + + component.isUploading = true; + component.hasPhoto = false; + + component.onUpload(); + + expect(component.isUploading).toBe(false); + expect(component.hasPhoto).toBe(true); + expect(component.photoTimestamp).toBe(999); + expect(emitSpy).toHaveBeenCalledWith(component.author); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'authorBrowser.editor.toast.photoUploadedSummary', + detail: 'authorBrowser.editor.toast.photoUploadedDetail', + }); + expect(nowSpy).toHaveBeenCalled(); + }); + + it('clears upload progress and shows an error toast when upload fails', () => { + const component = createComponent(); + component.isUploading = true; + + component.onUploadError(); + + expect(component.isUploading).toBe(false); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'authorBrowser.editor.toast.errorSummary', + detail: 'authorBrowser.editor.toast.photoUploadErrorDetail', + }); + }); +}); diff --git a/frontend/src/app/features/author-browser/components/author-match/author-match.component.spec.ts b/frontend/src/app/features/author-browser/components/author-match/author-match.component.spec.ts new file mode 100644 index 000000000..24685fab1 --- /dev/null +++ b/frontend/src/app/features/author-browser/components/author-match/author-match.component.spec.ts @@ -0,0 +1,206 @@ +import {TestBed} from '@angular/core/testing'; +import {TranslocoService} from '@jsverse/transloco'; +import {MessageService} from 'primeng/api'; +import {Subject, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import type {AuthorDetails, AuthorSearchResult} from '../../model/author.model'; +import {AuthorService} from '../../service/author.service'; +import {AuthorMatchComponent} from './author-match.component'; + +describe('AuthorMatchComponent', () => { + let searchAuthorMetadata: ReturnType; + let matchAuthor: ReturnType; + let messageService: Pick; + let translate: ReturnType; + + const createComponent = (overrides?: {authorId?: number; authorName?: string}) => { + const component = TestBed.runInInjectionContext(() => new AuthorMatchComponent()); + component.authorId = overrides?.authorId ?? 9; + component.authorName = overrides?.authorName ?? 'Ada Lovelace'; + return component; + }; + + beforeEach(() => { + searchAuthorMetadata = vi.fn(); + matchAuthor = vi.fn(); + messageService = { + add: vi.fn(), + }; + translate = vi.fn((key: string) => key); + + TestBed.configureTestingModule({ + providers: [ + { + provide: AuthorService, + useValue: { + searchAuthorMetadata, + matchAuthor, + }, + }, + { + provide: MessageService, + useValue: messageService, + }, + { + provide: TranslocoService, + useValue: { + translate, + }, + }, + ], + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('bootstraps searchQuery from authorName and gates canSearch on trimmed query inputs', () => { + const component = createComponent({authorName: ' Ada Lovelace '}); + + component.ngOnInit(); + + expect(component.searchQuery).toBe(' Ada Lovelace '); + expect(component.canSearch).toBe(true); + + component.searchQuery = ' '; + component.asinQuery = ' '; + expect(component.canSearch).toBe(false); + + component.asinQuery = ' B00TEST '; + expect(component.canSearch).toBe(true); + }); + + it('does not search when both query inputs are blank after trimming', () => { + const component = createComponent(); + component.searchQuery = ' '; + component.asinQuery = ' '; + component.results = [{source: 'seed', asin: 'old', name: 'Existing'}]; + + component.search(); + + expect(searchAuthorMetadata).not.toHaveBeenCalled(); + expect(component.searching).toBe(false); + expect(component.hasSearched).toBe(false); + expect(component.results).toEqual([{source: 'seed', asin: 'old', name: 'Existing'}]); + }); + + it('searches with trimmed values, clears stale results, and stores returned matches', () => { + const results$ = new Subject(); + searchAuthorMetadata.mockReturnValue(results$); + + const component = createComponent(); + component.searchQuery = ' Ada '; + component.asinQuery = ' B00MATCH '; + component.selectedRegion = 'uk'; + component.results = [{source: 'seed', asin: 'old', name: 'Existing'}]; + + component.search(); + + expect(searchAuthorMetadata).toHaveBeenCalledWith(9, 'Ada', 'uk', 'B00MATCH'); + expect(component.searching).toBe(true); + expect(component.hasSearched).toBe(true); + expect(component.results).toEqual([]); + + results$.next([ + {source: 'amazon', asin: 'B00MATCH', name: 'Ada Lovelace'}, + {source: 'amazon', asin: 'B00OTHER', name: 'A. Lovelace'}, + ]); + results$.complete(); + + expect(component.results).toEqual([ + {source: 'amazon', asin: 'B00MATCH', name: 'Ada Lovelace'}, + {source: 'amazon', asin: 'B00OTHER', name: 'A. Lovelace'}, + ]); + expect(component.searching).toBe(false); + }); + + it('reports a translated search failure toast when metadata search errors', () => { + searchAuthorMetadata.mockReturnValue(throwError(() => new Error('boom'))); + + const component = createComponent(); + component.searchQuery = 'Ada'; + + component.search(); + + expect(component.searching).toBe(false); + expect(translate).toHaveBeenCalledWith('authorBrowser.match.toast.searchFailedSummary'); + expect(translate).toHaveBeenCalledWith('authorBrowser.match.toast.searchFailedDetail'); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'authorBrowser.match.toast.searchFailedSummary', + detail: 'authorBrowser.match.toast.searchFailedDetail', + life: 3000, + }); + }); + + it('shapes the match request, emits the updated author, and reports success on matchAuthor', () => { + const updatedAuthor: AuthorDetails = { + id: 9, + name: 'Ada Lovelace', + asin: 'B00MATCH', + nameLocked: false, + descriptionLocked: false, + asinLocked: true, + photoLocked: false, + }; + const match$ = new Subject(); + matchAuthor.mockReturnValue(match$); + + const component = createComponent(); + component.selectedRegion = 'de'; + const emitSpy = vi.spyOn(component.authorMatched, 'emit'); + + component.matchAuthor({ + source: 'amazon', + asin: 'B00MATCH', + name: 'Ada Lovelace', + description: 'Pioneer', + }); + + expect(matchAuthor).toHaveBeenCalledWith(9, { + source: 'amazon', + asin: 'B00MATCH', + region: 'de', + }); + expect(component.matching).toBe(true); + + match$.next(updatedAuthor); + match$.complete(); + + expect(component.matching).toBe(false); + expect(translate).toHaveBeenCalledWith('authorBrowser.match.toast.matchSuccessSummary'); + expect(translate).toHaveBeenCalledWith('authorBrowser.match.toast.matchSuccessDetail'); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'authorBrowser.match.toast.matchSuccessSummary', + detail: 'authorBrowser.match.toast.matchSuccessDetail', + life: 3000, + }); + expect(emitSpy).toHaveBeenCalledWith(updatedAuthor); + }); + + it('reports a translated failure toast when matchAuthor errors', () => { + matchAuthor.mockReturnValue(throwError(() => new Error('nope'))); + + const component = createComponent(); + + component.matchAuthor({ + source: 'amazon', + asin: 'B00FAIL', + name: 'Ada Lovelace', + }); + + expect(component.matching).toBe(false); + expect(translate).toHaveBeenCalledWith('authorBrowser.match.toast.matchFailedSummary'); + expect(translate).toHaveBeenCalledWith('authorBrowser.match.toast.matchFailedDetail'); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'authorBrowser.match.toast.matchFailedSummary', + detail: 'authorBrowser.match.toast.matchFailedDetail', + life: 3000, + }); + }); +}); diff --git a/frontend/src/app/features/author-browser/components/author-photo-search/author-photo-search.component.spec.ts b/frontend/src/app/features/author-browser/components/author-photo-search/author-photo-search.component.spec.ts new file mode 100644 index 000000000..241d9f4aa --- /dev/null +++ b/frontend/src/app/features/author-browser/components/author-photo-search/author-photo-search.component.spec.ts @@ -0,0 +1,99 @@ +import {TestBed} from '@angular/core/testing'; +import {of, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {TranslocoService} from '@jsverse/transloco'; +import type {AuthorPhotoResult} from '../../model/author.model'; +import {AuthorService} from '../../service/author.service'; +import {AuthorPhotoSearchComponent} from './author-photo-search.component'; +import { + createDynamicDialogHarness, + createMessageServiceProvider, + createMessageServiceSpy, +} from '../../../../core/testing/dialog-testing'; + +describe('AuthorPhotoSearchComponent', () => { + let searchAuthorPhotos: ReturnType; + let uploadAuthorPhotoFromUrl: ReturnType; + let dialogHarness: ReturnType>; + let messageService: ReturnType; + + beforeEach(() => { + searchAuthorPhotos = vi.fn(() => of([])); + uploadAuthorPhotoFromUrl = vi.fn(() => of(undefined)); + dialogHarness = createDynamicDialogHarness({authorId: 9, authorName: 'Ada'}); + messageService = createMessageServiceSpy(); + + TestBed.configureTestingModule({ + providers: [ + ...dialogHarness.providers, + { + provide: AuthorService, + useValue: { + searchAuthorPhotos, + uploadAuthorPhotoFromUrl, + }, + }, + createMessageServiceProvider(messageService), + { + provide: TranslocoService, + useValue: { + translate: ((key: string) => key as T) as TranslocoService['translate'], + }, + }, + ], + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('hydrates the initial author query, performs the bootstrap search, and sorts the returned photos', () => { + searchAuthorPhotos.mockReturnValue(of([ + {index: 3, url: 'three', width: 300, height: 400}, + {index: 1, url: 'one', width: 100, height: 200}, + {index: 2, url: 'two', width: 200, height: 300}, + ])); + + const component = TestBed.runInInjectionContext(() => new AuthorPhotoSearchComponent()); + component.ngOnInit(); + + expect(searchAuthorPhotos).toHaveBeenCalledWith(9, 'Ada'); + expect(component.searchForm.value.query).toBe('Ada'); + expect(component.photos.map(photo => photo.index)).toEqual([1, 2, 3]); + expect(component.hasSearched).toBe(true); + expect(component.searching).toBe(false); + }); + + it('clears results when searching fails and resets the form state on clear', () => { + searchAuthorPhotos.mockReturnValue(throwError(() => new Error('boom'))); + + const component = TestBed.runInInjectionContext(() => new AuthorPhotoSearchComponent()); + component.ngOnInit(); + + expect(component.photos).toEqual([]); + expect(component.hasSearched).toBe(true); + + component.onClear(); + + expect(component.searchForm.value.query).toBeNull(); + expect(component.photos).toEqual([]); + expect(component.hasSearched).toBe(false); + }); + + it('uploads a selected photo, reports success, and closes the dialog', () => { + const component = TestBed.runInInjectionContext(() => new AuthorPhotoSearchComponent()); + component.ngOnInit(); + + component.selectAndUploadPhoto({index: 1, url: 'https://example.com/photo.jpg', width: 640, height: 480}); + + expect(uploadAuthorPhotoFromUrl).toHaveBeenCalledWith(9, 'https://example.com/photo.jpg'); + expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'success', + summary: 'authorBrowser.editor.toast.photoUploadedSummary', + })); + expect(dialogHarness.dialogRef.close).toHaveBeenCalledWith(true); + }); +}); diff --git a/frontend/src/app/features/author-browser/model/author.model.spec.ts b/frontend/src/app/features/author-browser/model/author.model.spec.ts new file mode 100644 index 000000000..b408187da --- /dev/null +++ b/frontend/src/app/features/author-browser/model/author.model.spec.ts @@ -0,0 +1,72 @@ +import {describe, expect, expectTypeOf, it} from 'vitest'; + +import { + AuthorDetails, + AuthorFilters, + AuthorMatchRequest, + AuthorSummary, + AuthorUpdateRequest, + DEFAULT_AUTHOR_FILTERS, + EnrichedAuthor +} from './author.model'; + +describe('author.model', () => { + it('provides all-author defaults for author filtering', () => { + expect(DEFAULT_AUTHOR_FILTERS).toEqual({ + matchStatus: 'all', + photoStatus: 'all', + readStatus: 'all', + bookCount: 'all', + library: 'all', + genre: 'all' + } satisfies AuthorFilters); + }); + + it('supports enriched authors extending the summary shape', () => { + const enriched: EnrichedAuthor = { + id: 7, + name: 'Ursula K. Le Guin', + bookCount: 12, + hasPhoto: true, + libraryIds: new Set([1, 2]), + libraryNames: ['Main', 'Archive'], + categories: ['Fantasy', 'Sci-Fi'], + readStatus: 'some-read', + hasSeries: true, + seriesCount: 2, + latestAddedOn: '2026-03-26', + lastReadTime: '2026-03-25T20:15:00Z', + readingProgress: 75, + avgPersonalRating: 4.5 + }; + + expect(enriched.libraryIds.has(2)).toBe(true); + expect(enriched.readStatus).toBe('some-read'); + expectTypeOf(enriched).toMatchTypeOf(); + }); + + it('keeps author request and update payloads structurally typed', () => { + const matchRequest: AuthorMatchRequest = { + source: 'hardcover', + asin: 'B001234', + region: 'US' + }; + const updateRequest: AuthorUpdateRequest = { + name: 'New Name', + descriptionLocked: true + }; + const details: AuthorDetails = { + id: 4, + name: 'Author', + nameLocked: false, + descriptionLocked: true, + asinLocked: false, + photoLocked: false + }; + + expect(matchRequest.region).toBe('US'); + expect(updateRequest.descriptionLocked).toBe(true); + expect(details.nameLocked).toBe(false); + expectTypeOf(updateRequest.name).toEqualTypeOf(); + }); +}); diff --git a/frontend/src/app/features/author-browser/service/author-query-cache.spec.ts b/frontend/src/app/features/author-browser/service/author-query-cache.spec.ts new file mode 100644 index 000000000..bdab805f3 --- /dev/null +++ b/frontend/src/app/features/author-browser/service/author-query-cache.spec.ts @@ -0,0 +1,30 @@ +import {QueryClient} from '@tanstack/angular-query-experimental'; +import {describe, expect, it} from 'vitest'; + +import {AUTHORS_QUERY_KEY} from './author-query-keys'; +import {patchAuthorInCache} from './author-query-cache'; + +describe('patchAuthorInCache', () => { + it('patches the matching author while keeping the rest intact', () => { + const queryClient = new QueryClient(); + queryClient.setQueryData(AUTHORS_QUERY_KEY, [ + {id: 1, name: 'Ada', bookCount: 1, hasPhoto: false}, + {id: 2, name: 'Bert', bookCount: 2, hasPhoto: true}, + ]); + + patchAuthorInCache(queryClient, 2, {name: 'Bert Updated', hasPhoto: false}); + + expect(queryClient.getQueryData(AUTHORS_QUERY_KEY)).toEqual([ + {id: 1, name: 'Ada', bookCount: 1, hasPhoto: false}, + {id: 2, name: 'Bert Updated', bookCount: 2, hasPhoto: false}, + ]); + }); + + it('initializes an empty cache when there is no existing author list', () => { + const queryClient = new QueryClient(); + + patchAuthorInCache(queryClient, 3, {name: 'Cy'}); + + expect(queryClient.getQueryData(AUTHORS_QUERY_KEY)).toEqual([]); + }); +}); diff --git a/frontend/src/app/features/author-browser/service/author-query-keys.spec.ts b/frontend/src/app/features/author-browser/service/author-query-keys.spec.ts new file mode 100644 index 000000000..a0f369f0f --- /dev/null +++ b/frontend/src/app/features/author-browser/service/author-query-keys.spec.ts @@ -0,0 +1,9 @@ +import {describe, expect, it} from 'vitest'; + +import {AUTHORS_QUERY_KEY} from './author-query-keys'; + +describe('AUTHORS_QUERY_KEY', () => { + it('uses a stable cache key for the author browser', () => { + expect(AUTHORS_QUERY_KEY).toEqual(['authors']); + }); +}); diff --git a/frontend/src/app/features/author-browser/service/author-scale-preference.service.spec.ts b/frontend/src/app/features/author-browser/service/author-scale-preference.service.spec.ts new file mode 100644 index 000000000..6421a82fb --- /dev/null +++ b/frontend/src/app/features/author-browser/service/author-scale-preference.service.spec.ts @@ -0,0 +1,66 @@ +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {LocalStorageService} from '../../../shared/service/local-storage.service'; +import {AuthorScalePreferenceService} from './author-scale-preference.service'; + +describe('AuthorScalePreferenceService', () => { + const localStorageService = { + get: vi.fn(), + set: vi.fn(), + }; + + beforeEach(() => { + vi.useFakeTimers(); + vi.restoreAllMocks(); + localStorageService.get.mockReset(); + localStorageService.set.mockReset(); + localStorageService.get.mockReturnValue(1.5); + + TestBed.configureTestingModule({ + providers: [ + AuthorScalePreferenceService, + {provide: LocalStorageService, useValue: localStorageService}, + ], + }); + }); + + afterEach(() => { + vi.useRealTimers(); + TestBed.resetTestingModule(); + }); + + it('loads the persisted scale and does not persist unchanged values', () => { + const service = TestBed.inject(AuthorScalePreferenceService); + + expect(service.scaleFactor()).toBe(1.5); + + service.setScale(1.5); + vi.runAllTimers(); + + expect(localStorageService.set).not.toHaveBeenCalled(); + }); + + it('debounces and persists the most recent scale value', () => { + const service = TestBed.inject(AuthorScalePreferenceService); + + service.setScale(1.2); + service.setScale(1.4); + + vi.advanceTimersByTime(999); + expect(localStorageService.set).not.toHaveBeenCalled(); + + vi.advanceTimersByTime(1); + + expect(localStorageService.set).toHaveBeenCalledOnce(); + expect(localStorageService.set).toHaveBeenCalledWith('authorScalePreference', 1.4); + }); + + it('falls back to the default scale when storage contains an invalid value', () => { + localStorageService.get.mockReturnValue(Number.NaN); + + const service = TestBed.inject(AuthorScalePreferenceService); + + expect(service.scaleFactor()).toBe(1); + }); +}); diff --git a/frontend/src/app/features/author-browser/service/author-selection.service.spec.ts b/frontend/src/app/features/author-browser/service/author-selection.service.spec.ts new file mode 100644 index 000000000..4ca1f9a34 --- /dev/null +++ b/frontend/src/app/features/author-browser/service/author-selection.service.spec.ts @@ -0,0 +1,78 @@ +import {describe, expect, it} from 'vitest'; + +import {AuthorSelectionService} from './author-selection.service'; + +describe('AuthorSelectionService', () => { + const authors = [ + {id: 1, name: 'Ada', bookCount: 1, hasPhoto: false}, + {id: 2, name: 'Bert', bookCount: 2, hasPhoto: true}, + {id: 3, name: 'Cy', bookCount: 3, hasPhoto: false}, + {id: 4, name: 'Dee', bookCount: 4, hasPhoto: true}, + ]; + + it('selects and deselects authors and exposes the selected count', () => { + const service = new AuthorSelectionService(); + service.setCurrentAuthors(authors); + + service.handleCheckboxClick({ + index: 1, + author: authors[1], + selected: true, + shiftKey: false, + }); + + expect(service.getSelectedIds()).toEqual([2]); + expect(service.selectedCount()).toBe(1); + + service.handleCheckboxClick({ + index: 1, + author: authors[1], + selected: false, + shiftKey: false, + }); + + expect(service.getSelectedIds()).toEqual([]); + expect(service.selectedCount()).toBe(0); + }); + + it('supports shift-click range selection and deselection', () => { + const service = new AuthorSelectionService(); + service.setCurrentAuthors(authors); + + service.handleCheckboxClick({ + index: 1, + author: authors[1], + selected: true, + shiftKey: false, + }); + service.handleCheckboxClick({ + index: 3, + author: authors[3], + selected: true, + shiftKey: true, + }); + + expect(service.getSelectedIds()).toEqual([2, 3, 4]); + + service.handleCheckboxClick({ + index: 2, + author: authors[2], + selected: false, + shiftKey: true, + }); + + expect(service.getSelectedIds()).toEqual([4]); + }); + + it('selects and clears the full current author list', () => { + const service = new AuthorSelectionService(); + service.setCurrentAuthors(authors); + + service.selectAll(); + expect(service.getSelectedIds()).toEqual([1, 2, 3, 4]); + + service.deselectAll(); + expect(service.getSelectedIds()).toEqual([]); + expect(service.selectedCount()).toBe(0); + }); +}); diff --git a/frontend/src/app/features/author-browser/service/author.service.spec.ts b/frontend/src/app/features/author-browser/service/author.service.spec.ts new file mode 100644 index 000000000..29cff00bf --- /dev/null +++ b/frontend/src/app/features/author-browser/service/author.service.spec.ts @@ -0,0 +1,145 @@ +import {HttpClient} from '@angular/common/http'; +import {TestBed} from '@angular/core/testing'; +import {QueryClient} from '@tanstack/angular-query-experimental'; +import {SseClient} from 'ngx-sse-client'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {of} from 'rxjs'; + +import {API_CONFIG} from '../../../core/config/api-config'; +import {AuthService} from '../../../shared/service/auth.service'; +import {AuthorService} from './author.service'; + +describe('AuthorService', () => { + const httpClient = { + get: vi.fn(), + post: vi.fn(), + put: vi.fn(), + delete: vi.fn(), + }; + + const authService = { + token: vi.fn(), + getInternalAccessToken: vi.fn(), + }; + + const sseClient = { + stream: vi.fn(), + }; + + const queryClient = { + removeQueries: vi.fn(), + invalidateQueries: vi.fn(), + }; + + let service: AuthorService; + + beforeEach(() => { + httpClient.get.mockReset(); + httpClient.post.mockReset(); + httpClient.put.mockReset(); + httpClient.delete.mockReset(); + authService.token.mockReset(); + authService.getInternalAccessToken.mockReset(); + sseClient.stream.mockReset(); + queryClient.removeQueries.mockReset(); + queryClient.invalidateQueries.mockReset(); + + authService.token.mockReturnValue('token-123'); + authService.getInternalAccessToken.mockReturnValue('token-123'); + httpClient.get.mockReturnValue(of([])); + httpClient.post.mockReturnValue(of({})); + httpClient.put.mockReturnValue(of({})); + httpClient.delete.mockReturnValue(of(undefined)); + sseClient.stream.mockReturnValue(of({type: 'message', data: '{"id":7,"name":"Ada"}'})); + + TestBed.configureTestingModule({ + providers: [ + AuthorService, + {provide: HttpClient, useValue: httpClient}, + {provide: AuthService, useValue: authService}, + {provide: SseClient, useValue: sseClient}, + {provide: QueryClient, useValue: queryClient}, + ], + }); + + service = TestBed.inject(AuthorService); + }); + + afterEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + it('builds metadata search params with q or asin depending on the request', () => { + service.searchAuthorMetadata(9, 'Ada', 'us'); + + expect(httpClient.get).toHaveBeenCalledWith( + `${API_CONFIG.BASE_URL}/api/v1/authors/9/search-metadata`, + {params: {region: 'us', q: 'Ada'}}, + ); + + service.searchAuthorMetadata(9, 'Ada', 'us', 'B000123'); + + expect(httpClient.get).toHaveBeenCalledWith( + `${API_CONFIG.BASE_URL}/api/v1/authors/9/search-metadata`, + {params: {region: 'us', asin: 'B000123'}}, + ); + }); + + it('uses the default region for quick matches and preserves custom regions', () => { + service.quickMatchAuthor(11); + service.quickMatchAuthor(11, 'gb'); + + expect(httpClient.post).toHaveBeenNthCalledWith( + 1, + `${API_CONFIG.BASE_URL}/api/v1/authors/11/quick-match`, + null, + {params: {region: 'us'}}, + ); + expect(httpClient.post).toHaveBeenNthCalledWith( + 2, + `${API_CONFIG.BASE_URL}/api/v1/authors/11/quick-match`, + null, + {params: {region: 'gb'}}, + ); + }); + + it('maps SSE auto-match responses and throws on error events', () => { + sseClient.stream.mockReturnValueOnce(of({type: 'message', data: '{"id":3,"name":"Grace"}'})); + + const results: unknown[] = []; + service.autoMatchAuthors([1, 2]).subscribe(value => results.push(value)); + + expect(sseClient.stream).toHaveBeenCalledWith( + `${API_CONFIG.BASE_URL}/api/v1/authors/auto-match`, + expect.objectContaining({keepAlive: false, reconnectionDelay: 1000, responseType: 'event'}), + expect.objectContaining({ + body: [1, 2], + withCredentials: true, + }), + 'POST', + ); + expect(results).toEqual([{id: 3, name: 'Grace'}]); + + sseClient.stream.mockReturnValueOnce(of({type: 'error', message: 'boom'})); + + const errors: Error[] = []; + service.autoMatchAuthors([7]).subscribe({ + next: () => undefined, + error: error => errors.push(error), + }); + + expect(errors).toHaveLength(1); + expect(errors[0]).toEqual(new Error('boom')); + }); + + it('builds tokenized author media urls with and without cache busters', () => { + expect(service.getAuthorPhotoUrl(5)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/author/5/photo?token=token-123`); + expect(service.getAuthorThumbnailUrl(5)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/author/5/thumbnail?token=token-123`); + expect(service.getAuthorThumbnailUrl(5, 99)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/author/5/thumbnail?token=token-123&t=99`); + + authService.getInternalAccessToken.mockReturnValue(null); + expect(service.getAuthorPhotoUrl(5)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/author/5/photo`); + expect(service.getAuthorThumbnailUrl(5, 99)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/author/5/thumbnail?t=99`); + }); +}); diff --git a/frontend/src/app/features/book/components/add-physical-book-dialog/add-physical-book-dialog.component.spec.ts b/frontend/src/app/features/book/components/add-physical-book-dialog/add-physical-book-dialog.component.spec.ts new file mode 100644 index 000000000..92829dcb5 --- /dev/null +++ b/frontend/src/app/features/book/components/add-physical-book-dialog/add-physical-book-dialog.component.spec.ts @@ -0,0 +1,320 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import type {AutoCompleteCompleteEvent} from 'primeng/autocomplete'; +import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; +import {Observable, Subject, throwError} from 'rxjs'; +import {afterEach, describe, expect, it, vi} from 'vitest'; + +import {Book, BookMetadata} from '../../model/book.model'; +import {Library} from '../../model/library.model'; +import {BookMetadataService} from '../../service/book-metadata.service'; +import {BookService} from '../../service/book.service'; +import {LibraryService} from '../../service/library.service'; +import {AddPhysicalBookDialogComponent} from './add-physical-book-dialog.component'; + +describe('AddPhysicalBookDialogComponent', () => { + afterEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + function createLibrary(overrides: Partial = {}): Library { + return { + id: 1, + name: 'Main Library', + watch: true, + paths: [], + ...overrides, + }; + } + + function createBook(overrides: Partial = {}): Book { + return { + id: 99, + libraryId: 2, + libraryName: 'Branch Library', + ...overrides, + }; + } + + function createMetadata(overrides: Partial = {}): BookMetadata { + return { + bookId: 0, + ...overrides, + }; + } + + function createHarness(options: { + dialogData?: {libraryId?: number}; + librariesData?: Library[]; + metadataValues?: { + authors: string[]; + categories: string[]; + moods: string[]; + tags: string[]; + publishers: string[]; + series: string[]; + }; + lookupResult$?: Observable; + createResult$?: Observable; + } = {}) { + const libraries = signal(options.librariesData ?? [ + createLibrary({id: 1, name: 'Main Library'}), + createLibrary({id: 2, name: 'Branch Library'}), + ]); + const uniqueMetadata = signal(options.metadataValues ?? { + authors: ['Ursula Le Guin', 'Octavia Butler', 'Robin Hobb'], + categories: ['Science Fiction', 'Epic Fantasy', 'Mystery'], + moods: [], + tags: [], + publishers: [], + series: [], + }); + const lookupResult$ = options.lookupResult$ ?? new Subject(); + const createResult$ = options.createResult$ ?? new Subject(); + const lookupByIsbn = vi.fn(() => lookupResult$); + const createPhysicalBook = vi.fn(() => createResult$); + const dialogRef = {close: vi.fn()}; + + TestBed.configureTestingModule({ + providers: [ + {provide: DynamicDialogConfig, useValue: {data: options.dialogData ?? {}}}, + {provide: DynamicDialogRef, useValue: dialogRef}, + {provide: BookService, useValue: {uniqueMetadata, createPhysicalBook}}, + {provide: BookMetadataService, useValue: {lookupByIsbn}}, + {provide: LibraryService, useValue: {libraries}}, + ], + }); + + const component = TestBed.runInInjectionContext(() => new AddPhysicalBookDialogComponent()); + TestBed.flushEffects(); + + return { + component, + libraries, + uniqueMetadata, + lookupResult$, + createResult$, + lookupByIsbn, + createPhysicalBook, + dialogRef, + }; + } + + function triggerEnter(component: AddPhysicalBookDialogComponent, fieldName: 'authors' | 'categories', value: string): HTMLInputElement { + const input = document.createElement('input'); + input.value = value; + + component.onAutoCompleteKeyUp(fieldName, { + key: 'Enter', + target: input, + } as unknown as KeyboardEvent); + + return input; + } + + function triggerSelect(component: AddPhysicalBookDialogComponent, fieldName: 'authors' | 'categories', value: string): HTMLInputElement { + const input = document.createElement('input'); + input.value = value; + + component.onAutoCompleteSelect(fieldName, { + value, + originalEvent: {target: input} as unknown as Event, + }); + + return input; + } + + it('prefers the dialog library selection when one is provided', () => { + const {component} = createHarness({ + dialogData: {libraryId: 2}, + }); + + expect(component.selectedLibraryId).toBe(2); + }); + + it('defaults to the first available library when the dialog does not provide one', () => { + const {component} = createHarness({ + dialogData: {}, + }); + + expect(component.selectedLibraryId).toBe(1); + }); + + it('filters authors and categories with case-insensitive substring matches', () => { + const {component} = createHarness(); + + component.filterAuthors({query: 'taV', originalEvent: new Event('input')} as AutoCompleteCompleteEvent); + component.filterCategories({query: 'fic', originalEvent: new Event('input')} as AutoCompleteCompleteEvent); + + expect(component.filteredAuthors).toEqual(['Octavia Butler']); + expect(component.filteredCategories).toEqual(['Science Fiction']); + }); + + it('adds entered autocomplete values once and clears the input after Enter', () => { + const {component} = createHarness(); + + const firstInput = triggerEnter(component, 'authors', ' N. K. Jemisin '); + const duplicateInput = triggerEnter(component, 'authors', 'N. K. Jemisin'); + + expect(component.authors).toEqual(['N. K. Jemisin']); + expect(firstInput.value).toBe(''); + expect(duplicateInput.value).toBe(''); + }); + + it('adds selected autocomplete values once and clears the input after selection', () => { + const {component} = createHarness(); + + const firstInput = triggerSelect(component, 'categories', 'Mythic Fantasy'); + const duplicateInput = triggerSelect(component, 'categories', 'Mythic Fantasy'); + + expect(component.categories).toEqual(['Mythic Fantasy']); + expect(firstInput.value).toBe(''); + expect(duplicateInput.value).toBe(''); + }); + + it('trims the isbn, hydrates metadata fields, and clears the fetching flag on success', () => { + const lookupResult$ = new Subject(); + const {component, lookupByIsbn} = createHarness({lookupResult$}); + + component.isbn = ' 9780441172719 '; + component.fetchMetadataByIsbn(); + + expect(lookupByIsbn).toHaveBeenCalledWith('9780441172719'); + expect(component.isFetchingMetadata).toBe(true); + + lookupResult$.next(createMetadata({ + title: 'Dune', + authors: ['Frank Herbert'], + description: 'Arrakis.', + publisher: 'Ace', + publishedDate: '1965', + language: 'en', + pageCount: 412, + categories: ['Science Fiction'], + thumbnailUrl: 'https://covers.example/dune.jpg', + })); + lookupResult$.complete(); + + expect(component.title).toBe('Dune'); + expect(component.authors).toEqual(['Frank Herbert']); + expect(component.description).toBe('Arrakis.'); + expect(component.publisher).toBe('Ace'); + expect(component.publishedDate).toBe('1965'); + expect(component.language).toBe('en'); + expect(component.pageCount).toBe(412); + expect(component.categories).toEqual(['Science Fiction']); + expect(component.coverUrl).toBe('https://covers.example/dune.jpg'); + expect(component.isFetchingMetadata).toBe(false); + }); + + it('does not start isbn lookup for blank or in-flight requests and clears the flag on error', () => { + const {component, lookupByIsbn} = createHarness(); + + component.isbn = ' '; + component.fetchMetadataByIsbn(); + expect(lookupByIsbn).not.toHaveBeenCalled(); + + component.isbn = '9780441172719'; + component.isFetchingMetadata = true; + component.fetchMetadataByIsbn(); + expect(lookupByIsbn).not.toHaveBeenCalled(); + + component.isFetchingMetadata = false; + lookupByIsbn.mockReturnValueOnce(throwError(() => new Error('lookup failed'))); + + component.fetchMetadataByIsbn(); + + expect(lookupByIsbn).toHaveBeenCalledWith('9780441172719'); + expect(component.isFetchingMetadata).toBe(false); + }); + + it('gates creation on required fields and does not submit when already loading', () => { + const {component, createPhysicalBook} = createHarness(); + + expect(component.canCreate()).toBe(false); + component.createBook(); + expect(createPhysicalBook).not.toHaveBeenCalled(); + + component.selectedLibraryId = 2; + component.title = 'Physical Copy'; + expect(component.canCreate()).toBe(true); + + component.isLoading = true; + component.createBook(); + + expect(createPhysicalBook).not.toHaveBeenCalled(); + }); + + it('shapes the create payload, resets loading, and closes with the created book on success', () => { + const createResult$ = new Subject(); + const createdBook = createBook({ + id: 321, + libraryId: 2, + libraryName: 'Branch Library', + metadata: {bookId: 321, title: 'The Left Hand of Darkness'}, + }); + const {component, createPhysicalBook, dialogRef} = createHarness({createResult$}); + + component.selectedLibraryId = 2; + component.title = ' The Left Hand of Darkness '; + component.isbn = ' '; + component.authors = ['Ursula Le Guin']; + component.description = ' '; + component.publisher = ' Ace Books '; + component.publishedDate = ' 1969 '; + component.language = ' en '; + component.pageCount = 304; + component.categories = ['Science Fiction']; + component.coverUrl = 'https://covers.example/left-hand.jpg'; + + component.createBook(); + + expect(component.isLoading).toBe(true); + expect(createPhysicalBook).toHaveBeenCalledWith({ + libraryId: 2, + title: 'The Left Hand of Darkness', + isbn: undefined, + authors: ['Ursula Le Guin'], + description: undefined, + publisher: 'Ace Books', + publishedDate: '1969', + language: 'en', + pageCount: 304, + categories: ['Science Fiction'], + thumbnailUrl: 'https://covers.example/left-hand.jpg', + }); + + createResult$.next(createdBook); + createResult$.complete(); + + expect(component.isLoading).toBe(false); + expect(dialogRef.close).toHaveBeenCalledWith(createdBook); + }); + + it('resets loading and keeps the dialog open when create fails', () => { + const {component, createPhysicalBook, dialogRef} = createHarness(); + createPhysicalBook.mockReturnValueOnce(throwError(() => new Error('create failed'))); + + component.selectedLibraryId = 2; + component.isbn = '9780441172719'; + + component.createBook(); + + expect(createPhysicalBook).toHaveBeenCalledWith({ + libraryId: 2, + title: undefined, + isbn: '9780441172719', + authors: undefined, + description: undefined, + publisher: undefined, + publishedDate: undefined, + language: undefined, + pageCount: undefined, + categories: undefined, + thumbnailUrl: undefined, + }); + expect(component.isLoading).toBe(false); + expect(dialogRef.close).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/app/features/book/components/additional-file-uploader/additional-file-uploader.component.spec.ts b/frontend/src/app/features/book/components/additional-file-uploader/additional-file-uploader.component.spec.ts new file mode 100644 index 000000000..a47a62267 --- /dev/null +++ b/frontend/src/app/features/book/components/additional-file-uploader/additional-file-uploader.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around PrimeNG file-upload callbacks, +// dialog bootstrapping, and upload stream orchestration so single-file validation and upload state +// transitions can be asserted without browser File objects and the live upload widget runtime. +describe.skip('AdditionalFileUploaderComponent', () => { + it('needs upload-widget seams to verify file-type resets, size validation, and file list management', () => { + // TODO(seam): Cover onFileTypeChange, onFilesSelect, onClear, and badge/status helpers after FileUpload callbacks and browser File objects are isolated behind deterministic doubles. + }); + + it('needs upload-service seams to verify upload success, upload failure, and dialog close behavior', () => { + // TODO(seam): Cover uploadFiles and closeDialog after BookFileService streams and dialog refs are exposed through a stable test harness. + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/book-browser-entity.service.spec.ts b/frontend/src/app/features/book/components/book-browser/book-browser-entity.service.spec.ts new file mode 100644 index 000000000..f06c762ba --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/book-browser-entity.service.spec.ts @@ -0,0 +1,149 @@ +import {TestBed} from '@angular/core/testing'; +import {convertToParamMap} from '@angular/router'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; + +import {BookBrowserEntityService} from './book-browser-entity.service'; +import {Book} from '../../model/book.model'; +import {Library} from '../../model/library.model'; +import {Shelf} from '../../model/shelf.model'; +import {EntityType} from './book-browser.component'; +import {LibraryService} from '../../service/library.service'; +import {ShelfService} from '../../service/shelf.service'; +import {MagicShelfService, MagicShelf} from '../../../magic-shelf/service/magic-shelf.service'; +import {BookRuleEvaluatorService} from '../../../magic-shelf/service/book-rule-evaluator.service'; + +function makeBook(id: number, overrides: Partial = {}): Book { + return { + id, + libraryId: 1, + libraryName: 'Library', + metadata: {bookId: id, title: `Book ${id}`}, + ...overrides + }; +} + +describe('BookBrowserEntityService', () => { + let service: BookBrowserEntityService; + let libraryService: {libraries: ReturnType}; + let shelfService: {shelves: ReturnType}; + let magicShelfService: {findShelfById: ReturnType}; + let bookRuleEvaluatorService: {evaluateGroup: ReturnType}; + + const library = { + id: 1, + name: 'Library', + watch: true, + paths: [{path: '/books'}] + } as Library; + const shelf = {id: 2, name: 'Shelf'} as Shelf; + const magicShelf = { + id: 3, + name: 'Magic Shelf', + filterJson: JSON.stringify({group: 'all'}) + } as MagicShelf; + + beforeEach(() => { + libraryService = { + libraries: vi.fn(() => [library]) + }; + shelfService = { + shelves: vi.fn(() => [shelf]) + }; + magicShelfService = { + findShelfById: vi.fn((id: number) => id === 3 ? magicShelf : null) + }; + bookRuleEvaluatorService = { + evaluateGroup: vi.fn((book: Book) => book.id === 2) + }; + + TestBed.configureTestingModule({ + providers: [ + BookBrowserEntityService, + {provide: LibraryService, useValue: libraryService}, + {provide: ShelfService, useValue: shelfService}, + {provide: MagicShelfService, useValue: magicShelfService}, + {provide: BookRuleEvaluatorService, useValue: bookRuleEvaluatorService} + ] + }); + + service = TestBed.inject(BookBrowserEntityService); + }); + + it('resolves entity ids from route params in priority order', () => { + const allParams = convertToParamMap({ + libraryId: '1', + shelfId: '2', + magicShelfId: '3' + }); + const shelfFirstParams = convertToParamMap({ + shelfId: '2', + magicShelfId: '3' + }); + const emptyParams = convertToParamMap({}); + + expect(service.getEntityInfo(allParams)).toEqual({ + entityId: 1, + entityType: EntityType.LIBRARY + }); + expect(service.getEntityInfo(shelfFirstParams)).toEqual({ + entityId: 2, + entityType: EntityType.SHELF + }); + expect(service.getEntityInfo(emptyParams)).toEqual({ + entityId: NaN, + entityType: EntityType.ALL_BOOKS + }); + }); + + it('returns entity records and recognizes library and magic shelf types', () => { + expect(service.getEntity(1, EntityType.LIBRARY)).toBe(library); + expect(service.getEntity(2, EntityType.SHELF)).toBe(shelf); + expect(service.getEntity(3, EntityType.MAGIC_SHELF)).toBe(magicShelf); + expect(service.getEntity(999, EntityType.ALL_BOOKS)).toBeNull(); + + expect(service.isLibrary(library)).toBe(true); + expect(service.isLibrary(shelf as Library | Shelf | MagicShelf)).toBe(false); + expect(service.isMagicShelf(magicShelf)).toBe(true); + expect(service.isMagicShelf(null)).toBe(false); + }); + + it('filters books by entity type and handles magic shelf parsing failures', () => { + const books = [ + makeBook(1, {libraryId: 1, shelves: [{id: 2} as never]}), + makeBook(2, {libraryId: 1, shelves: []}), + makeBook(3, {libraryId: 2, shelves: [{id: 2} as never]}) + ]; + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + + expect(service.getBooksByEntity(books, 1, EntityType.LIBRARY)).toEqual([ + books[0], + books[1] + ]); + expect(service.getBooksByEntity(books, 2, EntityType.SHELF)).toEqual([ + books[0], + books[2] + ]); + expect(service.getBooksByEntity(books, 0, EntityType.UNSHELVED)).toEqual([ + books[1] + ]); + expect(service.getBooksByEntity(books, 0, EntityType.ALL_BOOKS)).toBe(books); + + expect(service.getBooksByEntity(books, 3, EntityType.MAGIC_SHELF)).toEqual([ + books[1] + ]); + expect(bookRuleEvaluatorService.evaluateGroup).toHaveBeenCalledWith( + books[0], + {group: 'all'}, + books + ); + + magicShelfService.findShelfById.mockReturnValueOnce({ + id: 4, + name: 'Broken Magic Shelf', + filterJson: '{broken json' + } as MagicShelf); + + expect(service.getBooksByEntity(books, 4, EntityType.MAGIC_SHELF)).toEqual([]); + expect(warnSpy).toHaveBeenCalledWith('Invalid filterJson for MagicShelf'); + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/book-browser-query-params.service.spec.ts b/frontend/src/app/features/book/components/book-browser/book-browser-query-params.service.spec.ts new file mode 100644 index 000000000..00e18e826 --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/book-browser-query-params.service.spec.ts @@ -0,0 +1,300 @@ +import {TestBed} from '@angular/core/testing'; +import {ActivatedRoute, convertToParamMap, ParamMap, Router} from '@angular/router'; +import {vi, describe, beforeEach, afterEach, expect, it} from 'vitest'; + +import {EntityType} from './book-browser.component'; +import { + BookBrowserQueryParamsService, + QUERY_PARAMS, + VIEW_MODES +} from './book-browser-query-params.service'; +import {SortDirection, SortOption} from '../../model/sort.model'; +import {EntityViewPreferences} from '../../../settings/user-management/user.service'; + +describe('BookBrowserQueryParamsService', () => { + let service: BookBrowserQueryParamsService; + let routerNavigate: ReturnType; + let routeSnapshot: { + queryParams: Record; + queryParamMap: ParamMap; + }; + let activatedRoute: {snapshot: typeof routeSnapshot}; + + const sortOptions: SortOption[] = [ + {label: 'Added On', field: 'addedOn', direction: SortDirection.DESCENDING}, + {label: 'Title', field: 'title', direction: SortDirection.ASCENDING}, + {label: 'Authors', field: 'author', direction: SortDirection.ASCENDING} + ]; + + beforeEach(() => { + routerNavigate = vi.fn(); + routeSnapshot = { + queryParams: {}, + queryParamMap: convertToParamMap({}) + }; + activatedRoute = {snapshot: routeSnapshot}; + + TestBed.configureTestingModule({ + providers: [ + BookBrowserQueryParamsService, + {provide: Router, useValue: {navigate: routerNavigate}}, + {provide: ActivatedRoute, useValue: activatedRoute} + ] + }); + + service = TestBed.inject(BookBrowserQueryParamsService); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('parses explicit query params, filters, and toggle state', () => { + const result = service.parseQueryParams( + convertToParamMap({ + [QUERY_PARAMS.VIEW]: VIEW_MODES.TABLE, + [QUERY_PARAMS.SORT]: 'title:desc,author:asc', + [QUERY_PARAMS.FILTER]: 'tag:fiction|sci%20fi,series:A%3AB', + [QUERY_PARAMS.FMODE]: 'or', + [QUERY_PARAMS.FROM]: 'toggle' + }), + undefined, + undefined, + undefined, + sortOptions, + 'and' + ); + + expect(result).toEqual({ + viewMode: VIEW_MODES.TABLE, + sortOption: {label: 'Title', field: 'title', direction: SortDirection.DESCENDING}, + sortCriteria: [ + {label: 'Title', field: 'title', direction: SortDirection.DESCENDING}, + {label: 'Authors', field: 'author', direction: SortDirection.ASCENDING} + ], + filters: { + tag: ['fiction', 'sci fi'], + series: ['A:B'] + }, + filterMode: 'or', + viewModeFromToggle: true + }); + }); + + it('uses entity overrides, legacy preferences, and default sort fallback', () => { + const userPrefs: EntityViewPreferences = { + global: { + sortKey: 'addedOn', + sortDir: 'ASC', + sortCriteria: [ + {field: 'title', direction: 'DESC'} + ], + view: 'TABLE', + coverSize: 1, + seriesCollapsed: false, + overlayBookType: true + }, + overrides: [ + { + entityType: 'LIBRARY', + entityId: 7, + preferences: { + sortKey: 'authors', + sortDir: 'DESC', + sortCriteria: [ + {field: 'authors', direction: 'DESC'} + ], + view: 'GRID', + coverSize: 1, + seriesCollapsed: false, + overlayBookType: false + } + } + ] + }; + + const overrideResult = service.parseQueryParams( + convertToParamMap({ + [QUERY_PARAMS.FMODE]: 'single' + }), + userPrefs, + EntityType.LIBRARY, + 7, + sortOptions, + 'and' + ); + + expect(overrideResult.viewMode).toBe(VIEW_MODES.GRID); + expect(overrideResult.filterMode).toBe('single'); + expect(overrideResult.sortCriteria).toEqual([ + {label: 'authors', field: 'authors', direction: SortDirection.DESCENDING} + ]); + + const legacyResult = service.parseQueryParams( + convertToParamMap({}), + { + global: { + sortKey: 'title', + sortDir: 'DESC', + view: 'TABLE', + coverSize: 1, + seriesCollapsed: false, + overlayBookType: true + }, + overrides: [] + }, + undefined, + undefined, + sortOptions, + 'and' + ); + + expect(legacyResult.sortOption).toEqual({ + label: 'Title', + field: 'title', + direction: SortDirection.DESCENDING + }); + expect(legacyResult.viewMode).toBe('table'); + + const fallbackResult = service.parseQueryParams( + convertToParamMap({}), + { + global: { + sortKey: 'missing', + sortDir: 'DESC', + view: 'TABLE', + coverSize: 1, + seriesCollapsed: false, + overlayBookType: true + }, + overrides: [] + }, + undefined, + undefined, + sortOptions, + 'and' + ); + + expect(fallbackResult.sortOption).toEqual({ + label: 'Added On', + field: 'addedOn', + direction: SortDirection.DESCENDING + }); + }); + + it('serializes and deserializes sorts and filters while ignoring malformed input', () => { + expect(service.serializeSort([ + {label: 'Title', field: 'title', direction: SortDirection.ASCENDING}, + {label: 'Added On', field: 'addedOn', direction: SortDirection.DESCENDING} + ])).toBe('title:asc,addedOn:desc'); + + expect(service.deserializeSort('title:desc,missing:asc', sortOptions)).toEqual([ + {label: 'Title', field: 'title', direction: SortDirection.DESCENDING} + ]); + + expect(service.serializeFilters({ + tag: ['sci fi', 'new:release'], + series: ['A/B'] + })).toBe('tag:sci%20fi|new%3Arelease,series:A%2FB'); + + expect(service.deserializeFilters('tag:sci%20fi|new%3Arelease,broken,series:A%2FB')).toEqual({ + tag: ['sci fi', 'new:release'], + series: ['A/B'] + }); + }); + + it('updates query params for view mode, sort, filters, and sync changes', () => { + routeSnapshot.queryParams = { + foo: 'bar', + [QUERY_PARAMS.SORT]: 'title:asc', + [QUERY_PARAMS.DIRECTION]: 'desc', + [QUERY_PARAMS.VIEW]: VIEW_MODES.GRID, + [QUERY_PARAMS.FMODE]: 'and', + [QUERY_PARAMS.FILTER]: 'tag:fiction' + }; + routeSnapshot.queryParamMap = convertToParamMap({ + [QUERY_PARAMS.FILTER]: 'tag:fiction' + }); + + service.updateViewMode(VIEW_MODES.TABLE); + expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({ + queryParams: { + [QUERY_PARAMS.VIEW]: VIEW_MODES.TABLE, + [QUERY_PARAMS.FROM]: 'toggle' + }, + queryParamsHandling: 'merge', + replaceUrl: true + })); + + service.updateSort({label: 'Added On', field: 'addedOn', direction: SortDirection.DESCENDING}); + expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({ + queryParams: expect.objectContaining({ + foo: 'bar', + [QUERY_PARAMS.SORT]: 'addedOn:desc', + [QUERY_PARAMS.DIRECTION]: null + }), + replaceUrl: true + })); + + routerNavigate.mockClear(); + routeSnapshot.queryParamMap = convertToParamMap({}); + service.updateFilters(null); + expect(routerNavigate).not.toHaveBeenCalled(); + + routeSnapshot.queryParamMap = convertToParamMap({ + [QUERY_PARAMS.FILTER]: 'tag:fiction' + }); + service.updateFilters({tag: ['fiction', 'sci fi']}); + expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({ + relativeTo: activatedRoute as never, + queryParams: {[QUERY_PARAMS.FILTER]: 'tag:fiction|sci%20fi'}, + queryParamsHandling: 'merge', + replaceUrl: false + })); + + service.updateFilterMode('single', {tag: ['fiction', 'sci fi']}); + expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({ + relativeTo: activatedRoute as never, + queryParams: { + [QUERY_PARAMS.FMODE]: 'single', + [QUERY_PARAMS.FILTER]: null + }, + queryParamsHandling: 'merge', + replaceUrl: false + })); + + service.updateFilterMode('or', {tag: ['fiction']}); + expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({ + relativeTo: activatedRoute as never, + queryParams: { + [QUERY_PARAMS.FMODE]: 'or' + }, + queryParamsHandling: 'merge', + replaceUrl: false + })); + + routerNavigate.mockClear(); + service.syncQueryParams('grid', 'and', {tag: ['fiction']}); + expect(routerNavigate).not.toHaveBeenCalled(); + + service.syncQueryParams('table', 'single', {tag: ['fiction']}); + expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({ + queryParams: { + foo: 'bar', + [QUERY_PARAMS.SORT]: 'title:asc', + [QUERY_PARAMS.DIRECTION]: 'desc', + [QUERY_PARAMS.VIEW]: 'table', + [QUERY_PARAMS.FMODE]: 'single', + [QUERY_PARAMS.FILTER]: 'tag:fiction' + }, + replaceUrl: true + })); + }); + + it('detects when a series filter should force expansion', () => { + expect(service.shouldForceExpandSeries(convertToParamMap({}))).toBe(false); + expect(service.shouldForceExpandSeries(convertToParamMap({ + [QUERY_PARAMS.FILTER]: 'tag:fiction,series:space-opera' + }))).toBe(true); + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/book-browser-scroll.service.spec.ts b/frontend/src/app/features/book/components/book-browser/book-browser-scroll.service.spec.ts new file mode 100644 index 000000000..a6e650486 --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/book-browser-scroll.service.spec.ts @@ -0,0 +1,22 @@ +import {describe, expect, it} from 'vitest'; + +import {BookBrowserScrollService} from './book-browser-scroll.service'; + +describe('BookBrowserScrollService', () => { + const service = new BookBrowserScrollService(); + + it('stores, retrieves, clears, and creates stable keys', () => { + expect(service.getPosition('books')).toBeUndefined(); + + service.savePosition('books', 144); + service.savePosition('books:library', 288); + + expect(service.getPosition('books')).toBe(144); + expect(service.getPosition('books:library')).toBe(288); + expect(service.createKey('/books', {libraryId: '1', shelfId: '2'})).toBe('/books:1-2'); + expect(service.createKey('/books', {})).toBe('/books'); + + service.clearPosition('books'); + expect(service.getPosition('books')).toBeUndefined(); + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/book-browser.component.spec.ts b/frontend/src/app/features/book/components/book-browser/book-browser.component.spec.ts new file mode 100644 index 000000000..4504fedb2 --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/book-browser.component.spec.ts @@ -0,0 +1,10 @@ +import {describe, expect, it} from 'vitest'; + +// TODO(seam): This needs a routed integration harness for the query-backed book browser, +// PrimeNG overlays, and the persisted filter/sidebar preference services before the +// control-flow branches can be exercised without brittle template scaffolding. +describe.skip('BookBrowserComponent', () => { + it('needs a browser-level harness for routed query state, filters, and overlay actions', () => { + expect.hasAssertions(); + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/book-card-overlay-preference.service.spec.ts b/frontend/src/app/features/book/components/book-browser/book-card-overlay-preference.service.spec.ts new file mode 100644 index 000000000..7174b78f8 --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/book-card-overlay-preference.service.spec.ts @@ -0,0 +1,81 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {UserService} from '../../../settings/user-management/user.service'; +import {BookCardOverlayPreferenceService} from './book-card-overlay-preference.service'; + +describe('BookCardOverlayPreferenceService', () => { + let service: BookCardOverlayPreferenceService; + let userService: { + currentUser: unknown; + getCurrentUser: ReturnType; + updateUserSetting: ReturnType; + }; + let user: { + id: number; + userSettings: { + entityViewPreferences: { + global: { + overlayBookType?: boolean; + showBookTypePill?: boolean; + }; + overrides: unknown[]; + }; + }; + }; + + beforeEach(() => { + vi.useFakeTimers(); + + user = { + id: 7, + userSettings: { + entityViewPreferences: { + global: { + overlayBookType: false, + }, + overrides: [], + }, + }, + }; + userService = { + currentUser: signal(user), + getCurrentUser: vi.fn(() => user), + updateUserSetting: vi.fn(), + }; + + TestBed.configureTestingModule({ + providers: [ + BookCardOverlayPreferenceService, + {provide: UserService, useValue: userService}, + ], + }); + + service = TestBed.inject(BookCardOverlayPreferenceService); + }); + + afterEach(() => { + vi.useRealTimers(); + TestBed.resetTestingModule(); + }); + + it('updates the exposed signal immediately when the overlay preference changes', () => { + service.setShowBookTypePill(false); + + expect(service.showBookTypePill()).toBe(false); + }); + + it('persists the updated global overlay preference after the debounce delay', () => { + service.setShowBookTypePill(true); + vi.advanceTimersByTime(500); + + expect(userService.updateUserSetting).toHaveBeenCalledWith( + 7, + 'entityViewPreferences', + expect.objectContaining({ + global: expect.objectContaining({overlayBookType: true}), + }) + ); + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/book-card/book-card.component.spec.ts b/frontend/src/app/features/book/components/book-browser/book-card/book-card.component.spec.ts new file mode 100644 index 000000000..4d0b67379 --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/book-card/book-card.component.spec.ts @@ -0,0 +1,438 @@ +import {NO_ERRORS_SCHEMA, SimpleChange, SimpleChanges} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {Router} from '@angular/router'; +import {QueryClient} from '@tanstack/angular-query-experimental'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {TranslocoService} from '@jsverse/transloco'; +import {ConfirmationService, MessageService} from 'primeng/api'; +import {TaskHelperService} from '../../../../settings/task-management/task-helper.service'; +import {EmailService} from '../../../../settings/email-v2/email.service'; +import {User, UserService} from '../../../../settings/user-management/user.service'; +import {AppSettingsService} from '../../../../../shared/service/app-settings.service'; +import {UrlHelperService} from '../../../../../shared/service/url-helper.service'; +import {AdditionalFile, Book, ReadStatus} from '../../../model/book.model'; +import {BookDialogHelperService} from '../book-dialog-helper.service'; +import {BookCardComponent} from './book-card.component'; +import {BookFileService} from '../../../service/book-file.service'; +import {BookMetadataManageService} from '../../../service/book-metadata-manage.service'; +import {BookNavigationService} from '../../../service/book-navigation.service'; +import {BookService} from '../../../service/book.service'; + +function makeBook(overrides: Partial = {}): Book { + return { + id: 41, + libraryId: 2, + libraryName: 'Library', + metadata: { + bookId: 41, + title: 'Book Title', + seriesName: 'Series Name', + coverUpdatedOn: '2024-01-01', + audiobookCoverUpdatedOn: '2024-01-02', + }, + ...overrides, + }; +} + +function makeUser(metadataCenterViewMode: 'route' | 'dialog'): User { + return { + id: 1, + username: 'tester', + name: 'Tester', + email: 'tester@example.com', + assignedLibraries: [], + permissions: { + admin: false, + canUpload: false, + canDownload: false, + canEmailBook: false, + canDeleteBook: false, + canEditMetadata: false, + canManageLibrary: false, + canManageMetadataConfig: false, + canSyncKoReader: false, + canSyncKobo: false, + canAccessOpds: false, + canAccessBookdrop: false, + canAccessLibraryStats: false, + canAccessUserStats: false, + canAccessTaskManager: false, + canManageEmailConfig: false, + canManageGlobalPreferences: false, + canManageIcons: false, + canManageFonts: false, + demoUser: false, + canBulkAutoFetchMetadata: false, + canBulkCustomFetchMetadata: false, + canBulkEditMetadata: false, + canBulkRegenerateCover: false, + canMoveOrganizeFiles: false, + canBulkLockUnlockMetadata: false, + }, + userSettings: { + metadataCenterViewMode, + perBookSetting: {} as never, + pdfReaderSetting: {} as never, + epubReaderSetting: {} as never, + ebookReaderSetting: {} as never, + cbxReaderSetting: {} as never, + newPdfReaderSetting: {} as never, + sidebarLibrarySorting: {} as never, + sidebarShelfSorting: {} as never, + sidebarMagicShelfSorting: {} as never, + filterMode: 'and', + enableSeriesView: false, + entityViewPreferences: {global: {} as never, overrides: []}, + koReaderEnabled: false, + autoSaveMetadata: false, + }, + }; +} + +describe('BookCardComponent', () => { + let component: BookCardComponent; + let bookService: { + readBook: ReturnType; + }; + let bookFileService: { + downloadFile: ReturnType; + downloadAdditionalFile: ReturnType; + deleteAdditionalFile: ReturnType; + }; + let bookMetadataManageService: { + regenerateCover: ReturnType; + generateCustomCover: ReturnType; + }; + let taskHelperService: { + refreshMetadataTask: ReturnType; + }; + let userService: { + currentUser: ReturnType; + }; + let emailService: { + emailBookQuick: ReturnType; + }; + let messageService: { + add: ReturnType; + }; + let router: { + navigate: ReturnType; + }; + let urlHelper: { + getThumbnailUrl: ReturnType; + getAudiobookThumbnailUrl: ReturnType; + }; + let confirmationService: { + confirm: ReturnType; + }; + let bookDialogHelperService: { + openShelfAssignerDialog: ReturnType; + openBookDetailsDialog: ReturnType; + openCustomSendDialog: ReturnType; + openMetadataRefreshDialog: ReturnType; + openFileMoverDialog: ReturnType; + }; + let bookNavigationService: { + availableBookIds: ReturnType; + setNavigationContext: ReturnType; + }; + let appSettingsService: { + appSettings: ReturnType; + }; + let translocoService: { + translate: ReturnType; + }; + let queryClient: { + fetchQuery: ReturnType; + }; + let cdr: { + markForCheck: ReturnType; + }; + + beforeEach(() => { + bookService = { + readBook: vi.fn(), + }; + bookFileService = { + downloadFile: vi.fn(), + downloadAdditionalFile: vi.fn(), + deleteAdditionalFile: vi.fn(), + }; + bookMetadataManageService = { + regenerateCover: vi.fn(), + generateCustomCover: vi.fn(), + }; + taskHelperService = { + refreshMetadataTask: vi.fn(), + }; + userService = { + currentUser: vi.fn(() => null), + }; + emailService = { + emailBookQuick: vi.fn(), + }; + messageService = { + add: vi.fn(), + }; + router = { + navigate: vi.fn(), + }; + urlHelper = { + getThumbnailUrl: vi.fn((bookId: number, coverUpdatedOn?: string) => `thumb:${bookId}:${coverUpdatedOn ?? 'none'}`), + getAudiobookThumbnailUrl: vi.fn((bookId: number, audiobookCoverUpdatedOn?: string) => `audio-thumb:${bookId}:${audiobookCoverUpdatedOn ?? 'none'}`), + }; + confirmationService = { + confirm: vi.fn(), + }; + bookDialogHelperService = { + openShelfAssignerDialog: vi.fn(), + openBookDetailsDialog: vi.fn(), + openCustomSendDialog: vi.fn(), + openMetadataRefreshDialog: vi.fn(), + openFileMoverDialog: vi.fn(), + }; + bookNavigationService = { + availableBookIds: vi.fn(() => []), + setNavigationContext: vi.fn(), + }; + appSettingsService = { + appSettings: vi.fn(() => ({diskType: 'LOCAL'})), + }; + translocoService = { + translate: vi.fn((key: string, params?: Record) => (params ? `${key}:${JSON.stringify(params)}` : key)), + }; + queryClient = { + fetchQuery: vi.fn(), + }; + cdr = { + markForCheck: vi.fn(), + }; + + TestBed.configureTestingModule({ + imports: [BookCardComponent], + schemas: [NO_ERRORS_SCHEMA], + providers: [ + {provide: BookService, useValue: bookService}, + {provide: BookFileService, useValue: bookFileService}, + {provide: BookMetadataManageService, useValue: bookMetadataManageService}, + {provide: TaskHelperService, useValue: taskHelperService}, + {provide: UserService, useValue: userService}, + {provide: EmailService, useValue: emailService}, + {provide: MessageService, useValue: messageService}, + {provide: Router, useValue: router}, + {provide: UrlHelperService, useValue: urlHelper}, + {provide: ConfirmationService, useValue: confirmationService}, + {provide: BookDialogHelperService, useValue: bookDialogHelperService}, + {provide: BookNavigationService, useValue: bookNavigationService}, + {provide: AppSettingsService, useValue: appSettingsService}, + {provide: TranslocoService, useValue: translocoService}, + {provide: QueryClient, useValue: queryClient}, + {provide: QueryClient, useValue: queryClient}, + {provide: BookCardComponent, useValue: BookCardComponent}, + {provide: 'ChangeDetectorRef', useValue: cdr}, + ], + }); + + component = TestBed.createComponent(BookCardComponent).componentInstance; + (component as unknown as {cdr: typeof cdr}).cdr = cdr; + }); + + afterEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + it('derives progress, audiobook, and series display state from inputs and changes', () => { + component.book = makeBook({ + id: 8, + metadata: { + bookId: 8, + title: 'Volume One', + seriesName: 'Series Saga', + coverUpdatedOn: '2024-04-01', + audiobookCoverUpdatedOn: '2024-04-02', + }, + seriesCount: 2, + primaryFile: { + id: 81, + bookId: 8, + bookType: 'AUDIOBOOK', + extension: 'm4b', + filePath: 'books/volume-one.m4b', + }, + pdfProgress: {page: 11, percentage: 42}, + koreaderProgress: {percentage: 11}, + koboProgress: {percentage: 7}, + readStatus: ReadStatus.READING, + }); + component.seriesViewEnabled = true; + component.isSeriesCollapsed = true; + component.forceEbookMode = false; + + component.ngOnInit(); + + expect(component.hasProgress).toBe(true); + expect(component.displayTitle).toBe('Series Saga'); + expect(component.titleTooltip).toContain('Series Saga'); + expect(component.coverImageUrl).toBe('audio-thumb:8:2024-04-02'); + expect(component.progressTooltip).toBe('42% (Grimmory) | 11% (KOReader) | 7% (Kobo)'); + expect(component.readButtonIcon).toBe('pi pi-forward'); + + component.isSeriesCollapsed = false; + component.ngOnChanges({ + isSeriesCollapsed: new SimpleChange(true, false, false), + } as SimpleChanges); + + expect(component.displayTitle).toBe('Volume One'); + expect(component.titleTooltip).toContain('Volume One'); + }); + + it('uses forced ebook mode for audiobook reads and falls back to the normal read flow otherwise', () => { + const audiobookWithAlternativeFormat = makeBook({ + id: 12, + primaryFile: { + id: 121, + bookId: 12, + bookType: 'AUDIOBOOK', + extension: 'm4b', + filePath: 'books/audiobook.m4b', + }, + alternativeFormats: [ + { + id: 122, + bookId: 12, + bookType: 'PDF', + fileName: 'A PDF', + filePath: 'books/audiobook.pdf', + fileSizeKb: 2048, + } as AdditionalFile, + ], + }); + + component.forceEbookMode = true; + component.readBook(audiobookWithAlternativeFormat); + + expect(bookService.readBook).toHaveBeenCalledWith(12, undefined, 'PDF'); + + component.forceEbookMode = false; + component.readBook(makeBook({id: 13})); + + expect(bookService.readBook).toHaveBeenCalledWith(13); + }); + + it('derives display format from missing primary files, extensions, paths, and forced audiobook ebook types', () => { + component.book = makeBook({id: 20, primaryFile: undefined}); + component.forceEbookMode = false; + expect(component.getDisplayFormat()).toBe('PHY'); + + component.book = makeBook({ + id: 21, + primaryFile: { + id: 211, + bookId: 21, + bookType: 'PDF', + extension: 'pdf', + filePath: 'books/volume-one.pdf', + }, + }); + expect(component.getDisplayFormat()).toBe('PDF'); + + component.book = makeBook({ + id: 22, + primaryFile: { + id: 221, + bookId: 22, + bookType: 'EPUB', + filePath: 'books/volume-one.mobi', + }, + }); + expect(component.getDisplayFormat()).toBe('MOBI'); + + component.book = makeBook({ + id: 23, + primaryFile: { + id: 231, + bookId: 23, + bookType: 'AUDIOBOOK', + filePath: 'books/volume-one.m4b', + }, + epubProgress: {cfi: 'epub', percentage: 73}, + }); + component.forceEbookMode = true; + expect(component.getDisplayFormat()).toBe('EPUB'); + }); + + it('guards card selection and preserves shift metadata for ctrl-initiated changes only', () => { + component.book = makeBook({id: 30}); + component.index = 4; + component.isCheckboxEnabled = false; + component.isSelected = false; + component.onBookSelect = vi.fn(); + + const emitSpy = vi.spyOn(component.checkboxClick, 'emit'); + + component.toggleCardSelection(true); + expect(emitSpy).not.toHaveBeenCalled(); + expect(component.onBookSelect).not.toHaveBeenCalled(); + + component.isCheckboxEnabled = true; + component.captureMouseEvent(new MouseEvent('mousedown', {shiftKey: true})); + + component.onCardClick(new MouseEvent('click', {ctrlKey: false})); + expect(emitSpy).not.toHaveBeenCalled(); + + component.onCardClick(new MouseEvent('click', {ctrlKey: true})); + + expect(component.isSelected).toBe(true); + expect(emitSpy).toHaveBeenCalledWith({ + index: 4, + book: component.book, + selected: true, + shiftKey: true, + }); + expect(component.onBookSelect).toHaveBeenCalledWith(component.book, true); + }); + + it('routes series info and book details through the correct destination', () => { + const book = makeBook({ + id: 44, + metadata: { + bookId: 44, + title: 'Volume Four', + seriesName: 'The Series', + coverUpdatedOn: '2024-05-01', + audiobookCoverUpdatedOn: '2024-05-02', + }, + }); + + userService.currentUser.mockReturnValue(makeUser('route')); + component.book = book; + component.isSeriesCollapsed = true; + component.ngOnInit(); + + component.openSeriesInfo(); + expect(router.navigate).toHaveBeenCalledWith(['/series', 'The Series']); + + bookNavigationService.availableBookIds.mockReturnValue([2, 44, 77]); + component.isSeriesCollapsed = false; + component.openSeriesInfo(); + + expect(bookNavigationService.setNavigationContext).toHaveBeenCalledWith([2, 44, 77], 44); + expect(router.navigate).toHaveBeenCalledWith(['/book', 44], { + queryParams: {tab: 'view'}, + }); + + userService.currentUser.mockReturnValue(makeUser('dialog')); + const dialogComponent = component as unknown as {metadataCenterViewMode: 'route' | 'dialog'}; + dialogComponent.metadataCenterViewMode = 'dialog'; + router.navigate.mockClear(); + bookNavigationService.setNavigationContext.mockClear(); + + component.openBookInfo(book); + + expect(bookDialogHelperService.openBookDetailsDialog).toHaveBeenCalledWith(44); + expect(router.navigate).not.toHaveBeenCalled(); + expect(bookNavigationService.setNavigationContext).toHaveBeenCalledWith([2, 44, 77], 44); + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/book-dialog-helper.service.spec.ts b/frontend/src/app/features/book/components/book-browser/book-dialog-helper.service.spec.ts new file mode 100644 index 000000000..93bc7f2cd --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/book-dialog-helper.service.spec.ts @@ -0,0 +1,63 @@ +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {DialogLauncherService} from '../../../../shared/services/dialog-launcher.service'; +import {BookDialogHelperService} from './book-dialog-helper.service'; + +describe('BookDialogHelperService', () => { + let service: BookDialogHelperService; + let dialogLauncherService: {openDialog: ReturnType}; + + beforeEach(() => { + dialogLauncherService = { + openDialog: vi.fn(() => ({id: 'dialog-ref'})), + }; + + TestBed.configureTestingModule({ + providers: [ + BookDialogHelperService, + {provide: DialogLauncherService, useValue: dialogLauncherService}, + ], + }); + + service = TestBed.inject(BookDialogHelperService); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('opens the book details dialog with the expected payload', () => { + const dialogRef = service.openBookDetailsDialog(42); + + expect(dialogLauncherService.openDialog).toHaveBeenCalledWith( + expect.any(Function), + expect.objectContaining({ + showHeader: false, + data: {bookId: 42}, + }) + ); + expect(dialogRef).toEqual({id: 'dialog-ref'}); + }); + + it('returns null instead of opening the shelf assigner when no inputs are provided', () => { + const dialogRef = service.openShelfAssignerDialog(null, null); + + expect(dialogRef).toBeNull(); + expect(dialogLauncherService.openDialog).not.toHaveBeenCalled(); + }); + + it('opens the bulk file attacher with the provided source books', () => { + const sourceBooks = [{id: 1}, {id: 2}] as never[]; + + service.openBulkBookFileAttacherDialog(sourceBooks); + + expect(dialogLauncherService.openDialog).toHaveBeenCalledWith( + expect.any(Function), + expect.objectContaining({ + showHeader: false, + data: {sourceBooks}, + }) + ); + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/book-filter-orchestration.service.spec.ts b/frontend/src/app/features/book/components/book-browser/book-filter-orchestration.service.spec.ts new file mode 100644 index 000000000..5cca282ec --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/book-filter-orchestration.service.spec.ts @@ -0,0 +1,66 @@ +import {TestBed} from '@angular/core/testing'; +import {convertToParamMap} from '@angular/router'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {BookFilterOrchestrationService} from './book-filter-orchestration.service'; +import {SortService} from '../../service/sort.service'; + +describe('BookFilterOrchestrationService', () => { + let service: BookFilterOrchestrationService; + let sortService: {applyMultiSort: ReturnType}; + + beforeEach(() => { + sortService = { + applyMultiSort: vi.fn((books: unknown[]) => books), + }; + + TestBed.configureTestingModule({ + providers: [ + BookFilterOrchestrationService, + {provide: SortService, useValue: sortService}, + ], + }); + + service = TestBed.inject(BookFilterOrchestrationService); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('passes searched and collapsed books through the sorter', () => { + const books = [ + {id: 1, metadata: {title: 'Alpha Flight'}}, + {id: 2, metadata: {title: 'Beta Test'}}, + ] as never[]; + const seriesCollapseFilter = { + collapseBooks: vi.fn((items: unknown[]) => items), + }; + const sortCriteria = [{property: 'title', direction: 'ASC'}] as never[]; + + const result = service.applyFilters( + books, + 'alpha', + null, + 'and', + seriesCollapseFilter as never, + false, + false, + sortCriteria + ); + + expect(seriesCollapseFilter.collapseBooks).toHaveBeenCalledWith( + [books[0]], + false, + false + ); + expect(sortService.applyMultiSort).toHaveBeenCalledWith([books[0]], sortCriteria); + expect(result).toEqual([books[0]]); + }); + + it('forces series expansion only when a series filter is present in the query string', () => { + expect(service.shouldForceExpandSeries(convertToParamMap({filter: 'author:42,series:Saga'}))).toBe(true); + expect(service.shouldForceExpandSeries(convertToParamMap({filter: 'author:42'}))).toBe(false); + expect(service.shouldForceExpandSeries(convertToParamMap({}))).toBe(false); + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/book-filter/book-filter.component.spec.ts b/frontend/src/app/features/book/components/book-browser/book-filter/book-filter.component.spec.ts new file mode 100644 index 000000000..38fa53cef --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/book-filter/book-filter.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around reset streams, user-setting effects, +// and virtual-scroll accordion rendering so filter-mode changes and panel expansion can be +// asserted without the full book-browser sidebar runtime. +describe.skip('BookFilterComponent', () => { + it('needs signal seams to verify visible filter hydration, mode changes, and emitted active-filter payloads', () => { + // TODO(seam): Cover selectedFilterMode, setFilters, and emitFilters after the user-settings signal and filter service signals are isolated behind deterministic doubles. + }); + + it('needs UI-shell seams to verify reset handling, panel expansion, and multi-select filter clicks', () => { + // TODO(seam): Cover handleFilterClick, clearActiveFilter, and accordion expansion after the virtual-scroll and select-button runtime is removed from the test surface. + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/book-filter/book-filter.config.spec.ts b/frontend/src/app/features/book/components/book-browser/book-filter/book-filter.config.spec.ts new file mode 100644 index 000000000..2cbb628e5 --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/book-filter/book-filter.config.spec.ts @@ -0,0 +1,79 @@ +import {describe, expect, it} from 'vitest'; + +import {Book, ReadStatus} from '../../../model/book.model'; +import { + CONTENT_RATING_LABELS, + FILTER_CONFIGS, + FILTER_EXTRACTORS, + FILTER_LABEL_KEYS, + MATCH_SCORE_RANGES, + NUMERIC_ID_FILTER_TYPES, + RATING_OPTIONS_10, + READ_STATUS_LABELS +} from './book-filter.config'; + +const makeBook = (overrides: Partial = {}): Book => ({ + id: 1, + libraryId: 9, + libraryName: 'Main', + ...overrides +}); + +describe('book-filter.config', () => { + it('covers every read status with a label', () => { + expect(READ_STATUS_LABELS[ReadStatus.UNREAD]).toBe('Unread'); + expect(READ_STATUS_LABELS[ReadStatus.UNSET]).toBe('Unset'); + expect(Object.keys(READ_STATUS_LABELS)).toHaveLength(Object.keys(ReadStatus).length); + }); + + it('defines 10 one-step rating buckets', () => { + expect(RATING_OPTIONS_10).toHaveLength(10); + expect(RATING_OPTIONS_10[0]).toMatchObject({id: 1, label: '1', min: 1, max: 2, sortIndex: 0}); + expect(RATING_OPTIONS_10.at(-1)).toMatchObject({id: 10, label: '10', min: 10, max: 11, sortIndex: 9}); + }); + + it('keeps filter labels and configs aligned', () => { + const configKeys = Object.keys(FILTER_CONFIGS).sort(); + const labelKeysWithoutLibrary = Object.keys(FILTER_LABEL_KEYS).filter((key) => key !== 'library').sort(); + + expect(labelKeysWithoutLibrary).toEqual(configKeys); + expect(FILTER_LABEL_KEYS.library).toBe('book.filter.labels.library'); + expect(NUMERIC_ID_FILTER_TYPES.has('pageCount')).toBe(true); + expect(NUMERIC_ID_FILTER_TYPES.has('author')).toBe(false); + }); + + it('normalizes read status, metadata match score, and content ratings', () => { + expect(FILTER_EXTRACTORS.readStatus(makeBook({readStatus: ReadStatus.READING}))).toEqual([ + {id: ReadStatus.READING, name: 'Reading'} + ]); + + expect(FILTER_EXTRACTORS.readStatus(makeBook({readStatus: 'INVALID' as ReadStatus}))).toEqual([ + {id: ReadStatus.UNSET, name: 'Unset'} + ]); + + expect(FILTER_EXTRACTORS.matchScore(makeBook({metadataMatchScore: 92}))).toEqual([ + {id: MATCH_SCORE_RANGES[1].id, name: MATCH_SCORE_RANGES[1].label, sortIndex: MATCH_SCORE_RANGES[1].sortIndex} + ]); + + expect(FILTER_EXTRACTORS.contentRating(makeBook({ + metadata: {bookId: 1, contentRating: 'EVERYONE'} + }))).toEqual([{id: 'EVERYONE', name: CONTENT_RATING_LABELS['EVERYONE']}]); + }); + + it('builds comic creator filters with role-aware labels', () => { + const filters = FILTER_EXTRACTORS.comicCreator(makeBook({ + metadata: { + bookId: 1, + comicMetadata: { + pencillers: ['Jane Artist'], + editors: ['Max Editor'] + } + } + })); + + expect(filters).toEqual([ + {id: 'Jane Artist:penciller', name: 'Jane Artist (Penciller)'}, + {id: 'Max Editor:editor', name: 'Max Editor (Editor)'} + ]); + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/book-filter/book-filter.service.spec.ts b/frontend/src/app/features/book/components/book-browser/book-filter/book-filter.service.spec.ts new file mode 100644 index 000000000..a3d39ba76 --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/book-filter/book-filter.service.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around the live book, library, and +// magic-shelf signal graph so dynamic filter aggregation can be asserted without recreating the +// full sidebar filter runtime and evaluator dependencies. +describe.skip('BookFilterService', () => { + it('needs signal seams to verify library, shelf, and magic-shelf entity filtering across active sidebar filters', () => { + // TODO(seam): Cover createFilterSignals and filterBooksByEntity once the dependent signals and evaluator service are isolated behind deterministic doubles. + }); + + it('needs aggregation seams to verify filter count sorting, numeric-id coercion, and invalid magic-shelf fallback handling', () => { + // TODO(seam): Cover buildAndSortFilters, processFilterValue, and filterByMagicShelf after extractor inputs and service state are exposed through a stable harness. + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/book-selection.service.spec.ts b/frontend/src/app/features/book/components/book-browser/book-selection.service.spec.ts new file mode 100644 index 000000000..e10a2f21c --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/book-selection.service.spec.ts @@ -0,0 +1,79 @@ +import {TestBed} from '@angular/core/testing'; +import {beforeEach, describe, expect, it} from 'vitest'; + +import {BookSelectionService} from './book-selection.service'; +import {Book} from '../../model/book.model'; + +function makeBook(id: number, overrides: Partial = {}): Book { + return { + id, + libraryId: 1, + libraryName: 'Library', + metadata: {bookId: id, title: `Book ${id}`}, + ...overrides + }; +} + +describe('BookSelectionService', () => { + let service: BookSelectionService; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [BookSelectionService] + }); + + service = TestBed.inject(BookSelectionService); + }); + + it('selects and deselects single books and series groups', () => { + const singleBook = makeBook(1); + const seriesBook = makeBook(2, { + seriesBooks: [makeBook(2), makeBook(3)] + }); + + service.selectBook(singleBook); + service.selectBook(seriesBook); + + expect(service.selectedBooks()).toEqual(new Set([1, 2, 3])); + expect(service.selectedCount()).toBe(3); + + service.deselectBook(makeBook(1)); + service.deselectBook(seriesBook); + + expect(service.selectedBooks()).toEqual(new Set()); + expect(service.selectedCount()).toBe(0); + }); + + it('tracks checkbox clicks with and without shift selection', () => { + const books = [makeBook(1), makeBook(2), makeBook(3), makeBook(4)]; + service.setCurrentBooks(books); + + service.handleCheckboxClick({index: 1, book: books[1], selected: true, shiftKey: false}); + expect(service.selectedBooks()).toEqual(new Set([2])); + + service.handleCheckboxClick({index: 3, book: books[3], selected: true, shiftKey: true}); + expect(service.selectedBooks()).toEqual(new Set([2, 3, 4])); + + service.handleCheckboxClick({index: 3, book: books[3], selected: false, shiftKey: true}); + expect(service.selectedBooks()).toEqual(new Set()); + }); + + it('selects all current books, resets selection, and clones selected ids', () => { + expect(() => service.selectAll()).not.toThrow(); + + const books = [makeBook(1), makeBook(2)]; + service.setCurrentBooks(books); + service.selectAll(); + expect(service.selectedBooks()).toEqual(new Set([1, 2])); + + const selectedIds = new Set([4, 5]); + service.setSelectedBooks(selectedIds); + selectedIds.add(6); + + expect(service.selectedBooks()).toEqual(new Set([4, 5])); + + service.deselectAll(); + expect(service.selectedBooks()).toEqual(new Set()); + expect(service.selectedCount()).toBe(0); + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.spec.ts b/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.spec.ts new file mode 100644 index 000000000..698ed4115 --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around DOM sizing, table selection events, +// router-link rendering, and metadata-lock helpers so table interactions can be asserted without +// mounting the full PrimeNG virtual-table runtime. +describe.skip('BookTableComponent', () => { + it('needs browser seams to verify responsive scroll-height updates and virtual scroller resizing', () => { + // TODO(seam): Cover setScrollHeight and ngOnChanges after window/document globals are isolated behind deterministic adapters. + }); + + it('needs table-event seams to verify row selection, bulk selection, and clickable metadata cell generation', () => { + // TODO(seam): Cover selection methods and getCellClickableValue after the PrimeNG table event surface is extracted into a stable test harness. + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/cover-scale-preference.service.spec.ts b/frontend/src/app/features/book/components/book-browser/cover-scale-preference.service.spec.ts new file mode 100644 index 000000000..e2dd4638a --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/cover-scale-preference.service.spec.ts @@ -0,0 +1,120 @@ +import {TestBed} from '@angular/core/testing'; +import {MessageService} from 'primeng/api'; +import {TranslocoService} from '@jsverse/transloco'; +import {vi, describe, beforeEach, afterEach, expect, it} from 'vitest'; + +import {CoverScalePreferenceService} from './cover-scale-preference.service'; +import {LocalStorageService} from '../../../../shared/service/local-storage.service'; + +describe('CoverScalePreferenceService', () => { + let service: CoverScalePreferenceService; + let localStorageService: { get: ReturnType; set: ReturnType }; + let messageService: { add: ReturnType }; + let translocoService: { translate: ReturnType }; + + beforeEach(() => { + vi.useFakeTimers(); + localStorageService = { + get: vi.fn(), + set: vi.fn() + }; + messageService = { + add: vi.fn() + }; + translocoService = { + translate: vi.fn((key: string, params?: Record) => + params ? `${key}:${JSON.stringify(params)}` : `t:${key}` + ) + }; + }); + + afterEach(() => { + vi.runOnlyPendingTimers(); + vi.useRealTimers(); + TestBed.resetTestingModule(); + }); + + it('loads the saved scale and derives the card metrics', () => { + localStorageService.get.mockReturnValue(1.5); + + TestBed.configureTestingModule({ + providers: [ + CoverScalePreferenceService, + {provide: LocalStorageService, useValue: localStorageService}, + {provide: MessageService, useValue: messageService}, + {provide: TranslocoService, useValue: translocoService} + ] + }); + + service = TestBed.inject(CoverScalePreferenceService); + + expect(service.scaleFactor()).toBe(1.5); + expect(service.currentCardSize()).toEqual({width: 203, height: 330}); + expect(service.gridColumnMinWidth()).toBe('203px'); + expect(service.getCardHeight({} as never)).toBe(330); + }); + + it('falls back to the default scale and skips persistence when unchanged', () => { + localStorageService.get.mockReturnValue(null); + + TestBed.configureTestingModule({ + providers: [ + CoverScalePreferenceService, + {provide: LocalStorageService, useValue: localStorageService}, + {provide: MessageService, useValue: messageService}, + {provide: TranslocoService, useValue: translocoService} + ] + }); + + service = TestBed.inject(CoverScalePreferenceService); + + service.setScale(1.0); + vi.runOnlyPendingTimers(); + + expect(localStorageService.set).not.toHaveBeenCalled(); + expect(messageService.add).not.toHaveBeenCalled(); + }); + + it('persists updated scale after debounce and reports failures', () => { + localStorageService.get.mockReturnValue(1.0); + + TestBed.configureTestingModule({ + providers: [ + CoverScalePreferenceService, + {provide: LocalStorageService, useValue: localStorageService}, + {provide: MessageService, useValue: messageService}, + {provide: TranslocoService, useValue: translocoService} + ] + }); + + service = TestBed.inject(CoverScalePreferenceService); + + service.setScale(1.2); + expect(localStorageService.set).not.toHaveBeenCalled(); + + vi.advanceTimersByTime(1000); + + expect(localStorageService.set).toHaveBeenCalledWith('coverScalePreference', 1.2); + expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'success', + summary: 't:book.coverPref.toast.savedSummary', + detail: 'book.coverPref.toast.savedDetail:{"scale":"1.20"}', + life: 1500 + })); + + vi.clearAllMocks(); + localStorageService.set.mockImplementation(() => { + throw new Error('storage unavailable'); + }); + + service.setScale(1.3); + vi.advanceTimersByTime(1000); + + expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'error', + summary: 't:book.coverPref.toast.saveFailedSummary', + detail: 't:book.coverPref.toast.saveFailedDetail', + life: 3000 + })); + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/filter-label.helper.spec.ts b/frontend/src/app/features/book/components/book-browser/filter-label.helper.spec.ts new file mode 100644 index 000000000..ccbf3726b --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/filter-label.helper.spec.ts @@ -0,0 +1,23 @@ +import {describe, expect, it} from 'vitest'; + +import {FilterLabelHelper} from './filter-label.helper'; + +describe('FilterLabelHelper', () => { + it('returns friendly names for known filter types and capitalizes unknown names', () => { + expect(FilterLabelHelper.getFilterTypeName('personalRating')).toBe('Personal Rating'); + expect(FilterLabelHelper.getFilterTypeName('customFilter')).toBe('CustomFilter'); + }); + + it('maps numeric ids to configured range labels', () => { + expect(FilterLabelHelper.getFilterDisplayValue('fileSize', 1)).toBe('1–10 MB'); + expect(FilterLabelHelper.getFilterDisplayValue('pageCount', 3)).toBe('200–400 pages'); + expect(FilterLabelHelper.getFilterDisplayValue('matchScore', 0)).toBe('Outstanding (95–100%)'); + expect(FilterLabelHelper.getFilterDisplayValue('personalRating', 7)).toBe('7'); + expect(FilterLabelHelper.getFilterDisplayValue('amazonRating', 5)).toBe('4.5+'); + }); + + it('falls back to the raw value when a numeric id is not recognized', () => { + expect(FilterLabelHelper.getFilterDisplayValue('fileSize', 999)).toBe('999'); + expect(FilterLabelHelper.getFilterDisplayValue('tag', 'favorite')).toBe('favorite'); + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/filters/HeaderFilter.spec.ts b/frontend/src/app/features/book/components/book-browser/filters/HeaderFilter.spec.ts new file mode 100644 index 000000000..0c1a8e3aa --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/filters/HeaderFilter.spec.ts @@ -0,0 +1,72 @@ +import {describe, expect, it} from 'vitest'; + +import {Book} from '../../../model/book.model'; +import {filterBooksBySearchTerm, normalizeSearchTerm} from './HeaderFilter'; + +function makeBook(id: number, overrides: Partial = {}): Book { + return { + id, + libraryId: 1, + libraryName: 'Library', + fileName: `Book ${id}.epub`, + metadata: { + bookId: id, + title: `Title ${id}`, + seriesName: `Series ${id}`, + authors: [`Author ${id}`], + categories: [`Category ${id}`], + isbn10: `ISBN10-${id}`, + isbn13: `ISBN13-${id}` + }, + primaryFile: {id, bookId: id, fileName: `Book ${id}.epub`, bookType: 'EPUB'}, + ...overrides + }; +} + +describe('HeaderFilter', () => { + it('normalizes unicode, punctuation, whitespace, and empty input', () => { + expect(normalizeSearchTerm('')).toBe(''); + expect(normalizeSearchTerm(' Ætna øresund! ')).toBe('aetna oresund'); + expect(normalizeSearchTerm('Łódź / Straße')).toBe('lodz strasse'); + }); + + it('keeps the full book list for short terms and filters by searchable fields', () => { + const books = [ + makeBook(1), + makeBook(2, { + metadata: { + bookId: 2, + title: 'The Other Title', + seriesName: 'Other Series', + authors: ['Different Author'], + categories: ['Biography'], + isbn10: '999', + isbn13: '888' + }, + primaryFile: {id: 2, bookId: 2, fileName: 'Notes.txt', bookType: 'EPUB'} + }), + makeBook(3, { + metadata: { + bookId: 3, + title: 'Completely Different', + seriesName: 'Third Series', + authors: ['Series Match'], + categories: ['History'], + isbn10: '111', + isbn13: '222' + }, + primaryFile: {id: 3, bookId: 3, fileName: 'Search Target.epub', bookType: 'EPUB'} + }) + ]; + + expect(filterBooksBySearchTerm(books, '')).toBe(books); + expect(filterBooksBySearchTerm(books, 'a')).toBe(books); + + expect(filterBooksBySearchTerm(books, 'other title').map(book => book.id)).toEqual([2]); + expect(filterBooksBySearchTerm(books, 'other series').map(book => book.id)).toEqual([2]); + expect(filterBooksBySearchTerm(books, 'series match').map(book => book.id)).toEqual([3]); + expect(filterBooksBySearchTerm(books, 'biography').map(book => book.id)).toEqual([2]); + expect(filterBooksBySearchTerm(books, '222').map(book => book.id)).toEqual([3]); + expect(filterBooksBySearchTerm(books, 'search target').map(book => book.id)).toEqual([3]); + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/filters/SeriesCollapseFilter.spec.ts b/frontend/src/app/features/book/components/book-browser/filters/SeriesCollapseFilter.spec.ts new file mode 100644 index 000000000..54f21101c --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/filters/SeriesCollapseFilter.spec.ts @@ -0,0 +1,148 @@ +import {TestBed} from '@angular/core/testing'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {MessageService} from 'primeng/api'; + +import {SeriesCollapseFilter} from './SeriesCollapseFilter'; +import {UserService} from '../../../../settings/user-management/user.service'; +import {Book} from '../../../model/book.model'; + +function makeBook(id: number, seriesName?: string, seriesNumber?: number): Book { + return { + id, + libraryId: 1, + libraryName: 'Library', + metadata: { + bookId: id, + title: `Book ${id}`, + seriesName, + seriesNumber + } + }; +} + +describe('SeriesCollapseFilter', () => { + let userService: {currentUser: ReturnType; getCurrentUser: ReturnType; updateUserSetting: ReturnType}; + let messageService: {add: ReturnType}; + let service: SeriesCollapseFilter; + + beforeEach(() => { + vi.useFakeTimers(); + userService = { + currentUser: vi.fn(() => ({id: 1})), + getCurrentUser: vi.fn(() => null), + updateUserSetting: vi.fn() + }; + messageService = {add: vi.fn()}; + + TestBed.configureTestingModule({ + providers: [ + SeriesCollapseFilter, + {provide: UserService, useValue: userService}, + {provide: MessageService, useValue: messageService} + ] + }); + + service = TestBed.inject(SeriesCollapseFilter); + }); + + it('returns books unchanged when collapse is disabled or series expansion is forced', () => { + const books = [makeBook(1), makeBook(2, 'Series', 2)]; + + expect(service.collapseBooks(books, false, false)).toBe(books); + expect(service.collapseBooks([], false, true)).toEqual([]); + expect(service.collapseBooks(books, true, true)).toBe(books); + }); + + it('collapses series into grouped books with the lowest numbered entry first', () => { + const books = [ + makeBook(1, 'Series', 2), + makeBook(2, 'Series', 1), + makeBook(3), + makeBook(4, 'Other Series', 5) + ]; + + const collapsed = service.collapseBooks(books, false, true); + + expect(collapsed).toEqual([ + makeBook(3), + { + ...makeBook(2, 'Series', 1), + seriesBooks: [books[0], books[1]], + seriesCount: 2 + }, + { + ...makeBook(4, 'Other Series', 5), + seriesBooks: [books[3]], + seriesCount: 1 + } + ]); + }); + + it('persists context-aware and global preferences with legacy fallbacks', () => { + const user = { + id: 1, + userSettings: { + entityViewPreferences: { + global: { + sortKey: 'addedOn', + sortDir: 'DESC', + view: 'GRID', + coverSize: 1, + seriesCollapse: true + }, + overrides: [ + { + entityType: 'LIBRARY', + entityId: 99, + preferences: { + sortKey: 'title', + sortDir: 'ASC', + view: 'TABLE', + coverSize: 1, + seriesCollapsed: false, + overlayBookType: true + } + } + ] + } + } + }; + + userService.getCurrentUser.mockReturnValue(user); + + service.setContext('LIBRARY', 99); + expect(service.seriesCollapsed()).toBe(false); + + service.setCollapsed(true); + vi.advanceTimersByTime(500); + + expect(userService.updateUserSetting).toHaveBeenCalledWith(1, 'entityViewPreferences', expect.objectContaining({ + overrides: expect.arrayContaining([ + expect.objectContaining({ + entityType: 'LIBRARY', + entityId: 99, + preferences: expect.objectContaining({ + seriesCollapsed: true + }) + }) + ]) + })); + expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'success', + summary: 'Preference Saved' + })); + + userService.updateUserSetting.mockClear(); + messageService.add.mockClear(); + + service.setContext(null, null); + service.setCollapsed(false); + vi.advanceTimersByTime(500); + + expect(userService.updateUserSetting).toHaveBeenCalledWith(1, 'entityViewPreferences', expect.objectContaining({ + global: expect.objectContaining({ + seriesCollapsed: false + }) + })); + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.spec.ts b/frontend/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.spec.ts new file mode 100644 index 000000000..96d8f501c --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.spec.ts @@ -0,0 +1,98 @@ +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {TranslocoService} from '@jsverse/transloco'; +import {MessageService} from 'primeng/api'; + +import {LocalStorageService} from '../../../../../shared/service/local-storage.service'; +import {SidebarFilterTogglePrefService} from './sidebar-filter-toggle-pref.service'; + +describe('SidebarFilterTogglePrefService', () => { + let originalInnerWidth: number; + let messageService: {add: ReturnType}; + let localStorageService: { + get: ReturnType; + set: ReturnType; + }; + + const setViewport = (width: number) => { + Object.defineProperty(window, 'innerWidth', { + configurable: true, + value: width, + }); + }; + + beforeEach(() => { + originalInnerWidth = window.innerWidth; + messageService = {add: vi.fn()}; + localStorageService = { + get: vi.fn(() => null), + set: vi.fn(), + }; + }); + + afterEach(() => { + setViewport(originalInnerWidth); + TestBed.resetTestingModule(); + }); + + const createService = () => { + TestBed.configureTestingModule({ + providers: [ + SidebarFilterTogglePrefService, + {provide: MessageService, useValue: messageService}, + {provide: LocalStorageService, useValue: localStorageService}, + {provide: TranslocoService, useValue: {translate: (key: string) => key}}, + ], + }); + + return TestBed.inject(SidebarFilterTogglePrefService); + }; + + it('loads the stored preference on wide screens', () => { + setViewport(1280); + localStorageService.get.mockReturnValue(false); + + const service = createService(); + + expect(service.showFilter()).toBe(false); + expect(localStorageService.get).toHaveBeenCalledWith('showSidebarFilter'); + }); + + it('forces the filter closed on narrow screens', () => { + setViewport(640); + + const service = createService(); + + expect(service.showFilter()).toBe(false); + expect(localStorageService.get).not.toHaveBeenCalled(); + }); + + it('toggles the visibility and persists the updated value', () => { + setViewport(1280); + const service = createService(); + + service.toggle(); + + expect(service.showFilter()).toBe(false); + expect(localStorageService.set).toHaveBeenCalledWith('showSidebarFilter', false); + }); + + it('shows an error toast when persistence fails', () => { + setViewport(1280); + localStorageService.set.mockImplementation(() => { + throw new Error('storage failed'); + }); + const service = createService(); + + service.setShowFilter(false); + + expect(messageService.add).toHaveBeenCalledWith( + expect.objectContaining({ + severity: 'error', + summary: 'book.filterPref.toast.saveFailedSummary', + detail: 'book.filterPref.toast.saveFailedDetail', + }) + ); + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/filters/sidebar-filter.spec.ts b/frontend/src/app/features/book/components/book-browser/filters/sidebar-filter.spec.ts new file mode 100644 index 000000000..4dda6f581 --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/filters/sidebar-filter.spec.ts @@ -0,0 +1,148 @@ +import {describe, expect, it} from 'vitest'; + +import {Book, ReadStatus} from '../../../model/book.model'; +import { + doesBookMatchFilter, + doesBookMatchReadStatus, + filterBooksByFilters, + isFileSizeInRange, + isMatchScoreInRange, + isPageCountInRange, + isRatingInRange, + isRatingInRange10 +} from './sidebar-filter'; + +function makeBook(id: number, overrides: Partial = {}): Book { + return { + id, + libraryId: 1, + libraryName: 'Library', + readStatus: ReadStatus.UNREAD, + fileSizeKb: 1500, + metadataMatchScore: 87, + metadata: { + bookId: id, + title: `Title ${id}`, + authors: [`Author ${id}`], + categories: [`Category ${id}`], + seriesName: `Series ${id}`, + publisher: 'Publisher', + publishedDate: '2024-02-01', + pageCount: 230, + language: 'en', + tags: ['tag-a'], + moods: ['mood-a'], + amazonRating: 4.3, + goodreadsRating: 4.1, + hardcoverRating: 4.2, + narrator: 'Narrator', + ageRating: 16, + contentRating: 'PG-13', + comicMetadata: { + characters: ['hero'], + teams: ['team-a'], + locations: ['earth'], + pencillers: ['Penciller'], + inkers: ['Inker'], + colorists: ['Colorist'], + letterers: ['Letterer'], + coverArtists: ['Cover'], + editors: ['Editor'] + } + }, + shelves: [{id: 7, name: 'Favorites'}], + ...overrides + }; +} + +describe('sidebar-filter', () => { + it('covers the numeric helper ranges and read status matching', () => { + expect(isRatingInRange(null, 1)).toBe(false); + expect(isRatingInRange(4.3, '4')).toBe(true); + expect(isRatingInRange10(4.4, 4)).toBe(true); + expect(isFileSizeInRange(undefined, 1)).toBe(false); + expect(isFileSizeInRange(1500, 1)).toBe(true); + expect(isPageCountInRange(230, '3')).toBe(true); + expect(isMatchScoreInRange(87, 2)).toBe(true); + expect(isMatchScoreInRange(87, 9)).toBe(false); + expect(doesBookMatchReadStatus(makeBook(1), [ReadStatus.UNREAD])).toBe(true); + expect(doesBookMatchReadStatus(makeBook(1, {readStatus: undefined}), [ReadStatus.UNSET])).toBe(true); + }); + + it('matches all filter branches across or, and, and not modes', () => { + const book = makeBook(1); + const books = [book, makeBook(2, { + readStatus: ReadStatus.READING, + metadata: { + bookId: 2, + title: 'Other', + authors: ['Other Author'], + categories: ['Other Category'], + seriesName: 'Other Series', + publisher: 'Other Publisher', + publishedDate: '2021-01-01', + pageCount: 50, + language: 'fr', + tags: ['other-tag'], + moods: ['other-mood'], + amazonRating: 3.1, + goodreadsRating: 3.2, + hardcoverRating: 3.3, + narrator: 'Someone Else', + ageRating: 12, + contentRating: 'R', + comicMetadata: { + characters: ['villain'], + teams: ['team-b'], + locations: ['mars'], + pencillers: ['Alt Penciller'], + inkers: ['Alt Inker'], + colorists: ['Alt Colorist'], + letterers: ['Alt Letterer'], + coverArtists: ['Alt Cover'], + editors: ['Alt Editor'] + } + }, + shelves: [] + })]; + + expect(doesBookMatchFilter(book, 'author', ['Author 1'], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'category', ['Category 1'], 'and')).toBe(true); + expect(doesBookMatchFilter(book, 'series', ['Series 1'], 'not')).toBe(true); + expect(doesBookMatchFilter(book, 'bookType', ['PHYSICAL'], 'or')).toBe(false); + expect(doesBookMatchFilter(book, 'readStatus', [ReadStatus.UNREAD], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'publisher', ['Publisher'], 'and')).toBe(true); + expect(doesBookMatchFilter(book, 'matchScore', [2], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'library', [1], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'shelf', [7], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'shelfStatus', ['shelved'], 'or')).toBe(true); + expect(doesBookMatchFilter(makeBook(3, {shelves: []}), 'shelfStatus', ['unshelved'], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'tag', ['tag-a'], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'publishedDate', ['2024'], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'fileSize', [1], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'amazonRating', [4], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'goodreadsRating', [4], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'hardcoverRating', [4], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'language', ['en'], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'pageCount', [3], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'mood', ['mood-a'], 'and')).toBe(true); + expect(doesBookMatchFilter(book, 'ageRating', ['16'], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'contentRating', ['PG-13'], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'narrator', ['Narrator'], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'comicCharacter', ['hero'], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'comicTeam', ['team-a'], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'comicLocation', ['earth'], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'comicCreator', ['Penciller:penciller'], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'unknown', ['x'], 'or')).toBe(false); + + expect(doesBookMatchFilter(makeBook(4, {isPhysical: true}), 'bookType', ['PHYSICAL'], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'author', [], 'or')).toBe(true); + expect(doesBookMatchFilter(book, 'author', [], 'and')).toBe(false); + + expect(filterBooksByFilters(books, null, 'or')).toBe(books); + expect(filterBooksByFilters(books, {author: ['Author 1']}, 'or')).toEqual([book]); + expect(filterBooksByFilters(books, {author: ['Other Author']}, 'not')).toEqual([book]); + expect(filterBooksByFilters(books, {author: ['Author 1'], category: ['Category 1']}, 'and')).toEqual([book]); + expect(filterBooksByFilters(books, {author: ['Other Author'], category: ['Category 1']}, 'or', 'author')).toEqual([book]); + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/lock-unlock-metadata-dialog/lock-unlock-metadata-dialog.component.spec.ts b/frontend/src/app/features/book/components/book-browser/lock-unlock-metadata-dialog/lock-unlock-metadata-dialog.component.spec.ts new file mode 100644 index 000000000..42b639398 --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/lock-unlock-metadata-dialog/lock-unlock-metadata-dialog.component.spec.ts @@ -0,0 +1,164 @@ +import {TestBed} from '@angular/core/testing'; +import {of, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {TranslocoService} from '@jsverse/transloco'; +import {LoadingService} from '../../../../../core/services/loading.service'; +import { + createDynamicDialogHarness, + createMessageServiceProvider, + createMessageServiceSpy, +} from '../../../../../core/testing/dialog-testing'; +import {BookMetadataManageService} from '../../../service/book-metadata-manage.service'; +import {LockUnlockMetadataDialogComponent} from './lock-unlock-metadata-dialog.component'; + +describe('LockUnlockMetadataDialogComponent', () => { + let toggleFieldLocks: ReturnType; + let dialogHarness: ReturnType}>>; + let messageService: ReturnType; + let loadingService: { + show: ReturnType; + hide: ReturnType; + }; + let translate: TranslocoService['translate']; + + beforeEach(() => { + toggleFieldLocks = vi.fn(() => of(void 0)); + dialogHarness = createDynamicDialogHarness({bookIds: new Set([7, 9])}); + messageService = createMessageServiceSpy(); + loadingService = { + show: vi.fn(() => 'loader-token'), + hide: vi.fn(), + }; + translate = ((key: string) => `translated:${key}` as T) as TranslocoService['translate']; + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + function createComponent() { + TestBed.configureTestingModule({ + providers: [ + ...dialogHarness.providers, + { + provide: BookMetadataManageService, + useValue: { + toggleFieldLocks, + }, + }, + createMessageServiceProvider(messageService), + { + provide: LoadingService, + useValue: loadingService, + }, + { + provide: TranslocoService, + useValue: { + translate, + }, + }, + ], + }); + + const component = TestBed.runInInjectionContext(() => new LockUnlockMetadataDialogComponent()); + component.ngOnInit(); + return component; + } + + it('toggles every lockable field between locked and unlocked states', () => { + const component = createComponent(); + + component.toggleLockAll('LOCK'); + expect(component.lockableFields.every(field => component.fieldLocks[field] === true)).toBe(true); + + component.toggleLockAll('UNLOCK'); + expect(component.lockableFields.every(field => component.fieldLocks[field] === false)).toBe(true); + }); + + it('returns translated labels and icons for unselected, locked, and unlocked states', () => { + const component = createComponent(); + + expect(component.getLockLabel('titleLocked')).toBe('translated:book.lockUnlockDialog.unselected'); + expect(component.getLockIcon('titleLocked')).toBe(''); + + component.fieldLocks['titleLocked'] = true; + expect(component.getLockLabel('titleLocked')).toBe('translated:book.lockUnlockDialog.locked'); + expect(component.getLockIcon('titleLocked')).toBe('pi pi-lock'); + + component.fieldLocks['titleLocked'] = false; + expect(component.getLockLabel('titleLocked')).toBe('translated:book.lockUnlockDialog.unlocked'); + expect(component.getLockIcon('titleLocked')).toBe('pi pi-lock-open'); + }); + + it('resets every field lock back to an unselected state', () => { + const component = createComponent(); + component.toggleLockAll('LOCK'); + + component.resetFieldLocks(); + + expect(component.lockableFields.every(field => component.fieldLocks[field] === undefined)).toBe(true); + }); + + it('cycles a field through locked, unlocked, and cleared states', () => { + const component = createComponent(); + + component.cycleLockState('titleLocked'); + expect(component.fieldLocks['titleLocked']).toBe(true); + + component.cycleLockState('titleLocked'); + expect(component.fieldLocks['titleLocked']).toBe(false); + + component.cycleLockState('titleLocked'); + expect(component.fieldLocks['titleLocked']).toBeUndefined(); + }); + + it('applies selected field locks, shows a success toast, and closes the dialog', () => { + const component = createComponent(); + component.fieldLocks['titleLocked'] = true; + component.fieldLocks['authorsLocked'] = false; + component.fieldLocks['subtitleLocked'] = undefined; + + component.applyFieldLocks(); + + expect(toggleFieldLocks).toHaveBeenCalledWith(new Set([7, 9]), { + titleLocked: 'LOCK', + authorsLocked: 'UNLOCK', + }); + expect(loadingService.show).toHaveBeenCalledWith( + 'translated:book.lockUnlockDialog.toast.updatingFieldLocks' + ); + expect(loadingService.hide).toHaveBeenCalledWith('loader-token'); + expect(component.isSaving).toBe(false); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'translated:book.lockUnlockDialog.toast.updatedSummary', + detail: 'translated:book.lockUnlockDialog.toast.updatedDetail', + }); + expect(dialogHarness.dialogRef.close).toHaveBeenCalledWith('fields-updated'); + }); + + it('shows an error toast and keeps the dialog open when saving fails', () => { + toggleFieldLocks.mockReturnValueOnce(throwError(() => new Error('save failed'))); + const component = createComponent(); + component.fieldLocks['titleLocked'] = false; + + component.applyFieldLocks(); + + expect(toggleFieldLocks).toHaveBeenCalledWith(new Set([7, 9]), { + titleLocked: 'UNLOCK', + }); + expect(loadingService.show).toHaveBeenCalledWith( + 'translated:book.lockUnlockDialog.toast.updatingFieldLocks' + ); + expect(loadingService.hide).toHaveBeenCalledWith('loader-token'); + expect(component.isSaving).toBe(false); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'translated:book.lockUnlockDialog.toast.failedSummary', + detail: 'translated:book.lockUnlockDialog.toast.failedDetail', + }); + expect(dialogHarness.dialogRef.close).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/sorting/BookSorter.spec.ts b/frontend/src/app/features/book/components/book-browser/sorting/BookSorter.spec.ts new file mode 100644 index 000000000..e4b3d3015 --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/sorting/BookSorter.spec.ts @@ -0,0 +1,89 @@ +import {describe, expect, it, vi} from 'vitest'; + +import {TranslocoService} from '@jsverse/transloco'; +import {CdkDragDrop} from '@angular/cdk/drag-drop'; + +import {SortDirection, SortOption} from '../../../model/sort.model'; +import {BookSorter} from './BookSorter'; + +describe('BookSorter', () => { + it('uses default labels when no transloco service is provided', () => { + const sorter = new BookSorter(() => undefined); + + expect(sorter.sortOptions[0]).toMatchObject({ + field: 'title', + label: 'Title', + direction: SortDirection.ASCENDING + }); + }); + + it('uses translated labels when transloco is available', () => { + const transloco = { + translate: vi.fn((key: string) => `translated:${key}`) + } as unknown as TranslocoService; + + const sorter = new BookSorter(() => undefined, transloco); + + expect(sorter.sortOptions[0].label).toBe('translated:book.sorting.options.title'); + }); + + it('supports legacy selectedSort getter and setter', () => { + const sorter = new BookSorter(() => undefined); + const sort: SortOption = {label: 'Title', field: 'title', direction: SortDirection.ASCENDING}; + + sorter.selectedSort = sort; + expect(sorter.selectedSort).toEqual(sort); + + sorter.selectedSort = undefined; + expect(sorter.selectedSortCriteria).toEqual([]); + }); + + it('sorts by a field and toggles the primary direction on repeat', () => { + const onSortChange = vi.fn(); + const sorter = new BookSorter(onSortChange); + + sorter.sortBooks('title'); + expect(sorter.selectedSortCriteria).toEqual([ + {label: 'Title', field: 'title', direction: SortDirection.ASCENDING} + ]); + + sorter.sortBooks('title'); + expect(sorter.selectedSortCriteria[0].direction).toBe(SortDirection.DESCENDING); + expect(onSortChange).toHaveBeenCalledTimes(2); + }); + + it('adds, removes, toggles, and reorders criteria', () => { + const onSortChange = vi.fn(); + const sorter = new BookSorter(onSortChange); + + sorter.addSortCriterion('title'); + sorter.addSortCriterion('author'); + sorter.addSortCriterion('title'); + expect(sorter.selectedSortCriteria.map((criterion) => criterion.field)).toEqual(['title', 'author']); + + sorter.toggleCriterionDirection(1); + expect(sorter.selectedSortCriteria[1].direction).toBe(SortDirection.DESCENDING); + + sorter.reorderCriteria({ + previousIndex: 1, + currentIndex: 0 + } as unknown as CdkDragDrop); + expect(sorter.selectedSortCriteria.map((criterion) => criterion.field)).toEqual(['author', 'title']); + + sorter.removeSortCriterion(0); + expect(sorter.selectedSortCriteria.map((criterion) => criterion.field)).toEqual(['title']); + }); + + it('omits already-used fields from available options and marks the primary icon', () => { + const sorter = new BookSorter(() => undefined); + + sorter.setSortCriteria([ + {label: 'Title', field: 'title', direction: SortDirection.ASCENDING} + ]); + + const titleOption = sorter.sortOptions.find((option) => option.field === 'title') as SortOption & {icon?: string}; + + expect(sorter.getAvailableSortOptions().some((option) => option.field === 'title')).toBe(false); + expect(titleOption.icon).toBe('pi pi-arrow-up'); + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/sorting/multi-sort-popover/multi-sort-popover.component.spec.ts b/frontend/src/app/features/book/components/book-browser/sorting/multi-sort-popover/multi-sort-popover.component.spec.ts new file mode 100644 index 000000000..14a1fb22e --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/sorting/multi-sort-popover/multi-sort-popover.component.spec.ts @@ -0,0 +1,9 @@ +import {describe, expect, it} from 'vitest'; + +// TODO(seam): This popover needs a PrimeNG overlay and drag-drop harness so the +// multi-sort reorder and apply flows can be tested against real emitted events. +describe.skip('MultiSortPopoverComponent', () => { + it('needs an overlay harness for drag-drop reorder and sort application flows', () => { + expect.hasAssertions(); + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/table-column-preference.service.spec.ts b/frontend/src/app/features/book/components/book-browser/table-column-preference.service.spec.ts new file mode 100644 index 000000000..180fd6a44 --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/table-column-preference.service.spec.ts @@ -0,0 +1,117 @@ +import {TestBed} from '@angular/core/testing'; +import {MessageService} from 'primeng/api'; +import {TranslocoService} from '@jsverse/transloco'; +import {vi, describe, beforeEach, afterEach, expect, it} from 'vitest'; + +import {TableColumnPreferenceService} from './table-column-preference.service'; +import {TableColumnPreference, UserService} from '../../../settings/user-management/user.service'; + +describe('TableColumnPreferenceService', () => { + let service: TableColumnPreferenceService; + let userService: { getCurrentUser: ReturnType; updateUserSetting: ReturnType }; + let messageService: { add: ReturnType }; + let translocoService: { translate: ReturnType }; + + beforeEach(() => { + userService = { + getCurrentUser: vi.fn(), + updateUserSetting: vi.fn() + }; + messageService = { + add: vi.fn() + }; + translocoService = { + translate: vi.fn((key: string) => `t:${key}`) + }; + + TestBed.configureTestingModule({ + providers: [ + TableColumnPreferenceService, + {provide: UserService, useValue: userService}, + {provide: MessageService, useValue: messageService}, + {provide: TranslocoService, useValue: translocoService} + ] + }); + + service = TestBed.inject(TableColumnPreferenceService); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('merges saved preferences with all available columns', () => { + const savedPrefs: TableColumnPreference[] = [ + {field: 'title', visible: false, order: 4}, + {field: 'authors', visible: true, order: 1}, + {field: 'fileName', visible: true, order: 0} + ]; + + service.initPreferences(savedPrefs); + + expect(service.preferences().find(pref => pref.field === 'title')).toEqual({ + field: 'title', + visible: false, + order: 4 + }); + expect(service.preferences().find(pref => pref.field === 'authors')).toEqual({ + field: 'authors', + visible: true, + order: 1 + }); + expect(service.allColumns[0]).toEqual({ + field: 'readStatus', + header: 't:book.columnPref.columns.readStatus' + }); + expect(service.visibleColumns.map(column => column.field).slice(0, 2)).toEqual(['readStatus', 'fileName']); + }); + + it('falls back to defaults when no saved preferences exist', () => { + service.initPreferences(undefined); + + expect(service.preferences().length).toBe(service.allColumns.length); + expect(service.visibleColumns[0]).toEqual({ + field: 'readStatus', + header: 't:book.columnPref.columns.readStatus' + }); + }); + + it('skips persistence when there is no current user', () => { + userService.getCurrentUser.mockReturnValue(null); + + service.saveVisibleColumns([{field: 'title'}]); + + expect(userService.updateUserSetting).not.toHaveBeenCalled(); + expect(messageService.add).not.toHaveBeenCalled(); + expect(service.preferences().find(pref => pref.field === 'title')).toEqual({ + field: 'title', + visible: true, + order: 0 + }); + }); + + it('saves preferences and shows a success toast for the current user', () => { + userService.getCurrentUser.mockReturnValue({id: 42}); + + service.saveVisibleColumns([{field: 'title'}, {field: 'authors'}]); + + expect(userService.updateUserSetting).toHaveBeenCalledWith(42, 'tableColumnPreference', expect.any(Array)); + const savedPrefs = userService.updateUserSetting.mock.calls[0][2] as TableColumnPreference[]; + expect(savedPrefs.find(pref => pref.field === 'title')).toEqual({ + field: 'title', + visible: true, + order: 0 + }); + expect(savedPrefs.find(pref => pref.field === 'authors')).toEqual({ + field: 'authors', + visible: true, + order: 1 + }); + expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'success', + summary: 't:book.columnPref.toast.savedSummary', + detail: 't:book.columnPref.toast.savedDetail', + life: 1500 + })); + }); +}); diff --git a/frontend/src/app/features/book/components/book-card-lite/book-card-lite-component.spec.ts b/frontend/src/app/features/book/components/book-card-lite/book-card-lite-component.spec.ts new file mode 100644 index 000000000..886fa2b75 --- /dev/null +++ b/frontend/src/app/features/book/components/book-card-lite/book-card-lite-component.spec.ts @@ -0,0 +1,115 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {Router} from '@angular/router'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {BookMetadataHostService} from '../../../../shared/service/book-metadata-host.service'; +import {UrlHelperService} from '../../../../shared/service/url-helper.service'; +import {Book} from '../../model/book.model'; +import {BookCardLiteComponent} from './book-card-lite-component'; +import {UserService} from '../../../settings/user-management/user.service'; + +describe('BookCardLiteComponent', () => { + let fixture: ComponentFixture; + let component: BookCardLiteComponent; + let router: {navigate: ReturnType}; + let urlHelper: { + getThumbnailUrl: ReturnType; + getAudiobookThumbnailUrl: ReturnType; + }; + let userService: {currentUser: ReturnType}; + let hostService: {requestBookSwitch: ReturnType}; + + beforeEach(async () => { + router = {navigate: vi.fn()}; + urlHelper = { + getThumbnailUrl: vi.fn(() => '/covers/1'), + getAudiobookThumbnailUrl: vi.fn(() => '/covers/audio/1'), + }; + userService = { + currentUser: vi.fn(() => ({userSettings: {metadataCenterViewMode: 'route'}})), + }; + hostService = { + requestBookSwitch: vi.fn(), + }; + + await TestBed.configureTestingModule({ + imports: [BookCardLiteComponent], + providers: [ + {provide: Router, useValue: router}, + {provide: UrlHelperService, useValue: urlHelper}, + {provide: UserService, useValue: userService}, + {provide: BookMetadataHostService, useValue: hostService}, + ], + }).compileComponents(); + + fixture = TestBed.createComponent(BookCardLiteComponent); + component = fixture.componentInstance; + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('treats a book as audiobook-only when no non-audiobook alternative format exists', () => { + component.book = buildBook({ + primaryFile: {id: 10, bookId: 1, bookType: 'AUDIOBOOK'}, + alternativeFormats: [{id: 11, bookId: 1, bookType: 'AUDIOBOOK'}], + }); + + expect(component.isAudiobookOnly()).toBe(true); + expect(component.getThumbnailUrl()).toBe('/covers/audio/1'); + expect(urlHelper.getAudiobookThumbnailUrl).toHaveBeenCalledWith(1, '2026-01-02'); + }); + + it('uses the standard thumbnail when the book has an ebook format available', () => { + component.book = buildBook({ + primaryFile: {id: 10, bookId: 1, bookType: 'AUDIOBOOK'}, + alternativeFormats: [{id: 11, bookId: 1, bookType: 'EPUB'}], + }); + + expect(component.isAudiobookOnly()).toBe(false); + expect(component.getThumbnailUrl()).toBe('/covers/1'); + expect(urlHelper.getThumbnailUrl).toHaveBeenCalledWith(1, '2026-01-01'); + }); + + it('navigates to the route-based metadata center when that mode is active', () => { + const book = buildBook(); + + component.openBookInfo(book); + + expect(router.navigate).toHaveBeenCalledWith(['/book', 1], { + queryParams: {tab: 'view'} + }); + expect(hostService.requestBookSwitch).not.toHaveBeenCalled(); + }); + + it('delegates to the metadata host when the user prefers dialog mode', () => { + userService.currentUser.mockReturnValue({userSettings: {metadataCenterViewMode: 'dialog'}}); + const book = buildBook(); + + component.openBookInfo(book); + + expect(hostService.requestBookSwitch).toHaveBeenCalledWith(1); + expect(router.navigate).not.toHaveBeenCalled(); + }); +}); + +function buildBook(overrides: Partial = {}): Book { + return { + id: 1, + fileName: 'Example Book', + metadata: { + title: 'Example Book', + coverUpdatedOn: '2026-01-01', + audiobookCoverUpdatedOn: '2026-01-02', + ...overrides.metadata, + }, + primaryFile: { + id: 10, + bookType: 'EPUB', + ...overrides.primaryFile, + }, + alternativeFormats: overrides.alternativeFormats ?? [], + ...overrides, + } as Book; +} diff --git a/frontend/src/app/features/book/components/book-file-attacher/book-file-attacher.component.spec.ts b/frontend/src/app/features/book/components/book-file-attacher/book-file-attacher.component.spec.ts new file mode 100644 index 000000000..058acb3a2 --- /dev/null +++ b/frontend/src/app/features/book/components/book-file-attacher/book-file-attacher.component.spec.ts @@ -0,0 +1,259 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {TranslocoService} from '@jsverse/transloco'; +import {MessageService} from 'primeng/api'; +import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; +import {describe, expect, it, vi} from 'vitest'; +import {Observable, of, throwError} from 'rxjs'; +import {Book} from '../../model/book.model'; +import {BookFileService} from '../../service/book-file.service'; +import {BookService} from '../../service/book.service'; +import {BookFileAttacherComponent} from './book-file-attacher.component'; +import {AppSettingsService} from '../../../../shared/service/app-settings.service'; + +interface DialogData { + sourceBook?: Book; + sourceBooks?: Book[]; +} + +type AppSettingsLike = { + metadataPersistenceSettings?: { + moveFilesToLibraryPattern?: boolean; + }; +} | null; + +function buildBook(overrides: Partial = {}): Book { + const id = overrides.id ?? 1; + return { + id, + libraryId: overrides.libraryId ?? 10, + libraryName: overrides.libraryName ?? 'Main Library', + metadata: overrides.metadata ?? { + bookId: id, + title: `Book ${id}`, + authors: [`Author ${id}`], + }, + primaryFile: overrides.primaryFile, + ...overrides, + }; +} + +function setup(options: { + dialogData?: DialogData; + books?: Book[]; + appSettings?: AppSettingsLike; + attachResult?: Observable<{updatedBook: Book; deletedSourceBookIds: number[]}>; +} = {}) { + const dialogRef = { + close: vi.fn(), + }; + const config = { + data: options.dialogData ?? {}, + }; + const booksSignal = signal(options.books ?? []); + const bookFileService = { + attachBookFiles: vi.fn().mockReturnValue( + options.attachResult ?? of({updatedBook: buildBook({id: 999}), deletedSourceBookIds: []}) + ), + }; + const appSettingsService = { + appSettings: vi.fn(() => options.appSettings ?? null), + }; + const translocoService = { + translate: vi.fn((key: string) => key), + }; + const messageService = { + add: vi.fn(), + }; + + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + {provide: DynamicDialogRef, useValue: dialogRef}, + {provide: DynamicDialogConfig, useValue: config}, + {provide: BookService, useValue: {books: booksSignal}}, + {provide: BookFileService, useValue: bookFileService}, + {provide: AppSettingsService, useValue: appSettingsService}, + {provide: TranslocoService, useValue: translocoService}, + {provide: MessageService, useValue: messageService}, + ], + }); + + const component = TestBed.runInInjectionContext(() => new BookFileAttacherComponent()); + + return { + component, + dialogRef, + bookFileService, + appSettingsService, + translocoService, + booksSignal, + }; +} + +describe('BookFileAttacherComponent', () => { + it('bootstraps a single source book, filters candidates by library/source ids, and applies the moveFiles setting', () => { + const sourceBook = buildBook({id: 1, libraryId: 7, metadata: {bookId: 1, title: 'Source', authors: ['Origin']}}); + const siblingCandidate = buildBook({id: 2, libraryId: 7, metadata: {bookId: 2, title: 'Sibling', authors: ['Match']}}); + const foreignLibraryBook = buildBook({id: 3, libraryId: 99, metadata: {bookId: 3, title: 'Foreign', authors: ['Other']}}); + const {component} = setup({ + dialogData: {sourceBook}, + books: [sourceBook, siblingCandidate, foreignLibraryBook], + appSettings: { + metadataPersistenceSettings: { + moveFilesToLibraryPattern: true, + }, + }, + }); + + component.ngOnInit(); + + expect(component.sourceBooks).toEqual([sourceBook]); + expect(component.isBulkMode).toBe(false); + expect(component.moveFiles).toBe(true); + expect(component.filteredBooks).toEqual([siblingCandidate]); + }); + + it('bootstraps bulk mode from sourceBooks and defaults moveFiles to false when settings are unavailable', () => { + const sourceA = buildBook({id: 10, libraryId: 4}); + const sourceB = buildBook({id: 11, libraryId: 4}); + const target = buildBook({id: 12, libraryId: 4}); + const {component} = setup({ + dialogData: {sourceBooks: [sourceA, sourceB]}, + books: [sourceA, sourceB, target], + appSettings: null, + }); + + component.ngOnInit(); + + expect(component.sourceBooks).toEqual([sourceA, sourceB]); + expect(component.isBulkMode).toBe(true); + expect(component.moveFiles).toBe(false); + expect(component.filteredBooks).toEqual([target]); + }); + + it('closes immediately when no source payload is provided', () => { + const {component, dialogRef, appSettingsService} = setup({ + dialogData: {}, + books: [buildBook({id: 20})], + }); + + component.ngOnInit(); + + expect(dialogRef.close).toHaveBeenCalledOnce(); + expect(dialogRef.close).toHaveBeenCalledWith(); + expect(appSettingsService.appSettings).not.toHaveBeenCalled(); + }); + + it('filters candidate books by title and author and resets blank queries to the first twenty matches', () => { + const sourceBook = buildBook({id: 1, libraryId: 5, metadata: {bookId: 1, title: 'Source', authors: ['Keeper']}}); + const matchingByTitle = buildBook({id: 2, libraryId: 5, metadata: {bookId: 2, title: 'Dune Messiah', authors: ['Frank Herbert']}}); + const matchingByAuthor = buildBook({id: 3, libraryId: 5, metadata: {bookId: 3, title: 'Fahrenheit 451', authors: ['Ray Bradbury']}}); + const fillerBooks = Array.from({length: 25}, (_, index) => + buildBook({ + id: index + 10, + libraryId: 5, + metadata: {bookId: index + 10, title: `Candidate ${index}`, authors: [`Writer ${index}`]}, + }) + ); + const {component} = setup({ + dialogData: {sourceBook}, + books: [sourceBook, matchingByTitle, matchingByAuthor, ...fillerBooks], + }); + + component.ngOnInit(); + + expect(component.filteredBooks).toHaveLength(20); + + component.filterBooks({query: ' dune '}); + expect(component.filteredBooks).toEqual([matchingByTitle]); + + component.filterBooks({query: 'bradbury'}); + expect(component.filteredBooks).toEqual([matchingByAuthor]); + + component.filterBooks({query: ' '}); + expect(component.filteredBooks).toHaveLength(20); + expect(component.filteredBooks[0]).toEqual(matchingByTitle); + }); + + it('handles lightweight selection events and formats display helpers with fallbacks', () => { + const selectedBook = buildBook({ + id: 30, + metadata: {bookId: 30, title: 'The Left Hand of Darkness', authors: ['Ursula K. Le Guin', 'Guest Author']}, + primaryFile: {id: 301, bookId: 30, extension: 'epub', fileName: 'left-hand.epub'}, + }); + const untitledBook = buildBook({id: 31, metadata: undefined, primaryFile: undefined}); + const {component, translocoService} = setup(); + + component.onBookSelect({value: selectedBook} as never); + expect(component.targetBook).toEqual(selectedBook); + + component.onBookClear(); + expect(component.targetBook).toBeNull(); + + expect(component.getBookDisplayName(selectedBook)).toBe('The Left Hand of Darkness - Ursula K. Le Guin, Guest Author'); + expect(component.getBookDisplayName(untitledBook)).toBe('Book #31'); + expect(component.getSourceFileInfo(selectedBook)).toBe('EPUB - left-hand.epub'); + expect(component.getSourceFileInfo(untitledBook)).toBe('book.fileAttacher.unknownFile'); + expect(translocoService.translate).toHaveBeenCalledWith('book.fileAttacher.unknownFile'); + }); + + it('uses the target selection and defaulted moveFiles value when attach succeeds', () => { + const sourceBook = buildBook({id: 40, libraryId: 8}); + const targetBook = buildBook({id: 41, libraryId: 8}); + const {component, bookFileService, dialogRef} = setup({ + dialogData: {sourceBook}, + books: [sourceBook, targetBook], + appSettings: null, + }); + + component.ngOnInit(); + component.targetBook = targetBook; + + component.attach(); + + expect(bookFileService.attachBookFiles).toHaveBeenCalledWith(41, [40], false); + expect(dialogRef.close).toHaveBeenCalledWith({success: true}); + }); + + it('resets attaching state when attach fails and preserves the dialog', () => { + const sourceBook = buildBook({id: 50, libraryId: 9}); + const targetBook = buildBook({id: 51, libraryId: 9}); + const {component, bookFileService, dialogRef} = setup({ + dialogData: {sourceBook}, + books: [sourceBook, targetBook], + appSettings: { + metadataPersistenceSettings: { + moveFilesToLibraryPattern: true, + }, + }, + attachResult: throwError(() => new Error('attach failed')), + }); + + component.ngOnInit(); + component.targetBook = targetBook; + + component.attach(); + + expect(bookFileService.attachBookFiles).toHaveBeenCalledWith(51, [50], true); + expect(component.isAttaching).toBe(false); + expect(dialogRef.close).not.toHaveBeenCalled(); + }); + + it('does not attach without a target book and exposes direct close behavior', () => { + const sourceBook = buildBook({id: 60}); + const {component, bookFileService, dialogRef} = setup({ + dialogData: {sourceBook}, + books: [sourceBook], + }); + + component.ngOnInit(); + component.attach(); + component.closeDialog(); + + expect(component.canAttach()).toBe(false); + expect(bookFileService.attachBookFiles).not.toHaveBeenCalled(); + expect(dialogRef.close).toHaveBeenCalledOnce(); + expect(dialogRef.close).toHaveBeenCalledWith(); + }); +}); diff --git a/frontend/src/app/features/book/components/book-notes/book-notes-component.spec.ts b/frontend/src/app/features/book/components/book-notes/book-notes-component.spec.ts new file mode 100644 index 000000000..ba3422d16 --- /dev/null +++ b/frontend/src/app/features/book/components/book-notes/book-notes-component.spec.ts @@ -0,0 +1,325 @@ +import {TestBed} from '@angular/core/testing'; +import {of, throwError} from 'rxjs'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {ConfirmationService, MessageService} from 'primeng/api'; +import {TranslocoService} from '@jsverse/transloco'; + +import {BookNote, BookNoteService} from '../../../../shared/service/book-note.service'; +import {BookNotesComponent} from './book-notes-component'; + +interface ConfirmationLike { + key?: string; + message?: string; + header?: string; + accept?: () => void; +} + +function createNote(id: number, overrides: Partial = {}): BookNote { + return { + id, + userId: 7, + bookId: 42, + title: `Note ${id}`, + content: `Content ${id}`, + createdAt: '2026-03-28T09:00:00.000Z', + updatedAt: `2026-03-28T09:0${id}:00.000Z`, + ...overrides, + }; +} + +describe('BookNotesComponent', () => { + let component: BookNotesComponent; + let bookNoteService: { + getNotesForBook: ReturnType; + createOrUpdateNote: ReturnType; + deleteNote: ReturnType; + }; + let messageService: { + add: ReturnType; + }; + let confirmationService: { + confirm: ReturnType; + }; + let translate: ReturnType; + let lastConfirmation: ConfirmationLike | null; + + function createComponent(): BookNotesComponent { + return TestBed.runInInjectionContext(() => new BookNotesComponent()); + } + + beforeEach(() => { + lastConfirmation = null; + bookNoteService = { + getNotesForBook: vi.fn(), + createOrUpdateNote: vi.fn(), + deleteNote: vi.fn(), + }; + messageService = { + add: vi.fn(), + }; + confirmationService = { + confirm: vi.fn((confirmation: ConfirmationLike) => { + lastConfirmation = confirmation; + }), + }; + translate = vi.fn((key: string, params?: Record) => ( + params ? `${key}:${JSON.stringify(params)}` : key + )); + + TestBed.configureTestingModule({ + providers: [ + {provide: BookNoteService, useValue: bookNoteService}, + {provide: ConfirmationService, useValue: confirmationService}, + {provide: MessageService, useValue: messageService}, + {provide: TranslocoService, useValue: {translate}}, + ], + }); + + component = createComponent(); + component.bookId = 42; + }); + + it('skips loading notes when no book is selected', () => { + component.bookId = 0; + + component.loadNotes(); + + expect(bookNoteService.getNotesForBook).not.toHaveBeenCalled(); + expect(component.loading).toBe(false); + }); + + it('loads notes and orders them by most recent update first', () => { + const oldest = createNote(1, {updatedAt: '2026-03-28T08:00:00.000Z'}); + const newest = createNote(2, {updatedAt: '2026-03-28T12:00:00.000Z'}); + const middle = createNote(3, {updatedAt: '2026-03-28T10:00:00.000Z'}); + bookNoteService.getNotesForBook.mockReturnValue(of([oldest, newest, middle])); + + component.loadNotes(); + + expect(bookNoteService.getNotesForBook).toHaveBeenCalledWith(42); + expect(component.notes.map(note => note.id)).toEqual([2, 3, 1]); + expect(component.loading).toBe(false); + }); + + it('shows an error toast when loading notes fails', () => { + bookNoteService.getNotesForBook.mockReturnValue(throwError(() => new Error('load failed'))); + + component.loadNotes(); + + expect(component.loading).toBe(false); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'common.error', + detail: 'book.notes.toast.loadFailedDetail', + }); + }); + + it('blocks note creation when title or content is blank after trimming', () => { + component.newNote = { + bookId: 42, + title: ' ', + content: ' ', + }; + + component.createNote(); + + expect(bookNoteService.createOrUpdateNote).not.toHaveBeenCalled(); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'warn', + summary: 'book.notes.toast.validationSummary', + detail: 'book.notes.toast.validationDetail', + }); + }); + + it('creates a note and closes the create dialog on success', () => { + const createdNote = createNote(9, {title: 'Created', content: 'Fresh content'}); + component.notes = [createNote(1)]; + component.showCreateDialog = true; + component.newNote = { + bookId: 42, + title: 'Created', + content: 'Fresh content', + }; + bookNoteService.createOrUpdateNote.mockReturnValue(of(createdNote)); + + component.createNote(); + + expect(bookNoteService.createOrUpdateNote).toHaveBeenCalledWith(component.newNote); + expect(component.notes[0]).toEqual(createdNote); + expect(component.showCreateDialog).toBe(false); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'common.success', + detail: 'book.notes.toast.createSuccessDetail', + }); + }); + + it('shows an error toast when note creation fails', () => { + component.showCreateDialog = true; + component.newNote = { + bookId: 42, + title: 'Created', + content: 'Fresh content', + }; + bookNoteService.createOrUpdateNote.mockReturnValue(throwError(() => new Error('create failed'))); + + component.createNote(); + + expect(component.showCreateDialog).toBe(true); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'common.error', + detail: 'book.notes.toast.createFailedDetail', + }); + }); + + it('blocks note updates when title or content is blank after trimming', () => { + component.editNote = { + id: 4, + bookId: 42, + title: ' ', + content: ' ', + }; + + component.updateNote(); + + expect(bookNoteService.createOrUpdateNote).not.toHaveBeenCalled(); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'warn', + summary: 'book.notes.toast.validationSummary', + detail: 'book.notes.toast.validationDetail', + }); + }); + + it('updates an existing note, resorts the list, and clears edit state on success', () => { + const staleNote = createNote(1, {updatedAt: '2026-03-28T08:00:00.000Z', title: 'Old title'}); + const selectedNote = createNote(2, {updatedAt: '2026-03-28T10:00:00.000Z', title: 'Before edit'}); + const updatedNote = createNote(2, { + updatedAt: '2026-03-28T14:00:00.000Z', + title: 'After edit', + content: 'Updated body', + }); + component.notes = [staleNote, selectedNote]; + component.selectedNote = selectedNote; + component.showEditDialog = true; + component.editNote = { + id: 2, + bookId: 42, + title: 'After edit', + content: 'Updated body', + }; + bookNoteService.createOrUpdateNote.mockReturnValue(of(updatedNote)); + + component.updateNote(); + + expect(bookNoteService.createOrUpdateNote).toHaveBeenCalledWith(component.editNote); + expect(component.notes.map(note => note.id)).toEqual([2, 1]); + expect(component.notes[0]).toEqual(updatedNote); + expect(component.showEditDialog).toBe(false); + expect(component.selectedNote).toBeNull(); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'common.success', + detail: 'book.notes.toast.updateSuccessDetail', + }); + }); + + it('shows an error toast when updating a note fails', () => { + const selectedNote = createNote(2, {title: 'Before edit'}); + component.selectedNote = selectedNote; + component.showEditDialog = true; + component.editNote = { + id: 2, + bookId: 42, + title: 'After edit', + content: 'Updated body', + }; + bookNoteService.createOrUpdateNote.mockReturnValue(throwError(() => new Error('update failed'))); + + component.updateNote(); + + expect(component.showEditDialog).toBe(true); + expect(component.selectedNote).toEqual(selectedNote); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'common.error', + detail: 'book.notes.toast.updateFailedDetail', + }); + }); + + it('confirms note deletion and removes the note when the accept callback succeeds', () => { + const keepNote = createNote(1); + const deleteCandidate = createNote(2, {title: 'Delete me'}); + component.notes = [keepNote, deleteCandidate]; + bookNoteService.deleteNote.mockReturnValue(of(void 0)); + + component.deleteNote(deleteCandidate); + lastConfirmation?.accept?.(); + + expect(confirmationService.confirm).toHaveBeenCalledOnce(); + expect(lastConfirmation).toMatchObject({ + key: 'deleteNote', + header: 'book.notes.confirm.deleteHeader', + message: 'book.notes.confirm.deleteMessage:{"title":"Delete me"}', + }); + expect(bookNoteService.deleteNote).toHaveBeenCalledWith(2); + expect(component.notes).toEqual([keepNote]); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'common.success', + detail: 'book.notes.toast.deleteSuccessDetail', + }); + }); + + it('shows an error toast when the confirmed delete fails', () => { + const note = createNote(3, {title: 'Delete me'}); + component.notes = [note]; + bookNoteService.deleteNote.mockReturnValue(throwError(() => new Error('delete failed'))); + + component.deleteNote(note); + lastConfirmation?.accept?.(); + + expect(bookNoteService.deleteNote).toHaveBeenCalledWith(3); + expect(component.notes).toEqual([note]); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'common.error', + detail: 'book.notes.toast.deleteFailedDetail', + }); + }); + + it('resets create and edit state when dialogs are cancelled', () => { + const selectedNote = createNote(4); + component.showCreateDialog = true; + component.newNote = { + bookId: 42, + title: 'Draft title', + content: 'Draft content', + }; + component.showEditDialog = true; + component.selectedNote = selectedNote; + component.editNote = { + id: selectedNote.id, + bookId: 42, + title: 'Edited title', + content: 'Edited content', + }; + + component.cancelCreate(); + component.cancelEdit(); + + expect(component.showCreateDialog).toBe(false); + expect(component.newNote).toEqual({ + bookId: 42, + title: '', + content: '', + }); + expect(component.showEditDialog).toBe(false); + expect(component.selectedNote).toBeNull(); + expect(component.editNote).toEqual({ + bookId: 42, + title: '', + content: '', + }); + }); +}); diff --git a/frontend/src/app/features/book/components/book-reviews/book-review-service.spec.ts b/frontend/src/app/features/book/components/book-reviews/book-review-service.spec.ts new file mode 100644 index 000000000..97b568e1f --- /dev/null +++ b/frontend/src/app/features/book/components/book-reviews/book-review-service.spec.ts @@ -0,0 +1,72 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {BookReviewService} from './book-review-service'; + +describe('BookReviewService', () => { + let service: BookReviewService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + BookReviewService, + ], + }); + + service = TestBed.inject(BookReviewService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('loads reviews for a specific book', () => { + let responseBody: unknown; + + service.getByBookId(7).subscribe(response => { + responseBody = response; + }); + + const request = httpTestingController.expectOne(req => + req.method === 'GET' && req.url.endsWith('/api/v1/reviews/book/7') + ); + request.flush([{id: 1, title: 'Great review'}]); + + expect(responseBody).toEqual([{id: 1, title: 'Great review'}]); + }); + + it('refreshes reviews through the refresh endpoint', () => { + service.refreshReviews(9).subscribe(); + + const request = httpTestingController.expectOne(req => + req.method === 'POST' && req.url.endsWith('/api/v1/reviews/book/9/refresh') + ); + expect(request.request.body).toEqual({}); + request.flush([{id: 3, title: 'Fresh review'}]); + }); + + it('deletes a single review by id', () => { + service.delete(11).subscribe(); + + const request = httpTestingController.expectOne(req => + req.method === 'DELETE' && req.url.endsWith('/api/v1/reviews/11') + ); + request.flush(null); + }); + + it('deletes all reviews for a book', () => { + service.deleteAllByBookId(12).subscribe(); + + const request = httpTestingController.expectOne(req => + req.method === 'DELETE' && req.url.endsWith('/api/v1/reviews/book/12') + ); + request.flush(null); + }); +}); diff --git a/frontend/src/app/features/book/components/book-reviews/book-reviews.component.spec.ts b/frontend/src/app/features/book/components/book-reviews/book-reviews.component.spec.ts new file mode 100644 index 000000000..fa60eb039 --- /dev/null +++ b/frontend/src/app/features/book/components/book-reviews/book-reviews.component.spec.ts @@ -0,0 +1,342 @@ +import {SimpleChange} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {of, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {ConfirmationService, MessageService} from 'primeng/api'; +import {TranslocoService} from '@jsverse/transloco'; + +import {BookService} from '../../service/book.service'; +import {BookMetadataManageService} from '../../service/book-metadata-manage.service'; +import {AppSettingsService} from '../../../../shared/service/app-settings.service'; +import {UserService} from '../../../settings/user-management/user.service'; +import {BookReview, BookReviewService} from './book-review-service'; +import {BookReviewsComponent} from './book-reviews.component'; + +interface ConfirmationLike { + message?: string; + header?: string; + accept?: () => void; +} + +function createReview(id: number, overrides: Partial = {}): BookReview { + return { + id, + metadataProvider: 'goodreads', + reviewerName: `Reviewer ${id}`, + title: `Review ${id}`, + rating: 4, + date: `2026-03-${String(id).padStart(2, '0')}T12:00:00.000Z`, + body: `Review body ${id}`, + country: 'US', + spoiler: false, + followersCount: 10, + textReviewsCount: 20, + ...overrides, + }; +} + +describe('BookReviewsComponent', () => { + let component: BookReviewsComponent; + let reviewService: { + getByBookId: ReturnType; + refreshReviews: ReturnType; + delete: ReturnType; + deleteAllByBookId: ReturnType; + }; + let bookService: { + findBookById: ReturnType; + }; + let bookMetadataManageService: { + toggleFieldLocks: ReturnType; + }; + let confirmationService: { + confirm: ReturnType; + }; + let messageService: { + add: ReturnType; + }; + let userService: { + currentUser: ReturnType; + }; + let appSettingsService: { + appSettings: ReturnType; + }; + let translate: ReturnType; + let lastConfirmation: ConfirmationLike | null; + + function createComponent(): BookReviewsComponent { + return TestBed.runInInjectionContext(() => new BookReviewsComponent()); + } + + beforeEach(() => { + lastConfirmation = null; + reviewService = { + getByBookId: vi.fn(), + refreshReviews: vi.fn(), + delete: vi.fn(), + deleteAllByBookId: vi.fn(), + }; + bookService = { + findBookById: vi.fn(), + }; + bookMetadataManageService = { + toggleFieldLocks: vi.fn(), + }; + confirmationService = { + confirm: vi.fn((confirmation: ConfirmationLike) => { + lastConfirmation = confirmation; + }), + }; + messageService = { + add: vi.fn(), + }; + userService = { + currentUser: vi.fn(() => ({ + permissions: { + admin: false, + canEditMetadata: true, + }, + })), + }; + appSettingsService = { + appSettings: vi.fn(() => ({ + metadataPublicReviewsSettings: { + downloadEnabled: false, + }, + })), + }; + translate = vi.fn((key: string, params?: Record) => ( + params ? `${key}:${JSON.stringify(params)}` : key + )); + + TestBed.configureTestingModule({ + providers: [ + {provide: BookReviewService, useValue: reviewService}, + {provide: BookService, useValue: bookService}, + {provide: BookMetadataManageService, useValue: bookMetadataManageService}, + {provide: ConfirmationService, useValue: confirmationService}, + {provide: MessageService, useValue: messageService}, + {provide: UserService, useValue: userService}, + {provide: AppSettingsService, useValue: appSettingsService}, + {provide: TranslocoService, useValue: {translate}}, + ], + }); + + component = createComponent(); + component.bookId = 42; + }); + + afterEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + it('loads reviews on book changes, sorts them by date, and mirrors the current lock state', () => { + const undated = createReview(1, {date: undefined}); + const oldest = createReview(2, {date: '2026-03-02T12:00:00.000Z'}); + const newest = createReview(3, {date: '2026-03-03T12:00:00.000Z'}); + reviewService.getByBookId.mockReturnValue(of([oldest, undated, newest])); + bookService.findBookById.mockReturnValue({ + metadata: { + reviewsLocked: true, + }, + }); + + component.ngOnChanges({ + bookId: new SimpleChange(undefined, 42, true), + }); + TestBed.flushEffects(); + + expect(bookService.findBookById).toHaveBeenCalledWith(42); + expect(reviewService.getByBookId).toHaveBeenCalledWith(42); + expect(component.reviews?.map(review => review.id)).toEqual([3, 2, 1]); + expect(component.reviewsLocked).toBe(true); + expect(component.loading).toBe(false); + }); + + it('refreshes reviews, clears revealed spoilers, and shows a success toast', () => { + const spoilerReview = createReview(5, {spoiler: true, date: '2026-03-05T12:00:00.000Z'}); + const plainReview = createReview(4, {date: '2026-03-04T12:00:00.000Z'}); + reviewService.refreshReviews.mockReturnValue(of([plainReview, spoilerReview])); + component.revealedSpoilers.add(spoilerReview.id!); + component.allSpoilersRevealed = true; + + component.fetchNewReviews(); + + expect(reviewService.refreshReviews).toHaveBeenCalledWith(42); + expect(component.reviews?.map(review => review.id)).toEqual([5, 4]); + expect(component.revealedSpoilers.size).toBe(0); + expect(component.allSpoilersRevealed).toBe(false); + expect(component.loading).toBe(false); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'book.reviews.toast.reviewsUpdatedSummary', + detail: 'book.reviews.toast.reviewsUpdatedDetail', + life: 3000, + }); + }); + + it('shows an error toast when refreshing reviews fails', () => { + const error = new Error('refresh failed'); + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined); + reviewService.refreshReviews.mockReturnValue(throwError(() => error)); + + component.fetchNewReviews(); + + expect(errorSpy).toHaveBeenCalledWith('Failed to fetch new reviews:', error); + expect(component.loading).toBe(false); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'book.reviews.toast.fetchFailedSummary', + detail: 'book.reviews.toast.fetchFailedDetail', + life: 3000, + }); + }); + + it('confirms single-review deletion, removes the review, and recomputes spoiler state', () => { + const keepReview = createReview(1, {spoiler: false}); + const deleteReview = createReview(2, {spoiler: true}); + reviewService.delete.mockReturnValue(of(void 0)); + component.reviews = [keepReview, deleteReview]; + component.revealedSpoilers.add(deleteReview.id!); + component.allSpoilersRevealed = true; + + component.deleteReview(deleteReview); + lastConfirmation?.accept?.(); + + expect(confirmationService.confirm).toHaveBeenCalledOnce(); + expect(lastConfirmation).toMatchObject({ + message: 'book.reviews.confirm.deleteMessage:{"reviewer":"Reviewer 2"}', + header: 'book.reviews.confirm.deleteHeader', + }); + expect(reviewService.delete).toHaveBeenCalledWith(2); + expect(component.reviews).toEqual([keepReview]); + expect(component.allSpoilersRevealed).toBe(false); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'book.reviews.toast.deleteSuccessSummary', + detail: 'book.reviews.toast.deleteSuccessDetail', + life: 2000, + }); + }); + + it('confirms deleting all reviews and clears state after the accept callback succeeds', () => { + const firstReview = createReview(7, {spoiler: true}); + const secondReview = createReview(8, {spoiler: false}); + reviewService.deleteAllByBookId.mockReturnValue(of(void 0)); + component.reviews = [firstReview, secondReview]; + component.revealedSpoilers.add(firstReview.id!); + component.allSpoilersRevealed = true; + + component.deleteAllReviews(); + lastConfirmation?.accept?.(); + + expect(confirmationService.confirm).toHaveBeenCalledOnce(); + expect(lastConfirmation).toMatchObject({ + message: 'book.reviews.confirm.deleteAllMessage:{"count":2}', + header: 'book.reviews.confirm.deleteAllHeader', + }); + expect(reviewService.deleteAllByBookId).toHaveBeenCalledWith(42); + expect(component.reviews).toEqual([]); + expect(component.revealedSpoilers.size).toBe(0); + expect(component.allSpoilersRevealed).toBe(false); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'book.reviews.toast.allDeletedSummary', + detail: 'book.reviews.toast.allDeletedDetail', + life: 3000, + }); + }); + + it('sends lock and unlock actions through the metadata service and reports the result', () => { + bookMetadataManageService.toggleFieldLocks.mockReturnValue(of(void 0)); + + component.reviewsLocked = false; + component.toggleReviewsLock(); + + component.reviewsLocked = true; + component.toggleReviewsLock(); + + expect(bookMetadataManageService.toggleFieldLocks).toHaveBeenNthCalledWith(1, [42], { + reviewsLocked: 'LOCK', + }); + expect(bookMetadataManageService.toggleFieldLocks).toHaveBeenNthCalledWith(2, [42], { + reviewsLocked: 'UNLOCK', + }); + expect(messageService.add).toHaveBeenNthCalledWith(1, { + severity: 'info', + summary: 'book.reviews.toast.lockedSummary', + detail: 'book.reviews.toast.lockedDetail', + life: 3000, + }); + expect(messageService.add).toHaveBeenNthCalledWith(2, { + severity: 'info', + summary: 'book.reviews.toast.unlockedSummary', + detail: 'book.reviews.toast.unlockedDetail', + life: 3000, + }); + }); + + it('shows an error toast when lock toggling fails', () => { + const error = new Error('toggle failed'); + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined); + bookMetadataManageService.toggleFieldLocks.mockReturnValue(throwError(() => error)); + + component.toggleReviewsLock(); + + expect(bookMetadataManageService.toggleFieldLocks).toHaveBeenCalledWith([42], { + reviewsLocked: 'LOCK', + }); + expect(errorSpy).toHaveBeenCalledWith('Failed to toggle lock status:', error); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'book.reviews.toast.lockFailedSummary', + detail: 'book.reviews.toast.lockFailedDetail', + life: 3000, + }); + }); + + it('tracks spoiler visibility for individual and bulk reveal flows', () => { + const firstSpoiler = createReview(9, {spoiler: true}); + const secondSpoiler = createReview(10, {spoiler: true}); + const nonSpoiler = createReview(11, {spoiler: false}); + component.reviews = [firstSpoiler, secondSpoiler, nonSpoiler]; + + component.revealSpoiler(firstSpoiler.id!); + expect(component.isSpoilerRevealed(firstSpoiler.id!)).toBe(true); + expect(component.allSpoilersRevealed).toBe(false); + + component.toggleSpoilerVisibility(); + expect(component.isSpoilerRevealed(secondSpoiler.id!)).toBe(true); + expect(component.allSpoilersRevealed).toBe(true); + + component.toggleSpoilerVisibility(); + expect(component.revealedSpoilers.size).toBe(0); + expect(component.allSpoilersRevealed).toBe(false); + }); + + it('toggles sort order and reorders dated and undated reviews accordingly', () => { + const newest = createReview(12, {date: '2026-03-12T12:00:00.000Z'}); + const oldest = createReview(13, {date: '2026-03-01T12:00:00.000Z'}); + const undated = createReview(14, {date: undefined}); + component.reviews = [newest, undated, oldest]; + + component.toggleSortOrder(); + expect(component.sortAscending).toBe(true); + expect(component.reviews?.map(review => review.id)).toEqual([14, 13, 12]); + + component.toggleSortOrder(); + expect(component.sortAscending).toBe(false); + expect(component.reviews?.map(review => review.id)).toEqual([12, 13, 14]); + }); + + it('derives permission and app-setting state and exposes helper formatting behavior', () => { + component.ngOnInit(); + + expect(component.hasPermission).toBe(true); + expect(component.reviewDownloadEnabled).toBe(false); + expect(component.getProviderSeverity('amazon')).toBe('warn'); + expect(component.getProviderSeverity('goodreads')).toBe('success'); + expect(component.formatDate('2026-03-28T12:00:00.000Z')).toBe('March 28, 2026'); + }); +}); diff --git a/frontend/src/app/features/book/components/book-searcher/book-searcher.component.spec.ts b/frontend/src/app/features/book/components/book-searcher/book-searcher.component.spec.ts new file mode 100644 index 000000000..a5083f431 --- /dev/null +++ b/frontend/src/app/features/book/components/book-searcher/book-searcher.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around debounced signal-to-observable +// search state, global document click listeners, and router navigation so search dropdown behavior +// can be tested without a browser-event harness. +describe.skip('BookSearcherComponent', () => { + it('needs debounce seams to verify filtered-book output, loading state, and active-index reset behavior', () => { + // TODO(seam): Cover the debounced search signal and filteredBooks computed state once timing concerns are extracted for direct control. + }); + + it('needs event seams to verify keyboard navigation, outside-click clearing, and routed book selection', () => { + // TODO(seam): Cover onKeydown and onDocumentClick after isolating host listeners and router side effects behind adapters. + }); +}); diff --git a/frontend/src/app/features/book/components/book-sender/book-sender.component.spec.ts b/frontend/src/app/features/book/components/book-sender/book-sender.component.spec.ts new file mode 100644 index 000000000..cbe0d8e0e --- /dev/null +++ b/frontend/src/app/features/book/components/book-sender/book-sender.component.spec.ts @@ -0,0 +1,367 @@ +import {TestBed} from '@angular/core/testing'; +import {TranslocoService} from '@jsverse/transloco'; +import {beforeEach, afterEach, describe, expect, it, vi} from 'vitest'; +import {of, throwError} from 'rxjs'; +import {MessageService} from 'primeng/api'; +import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; +import { + AdditionalFile, + AdditionalFileType, + Book, + BookFile, +} from '../../model/book.model'; +import {BookSenderComponent} from './book-sender.component'; +import {EmailProvider} from '../../../settings/email-v2/email-provider.model'; +import {EmailRecipient} from '../../../settings/email-v2/email-recipient.model'; +import {EmailService} from '../../../settings/email-v2/email.service'; +import {EmailV2ProviderService} from '../../../settings/email-v2/email-v2-provider/email-v2-provider.service'; +import {EmailV2RecipientService} from '../../../settings/email-v2/email-v2-recipient/email-v2-recipient.service'; + +type EmailBookRequest = Parameters[0]; + +describe('BookSenderComponent', () => { + let emailProviders: EmailProvider[]; + let emailRecipients: EmailRecipient[]; + let emailBookError: Error | null; + + const providerService = { + getEmailProviders: vi.fn(() => of(emailProviders)), + }; + const recipientService = { + getRecipients: vi.fn(() => of(emailRecipients)), + }; + const emailService = { + emailBook: vi.fn((request: EmailBookRequest) => { + void request; + return emailBookError + ? throwError(() => emailBookError) + : of(void 0); + }), + }; + const messageService = { + add: vi.fn(), + }; + const dialogRef = { + close: vi.fn(), + }; + const translocoService = { + translate: vi.fn((key: string) => key), + }; + const dialogConfig: {data: {book: Book}} = { + data: {book: createBook()}, + }; + + let consoleErrorSpy: ReturnType; + + beforeEach(() => { + emailProviders = [ + createProvider({ + id: 101, + name: 'Primary SMTP', + fromAddress: 'books@example.com', + host: 'smtp.primary.test', + }), + createProvider({ + id: 102, + name: 'Fallback SMTP', + fromAddress: '', + host: 'smtp.fallback.test', + }), + ]; + emailRecipients = [ + createRecipient({ + id: 201, + name: 'Alice Reader', + email: 'alice@example.com', + }), + ]; + emailBookError = null; + + providerService.getEmailProviders.mockClear(); + recipientService.getRecipients.mockClear(); + emailService.emailBook.mockClear(); + messageService.add.mockClear(); + dialogRef.close.mockClear(); + translocoService.translate.mockClear(); + + dialogConfig.data = {book: createBook()}; + + consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined); + + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + {provide: EmailV2ProviderService, useValue: providerService}, + {provide: EmailV2RecipientService, useValue: recipientService}, + {provide: EmailService, useValue: emailService}, + {provide: MessageService, useValue: messageService}, + {provide: TranslocoService, useValue: translocoService}, + {provide: DynamicDialogRef, useValue: dialogRef}, + {provide: DynamicDialogConfig, useValue: dialogConfig}, + ], + }); + }); + + afterEach(() => { + consoleErrorSpy.mockRestore(); + TestBed.resetTestingModule(); + }); + + it('builds emailable files and maps provider and recipient options on init', () => { + const component = instantiateComponent(createBook({ + primaryFile: createBookFile({ + id: 11, + bookId: 1, + bookType: 'EPUB', + fileSizeKb: 512, + }), + alternativeFormats: [ + createAdditionalFile({ + id: 22, + bookId: 1, + bookType: 'PDF', + fileSizeKb: 4096, + additionalFileType: AdditionalFileType.ALTERNATIVE_FORMAT, + }), + createAdditionalFile({ + id: 33, + bookId: 1, + bookType: 'MOBI', + fileSizeKb: 2048, + additionalFileType: AdditionalFileType.ALTERNATIVE_FORMAT, + }), + ], + supplementaryFiles: [ + createAdditionalFile({ + id: 44, + bookId: 1, + bookType: 'PDF', + fileSizeKb: 128, + additionalFileType: AdditionalFileType.SUPPLEMENTARY, + }), + ], + })); + + component.ngOnInit(); + + expect(providerService.getEmailProviders).toHaveBeenCalledOnce(); + expect(recipientService.getRecipients).toHaveBeenCalledOnce(); + expect(component.emailProviders).toEqual([ + { + label: 'Primary SMTP | books@example.com', + value: emailProviders[0], + }, + { + label: 'Fallback SMTP | smtp.fallback.test', + value: emailProviders[1], + }, + ]); + expect(component.emailRecipients).toEqual([ + { + label: 'Alice Reader | alice@example.com', + value: emailRecipients[0], + }, + ]); + expect(component.selectedFileId).toBe(11); + expect(component.emailableFiles).toHaveLength(3); + expect(component.emailableFiles.map(file => file.id)).toEqual([11, 22, 33]); + expect(component.emailableFiles).toMatchObject([ + {id: 11, bookType: 'EPUB', fileSizeKb: 512, isPrimary: true}, + {id: 22, bookType: 'PDF', fileSizeKb: 4096, isPrimary: false}, + {id: 33, bookType: 'MOBI', fileSizeKb: 2048, isPrimary: false}, + ]); + }); + + it('formats file sizes across empty, kilobyte, and megabyte values', () => { + const component = instantiateComponent(); + + expect(component.formatFileSize()).toBe('-'); + expect(component.formatFileSize(512)).toBe('512 KB'); + expect(component.formatFileSize(1536)).toBe('1.50 MB'); + }); + + it('shows the large-file warning only for selected files above the threshold', () => { + const component = instantiateComponent(createBook({ + primaryFile: createBookFile({ + id: 11, + bookId: 1, + fileSizeKb: 512, + }), + alternativeFormats: [ + createAdditionalFile({ + id: 22, + bookId: 1, + fileSizeKb: 30 * 1024, + }), + ], + })); + + component.ngOnInit(); + + expect(component.showLargeFileWarning).toBe(false); + + component.selectedFileId = 22; + expect(component.showLargeFileWarning).toBe(true); + + component.selectedFileId = undefined; + expect(component.showLargeFileWarning).toBe(false); + }); + + it('shows validation errors and does not send when provider, recipient, or book are missing', () => { + const component = instantiateComponent(createBook({id: 0})); + + component.sendBook(); + + expect(emailService.emailBook).not.toHaveBeenCalled(); + expect(messageService.add).toHaveBeenCalledTimes(3); + expect(messageService.add).toHaveBeenNthCalledWith(1, { + severity: 'error', + summary: 'book.sender.toast.providerMissingSummary', + detail: 'book.sender.toast.providerMissingDetail', + }); + expect(messageService.add).toHaveBeenNthCalledWith(2, { + severity: 'error', + summary: 'book.sender.toast.recipientMissingSummary', + detail: 'book.sender.toast.recipientMissingDetail', + }); + expect(messageService.add).toHaveBeenNthCalledWith(3, { + severity: 'error', + summary: 'book.sender.toast.bookNotSelectedSummary', + detail: 'book.sender.toast.bookNotSelectedDetail', + }); + }); + + it('sends the selected file and closes the dialog after a successful response', () => { + const component = instantiateComponent(); + component.ngOnInit(); + component.selectedProvider = component.emailProviders[0]; + component.selectedRecipient = component.emailRecipients[0]; + component.selectedFileId = 22; + + component.sendBook(); + + expect(emailService.emailBook).toHaveBeenCalledWith({ + bookId: 1, + providerId: 101, + recipientId: 201, + bookFileId: 22, + }); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'book.sender.toast.emailScheduledSummary', + detail: 'book.sender.toast.emailScheduledDetail', + }); + expect(dialogRef.close).toHaveBeenCalledWith(true); + }); + + it('shows an error toast and keeps the dialog open when sending fails', () => { + emailBookError = new Error('SMTP rejected request'); + + const component = instantiateComponent(); + component.ngOnInit(); + component.selectedProvider = component.emailProviders[0]; + component.selectedRecipient = component.emailRecipients[0]; + + component.sendBook(); + + expect(emailService.emailBook).toHaveBeenCalledWith({ + bookId: 1, + providerId: 101, + recipientId: 201, + bookFileId: 11, + }); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'book.sender.toast.sendingFailedSummary', + detail: 'book.sender.toast.sendingFailedDetail', + }); + expect(dialogRef.close).not.toHaveBeenCalled(); + expect(consoleErrorSpy).toHaveBeenCalledOnce(); + }); + + function instantiateComponent(book: Book = createBook()): BookSenderComponent { + dialogConfig.data = {book}; + return TestBed.runInInjectionContext(() => new BookSenderComponent()); + } +}); + +function createBook(overrides: Partial = {}): Book { + return { + id: 1, + libraryId: 7, + libraryName: 'Main Library', + primaryFile: createBookFile({ + id: 11, + bookId: 1, + bookType: 'EPUB', + fileSizeKb: 512, + }), + alternativeFormats: [ + createAdditionalFile({ + id: 22, + bookId: 1, + bookType: 'PDF', + fileSizeKb: 2048, + }), + ], + supplementaryFiles: [ + createAdditionalFile({ + id: 44, + bookId: 1, + bookType: 'PDF', + fileSizeKb: 128, + additionalFileType: AdditionalFileType.SUPPLEMENTARY, + }), + ], + ...overrides, + }; +} + +function createBookFile(overrides: Partial = {}): BookFile { + return { + id: 11, + bookId: 1, + fileName: 'book.epub', + bookType: 'EPUB', + fileSizeKb: 512, + ...overrides, + }; +} + +function createAdditionalFile(overrides: Partial = {}): AdditionalFile { + return { + ...createBookFile(), + additionalFileType: AdditionalFileType.ALTERNATIVE_FORMAT, + ...overrides, + }; +} + +function createProvider(overrides: Partial = {}): EmailProvider { + return { + isEditing: false, + id: 101, + userId: 1, + name: 'Primary SMTP', + host: 'smtp.example.test', + port: 587, + username: 'mailer', + password: 'secret', + fromAddress: 'books@example.com', + auth: true, + startTls: true, + defaultProvider: true, + shared: false, + ...overrides, + }; +} + +function createRecipient(overrides: Partial = {}): EmailRecipient { + return { + id: 201, + email: 'alice@example.com', + name: 'Alice Reader', + defaultRecipient: true, + isEditing: false, + ...overrides, + }; +} diff --git a/frontend/src/app/features/book/components/bulk-isbn-import-dialog/bulk-isbn-import-dialog.component.spec.ts b/frontend/src/app/features/book/components/bulk-isbn-import-dialog/bulk-isbn-import-dialog.component.spec.ts new file mode 100644 index 000000000..8cc0027ee --- /dev/null +++ b/frontend/src/app/features/book/components/bulk-isbn-import-dialog/bulk-isbn-import-dialog.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around file-reader input, paced async +// import loops, metadata lookup retries, and library-service state so ISBN parsing and import +// progress can be asserted without browser file APIs and timing-heavy runtime behavior. +describe.skip('BulkIsbnImportDialogComponent', () => { + it('needs parser seams to verify pasted-text parsing, file parsing, duplicate removal, and already-existing ISBN filtering', () => { + // TODO(seam): Cover parseContent and related normalization helpers once file-reader inputs and existing-library lookup state are isolated behind deterministic doubles. + }); + + it('needs async-loop seams to verify import progress, cancellation, retry timing, and summary transitions', () => { + // TODO(seam): Cover startImport and progress bookkeeping after metadata lookup, create-book requests, and delay scheduling are extracted into a stable harness. + }); +}); diff --git a/frontend/src/app/features/book/components/duplicate-merger/duplicate-merger.component.spec.ts b/frontend/src/app/features/book/components/duplicate-merger/duplicate-merger.component.spec.ts new file mode 100644 index 000000000..1d434bc5d --- /dev/null +++ b/frontend/src/app/features/book/components/duplicate-merger/duplicate-merger.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around dialog config/bootstrap state, +// paginator state, confirmation flows, and multi-step duplicate merge orchestration so the +// component can be tested without building a full dialog-plus-confirmation harness. +describe.skip('DuplicateMergerComponent', () => { + it('needs scanning seams to verify preset toggles, duplicate detection request shaping, and display-group initialization', () => { + // TODO(seam): Cover applyPreset and scan once the dialog config and duplicate scan subscription flow are isolated behind test doubles. + }); + + it('needs merge seams to verify target selection, dismissal, pagination, and attach-file success and failure handling', () => { + // TODO(seam): Cover the merge workflow after extracting confirmation, loader, and dialog-close side effects from the component runtime. + }); +}); diff --git a/frontend/src/app/features/book/components/series-page/series-page.component.spec.ts b/frontend/src/app/features/book/components/series-page/series-page.component.spec.ts new file mode 100644 index 000000000..5722f0139 --- /dev/null +++ b/frontend/src/app/features/book/components/series-page/series-page.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around route-param signals, Angular Query +// detail loading, selection state, and the large series dashboard template so the series page +// control flow can be asserted without mounting the full browser and query runtime. +describe.skip('SeriesPageComponent', () => { + it('needs route and query seams to verify filtered series books, cover-book resolution, and description loading', () => { + // TODO(seam): Cover the computed series view model once route params and injectQuery data can be driven through a deterministic harness. + }); + + it('needs interaction seams to verify selection, menu actions, metadata flows, and overflow handling', () => { + // TODO(seam): Cover selection state, action menus, and description expansion after overlay, loading-service, and DOM measurement concerns are isolated behind test adapters. + }); +}); diff --git a/frontend/src/app/features/book/components/shelf-assigner/shelf-assigner.component.spec.ts b/frontend/src/app/features/book/components/shelf-assigner/shelf-assigner.component.spec.ts new file mode 100644 index 000000000..adae5bc25 --- /dev/null +++ b/frontend/src/app/features/book/components/shelf-assigner/shelf-assigner.component.spec.ts @@ -0,0 +1,280 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {TranslocoService} from '@jsverse/transloco'; +import {MessageService} from 'primeng/api'; +import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; +import {Observable, of, throwError} from 'rxjs'; +import {afterEach, describe, expect, it, vi} from 'vitest'; + +import {LoadingService} from '../../../../core/services/loading.service'; +import {UserService} from '../../../settings/user-management/user.service'; +import {Book} from '../../model/book.model'; +import {Shelf} from '../../model/shelf.model'; +import {BookService} from '../../service/book.service'; +import {ShelfService} from '../../service/shelf.service'; +import {BookDialogHelperService} from '../book-browser/book-dialog-helper.service'; +import {ShelfAssignerComponent} from './shelf-assigner.component'; + +interface CurrentUserLike { + id: number; + userSettings: { + sidebarShelfSorting: { + field: string; + order: string; + }; + }; +} + +describe('ShelfAssignerComponent', () => { + afterEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + function createShelf(overrides: Partial = {}): Shelf { + return { + id: 1, + name: 'Shelf', + icon: null, + iconType: null, + userId: 7, + ...overrides, + }; + } + + function createBook(overrides: Partial = {}): Book { + return { + id: 101, + libraryId: 1, + libraryName: 'Library', + shelves: [], + ...overrides, + }; + } + + function createCurrentUser( + sorting: {field: string; order: string} = {field: 'name', order: 'asc'}, + id: number = 7, + ): CurrentUserLike { + return { + id, + userSettings: { + sidebarShelfSorting: sorting, + }, + }; + } + + function createHarness(options: { + book?: Book; + bookIds?: Set; + isMultiBooks?: boolean; + shelves?: Shelf[]; + currentUser?: CurrentUserLike | null; + updateResult?: Observable; + } = {}) { + const shelves = signal(options.shelves ?? []); + const currentUser = signal(options.currentUser ?? createCurrentUser()); + const updateBookShelves = vi.fn(() => options.updateResult ?? of([] as Book[])); + const dialogRef = {close: vi.fn()}; + const messageService = {add: vi.fn()}; + const bookDialogHelper = {openShelfCreatorDialog: vi.fn()}; + const loader = document.createElement('div'); + const loadingService = { + show: vi.fn(() => loader), + hide: vi.fn(), + }; + const translate = vi.fn((key: string, params?: Record) => { + if (typeof params?.['count'] === 'number') { + return `translated:${key}:${String(params['count'])}` as T; + } + + return `translated:${key}` as T; + }); + + TestBed.configureTestingModule({ + providers: [ + { + provide: ShelfService, + useValue: {shelves}, + }, + { + provide: DynamicDialogConfig, + useValue: { + data: { + book: options.book ?? createBook(), + bookIds: options.bookIds ?? new Set(), + isMultiBooks: options.isMultiBooks ?? false, + }, + }, + }, + {provide: DynamicDialogRef, useValue: dialogRef}, + {provide: MessageService, useValue: messageService}, + {provide: BookService, useValue: {updateBookShelves}}, + {provide: BookDialogHelperService, useValue: bookDialogHelper}, + {provide: LoadingService, useValue: loadingService}, + {provide: UserService, useValue: {currentUser}}, + {provide: TranslocoService, useValue: {translate}}, + ], + }); + + const component = TestBed.runInInjectionContext(() => new ShelfAssignerComponent()); + TestBed.flushEffects(); + + return { + component, + shelves, + currentUser, + updateBookShelves, + dialogRef, + messageService, + bookDialogHelper, + loadingService, + loader, + translate, + }; + } + + it('initializes selected shelves from the injected book once shelf data is available', () => { + const unread = createShelf({id: 1, name: 'Unread'}); + const favorites = createShelf({id: 2, name: 'Favorites'}); + const foreignShelf = createShelf({id: 3, name: 'Other User Shelf', userId: 8}); + const book = createBook({ + shelves: [ + createShelf({id: 2, name: 'Favorites'}), + ], + }); + + const {component} = createHarness({ + book, + shelves: [unread, favorites, foreignShelf], + }); + + expect(component.selectedShelves).toEqual([favorites]); + expect(component.isShelfSelected(favorites)).toBe(true); + expect(component.isShelfSelected(unread)).toBe(false); + }); + + it('falls back to name ascending sorting when sidebar preferences are invalid', () => { + const {component} = createHarness({ + currentUser: createCurrentUser({field: 'createdAt', order: 'SIDEWAYS'}), + shelves: [ + createShelf({id: 2, name: 'Zulu'}), + createShelf({id: 1, name: 'Alpha'}), + createShelf({id: 3, name: 'Hidden', userId: 42}), + ], + }); + + expect(component.shelves().map(shelf => shelf.name)).toEqual(['Alpha', 'Zulu']); + }); + + it('sorts shelves by id descending when the stored sidebar preferences are valid', () => { + const {component} = createHarness({ + currentUser: createCurrentUser({field: 'id', order: 'desc'}), + shelves: [ + createShelf({id: 1, name: 'One'}), + createShelf({id: 3, name: 'Three'}), + createShelf({id: 2, name: 'Two'}), + ], + }); + + expect(component.shelves().map(shelf => shelf.id)).toEqual([3, 2, 1]); + }); + + it('filters shelves by a trimmed case-insensitive query', () => { + const {component} = createHarness(); + const shelves = [ + createShelf({id: 1, name: 'Science Fiction'}), + createShelf({id: 2, name: 'History'}), + createShelf({id: 3, name: 'Sci-Fi Favorites'}), + ]; + + component.searchQuery = ' sci '; + + expect(component.filterShelves(shelves).map(shelf => shelf.name)).toEqual([ + 'Science Fiction', + 'Sci-Fi Favorites', + ]); + }); + + it('maps custom svg and PrimeNG shelf icons to icon-display selections', () => { + const {component} = createHarness(); + + expect(component.getShelfIcon(createShelf({ + iconType: 'CUSTOM_SVG', + icon: 'custom-icons/moon.svg', + }))).toEqual({ + type: 'CUSTOM_SVG', + value: 'custom-icons/moon.svg', + }); + expect(component.getShelfIcon(createShelf({ + iconType: 'PRIME_NG', + icon: 'bookmark', + }))).toEqual({ + type: 'PRIME_NG', + value: 'pi pi-bookmark', + }); + }); + + it('shapes assign and unassign payloads for a single-book update and closes with success', () => { + const existing = createShelf({id: 1, name: 'Existing'}); + const added = createShelf({id: 2, name: 'Added'}); + const removed = createShelf({id: 3, name: 'Removed'}); + const {component, updateBookShelves, loadingService, loader, messageService, dialogRef, translate} = createHarness({ + book: createBook({ + id: 11, + shelves: [existing, removed], + }), + }); + + component.selectedShelves = [existing, added]; + + component.updateBooksShelves(); + + expect(translate).toHaveBeenCalledWith('book.shelfAssigner.loading.updatingShelves', {count: 1}); + expect(loadingService.show).toHaveBeenCalledWith('translated:book.shelfAssigner.loading.updatingShelves:1'); + expect(updateBookShelves).toHaveBeenCalledWith( + new Set([11]), + new Set([1, 2]), + new Set([3]), + ); + expect(loadingService.hide).toHaveBeenCalledWith(loader); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'info', + summary: 'translated:common.success', + detail: 'translated:book.shelfAssigner.toast.updateSuccessDetail', + }); + expect(dialogRef.close).toHaveBeenCalledWith({assigned: true}); + }); + + it('uses the injected multi-book ids, skips unassigns, and closes with failure on update errors', () => { + const selected = createShelf({id: 5, name: 'Selected'}); + const targetBookIds = new Set([41, 42]); + const {component, updateBookShelves, loadingService, loader, messageService, dialogRef, translate} = createHarness({ + book: createBook({ + id: 11, + shelves: [createShelf({id: 9, name: 'Ignored Existing'})], + }), + bookIds: targetBookIds, + isMultiBooks: true, + updateResult: throwError(() => new Error('update failed')), + }); + + component.selectedShelves = [selected]; + + component.updateBooksShelves(); + + expect(translate).toHaveBeenCalledWith('book.shelfAssigner.loading.updatingShelves', {count: 2}); + expect(updateBookShelves).toHaveBeenCalledWith( + targetBookIds, + new Set([5]), + new Set(), + ); + expect(loadingService.hide).toHaveBeenCalledWith(loader); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'translated:common.error', + detail: 'translated:book.shelfAssigner.toast.updateFailedDetail', + }); + expect(dialogRef.close).toHaveBeenCalledWith({assigned: false}); + }); +}); diff --git a/frontend/src/app/features/book/components/shelf-creator/shelf-creator.component.spec.ts b/frontend/src/app/features/book/components/shelf-creator/shelf-creator.component.spec.ts new file mode 100644 index 000000000..4ae8455a6 --- /dev/null +++ b/frontend/src/app/features/book/components/shelf-creator/shelf-creator.component.spec.ts @@ -0,0 +1,189 @@ +import {TestBed} from '@angular/core/testing'; +import {TranslocoService} from '@jsverse/transloco'; +import {MessageService} from 'primeng/api'; +import {DynamicDialogRef} from 'primeng/dynamicdialog'; +import {Observable, of, throwError} from 'rxjs'; +import {afterEach, describe, expect, it, vi} from 'vitest'; + +import {IconSelection, IconPickerService} from '../../../../shared/service/icon-picker.service'; +import {UserService} from '../../../settings/user-management/user.service'; +import {Shelf} from '../../model/shelf.model'; +import {ShelfService} from '../../service/shelf.service'; +import {ShelfCreatorComponent} from './shelf-creator.component'; + +describe('ShelfCreatorComponent', () => { + afterEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + function createHarness(options: { + createResult?: Observable; + iconPickerResult?: IconSelection | null; + currentUser?: {permissions: {admin: boolean}} | null; + } = {}) { + const createShelf = vi.fn(() => options.createResult ?? of({ + name: 'Created Shelf', + icon: null, + iconType: null, + publicShelf: false, + })); + const dialogRef = {close: vi.fn()}; + const messageService = {add: vi.fn()}; + const iconPickerService = { + open: vi.fn(() => of(options.iconPickerResult ?? null)), + }; + const getCurrentUser = vi.fn(() => options.currentUser ?? {permissions: {admin: false}}); + const translate = vi.fn((key: string, params?: Record) => { + if (params?.['name']) { + return `translated:${key}:${String(params['name'])}` as T; + } + + return `translated:${key}` as T; + }); + + TestBed.configureTestingModule({ + providers: [ + {provide: ShelfService, useValue: {createShelf}}, + {provide: DynamicDialogRef, useValue: dialogRef}, + {provide: MessageService, useValue: messageService}, + {provide: IconPickerService, useValue: iconPickerService}, + {provide: UserService, useValue: {getCurrentUser}}, + {provide: TranslocoService, useValue: {translate}}, + ], + }); + + const component = TestBed.runInInjectionContext(() => new ShelfCreatorComponent()); + + return { + component, + createShelf, + dialogRef, + messageService, + iconPickerService, + translate, + }; + } + + it('picks an icon through the injected icon picker and ignores empty selections', () => { + const pickedIcon: IconSelection = { + type: 'PRIME_NG', + value: 'pi pi-star', + }; + const {component, iconPickerService} = createHarness({ + iconPickerResult: pickedIcon, + }); + + component.openIconPicker(); + + expect(iconPickerService.open).toHaveBeenCalledOnce(); + expect(component.selectedIcon).toEqual(pickedIcon); + + iconPickerService.open.mockReturnValueOnce(of(null)); + component.openIconPicker(); + + expect(component.selectedIcon).toEqual(pickedIcon); + }); + + it('clears the selected icon directly', () => { + const {component} = createHarness(); + component.selectedIcon = { + type: 'CUSTOM_SVG', + value: 'custom-icons/moon.svg', + }; + + component.clearSelectedIcon(); + + expect(component.selectedIcon).toBeNull(); + }); + + it('closes the dialog without a payload when cancelled', () => { + const {component, dialogRef} = createHarness(); + + component.cancel(); + + expect(dialogRef.close).toHaveBeenCalledOnce(); + expect(dialogRef.close).toHaveBeenCalledWith(); + }); + + it('creates a shelf with the selected icon, shows a success toast, and closes with true', () => { + const {component, createShelf, messageService, dialogRef, translate} = createHarness({ + currentUser: {permissions: {admin: true}}, + }); + + component.shelfName = 'Weekend Reads'; + component.isPublic = true; + component.selectedIcon = { + type: 'PRIME_NG', + value: 'pi pi-bookmark', + }; + + component.createShelf(); + + expect(createShelf).toHaveBeenCalledWith({ + name: 'Weekend Reads', + icon: 'pi pi-bookmark', + iconType: 'PRIME_NG', + publicShelf: true, + }); + expect(translate).toHaveBeenCalledWith('common.success'); + expect(translate).toHaveBeenCalledWith('book.shelfCreator.toast.createSuccessDetail', { + name: 'Weekend Reads', + }); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'info', + summary: 'translated:common.success', + detail: 'translated:book.shelfCreator.toast.createSuccessDetail:Weekend Reads', + }); + expect(dialogRef.close).toHaveBeenCalledWith(true); + }); + + it('creates a shelf with null icon fields when no icon is selected', () => { + const {component, createShelf} = createHarness(); + + component.shelfName = 'Plain Shelf'; + component.isPublic = false; + component.selectedIcon = null; + + component.createShelf(); + + expect(createShelf).toHaveBeenCalledWith({ + name: 'Plain Shelf', + icon: null, + iconType: null, + publicShelf: false, + }); + }); + + it('shows an error toast and keeps the dialog open when create fails', () => { + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined); + const {component, createShelf, messageService, dialogRef, translate} = createHarness({ + createResult: throwError(() => new Error('create failed')), + }); + + component.shelfName = 'Broken Shelf'; + component.selectedIcon = { + type: 'CUSTOM_SVG', + value: 'custom-icons/moon.svg', + }; + component.isPublic = true; + + component.createShelf(); + + expect(createShelf).toHaveBeenCalledWith({ + name: 'Broken Shelf', + icon: 'custom-icons/moon.svg', + iconType: 'CUSTOM_SVG', + publicShelf: true, + }); + expect(translate).toHaveBeenCalledWith('common.error'); + expect(translate).toHaveBeenCalledWith('book.shelfCreator.toast.createFailedDetail'); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'translated:common.error', + detail: 'translated:book.shelfCreator.toast.createFailedDetail', + }); + expect(dialogRef.close).not.toHaveBeenCalled(); + expect(errorSpy).toHaveBeenCalledOnce(); + }); +}); diff --git a/frontend/src/app/features/book/components/shelf-edit-dialog/shelf-edit-dialog.component.spec.ts b/frontend/src/app/features/book/components/shelf-edit-dialog/shelf-edit-dialog.component.spec.ts new file mode 100644 index 000000000..f60a20928 --- /dev/null +++ b/frontend/src/app/features/book/components/shelf-edit-dialog/shelf-edit-dialog.component.spec.ts @@ -0,0 +1,222 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {MessageService} from 'primeng/api'; +import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; +import {Observable, of, throwError} from 'rxjs'; +import {afterEach, describe, expect, it, vi} from 'vitest'; + +import {getTranslocoModule} from '../../../../core/testing/transloco-testing'; +import {IconSelection, IconPickerService} from '../../../../shared/service/icon-picker.service'; +import {UserService} from '../../../settings/user-management/user.service'; +import {Shelf} from '../../model/shelf.model'; +import {ShelfService} from '../../service/shelf.service'; +import {ShelfEditDialogComponent} from './shelf-edit-dialog.component'; + +describe('ShelfEditDialogComponent', () => { + afterEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + function createShelf(overrides: Partial = {}): Shelf { + return { + id: 7, + name: 'Favorites', + icon: null, + iconType: null, + publicShelf: false, + ...overrides, + }; + } + + function createHarness(options: { + shelfId?: number; + shelvesData?: Shelf[]; + updateResult?: Observable; + iconPickerResult?: IconSelection | null; + currentUser?: {permissions: {admin: boolean}} | null; + } = {}) { + const shelves = signal(options.shelvesData ?? []); + const updateShelf = vi.fn(() => options.updateResult ?? of(createShelf())); + const dialogRef = {close: vi.fn()}; + const messageService = {add: vi.fn()}; + const iconPickerService = { + open: vi.fn(() => of(options.iconPickerResult ?? null)), + }; + const getCurrentUser = vi.fn(() => options.currentUser ?? {permissions: {admin: false}}); + + TestBed.configureTestingModule({ + imports: [getTranslocoModule()], + providers: [ + {provide: ShelfService, useValue: {shelves, updateShelf}}, + {provide: DynamicDialogConfig, useValue: {data: {shelfId: options.shelfId ?? 7}}}, + {provide: DynamicDialogRef, useValue: dialogRef}, + {provide: MessageService, useValue: messageService}, + {provide: IconPickerService, useValue: iconPickerService}, + {provide: UserService, useValue: {getCurrentUser}}, + ], + }); + + const component = TestBed.runInInjectionContext(() => new ShelfEditDialogComponent()); + component.ngOnInit(); + TestBed.flushEffects(); + + return { + component, + shelves, + updateShelf, + dialogRef, + messageService, + iconPickerService, + }; + } + + it('hydrates the dialog from a matching PrimeNG shelf', () => { + const shelf = createShelf({ + id: 42, + name: 'Queue', + icon: 'bookmark', + iconType: 'PRIME_NG', + publicShelf: true, + }); + + const {component} = createHarness({ + shelfId: 42, + shelvesData: [shelf], + }); + + expect(component.shelf).toEqual(shelf); + expect(component.shelfName).toBe('Queue'); + expect(component.isPublic).toBe(true); + expect(component.selectedIcon).toEqual({ + type: 'PRIME_NG', + value: 'pi pi-bookmark', + }); + }); + + it('hydrates custom SVG icons and only initializes once after the shelf becomes available', () => { + const {component, shelves} = createHarness({ + shelfId: 11, + shelvesData: [createShelf({id: 99, name: 'Other Shelf'})], + }); + + expect(component.shelf).toBeUndefined(); + expect(component.shelfName).toBe(''); + expect(component.selectedIcon).toBeNull(); + + shelves.set([ + createShelf({ + id: 11, + name: 'Readable', + icon: 'custom-icons/moon.svg', + iconType: 'CUSTOM_SVG', + }), + ]); + TestBed.flushEffects(); + + expect(component.shelfName).toBe('Readable'); + expect(component.selectedIcon).toEqual({ + type: 'CUSTOM_SVG', + value: 'custom-icons/moon.svg', + }); + + shelves.set([ + createShelf({ + id: 11, + name: 'Should Not Replace', + icon: 'bookmark', + iconType: 'PRIME_NG', + publicShelf: true, + }), + ]); + TestBed.flushEffects(); + + expect(component.shelfName).toBe('Readable'); + expect(component.isPublic).toBe(false); + expect(component.selectedIcon).toEqual({ + type: 'CUSTOM_SVG', + value: 'custom-icons/moon.svg', + }); + }); + + it('picks and clears icons through the dialog-local icon selection methods', () => { + const pickedIcon: IconSelection = { + type: 'PRIME_NG', + value: 'pi pi-star', + }; + const {component, iconPickerService} = createHarness({ + shelvesData: [createShelf()], + iconPickerResult: pickedIcon, + }); + + component.openIconPicker(); + expect(iconPickerService.open).toHaveBeenCalledOnce(); + expect(component.selectedIcon).toEqual(pickedIcon); + + component.clearSelectedIcon(); + expect(component.selectedIcon).toBeNull(); + }); + + it('saves the edited shelf, shows a success toast, and closes the dialog', () => { + const {component, updateShelf, messageService, dialogRef} = createHarness({ + shelfId: 7, + shelvesData: [createShelf({id: 7})], + }); + + component.shelfName = 'Renamed Shelf'; + component.isPublic = true; + component.selectedIcon = { + type: 'PRIME_NG', + value: 'pi pi-heart', + }; + + component.save(); + + expect(updateShelf).toHaveBeenCalledWith({ + name: 'Renamed Shelf', + icon: 'pi pi-heart', + iconType: 'PRIME_NG', + publicShelf: true, + }, 7); + expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'success', + })); + expect(dialogRef.close).toHaveBeenCalledOnce(); + }); + + it('shows an error toast and keeps the dialog open when save fails', () => { + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined); + const {component, updateShelf, messageService, dialogRef} = createHarness({ + shelfId: 7, + shelvesData: [createShelf({id: 7})], + updateResult: throwError(() => new Error('save failed')), + }); + + component.shelfName = 'Broken Shelf'; + component.selectedIcon = null; + component.isPublic = false; + component.save(); + + expect(updateShelf).toHaveBeenCalledWith({ + name: 'Broken Shelf', + icon: null, + iconType: null, + publicShelf: false, + }, 7); + expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'error', + })); + expect(dialogRef.close).not.toHaveBeenCalled(); + expect(errorSpy).toHaveBeenCalledOnce(); + }); + + it('closes the dialog without saving when cancelled', () => { + const {component, dialogRef} = createHarness({ + shelvesData: [createShelf()], + }); + + component.closeDialog(); + + expect(dialogRef.close).toHaveBeenCalledOnce(); + }); +}); diff --git a/frontend/src/app/features/book/helpers/read-status.helper.spec.ts b/frontend/src/app/features/book/helpers/read-status.helper.spec.ts new file mode 100644 index 000000000..228e402cb --- /dev/null +++ b/frontend/src/app/features/book/helpers/read-status.helper.spec.ts @@ -0,0 +1,50 @@ +import {describe, expect, it} from 'vitest'; + +import {ReadStatus} from '../model/book.model'; +import {ReadStatusHelper} from './read-status.helper'; + +describe('ReadStatusHelper', () => { + const helper = new ReadStatusHelper(); + + it('maps statuses to icons and classes', () => { + expect(helper.getReadStatusIcon(undefined)).toBe('pi pi-book'); + expect(helper.getReadStatusIcon(ReadStatus.READ)).toBe('pi pi-check'); + expect(helper.getReadStatusIcon(ReadStatus.READING)).toBe('pi pi-play'); + expect(helper.getReadStatusIcon(ReadStatus.RE_READING)).toBe('pi pi-refresh'); + expect(helper.getReadStatusIcon(ReadStatus.PARTIALLY_READ)).toBe('pi pi-clock'); + expect(helper.getReadStatusIcon(ReadStatus.PAUSED)).toBe('pi pi-pause'); + expect(helper.getReadStatusIcon(ReadStatus.ABANDONED)).toBe('pi pi-times'); + expect(helper.getReadStatusIcon(ReadStatus.WONT_READ)).toBe('pi pi-ban'); + expect(helper.getReadStatusIcon(ReadStatus.UNREAD)).toBe('pi pi-book'); + expect(helper.getReadStatusIcon(ReadStatus.UNSET)).toBe('pi pi-book'); + + expect(helper.getReadStatusClass(undefined)).toBe('status-unset'); + expect(helper.getReadStatusClass(ReadStatus.READ)).toBe('status-read'); + expect(helper.getReadStatusClass(ReadStatus.READING)).toBe('status-reading'); + expect(helper.getReadStatusClass(ReadStatus.RE_READING)).toBe('status-re-reading'); + expect(helper.getReadStatusClass(ReadStatus.PARTIALLY_READ)).toBe('status-partially-read'); + expect(helper.getReadStatusClass(ReadStatus.PAUSED)).toBe('status-paused'); + expect(helper.getReadStatusClass(ReadStatus.ABANDONED)).toBe('status-abandoned'); + expect(helper.getReadStatusClass(ReadStatus.WONT_READ)).toBe('status-wont-read'); + expect(helper.getReadStatusClass(ReadStatus.UNREAD)).toBe('status-unset'); + expect(helper.getReadStatusClass(ReadStatus.UNSET)).toBe('status-unset'); + }); + + it('maps statuses to tooltips', () => { + expect(helper.getReadStatusTooltip(undefined)).toBe('Unset'); + expect(helper.getReadStatusTooltip(ReadStatus.READ)).toBe('Read'); + expect(helper.getReadStatusTooltip(ReadStatus.READING)).toBe('Currently Reading'); + expect(helper.getReadStatusTooltip(ReadStatus.RE_READING)).toBe('Re-reading'); + expect(helper.getReadStatusTooltip(ReadStatus.PARTIALLY_READ)).toBe('Partially Read'); + expect(helper.getReadStatusTooltip(ReadStatus.PAUSED)).toBe('Paused'); + expect(helper.getReadStatusTooltip(ReadStatus.ABANDONED)).toBe('Abandoned'); + expect(helper.getReadStatusTooltip(ReadStatus.WONT_READ)).toBe("Won't Read"); + expect(helper.getReadStatusTooltip(ReadStatus.UNREAD)).toBe('Unread'); + expect(helper.getReadStatusTooltip(ReadStatus.UNSET)).toBe('Unset'); + }); + + it('always shows the status icon', () => { + expect(helper.shouldShowStatusIcon(undefined)).toBe(true); + expect(helper.shouldShowStatusIcon(ReadStatus.READ)).toBe(true); + }); +}); diff --git a/frontend/src/app/features/book/model/book.model.spec.ts b/frontend/src/app/features/book/model/book.model.spec.ts new file mode 100644 index 000000000..95b81f69f --- /dev/null +++ b/frontend/src/app/features/book/model/book.model.spec.ts @@ -0,0 +1,69 @@ +import {describe, expect, expectTypeOf, it} from 'vitest'; + +import { + AdditionalFileType, + Book, + BookMetadata, + BookStatusUpdateResponse, + BulkMetadataUpdateRequest, + computeSeriesReadStatus, + CreatePhysicalBookRequest, + ReadStatus +} from './book.model'; + +describe('book.model', () => { + it('exposes stable additional file and read-status enums', () => { + expect(AdditionalFileType).toEqual({ + ALTERNATIVE_FORMAT: 'ALTERNATIVE_FORMAT', + SUPPLEMENTARY: 'SUPPLEMENTARY' + }); + expect(ReadStatus.UNREAD).toBe('UNREAD'); + expect(ReadStatus.RE_READING).toBe('RE_READING'); + }); + + it('computes aggregate series status from book states', () => { + expect(computeSeriesReadStatus([])).toBe(ReadStatus.UNREAD); + expect(computeSeriesReadStatus([{id: 1, libraryId: 1, libraryName: 'Main', readStatus: ReadStatus.READ} as Book])).toBe(ReadStatus.READ); + expect(computeSeriesReadStatus([ + {id: 1, libraryId: 1, libraryName: 'Main', readStatus: ReadStatus.READ} as Book, + {id: 2, libraryId: 1, libraryName: 'Main', readStatus: ReadStatus.UNREAD} as Book + ])).toBe(ReadStatus.PARTIALLY_READ); + expect(computeSeriesReadStatus([ + {id: 1, libraryId: 1, libraryName: 'Main', readStatus: ReadStatus.READING} as Book, + {id: 2, libraryId: 1, libraryName: 'Main', readStatus: ReadStatus.UNREAD} as Book + ])).toBe(ReadStatus.READING); + expect(computeSeriesReadStatus([ + {id: 1, libraryId: 1, libraryName: 'Main', readStatus: ReadStatus.WONT_READ} as Book + ])).toBe(ReadStatus.WONT_READ); + }); + + it('keeps core payload and metadata contracts typed', () => { + const metadata: BookMetadata = { + bookId: 4, + title: 'A Wizard of Earthsea', + authors: ['Ursula K. Le Guin'], + pageCount: 205 + }; + const createRequest: CreatePhysicalBookRequest = { + libraryId: 2, + title: 'The Tombs of Atuan', + authors: ['Ursula K. Le Guin'] + }; + const bulkUpdate: BulkMetadataUpdateRequest = { + bookIds: [1, 2], + genres: ['Fantasy'], + mergeCategories: true + }; + const statusUpdate: BookStatusUpdateResponse = { + bookId: 1, + readStatus: ReadStatus.READ, + readStatusModifiedTime: '2026-03-26T10:00:00Z' + }; + + expect(metadata.authors).toEqual(['Ursula K. Le Guin']); + expect(createRequest.libraryId).toBe(2); + expect(bulkUpdate.mergeCategories).toBe(true); + expect(statusUpdate.readStatus).toBe(ReadStatus.READ); + expectTypeOf(metadata.pageCount).toEqualTypeOf(); + }); +}); diff --git a/frontend/src/app/features/book/model/library.model.spec.ts b/frontend/src/app/features/book/model/library.model.spec.ts new file mode 100644 index 000000000..f9a35fd27 --- /dev/null +++ b/frontend/src/app/features/book/model/library.model.spec.ts @@ -0,0 +1,29 @@ +import {describe, expect, expectTypeOf, it} from 'vitest'; + +import {Library, LibraryPath, MetadataSource, OrganizationMode} from './library.model'; + +describe('library.model', () => { + it('supports a library with paths and optional metadata settings', () => { + const library: Library = { + id: 1, + name: 'Main Library', + watch: true, + paths: [{id: 10, path: '/books'}], + metadataSource: 'PREFER_EMBEDDED', + organizationMode: 'AUTO_DETECT' + }; + + expect(library.paths[0].path).toBe('/books'); + expect(library.metadataSource).toBe('PREFER_EMBEDDED'); + expectTypeOf(library.paths).toMatchTypeOf(); + }); + + it('keeps metadata source and organization mode unions constrained', () => { + expectTypeOf().toEqualTypeOf< + 'EMBEDDED' | 'SIDECAR' | 'PREFER_SIDECAR' | 'PREFER_EMBEDDED' | 'NONE' + >(); + expectTypeOf().toEqualTypeOf< + 'BOOK_PER_FILE' | 'BOOK_PER_FOLDER' | 'AUTO_DETECT' + >(); + }); +}); diff --git a/frontend/src/app/features/book/model/shelf.model.spec.ts b/frontend/src/app/features/book/model/shelf.model.spec.ts new file mode 100644 index 000000000..a0a83f4e4 --- /dev/null +++ b/frontend/src/app/features/book/model/shelf.model.spec.ts @@ -0,0 +1,29 @@ +import {describe, expect, expectTypeOf, it} from 'vitest'; + +import {Shelf} from './shelf.model'; +import {SortDirection} from './sort.model'; + +describe('shelf.model', () => { + it('supports optional presentation and ownership fields', () => { + const shelf: Shelf = { + id: 3, + name: 'Favorites', + icon: 'pi pi-heart', + publicShelf: true, + userId: 9, + bookCount: 24, + sort: { + label: 'Title', + field: 'title', + direction: SortDirection.ASCENDING + } + }; + + expect(shelf.name).toBe('Favorites'); + expect(shelf.sort?.direction).toBe(SortDirection.ASCENDING); + }); + + it('allows nullable icon values', () => { + expectTypeOf().toEqualTypeOf(); + }); +}); diff --git a/frontend/src/app/features/book/model/sort.model.spec.ts b/frontend/src/app/features/book/model/sort.model.spec.ts new file mode 100644 index 000000000..c77d34d38 --- /dev/null +++ b/frontend/src/app/features/book/model/sort.model.spec.ts @@ -0,0 +1,23 @@ +import {describe, expect, expectTypeOf, it} from 'vitest'; + +import {SortDirection, SortOption} from './sort.model'; + +describe('sort.model', () => { + it('exposes the supported sort directions', () => { + expect(SortDirection).toEqual({ + ASCENDING: 'ASCENDING', + DESCENDING: 'DESCENDING' + }); + }); + + it('keeps sort options structurally typed', () => { + const sortOption: SortOption = { + label: 'Title', + field: 'title', + direction: SortDirection.ASCENDING + }; + + expect(sortOption.field).toBe('title'); + expectTypeOf(sortOption.direction).toEqualTypeOf(); + }); +}); diff --git a/frontend/src/app/features/book/service/book-file.service.spec.ts b/frontend/src/app/features/book/service/book-file.service.spec.ts new file mode 100644 index 000000000..ddd7cb254 --- /dev/null +++ b/frontend/src/app/features/book/service/book-file.service.spec.ts @@ -0,0 +1,360 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {TranslocoService} from '@jsverse/transloco'; +import {QueryClient} from '@tanstack/angular-query-experimental'; +import {firstValueFrom} from 'rxjs'; +import {MessageService} from 'primeng/api'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import type {AdditionalFile, Book, BookMetadata, DetachBookFileResponse} from '../model/book.model'; +import {AdditionalFileType} from '../model/book.model'; +import {BOOKS_QUERY_KEY, bookDetailQueryKey} from './book-query-keys'; +import {BookFileService} from './book-file.service'; +import {FileDownloadService} from '../../../shared/service/file-download.service'; + +type BuildBookOverrides = Omit, 'metadata'> & { + metadata?: Partial; +}; + +function buildAdditionalFile(id: number, overrides: Partial = {}): AdditionalFile { + const bookId = overrides.bookId ?? 1; + + return { + id, + bookId, + fileName: `file-${id}.epub`, + additionalFileType: AdditionalFileType.ALTERNATIVE_FORMAT, + ...overrides, + }; +} + +function buildBook(id: number, overrides: BuildBookOverrides = {}): Book { + const {metadata, ...bookOverrides} = overrides; + + return { + id, + libraryId: 1, + libraryName: 'Library', + metadata: { + bookId: id, + title: `Book ${id}`, + ...metadata, + }, + ...bookOverrides, + }; +} + +describe('BookFileService', () => { + let service: BookFileService; + let httpTestingController: HttpTestingController; + let queryClient: QueryClient; + let messageService: {add: ReturnType}; + let fileDownloadService: {downloadFile: ReturnType}; + let translate: ReturnType; + + beforeEach(() => { + queryClient = new QueryClient(); + vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue(); + messageService = { + add: vi.fn(), + }; + fileDownloadService = { + downloadFile: vi.fn(), + }; + translate = vi.fn((key: string, params?: Record) => ( + params ? `${key}:${JSON.stringify(params)}` : key + )); + + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + BookFileService, + {provide: QueryClient, useValue: queryClient}, + {provide: MessageService, useValue: messageService}, + {provide: FileDownloadService, useValue: fileDownloadService}, + {provide: TranslocoService, useValue: {translate}}, + ], + }); + + service = TestBed.inject(BookFileService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + queryClient.clear(); + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('requests blob content with the optional bookType query param', async () => { + const responseBlob = new Blob(['book-content']); + const requestPromise = firstValueFrom(service.getFileContent(7, 'EPUB')); + + const request = httpTestingController.expectOne(req => req.urlWithParams.endsWith('/api/v1/books/7/content?bookType=EPUB')); + expect(request.request.method).toBe('GET'); + expect(request.request.urlWithParams).toBe('http://localhost:6060/api/v1/books/7/content?bookType=EPUB'); + expect(request.request.responseType).toBe('blob'); + + request.flush(responseBlob); + + await expect(requestPromise).resolves.toEqual(responseBlob); + }); + + it('delegates direct, aggregate, and additional file downloads with derived filenames', () => { + const book = buildBook(5, { + primaryFile: buildAdditionalFile(51, {bookId: 5, fileName: 'main.epub'}), + metadata: {title: 'Title: Volume 1'}, + alternativeFormats: [ + buildAdditionalFile(52, {bookId: 5, fileName: 'alt.epub'}), + ], + supplementaryFiles: [ + buildAdditionalFile(53, { + bookId: 5, + fileName: 'notes.pdf', + additionalFileType: AdditionalFileType.SUPPLEMENTARY, + }), + ], + }); + + service.downloadFile(book); + service.downloadAllFiles(book); + service.downloadAdditionalFile(book, 53); + + expect(fileDownloadService.downloadFile).toHaveBeenNthCalledWith( + 1, + 'http://localhost:6060/api/v1/books/5/download', + 'main.epub', + ); + expect(fileDownloadService.downloadFile).toHaveBeenNthCalledWith( + 2, + 'http://localhost:6060/api/v1/books/5/download-all', + 'Title__Volume_1.zip', + ); + expect(fileDownloadService.downloadFile).toHaveBeenNthCalledWith( + 3, + 'http://localhost:6060/api/v1/books/5/files/53/download', + 'notes.pdf', + ); + }); + + it('deletes an additional file, patches the cached lists, and shows a success toast', () => { + queryClient.setQueryData(BOOKS_QUERY_KEY, [ + buildBook(7, { + alternativeFormats: [buildAdditionalFile(70, {bookId: 7, fileName: 'alt.epub'})], + supplementaryFiles: [ + buildAdditionalFile(71, { + bookId: 7, + fileName: 'notes.pdf', + additionalFileType: AdditionalFileType.SUPPLEMENTARY, + }), + ], + }), + ]); + + service.deleteAdditionalFile(7, 71).subscribe(); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/7/files/71')); + expect(request.request.method).toBe('DELETE'); + request.flush(null); + + expect(queryClient.getQueryData(BOOKS_QUERY_KEY)).toEqual([ + buildBook(7, { + alternativeFormats: [buildAdditionalFile(70, {bookId: 7, fileName: 'alt.epub'})], + supplementaryFiles: [], + }), + ]); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'book.bookService.toast.fileDeletedSummary', + detail: 'book.bookService.toast.additionalFileDeletedDetail', + }); + }); + + it('promotes the next alternative format when deleting the primary book file', () => { + queryClient.setQueryData(BOOKS_QUERY_KEY, [ + buildBook(9, { + primaryFile: buildAdditionalFile(90, {bookId: 9, fileName: 'main.epub'}), + alternativeFormats: [ + buildAdditionalFile(91, {bookId: 9, fileName: 'alt-one.pdf', bookType: 'PDF'}), + buildAdditionalFile(92, {bookId: 9, fileName: 'alt-two.fb2', bookType: 'FB2'}), + ], + }), + ]); + + service.deleteBookFile(9, 90, true).subscribe(); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/9/files/90')); + expect(request.request.method).toBe('DELETE'); + request.flush(null); + + expect(queryClient.getQueryData(BOOKS_QUERY_KEY)).toEqual([ + buildBook(9, { + primaryFile: buildAdditionalFile(91, {bookId: 9, fileName: 'alt-one.pdf', bookType: 'PDF'}), + alternativeFormats: [ + buildAdditionalFile(92, {bookId: 9, fileName: 'alt-two.fb2', bookType: 'FB2'}), + ], + }), + ]); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'book.bookService.toast.fileDeletedSummary', + detail: 'book.bookService.toast.bookFileDeletedDetail', + }); + }); + + it('surfaces delete failures through an error toast and preserves cached files', () => { + const cachedBook = buildBook(11, { + supplementaryFiles: [ + buildAdditionalFile(111, { + bookId: 11, + fileName: 'appendix.pdf', + additionalFileType: AdditionalFileType.SUPPLEMENTARY, + }), + ], + }); + let thrown: unknown; + + queryClient.setQueryData(BOOKS_QUERY_KEY, [cachedBook]); + + service.deleteAdditionalFile(11, 111).subscribe({ + error: error => { + thrown = error; + }, + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/11/files/111')); + request.flush({message: 'cannot delete'}, {status: 500, statusText: 'Server Error'}); + + expect(thrown).toBeTruthy(); + expect(queryClient.getQueryData(BOOKS_QUERY_KEY)).toEqual([cachedBook]); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'book.bookService.toast.fileDeleteFailedSummary', + detail: 'cannot delete', + }); + }); + + it('uploads alternative-format files with inferred bookType and patches cached formats', () => { + const upload = new File(['epub'], 'edition.epub', {type: 'application/epub+zip'}); + const uploadedFile = buildAdditionalFile(121, { + bookId: 12, + fileName: 'edition.epub', + bookType: 'EPUB', + additionalFileType: AdditionalFileType.ALTERNATIVE_FORMAT, + }); + + queryClient.setQueryData(BOOKS_QUERY_KEY, [buildBook(12)]); + + service.uploadAdditionalFile(12, upload, AdditionalFileType.ALTERNATIVE_FORMAT).subscribe(result => { + expect(result).toEqual(uploadedFile); + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/12/files')); + expect(request.request.method).toBe('POST'); + + const formData = request.request.body as FormData; + expect(formData.get('file')).toBe(upload); + expect(formData.get('isBook')).toBe('true'); + expect(formData.get('bookType')).toBe('EPUB'); + + request.flush(uploadedFile); + + expect(queryClient.getQueryData(BOOKS_QUERY_KEY)).toEqual([ + buildBook(12, { + alternativeFormats: [uploadedFile], + }), + ]); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'book.bookService.toast.fileUploadedSummary', + detail: 'book.bookService.toast.fileUploadedDetail', + }); + }); + + it('detaches a book file with copyMetadata and patches both returned books in cache', () => { + const sourceBook = buildBook(20, { + alternativeFormats: [buildAdditionalFile(201, {bookId: 20, fileName: 'source.epub'})], + }); + const placeholderNewBook = buildBook(21, { + metadata: {title: 'Placeholder'}, + }); + const response: DetachBookFileResponse = { + sourceBook: buildBook(20, {alternativeFormats: []}), + newBook: buildBook(21, { + primaryFile: buildAdditionalFile(201, {bookId: 21, fileName: 'source.epub'}), + metadata: {title: 'Detached Copy'}, + }), + }; + + queryClient.setQueryData(BOOKS_QUERY_KEY, [sourceBook, placeholderNewBook]); + + service.detachBookFile(20, 201, true).subscribe(result => { + expect(result).toEqual(response); + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/20/files/201/detach')); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual({copyMetadata: true}); + request.flush(response); + + expect(queryClient.getQueryData(BOOKS_QUERY_KEY)).toEqual([response.sourceBook, response.newBook]); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'metadata.viewer.toast.detachFileSuccessSummary', + detail: 'metadata.viewer.toast.detachFileSuccessDetail', + }); + }); + + it('attaches source book files, updates the target cache entry, and evicts removed books', () => { + const targetBook = buildBook(30, { + primaryFile: buildAdditionalFile(301, {bookId: 30, fileName: 'target.epub'}), + }); + const sourceBook = buildBook(31, { + primaryFile: buildAdditionalFile(311, {bookId: 31, fileName: 'source-one.epub'}), + }); + const secondSourceBook = buildBook(32, { + primaryFile: buildAdditionalFile(321, {bookId: 32, fileName: 'source-two.epub'}), + }); + const updatedTargetBook = buildBook(30, { + primaryFile: buildAdditionalFile(301, {bookId: 30, fileName: 'target.epub'}), + alternativeFormats: [ + buildAdditionalFile(311, {bookId: 30, fileName: 'source-one.epub'}), + buildAdditionalFile(321, {bookId: 30, fileName: 'source-two.epub'}), + ], + }); + + queryClient.setQueryData(BOOKS_QUERY_KEY, [targetBook, sourceBook, secondSourceBook]); + queryClient.setQueryData(bookDetailQueryKey(31, false), sourceBook); + queryClient.setQueryData(bookDetailQueryKey(32, false), secondSourceBook); + + service.attachBookFiles(30, [31, 32], false).subscribe(result => { + expect(result).toEqual({ + updatedBook: updatedTargetBook, + deletedSourceBookIds: [31, 32], + }); + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/30/attach-file')); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual({ + sourceBookIds: [31, 32], + moveFiles: false, + }); + request.flush({ + updatedBook: updatedTargetBook, + deletedSourceBookIds: [31, 32], + }); + + expect(queryClient.getQueryData(BOOKS_QUERY_KEY)).toEqual([updatedTargetBook]); + expect(queryClient.getQueryData(bookDetailQueryKey(31, false))).toBeUndefined(); + expect(queryClient.getQueryData(bookDetailQueryKey(32, false))).toBeUndefined(); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'book.bookService.toast.filesAttachedSummary', + detail: 'book.bookService.toast.filesAttachedDetail:{"count":2}', + }); + }); +}); diff --git a/frontend/src/app/features/book/service/book-menu.service.spec.ts b/frontend/src/app/features/book/service/book-menu.service.spec.ts new file mode 100644 index 000000000..70b37a8cb --- /dev/null +++ b/frontend/src/app/features/book/service/book-menu.service.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around confirmation-dialog callbacks, +// loader orchestration, and message-service side effects so menu-action branching can be asserted +// without reproducing the full imperative overlay runtime. +describe.skip('BookMenuService', () => { + it('needs dialog seams to verify delete, merge, send, rescan, and metadata-refresh action branching', () => { + // TODO(seam): Cover menu item creation and destructive-action callbacks once confirm dialog payloads can be asserted directly. + }); + + it('needs loader and toast seams to verify success, failure, and bulk-operation messaging paths', () => { + // TODO(seam): Cover async action handlers after loader wrappers and message dispatch are extracted behind deterministic collaborators. + }); +}); diff --git a/frontend/src/app/features/book/service/book-metadata-manage.service.spec.ts b/frontend/src/app/features/book/service/book-metadata-manage.service.spec.ts new file mode 100644 index 000000000..2f1a6d40c --- /dev/null +++ b/frontend/src/app/features/book/service/book-metadata-manage.service.spec.ts @@ -0,0 +1,144 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {QueryClient} from '@tanstack/angular-query-experimental'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {MessageService} from 'primeng/api'; + +import {Book, BookMetadata, MetadataUpdateWrapper} from '../model/book.model'; +import {BOOKS_QUERY_KEY} from './book-query-keys'; +import {BookMetadataManageService} from './book-metadata-manage.service'; +import {TranslocoService} from '@jsverse/transloco'; + +function makeBook(id: number, metadata: Partial = {}): Book { + return { + id, + libraryId: 1, + libraryName: 'Library', + metadata: { + bookId: id, + title: `Book ${id}`, + titleLocked: false, + authorsLocked: false, + ...metadata, + }, + }; +} + +describe('BookMetadataManageService', () => { + let service: BookMetadataManageService; + let httpTestingController: HttpTestingController; + let queryClient: QueryClient; + let messageService: {add: ReturnType}; + + beforeEach(() => { + queryClient = new QueryClient(); + vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue(); + messageService = { + add: vi.fn(), + }; + + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + BookMetadataManageService, + {provide: QueryClient, useValue: queryClient}, + {provide: MessageService, useValue: messageService}, + {provide: TranslocoService, useValue: {translate: (key: string) => key}}, + ], + }); + + service = TestBed.inject(BookMetadataManageService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + queryClient.clear(); + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('updates metadata with merge params and patches the cached metadata', () => { + const original = makeBook(7, {title: 'Old Title'}); + const wrapper: MetadataUpdateWrapper = { + metadata: {bookId: 7, title: 'Updated Title'}, + clearFlags: {}, + }; + queryClient.setQueryData(BOOKS_QUERY_KEY, [original]); + + service.updateBookMetadata(7, wrapper, true, 'REPLACE_WHEN_PROVIDED').subscribe(metadata => { + expect(metadata.title).toBe('Updated Title'); + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/7/metadata')); + expect(request.request.method).toBe('PUT'); + expect(request.request.params.get('mergeCategories')).toBe('true'); + expect(request.request.params.get('replaceMode')).toBe('REPLACE_WHEN_PROVIDED'); + expect(request.request.body).toEqual(wrapper); + request.flush({bookId: 7, title: 'Updated Title'}); + + expect(queryClient.getQueryData(BOOKS_QUERY_KEY)?.[0].metadata?.title).toBe('Updated Title'); + }); + + it('toggles cached metadata lock fields for successful bulk lock updates', () => { + queryClient.setQueryData(BOOKS_QUERY_KEY, [ + makeBook(1, {titleLocked: false, authorsLocked: false}), + ]); + + service.toggleFieldLocks([1], {title: 'LOCK', authorsLocked: 'LOCK'}).subscribe(); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/metadata/toggle-field-locks')); + expect(request.request.method).toBe('PUT'); + expect(request.request.body).toEqual({ + bookIds: [1], + fieldActions: {title: 'LOCK', authorsLocked: 'LOCK'}, + }); + request.flush(null); + + expect(queryClient.getQueryData(BOOKS_QUERY_KEY)?.[0].metadata).toMatchObject({ + titleLocked: true, + authorsLocked: true, + }); + }); + + it('shows an error toast when toggleFieldLocks fails', () => { + let thrown: unknown; + + service.toggleFieldLocks(new Set([2]), {title: 'UNLOCK'}).subscribe({ + error: error => { + thrown = error; + }, + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/metadata/toggle-field-locks')); + request.flush({message: 'nope'}, {status: 500, statusText: 'Server Error'}); + + expect(thrown).toBeTruthy(); + expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'error', + summary: 'book.bookService.toast.fieldLockFailedSummary', + })); + }); + + it('reports whether a book has both audiobook and ebook files', () => { + const dualFormatBook = makeBook(3, { + audiobookCoverUpdatedOn: '2026-03-01', + }); + dualFormatBook.primaryFile = {id: 10, bookId: 3, bookType: 'EPUB'}; + dualFormatBook.alternativeFormats = [{id: 11, bookId: 3, bookType: 'AUDIOBOOK'}]; + + const audiobookOnlyBook = makeBook(4); + audiobookOnlyBook.primaryFile = {id: 12, bookId: 4, bookType: 'AUDIOBOOK'}; + + expect(service.supportsDualCovers(dualFormatBook)).toBe(true); + expect(service.supportsDualCovers(audiobookOnlyBook)).toBe(false); + }); + + it('returns stable upload URLs for ebook and audiobook cover endpoints', () => { + expect(service.getUploadCoverUrl(9)).toBe('http://localhost:6060/api/v1/books/9/metadata/cover/upload'); + expect(service.getUploadAudiobookCoverUrl(9)).toBe('http://localhost:6060/api/v1/books/9/metadata/audiobook-cover/upload'); + }); +}); diff --git a/frontend/src/app/features/book/service/book-metadata.service.spec.ts b/frontend/src/app/features/book/service/book-metadata.service.spec.ts new file mode 100644 index 000000000..b55959500 --- /dev/null +++ b/frontend/src/app/features/book/service/book-metadata.service.spec.ts @@ -0,0 +1,113 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {of} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {AuthService} from '../../../shared/service/auth.service'; +import {BookMetadataService} from './book-metadata.service'; +import {SseClient} from 'ngx-sse-client'; + +describe('BookMetadataService', () => { + let service: BookMetadataService; + let httpTestingController: HttpTestingController; + let authService: {getInternalAccessToken: ReturnType}; + let sseClient: {stream: ReturnType}; + const fetchRequest = { + bookId: 7, + providers: ['google'], + title: 'Dune', + author: 'Frank Herbert', + isbn: '9780441172719', + }; + + beforeEach(() => { + authService = { + getInternalAccessToken: vi.fn(() => 'token-123'), + }; + sseClient = { + stream: vi.fn(() => of({type: 'message', data: JSON.stringify({title: 'Dune'})})), + }; + + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + BookMetadataService, + {provide: AuthService, useValue: authService}, + {provide: SseClient, useValue: sseClient}, + ], + }); + + service = TestBed.inject(BookMetadataService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('throws when fetching metadata without an auth token', () => { + authService.getInternalAccessToken.mockReturnValueOnce(null); + + expect(() => service.fetchBookMetadata(7, fetchRequest)).toThrowError( + 'No authentication token available' + ); + }); + + it('streams metadata over SSE with auth headers and maps message payloads', () => { + let result: unknown; + + service.fetchBookMetadata(7, fetchRequest).subscribe(value => { + result = value; + }); + + const [url, clientConfig, requestOptions, method] = sseClient.stream.mock.calls[0] ?? []; + expect(url).toMatch(/\/api\/v1\/books\/7\/metadata\/prospective$/); + expect(clientConfig).toEqual({ + keepAlive: false, + reconnectionDelay: 1000, + responseType: 'event' + }); + expect(requestOptions.body).toEqual(fetchRequest); + expect(requestOptions.withCredentials).toBe(true); + expect(requestOptions.headers.get('Authorization')).toBe('Bearer token-123'); + expect(requestOptions.headers.get('Content-Type')).toBe('application/json'); + expect(method).toBe('POST'); + expect(result).toEqual({title: 'Dune'}); + }); + + it('turns SSE error events into thrown errors', () => { + sseClient.stream.mockReturnValueOnce(of({type: 'error', message: 'bad stream'})); + + let error: unknown; + service.fetchBookMetadata(7, fetchRequest).subscribe({ + error: err => { + error = err; + } + }); + + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toBe('bad stream'); + }); + + it('requests provider detail and ISBN lookup through HTTP endpoints', () => { + service.fetchMetadataDetail('google', 'abc123').subscribe(); + service.lookupByIsbn('9780441172719').subscribe(); + + const detailRequest = httpTestingController.expectOne(req => + req.url.endsWith('/api/v1/books/metadata/detail/google/abc123') + ); + expect(detailRequest.request.method).toBe('GET'); + detailRequest.flush({}); + + const lookupRequest = httpTestingController.expectOne(req => + req.url.endsWith('/api/v1/books/metadata/isbn-lookup') + ); + expect(lookupRequest.request.method).toBe('POST'); + expect(lookupRequest.request.body).toEqual({isbn: '9780441172719'}); + lookupRequest.flush({}); + }); +}); diff --git a/frontend/src/app/features/book/service/book-navigation.service.spec.ts b/frontend/src/app/features/book/service/book-navigation.service.spec.ts new file mode 100644 index 000000000..2d0f79aa9 --- /dev/null +++ b/frontend/src/app/features/book/service/book-navigation.service.spec.ts @@ -0,0 +1,52 @@ +import {describe, expect, it} from 'vitest'; + +import {BookNavigationService} from './book-navigation.service'; + +describe('BookNavigationService', () => { + it('tracks navigation context and derived positions', () => { + const service = new BookNavigationService(); + + expect(service.navigationState()).toBeNull(); + expect(service.canNavigatePrevious()).toBe(false); + expect(service.canNavigateNext()).toBe(false); + expect(service.previousBookId()).toBeNull(); + expect(service.nextBookId()).toBeNull(); + expect(service.currentPosition()).toBeNull(); + + service.setAvailableBookIds([1, 2, 3]); + expect(service.availableBookIds()).toEqual([1, 2, 3]); + + service.setNavigationContext([1, 2, 3], 2); + + expect(service.navigationState()).toEqual({bookIds: [1, 2, 3], currentIndex: 1}); + expect(service.canNavigatePrevious()).toBe(true); + expect(service.canNavigateNext()).toBe(true); + expect(service.previousBookId()).toBe(1); + expect(service.nextBookId()).toBe(3); + expect(service.currentPosition()).toEqual({current: 2, total: 3}); + + service.updateCurrentBook(3); + + expect(service.navigationState()).toEqual({bookIds: [1, 2, 3], currentIndex: 2}); + expect(service.canNavigatePrevious()).toBe(true); + expect(service.canNavigateNext()).toBe(false); + expect(service.previousBookId()).toBe(2); + expect(service.nextBookId()).toBeNull(); + expect(service.currentPosition()).toEqual({current: 3, total: 3}); + }); + + it('clears invalid navigation context and ignores unknown book ids', () => { + const service = new BookNavigationService(); + + service.setNavigationContext([1, 2, 3], 99); + expect(service.navigationState()).toBeNull(); + + service.updateCurrentBook(2); + expect(service.navigationState()).toBeNull(); + + service.setNavigationContext([1, 2, 3], 1); + service.updateCurrentBook(99); + + expect(service.navigationState()).toEqual({bookIds: [1, 2, 3], currentIndex: 0}); + }); +}); diff --git a/frontend/src/app/features/book/service/book-patch.service.spec.ts b/frontend/src/app/features/book/service/book-patch.service.spec.ts new file mode 100644 index 000000000..3dfae4a73 --- /dev/null +++ b/frontend/src/app/features/book/service/book-patch.service.spec.ts @@ -0,0 +1,145 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {QueryClient} from '@tanstack/angular-query-experimental'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {ResetProgressTypes} from '../../../shared/constants/reset-progress-type'; +import {ReadStatus} from '../model/book.model'; +import {BOOKS_QUERY_KEY} from './book-query-keys'; +import {BookPatchService} from './book-patch.service'; + +describe('BookPatchService', () => { + let service: BookPatchService; + let httpTestingController: HttpTestingController; + let queryClient: QueryClient; + + beforeEach(() => { + queryClient = new QueryClient(); + vi.spyOn(queryClient, 'setQueryData'); + vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue(); + + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + BookPatchService, + {provide: QueryClient, useValue: queryClient}, + ], + }); + + service = TestBed.inject(BookPatchService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + queryClient.clear(); + TestBed.resetTestingModule(); + }); + + it('posts PDF progress with file progress when a book file id is provided', () => { + service.savePdfProgress(11, 23, 74, 88).subscribe(); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/progress')); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual({ + bookId: 11, + pdfProgress: { + page: 23, + percentage: 74, + }, + fileProgress: { + bookFileId: 88, + positionData: '23', + progressPercent: 74, + }, + }); + request.flush(null); + }); + + it('deduplicates identical EPUB progress updates before posting', () => { + service.saveEpubProgress(7, 'epubcfi(/6/2)', 'chapter-1.xhtml', 15, 31); + service.saveEpubProgress(7, 'epubcfi(/6/2)', 'chapter-1.xhtml', 15, 31); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/progress')); + expect(request.request.body).toEqual({ + bookId: 7, + epubProgress: { + cfi: 'epubcfi(/6/2)', + href: 'chapter-1.xhtml', + percentage: 15, + }, + fileProgress: { + bookFileId: 31, + positionData: 'epubcfi(/6/2)', + positionHref: 'chapter-1.xhtml', + progressPercent: 15, + }, + }); + request.flush(null); + + httpTestingController.expectNone(req => req.url.endsWith('/api/v1/books/progress')); + }); + + it('patches cached progress fields when resetting kobo progress', () => { + service.resetProgress([1, 2], ResetProgressTypes.KOBO).subscribe(); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/reset-progress')); + expect(request.request.method).toBe('POST'); + expect(request.request.params.get('type')).toBe(ResetProgressTypes.KOBO); + expect(request.request.body).toEqual([1, 2]); + request.flush([ + {bookId: 1, readStatus: ReadStatus.UNREAD, readStatusModifiedTime: '2026-03-01T00:00:00Z', dateFinished: null}, + {bookId: 2, readStatus: ReadStatus.READING, readStatusModifiedTime: '2026-03-02T00:00:00Z', dateFinished: '2026-03-03'}, + ]); + + expect(queryClient.setQueryData).toHaveBeenCalledWith(BOOKS_QUERY_KEY, expect.any(Function)); + expect(queryClient.invalidateQueries).toHaveBeenCalledTimes(2); + }); + + it('updates cached date finished after the backend accepts the change', () => { + service.updateDateFinished(5, '2026-03-10').subscribe(); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/progress')); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual({ + bookId: 5, + dateFinished: '2026-03-10', + }); + request.flush(null); + + expect(queryClient.setQueryData).toHaveBeenCalledWith(BOOKS_QUERY_KEY, expect.any(Function)); + expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['books', 'detail', 5]}); + }); + + it('updates the read status for multiple books and patches cached fields', () => { + service.updateBookReadStatus([1, 2], ReadStatus.READ).subscribe(); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/status')); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual({ + bookIds: [1, 2], + status: ReadStatus.READ, + }); + request.flush([ + {bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: '2026-03-04T00:00:00Z', dateFinished: '2026-03-04'}, + {bookId: 2, readStatus: ReadStatus.READ, readStatusModifiedTime: '2026-03-05T00:00:00Z', dateFinished: '2026-03-05'}, + ]); + + expect(queryClient.setQueryData).toHaveBeenCalledWith(BOOKS_QUERY_KEY, expect.any(Function)); + expect(queryClient.invalidateQueries).toHaveBeenCalledTimes(2); + }); + + it('updates the cached last read timestamp without calling the backend', () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-03-26T12:00:00Z')); + + service.updateLastReadTime(3); + + expect(queryClient.setQueryData).toHaveBeenCalledWith(BOOKS_QUERY_KEY, expect.any(Function)); + httpTestingController.expectNone(req => req.url.includes('/api/v1/books')); + + vi.useRealTimers(); + }); +}); diff --git a/frontend/src/app/features/book/service/book-query-cache.spec.ts b/frontend/src/app/features/book/service/book-query-cache.spec.ts index 717ae5715..9989a55fd 100644 --- a/frontend/src/app/features/book/service/book-query-cache.spec.ts +++ b/frontend/src/app/features/book/service/book-query-cache.spec.ts @@ -1,9 +1,15 @@ import {beforeEach, describe, expect, it, vi} from 'vitest'; import {QueryClient} from '@tanstack/angular-query-experimental'; -import {Book} from '../model/book.model'; +import {Book, BookMetadata} from '../model/book.model'; import { addBookToCache, + invalidateBookDetailQueries, + invalidateBookQueries, + invalidateBooksQuery, + patchBookFieldsInCache, + patchBookInCacheWith, + patchBookMetadataInCache, patchBooksInCache, removeBookQueries, removeBooksFromCache @@ -55,6 +61,20 @@ describe('book-query-cache', () => { expect(queryClient.getQueryData(BOOKS_QUERY_KEY)).toEqual([firstBook, updatedSecondBook]); }); + it('invalidates the full books query and book detail queries', () => { + const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries'); + + invalidateBooksQuery(queryClient); + invalidateBookDetailQueries(queryClient, [1, 1, 2]); + invalidateBookQueries(queryClient, [3, 3]); + + expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: BOOKS_QUERY_KEY, exact: true}); + expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(1)}); + expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(2)}); + expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(3)}); + expect(invalidateQueriesSpy).toHaveBeenCalledTimes(5); + }); + it('patches list entries and invalidates matching detail queries', () => { const firstBook = makeBook(1); const secondBook = makeBook(2); @@ -72,6 +92,72 @@ describe('book-query-cache', () => { expect(invalidateQueriesSpy).toHaveBeenCalledTimes(1); }); + it('patches metadata, selected fields, and updater callbacks in the list cache', () => { + const firstBook = makeBook(1, { + metadata: { + bookId: 1, + title: 'Original Title', + authors: ['Old Author'] + } + }); + const secondBook = makeBook(2, { + metadata: { + bookId: 2, + title: 'Second' + }, + libraryName: 'Library A' + }); + const thirdBook = makeBook(3, { + metadata: { + bookId: 3, + title: 'Third' + } + }); + const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries'); + + queryClient.setQueryData(BOOKS_QUERY_KEY, [firstBook, secondBook, thirdBook]); + + const updatedMetadata: BookMetadata = { + bookId: 1, + title: 'Updated Title' + }; + + patchBookMetadataInCache(queryClient, 1, updatedMetadata); + patchBookFieldsInCache(queryClient, [ + {bookId: 2, fields: {libraryName: 'Updated Library'}}, + {bookId: 3, fields: {personalRating: 4}} + ]); + patchBookInCacheWith(queryClient, 1, book => ({ + ...book, + metadata: { + ...(book.metadata ?? {bookId: book.id}), + authors: ['New Author'] + } + })); + + expect(queryClient.getQueryData(BOOKS_QUERY_KEY)).toEqual([ + { + ...firstBook, + metadata: { + ...firstBook.metadata, + title: 'Updated Title', + authors: ['New Author'] + } + }, + { + ...secondBook, + libraryName: 'Updated Library' + }, + { + ...thirdBook, + personalRating: 4 + } + ]); + expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(1)}); + expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(2)}); + expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(3)}); + }); + it('removes detail and recommendation queries for deleted books', () => { const firstBook = makeBook(1); const secondBook = makeBook(2); @@ -103,4 +189,14 @@ describe('book-query-cache', () => { expect(queryClient.getQueryData(bookDetailQueryKey(1, false))).toBeUndefined(); expect(queryClient.getQueryData(bookRecommendationsQueryKey(1, 20))).toBeUndefined(); }); + + it('ignores an empty remove request', () => { + const setQueryDataSpy = vi.spyOn(queryClient, 'setQueryData'); + const removeQueriesSpy = vi.spyOn(queryClient, 'removeQueries'); + + removeBooksFromCache(queryClient, []); + + expect(setQueryDataSpy).not.toHaveBeenCalled(); + expect(removeQueriesSpy).not.toHaveBeenCalled(); + }); }); diff --git a/frontend/src/app/features/book/service/book-query-keys.spec.ts b/frontend/src/app/features/book/service/book-query-keys.spec.ts new file mode 100644 index 000000000..696106518 --- /dev/null +++ b/frontend/src/app/features/book/service/book-query-keys.spec.ts @@ -0,0 +1,25 @@ +import {describe, expect, it} from 'vitest'; + +import { + BOOKS_QUERY_KEY, + bookDetailQueryKey, + bookDetailQueryPrefix, + bookRecommendationsQueryKey, + bookRecommendationsQueryPrefix, +} from './book-query-keys'; +import {LIBRARIES_QUERY_KEY, libraryFormatCountsQueryKey} from './library-query-keys'; + +describe('book query keys', () => { + it('builds stable keys for book queries and recommendations', () => { + expect(BOOKS_QUERY_KEY).toEqual(['books']); + expect(bookDetailQueryKey(12, true)).toEqual(['books', 'detail', 12, true]); + expect(bookDetailQueryPrefix(12)).toEqual(['books', 'detail', 12]); + expect(bookRecommendationsQueryKey(12, 25)).toEqual(['books', 'recommendations', 12, 25]); + expect(bookRecommendationsQueryPrefix(12)).toEqual(['books', 'recommendations', 12]); + }); + + it('builds stable keys for library queries', () => { + expect(LIBRARIES_QUERY_KEY).toEqual(['libraries']); + expect(libraryFormatCountsQueryKey(7)).toEqual(['libraries', 'format-counts', 7]); + }); +}); diff --git a/frontend/src/app/features/book/service/book-socket.service.spec.ts b/frontend/src/app/features/book/service/book-socket.service.spec.ts new file mode 100644 index 000000000..4baefb4dd --- /dev/null +++ b/frontend/src/app/features/book/service/book-socket.service.spec.ts @@ -0,0 +1,113 @@ +import {TestBed} from '@angular/core/testing'; +import {QueryClient} from '@tanstack/angular-query-experimental'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {Book} from '../model/book.model'; +import {BOOKS_QUERY_KEY, bookDetailQueryKey, bookRecommendationsQueryKey} from './book-query-keys'; +import {BookSocketService} from './book-socket.service'; + +function makeBook(id: number, overrides: Partial = {}): Book { + return { + id, + libraryId: 1, + libraryName: 'Library', + metadata: { + bookId: id, + title: `Book ${id}`, + coverUpdatedOn: '2026-03-01T00:00:00Z', + }, + ...overrides, + }; +} + +describe('BookSocketService', () => { + let service: BookSocketService; + let queryClient: QueryClient; + + beforeEach(() => { + queryClient = new QueryClient(); + + TestBed.configureTestingModule({ + providers: [ + BookSocketService, + {provide: QueryClient, useValue: queryClient}, + ], + }); + + service = TestBed.inject(BookSocketService); + }); + + afterEach(() => { + queryClient.clear(); + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('adds newly created books into the list cache', () => { + const existing = makeBook(1); + const created = makeBook(2); + queryClient.setQueryData(BOOKS_QUERY_KEY, [existing]); + + service.handleNewlyCreatedBook(created); + + expect(queryClient.getQueryData(BOOKS_QUERY_KEY)).toEqual([existing, created]); + }); + + it('invalidates the books query and removes detail queries for removed ids', () => { + const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries'); + const kept = makeBook(2); + queryClient.setQueryData(BOOKS_QUERY_KEY, [makeBook(1), kept]); + queryClient.setQueryData(bookDetailQueryKey(1, false), makeBook(1)); + queryClient.setQueryData(bookRecommendationsQueryKey(1, 20), [kept]); + + service.handleRemovedBookIds([1]); + + expect(invalidateSpy).toHaveBeenCalledWith({queryKey: BOOKS_QUERY_KEY, exact: true}); + expect(queryClient.getQueryData(bookDetailQueryKey(1, false))).toBeUndefined(); + expect(queryClient.getQueryData(bookRecommendationsQueryKey(1, 20))).toBeUndefined(); + }); + + it('patches updated books directly into the list cache', () => { + const original = makeBook(7, {libraryName: 'Original'}); + const updated = makeBook(7, {libraryName: 'Updated'}); + queryClient.setQueryData(BOOKS_QUERY_KEY, [original]); + + service.handleBookUpdate(updated); + + expect(queryClient.getQueryData(BOOKS_QUERY_KEY)).toEqual([updated]); + }); + + it('patches multiple cover timestamps and invalidates their detail queries', () => { + const first = makeBook(3); + const second = makeBook(4, { + metadata: { + bookId: 4, + title: 'Book 4', + }, + }); + const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries'); + queryClient.setQueryData(BOOKS_QUERY_KEY, [first, second]); + + service.handleMultipleBookCoverPatches([{id: 3, coverUpdatedOn: '2026-03-26T12:34:00Z'}]); + + expect(queryClient.getQueryData(BOOKS_QUERY_KEY)).toEqual([ + { + ...first, + metadata: { + ...first.metadata, + coverUpdatedOn: '2026-03-26T12:34:00Z', + }, + }, + second, + ]); + expect(invalidateSpy).toHaveBeenCalledWith({queryKey: ['books', 'detail', 3]}); + }); + + it('ignores empty cover patch lists', () => { + const setQueryDataSpy = vi.spyOn(queryClient, 'setQueryData'); + + service.handleMultipleBookCoverPatches([]); + + expect(setQueryDataSpy).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/app/features/book/service/book.service.spec.ts b/frontend/src/app/features/book/service/book.service.spec.ts new file mode 100644 index 000000000..cdd96256a --- /dev/null +++ b/frontend/src/app/features/book/service/book.service.spec.ts @@ -0,0 +1,263 @@ +import {HttpTestingController} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {Router} from '@angular/router'; +import {TranslocoService} from '@jsverse/transloco'; +import {MessageService} from 'primeng/api'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {createAuthServiceStub, createQueryClientHarness, flushSignalAndQueryEffects} from '../../../core/testing/query-testing'; +import type {Book, BookMetadata} from '../model/book.model'; +import type {Shelf} from '../model/shelf.model'; +import {AuthService} from '../../../shared/service/auth.service'; +import {BookPatchService} from './book-patch.service'; +import {BOOKS_QUERY_KEY} from './book-query-keys'; +import {BookSocketService} from './book-socket.service'; +import {BookService} from './book.service'; + +type BuildBookOverrides = Omit, 'metadata' | 'shelves'> & { + metadata?: Partial; + shelves?: Shelf[]; +}; + +function buildShelf(id: number, overrides: Partial = {}): Shelf { + return { + id, + name: `Shelf ${id}`, + userId: 7, + bookCount: 0, + ...overrides, + }; +} + +function buildBook(id: number, overrides: BuildBookOverrides = {}): Book { + const {metadata, ...bookOverrides} = overrides; + + return { + id, + libraryId: 1, + libraryName: 'Main Library', + metadata: { + bookId: id, + title: `Book ${id}`, + ...metadata, + }, + ...bookOverrides, + }; +} + +async function flushBooksQuery(): Promise { + await Promise.resolve(); + flushSignalAndQueryEffects(); + await new Promise(resolve => setTimeout(resolve, 0)); + flushSignalAndQueryEffects(); + await Promise.resolve(); + flushSignalAndQueryEffects(); +} + +describe('BookService', () => { + let service: BookService; + let httpTestingController: HttpTestingController; + let authService: ReturnType; + let queryClientHarness: ReturnType; + + function setup(initialToken: string | null = 'token-123'): void { + authService = createAuthServiceStub(initialToken); + queryClientHarness = createQueryClientHarness(); + queryClientHarness.queryClient.setDefaultOptions({ + queries: { + retry: false, + }, + }); + + TestBed.configureTestingModule({ + providers: [ + ...queryClientHarness.providers, + BookService, + {provide: AuthService, useValue: authService}, + {provide: MessageService, useValue: {add: vi.fn()}}, + {provide: Router, useValue: {navigate: vi.fn()}}, + { + provide: BookSocketService, + useValue: { + handleNewlyCreatedBook: vi.fn(), + handleRemovedBookIds: vi.fn(), + handleBookUpdate: vi.fn(), + handleMultipleBookUpdates: vi.fn(), + handleBookMetadataUpdate: vi.fn(), + handleMultipleBookCoverPatches: vi.fn(), + }, + }, + { + provide: BookPatchService, + useValue: { + updateLastReadTime: vi.fn(), + savePdfProgress: vi.fn(), + saveCbxProgress: vi.fn(), + updateDateFinished: vi.fn(), + resetProgress: vi.fn(), + updateBookReadStatus: vi.fn(), + resetPersonalRating: vi.fn(), + updatePersonalRating: vi.fn(), + updateBookShelves: vi.fn(), + }, + }, + { + provide: TranslocoService, + useValue: { + translate: vi.fn((key: string) => key), + }, + }, + ], + }); + + service = TestBed.inject(BookService); + httpTestingController = TestBed.inject(HttpTestingController); + flushSignalAndQueryEffects(); + } + + beforeEach(() => { + vi.restoreAllMocks(); + }); + + afterEach(() => { + httpTestingController?.verify(); + queryClientHarness?.queryClient.clear(); + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('eagerly fetches books and hydrates query-backed state, loading state, and unique metadata', async () => { + setup(); + + const response = [ + buildBook(1, { + metadata: { + authors: ['Le Guin', 'Le Guin'], + categories: ['Fantasy'], + moods: ['Calm'], + tags: ['Classic', 'Classic'], + publisher: 'Ace', + seriesName: 'Earthsea', + }, + }), + buildBook(2, { + metadata: { + authors: ['Pratchett'], + categories: ['Fantasy', 'Humor'], + moods: ['Calm', 'Funny'], + tags: ['Classic', 'Satire'], + publisher: 'Corgi', + seriesName: 'Discworld', + }, + }), + ]; + + expect(service.books()).toEqual([]); + expect(service.isBooksLoading()).toBe(true); + expect(service.booksError()).toBeNull(); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books')); + expect(request.request.method).toBe('GET'); + request.flush(response); + await flushBooksQuery(); + + expect(service.books()).toEqual(response); + expect(service.findBookById(2)).toEqual(response[1]); + expect(service.findBookById(999)).toBeUndefined(); + expect(service.getBooksByIds([2, 999, 1])).toEqual(response); + expect(service.uniqueMetadata()).toEqual({ + authors: ['Le Guin', 'Pratchett'], + categories: ['Fantasy', 'Humor'], + moods: ['Calm', 'Funny'], + tags: ['Classic', 'Satire'], + publishers: ['Ace', 'Corgi'], + series: ['Earthsea', 'Discworld'], + }); + expect(service.isBooksLoading()).toBe(false); + expect(service.booksError()).toBeNull(); + }); + + it('gates loading on the auth token and starts the eager fetch once a token is available', async () => { + setup(null); + + expect(service.books()).toEqual([]); + expect(service.isBooksLoading()).toBe(false); + expect(service.booksError()).toBeNull(); + httpTestingController.expectNone(req => req.url.endsWith('/api/v1/books')); + + authService.token.set('token-123'); + flushSignalAndQueryEffects(); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books')); + expect(service.isBooksLoading()).toBe(true); + request.flush([buildBook(7)]); + await flushBooksQuery(); + + expect(service.books()).toEqual([buildBook(7)]); + expect(service.isBooksLoading()).toBe(false); + expect(service.booksError()).toBeNull(); + }); + + it('surfaces query errors through booksError and clears the loading flag', async () => { + setup(); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books')); + request.flush({message: 'boom'}, {status: 500, statusText: 'Server Error'}); + await flushBooksQuery(); + + expect(service.books()).toEqual([]); + expect(service.isBooksLoading()).toBe(false); + expect(service.booksError()).toBe('Failed to load books'); + }); + + it('removes a shelf from the cached books query without disturbing other shelf assignments', async () => { + setup(); + + const targetShelf = buildShelf(10, {name: 'Favorites'}); + const untouchedShelf = buildShelf(11, {name: 'Archive'}); + const initialBooks = [ + buildBook(1, {shelves: [targetShelf, untouchedShelf]}), + buildBook(2, {shelves: [targetShelf]}), + ]; + + httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books')).flush(initialBooks); + await flushBooksQuery(); + + service.removeBooksFromShelf(10); + await flushBooksQuery(); + + expect(queryClientHarness.queryClient.getQueryData(BOOKS_QUERY_KEY)).toEqual([ + buildBook(1, {shelves: [untouchedShelf]}), + buildBook(2, {shelves: []}), + ]); + expect(service.books()).toEqual([ + buildBook(1, {shelves: [untouchedShelf]}), + buildBook(2, {shelves: []}), + ]); + }); + + it('removes the books query cache when the auth token is cleared', async () => { + setup(); + + const removeQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'removeQueries'); + + httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books')).flush([ + buildBook(1), + buildBook(2), + ]); + await flushBooksQuery(); + + expect(queryClientHarness.queryClient.getQueryData(BOOKS_QUERY_KEY)).toEqual([ + buildBook(1), + buildBook(2), + ]); + + authService.token.set(null); + await flushBooksQuery(); + + expect(removeQueriesSpy).toHaveBeenCalledWith({queryKey: BOOKS_QUERY_KEY}); + expect(queryClientHarness.queryClient.getQueryData(BOOKS_QUERY_KEY)).toBeUndefined(); + expect(service.isBooksLoading()).toBe(false); + expect(service.booksError()).toBeNull(); + }); +}); diff --git a/frontend/src/app/features/book/service/cbx-reader.service.spec.ts b/frontend/src/app/features/book/service/cbx-reader.service.spec.ts new file mode 100644 index 000000000..fc6e53237 --- /dev/null +++ b/frontend/src/app/features/book/service/cbx-reader.service.spec.ts @@ -0,0 +1,80 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {AuthService} from '../../../shared/service/auth.service'; +import {CbxPageInfo, CbxReaderService} from './cbx-reader.service'; + +describe('CbxReaderService', () => { + let service: CbxReaderService; + let httpTestingController: HttpTestingController; + let authService: Pick; + + beforeEach(() => { + authService = { + getInternalAccessToken: vi.fn(() => 'token-123'), + }; + + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + CbxReaderService, + {provide: AuthService, useValue: authService}, + ], + }); + + service = TestBed.inject(CbxReaderService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('requests available pages and appends the auth token', () => { + const response = [1, 2, 3]; + + let result: number[] | undefined; + service.getAvailablePages(7).subscribe(value => { + result = value; + }); + + const request = httpTestingController.expectOne(req => req.urlWithParams.endsWith('/api/v1/cbx/7/pages?token=token-123')); + expect(request.request.method).toBe('GET'); + request.flush(response); + + expect(result).toEqual(response); + }); + + it('includes book type alongside the auth token when requesting page info', () => { + const response: CbxPageInfo[] = [{pageNumber: 1, displayName: 'Cover'}]; + + let result: CbxPageInfo[] | undefined; + service.getPageInfo(9, 'CBX').subscribe(value => { + result = value; + }); + + const request = httpTestingController.expectOne(req => req.urlWithParams.endsWith('/api/v1/cbx/9/page-info?bookType=CBX&token=token-123')); + expect(request.request.method).toBe('GET'); + request.flush(response); + + expect(result).toEqual(response); + }); + + it('returns page image urls with both book type and token when provided', () => { + const url = service.getPageImageUrl(12, 4, 'CBX'); + + expect(url).toBe('http://localhost:6060/api/v1/media/book/12/cbx/pages/4?bookType=CBX&token=token-123'); + }); + + it('returns unmodified urls when no auth token is available', () => { + vi.mocked(authService.getInternalAccessToken).mockReturnValue(null); + + const url = service.getPageImageUrl(12, 4); + + expect(url).toBe('http://localhost:6060/api/v1/media/book/12/cbx/pages/4'); + }); +}); diff --git a/frontend/src/app/features/book/service/library-query-keys.spec.ts b/frontend/src/app/features/book/service/library-query-keys.spec.ts new file mode 100644 index 000000000..8e1dc4632 --- /dev/null +++ b/frontend/src/app/features/book/service/library-query-keys.spec.ts @@ -0,0 +1,13 @@ +import {describe, expect, it} from 'vitest'; + +import {libraryFormatCountsQueryKey, LIBRARIES_QUERY_KEY} from './library-query-keys'; + +describe('library-query-keys', () => { + it('uses a stable key for the libraries collection', () => { + expect(LIBRARIES_QUERY_KEY).toEqual(['libraries']); + }); + + it('derives per-library format count keys', () => { + expect(libraryFormatCountsQueryKey(42)).toEqual(['libraries', 'format-counts', 42]); + }); +}); diff --git a/frontend/src/app/features/book/service/library-shelf-menu.service.spec.ts b/frontend/src/app/features/book/service/library-shelf-menu.service.spec.ts new file mode 100644 index 000000000..005b609a1 --- /dev/null +++ b/frontend/src/app/features/book/service/library-shelf-menu.service.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs a seam around nested Prime confirmation payloads, +// router/navigation side effects, clipboard writes, and multiple dialog/task services so menu-item +// command wiring can be asserted without turning the spec into a brittle integration harness. +describe.skip('LibraryShelfMenuService', () => { + it('needs a menu-command seam to verify library, shelf, and magic-shelf action wiring deterministically', () => { + // TODO(seam): Cover confirmation payloads, delete/refresh commands, and dialog launches after introducing a thin menu-action adapter. + }); + + it('needs a browser-side seam to verify clipboard and navigation behavior without relying on global runtime objects', () => { + // TODO(seam): Cover magic-shelf export and post-delete navigation once clipboard/router effects are injectable. + }); +}); diff --git a/frontend/src/app/features/book/service/library.service.spec.ts b/frontend/src/app/features/book/service/library.service.spec.ts new file mode 100644 index 000000000..da02d97a0 --- /dev/null +++ b/frontend/src/app/features/book/service/library.service.spec.ts @@ -0,0 +1,132 @@ +import {HttpTestingController} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {AuthService} from '../../../shared/service/auth.service'; +import {createAuthServiceStub, createQueryClientHarness, flushSignalAndQueryEffects} from '../../../core/testing/query-testing'; +import type {Library} from '../model/library.model'; +import {BookService} from './book.service'; +import {BOOKS_QUERY_KEY} from './book-query-keys'; +import {LIBRARIES_QUERY_KEY, libraryFormatCountsQueryKey} from './library-query-keys'; +import {LibraryService} from './library.service'; + +function buildLibrary(overrides: Partial = {}): Library { + return { + id: 1, + name: 'Zeta Library', + watch: true, + paths: [{path: '/books'}], + ...overrides, + }; +} + +describe('LibraryService', () => { + let service: LibraryService; + let httpTestingController: HttpTestingController; + let authService: ReturnType; + let queryClientHarness: ReturnType; + let bookService: { + books: ReturnType; + }; + + beforeEach(() => { + authService = createAuthServiceStub(); + queryClientHarness = createQueryClientHarness(); + bookService = { + books: vi.fn(() => []), + }; + + vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined); + vi.spyOn(queryClientHarness.queryClient, 'removeQueries').mockImplementation(() => undefined); + + TestBed.configureTestingModule({ + providers: [ + ...queryClientHarness.providers, + LibraryService, + {provide: AuthService, useValue: authService}, + {provide: BookService, useValue: bookService}, + ], + }); + + service = TestBed.inject(LibraryService); + httpTestingController = TestBed.inject(HttpTestingController); + flushSignalAndQueryEffects(); + }); + + afterEach(() => { + httpTestingController.verify(); + queryClientHarness.queryClient.clear(); + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('refreshes and patches library metadata endpoints while invalidating the library cache', () => { + httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries')).flush([]); + + service.refreshLibrary(9).subscribe(); + const refreshRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries/9/refresh')); + expect(refreshRequest.request.method).toBe('PUT'); + refreshRequest.flush(null); + + service.updateLibraryFileNamingPattern(9, '{Authors}/{Title}').subscribe(); + const patternRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries/9/file-naming-pattern')); + expect(patternRequest.request.method).toBe('PATCH'); + expect(patternRequest.request.body).toEqual({fileNamingPattern: '{Authors}/{Title}'}); + patternRequest.flush(buildLibrary({id: 9, fileNamingPattern: '{Authors}/{Title}'})); + + expect(queryClientHarness.queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: LIBRARIES_QUERY_KEY, exact: true}); + }); + + it('invalidates library and book caches after update and delete flows', () => { + httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries')).flush([]); + + service.updateLibrary(buildLibrary({name: 'Updated'}), 4).subscribe(); + const updateRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries/4')); + expect(updateRequest.request.method).toBe('PUT'); + updateRequest.flush(buildLibrary({id: 4, name: 'Updated'})); + + service.deleteLibrary(4).subscribe(); + const deleteRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries/4')); + expect(deleteRequest.request.method).toBe('DELETE'); + deleteRequest.flush(null); + + expect(queryClientHarness.queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: LIBRARIES_QUERY_KEY, exact: true}); + expect(queryClientHarness.queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: BOOKS_QUERY_KEY, exact: true}); + expect(queryClientHarness.queryClient.removeQueries).toHaveBeenCalledWith({queryKey: libraryFormatCountsQueryKey(4), exact: true}); + }); + + it('hydrates format counts through ensureQueryData and tracks large-library loading state', async () => { + httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries')).flush([]); + + const resultPromise = new Promise>((resolve, reject) => { + service.getBookCountsByFormat(8).subscribe({next: resolve, error: reject}); + }); + await Promise.resolve(); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries/8/format-counts')); + expect(request.request.method).toBe('GET'); + request.flush({EPUB: 7, PDF: 2}); + + await expect(resultPromise).resolves.toEqual({EPUB: 7, PDF: 2}); + + service.setLargeLibraryLoading(true, 2500); + expect(service.largeLibraryLoading()).toEqual({isLoading: true, expectedCount: 2500}); + + bookService.books.mockReturnValue([ + {libraryId: 8, shelves: []}, + {libraryId: 8, shelves: []}, + {libraryId: 9, shelves: []}, + ]); + expect(service.getBookCountValue(8)).toBe(2); + }); + + it('removes library queries when the auth token becomes null', () => { + const removeQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'removeQueries').mockImplementation(() => undefined); + + httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries')).flush([]); + authService.token.set(null); + flushSignalAndQueryEffects(); + + expect(removeQueriesSpy).toHaveBeenCalledWith({queryKey: LIBRARIES_QUERY_KEY}); + }); +}); diff --git a/frontend/src/app/features/book/service/metadata-task.spec.ts b/frontend/src/app/features/book/service/metadata-task.spec.ts new file mode 100644 index 000000000..516716fe6 --- /dev/null +++ b/frontend/src/app/features/book/service/metadata-task.spec.ts @@ -0,0 +1,124 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {MetadataBatchProgressNotification, MetadataBatchStatus} from '../../../shared/model/metadata-batch-progress.model'; +import { + FetchedMetadataProposalStatus, + MetadataFetchTask, + MetadataTaskService, +} from './metadata-task'; + +describe('MetadataTaskService', () => { + let service: MetadataTaskService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + MetadataTaskService, + ], + }); + + service = TestBed.inject(MetadataTaskService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('maps the wrapped task response when fetching a task with proposals', () => { + const task: MetadataFetchTask = { + id: 'task-1', + status: 'IN_PROGRESS', + completed: 2, + totalBooks: 5, + startedAt: '2026-03-26T00:00:00Z', + completedAt: null, + initiatedBy: 'alice', + errorMessage: null, + proposals: [ + { + proposalId: 42, + taskId: 'task-1', + bookId: 9, + fetchedAt: '2026-03-26T00:00:01Z', + reviewedAt: null, + reviewerUserId: null, + status: FetchedMetadataProposalStatus.FETCHED, + metadataJson: {title: 'Dune'} as MetadataFetchTask['proposals'][number]['metadataJson'], + }, + ], + }; + + let result: MetadataFetchTask | undefined; + service.getTaskWithProposals('task-1').subscribe(value => { + result = value; + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/metadata/tasks/task-1')); + expect(request.request.method).toBe('GET'); + request.flush({task}); + + expect(result).toEqual(task); + }); + + it('deletes tasks by id', () => { + let completed = false; + service.deleteTask('task-2').subscribe(() => { + completed = true; + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/metadata/tasks/task-2')); + expect(request.request.method).toBe('DELETE'); + request.flush(null); + + expect(completed).toBe(true); + }); + + it('posts status updates with the requested query param', () => { + let completed = false; + service.updateProposalStatus('task-3', 17, 'ACCEPTED').subscribe(() => { + completed = true; + }); + + const request = httpTestingController.expectOne(req => + req.url.endsWith('/api/metadata/tasks/task-3/proposals/17/status') + && req.params.get('status') === 'ACCEPTED' + ); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toBeNull(); + request.flush(null); + + expect(completed).toBe(true); + }); + + it('fetches active tasks directly from the active endpoint', () => { + const tasks: MetadataBatchProgressNotification[] = [ + { + taskId: 'task-4', + completed: 3, + total: 8, + message: 'still running', + status: MetadataBatchStatus.IN_PROGRESS, + review: false, + }, + ]; + + let result: MetadataBatchProgressNotification[] | undefined; + service.getActiveTasks().subscribe(value => { + result = value; + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/metadata/tasks/active')); + expect(request.request.method).toBe('GET'); + request.flush(tasks); + + expect(result).toEqual(tasks); + }); +}); diff --git a/frontend/src/app/features/book/service/shelf.service.spec.ts b/frontend/src/app/features/book/service/shelf.service.spec.ts new file mode 100644 index 000000000..bf0a3c034 --- /dev/null +++ b/frontend/src/app/features/book/service/shelf.service.spec.ts @@ -0,0 +1,171 @@ +import {HttpTestingController} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {createAuthServiceStub, createQueryClientHarness, flushSignalAndQueryEffects} from '../../../core/testing/query-testing'; +import type {Book} from '../model/book.model'; +import type {Shelf} from '../model/shelf.model'; +import {AuthService} from '../../../shared/service/auth.service'; +import {UserService} from '../../settings/user-management/user.service'; +import {BookService} from './book.service'; +import {ShelfService} from './shelf.service'; + +function buildShelf(overrides: Partial = {}): Shelf { + return { + id: 1, + name: 'Favorites', + userId: 7, + bookCount: 0, + ...overrides, + }; +} + +function buildBook(id: number, overrides: Partial = {}): Book { + return { + id, + libraryId: 1, + libraryName: 'Main Library', + ...overrides, + }; +} + +describe('ShelfService', () => { + let service: ShelfService; + let httpTestingController: HttpTestingController; + let authService: ReturnType; + let queryClientHarness: ReturnType; + let bookService: { + books: ReturnType; + removeBooksFromShelf: ReturnType; + }; + let userService: { + getCurrentUser: ReturnType; + }; + + beforeEach(() => { + authService = createAuthServiceStub(); + queryClientHarness = createQueryClientHarness(); + bookService = { + books: vi.fn(() => []), + removeBooksFromShelf: vi.fn(), + }; + userService = { + getCurrentUser: vi.fn(() => null), + }; + + vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined); + vi.spyOn(queryClientHarness.queryClient, 'removeQueries').mockImplementation(() => undefined); + + TestBed.configureTestingModule({ + providers: [ + ...queryClientHarness.providers, + ShelfService, + {provide: AuthService, useValue: authService}, + {provide: BookService, useValue: bookService}, + {provide: UserService, useValue: userService}, + ], + }); + + service = TestBed.inject(ShelfService); + httpTestingController = TestBed.inject(HttpTestingController); + flushSignalAndQueryEffects(); + }); + + afterEach(() => { + httpTestingController.verify(); + queryClientHarness.queryClient.clear(); + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + async function flushShelvesQueryResult(): Promise { + await Promise.resolve(); + flushSignalAndQueryEffects(); + } + + it('eagerly fetches shelves and hydrates the computed shelves signal', async () => { + const response = [ + buildShelf({id: 1, name: 'Reading', userId: 7}), + buildShelf({id: 2, name: 'Archive', userId: 9, bookCount: 5}), + ]; + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')); + expect(request.request.method).toBe('GET'); + request.flush(response); + await flushShelvesQueryResult(); + + expect(service.shelves()).toEqual(response); + expect(service.shelvesError()).toBeNull(); + }); + + it('removes shelf queries when the auth token is cleared', () => { + const removeQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'removeQueries').mockImplementation(() => undefined); + + httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([]); + + authService.token.set(null); + flushSignalAndQueryEffects(); + + expect(removeQueriesSpy).toHaveBeenCalledWith({queryKey: ['shelves']}); + }); + + it('invalidates shelf queries for reload/create/update/delete flows and removes books on delete', () => { + const invalidateQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined); + + httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([]); + + service.reloadShelves(); + + service.createShelf(buildShelf({name: 'New Shelf'})).subscribe(); + const createRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')); + expect(createRequest.request.method).toBe('POST'); + createRequest.flush(buildShelf({id: 11, name: 'New Shelf'})); + + service.updateShelf(buildShelf({name: 'Updated Shelf'}), 11).subscribe(); + const updateRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves/11')); + expect(updateRequest.request.method).toBe('PUT'); + updateRequest.flush(buildShelf({id: 11, name: 'Updated Shelf'})); + + service.deleteShelf(11).subscribe(); + const deleteRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves/11')); + expect(deleteRequest.request.method).toBe('DELETE'); + deleteRequest.flush(null); + + expect(invalidateQueriesSpy).toHaveBeenCalledTimes(4); + expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['shelves'], exact: true}); + expect(bookService.removeBooksFromShelf).toHaveBeenCalledWith(11); + }); + + it('uses owner-aware shelf counts and falls back to persisted counts for non-owners', async () => { + httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([ + buildShelf({id: 1, userId: 7, bookCount: 99}), + buildShelf({id: 2, userId: 10, bookCount: 6}), + ]); + await flushShelvesQueryResult(); + + bookService.books.mockReturnValue([ + buildBook(1, {shelves: [buildShelf({id: 1, name: 'Reading'})]}), + buildBook(2, {shelves: [buildShelf({id: 1, name: 'Reading'})]}), + buildBook(3, {shelves: [buildShelf({id: 2, name: 'Archive'})]}), + ]); + + userService.getCurrentUser.mockReturnValue({id: 7}); + expect(service.getBookCountValue(1)).toBe(2); + + userService.getCurrentUser.mockReturnValue({id: 42}); + expect(service.getBookCountValue(2)).toBe(6); + expect(service.getBookCountValue(999)).toBe(0); + }); + + it('counts unshelved books from the current book cache snapshot', () => { + httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([]); + + bookService.books.mockReturnValue([ + buildBook(1, {shelves: [buildShelf({id: 1, name: 'Reading'})]}), + buildBook(2, {shelves: []}), + buildBook(3, {shelves: undefined}), + ]); + + expect(service.getUnshelvedBookCountValue()).toBe(2); + }); +}); diff --git a/frontend/src/app/features/book/service/sort.service.spec.ts b/frontend/src/app/features/book/service/sort.service.spec.ts new file mode 100644 index 000000000..8e938bb54 --- /dev/null +++ b/frontend/src/app/features/book/service/sort.service.spec.ts @@ -0,0 +1,78 @@ +import {describe, expect, it, vi} from 'vitest'; + +import {SortDirection, SortOption} from '../model/sort.model'; +import {Book, ReadStatus} from '../model/book.model'; +import {SortService} from './sort.service'; + +function makeBook(id: number, overrides: Partial = {}): Book { + return { + id, + libraryId: 1, + libraryName: 'Library', + fileName: `Book ${id}`, + primaryFile: {id, bookId: id, bookType: 'EPUB'}, + metadata: { + bookId: id, + title: `Book ${id}`, + authors: [`Author ${id}`], + seriesName: `Series ${id}`, + publishedDate: '2024-01-01', + pageCount: id * 100, + }, + ...overrides, + }; +} + +describe('SortService', () => { + const service = new SortService(); + + it('returns the original array when no sort is provided', () => { + const books = [makeBook(1), makeBook(2)]; + + expect(service.applySort(books, null)).toBe(books); + expect(service.applyMultiSort(books, [])).toBe(books); + }); + + it('sorts by title and file name using natural ordering', () => { + const books = [ + makeBook(2, {fileName: 'Book 10', metadata: {bookId: 2, title: 'Book 10'}}), + makeBook(1, {fileName: 'Book 2', metadata: {bookId: 1, title: 'Book 2'}}), + ]; + const sortOption: SortOption = {label: 'Title', field: 'title', direction: SortDirection.ASCENDING}; + + expect(service.applySort(books, sortOption).map(book => book.id)).toEqual([1, 2]); + }); + + it('sorts by array fields and read status rank', () => { + const books = [ + makeBook(1, {metadata: {bookId: 1, authors: ['Jane Zed']}, readStatus: ReadStatus.READ}), + makeBook(2, {metadata: {bookId: 2, authors: ['Adam Alpha']}, readStatus: ReadStatus.READING}), + makeBook(3, {metadata: {bookId: 3, authors: ['Jane Zed']}, readStatus: ReadStatus.UNREAD}), + ]; + + expect(service.applyMultiSort(books, [ + {label: 'Authors', field: 'authorSurnameVorname', direction: SortDirection.ASCENDING}, + ]).map(book => book.id)).toEqual([2, 1, 3]); + + expect(service.applyMultiSort(books, [ + {label: 'Status', field: 'readStatus', direction: SortDirection.DESCENDING}, + ]).map(book => book.id)).toEqual([1, 2, 3]); + }); + + it('keeps null values sorted after non-null values and warns on unknown fields', () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const books = [ + makeBook(1, {metadata: {bookId: 1}}), + makeBook(2, {metadata: {bookId: 2, publishedDate: '2023-01-01'}}), + ]; + + expect(service.applyMultiSort(books, [ + {label: 'Published', field: 'publishedDate', direction: SortDirection.ASCENDING}, + ]).map(book => book.id)).toEqual([2, 1]); + + expect(service.applyMultiSort(books, [ + {label: 'Unknown', field: 'doesNotExist', direction: SortDirection.ASCENDING}, + ])).toEqual(books); + expect(warnSpy).toHaveBeenCalledWith('[SortService] No extractor for field: doesNotExist'); + }); +}); diff --git a/frontend/src/app/features/bookdrop/component/bookdrop-bulk-edit-dialog/bookdrop-bulk-edit-dialog.component.spec.ts b/frontend/src/app/features/bookdrop/component/bookdrop-bulk-edit-dialog/bookdrop-bulk-edit-dialog.component.spec.ts new file mode 100644 index 000000000..6fe39a267 --- /dev/null +++ b/frontend/src/app/features/bookdrop/component/bookdrop-bulk-edit-dialog/bookdrop-bulk-edit-dialog.component.spec.ts @@ -0,0 +1,99 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {getTranslocoModule} from '../../../../core/testing/transloco-testing'; +import {BookdropBulkEditDialogComponent, BulkEditResult} from './bookdrop-bulk-edit-dialog.component'; + +describe('BookdropBulkEditDialogComponent', () => { + let fixture: ComponentFixture; + let component: BookdropBulkEditDialogComponent; + let dialogRef: {close: ReturnType}; + + beforeEach(async () => { + dialogRef = { + close: vi.fn(), + }; + + await TestBed.configureTestingModule({ + imports: [BookdropBulkEditDialogComponent, getTranslocoModule()], + providers: [ + {provide: DynamicDialogRef, useValue: dialogRef}, + {provide: DynamicDialogConfig, useValue: {data: {fileCount: 4}}}, + ], + }).compileComponents(); + + fixture = TestBed.createComponent(BookdropBulkEditDialogComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + function blurAutoComplete(fieldName: string, value: string) { + const input = document.createElement('input'); + input.value = value; + + component.onAutoCompleteBlur(fieldName, {target: input} as unknown as Event); + + return input; + } + + it('hydrates the file count and enables fields when form controls receive values', () => { + component.getControl('seriesName').setValue('Saga'); + component.getControl('seriesTotal').setValue(7); + + expect(component.fileCount).toBe(4); + expect(component.enabledFields.has('seriesName')).toBe(true); + expect(component.enabledFields.has('seriesTotal')).toBe(true); + expect(component.hasEnabledFields).toBe(true); + }); + + it('adds trimmed autocomplete blur values once, clears the input, and enables the chip field', () => { + const firstInput = blurAutoComplete('authors', ' Octavia Butler '); + const duplicateInput = blurAutoComplete('authors', 'Octavia Butler'); + const blankInput = blurAutoComplete('authors', ' '); + + expect(component.getControl('authors').value).toEqual(['Octavia Butler']); + expect(component.enabledFields.has('authors')).toBe(true); + expect(firstInput.value).toBe(''); + expect(duplicateInput.value).toBe(''); + expect(blankInput.value).toBe(' '); + }); + + it('toggles fields on and off explicitly', () => { + component.toggleField('publisher'); + expect(component.isFieldEnabled('publisher')).toBe(true); + + component.toggleField('publisher'); + expect(component.isFieldEnabled('publisher')).toBe(false); + }); + + it('applies only enabled non-null fields and preserves merge mode in the dialog result', () => { + component.getControl('seriesName').setValue('Saga'); + component.getControl('authors').setValue(['Octavia Butler', 'N. K. Jemisin']); + component.toggleField('publisher'); + component.mergeArrays = false; + + component.apply(); + + const result = dialogRef.close.mock.calls[0]?.[0] as BulkEditResult; + + expect(result.fields).toEqual({ + seriesName: 'Saga', + authors: ['Octavia Butler', 'N. K. Jemisin'], + publisher: '', + }); + expect(result.enabledFields).toEqual(new Set(['seriesName', 'authors', 'publisher'])); + expect(result.mergeArrays).toBe(false); + }); + + it('closes the dialog with null when cancelled', () => { + component.cancel(); + + expect(dialogRef.close).toHaveBeenCalledWith(null); + }); +}); diff --git a/frontend/src/app/features/bookdrop/component/bookdrop-file-metadata-picker/bookdrop-file-metadata-picker.component.spec.ts b/frontend/src/app/features/bookdrop/component/bookdrop-file-metadata-picker/bookdrop-file-metadata-picker.component.spec.ts new file mode 100644 index 000000000..64ae39c80 --- /dev/null +++ b/frontend/src/app/features/bookdrop/component/bookdrop-file-metadata-picker/bookdrop-file-metadata-picker.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around dialog payload bootstrapping, +// autocomplete/search streams, and metadata copy/reset helpers so picker decisions can be +// asserted without the full bookdrop dialog and PrimeNG form runtime. +describe.skip('BookdropFileMetadataPickerComponent', () => { + it('needs dialog and form seams to verify metadata bootstrap, reset, and apply behavior', () => { + // TODO(seam): Cover initialization and confirmation branches once DynamicDialog config and reactive-form setup are isolated behind test doubles. + }); + + it('needs search seams to verify candidate loading, selection changes, and duplicate-handling paths', () => { + // TODO(seam): Cover autocomplete and metadata transfer flows after search streams and select widgets are extracted from the live component runtime. + }); +}); diff --git a/frontend/src/app/features/bookdrop/component/bookdrop-file-review/bookdrop-file-review.component.spec.ts b/frontend/src/app/features/bookdrop/component/bookdrop-file-review/bookdrop-file-review.component.spec.ts new file mode 100644 index 000000000..a30bbe938 --- /dev/null +++ b/frontend/src/app/features/bookdrop/component/bookdrop-file-review/bookdrop-file-review.component.spec.ts @@ -0,0 +1,240 @@ +import {DestroyRef, signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {ActivatedRoute} from '@angular/router'; +import {FormGroup} from '@angular/forms'; +import {TranslocoService} from '@jsverse/transloco'; +import {ConfirmationService, MessageService} from 'primeng/api'; +import {of} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {AppSettingsService} from '../../../../shared/service/app-settings.service'; +import {DialogLauncherService} from '../../../../shared/services/dialog-launcher.service'; +import {PageTitleService} from '../../../../shared/service/page-title.service'; +import {UrlHelperService} from '../../../../shared/service/url-helper.service'; +import {BookdropFileReviewComponent, BookdropFileUI} from './bookdrop-file-review.component'; +import {BookdropFile, BookdropFileStatus, BookdropService} from '../../service/bookdrop.service'; +import {Library} from '../../../book/model/library.model'; +import {LibraryService} from '../../../book/service/library.service'; + +describe('BookdropFileReviewComponent', () => { + const add = vi.fn(); + const confirm = vi.fn(); + const getPendingFiles = vi.fn(); + const discardFiles = vi.fn(); + const finalizeImport = vi.fn(); + const rescan = vi.fn(); + const openBookdropFinalizeResultDialog = vi.fn(); + const openDialog = vi.fn(); + const openDirectoryPickerDialog = vi.fn(); + const setPageTitle = vi.fn(); + const translate = vi.fn((key: string, params?: Record) => { + if (!params) { + return key; + } + + return `${key}:${Object.entries(params).map(([paramKey, value]) => `${paramKey}=${value}`).join(',')}`; + }); + + const libraries = signal([]); + const appSettings = signal(null); + + function makeLibrary(id: number, name: string, pathIds: number[]): Library { + return { + id, + name, + watch: false, + paths: pathIds.map((pathId, index) => ({id: pathId, path: `${name}-${index + 1}`})), + }; + } + + function makeFile(id: number): BookdropFile { + return { + id, + fileName: `file-${id}.epub`, + filePath: `/incoming/file-${id}.epub`, + fileSize: 1024, + originalMetadata: {bookId: id, title: `Book ${id}`}, + createdAt: '2026-03-26T00:00:00Z', + updatedAt: '2026-03-26T00:00:00Z', + status: BookdropFileStatus.ACCEPTED, + showDetails: false, + }; + } + + function makeFileUi( + id: number, + overrides: Partial = {} + ): BookdropFileUI { + return { + file: makeFile(id), + metadataForm: new FormGroup({}), + copiedFields: {}, + savedFields: {}, + selected: false, + showDetails: false, + selectedLibraryId: null, + selectedPathId: null, + availablePaths: [], + ...overrides, + }; + } + + function createComponent(): BookdropFileReviewComponent { + TestBed.configureTestingModule({ + providers: [ + { + provide: BookdropService, + useValue: { + getPendingFiles, + discardFiles, + finalizeImport, + rescan, + }, + }, + { + provide: LibraryService, + useValue: { + libraries: libraries.asReadonly(), + }, + }, + {provide: ConfirmationService, useValue: {confirm}}, + {provide: DestroyRef, useValue: {onDestroy: vi.fn()}}, + { + provide: DialogLauncherService, + useValue: { + openBookdropFinalizeResultDialog, + openDialog, + openDirectoryPickerDialog, + }, + }, + {provide: AppSettingsService, useValue: {appSettings: appSettings.asReadonly()}}, + {provide: MessageService, useValue: {add}}, + {provide: UrlHelperService, useValue: {getBookdropCoverUrl: vi.fn((id: number) => `/covers/${id}`)}}, + {provide: ActivatedRoute, useValue: {queryParams: of({}), snapshot: {queryParams: {}}}}, + {provide: PageTitleService, useValue: {setPageTitle}}, + {provide: TranslocoService, useValue: {translate}}, + ], + }); + + return TestBed.runInInjectionContext(() => new BookdropFileReviewComponent()); + } + + beforeEach(() => { + add.mockClear(); + confirm.mockClear(); + getPendingFiles.mockReset(); + discardFiles.mockReset(); + finalizeImport.mockReset(); + rescan.mockReset(); + openBookdropFinalizeResultDialog.mockClear(); + openDialog.mockClear(); + openDirectoryPickerDialog.mockClear(); + setPageTitle.mockClear(); + translate.mockClear(); + libraries.set([]); + appSettings.set(null); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('derives defaults, selection counts, and finalize eligibility from both selection modes', () => { + libraries.set([ + makeLibrary(1, 'Alpha', [10]), + makeLibrary(2, 'Beta', [20, 21]), + ]); + + const component = createComponent(); + const first = makeFileUi(1, {selected: true, selectedLibraryId: '1', selectedPathId: '10'}); + const second = makeFileUi(2, {selected: true, selectedLibraryId: '1', selectedPathId: '10'}); + const third = makeFileUi(3, {selected: false}); + + component.fileUiCache = {1: first, 2: second, 3: third}; + component.bookdropFileUis = [first, second, third]; + + component.defaultLibraryId = '1'; + expect(component.defaultPathId).toBe('10'); + expect(component.selectedLibraryPaths).toEqual([{label: 'Alpha-1', value: '10'}]); + expect(component.canApplyDefaults).toBe(true); + + expect(component.hasSelectedFiles).toBe(true); + expect(component.selectedCount).toBe(2); + expect(component.canFinalize).toBe(true); + + second.selectedPathId = null; + component.fileUiCache[2].selectedPathId = null; + expect(component.canFinalize).toBe(false); + + second.selectedPathId = '10'; + component.fileUiCache[2].selectedPathId = '10'; + component.selectAllAcrossPages = true; + component.totalRecords = 10; + component.excludedFiles.add(3); + + expect(component.hasSelectedFiles).toBe(true); + expect(component.selectedCount).toBe(9); + expect(component.canFinalize).toBe(true); + + component.fileUiCache[2].selectedPathId = null; + expect(component.canFinalize).toBe(false); + }); + + it('keeps the current-page selection state in sync with select-all changes', () => { + const component = createComponent(); + const first = makeFileUi(1); + const second = makeFileUi(2); + + component.fileUiCache = {1: first, 2: second}; + component.bookdropFileUis = [first, second]; + + component.selectAll(true); + expect(component.selectAllAcrossPages).toBe(true); + expect(component.excludedFiles.size).toBe(0); + expect(component.bookdropFileUis.map(file => file.selected)).toEqual([true, true]); + expect(Object.values(component.fileUiCache).map(file => file.selected)).toEqual([true, true]); + + component.toggleFileSelection(1, false); + expect(component.excludedFiles.has(1)).toBe(true); + expect(component.fileUiCache[1].selected).toBe(false); + expect(component.bookdropFileUis[0].selected).toBe(false); + + component.toggleFileSelection(1, true); + expect(component.excludedFiles.has(1)).toBe(false); + expect(component.fileUiCache[1].selected).toBe(true); + + component.selectAll(false); + expect(component.selectAllAcrossPages).toBe(false); + expect(component.excludedFiles.size).toBe(0); + expect(component.bookdropFileUis.map(file => file.selected)).toEqual([false, false]); + expect(Object.values(component.fileUiCache).map(file => file.selected)).toEqual([false, false]); + }); + + it('warns instead of prompting when destructive actions have no selected files', () => { + const component = createComponent(); + component.bookdropFileUis = []; + component.fileUiCache = {}; + + component.confirmReset(); + component.confirmFinalize(); + component.confirmDelete(); + + expect(confirm).not.toHaveBeenCalled(); + expect(add).toHaveBeenCalledTimes(3); + expect(add).toHaveBeenNthCalledWith(1, expect.objectContaining({ + severity: 'warn', + summary: 'bookdrop.fileReview.toast.noFilesSelectedSummary', + detail: 'bookdrop.fileReview.toast.noFilesResetDetail', + })); + expect(add).toHaveBeenNthCalledWith(2, expect.objectContaining({ + severity: 'warn', + summary: 'bookdrop.fileReview.toast.noFilesSelectedSummary', + detail: 'bookdrop.fileReview.toast.noFilesFinalizeDetail', + })); + expect(add).toHaveBeenNthCalledWith(3, expect.objectContaining({ + severity: 'warn', + summary: 'bookdrop.fileReview.toast.noFilesSelectedSummary', + detail: 'bookdrop.fileReview.toast.noFilesDeleteDetail', + })); + }); +}); diff --git a/frontend/src/app/features/bookdrop/component/bookdrop-files-widget/bookdrop-files-widget.component.spec.ts b/frontend/src/app/features/bookdrop/component/bookdrop-files-widget/bookdrop-files-widget.component.spec.ts new file mode 100644 index 000000000..249afdc59 --- /dev/null +++ b/frontend/src/app/features/bookdrop/component/bookdrop-files-widget/bookdrop-files-widget.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around the live summary stream, router +// navigation timing, and widget lifecycle teardown so bookdrop notification state can be tested +// without mounting the live websocket-backed runtime. +describe.skip('BookdropFilesWidgetComponent', () => { + it('needs subscription seams to verify pending-count updates and timestamp hydration from summary notifications', () => { + // TODO(seam): Cover ngOnInit once the live summary observable is isolated behind a deterministic subject. + }); + + it('needs routing seams to verify review navigation and destroy-time subscription cleanup', () => { + // TODO(seam): Cover openReviewDialog and ngOnDestroy after extracting router and subscription lifecycle concerns. + }); +}); diff --git a/frontend/src/app/features/bookdrop/component/bookdrop-finalize-result-dialog/bookdrop-finalize-result-dialog.component.spec.ts b/frontend/src/app/features/bookdrop/component/bookdrop-finalize-result-dialog/bookdrop-finalize-result-dialog.component.spec.ts new file mode 100644 index 000000000..73413976b --- /dev/null +++ b/frontend/src/app/features/bookdrop/component/bookdrop-finalize-result-dialog/bookdrop-finalize-result-dialog.component.spec.ts @@ -0,0 +1,50 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {getTranslocoModule} from '../../../../core/testing/transloco-testing'; +import {BookdropFinalizeResultDialogComponent} from './bookdrop-finalize-result-dialog.component'; + +describe('BookdropFinalizeResultDialogComponent', () => { + let fixture: ComponentFixture; + let component: BookdropFinalizeResultDialogComponent; + let dialogRef: {close: ReturnType}; + const result = { + totalFiles: 4, + successfulFiles: 3, + failedFiles: 1, + finishedAt: '2026-03-26T00:00:00Z', + }; + + beforeEach(async () => { + dialogRef = { + close: vi.fn(), + }; + + await TestBed.configureTestingModule({ + imports: [BookdropFinalizeResultDialogComponent, getTranslocoModule()], + providers: [ + {provide: DynamicDialogRef, useValue: dialogRef}, + {provide: DynamicDialogConfig, useValue: {data: {result}}}, + ], + }).compileComponents(); + + fixture = TestBed.createComponent(BookdropFinalizeResultDialogComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('hydrates the finalize result from the dialog config', () => { + expect(component.result).toEqual(result); + }); + + it('closes the dialog when the component is destroyed', () => { + component.ngOnDestroy(); + + expect(dialogRef.close).toHaveBeenCalledOnce(); + }); +}); diff --git a/frontend/src/app/features/bookdrop/component/bookdrop-pattern-extract-dialog/bookdrop-pattern-extract-dialog.component.spec.ts b/frontend/src/app/features/bookdrop/component/bookdrop-pattern-extract-dialog/bookdrop-pattern-extract-dialog.component.spec.ts new file mode 100644 index 000000000..deb63f0e9 --- /dev/null +++ b/frontend/src/app/features/bookdrop/component/bookdrop-pattern-extract-dialog/bookdrop-pattern-extract-dialog.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around dialog payload bootstrapping, +// placeholder insertion with cursor management, preview extraction streams, and translated toast +// side effects so pattern extraction can be asserted without browser selection APIs. +describe.skip('BookdropPatternExtractDialogComponent', () => { + it('needs input-cursor seams to verify placeholder insertion, duplicate placeholder replacement, and common-pattern application', () => { + // TODO(seam): Cover insertPlaceholder and applyCommonPattern after input selection state and setTimeout cursor management are isolated behind deterministic helpers. + }); + + it('needs service seams to verify preview, extraction success, and extraction failure behavior', () => { + // TODO(seam): Cover previewPattern and extract once bookdrop service streams, dialog closing, and toast dispatch can be asserted without the live dialog runtime. + }); +}); diff --git a/frontend/src/app/features/bookdrop/service/bookdrop-file-api.service.spec.ts b/frontend/src/app/features/bookdrop/service/bookdrop-file-api.service.spec.ts new file mode 100644 index 000000000..f2680d15e --- /dev/null +++ b/frontend/src/app/features/bookdrop/service/bookdrop-file-api.service.spec.ts @@ -0,0 +1,48 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {BookdropFileApiService} from './bookdrop-file-api.service'; + +describe('BookdropFileApiService', () => { + let service: BookdropFileApiService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + BookdropFileApiService, + ], + }); + + service = TestBed.inject(BookdropFileApiService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('requests the current bookdrop notification summary', () => { + let result: unknown; + service.getNotification().subscribe(value => { + result = value; + }); + + const request = httpTestingController.expectOne(req => + req.url.endsWith('/api/v1/bookdrop/notification') + ); + expect(request.request.method).toBe('GET'); + request.flush({pendingCount: 3, totalCount: 8, lastUpdatedAt: '2026-03-26T00:00:00Z'}); + + expect(result).toEqual({ + pendingCount: 3, + totalCount: 8, + lastUpdatedAt: '2026-03-26T00:00:00Z', + }); + }); +}); diff --git a/frontend/src/app/features/bookdrop/service/bookdrop-file.service.spec.ts b/frontend/src/app/features/bookdrop/service/bookdrop-file.service.spec.ts new file mode 100644 index 000000000..490b753cc --- /dev/null +++ b/frontend/src/app/features/bookdrop/service/bookdrop-file.service.spec.ts @@ -0,0 +1,102 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {of, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {AuthService} from '../../../shared/service/auth.service'; +import {BookdropFileApiService} from './bookdrop-file-api.service'; +import {BookdropFileNotification, BookdropFileService} from './bookdrop-file.service'; +import {UserService} from '../../settings/user-management/user.service'; + +describe('BookdropFileService', () => { + let getNotification: ReturnType; + let currentUser: ReturnType>; + let token: ReturnType>; + let service: BookdropFileService; + + const summary: BookdropFileNotification = { + pendingCount: 2, + totalCount: 6, + lastUpdatedAt: '2026-03-26T00:00:00Z', + }; + + beforeEach(() => { + getNotification = vi.fn(() => of(summary)); + currentUser = signal({ + permissions: { + admin: false, + canAccessBookdrop: true, + }, + }); + token = signal('token'); + + TestBed.configureTestingModule({ + providers: [ + BookdropFileService, + {provide: BookdropFileApiService, useValue: {getNotification}}, + {provide: AuthService, useValue: {token}}, + {provide: UserService, useValue: {currentUser}}, + ], + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('initializes from the API once for users who can access bookdrop and have a token', () => { + service = TestBed.inject(BookdropFileService); + TestBed.flushEffects(); + + let latestSummary: BookdropFileNotification | undefined; + service.summary$.subscribe(value => { + latestSummary = value; + }); + + expect(getNotification).toHaveBeenCalledOnce(); + expect(latestSummary).toEqual(summary); + }); + + it('does not auto-refresh when the current user lacks access', () => { + currentUser.set({ + permissions: { + admin: false, + canAccessBookdrop: false, + }, + }); + + service = TestBed.inject(BookdropFileService); + TestBed.flushEffects(); + + expect(getNotification).not.toHaveBeenCalled(); + }); + + it('publishes incoming file summaries and pending state', () => { + service = TestBed.inject(BookdropFileService); + + let hasPendingFiles: boolean | undefined; + service.hasPendingFiles$.subscribe(value => { + hasPendingFiles = value; + }); + + service.handleIncomingFile(summary); + expect(hasPendingFiles).toBe(true); + + service.handleIncomingFile({...summary, pendingCount: 0}); + expect(hasPendingFiles).toBe(false); + }); + + it('warns when manual refresh fails', () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + getNotification.mockReturnValueOnce(throwError(() => new Error('boom'))); + service = TestBed.inject(BookdropFileService); + TestBed.flushEffects(); + + service.refresh(); + + expect(warnSpy).toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/app/features/bookdrop/service/bookdrop.service.spec.ts b/frontend/src/app/features/bookdrop/service/bookdrop.service.spec.ts new file mode 100644 index 000000000..51115b904 --- /dev/null +++ b/frontend/src/app/features/bookdrop/service/bookdrop.service.spec.ts @@ -0,0 +1,76 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {BookdropService} from './bookdrop.service'; + +describe('BookdropService', () => { + let service: BookdropService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + BookdropService, + ], + }); + + service = TestBed.inject(BookdropService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('requests pending files with default pagination', () => { + service.getPendingFiles().subscribe(); + + const request = httpTestingController.expectOne( + 'http://localhost:6060/api/v1/bookdrop/files?status=pending&page=0&size=50' + ); + expect(request.request.method).toBe('GET'); + request.flush({content: [], page: {totalElements: 0, totalPages: 0, number: 0, size: 50}}); + }); + + it('posts finalize, discard, rescan, extract, and bulk-edit requests to the expected endpoints', () => { + const finalizePayload = {selectAll: true}; + const discardPayload = {selectAll: false, selectedIds: [1, 2]}; + const extractPayload = {pattern: '{author}', preview: true}; + const bulkEditPayload = { + fields: {title: 'Dune'}, + enabledFields: ['title'], + mergeArrays: false, + }; + + service.finalizeImport(finalizePayload).subscribe(); + service.discardFiles(discardPayload).subscribe(); + service.rescan().subscribe(); + service.extractFromPattern(extractPayload).subscribe(); + service.bulkEditMetadata(bulkEditPayload).subscribe(); + + const finalizeRequest = httpTestingController.expectOne(req => req.url.includes('/api/v1/bookdrop/imports/finalize')); + expect(finalizeRequest.request.body).toEqual(finalizePayload); + finalizeRequest.flush({}); + + const discardRequest = httpTestingController.expectOne(req => req.url.includes('/api/v1/bookdrop/files/discard')); + expect(discardRequest.request.body).toEqual(discardPayload); + discardRequest.flush(null); + + const rescanRequest = httpTestingController.expectOne(req => req.url.includes('/api/v1/bookdrop/rescan')); + expect(rescanRequest.request.body).toEqual({}); + rescanRequest.flush(null); + + const extractRequest = httpTestingController.expectOne(req => req.url.includes('/api/v1/bookdrop/files/extract-pattern')); + expect(extractRequest.request.body).toEqual(extractPayload); + extractRequest.flush({}); + + const bulkEditRequest = httpTestingController.expectOne(req => req.url.includes('/api/v1/bookdrop/files/bulk-edit')); + expect(bulkEditRequest.request.body).toEqual(bulkEditPayload); + bulkEditRequest.flush({}); + }); +}); diff --git a/frontend/src/app/features/dashboard/components/dashboard-scroller/dashboard-scroller.component.spec.ts b/frontend/src/app/features/dashboard/components/dashboard-scroller/dashboard-scroller.component.spec.ts new file mode 100644 index 000000000..6ba70202b --- /dev/null +++ b/frontend/src/app/features/dashboard/components/dashboard-scroller/dashboard-scroller.component.spec.ts @@ -0,0 +1,10 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around ngx-infinite-scroll, nested book-card +// interactions, and overlay/menu state so scroller paging and open-menu coordination can be tested +// without booting a full dashboard rendering stack. +describe.skip('DashboardScrollerComponent', () => { + it('needs scroller and card seams to verify force-ebook mode, infinite scrolling, and menu-toggle behavior', () => { + // TODO(seam): Cover scroller rendering and book-card coordination once the scroll and card interactions are isolated. + }); +}); diff --git a/frontend/src/app/features/dashboard/components/dashboard-settings/dashboard-settings.component.spec.ts b/frontend/src/app/features/dashboard/components/dashboard-settings/dashboard-settings.component.spec.ts new file mode 100644 index 000000000..84fdf1096 --- /dev/null +++ b/frontend/src/app/features/dashboard/components/dashboard-settings/dashboard-settings.component.spec.ts @@ -0,0 +1,10 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around effect-driven dashboard config syncing, +// dynamic dialog lifecycle, translated option rebuilding, and magic-shelf collections so config edits +// can be asserted without coupling the spec to the full dashboard settings UI. +describe.skip('DashboardSettingsComponent', () => { + it('needs config and dialog seams to verify scroller add/remove/reorder behavior and translated option rebuilding', () => { + // TODO(seam): Cover dashboard config mutation and save/close flows once the config service and dialog interactions are wrapped. + }); +}); diff --git a/frontend/src/app/features/dashboard/components/main-dashboard/main-dashboard.component.spec.ts b/frontend/src/app/features/dashboard/components/main-dashboard/main-dashboard.component.spec.ts new file mode 100644 index 000000000..a09b8e997 --- /dev/null +++ b/frontend/src/app/features/dashboard/components/main-dashboard/main-dashboard.component.spec.ts @@ -0,0 +1,10 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around computed dashboard config signals, +// magic-shelf rule evaluation, sorting, dialog launches, and page-title side effects so scroller +// selection logic can be tested without instantiating the full dashboard ecosystem. +describe.skip('MainDashboardComponent', () => { + it('needs dashboard-config and magic-shelf seams to verify scroller book selection and page setup deterministically', () => { + // TODO(seam): Cover per-scroller book selection, randomization, and page-title behavior after the dependent services are adapterized. + }); +}); diff --git a/frontend/src/app/features/dashboard/models/dashboard-config.model.spec.ts b/frontend/src/app/features/dashboard/models/dashboard-config.model.spec.ts new file mode 100644 index 000000000..aa5a78a09 --- /dev/null +++ b/frontend/src/app/features/dashboard/models/dashboard-config.model.spec.ts @@ -0,0 +1,27 @@ +import {describe, expect, it} from 'vitest'; + +import {DEFAULT_DASHBOARD_CONFIG, ScrollerType} from './dashboard-config.model'; + +describe('dashboard-config.model', () => { + it('ships with four enabled default scrollers', () => { + expect(DEFAULT_DASHBOARD_CONFIG.scrollers).toHaveLength(4); + expect(DEFAULT_DASHBOARD_CONFIG.scrollers.every((scroller) => scroller.enabled)).toBe(true); + }); + + it('uses ordered defaults and a shared max-items value across all defaults', () => { + const maxItems = DEFAULT_DASHBOARD_CONFIG.scrollers.map((scroller) => scroller.maxItems); + + expect(DEFAULT_DASHBOARD_CONFIG.scrollers.map((scroller) => scroller.order)).toEqual([1, 2, 3, 4]); + expect(new Set(maxItems).size).toBe(1); + expect(maxItems[0]).toBeGreaterThan(0); + }); + + it('covers the expected default scroller types', () => { + expect(DEFAULT_DASHBOARD_CONFIG.scrollers.map((scroller) => scroller.type)).toEqual([ + ScrollerType.LAST_LISTENED, + ScrollerType.LAST_READ, + ScrollerType.LATEST_ADDED, + ScrollerType.RANDOM + ]); + }); +}); diff --git a/frontend/src/app/features/dashboard/services/dashboard-config.service.spec.ts b/frontend/src/app/features/dashboard/services/dashboard-config.service.spec.ts new file mode 100644 index 000000000..ffeaeae2b --- /dev/null +++ b/frontend/src/app/features/dashboard/services/dashboard-config.service.spec.ts @@ -0,0 +1,135 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {MagicShelfService, type MagicShelf} from '../../magic-shelf/service/magic-shelf.service'; +import {UserService} from '../../settings/user-management/user.service'; +import {DEFAULT_DASHBOARD_CONFIG, type DashboardConfig, ScrollerType} from '../models/dashboard-config.model'; +import {DashboardConfigService} from './dashboard-config.service'; + +describe('DashboardConfigService', () => { + const updateUserSetting = vi.fn(); + interface TestUser { + id: number; + userSettings?: { + dashboardConfig?: DashboardConfig; + }; + } + const userState = signal(null); + const shelvesState = signal([]); + + const userService = { + currentUser: userState.asReadonly(), + getCurrentUser: vi.fn(() => userState()), + updateUserSetting, + }; + + const magicShelfService = { + shelves: shelvesState.asReadonly(), + }; + + beforeEach(() => { + vi.restoreAllMocks(); + updateUserSetting.mockReset(); + userService.getCurrentUser.mockReset(); + userService.getCurrentUser.mockImplementation(() => userState()); + userState.set(null); + shelvesState.set([]); + + TestBed.configureTestingModule({ + providers: [ + DashboardConfigService, + {provide: UserService, useValue: userService}, + {provide: MagicShelfService, useValue: magicShelfService}, + ], + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('normalizes missing dashboard config to a cloned default value', () => { + userState.set({ + id: 11, + userSettings: {dashboardConfig: {scrollers: []}}, + }); + + const service = TestBed.inject(DashboardConfigService); + + expect(service.config()).toEqual(DEFAULT_DASHBOARD_CONFIG); + expect(service.config()).not.toBe(DEFAULT_DASHBOARD_CONFIG); + }); + + it('syncs renamed magic shelf titles into the config and persists the change', async () => { + userState.set({ + id: 12, + userSettings: { + dashboardConfig: { + scrollers: [ + { + id: '1', + type: ScrollerType.MAGIC_SHELF, + title: 'Old shelf title', + enabled: true, + order: 1, + maxItems: 20, + magicShelfId: 55, + }, + ], + }, + }, + }); + + const service = TestBed.inject(DashboardConfigService); + await new Promise(resolve => setTimeout(resolve, 0)); + await new Promise(resolve => setTimeout(resolve, 0)); + shelvesState.set([{id: 55, name: 'New shelf title', filterJson: '{}'} as MagicShelf]); + await new Promise(resolve => setTimeout(resolve, 0)); + await new Promise(resolve => setTimeout(resolve, 0)); + + expect(service.config().scrollers[0].title).toBe('New shelf title'); + expect(updateUserSetting).toHaveBeenCalledWith(12, 'dashboardConfig', { + scrollers: [ + { + id: '1', + type: ScrollerType.MAGIC_SHELF, + title: 'New shelf title', + enabled: true, + order: 1, + maxItems: 20, + magicShelfId: 55, + }, + ], + }); + }); + + it('saves normalized configs and skips persistence when no user is available', () => { + const service = TestBed.inject(DashboardConfigService); + + service.saveConfig({ + scrollers: [ + { + id: '9', + type: ScrollerType.LATEST_ADDED, + title: 'recent', + enabled: true, + order: 1, + maxItems: 15, + }, + ], + }); + + expect(service.config().scrollers[0].id).toBe('9'); + expect(updateUserSetting).not.toHaveBeenCalled(); + + userState.set({ + id: 21, + userSettings: {dashboardConfig: DEFAULT_DASHBOARD_CONFIG}, + }); + + service.resetToDefault(); + + expect(updateUserSetting).toHaveBeenCalledWith(21, 'dashboardConfig', DEFAULT_DASHBOARD_CONFIG); + }); +}); diff --git a/frontend/src/app/features/library-creator/library-creator.component.spec.ts b/frontend/src/app/features/library-creator/library-creator.component.spec.ts new file mode 100644 index 000000000..531f7db93 --- /dev/null +++ b/frontend/src/app/features/library-creator/library-creator.component.spec.ts @@ -0,0 +1,17 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): This component currently couples DynamicDialog config/ref data, +// router navigation, live library/icon services, format-count HTTP reads, drag-drop, and +// transloco-backed option initialization in one large standalone surface. Honest coverage +// needs a narrower presenter seam or a purpose-built harness, not a brittle all-up mock stack. +describe.skip('LibraryCreatorComponent', () => { + it('needs a dialog-and-library seam to verify create vs edit initialization and duplicate-name handling', () => { + // TODO(seam): Cover dialog mode hydration, icon normalization, and duplicate-name validation + // once the component state can be supplied without mocking the full runtime graph. + }); + + it('needs a stable interaction seam to verify format selection, folder updates, and submit payload assembly', () => { + // TODO(seam): Cover allowed-format toggles, folder selection, and create/update submission + // after these flows are exposed behind testable methods or a smaller facade. + }); +}); diff --git a/frontend/src/app/features/library-creator/library-loading.service.spec.ts b/frontend/src/app/features/library-creator/library-loading.service.spec.ts new file mode 100644 index 000000000..6fa5434c0 --- /dev/null +++ b/frontend/src/app/features/library-creator/library-loading.service.spec.ts @@ -0,0 +1,13 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Replace this skipped spec once the component-factory lifecycle +// is wrapped behind a testable seam. The current service hard-codes Angular's +// `createComponent()` ESM export plus direct `document.body` mutation, and Vitest in +// this browser-mode setup cannot reliably intercept that export to prove attach/detach +// behavior without changing runtime code. +describe.skip('LibraryLoadingService', () => { + it('needs a component-factory seam to verify dynamic creation and teardown', () => { + // TODO(seam): Cover component creation, progress updates, and body overflow cleanup + // after introducing a testable wrapper around createComponent/document.body behavior. + }); +}); diff --git a/frontend/src/app/features/library-creator/library-loading/library-loading.component.spec.ts b/frontend/src/app/features/library-creator/library-loading/library-loading.component.spec.ts new file mode 100644 index 000000000..bae299623 --- /dev/null +++ b/frontend/src/app/features/library-creator/library-loading/library-loading.component.spec.ts @@ -0,0 +1,39 @@ +import {describe, expect, it} from 'vitest'; + +import {LibraryLoadingComponent} from './library-loading.component'; + +describe('LibraryLoadingComponent', () => { + it('computes progress percentage and completion state from the latest update', () => { + const component = new LibraryLoadingComponent(); + + component.updateProgress('Dune', 2, 3); + + expect(component.bookTitle).toBe('Dune'); + expect(component.current).toBe(2); + expect(component.total).toBe(3); + expect(component.percentage).toBe(67); + expect(component.isComplete).toBe(false); + }); + + it('marks the flow complete when current reaches the total', () => { + const component = new LibraryLoadingComponent(); + + component.updateProgress('Children of Dune', 5, 5); + + expect(component.isComplete).toBe(true); + expect(component.percentage).toBe(100); + }); + + it('truncates very long titles for display', () => { + const component = new LibraryLoadingComponent(); + component.bookTitle = 'A'.repeat(60); + + expect(component.truncatedTitle).toBe(`${'A'.repeat(50)}...`); + }); + + it('returns zero percent when there is no total yet', () => { + const component = new LibraryLoadingComponent(); + + expect(component.percentage).toBe(0); + }); +}); diff --git a/frontend/src/app/features/magic-shelf/service/magic-shelf.service.spec.ts b/frontend/src/app/features/magic-shelf/service/magic-shelf.service.spec.ts new file mode 100644 index 000000000..672ab9fd1 --- /dev/null +++ b/frontend/src/app/features/magic-shelf/service/magic-shelf.service.spec.ts @@ -0,0 +1,254 @@ +import {HttpTestingController} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {createAuthServiceStub, createQueryClientHarness, flushSignalAndQueryEffects} from '../../../core/testing/query-testing'; +import type {Book} from '../../book/model/book.model'; +import {AuthService} from '../../../shared/service/auth.service'; +import type {GroupRule} from '../component/magic-shelf-component'; +import {BookService} from '../../book/service/book.service'; +import {BookRuleEvaluatorService} from './book-rule-evaluator.service'; +import {MagicShelfService, type MagicShelf} from './magic-shelf.service'; + +function buildMagicShelf(overrides: Partial = {}): MagicShelf { + return { + id: 1, + name: 'Favorites', + icon: 'pi pi-star', + iconType: 'PRIME_NG', + filterJson: JSON.stringify(buildGroupRule()), + isPublic: false, + ...overrides, + }; +} + +function buildGroupRule(overrides: Partial = {}): GroupRule { + return { + name: 'Favorites', + type: 'group', + join: 'and', + rules: [], + ...overrides, + }; +} + +function buildBook(id: number, overrides: Partial = {}): Book { + return { + id, + libraryId: 1, + libraryName: 'Main Library', + metadata: { + bookId: id, + title: `Book ${id}`, + }, + ...overrides, + }; +} + +async function flushShelvesQuery(): Promise { + await Promise.resolve(); + flushSignalAndQueryEffects(); + await new Promise(resolve => setTimeout(resolve, 0)); + flushSignalAndQueryEffects(); + await Promise.resolve(); + flushSignalAndQueryEffects(); +} + +describe('MagicShelfService', () => { + let service: MagicShelfService; + let httpTestingController: HttpTestingController; + let authService: ReturnType; + let queryClientHarness: ReturnType; + let bookService: { + books: ReturnType; + }; + let ruleEvaluatorService: { + evaluateGroup: ReturnType; + }; + + beforeEach(() => { + authService = createAuthServiceStub(); + queryClientHarness = createQueryClientHarness(); + queryClientHarness.queryClient.setDefaultOptions({ + queries: { + retry: false, + }, + }); + + bookService = { + books: vi.fn(() => []), + }; + ruleEvaluatorService = { + evaluateGroup: vi.fn(() => false), + }; + + vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined); + vi.spyOn(queryClientHarness.queryClient, 'removeQueries').mockImplementation(() => undefined); + + TestBed.configureTestingModule({ + providers: [ + ...queryClientHarness.providers, + MagicShelfService, + {provide: AuthService, useValue: authService}, + {provide: BookService, useValue: bookService}, + {provide: BookRuleEvaluatorService, useValue: ruleEvaluatorService}, + ], + }); + + service = TestBed.inject(MagicShelfService); + httpTestingController = TestBed.inject(HttpTestingController); + flushSignalAndQueryEffects(); + }); + + afterEach(() => { + httpTestingController.verify(); + queryClientHarness.queryClient.clear(); + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('eagerly fetches shelves and hydrates the computed shelves signal', async () => { + const shelves = [ + buildMagicShelf({id: 1, name: 'Reading'}), + buildMagicShelf({id: 2, name: 'Finished', isPublic: true}), + ]; + + expect(service.shelves()).toEqual([]); + expect(service.isShelvesLoading()).toBe(true); + expect(service.shelvesError()).toBeNull(); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/magic-shelves')); + expect(request.request.method).toBe('GET'); + request.flush(shelves); + await flushShelvesQuery(); + + expect(service.shelves()).toEqual(shelves); + expect(service.isShelvesLoading()).toBe(false); + expect(service.shelvesError()).toBeNull(); + }); + + it('removes shelf queries when the auth token is cleared', async () => { + const removeQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'removeQueries').mockImplementation(() => undefined); + + httpTestingController.expectOne(req => req.url.endsWith('/api/magic-shelves')).flush([ + buildMagicShelf({id: 7, name: 'Cached'}), + ]); + await flushShelvesQuery(); + + authService.token.set(null); + flushSignalAndQueryEffects(); + + expect(removeQueriesSpy).toHaveBeenCalledWith({queryKey: ['magicShelves']}); + }); + + it('invalidates shelf queries after save and serializes the group payload', () => { + const invalidateQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined); + const group = buildGroupRule({ + rules: [ + { + field: 'title', + operator: 'contains', + value: 'magic', + }, + ], + }); + + httpTestingController.expectOne(req => req.url.endsWith('/api/magic-shelves')).flush([]); + + service.saveShelf({ + name: 'Magic', + icon: 'pi pi-bolt', + iconType: 'PRIME_NG', + group, + isPublic: true, + }).subscribe(); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/magic-shelves')); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual(expect.objectContaining({ + name: 'Magic', + icon: 'pi pi-bolt', + iconType: 'PRIME_NG', + filterJson: JSON.stringify(group), + isPublic: true, + })); + request.flush(buildMagicShelf({id: 11, name: 'Magic', filterJson: JSON.stringify(group), isPublic: true})); + + expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['magicShelves'], exact: true}); + }); + + it('invalidates shelf queries after delete', () => { + const invalidateQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined); + + httpTestingController.expectOne(req => req.url.endsWith('/api/magic-shelves')).flush([]); + + service.deleteShelf(11).subscribe(); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/magic-shelves/11')); + expect(request.request.method).toBe('DELETE'); + request.flush(null); + + expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['magicShelves'], exact: true}); + }); + + it('finds shelves by id from the hydrated query state', async () => { + const readingShelf = buildMagicShelf({id: 1, name: 'Reading'}); + const archiveShelf = buildMagicShelf({id: 2, name: 'Archive'}); + + httpTestingController.expectOne(req => req.url.endsWith('/api/magic-shelves')).flush([ + readingShelf, + archiveShelf, + ]); + await flushShelvesQuery(); + + expect(service.findShelfById(2)).toEqual(archiveShelf); + expect(service.findShelfById(999)).toBeUndefined(); + }); + + it('returns zero and logs when a shelf filter contains invalid JSON', async () => { + const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined); + + httpTestingController.expectOne(req => req.url.endsWith('/api/magic-shelves')).flush([ + buildMagicShelf({id: 1, filterJson: '{invalid-json'}), + ]); + await flushShelvesQuery(); + + expect(service.getBookCountValue(1)).toBe(0); + expect(bookService.books).not.toHaveBeenCalled(); + expect(ruleEvaluatorService.evaluateGroup).not.toHaveBeenCalled(); + expect(consoleErrorSpy).toHaveBeenCalledWith('Invalid filter JSON', expect.any(SyntaxError)); + }); + + it('counts matching books against the parsed shelf rule group', async () => { + const group = buildGroupRule({ + rules: [ + { + field: 'title', + operator: 'contains', + value: 'book', + }, + ], + }); + const books = [ + buildBook(1), + buildBook(2), + buildBook(3), + ]; + + bookService.books.mockReturnValue(books); + ruleEvaluatorService.evaluateGroup.mockImplementation((book: Book, parsedGroup: GroupRule, allBooks: Book[]) => + parsedGroup.name === group.name && allBooks === books && book.id !== 2 + ); + + httpTestingController.expectOne(req => req.url.endsWith('/api/magic-shelves')).flush([ + buildMagicShelf({id: 5, filterJson: JSON.stringify(group)}), + ]); + await flushShelvesQuery(); + + expect(service.getBookCountValue(5)).toBe(2); + expect(ruleEvaluatorService.evaluateGroup).toHaveBeenCalledTimes(3); + expect(ruleEvaluatorService.evaluateGroup).toHaveBeenNthCalledWith(1, books[0], group, books); + expect(ruleEvaluatorService.evaluateGroup).toHaveBeenNthCalledWith(2, books[1], group, books); + expect(ruleEvaluatorService.evaluateGroup).toHaveBeenNthCalledWith(3, books[2], group, books); + }); +}); diff --git a/frontend/src/app/features/metadata/component/book-metadata-center/book-metadata-center.component.spec.ts b/frontend/src/app/features/metadata/component/book-metadata-center/book-metadata-center.component.spec.ts new file mode 100644 index 000000000..87fc28eb9 --- /dev/null +++ b/frontend/src/app/features/metadata/component/book-metadata-center/book-metadata-center.component.spec.ts @@ -0,0 +1,9 @@ +import {describe, expect, it} from 'vitest'; + +// TODO(seam): This surface combines routed params, dynamic-dialog inputs, TanStack query +// state, and metadata-host book switching, so it needs a routed integration harness. +describe.skip('BookMetadataCenterComponent', () => { + it('needs a routed dialog harness for tab sync, book switching, and recommendation loading', () => { + expect.hasAssertions(); + }); +}); diff --git a/frontend/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.spec.ts b/frontend/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.spec.ts new file mode 100644 index 000000000..3084c0e54 --- /dev/null +++ b/frontend/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.spec.ts @@ -0,0 +1,152 @@ +import {SimpleChange} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {of, throwError} from 'rxjs'; +import {TranslocoService} from '@jsverse/transloco'; + +import {ReadingSessionApiService, ReadingSessionResponse} from '../../../../../shared/service/reading-session-api.service'; +import {BookReadingSessionsComponent} from './book-reading-sessions.component'; + +describe('BookReadingSessionsComponent', () => { + const getSessionsByBookId = vi.fn(); + const translate = vi.fn((key: string) => `translated:${key}`); + + function createSession(overrides: Partial = {}): ReadingSessionResponse { + return { + id: 1, + bookId: 7, + bookTitle: 'Example', + bookType: 'EPUB', + startTime: '2026-03-26T10:00:00Z', + endTime: '2026-03-26T10:05:30Z', + durationSeconds: 330, + startProgress: 10, + endProgress: 18, + progressDelta: 8, + startLocation: '15', + endLocation: '20', + createdAt: '2026-03-26T10:05:30Z', + ...overrides, + }; + } + + beforeEach(() => { + getSessionsByBookId.mockReset(); + translate.mockClear(); + + TestBed.configureTestingModule({ + providers: [ + {provide: ReadingSessionApiService, useValue: {getSessionsByBookId}}, + {provide: TranslocoService, useValue: {translate}}, + ] + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('loads reading sessions on init and exposes the translated page report template', () => { + const session = createSession(); + getSessionsByBookId.mockReturnValue(of({ + content: [session], + page: {totalElements: 1, totalPages: 1, number: 0, size: 100}, + })); + + const component = TestBed.runInInjectionContext(() => new BookReadingSessionsComponent()); + component.bookId = 7; + component.ngOnInit(); + + expect(getSessionsByBookId).toHaveBeenCalledWith(7, 0, 100); + expect(component.sessions).toEqual([session]); + expect(component.loading).toBe(false); + expect(component.pageReportTemplate).toBe('translated:metadata.readingSessions.pageReport'); + }); + + it('reloads when the book id changes after the first change and clears loading on errors', () => { + getSessionsByBookId + .mockReturnValueOnce(throwError(() => new Error('failed'))) + .mockReturnValueOnce(of({ + content: [createSession({id: 2, bookId: 9})], + page: {totalElements: 1, totalPages: 1, number: 0, size: 100}, + })); + + const component = TestBed.runInInjectionContext(() => new BookReadingSessionsComponent()); + component.bookId = 7; + + component.loadSessions(); + expect(component.loading).toBe(false); + expect(component.sessions).toEqual([]); + + component.bookId = 9; + component.ngOnChanges({ + bookId: new SimpleChange(7, 9, false), + }); + + expect(getSessionsByBookId).toHaveBeenNthCalledWith(2, 9, 0, 100); + expect(component.sessions).toEqual([createSession({id: 2, bookId: 9})]); + expect(component.loading).toBe(false); + }); + + it('ignores the initial ngOnChanges first-change event', () => { + const component = TestBed.runInInjectionContext(() => new BookReadingSessionsComponent()); + + component.ngOnChanges({ + bookId: new SimpleChange(undefined, 7, true), + }); + + expect(getSessionsByBookId).not.toHaveBeenCalled(); + }); + + it('formats durations, actual durations, and date helpers consistently', () => { + const component = TestBed.runInInjectionContext(() => new BookReadingSessionsComponent()); + const session = createSession(); + + expect(component.formatDuration(3725)).toBe('1h 2m'); + expect(component.formatDuration(125)).toBe('2m 5s'); + expect(component.formatDuration(45)).toBe('45s'); + expect(component.calculateActualDuration(session)).toBe(330); + expect(component.getActualDuration(session)).toBe('5m 30s'); + expect(component.getActualDuration(createSession({durationSeconds: 300}))).toBe('5m 30s'); + expect(component.formatDate(session.startTime)).toBe(new Date(session.startTime).toLocaleString()); + expect(component.formatSessionDate(session.startTime)).toBe(new Date(session.startTime).toLocaleDateString(undefined, { + month: 'short', + day: 'numeric', + year: 'numeric' + })); + expect(component.formatTime(session.startTime)).toBe(new Date(session.startTime).toLocaleTimeString(undefined, { + hour: 'numeric', + minute: '2-digit' + })); + }); + + it('maps book types, progress deltas, and location formatting branches', () => { + const component = TestBed.runInInjectionContext(() => new BookReadingSessionsComponent()); + const pageSession = createSession(); + const audioSession = createSession({bookType: 'AUDIOBOOK', startLocation: '00:01:00', endLocation: '00:02:00'}); + + expect(component.getBookTypeIcon('PDF')).toBe('pi pi-file-pdf'); + expect(component.getBookTypeIcon('CBR')).toBe('pi pi-images'); + expect(component.getBookTypeIcon('UNKNOWN')).toBe('pi pi-file'); + expect(component.formatBookType('AUDIOBOOK')).toBe('translated:metadata.readingSessions.audio'); + expect(component.formatBookType('EPUB')).toBe('EPUB'); + + expect(component.getProgressColor(3)).toBe('success'); + expect(component.getProgressColor(-1)).toBe('danger'); + expect(component.getProgressColor(0)).toBe('secondary'); + expect(component.getProgressDeltaClass(3)).toBe('progress-positive'); + expect(component.getProgressDeltaClass(-1)).toBe('progress-negative'); + expect(component.getProgressDeltaClass(0)).toBe('progress-neutral'); + expect(component.getProgressDeltaIcon(3)).toBe('pi pi-arrow-up'); + expect(component.getProgressDeltaIcon(-1)).toBe('pi pi-arrow-down'); + expect(component.getProgressDeltaIcon(0)).toBe('pi pi-minus'); + + expect(component.isPageNumber('15')).toBe(true); + expect(component.isPageNumber('chapter-1')).toBe(false); + expect(component.isPageNumber(undefined)).toBe(false); + expect(component.formatLocation(pageSession)).toBe('translated:metadata.readingSessions.page 15 → 20'); + expect(component.formatLocation(audioSession)).toBe('00:01:00 → 00:02:00'); + expect(component.formatLocation(createSession({startLocation: undefined, endLocation: undefined}))).toBe('-'); + expect(component.formatLocation(createSession({startLocation: 'chapter-1', endLocation: 'chapter-2'}))).toBe('-'); + }); +}); diff --git a/frontend/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.spec.ts b/frontend/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.spec.ts new file mode 100644 index 000000000..7ab2d2c8d --- /dev/null +++ b/frontend/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.spec.ts @@ -0,0 +1,9 @@ +import {describe, expect, it} from 'vitest'; + +// TODO(seam): The metadata editor requires a high-fidelity form harness for PrimeNG +// upload, autocomplete, drag-drop author ordering, router navigation, and autosave flows. +describe.skip('MetadataEditorComponent', () => { + it('needs an integration harness for form population, upload, save, and navigation branches', () => { + expect.hasAssertions(); + }); +}); diff --git a/frontend/src/app/features/metadata/component/book-metadata-center/metadata-picker/metadata-picker.component.spec.ts b/frontend/src/app/features/metadata/component/book-metadata-center/metadata-picker/metadata-picker.component.spec.ts new file mode 100644 index 000000000..3a97c6d97 --- /dev/null +++ b/frontend/src/app/features/metadata/component/book-metadata-center/metadata-picker/metadata-picker.component.spec.ts @@ -0,0 +1,298 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {of} from 'rxjs'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {MessageService} from 'primeng/api'; +import {TranslocoService} from '@jsverse/transloco'; +import {CdkDragDrop} from '@angular/cdk/drag-drop'; +import {AutoCompleteSelectEvent} from 'primeng/autocomplete'; + +import {Book, BookMetadata} from '../../../../book/model/book.model'; +import {BookService} from '../../../../book/service/book.service'; +import {BookMetadataManageService} from '../../../../book/service/book-metadata-manage.service'; +import {AppSettings} from '../../../../../shared/model/app-settings.model'; +import {AppSettingsService} from '../../../../../shared/service/app-settings.service'; +import {UrlHelperService} from '../../../../../shared/service/url-helper.service'; +import {MetadataFormBuilder} from '../../../../../shared/metadata'; +import {MetadataUtilsService} from '../../../../../shared/metadata/metadata-utils.service'; +import {MetadataPickerComponent} from './metadata-picker.component'; + +describe('MetadataPickerComponent', () => { + const uniqueMetadata = signal({ + authors: ['Alice', 'Bob'], + categories: ['Fantasy', 'History'], + moods: ['Hopeful'], + tags: ['Epic'], + publishers: ['Orbit'], + series: ['Saga'], + }); + const appSettings = signal(null); + const updateBookMetadata = vi.fn(() => of(void 0)); + const uploadAudiobookCoverFromUrl = vi.fn(() => of(void 0)); + const supportsDualCovers = vi.fn(() => true); + const messageAdd = vi.fn(); + const translate = vi.fn((key: string, params?: Record) => params?.['field'] ? `${key}:${params['field']}` : key); + const getThumbnailUrl = vi.fn((bookId: number, updatedOn?: string) => `thumb:${bookId}:${updatedOn ?? 'none'}`); + const getCoverUrl = vi.fn((bookId: number, updatedOn?: string) => `cover:${bookId}:${updatedOn ?? 'none'}`); + const getAudiobookCoverUrl = vi.fn((bookId: number, updatedOn?: string) => `audio-cover:${bookId}:${updatedOn ?? 'none'}`); + + function createMetadata(overrides: Partial = {}): BookMetadata { + return { + bookId: 21, + title: 'Original Title', + subtitle: 'Original Subtitle', + authors: ['Alice'], + categories: ['Fantasy'], + description: 'Original description', + provider: 'googleBooks', + coverUpdatedOn: '2026-03-26', + titleLocked: true, + comicMetadata: { + issueNumber: '1', + }, + ...overrides, + }; + } + + function createBook(metadata: Partial = {}, overrides: Partial = {}): Book { + return { + id: 21, + libraryId: 1, + libraryName: 'Library', + metadata: createMetadata(metadata), + primaryFile: {id: 1, bookId: 21, bookType: 'EPUB'}, + alternativeFormats: [], + supplementaryFiles: [], + isPhysical: false, + ...overrides, + } as Book; + } + + beforeEach(() => { + uniqueMetadata.set({ + authors: ['Alice', 'Bob'], + categories: ['Fantasy', 'History'], + moods: ['Hopeful'], + tags: ['Epic'], + publishers: ['Orbit'], + series: ['Saga'], + }); + appSettings.set(null); + updateBookMetadata.mockClear(); + uploadAudiobookCoverFromUrl.mockClear(); + supportsDualCovers.mockClear(); + messageAdd.mockClear(); + translate.mockClear(); + getThumbnailUrl.mockClear(); + getCoverUrl.mockClear(); + getAudiobookCoverUrl.mockClear(); + + TestBed.configureTestingModule({ + providers: [ + MetadataFormBuilder, + MetadataUtilsService, + {provide: AppSettingsService, useValue: {appSettings}}, + {provide: BookService, useValue: {uniqueMetadata}}, + { + provide: BookMetadataManageService, + useValue: {updateBookMetadata, uploadAudiobookCoverFromUrl, supportsDualCovers}, + }, + { + provide: UrlHelperService, + useValue: {getThumbnailUrl, getCoverUrl, getAudiobookCoverUrl}, + }, + {provide: MessageService, useValue: {add: messageAdd}}, + {provide: TranslocoService, useValue: {translate}}, + ] + }); + }); + + it('syncs provider field visibility from app settings and filters metadata suggestions', () => { + appSettings.set({ + metadataProviderSpecificFields: { + googleId: true, + audibleId: true, + amazonRating: false, + }, + } as AppSettings); + + const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent()); + TestBed.flushEffects(); + + expect(component.metadataProviderFields.map(field => field.controlName)).toContain('googleId'); + expect(component.metadataProviderFields.map(field => field.controlName)).toContain('audibleId'); + expect(component.metadataProviderFields.map(field => field.controlName)).not.toContain('amazonRating'); + + component.filterItems({query: 'fan'}, 'categories'); + expect(component.getFiltered('categories')).toEqual(['Fantasy']); + expect(component.getFiltered('missing')).toEqual([]); + }); + + it('patches book metadata into the form and resets review state when a new book arrives', () => { + const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent()); + component.reviewMode = true; + component.copiedFields = {title: true}; + component.savedFields = {title: true}; + component.hoveredFields = {title: true}; + component.fetchedMetadata = createMetadata({provider: 'comicvine'}); + + component.book = createBook(); + + expect(component.currentBookId).toBe(21); + expect(component.metadataForm.get('title')?.value).toBe('Original Title'); + expect(component.metadataForm.get('authors')?.value).toEqual(['Alice']); + expect(component.metadataForm.get('title')?.disabled).toBe(true); + expect(component.originalMetadata.thumbnailUrl).toBe('thumb:21:2026-03-26'); + expect(component.comicSectionExpanded).toBe(true); + expect(component.copiedFields).toEqual({}); + expect(component.savedFields).toEqual({}); + expect(component.hoveredFields).toEqual({}); + }); + + it('handles author and array autocomplete helpers without duplicating values', () => { + const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent()); + component.book = createBook(); + component.metadataForm.get('authors')?.setValue(['Alice', 'Bob']); + + component.dropAuthor({previousIndex: 1, currentIndex: 0} as CdkDragDrop); + expect(component.metadataForm.get('authors')?.value).toEqual(['Bob', 'Alice']); + + component.removeAuthor(1); + expect(component.metadataForm.get('authors')?.value).toEqual(['Bob']); + + component.authorInputValue = 'Cara'; + component.onAuthorInputKeyUp({key: 'Enter'} as KeyboardEvent); + expect(component.metadataForm.get('authors')?.value).toEqual(['Bob', 'Cara']); + expect(component.authorInputValue).toBe(''); + + component.onAutoCompleteSelect('categories', { + value: 'Fantasy', + originalEvent: {target: {value: 'Fantasy'}}, + } as unknown as AutoCompleteSelectEvent); + component.onAutoCompleteKeyUp('categories', { + key: 'Enter', + target: {value: 'History'}, + } as unknown as KeyboardEvent); + + expect(component.metadataForm.get('categories')?.value).toEqual(['Fantasy', 'History']); + }); + + it('copies fetched values, respects locked fields, and resets fields back to the original metadata', () => { + const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent()); + component.book = createBook(); + component.fetchedMetadata = createMetadata({ + title: 'Fetched Title', + provider: 'Audible', + thumbnailUrl: 'https://covers.example/audiobook.jpg', + comicMetadata: {issueNumber: '7'}, + }); + + component.copyFetchedToCurrent('title'); + expect(messageAdd).toHaveBeenCalledWith({ + severity: 'warn', + summary: 'metadata.picker.toast.actionBlockedSummary', + detail: 'metadata.picker.toast.fieldLockedDetail:title', + }); + + component.metadataForm.get('titleLocked')?.setValue(false); + component.metadataForm.get('title')?.enable(); + component.copyFetchedToCurrent('title'); + expect(component.metadataForm.get('title')?.value).toBe('Fetched Title'); + expect(component.isValueCopied('title')).toBe(true); + + component.copyFetchedToCurrent('audiobookThumbnailUrl'); + expect(component.metadataForm.get('audiobookThumbnailUrl')?.value).toBe('https://covers.example/audiobook.jpg'); + expect(component.isValueCopied('audiobookThumbnailUrl')).toBe(true); + + component.metadataForm.get('comicIssueNumberLocked')?.setValue(true); + component.copyFetchedToCurrent('comicIssueNumber'); + expect(messageAdd).toHaveBeenLastCalledWith({ + severity: 'warn', + summary: 'metadata.picker.toast.actionBlockedSummary', + detail: 'metadata.picker.toast.fieldLockedDetail:Issue #', + }); + + component.resetField('title'); + expect(component.metadataForm.get('title')?.value).toBe('Original Title'); + expect(component.isValueCopied('title')).toBe(false); + }); + + it('saves metadata, uploads audible covers when needed, and toggles lock states', () => { + const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent()); + component.fetchedMetadata = createMetadata({ + provider: 'Audible', + thumbnailUrl: 'https://covers.example/audiobook.jpg', + }); + component.book = createBook(); + component.copiedFields = {title: true, audiobookThumbnailUrl: true}; + component.metadataForm.get('titleLocked')?.setValue(false); + component.metadataForm.get('title')?.enable(); + component.metadataForm.get('title')?.setValue('Updated Title'); + + component.onSave(); + + expect(updateBookMetadata).toHaveBeenCalledWith(21, expect.objectContaining({ + metadata: expect.objectContaining({title: 'Updated Title'}), + clearFlags: expect.any(Object), + }), false, 'REPLACE_WHEN_PROVIDED'); + expect(uploadAudiobookCoverFromUrl).toHaveBeenCalledWith(21, 'https://covers.example/audiobook.jpg'); + expect(component.isSaving).toBe(false); + expect(component.isValueSaved('title')).toBe(true); + expect(component.isValueSaved('audiobookThumbnailUrl')).toBe(true); + expect(messageAdd).toHaveBeenCalledWith({ + severity: 'info', + summary: 'metadata.picker.toast.successSummary', + detail: 'metadata.picker.toast.metadataUpdated', + }); + + component.toggleLock('thumbnailUrl'); + expect(component.metadataForm.get('coverLocked')?.value).toBe(true); + expect(component.metadataForm.get('thumbnailUrl')?.disabled).toBe(true); + + component.lockAll(); + component.unlockAll(); + + expect(updateBookMetadata).toHaveBeenCalledTimes(4); + }); + + it('covers hover state, back navigation, dual-cover helpers, and comic visibility helpers', () => { + const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent()); + const goBackEmit = vi.spyOn(component.goBack, 'emit'); + const book = createBook({}, { + isPhysical: true, + primaryFile: undefined, + alternativeFormats: [{id: 2, bookId: 21, bookType: 'AUDIOBOOK'}], + }); + + component.fetchedMetadata = createMetadata({ + provider: 'comicvine', + narrator: 'Narrator', + comicMetadata: {issueNumber: '7'}, + }); + component.book = book; + component.copiedFields = {title: true}; + component.savedFields = {title: false}; + + component.onMouseEnter('title'); + expect(component.hoveredFields['title']).toBe(true); + + component.onMouseLeave('title'); + expect(component.hoveredFields['title']).toBe(false); + + component.goBackClick(); + expect(goBackEmit).toHaveBeenCalledWith(true); + + expect(component.isAudibleProvider()).toBe(false); + component.fetchedMetadata = createMetadata({provider: 'Audible', narrator: 'Narrator', comicMetadata: {issueNumber: '7'}}); + expect(component.isAudibleProvider()).toBe(true); + expect(component.getFetchedAudiobookValue('narrator')).toBe('Narrator'); + expect(component.getFetchedComicValue('issueNumber')).toBe('7'); + + expect(component.hasEbookFormat(book)).toBe(true); + expect(component.hasAudiobookFormat(book)).toBe(true); + expect(component.supportsDualCovers(book)).toBe(true); + expect(component.hasAnyFetchedComicData()).toBe(true); + expect(component.hasAnyCurrentComicData()).toBe(true); + expect(component.shouldShowComicSection()).toBe(true); + }); +}); diff --git a/frontend/src/app/features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.spec.ts b/frontend/src/app/features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.spec.ts new file mode 100644 index 000000000..e15a72800 --- /dev/null +++ b/frontend/src/app/features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.spec.ts @@ -0,0 +1,9 @@ +import {describe, expect, it} from 'vitest'; + +// TODO(seam): Search orchestration depends on reactive form state, provider fan-out requests, +// and metadata picker integration that should be covered through a component harness. +describe.skip('MetadataSearcherComponent', () => { + it('needs an integration harness for provider filtering, auto-search, and detail-loading flows', () => { + expect.hasAssertions(); + }); +}); diff --git a/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.spec.ts b/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.spec.ts new file mode 100644 index 000000000..0f5bd79aa --- /dev/null +++ b/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.spec.ts @@ -0,0 +1,9 @@ +import {describe, expect, it} from 'vitest'; + +// TODO(seam): This tab surface coordinates nested review, notes, reading-session, and +// audiobook child components, so it needs an integration harness around real tab changes. +describe.skip('MetadataTabsComponent', () => { + it('needs a tab harness for chapter loading and file action emission branches', () => { + expect.hasAssertions(); + }); +}); diff --git a/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.spec.ts b/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.spec.ts new file mode 100644 index 000000000..f92a89d3f --- /dev/null +++ b/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.spec.ts @@ -0,0 +1,487 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {of, throwError} from 'rxjs'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {ConfirmationService, MessageService, MenuItem} from 'primeng/api'; +import {TranslocoService} from '@jsverse/transloco'; + +import {Book, BookFile, BookMetadata, BookRecommendation, ReadStatus} from '../../../../book/model/book.model'; +import {BookService} from '../../../../book/service/book.service'; +import {BookFileService} from '../../../../book/service/book-file.service'; +import {AppSettings} from '../../../../../shared/model/app-settings.model'; +import {AppSettingsService} from '../../../../../shared/service/app-settings.service'; +import {UrlHelperService} from '../../../../../shared/service/url-helper.service'; +import {UserService} from '../../../../settings/user-management/user.service'; +import {EmailService} from '../../../../settings/email-v2/email.service'; +import {BookDialogHelperService} from '../../../../book/components/book-browser/book-dialog-helper.service'; +import {LibraryService} from '../../../../book/service/library.service'; +import {TaskHelperService} from '../../../../settings/task-management/task-helper.service'; +import {AuthorService} from '../../../../author-browser/service/author.service'; +import {Router} from '@angular/router'; +import {BookNavigationService} from '../../../../book/service/book-navigation.service'; +import {BookMetadataHostService} from '../../../../../shared/service/book-metadata-host.service'; +import {MetadataViewerComponent} from './metadata-viewer.component'; + +interface CurrentUser { + permissions?: { + canManageLibrary?: boolean; + canUpload?: boolean; + canEmailBook?: boolean; + canDeleteBook?: boolean; + admin?: boolean; + }; + userSettings?: { + metadataCenterViewMode?: 'route' | 'dialog'; + }; +} + +interface ConfirmationLike { + message?: string; + header?: string; + accept?: () => void; +} + +describe('MetadataViewerComponent', () => { + const currentUser = signal(null); + const appSettings = signal(null); + const navigationState = signal(false); + const canNavigatePrevious = signal(false); + const canNavigateNext = signal(false); + const currentPosition = signal<{ current: number; total: number } | null>(null); + + const readBook = vi.fn(); + const togglePhysicalFlag = vi.fn(() => of(void 0)); + const deleteBooks = vi.fn(() => of(void 0)); + const updateDateFinished = vi.fn(() => of(void 0)); + const updateBookReadStatus = vi.fn(() => of(void 0)); + const resetProgress = vi.fn(() => of(void 0)); + const updatePersonalRating = vi.fn(() => of(void 0)); + const resetPersonalRating = vi.fn(() => of(void 0)); + const getBooksInSeries = vi.fn(() => of([] as Book[])); + const findBookById = vi.fn(); + + const downloadFile = vi.fn(); + const downloadAdditionalFile = vi.fn(); + const downloadAllFiles = vi.fn(); + const deleteAdditionalFile = vi.fn(() => of(void 0)); + const deleteBookFile = vi.fn(() => of(void 0)); + const detachBookFile = vi.fn(() => of(void 0)); + + const openAdditionalFileUploaderDialog = vi.fn(); + const openCustomSendDialog = vi.fn(); + const openBookFileAttacherDialog = vi.fn(); + const openFileMoverDialog = vi.fn(); + const openShelfAssignerDialog = vi.fn(); + + const emailBookQuick = vi.fn(() => of(void 0)); + const refreshMetadataTask = vi.fn(() => of(void 0)); + const getAuthorByName = vi.fn(() => of({id: 41})); + + const findLibraryById = vi.fn(() => ({allowedFormats: ['PDF', 'EPUB']})); + const switchBook = vi.fn(); + const updateCurrentBook = vi.fn(); + const previousBookId = vi.fn(); + const nextBookId = vi.fn(); + const routerNavigate = vi.fn(() => Promise.resolve(true)); + + let lastConfirmation: ConfirmationLike | null = null; + const confirm = vi.fn((confirmation: ConfirmationLike) => { + lastConfirmation = confirmation; + }); + const messageAdd = vi.fn(); + const translate = vi.fn((key: string, params?: Record) => { + if (!params) { + return key; + } + return `${key}:${Object.entries(params).map(([paramKey, value]) => `${paramKey}=${value}`).join(',')}`; + }); + const getCoverUrl = vi.fn((bookId: number, updatedOn?: string) => `cover:${bookId}:${updatedOn ?? 'none'}`); + const getAudiobookCoverUrl = vi.fn((bookId: number, updatedOn?: string) => `audio:${bookId}:${updatedOn ?? 'none'}`); + const getThumbnailUrl = vi.fn((bookId: number, updatedOn?: string) => `thumb:${bookId}:${updatedOn ?? 'none'}`); + + function createFile( + id: number, + overrides: Partial = {}, + ): BookFile { + return { + id, + bookId: 21, + fileName: `file-${id}.epub`, + filePath: `/books/file-${id}.epub`, + fileSizeKb: 100, + ...overrides, + }; + } + + function createMetadata(overrides: Partial = {}): BookMetadata { + return { + bookId: 21, + title: 'Original Title', + authors: ['Alice'], + coverUpdatedOn: '2026-03-26', + audiobookCoverUpdatedOn: '2026-03-26', + ...overrides, + }; + } + + function createBook( + overrides: Partial = {}, + metadataOverrides: Partial = {}, + ): Book { + return { + id: 21, + libraryId: 1, + libraryName: 'Library', + metadata: createMetadata(metadataOverrides), + primaryFile: createFile(1, {bookId: 21, bookType: 'EPUB'}), + alternativeFormats: [], + supplementaryFiles: [], + isPhysical: false, + ...overrides, + } as Book; + } + + function createComponent(): MetadataViewerComponent { + return TestBed.runInInjectionContext(() => new MetadataViewerComponent()); + } + + function runMenuCommand(command: MenuItem['command'] | undefined): void { + (command as (() => void) | undefined)?.(); + } + + beforeEach(() => { + currentUser.set(null); + appSettings.set(null); + navigationState.set(false); + canNavigatePrevious.set(false); + canNavigateNext.set(false); + currentPosition.set(null); + + readBook.mockClear(); + togglePhysicalFlag.mockClear(); + deleteBooks.mockClear(); + updateDateFinished.mockClear(); + updateBookReadStatus.mockClear(); + resetProgress.mockClear(); + updatePersonalRating.mockClear(); + resetPersonalRating.mockClear(); + getBooksInSeries.mockClear(); + findBookById.mockClear(); + + downloadFile.mockClear(); + downloadAdditionalFile.mockClear(); + downloadAllFiles.mockClear(); + deleteAdditionalFile.mockClear(); + deleteBookFile.mockClear(); + detachBookFile.mockClear(); + + openAdditionalFileUploaderDialog.mockClear(); + openCustomSendDialog.mockClear(); + openBookFileAttacherDialog.mockClear(); + openFileMoverDialog.mockClear(); + openShelfAssignerDialog.mockClear(); + + emailBookQuick.mockClear(); + refreshMetadataTask.mockClear(); + getAuthorByName.mockClear(); + + findLibraryById.mockClear(); + switchBook.mockClear(); + updateCurrentBook.mockClear(); + previousBookId.mockClear(); + nextBookId.mockClear(); + routerNavigate.mockClear(); + + confirm.mockClear(); + messageAdd.mockClear(); + translate.mockClear(); + getCoverUrl.mockClear(); + getAudiobookCoverUrl.mockClear(); + getThumbnailUrl.mockClear(); + lastConfirmation = null; + + TestBed.configureTestingModule({ + providers: [ + {provide: TranslocoService, useValue: {translate}}, + {provide: LibraryService, useValue: {findLibraryById}}, + { + provide: BookDialogHelperService, + useValue: { + openAdditionalFileUploaderDialog, + openCustomSendDialog, + openBookFileAttacherDialog, + openFileMoverDialog, + openShelfAssignerDialog, + }, + }, + {provide: EmailService, useValue: {emailBookQuick}}, + {provide: MessageService, useValue: {add: messageAdd}}, + { + provide: BookService, + useValue: { + readBook, + togglePhysicalFlag, + deleteBooks, + updateDateFinished, + updateBookReadStatus, + resetProgress, + updatePersonalRating, + resetPersonalRating, + getBooksInSeries, + findBookById, + }, + }, + {provide: BookFileService, useValue: {downloadFile, downloadAdditionalFile, downloadAllFiles, deleteAdditionalFile, deleteBookFile, detachBookFile}}, + {provide: TaskHelperService, useValue: {refreshMetadataTask}}, + {provide: AuthorService, useValue: {getAuthorByName}}, + {provide: UrlHelperService, useValue: {getCoverUrl, getAudiobookCoverUrl, getThumbnailUrl}}, + {provide: UserService, useValue: {currentUser}}, + {provide: AppSettingsService, useValue: {appSettings}}, + {provide: ConfirmationService, useValue: {confirm}}, + {provide: Router, useValue: {navigate: routerNavigate}}, + { + provide: BookNavigationService, + useValue: { + navigationState, + canNavigatePrevious, + canNavigateNext, + currentPosition, + previousBookId, + nextBookId, + updateCurrentBook, + }, + }, + {provide: BookMetadataHostService, useValue: {switchBook}}, + ], + }); + }); + + it('filters series recommendations and builds the read, download, and other menus from the current book', () => { + const component = createComponent(); + const seriesBooks = [ + {id: 8, metadata: {seriesNumber: 2}}, + {id: 4, metadata: {seriesNumber: 1}}, + ] as Book[]; + getBooksInSeries.mockReturnValueOnce(of(seriesBooks as Book[])); + + const recommendedBooks: BookRecommendation[] = [ + {book: {id: 4} as Book, similarityScore: 0.99}, + {book: {id: 17} as Book, similarityScore: 0.87}, + ]; + + component.recommendedBooks = recommendedBooks; + const richBook = createBook( + { + id: 21, + primaryFile: createFile(1, {bookId: 21, bookType: 'EPUB', fileName: 'main.epub', filePath: '/books/main.epub', fileSizeKb: 2048}), + alternativeFormats: [ + createFile(2, {bookId: 21, bookType: 'EPUB', fileName: 'alt.epub', filePath: '/books/alt.epub', fileSizeKb: 1024}), + createFile(3, {bookId: 21, bookType: 'PDF', fileName: 'art.pdf', filePath: '/books/art.pdf', fileSizeKb: 5120}), + ], + supplementaryFiles: [ + createFile(4, {bookId: 21, fileName: 'appendix.txt', filePath: '/books/appendix.txt', fileSizeKb: 12}), + ], + }, + { + bookId: 21, + seriesName: 'Series One', + seriesNumber: 3, + } + ); + findBookById.mockReturnValue(richBook); + + currentUser.set({ + permissions: { + canManageLibrary: true, + canUpload: true, + canEmailBook: true, + canDeleteBook: true, + }, + userSettings: { + metadataCenterViewMode: 'route', + }, + }); + appSettings.set({ + diskType: 'LOCAL', + metadataProviderSettings: { + amazon: {domain: 'co.uk'}, + }, + } as AppSettings); + + component.book = richBook; + + expect(component.bookInSeries.map(book => book.id)).toEqual([4, 8]); + expect(component.recommendedBooks.map(book => book.book.id)).toEqual([17]); + + const readItems = component.readMenuItems(); + expect(readItems.map(item => item.separator ? 'separator' : item.label)).toEqual([ + 'metadata.viewer.menuStreamingReader', + 'separator', + 'EPUB', + 'PDF', + ]); + expect(readItems[0].command).toBeDefined(); + runMenuCommand(readItems[0].command); + expect(readBook).toHaveBeenCalledWith(21, 'epub-streaming', undefined); + runMenuCommand(readItems[2].items?.[0].command); + expect(readBook).toHaveBeenLastCalledWith(21, undefined, 'EPUB'); + + const downloadItems = component.downloadMenuItems(); + expect(downloadItems.some(item => item.separator)).toBe(true); + expect(downloadItems[0].label).toContain('EPUB ·'); + expect(downloadItems[3].label).toContain('appendix.txt'); + runMenuCommand(downloadItems[0].command); + expect(downloadAdditionalFile).toHaveBeenCalledWith(richBook, 2); + runMenuCommand(downloadItems[3].command); + expect(downloadAdditionalFile).toHaveBeenCalledWith(richBook, 4); + + const otherItems = component.otherItems(); + expect(otherItems.map(item => item.separator ? 'separator' : item.label)).toEqual([ + 'metadata.viewer.menuShelf', + 'metadata.viewer.menuMarkPhysical', + 'metadata.viewer.menuUploadFile', + 'metadata.viewer.menuOrganizeFiles', + 'metadata.viewer.menuSendBook', + 'metadata.viewer.menuDeleteFileFormats', + 'metadata.viewer.menuDeleteSupplementaryFiles', + 'metadata.viewer.menuDeleteBookAllFiles', + ]); + + runMenuCommand(otherItems[0].command); + expect(openShelfAssignerDialog).toHaveBeenCalledWith(richBook, null); + + runMenuCommand(otherItems[1].command); + expect(togglePhysicalFlag).toHaveBeenCalledWith(21, true); + + runMenuCommand(otherItems[2].command); + expect(openAdditionalFileUploaderDialog).toHaveBeenCalledWith(richBook); + + runMenuCommand(otherItems[3].command); + expect(openFileMoverDialog).toHaveBeenCalledWith(new Set([21])); + + const sendBookItem = otherItems[4]; + runMenuCommand(sendBookItem.items?.[0].command); + expect(emailBookQuick).toHaveBeenCalledWith(21); + runMenuCommand(sendBookItem.items?.[1].command); + expect(openCustomSendDialog).toHaveBeenCalledWith(richBook); + + const deleteFormatItems = otherItems[5].items ?? []; + runMenuCommand(deleteFormatItems[0].command); + expect(confirm).toHaveBeenCalled(); + + const deleteSupplementaryItems = otherItems[6].items ?? []; + runMenuCommand(deleteSupplementaryItems[0].command); + expect(confirm).toHaveBeenCalledTimes(2); + }); + + it('chooses confirmation copy for file deletion branches and runs the accept callbacks', () => { + const component = createComponent(); + const book = createBook(); + + component.deleteBookFile(book, 1, 'primary.epub', true, true); + expect(lastConfirmation).toMatchObject({ + message: 'metadata.viewer.confirm.deleteOnlyFormatMessage:fileName=primary.epub', + header: 'metadata.viewer.confirm.deleteOnlyFormatHeader', + }); + + component.deleteBookFile(book, 2, 'primary.epub', true, false); + expect(lastConfirmation).toMatchObject({ + message: 'metadata.viewer.confirm.deletePrimaryFormatMessage:fileName=primary.epub', + header: 'metadata.viewer.confirm.deletePrimaryFormatHeader', + }); + + component.deleteBookFile(book, 3, 'alt.pdf', false, false); + expect(lastConfirmation).toMatchObject({ + message: 'metadata.viewer.confirm.deleteAltFormatMessage:fileName=alt.pdf', + header: 'metadata.viewer.confirm.deleteAltFormatHeader', + }); + lastConfirmation?.accept?.(); + expect(deleteBookFile).toHaveBeenCalledWith(21, 3, false); + expect(messageAdd).toHaveBeenLastCalledWith(expect.objectContaining({ + severity: 'success', + summary: 'metadata.viewer.toast.deleteFormatSuccessSummary', + })); + + deleteAdditionalFile.mockReturnValueOnce(throwError(() => new Error('boom'))); + component.deleteAdditionalFile(21, 9, 'appendix.txt'); + expect(lastConfirmation).toMatchObject({ + message: 'metadata.viewer.confirm.deleteSupplementaryMessage:fileName=appendix.txt', + header: 'metadata.viewer.confirm.deleteSupplementaryHeader', + }); + lastConfirmation?.accept?.(); + expect(deleteAdditionalFile).toHaveBeenCalledWith(21, 9); + expect(messageAdd).toHaveBeenLastCalledWith(expect.objectContaining({ + severity: 'error', + summary: 'metadata.viewer.toast.deleteSupplementaryErrorSummary', + })); + }); + + it('navigates and formats helper branches for read states, file metadata, and location helpers', () => { + const component = createComponent(); + const viewer = component as unknown as { + metadataCenterViewMode: 'route' | 'dialog'; + }; + + previousBookId.mockReturnValue(12); + nextBookId.mockReturnValue(27); + + viewer.metadataCenterViewMode = 'route'; + component.navigatePrevious(); + expect(updateCurrentBook).toHaveBeenCalledWith(12); + expect(routerNavigate).toHaveBeenCalledWith(['/book', 12], {queryParams: {tab: 'view'}}); + + viewer.metadataCenterViewMode = 'dialog'; + component.navigateNext(); + expect(updateCurrentBook).toHaveBeenLastCalledWith(27); + expect(switchBook).toHaveBeenCalledWith(27); + + const audiobookBook = createBook({primaryFile: createFile(1, {bookType: 'AUDIOBOOK'})}); + component.selectedReadStatus = ReadStatus.READING; + expect(component.isInProgressStatus()).toBe(true); + expect(component.getReadButtonLabel(audiobookBook)).toBe('metadata.viewer.continueBtn'); + expect(component.getReadButtonIcon(audiobookBook)).toBe('pi pi-play'); + + component.selectedReadStatus = ReadStatus.UNREAD; + expect(component.isInProgressStatus()).toBe(false); + expect(component.getReadButtonLabel(audiobookBook)).toBe('metadata.viewer.playBtn'); + expect(component.getReadButtonLabel(createBook())).toBe('metadata.viewer.readBtn'); + expect(component.getReadButtonIcon(createBook())).toBe('pi pi-book'); + + expect(component.formatFileSize(null)).toBe('-'); + expect(component.formatFileSize({fileSizeKb: 1536})).toBe('1.50 MB'); + expect(component.truncateFileName('plain-name-without-extension', 12)).toBe('plain-nam...'); + expect(component.truncateFileName('very-long-name.epub', 12)).toBe('very....epub'); + expect(component.getDisplayFormat(createFile(9, {extension: 'pdf'}))).toBe('PDF'); + expect(component.getDisplayFormat(createFile(10, {filePath: '/books/chapter.cbx'}))).toBe('CBX'); + expect(component.getUniqueAlternativeFormats(createBook({ + primaryFile: createFile(1, {bookType: 'EPUB', extension: 'epub'}), + alternativeFormats: [ + createFile(2, {bookType: 'EPUB', extension: 'epub'}), + createFile(3, {bookType: 'PDF', extension: 'pdf'}), + createFile(4, {bookType: 'PDF', extension: 'pdf'}), + ], + }))).toEqual(['PDF']); + expect(component.getFileIcon(null)).toBe('pi pi-file'); + expect(component.getFileIcon('pdf')).toBe('pi pi-file-pdf'); + expect(component.getFileIcon('audiobook')).toBe('pi pi-headphones'); + expect(component.getFileTypeBgColor('PDF')).toBe('var(--book-type-pdf-color, var(--p-gray-500))'); + expect(component.getStarColorScaled(null)).toBe('rgb(203, 213, 225)'); + expect(component.getStarColorScaled(5)).toBe('rgb(34, 197, 94)'); + expect(component.getRatingPercent(4.5)).toBe(90); + expect(component.getRatingTooltip(createBook({metadata: createMetadata({amazonRating: 4.2, amazonReviewCount: 1234})}), 'amazon')).toBe('★ 4.2 | 1,234 reviews'); + expect(component.getStatusLabel(ReadStatus.READING)).toBe('metadata.viewer.readStatusReading'.toUpperCase()); + expect(component.getStatusLabel('missing')).toBe('UNSET'); + expect(component.getBookCoverUrl(createBook())).toBe('cover:21:2026-03-26'); + expect(component.getBookCoverUrl(createBook({primaryFile: createFile(1, {bookType: 'AUDIOBOOK'})}))).toBe('audio:21:2026-03-26'); + expect(component.hasAnyFiles(createBook())).toBe(true); + expect(component.isPhysicalBook(createBook({primaryFile: undefined, alternativeFormats: []}))).toBe(true); + expect(component.isMetadataFullyLocked(createMetadata({titleLocked: true, subtitleLocked: false}))).toBe(false); + expect(component.isMetadataFullyLocked(createMetadata({titleLocked: true, subtitleLocked: true, allMetadataLocked: true}))).toBe(true); + expect(component.hasComicMetadata(createBook({metadata: createMetadata({comicMetadata: {issueNumber: '7'}})}))).toBe(true); + expect(component.hasAnyCreators({pencillers: ['A']})).toBe(true); + expect(component.formatWebLink('https://example.com/books/very/long/path/segment/that/exceeds/limit')).toContain('example.com'); + expect(component.getChannelLabel(1)).toBe('metadata.viewer.channelMono'); + expect(component.getChannelLabel(2)).toBe('metadata.viewer.channelStereo'); + expect(component.getChannelLabel(6)).toBe('metadata.viewer.channelMultiple:count=6'); + }); +}); diff --git a/frontend/src/app/features/metadata/component/book-metadata-center/sidecar-viewer/sidecar-viewer.component.spec.ts b/frontend/src/app/features/metadata/component/book-metadata-center/sidecar-viewer/sidecar-viewer.component.spec.ts new file mode 100644 index 000000000..5c2e56405 --- /dev/null +++ b/frontend/src/app/features/metadata/component/book-metadata-center/sidecar-viewer/sidecar-viewer.component.spec.ts @@ -0,0 +1,232 @@ +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {of, throwError} from 'rxjs'; +import {MessageService} from 'primeng/api'; +import {TranslocoService} from '@jsverse/transloco'; + +import {Book} from '../../../../book/model/book.model'; +import {SidecarMetadata, SidecarService, SidecarSyncStatus} from '../../../service/sidecar.service'; +import {SidecarViewerComponent} from './sidecar-viewer.component'; + +describe('SidecarViewerComponent', () => { + const getSyncStatus = vi.fn(); + const getSidecarContent = vi.fn(); + const exportToSidecar = vi.fn(); + const importFromSidecar = vi.fn(); + const messageAdd = vi.fn(); + const translate = vi.fn((key: string) => `translated:${key}`); + + function createBook(id: number): Book { + return { + id, + title: `Book ${id}`, + libraryId: 1, + libraryName: 'Library', + } as Book; + } + + function createMetadata(): SidecarMetadata { + return { + version: '1', + generatedAt: '2026-03-26T00:00:00Z', + generatedBy: 'test', + metadata: {title: 'Example'}, + cover: {source: 'embedded', path: '/covers/example.jpg'}, + }; + } + + beforeEach(() => { + vi.restoreAllMocks(); + getSyncStatus.mockReset(); + getSidecarContent.mockReset(); + exportToSidecar.mockReset(); + importFromSidecar.mockReset(); + messageAdd.mockReset(); + translate.mockClear(); + + TestBed.configureTestingModule({ + providers: [ + { + provide: SidecarService, + useValue: {getSyncStatus, getSidecarContent, exportToSidecar, importFromSidecar}, + }, + {provide: MessageService, useValue: {add: messageAdd}}, + {provide: TranslocoService, useValue: {translate}}, + ] + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('resets its state when the selected book is cleared', () => { + const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent()); + component.currentBookId = 7; + component.sidecarContent = createMetadata(); + component.syncStatus = 'IN_SYNC'; + component.loading = true; + component.error = 'failed'; + + component.book = null; + + expect(component.currentBookId).toBeNull(); + expect(component.sidecarContent).toBeNull(); + expect(component.syncStatus).toBe('NOT_APPLICABLE'); + expect(component.loading).toBe(false); + expect(component.error).toBeNull(); + }); + + it('loads sync status and content when a sidecar exists for the selected book', () => { + const metadata = createMetadata(); + getSyncStatus.mockReturnValue(of({status: 'IN_SYNC'})); + getSidecarContent.mockReturnValue(of(metadata)); + + const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent()); + component.book = createBook(7); + + expect(getSyncStatus).toHaveBeenCalledWith(7); + expect(getSidecarContent).toHaveBeenCalledWith(7); + expect(component.currentBookId).toBe(7); + expect(component.syncStatus).toBe('IN_SYNC'); + expect(component.sidecarContent).toEqual(metadata); + expect(component.loading).toBe(false); + }); + + it('skips content loading when the sidecar is missing or not applicable', () => { + const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent()); + getSyncStatus.mockReturnValue(of({status: 'MISSING'})); + + component.book = createBook(3); + + expect(getSidecarContent).not.toHaveBeenCalled(); + expect(component.syncStatus).toBe('MISSING'); + expect(component.sidecarContent).toBeNull(); + expect(component.loading).toBe(false); + + getSyncStatus.mockReturnValue(of({status: 'NOT_APPLICABLE'})); + component.book = createBook(4); + + expect(getSidecarContent).not.toHaveBeenCalled(); + expect(component.syncStatus).toBe('NOT_APPLICABLE'); + expect(component.loading).toBe(false); + }); + + it('falls back to NOT_APPLICABLE when sync status lookup fails', () => { + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined); + getSyncStatus.mockReturnValue(throwError(() => new Error('boom'))); + + const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent()); + component.book = createBook(5); + + expect(component.syncStatus).toBe('NOT_APPLICABLE'); + expect(component.sidecarContent).toBeNull(); + expect(component.loading).toBe(false); + expect(consoleError).toHaveBeenCalledOnce(); + }); + + it('suppresses console noise for missing sidecar content but logs other load failures', () => { + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined); + const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent()); + + getSyncStatus.mockReturnValue(of({status: 'OUTDATED'})); + getSidecarContent.mockReturnValue(throwError(() => ({status: 404}))); + component.book = createBook(6); + + expect(component.sidecarContent).toBeNull(); + expect(component.loading).toBe(false); + expect(consoleError).not.toHaveBeenCalled(); + + getSidecarContent.mockReturnValue(throwError(() => ({status: 500}))); + component.loadSidecarData(6); + + expect(consoleError).toHaveBeenCalledOnce(); + }); + + it('exports to sidecar, shows a success toast, and reloads the current book data', () => { + exportToSidecar.mockReturnValue(of({message: 'ok'})); + + const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent()); + const reload = vi.spyOn(component, 'loadSidecarData').mockImplementation(() => undefined); + component.currentBookId = 9; + + component.exportToSidecar(); + + expect(exportToSidecar).toHaveBeenCalledWith(9); + expect(messageAdd).toHaveBeenCalledWith({ + severity: 'success', + summary: 'translated:metadata.sidecar.toast.exportSuccessSummary', + detail: 'translated:metadata.sidecar.toast.exportSuccessDetail', + }); + expect(reload).toHaveBeenCalledWith(9); + expect(component.exporting).toBe(false); + }); + + it('shows an error toast when export fails and ignores export without a selected book', () => { + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined); + exportToSidecar.mockReturnValue(throwError(() => new Error('export failed'))); + + const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent()); + component.exportToSidecar(); + + expect(exportToSidecar).not.toHaveBeenCalled(); + + component.currentBookId = 11; + component.exportToSidecar(); + + expect(messageAdd).toHaveBeenCalledWith({ + severity: 'error', + summary: 'translated:metadata.sidecar.toast.exportFailedSummary', + detail: 'translated:metadata.sidecar.toast.exportFailedDetail', + }); + expect(component.exporting).toBe(false); + expect(consoleError).toHaveBeenCalledOnce(); + }); + + it('imports from sidecar, shows success or error toasts, and reloads when needed', () => { + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined); + importFromSidecar.mockReturnValueOnce(of({message: 'ok'})).mockReturnValueOnce(throwError(() => new Error('import failed'))); + + const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent()); + const reload = vi.spyOn(component, 'loadSidecarData').mockImplementation(() => undefined); + + component.currentBookId = 12; + component.importFromSidecar(); + + expect(messageAdd).toHaveBeenCalledWith({ + severity: 'success', + summary: 'translated:metadata.sidecar.toast.importSuccessSummary', + detail: 'translated:metadata.sidecar.toast.importSuccessDetail', + }); + expect(reload).toHaveBeenCalledWith(12); + expect(component.importing).toBe(false); + + component.importFromSidecar(); + + expect(messageAdd).toHaveBeenLastCalledWith({ + severity: 'error', + summary: 'translated:metadata.sidecar.toast.importFailedSummary', + detail: 'translated:metadata.sidecar.toast.importFailedDetail', + }); + expect(component.importing).toBe(false); + expect(consoleError).toHaveBeenCalledOnce(); + }); + + it('maps sync status severities and labels across all branches', () => { + const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent()); + const cases: [SidecarSyncStatus | 'UNKNOWN', string, string][] = [ + ['IN_SYNC', 'success', 'translated:metadata.sidecar.syncStatusInSync'], + ['OUTDATED', 'warn', 'translated:metadata.sidecar.syncStatusOutdated'], + ['CONFLICT', 'danger', 'translated:metadata.sidecar.syncStatusConflict'], + ['MISSING', 'secondary', 'translated:metadata.sidecar.syncStatusMissing'], + ['NOT_APPLICABLE', 'info', 'translated:metadata.sidecar.syncStatusNA'], + ['UNKNOWN', 'info', 'translated:metadata.sidecar.syncStatusUnknown'], + ]; + + for (const [status, severity, label] of cases) { + component.syncStatus = status as SidecarSyncStatus; + expect(component.getSyncStatusSeverity()).toBe(severity); + expect(component.getSyncStatusLabel()).toBe(label); + } + }); +}); diff --git a/frontend/src/app/features/metadata/component/bulk-metadata-update/bulk-metadata-update-component.spec.ts b/frontend/src/app/features/metadata/component/bulk-metadata-update/bulk-metadata-update-component.spec.ts new file mode 100644 index 000000000..79cbb6253 --- /dev/null +++ b/frontend/src/app/features/metadata/component/bulk-metadata-update/bulk-metadata-update-component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around dialog payload setup, reactive-form +// state mutation, autocomplete widgets, and chained metadata-plus-cover uploads so bulk update +// branching can be asserted without the full dialog and PrimeNG runtime. +describe.skip('BulkMetadataUpdateComponent', () => { + it('needs form seams to verify clear-field toggles, manual autocomplete entry, and payload construction', () => { + // TODO(seam): Cover onFieldClearToggle, autocomplete handlers, and onSubmit payload mapping once the reactive-form shell is isolated behind deterministic helpers. + }); + + it('needs upload seams to verify metadata success, partial cover-upload failure, and loading-state transitions', () => { + // TODO(seam): Cover chained updateBooksMetadata and bulkUploadCover branches after dialog, message, and file-upload concerns are exposed through stable doubles. + }); +}); diff --git a/frontend/src/app/features/metadata/component/cover-search/cover-search.component.spec.ts b/frontend/src/app/features/metadata/component/cover-search/cover-search.component.spec.ts new file mode 100644 index 000000000..270ce8fa4 --- /dev/null +++ b/frontend/src/app/features/metadata/component/cover-search/cover-search.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around dialog-driven book bootstrapping, +// remote cover-search streams, file-upload handling, and toast side effects so cover selection +// behavior can be asserted without the full overlay and browser file runtime. +describe.skip('CoverSearchComponent', () => { + it('needs search seams to verify lookup, result selection, and empty-state messaging', () => { + // TODO(seam): Cover remote search branches once the metadata lookup stream and dialog payload are isolated behind deterministic doubles. + }); + + it('needs upload seams to verify local file import, cover replacement, and error reporting paths', () => { + // TODO(seam): Cover upload and confirm flows after browser file APIs and message dispatch are extracted into testable adapters. + }); +}); diff --git a/frontend/src/app/features/metadata/component/metadata-manager/metadata-manager.component.spec.ts b/frontend/src/app/features/metadata/component/metadata-manager/metadata-manager.component.spec.ts new file mode 100644 index 000000000..a453c375d --- /dev/null +++ b/frontend/src/app/features/metadata/component/metadata-manager/metadata-manager.component.spec.ts @@ -0,0 +1,194 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {BehaviorSubject, of} from 'rxjs'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TranslocoService} from '@jsverse/transloco'; +import {ActivatedRoute, Router} from '@angular/router'; +import {MessageService} from 'primeng/api'; + +import {Book} from '../../../book/model/book.model'; +import {BookMetadataManageService} from '../../../book/service/book-metadata-manage.service'; +import {BookService} from '../../../book/service/book.service'; +import {PageTitleService} from '../../../../shared/service/page-title.service'; +import {MetadataManagerComponent} from './metadata-manager.component'; + +describe('MetadataManagerComponent', () => { + const books = signal([]); + const isBooksLoading = signal(false); + const add = vi.fn(); + const navigate = vi.fn(() => Promise.resolve(true)); + const setPageTitle = vi.fn(); + const translate = vi.fn((key: string) => `translated:${key}`); + const consolidateMetadata = vi.fn(() => of(void 0)); + const deleteMetadata = vi.fn(() => of(void 0)); + let queryParams$: BehaviorSubject>; + + beforeEach(() => { + add.mockClear(); + navigate.mockClear(); + setPageTitle.mockClear(); + translate.mockClear(); + consolidateMetadata.mockClear(); + deleteMetadata.mockClear(); + books.set([]); + isBooksLoading.set(false); + queryParams$ = new BehaviorSubject>({}); + + TestBed.configureTestingModule({ + providers: [ + {provide: BookService, useValue: {books, isBooksLoading}}, + {provide: BookMetadataManageService, useValue: {consolidateMetadata, deleteMetadata}}, + {provide: PageTitleService, useValue: {setPageTitle}}, + {provide: TranslocoService, useValue: {translate}}, + {provide: MessageService, useValue: {add}}, + {provide: ActivatedRoute, useValue: {queryParams: queryParams$}}, + {provide: Router, useValue: {navigate}}, + ] + }); + }); + + function createBook(id: number, metadata: Partial = {}): Book { + return { + id, + title: `Book ${id}`, + libraryId: 1, + libraryName: 'Library', + metadata: { + bookId: id, + ...metadata, + }, + }; + } + + function createComponent() { + return TestBed.runInInjectionContext(() => new MetadataManagerComponent()); + } + + it('aggregates metadata once books finish loading', () => { + books.set([ + createBook(1, { + authors: ['Alice', 'Bob'], + categories: ['Fantasy'], + moods: ['Cozy'], + tags: ['magic'], + seriesName: 'Series A', + publisher: 'Pub One', + language: 'en', + }), + createBook(2, { + authors: ['Alice'], + categories: ['Fantasy', 'Adventure'], + moods: ['Epic'], + tags: ['magic', 'epic'], + seriesName: 'Series A', + publisher: 'Pub Two', + language: 'fr', + }), + ]); + + const component = createComponent(); + TestBed.flushEffects(); + + expect(component.loading).toBe(false); + expect(component.authors[0]).toEqual({value: 'Alice', count: 2, bookIds: [1, 2], selected: false}); + expect(component.categories[0]).toEqual({value: 'Fantasy', count: 2, bookIds: [1, 2], selected: false}); + expect(component.series).toEqual([{value: 'Series A', count: 2, bookIds: [1, 2], selected: false}]); + expect(component.publishers).toEqual([ + {value: 'Pub One', count: 1, bookIds: [1], selected: false}, + {value: 'Pub Two', count: 1, bookIds: [2], selected: false}, + ]); + expect(component.languages).toEqual([ + {value: 'en', count: 1, bookIds: [1], selected: false}, + {value: 'fr', count: 1, bookIds: [2], selected: false}, + ]); + }); + + it('waits for the book list to finish loading before extracting metadata', () => { + books.set([createBook(1, {authors: ['Alice']})]); + isBooksLoading.set(true); + + const component = createComponent(); + TestBed.flushEffects(); + + expect(component.loading).toBe(true); + expect(component.authors).toEqual([]); + + isBooksLoading.set(false); + TestBed.flushEffects(); + + expect(component.loading).toBe(false); + expect(component.authors).toEqual([{value: 'Alice', count: 1, bookIds: [1], selected: false}]); + }); + + it('tracks valid and invalid tabs from query params and updates the page title', () => { + queryParams$.next({tab: 'tags'}); + + const component = createComponent(); + component.ngOnInit(); + + expect(component.activeTab).toBe('tags'); + expect(setPageTitle).toHaveBeenCalledWith('translated:metadata.manager.title: translated:metadata.manager.tabs.tag'); + + queryParams$.next({tab: 'invalid'}); + + expect(component.activeTab).toBe('authors'); + expect(navigate).toHaveBeenCalledWith([], { + relativeTo: expect.anything(), + queryParams: {tab: 'authors'}, + queryParamsHandling: 'merge', + replaceUrl: true, + }); + }); + + it('navigates when the active tab changes through the setter', () => { + const component = createComponent(); + component.ngOnInit(); + navigate.mockClear(); + setPageTitle.mockClear(); + + component.activeTab = 'categories'; + + expect(component.activeTab).toBe('categories'); + expect(setPageTitle).toHaveBeenCalledWith('translated:metadata.manager.title: translated:metadata.manager.tabs.genre'); + expect(navigate).toHaveBeenCalledWith([], { + relativeTo: expect.anything(), + queryParams: {tab: 'categories'}, + queryParamsHandling: 'merge', + }); + }); + + it('toggles selections, selects similar values, filters tables, and navigates to filtered books', () => { + const component = createComponent(); + component.authors = [ + {value: 'Alice', count: 2, bookIds: [1, 2], selected: false}, + {value: 'Al', count: 1, bookIds: [3], selected: false}, + {value: 'Bob', count: 1, bookIds: [4], selected: false}, + ]; + const filterGlobal = vi.fn(); + + component.toggleAll('authors', true); + expect(component.authors.every(item => item.selected)).toBe(true); + expect(component.selectAllAuthors).toBe(true); + + component.clearSelection('authors'); + component.selectSimilar('authors', ' alice '); + + expect(component.authors[0].selected).toBe(true); + expect(component.authors[1].selected).toBe(true); + expect(component.authors[2].selected).toBe(false); + + component.filterGlobal({target: {value: 'magic'}} as unknown as Event, {filterGlobal}); + expect(filterGlobal).toHaveBeenCalledWith('magic', 'contains'); + + component.onMetadataClick('authors', 'A&B'); + expect(navigate).toHaveBeenCalledWith(['/all-books'], { + queryParams: { + view: 'grid', + sort: 'title', + direction: 'asc', + sidebar: true, + filter: 'author:A%26B', + } + }); + }); +}); diff --git a/frontend/src/app/features/metadata/component/metadata-options-dialog/metadata-advanced-fetch-options/metadata-advanced-fetch-options.component.spec.ts b/frontend/src/app/features/metadata/component/metadata-options-dialog/metadata-advanced-fetch-options/metadata-advanced-fetch-options.component.spec.ts new file mode 100644 index 000000000..e32568184 --- /dev/null +++ b/frontend/src/app/features/metadata/component/metadata-options-dialog/metadata-advanced-fetch-options/metadata-advanced-fetch-options.component.spec.ts @@ -0,0 +1,145 @@ +import {SimpleChange} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {MessageService} from 'primeng/api'; +import {TranslocoService} from '@jsverse/transloco'; + +import {FieldOptions, MetadataRefreshOptions} from '../../../model/request/metadata-refresh-options.model'; +import {MetadataAdvancedFetchOptionsComponent} from './metadata-advanced-fetch-options.component'; + +describe('MetadataAdvancedFetchOptionsComponent', () => { + const add = vi.fn(); + const translate = vi.fn((key: string) => `translated:${key}`); + + beforeEach(() => { + add.mockClear(); + translate.mockClear(); + + TestBed.configureTestingModule({ + providers: [ + {provide: MessageService, useValue: {add}}, + {provide: TranslocoService, useValue: {translate}}, + ] + }); + }); + + function createComponent() { + return TestBed.runInInjectionContext(() => new MetadataAdvancedFetchOptionsComponent()); + } + + function createOptions(): MetadataRefreshOptions { + return { + libraryId: null, + refreshCovers: true, + mergeCategories: true, + reviewBeforeApply: true, + replaceMode: 'REPLACE_ALL', + fieldOptions: { + title: {p1: 'Google', p2: null, p3: null, p4: undefined}, + goodreadsId: {p1: null, p2: null, p3: null, p4: null}, + } as unknown as FieldOptions, + enabledFields: { + title: true, + goodreadsId: false, + } as Record, + }; + } + + it('hydrates flags, field options, and enabled fields from input changes', () => { + const component = createComponent(); + component.currentMetadataOptions = createOptions(); + + component.ngOnChanges({ + currentMetadataOptions: new SimpleChange(null, component.currentMetadataOptions, true), + }); + + expect(component.refreshCovers).toBe(true); + expect(component.mergeCategories).toBe(true); + expect(component.reviewBeforeApply).toBe(true); + expect(component.replaceMode).toBe('REPLACE_ALL'); + expect(component.fieldOptions.title).toEqual({p1: 'Google', p2: null, p3: null, p4: null}); + expect(component.fieldOptions.goodreadsId).toEqual({p1: null, p2: null, p3: null, p4: null}); + expect(component.enabledFields.title).toBe(true); + expect(component.enabledFields.goodreadsId).toBe(false); + }); + + it('emits metadata options when all enabled non-provider fields have a provider', () => { + const component = createComponent(); + const emit = vi.spyOn(component.metadataOptionsSubmitted, 'emit'); + + for (const field of component.fields) { + component.enabledFields[field] = false; + } + component.fieldOptions.title.p1 = 'Google'; + component.enabledFields.title = true; + component.enabledFields.goodreadsId = true; + component.fieldOptions.goodreadsId = {p1: null, p2: null, p3: null, p4: null}; + component.refreshCovers = true; + component.mergeCategories = false; + component.reviewBeforeApply = true; + component.replaceMode = 'REPLACE_WHEN_PROVIDED'; + + component.submit(); + + expect(emit).toHaveBeenCalledWith(expect.objectContaining({ + refreshCovers: true, + mergeCategories: false, + reviewBeforeApply: true, + replaceMode: 'REPLACE_WHEN_PROVIDED', + fieldOptions: component.fieldOptions, + enabledFields: component.enabledFields, + })); + expect(add).not.toHaveBeenCalled(); + }); + + it('shows an error when an enabled non-provider field has no provider priority set', () => { + const component = createComponent(); + component.enabledFields.title = true; + component.fieldOptions.title = {p1: null, p2: null, p3: null, p4: null}; + + component.submit(); + + expect(add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'translated:metadata.advancedFetchOptions.toast.providerRequiredSummary', + detail: 'translated:metadata.advancedFetchOptions.toast.providerRequiredDetail', + life: 5000, + }); + }); + + it('applies bulk providers only to enabled non-provider fields and clears the selector', () => { + const component = createComponent(); + component.enabledFields.title = true; + component.enabledFields.subtitle = false; + component.enabledFields.goodreadsId = true; + component.bulkP2 = 'Amazon'; + + component.setBulkProvider('p2', 'Google'); + + expect(component.fieldOptions.title.p2).toBe('Google'); + expect(component.fieldOptions.subtitle.p2).toBeNull(); + expect(component.fieldOptions.goodreadsId.p2).toBeNull(); + expect(component.bulkP2).toBeNull(); + }); + + it('resets field options, enabled fields, replace mode, and bulk selectors', () => { + const component = createComponent(); + component.fieldOptions.title = {p1: 'Google', p2: 'Amazon', p3: null, p4: null}; + component.enabledFields.title = false; + component.replaceMode = 'REPLACE_ALL'; + component.bulkP1 = 'Google'; + component.bulkP2 = 'Amazon'; + component.bulkP3 = 'GoodReads'; + component.bulkP4 = 'Hardcover'; + + component.reset(); + + expect(component.fieldOptions.title).toEqual({p1: null, p2: null, p3: null, p4: null}); + expect(component.enabledFields.title).toBe(true); + expect(component.replaceMode).toBe('REPLACE_MISSING'); + expect(component.bulkP1).toBeNull(); + expect(component.bulkP2).toBeNull(); + expect(component.bulkP3).toBeNull(); + expect(component.bulkP4).toBeNull(); + }); +}); diff --git a/frontend/src/app/features/metadata/component/metadata-options-dialog/metadata-fetch-options/metadata-fetch-options.component.spec.ts b/frontend/src/app/features/metadata/component/metadata-options-dialog/metadata-fetch-options/metadata-fetch-options.component.spec.ts new file mode 100644 index 000000000..c709b02b3 --- /dev/null +++ b/frontend/src/app/features/metadata/component/metadata-options-dialog/metadata-fetch-options/metadata-fetch-options.component.spec.ts @@ -0,0 +1,99 @@ +import {TestBed} from '@angular/core/testing'; +import {of} from 'rxjs'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; + +import {AppSettings} from '../../../../../shared/model/app-settings.model'; +import {AppSettingsService} from '../../../../../shared/service/app-settings.service'; +import {MetadataRefreshOptions} from '../../../model/request/metadata-refresh-options.model'; +import {TaskHelperService} from '../../../../settings/task-management/task-helper.service'; +import {MetadataRefreshType} from '../../../model/request/metadata-refresh-type.enum'; +import {MetadataFetchOptionsComponent} from './metadata-fetch-options.component'; + +describe('MetadataFetchOptionsComponent', () => { + const close = vi.fn(); + const refreshMetadataTask = vi.fn(() => of(void 0)); + const defaultMetadataRefreshOptions: MetadataRefreshOptions = { + libraryId: null, + refreshCovers: true, + mergeCategories: false, + reviewBeforeApply: false, + }; + + beforeEach(() => { + close.mockClear(); + refreshMetadataTask.mockClear(); + }); + + it('reads dialog data and current default metadata options on construction', () => { + TestBed.configureTestingModule({ + providers: [ + { + provide: DynamicDialogConfig, + useValue: { + data: { + libraryId: 7, + bookIds: [1, 2], + metadataRefreshType: MetadataRefreshType.LIBRARY, + }, + }, + }, + {provide: DynamicDialogRef, useValue: {close}}, + {provide: TaskHelperService, useValue: {refreshMetadataTask}}, + { + provide: AppSettingsService, + useValue: { + appSettings: () => ({ + defaultMetadataRefreshOptions, + } as AppSettings), + }, + }, + ] + }); + + const component = TestBed.runInInjectionContext(() => new MetadataFetchOptionsComponent()); + + expect(component.libraryId).toBe(7); + expect(component.bookIds).toEqual([1, 2]); + expect(component.metadataRefreshType).toBe(MetadataRefreshType.LIBRARY); + expect(component.currentMetadataOptions).toEqual(defaultMetadataRefreshOptions); + }); + + it('submits a metadata refresh task and closes the dialog', () => { + TestBed.configureTestingModule({ + providers: [ + { + provide: DynamicDialogConfig, + useValue: { + data: { + libraryId: 7, + bookIds: [1, 2], + metadataRefreshType: MetadataRefreshType.BOOKS, + }, + }, + }, + {provide: DynamicDialogRef, useValue: {close}}, + {provide: TaskHelperService, useValue: {refreshMetadataTask}}, + {provide: AppSettingsService, useValue: {appSettings: () => null}}, + ] + }); + + const component = TestBed.runInInjectionContext(() => new MetadataFetchOptionsComponent()); + const options: MetadataRefreshOptions = { + libraryId: 7, + refreshCovers: false, + mergeCategories: true, + reviewBeforeApply: true, + }; + + component.onMetadataSubmit(options); + + expect(refreshMetadataTask).toHaveBeenCalledWith({ + refreshType: MetadataRefreshType.BOOKS, + refreshOptions: options, + bookIds: [1, 2], + libraryId: 7, + }); + expect(close).toHaveBeenCalledOnce(); + }); +}); diff --git a/frontend/src/app/features/metadata/component/metadata-provider-field-selector/metadata-provider-field-selector.component.spec.ts b/frontend/src/app/features/metadata/component/metadata-provider-field-selector/metadata-provider-field-selector.component.spec.ts new file mode 100644 index 000000000..fa620529a --- /dev/null +++ b/frontend/src/app/features/metadata/component/metadata-provider-field-selector/metadata-provider-field-selector.component.spec.ts @@ -0,0 +1,70 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {of} from 'rxjs'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TranslocoService} from '@jsverse/transloco'; + +import {AppSettingKey, AppSettings} from '../../../../shared/model/app-settings.model'; +import {AppSettingsService} from '../../../../shared/service/app-settings.service'; +import {MetadataProviderFieldSelectorComponent} from './metadata-provider-field-selector.component'; + +describe('MetadataProviderFieldSelectorComponent', () => { + const saveSettings = vi.fn(() => of(void 0)); + const translate = vi.fn((key: string) => `translated:${key}`); + const appSettings = signal(null); + + beforeEach(() => { + saveSettings.mockClear(); + translate.mockClear(); + appSettings.set(null); + + TestBed.configureTestingModule({ + providers: [ + {provide: AppSettingsService, useValue: {appSettings, saveSettings}}, + {provide: TranslocoService, useValue: {translate}}, + ] + }); + }); + + it('loads selected provider-specific fields from app settings on init', () => { + appSettings.set({ + metadataProviderSpecificFields: { + asin: true, + amazonRating: false, + amazonReviewCount: true, + }, + } as AppSettings); + + const component = TestBed.runInInjectionContext(() => new MetadataProviderFieldSelectorComponent()); + component.ngOnInit(); + + expect(component.selectedFields).toEqual(['asin', 'amazonReviewCount']); + }); + + it('adds and removes selected fields while persisting the full field state', () => { + const component = TestBed.runInInjectionContext(() => new MetadataProviderFieldSelectorComponent()); + component.selectedFields = ['asin']; + + component.toggleField('googleId', true); + component.toggleField('asin', false); + + expect(component.selectedFields).toEqual(['googleId']); + expect(saveSettings).toHaveBeenCalledTimes(2); + expect(saveSettings).toHaveBeenLastCalledWith([{ + key: AppSettingKey.METADATA_PROVIDER_SPECIFIC_FIELDS, + newValue: expect.objectContaining({ + asin: false, + googleId: true, + }), + }]); + }); + + it('translates provider and field labels through Transloco', () => { + const component = TestBed.runInInjectionContext(() => new MetadataProviderFieldSelectorComponent()); + + expect(component.getProviderLabel('amazon')).toBe('translated:settingsMeta.fieldSelector.providers.amazon'); + expect(component.getFieldLabel('asin')).toBe('translated:settingsMeta.fieldSelector.fields.asin'); + expect(translate).toHaveBeenCalledWith('settingsMeta.fieldSelector.providers.amazon'); + expect(translate).toHaveBeenCalledWith('settingsMeta.fieldSelector.fields.asin'); + }); +}); diff --git a/frontend/src/app/features/metadata/component/metadata-review-dialog/metadata-review-dialog-component.spec.ts b/frontend/src/app/features/metadata/component/metadata-review-dialog/metadata-review-dialog-component.spec.ts new file mode 100644 index 000000000..6f055f98f --- /dev/null +++ b/frontend/src/app/features/metadata/component/metadata-review-dialog/metadata-review-dialog-component.spec.ts @@ -0,0 +1,157 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {of, throwError} from 'rxjs'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; + +import {BookService} from '../../../book/service/book.service'; +import {FetchedMetadataProposalStatus, FetchedProposal, MetadataTaskService} from '../../../book/service/metadata-task'; +import {BookMetadata} from '../../../book/model/book.model'; +import {MetadataProgressService} from '../../../../shared/service/metadata-progress.service'; +import {MetadataPickerComponent} from '../book-metadata-center/metadata-picker/metadata-picker.component'; +import {MetadataReviewDialogComponent} from './metadata-review-dialog-component'; + +describe('MetadataReviewDialogComponent', () => { + const close = vi.fn(); + const getTaskWithProposals = vi.fn(); + const updateProposalStatus = vi.fn(() => of(void 0)); + const deleteTask = vi.fn(() => of(void 0)); + const clearTask = vi.fn(); + const books = signal([{id: 11, title: 'Book 11'}]); + const findBookById = vi.fn((bookId: number) => books().find(book => book.id === bookId)); + + beforeEach(() => { + close.mockClear(); + getTaskWithProposals.mockReset(); + updateProposalStatus.mockClear(); + deleteTask.mockClear(); + clearTask.mockClear(); + findBookById.mockClear(); + }); + + function createProposal(overrides: Partial): FetchedProposal { + return { + proposalId: 1, + taskId: 'task-1', + bookId: 11, + fetchedAt: '2026-03-26T00:00:00Z', + reviewedAt: null, + reviewerUserId: null, + status: FetchedMetadataProposalStatus.FETCHED, + metadataJson: {} as BookMetadata, + ...overrides, + }; + } + + function createPickerStub() { + return { + onSave: vi.fn(), + lockAll: vi.fn(), + unlockAll: vi.fn(), + } as unknown as MetadataPickerComponent; + } + + function createComponent(taskId: string | undefined) { + TestBed.configureTestingModule({ + providers: [ + {provide: DynamicDialogConfig, useValue: {data: taskId ? {taskId} : {}}}, + {provide: DynamicDialogRef, useValue: {close}}, + {provide: MetadataTaskService, useValue: {getTaskWithProposals, updateProposalStatus, deleteTask}}, + {provide: BookService, useValue: {books, findBookById}}, + {provide: MetadataProgressService, useValue: {clearTask}}, + ] + }); + + return TestBed.runInInjectionContext(() => new MetadataReviewDialogComponent()); + } + + it('closes immediately when the dialog does not receive a task id', () => { + const component = createComponent(undefined); + + component.ngOnInit(); + + expect(close).toHaveBeenCalledOnce(); + }); + + it('loads proposals for the requested task and exposes the current book', () => { + getTaskWithProposals.mockReturnValue(of({ + proposals: [ + createProposal({proposalId: 5}), + ], + })); + + const component = createComponent('task-1'); + component.ngOnInit(); + TestBed.flushEffects(); + + expect(getTaskWithProposals).toHaveBeenCalledWith('task-1'); + expect(component.currentProposal).toEqual(createProposal({proposalId: 5})); + expect(component.currentBook()).toEqual({id: 11, title: 'Book 11'}); + expect(component.loading).toBe(false); + }); + + it('closes when loading the task proposals fails', () => { + getTaskWithProposals.mockReturnValue(throwError(() => new Error('failed'))); + + const component = createComponent('task-1'); + component.ngOnInit(); + + expect(close).toHaveBeenCalledOnce(); + }); + + it('saves the current proposal and clears progress when saving the last proposal', () => { + getTaskWithProposals.mockReturnValue(of({proposals: []})); + + const component = createComponent('task-1'); + component.proposals.set([createProposal({proposalId: 5})]); + component.pickerComponent = createPickerStub(); + + component.onSave(); + + expect(component.pickerComponent.onSave).toHaveBeenCalledOnce(); + expect(updateProposalStatus).toHaveBeenCalledWith('task-1', 5, 'ACCEPTED'); + expect(deleteTask).toHaveBeenCalledWith('task-1'); + expect(clearTask).toHaveBeenCalledWith('task-1'); + }); + + it('does nothing when save is triggered without an active proposal', () => { + getTaskWithProposals.mockReturnValue(of({proposals: []})); + + const component = createComponent('task-1'); + component.pickerComponent = createPickerStub(); + + component.onSave(); + + expect(component.pickerComponent.onSave).not.toHaveBeenCalled(); + expect(updateProposalStatus).not.toHaveBeenCalled(); + expect(deleteTask).not.toHaveBeenCalled(); + expect(clearTask).not.toHaveBeenCalled(); + }); + + it('advances between proposals and closes when moving past the last one', () => { + getTaskWithProposals.mockReturnValue(of({proposals: []})); + + const component = createComponent('task-1'); + component.proposals.set([ + createProposal({proposalId: 1, bookId: 11}), + createProposal({proposalId: 2, bookId: 12}), + ]); + + component.onNext(); + expect(component.currentProposal).toEqual(createProposal({proposalId: 2, bookId: 12})); + + component.onNext(); + expect(close).toHaveBeenCalledOnce(); + }); + + it('delegates lock and unlock actions to the picker component', () => { + const component = createComponent('task-1'); + component.pickerComponent = createPickerStub(); + + component.lockAllMetadata(); + component.unlockAllMetadata(); + + expect(component.pickerComponent.lockAll).toHaveBeenCalledOnce(); + expect(component.pickerComponent.unlockAll).toHaveBeenCalledOnce(); + }); +}); diff --git a/frontend/src/app/features/metadata/component/multi-book-metadata-editor/multi-book-metadata-editor-component.spec.ts b/frontend/src/app/features/metadata/component/multi-book-metadata-editor/multi-book-metadata-editor-component.spec.ts new file mode 100644 index 000000000..7434339bd --- /dev/null +++ b/frontend/src/app/features/metadata/component/multi-book-metadata-editor/multi-book-metadata-editor-component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around Angular Query detail loading, +// signal-based book navigation, and dialog-hosted tab composition so multi-book metadata editing +// can be asserted without the live query client and dialog runtime. +describe.skip('MultiBookMetadataEditorComponent', () => { + it('needs query seams to verify filtered-book selection and current-book detail loading', () => { + // TODO(seam): Cover book filtering and currentBook resolution once injectQuery can be driven with deterministic data without mutating runtime code. + }); + + it('needs navigation seams to verify next/previous boundaries and dialog close behavior', () => { + // TODO(seam): Cover index navigation and close delegation after dialog state and signal updates are isolated behind a stable test harness. + }); +}); diff --git a/frontend/src/app/features/metadata/component/multi-book-metadata-fetch/multi-book-metadata-fetch-component.spec.ts b/frontend/src/app/features/metadata/component/multi-book-metadata-fetch/multi-book-metadata-fetch-component.spec.ts new file mode 100644 index 000000000..0d799db6b --- /dev/null +++ b/frontend/src/app/features/metadata/component/multi-book-metadata-fetch/multi-book-metadata-fetch-component.spec.ts @@ -0,0 +1,78 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; + +import {AppSettings} from '../../../../shared/model/app-settings.model'; +import {AppSettingsService} from '../../../../shared/service/app-settings.service'; +import {Book} from '../../../book/model/book.model'; +import {BookService} from '../../../book/service/book.service'; +import {MetadataRefreshType} from '../../model/request/metadata-refresh-type.enum'; +import {MultiBookMetadataFetchComponent} from './multi-book-metadata-fetch-component'; + +describe('MultiBookMetadataFetchComponent', () => { + const appSettings = signal(null); + const getBooksByIds = vi.fn((bookIds: number[]) => bookIds.map(bookId => ({ + id: bookId, + title: `Book ${bookId}`, + libraryId: 1, + libraryName: 'Library', + } satisfies Book))); + + beforeEach(() => { + getBooksByIds.mockClear(); + appSettings.set(null); + + TestBed.configureTestingModule({ + providers: [ + { + provide: DynamicDialogConfig, + useValue: { + data: { + bookIds: [3, 5], + metadataRefreshType: MetadataRefreshType.BOOKS, + }, + }, + }, + {provide: DynamicDialogRef, useValue: {close: vi.fn()}}, + {provide: BookService, useValue: {getBooksByIds}}, + {provide: AppSettingsService, useValue: {appSettings}}, + ] + }); + }); + + it('reads dialog data and resolves the books to show on construction', () => { + const component = TestBed.runInInjectionContext(() => new MultiBookMetadataFetchComponent()); + + expect(component.bookIds).toEqual([3, 5]); + expect(component.metadataRefreshType).toBe(MetadataRefreshType.BOOKS); + expect(getBooksByIds).toHaveBeenCalledWith([3, 5]); + expect(component.booksToShow).toEqual([ + {id: 3, title: 'Book 3', libraryId: 1, libraryName: 'Library'}, + {id: 5, title: 'Book 5', libraryId: 1, libraryName: 'Library'}, + ]); + }); + + it('adopts the default metadata refresh options when app settings become available', () => { + const component = TestBed.runInInjectionContext(() => new MultiBookMetadataFetchComponent()); + + expect(component.currentMetadataOptions).toBeUndefined(); + + appSettings.set({ + defaultMetadataRefreshOptions: { + libraryId: 7, + refreshCovers: true, + mergeCategories: false, + reviewBeforeApply: true, + }, + } as AppSettings); + TestBed.flushEffects(); + + expect(component.currentMetadataOptions).toEqual({ + libraryId: 7, + refreshCovers: true, + mergeCategories: false, + reviewBeforeApply: true, + }); + }); +}); diff --git a/frontend/src/app/features/metadata/model/request/fetch-metadata-request.model.spec.ts b/frontend/src/app/features/metadata/model/request/fetch-metadata-request.model.spec.ts new file mode 100644 index 000000000..25ddafc60 --- /dev/null +++ b/frontend/src/app/features/metadata/model/request/fetch-metadata-request.model.spec.ts @@ -0,0 +1,19 @@ +import {describe, expect, expectTypeOf, it} from 'vitest'; + +import {FetchMetadataRequest} from './fetch-metadata-request.model'; + +describe('fetch-metadata-request.model', () => { + it('captures the metadata fetch payload shape', () => { + const request: FetchMetadataRequest = { + bookId: 12, + providers: ['google', 'hardcover'], + title: 'A Wizard of Earthsea', + author: 'Ursula K. Le Guin', + isbn: '9780547773742' + }; + + expect(request.providers).toContain('google'); + expect(request.bookId).toBe(12); + expectTypeOf(request.providers).toEqualTypeOf(); + }); +}); diff --git a/frontend/src/app/features/metadata/model/request/metadata-refresh-options.model.spec.ts b/frontend/src/app/features/metadata/model/request/metadata-refresh-options.model.spec.ts new file mode 100644 index 000000000..af70763a9 --- /dev/null +++ b/frontend/src/app/features/metadata/model/request/metadata-refresh-options.model.spec.ts @@ -0,0 +1,109 @@ +import {describe, expect, expectTypeOf, it} from 'vitest'; + +import { + FieldOptions, + FieldProvider, + MetadataRefreshOptions, + MetadataReplaceMode +} from './metadata-refresh-options.model'; + +const provider = (value: string | null): FieldProvider => ({ + p4: value, + p3: value, + p2: value, + p1: value +}); + +describe('metadata-refresh-options.model', () => { + it('supports replace-mode driven refresh settings', () => { + const fieldOptions: FieldOptions = { + title: provider('google'), + description: provider('google'), + authors: provider('google'), + categories: provider('google'), + cover: provider('google'), + subtitle: provider('google'), + publisher: provider('google'), + publishedDate: provider('google'), + seriesName: provider('google'), + seriesNumber: provider('google'), + seriesTotal: provider('google'), + isbn13: provider('google'), + isbn10: provider('google'), + language: provider('google'), + pageCount: provider('google'), + asin: provider('google'), + goodreadsId: provider('goodreads'), + comicvineId: provider(null), + hardcoverId: provider('hardcover'), + hardcoverBookId: provider('hardcover'), + googleId: provider('google'), + lubimyczytacId: provider(null), + amazonRating: provider('amazon'), + amazonReviewCount: provider('amazon'), + goodreadsRating: provider('goodreads'), + goodreadsReviewCount: provider('goodreads'), + hardcoverRating: provider('hardcover'), + hardcoverReviewCount: provider('hardcover'), + lubimyczytacRating: provider(null), + ranobedbId: provider(null), + ranobedbRating: provider(null), + audibleId: provider('audible'), + audibleRating: provider('audible'), + audibleReviewCount: provider('audible'), + moods: provider('google'), + tags: provider('google') + }; + + const options: MetadataRefreshOptions = { + libraryId: 3, + refreshCovers: true, + mergeCategories: false, + reviewBeforeApply: true, + replaceMode: 'REPLACE_MISSING', + fieldOptions, + enabledFields: { + title: true, + description: true, + authors: true, + categories: true, + cover: true, + subtitle: false, + publisher: true, + publishedDate: true, + seriesName: true, + seriesNumber: true, + seriesTotal: true, + isbn13: true, + isbn10: true, + language: true, + pageCount: true, + asin: true, + goodreadsId: true, + comicvineId: false, + hardcoverId: true, + hardcoverBookId: true, + googleId: true, + lubimyczytacId: false, + amazonRating: true, + amazonReviewCount: true, + goodreadsRating: true, + goodreadsReviewCount: true, + hardcoverRating: true, + hardcoverReviewCount: true, + lubimyczytacRating: false, + ranobedbId: false, + ranobedbRating: false, + audibleId: true, + audibleRating: true, + audibleReviewCount: true, + moods: true, + tags: true + } + }; + + expect(options.fieldOptions?.title.p4).toBe('google'); + expect(options.enabledFields?.subtitle).toBe(false); + expectTypeOf(options.replaceMode).toEqualTypeOf(); + }); +}); diff --git a/frontend/src/app/features/metadata/model/request/metadata-refresh-request.model.spec.ts b/frontend/src/app/features/metadata/model/request/metadata-refresh-request.model.spec.ts new file mode 100644 index 000000000..a1f774091 --- /dev/null +++ b/frontend/src/app/features/metadata/model/request/metadata-refresh-request.model.spec.ts @@ -0,0 +1,31 @@ +import {describe, expect, it} from 'vitest'; + +import {MetadataRefreshRequest} from './metadata-refresh-request.model'; +import {MetadataRefreshType} from './metadata-refresh-type.enum'; + +describe('metadata-refresh-request.model', () => { + it('supports library-wide refresh requests with nested options', () => { + const request: MetadataRefreshRequest = { + refreshType: MetadataRefreshType.LIBRARY, + libraryId: 8, + refreshOptions: { + libraryId: 8, + refreshCovers: true, + mergeCategories: true, + reviewBeforeApply: false + } + }; + + expect(request.refreshType).toBe(MetadataRefreshType.LIBRARY); + expect(request.refreshOptions?.refreshCovers).toBe(true); + }); + + it('supports book-scoped refresh requests', () => { + const request: MetadataRefreshRequest = { + refreshType: MetadataRefreshType.BOOKS, + bookIds: [1, 2, 3] + }; + + expect(request.bookIds).toEqual([1, 2, 3]); + }); +}); diff --git a/frontend/src/app/features/metadata/model/request/metadata-refresh-type.enum.spec.ts b/frontend/src/app/features/metadata/model/request/metadata-refresh-type.enum.spec.ts new file mode 100644 index 000000000..994653493 --- /dev/null +++ b/frontend/src/app/features/metadata/model/request/metadata-refresh-type.enum.spec.ts @@ -0,0 +1,12 @@ +import {describe, expect, it} from 'vitest'; + +import {MetadataRefreshType} from './metadata-refresh-type.enum'; + +describe('MetadataRefreshType', () => { + it('exposes both supported refresh scopes', () => { + expect(MetadataRefreshType).toEqual({ + BOOKS: 'BOOKS', + LIBRARY: 'LIBRARY' + }); + }); +}); diff --git a/frontend/src/app/features/metadata/service/sidecar.service.spec.ts b/frontend/src/app/features/metadata/service/sidecar.service.spec.ts new file mode 100644 index 000000000..c3dff788a --- /dev/null +++ b/frontend/src/app/features/metadata/service/sidecar.service.spec.ts @@ -0,0 +1,99 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {API_CONFIG} from '../../../core/config/api-config'; +import {SidecarService} from './sidecar.service'; + +describe('SidecarService', () => { + let service: SidecarService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + SidecarService, + ] + }); + + service = TestBed.inject(SidecarService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('fetches sidecar content for a book', () => { + service.getSidecarContent(42).subscribe(response => { + expect(response.metadata.title).toBe('Book'); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/books/42/sidecar`); + expect(request.request.method).toBe('GET'); + request.flush({ + version: '1', + generatedAt: '2026-03-26T00:00:00Z', + generatedBy: 'test', + metadata: {title: 'Book'}, + }); + }); + + it('fetches the sidecar sync status', () => { + service.getSyncStatus(42).subscribe(response => { + expect(response).toEqual({status: 'CONFLICT'}); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/books/42/sidecar/status`); + expect(request.request.method).toBe('GET'); + request.flush({status: 'CONFLICT'}); + }); + + it('exports a sidecar for a book', () => { + service.exportToSidecar(42).subscribe(response => { + expect(response).toEqual({message: 'ok'}); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/books/42/sidecar/export`); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual({}); + request.flush({message: 'ok'}); + }); + + it('imports a sidecar for a book', () => { + service.importFromSidecar(42).subscribe(response => { + expect(response).toEqual({message: 'done'}); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/books/42/sidecar/import`); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual({}); + request.flush({message: 'done'}); + }); + + it('bulk exports sidecars for a library', () => { + service.bulkExport(7).subscribe(response => { + expect(response).toEqual({message: 'exported', exported: 3}); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/libraries/7/sidecar/export-all`); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual({}); + request.flush({message: 'exported', exported: 3}); + }); + + it('bulk imports sidecars for a library', () => { + service.bulkImport(7).subscribe(response => { + expect(response).toEqual({message: 'imported', imported: 2}); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/libraries/7/sidecar/import-all`); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual({}); + request.flush({message: 'imported', imported: 2}); + }); +}); diff --git a/frontend/src/app/features/notebook/components/notebook/notebook.component.spec.ts b/frontend/src/app/features/notebook/components/notebook/notebook.component.spec.ts new file mode 100644 index 000000000..97a698ca9 --- /dev/null +++ b/frontend/src/app/features/notebook/components/notebook/notebook.component.spec.ts @@ -0,0 +1,10 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around debounced search subjects, paginated +// notebook service streams, URL helper thumbnails, and page-title side effects so notebook grouping +// and filtering can be verified without a brittle async integration harness. +describe.skip('NotebookComponent', () => { + it('needs notebook-query and debounce seams to verify grouping, filtering, and pagination flows deterministically', () => { + // TODO(seam): Cover entry grouping and filter transitions once the search/load streams are isolated from UI timing concerns. + }); +}); diff --git a/frontend/src/app/features/notebook/model/notebook.model.spec.ts b/frontend/src/app/features/notebook/model/notebook.model.spec.ts new file mode 100644 index 000000000..cf67e4c6e --- /dev/null +++ b/frontend/src/app/features/notebook/model/notebook.model.spec.ts @@ -0,0 +1,39 @@ +import {describe, expect, expectTypeOf, it} from 'vitest'; + +import {NotebookBookOption, NotebookEntry, NotebookPage} from './notebook.model'; + +describe('notebook.model', () => { + it('supports notebook entries with annotation metadata', () => { + const entry: NotebookEntry = { + id: 5, + type: 'HIGHLIGHT', + bookId: 10, + bookTitle: 'The Left Hand of Darkness', + text: 'Light is the left hand of darkness', + note: 'Opening line', + createdAt: '2026-03-26T10:00:00Z' + }; + + expect(entry.type).toBe('HIGHLIGHT'); + expectTypeOf(entry.updatedAt).toEqualTypeOf(); + }); + + it('captures paged notebook results and book options', () => { + const page: NotebookPage = { + content: [], + page: { + totalElements: 0, + totalPages: 0, + number: 0, + size: 25 + } + }; + const option: NotebookBookOption = { + bookId: 10, + bookTitle: 'The Left Hand of Darkness' + }; + + expect(page.page.size).toBe(25); + expect(option.bookTitle).toContain('Darkness'); + }); +}); diff --git a/frontend/src/app/features/notebook/service/notebook.service.spec.ts b/frontend/src/app/features/notebook/service/notebook.service.spec.ts new file mode 100644 index 000000000..de2769038 --- /dev/null +++ b/frontend/src/app/features/notebook/service/notebook.service.spec.ts @@ -0,0 +1,67 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {API_CONFIG} from '../../../core/config/api-config'; +import {NotebookService} from './notebook.service'; + +describe('NotebookService', () => { + let service: NotebookService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + NotebookService, + ], + }); + + service = TestBed.inject(NotebookService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('loads notebook entries with repeated types, book filter, and trimmed search', () => { + service.getNotebookEntries(2, 25, ['HIGHLIGHT', 'NOTE'], 42, ' query ', 'createdAt,desc') + .subscribe(entries => expect(entries).toEqual([])); + + const request = httpTestingController.expectOne(req => req.urlWithParams.startsWith(`${API_CONFIG.BASE_URL}/api/v1/notebook?`)); + expect(request.request.method).toBe('GET'); + expect(request.request.params.get('page')).toBe('2'); + expect(request.request.params.get('size')).toBe('25'); + expect(request.request.params.getAll('types')).toEqual(['HIGHLIGHT', 'NOTE']); + expect(request.request.params.get('bookId')).toBe('42'); + expect(request.request.params.get('search')).toBe('query'); + expect(request.request.params.get('sort')).toBe('createdAt,desc'); + request.flush([]); + }); + + it('loads export entries without optional filters when they are blank', () => { + service.getExportEntries(['BOOKMARK'], null, ' ', 'updatedAt,asc') + .subscribe(entries => expect(entries).toEqual([])); + + const request = httpTestingController.expectOne(req => req.urlWithParams.startsWith(`${API_CONFIG.BASE_URL}/api/v1/notebook/export?`)); + expect(request.request.method).toBe('GET'); + expect(request.request.params.getAll('types')).toEqual(['BOOKMARK']); + expect(request.request.params.has('bookId')).toBe(false); + expect(request.request.params.has('search')).toBe(false); + expect(request.request.params.get('sort')).toBe('updatedAt,asc'); + request.flush([]); + }); + + it('queries notebook books only when a non-empty search term is provided', () => { + service.getBooksWithAnnotations(' title ').subscribe(options => expect(options).toEqual([])); + + const request = httpTestingController.expectOne(req => req.urlWithParams.startsWith(`${API_CONFIG.BASE_URL}/api/v1/notebook/books`)); + expect(request.request.method).toBe('GET'); + expect(request.request.params.get('search')).toBe('title'); + request.flush([]); + }); +}); diff --git a/frontend/src/app/features/readers/audiobook-player/audiobook-player.component.spec.ts b/frontend/src/app/features/readers/audiobook-player/audiobook-player.component.spec.ts new file mode 100644 index 000000000..90dfb2dbc --- /dev/null +++ b/frontend/src/app/features/readers/audiobook-player/audiobook-player.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around the HTMLAudioElement lifecycle, +// sleep-timer intervals, route-driven loading, and bookmark/session browser behavior so the +// player can be tested honestly without booting the full audio runtime in Vitest. +describe.skip('AudiobookPlayerComponent', () => { + it('needs an audio-element seam to verify playback, seeking, buffering, and track switching', () => { + // TODO(seam): Cover player controls once the audio element and timer workflow are abstracted behind testable adapters. + }); + + it('needs a session-and-bookmark seam to verify progress saving and bookmark actions without browser media side effects', () => { + // TODO(seam): Cover session lifecycle, bookmark menus, and route changes after extracting the runtime audio/session dependencies. + }); +}); diff --git a/frontend/src/app/features/readers/audiobook-player/audiobook.model.spec.ts b/frontend/src/app/features/readers/audiobook-player/audiobook.model.spec.ts new file mode 100644 index 000000000..ca2a90b2f --- /dev/null +++ b/frontend/src/app/features/readers/audiobook-player/audiobook.model.spec.ts @@ -0,0 +1,51 @@ +import {describe, expect, expectTypeOf, it} from 'vitest'; + +import { + AudiobookChapter, + AudiobookInfo, + AudiobookProgress, + AudiobookTrack +} from './audiobook.model'; + +describe('audiobook.model', () => { + it('supports audiobook metadata, chapters, and tracks', () => { + const chapter: AudiobookChapter = { + index: 1, + title: 'Chapter 1', + startTimeMs: 0, + endTimeMs: 60000, + durationMs: 60000 + }; + const track: AudiobookTrack = { + index: 0, + fileName: 'track-01.mp3', + title: 'Track 1', + durationMs: 60000, + fileSizeBytes: 1024, + cumulativeStartMs: 0 + }; + const info: AudiobookInfo = { + bookId: 1, + bookFileId: 2, + durationMs: 60000, + folderBased: false, + chapters: [chapter], + tracks: [track] + }; + + expect(info.chapters?.[0].title).toBe('Chapter 1'); + expect(info.tracks?.[0].fileName).toBe('track-01.mp3'); + }); + + it('keeps audiobook progress numerically typed', () => { + const progress: AudiobookProgress = { + positionMs: 5000, + trackIndex: 0, + trackPositionMs: 5000, + percentage: 8.3 + }; + + expect(progress.percentage).toBeCloseTo(8.3); + expectTypeOf(progress.trackIndex).toEqualTypeOf(); + }); +}); diff --git a/frontend/src/app/features/readers/audiobook-player/audiobook.service.spec.ts b/frontend/src/app/features/readers/audiobook-player/audiobook.service.spec.ts new file mode 100644 index 000000000..c0f0a1b27 --- /dev/null +++ b/frontend/src/app/features/readers/audiobook-player/audiobook.service.spec.ts @@ -0,0 +1,112 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {AuthService} from '../../../shared/service/auth.service'; +import {AudiobookInfo, AudiobookProgress} from './audiobook.model'; +import {AudiobookService} from './audiobook.service'; + +describe('AudiobookService', () => { + let service: AudiobookService; + let httpTestingController: HttpTestingController; + let getInternalAccessToken: ReturnType; + + beforeEach(() => { + getInternalAccessToken = vi.fn(() => 'token 123'); + + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + AudiobookService, + { + provide: AuthService, + useValue: {getInternalAccessToken}, + }, + ], + }); + + service = TestBed.inject(AudiobookService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('fetches audiobook info and forwards the optional book type parameter', () => { + const info: AudiobookInfo = { + bookId: 7, + bookFileId: 8, + durationMs: 123_000, + folderBased: false, + }; + let result: AudiobookInfo | undefined; + + service.getAudiobookInfo(7, 'AUDIOBOOK').subscribe(value => { + result = value; + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/audiobooks/7/info')); + expect(request.request.method).toBe('GET'); + expect(request.request.params.get('bookType')).toBe('AUDIOBOOK'); + request.flush(info); + + expect(result).toEqual(info); + }); + + it('builds stream and cover URLs with an encoded token and optional track index', () => { + expect(service.getStreamUrl(4, 2)).toContain('/api/v1/audiobooks/4/stream?ngsw-bypass=true&token=token%20123&trackIndex=2'); + expect(service.getTrackStreamUrl(4, 9)).toContain('/api/v1/audiobooks/4/track/9/stream?ngsw-bypass=true&token=token%20123'); + expect(service.getEmbeddedCoverUrl(4)).toContain('/api/v1/audiobooks/4/cover?ngsw-bypass=true&token=token%20123'); + }); + + it('saves audiobook progress directly when no book file id is provided', () => { + const progress: AudiobookProgress = { + positionMs: 50_000, + trackIndex: 3, + percentage: 42.5, + }; + let completed = false; + + service.saveProgress(9, progress).subscribe(() => { + completed = true; + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/progress')); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual({ + bookId: 9, + audiobookProgress: progress, + }); + request.flush(null); + + expect(completed).toBe(true); + }); + + it('maps audiobook progress into a file progress payload when a book file id is present', () => { + const progress: AudiobookProgress = { + positionMs: 75_000, + trackIndex: 5, + percentage: 80, + }; + + service.saveProgress(12, progress, 99).subscribe(); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/progress')); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual({ + bookId: 12, + fileProgress: { + bookFileId: 99, + positionData: '75000', + positionHref: '5', + progressPercent: 80, + }, + }); + request.flush(null); + }); +}); diff --git a/frontend/src/app/features/readers/audiobook-player/index.spec.ts b/frontend/src/app/features/readers/audiobook-player/index.spec.ts new file mode 100644 index 000000000..2cde804f3 --- /dev/null +++ b/frontend/src/app/features/readers/audiobook-player/index.spec.ts @@ -0,0 +1,16 @@ +import {describe, expect, it} from 'vitest'; + +import * as audiobookIndex from './index'; +import {AudiobookPlayerComponent} from './audiobook-player.component'; +import {AudiobookService} from './audiobook.service'; + +describe('audiobook-player index', () => { + it('re-exports the component and service entrypoints', () => { + expect(audiobookIndex.AudiobookPlayerComponent).toBe(AudiobookPlayerComponent); + expect(audiobookIndex.AudiobookService).toBe(AudiobookService); + }); + + it('re-exports the audiobook model helpers namespace', () => { + expect('AudiobookInfo' in audiobookIndex).toBe(false); + }); +}); diff --git a/frontend/src/app/features/readers/cbx-reader/cbx-reader.component.spec.ts b/frontend/src/app/features/readers/cbx-reader/cbx-reader.component.spec.ts new file mode 100644 index 000000000..f4d047a2e --- /dev/null +++ b/frontend/src/app/features/readers/cbx-reader/cbx-reader.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around image preloading, fullscreen, +// touch/mouse/keyboard browser events, and the CBX header/sidebar/footer service graph so the +// reader can be tested without reproducing the full interactive runtime. +describe.skip('CbxReaderComponent', () => { + it('needs an interaction-runtime seam to verify pagination, reader controls, and bookmark/note state', () => { + // TODO(seam): Cover page transitions and control wiring once browser-event and image-loading dependencies are abstracted. + }); + + it('needs a session-and-route seam to verify startup, teardown, and series-navigation behavior deterministically', () => { + // TODO(seam): Cover progress persistence and route-driven loading after introducing testable adapters around the reader runtime. + }); +}); diff --git a/frontend/src/app/features/readers/cbx-reader/dialogs/cbx-note-dialog.component.spec.ts b/frontend/src/app/features/readers/cbx-reader/dialogs/cbx-note-dialog.component.spec.ts new file mode 100644 index 000000000..44095d0db --- /dev/null +++ b/frontend/src/app/features/readers/cbx-reader/dialogs/cbx-note-dialog.component.spec.ts @@ -0,0 +1,78 @@ +import {SimpleChange} from '@angular/core'; +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {getTranslocoModule} from '../../../../core/testing/transloco-testing'; +import {CbxNoteDialogComponent} from './cbx-note-dialog.component'; + +describe('CbxNoteDialogComponent', () => { + let fixture: ComponentFixture; + let component: CbxNoteDialogComponent; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [CbxNoteDialogComponent, getTranslocoModule()], + }).compileComponents(); + + fixture = TestBed.createComponent(CbxNoteDialogComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + it('hydrates its local state from input changes and reports edit mode when a note id is present', () => { + component.data = { + pageNumber: 9, + noteId: 3, + noteContent: ' remembered ', + color: '#2196F3', + }; + + component.ngOnChanges({ + data: new SimpleChange(null, component.data, false), + }); + + expect(component.isEditing).toBe(true); + expect(component.noteContent).toBe(' remembered '); + expect(component.selectedColor).toBe('#2196F3'); + }); + + it('emits saved notes with trimmed content and the selected color', () => { + const savedSpy = vi.fn(); + component.saved.subscribe(savedSpy); + component.noteContent = ' Panel reveal '; + component.selectColor('#E91E63'); + + component.onSave(); + + expect(savedSpy).toHaveBeenCalledWith({ + noteContent: 'Panel reveal', + color: '#E91E63', + }); + }); + + it('does not emit saves for blank notes and emits cancel events explicitly or through the overlay', () => { + const savedSpy = vi.fn(); + const cancelSpy = vi.fn(); + component.saved.subscribe(savedSpy); + component.cancelled.subscribe(cancelSpy); + + component.noteContent = ' '; + component.onSave(); + component.onCancel(); + component.onOverlayClick({ + target: { + classList: { + contains: vi.fn((value: string) => value === 'dialog-overlay'), + }, + }, + } as unknown as Event); + + expect(savedSpy).not.toHaveBeenCalled(); + expect(cancelSpy).toHaveBeenCalledTimes(2); + }); +}); diff --git a/frontend/src/app/features/readers/cbx-reader/dialogs/cbx-shortcuts-help.component.spec.ts b/frontend/src/app/features/readers/cbx-reader/dialogs/cbx-shortcuts-help.component.spec.ts new file mode 100644 index 000000000..a48e2caac --- /dev/null +++ b/frontend/src/app/features/readers/cbx-reader/dialogs/cbx-shortcuts-help.component.spec.ts @@ -0,0 +1,65 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {getTranslocoModule} from '../../../../core/testing/transloco-testing'; +import {CbxShortcutsHelpComponent} from './cbx-shortcuts-help.component'; + +describe('CbxShortcutsHelpComponent', () => { + let fixture: ComponentFixture; + let component: CbxShortcutsHelpComponent; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [CbxShortcutsHelpComponent, getTranslocoModule()], + }).compileComponents(); + + fixture = TestBed.createComponent(CbxShortcutsHelpComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + it('builds translated shortcut groups for navigation, display, playback, and other actions', () => { + const groups = component.shortcutGroups; + + expect(groups).toHaveLength(4); + expect(groups.map((group) => group.shortcuts.length)).toEqual([7, 7, 1, 1]); + expect(groups[0].shortcuts[0].keys).toEqual(['←', '→']); + expect(groups[0].shortcuts[0].mobileGesture).toBeTruthy(); + }); + + it('emits close events directly and when the overlay background is clicked', () => { + const closeSpy = vi.fn(); + component.closed.subscribe(closeSpy); + + component.onClose(); + component.onOverlayClick({ + target: { + classList: { + contains: vi.fn((value: string) => value === 'dialog-overlay'), + }, + }, + } as unknown as Event); + + expect(closeSpy).toHaveBeenCalledTimes(2); + }); + + it('ignores clicks that do not land on the dialog overlay', () => { + const closeSpy = vi.fn(); + component.closed.subscribe(closeSpy); + + component.onOverlayClick({ + target: { + classList: { + contains: vi.fn(() => false), + }, + }, + } as unknown as Event); + + expect(closeSpy).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/app/features/readers/cbx-reader/layout/footer/cbx-footer.component.spec.ts b/frontend/src/app/features/readers/cbx-reader/layout/footer/cbx-footer.component.spec.ts new file mode 100644 index 000000000..6f944555a --- /dev/null +++ b/frontend/src/app/features/readers/cbx-reader/layout/footer/cbx-footer.component.spec.ts @@ -0,0 +1,93 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {getTranslocoModule} from '../../../../../core/testing/transloco-testing'; +import {CbxFooterComponent} from './cbx-footer.component'; +import {CbxFooterService} from './cbx-footer.service'; + +describe('CbxFooterComponent', () => { + let fixture: ComponentFixture; + let component: CbxFooterComponent; + let footerService: CbxFooterService; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [CbxFooterComponent, getTranslocoModule()], + providers: [CbxFooterService], + }).compileComponents(); + + fixture = TestBed.createComponent(CbxFooterComponent); + component = fixture.componentInstance; + footerService = TestBed.inject(CbxFooterService); + fixture.detectChanges(); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('derives display state and navigation availability from the footer service state', () => { + footerService.updateState({ + currentPage: 1, + totalPages: 4, + isTwoPageView: true, + }); + + expect(component.displayPage).toBe(2); + expect(component.displaySecondPage).toBe(3); + expect(component.sliderValue).toBe(2); + expect(component.canGoPrevious).toBe(true); + expect(component.canGoNext).toBe(true); + }); + + it('builds page slider ticks for both short and long books', () => { + footerService.updateState({totalPages: 8}); + expect(component.sliderTicks).toEqual([1, 2, 3, 4, 5, 6, 7, 8]); + + footerService.updateState({totalPages: 53}); + expect(component.sliderTicks[0]).toBe(1); + expect(component.sliderTicks).toContain(6); + expect(component.sliderTicks.at(-1)).toBe(53); + }); + + it('emits navigation events through the footer service', () => { + const previousSpy = vi.spyOn(footerService, 'emitPreviousPage'); + const nextSpy = vi.spyOn(footerService, 'emitNextPage'); + const firstSpy = vi.spyOn(footerService, 'emitFirstPage'); + const lastSpy = vi.spyOn(footerService, 'emitLastPage'); + const previousBookSpy = vi.spyOn(footerService, 'emitPreviousBook'); + const nextBookSpy = vi.spyOn(footerService, 'emitNextBook'); + + component.onPreviousPage(); + component.onNextPage(); + component.onFirstPage(); + component.onLastPage(); + component.onPreviousBook(); + component.onNextBook(); + + expect(previousSpy).toHaveBeenCalledOnce(); + expect(nextSpy).toHaveBeenCalledOnce(); + expect(firstSpy).toHaveBeenCalledOnce(); + expect(lastSpy).toHaveBeenCalledOnce(); + expect(previousBookSpy).toHaveBeenCalledOnce(); + expect(nextBookSpy).toHaveBeenCalledOnce(); + }); + + it('emits page changes only for valid manual page input and slider changes', () => { + const goToPageSpy = vi.spyOn(footerService, 'emitGoToPage'); + const sliderSpy = vi.spyOn(footerService, 'emitSliderChange'); + footerService.updateState({totalPages: 10}); + + component.goToPageInput = 5; + component.onGoToPage(); + expect(goToPageSpy).toHaveBeenCalledWith(5); + expect(component.goToPageInput).toBeNull(); + + component.goToPageInput = 12; + component.onGoToPage(); + expect(goToPageSpy).toHaveBeenCalledTimes(1); + + component.onSliderChange({target: {value: '7'}} as unknown as Event); + expect(sliderSpy).toHaveBeenCalledWith(7); + }); +}); diff --git a/frontend/src/app/features/readers/cbx-reader/layout/footer/cbx-footer.service.spec.ts b/frontend/src/app/features/readers/cbx-reader/layout/footer/cbx-footer.service.spec.ts new file mode 100644 index 000000000..098d971df --- /dev/null +++ b/frontend/src/app/features/readers/cbx-reader/layout/footer/cbx-footer.service.spec.ts @@ -0,0 +1,92 @@ +import {describe, expect, it} from 'vitest'; + +import {CbxFooterService} from './cbx-footer.service'; +import {Book} from '../../../../book/model/book.model'; + +describe('CbxFooterService', () => { + const previousBook = { + id: 1, + libraryId: 11, + libraryName: 'Library', + metadata: {bookId: 1, title: 'Previous'}, + } as Book; + + const nextBook = { + id: 2, + libraryId: 11, + libraryName: 'Library', + metadata: {bookId: 2, title: 'Next'}, + } as Book; + + it('updates footer state and resets to the default values', () => { + const service = new CbxFooterService(); + + service.setForceVisible(true); + service.setCurrentPage(4); + service.setTotalPages(10); + service.setTwoPageView(true); + service.setSeriesBooks(previousBook, nextBook); + service.setHasSeries(true); + + expect(service.forceVisible()).toBe(true); + expect(service.state()).toEqual({ + currentPage: 4, + totalPages: 10, + isTwoPageView: true, + previousBookInSeries: previousBook, + nextBookInSeries: nextBook, + hasSeries: true + }); + + service.reset(); + + expect(service.forceVisible()).toBe(false); + expect(service.state()).toEqual({ + currentPage: 0, + totalPages: 0, + isTwoPageView: false, + previousBookInSeries: null, + nextBookInSeries: null, + hasSeries: false + }); + }); + + it('emits all footer navigation actions', () => { + const service = new CbxFooterService(); + const previousPageEvents: void[] = []; + const nextPageEvents: void[] = []; + const goToPageEvents: number[] = []; + const firstPageEvents: void[] = []; + const lastPageEvents: void[] = []; + const previousBookEvents: void[] = []; + const nextBookEvents: void[] = []; + const sliderChangeEvents: number[] = []; + + service.previousPage$.subscribe(() => previousPageEvents.push(undefined)); + service.nextPage$.subscribe(() => nextPageEvents.push(undefined)); + service.goToPage$.subscribe(value => goToPageEvents.push(value)); + service.firstPage$.subscribe(() => firstPageEvents.push(undefined)); + service.lastPage$.subscribe(() => lastPageEvents.push(undefined)); + service.previousBook$.subscribe(() => previousBookEvents.push(undefined)); + service.nextBook$.subscribe(() => nextBookEvents.push(undefined)); + service.sliderChange$.subscribe(value => sliderChangeEvents.push(value)); + + service.emitPreviousPage(); + service.emitNextPage(); + service.emitGoToPage(7); + service.emitFirstPage(); + service.emitLastPage(); + service.emitPreviousBook(); + service.emitNextBook(); + service.emitSliderChange(8); + + expect(previousPageEvents).toHaveLength(1); + expect(nextPageEvents).toHaveLength(1); + expect(goToPageEvents).toEqual([7]); + expect(firstPageEvents).toHaveLength(1); + expect(lastPageEvents).toHaveLength(1); + expect(previousBookEvents).toHaveLength(1); + expect(nextBookEvents).toHaveLength(1); + expect(sliderChangeEvents).toEqual([8]); + }); +}); diff --git a/frontend/src/app/features/readers/cbx-reader/layout/header/cbx-header.component.spec.ts b/frontend/src/app/features/readers/cbx-reader/layout/header/cbx-header.component.spec.ts new file mode 100644 index 000000000..7b3fab290 --- /dev/null +++ b/frontend/src/app/features/readers/cbx-reader/layout/header/cbx-header.component.spec.ts @@ -0,0 +1,90 @@ +import {signal} from '@angular/core'; +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {getTranslocoModule} from '../../../../../core/testing/transloco-testing'; +import {CbxHeaderComponent} from './cbx-header.component'; +import {CbxHeaderService} from './cbx-header.service'; + +describe('CbxHeaderComponent', () => { + let fixture: ComponentFixture; + let component: CbxHeaderComponent; + let headerService: { + forceVisible: ReturnType>; + state: ReturnType>; + bookTitle: ReturnType>; + openSidebar: ReturnType; + openQuickSettings: ReturnType; + toggleBookmark: ReturnType; + openNoteDialog: ReturnType; + toggleFullscreen: ReturnType; + toggleSlideshow: ReturnType; + toggleMagnifier: ReturnType; + showShortcutsHelp: ReturnType; + close: ReturnType; + }; + + beforeEach(async () => { + headerService = { + forceVisible: signal(true), + state: signal({isFullscreen: false, isSlideshowActive: false, isMagnifierActive: false}), + bookTitle: signal('Chapter One'), + openSidebar: vi.fn(), + openQuickSettings: vi.fn(), + toggleBookmark: vi.fn(), + openNoteDialog: vi.fn(), + toggleFullscreen: vi.fn(), + toggleSlideshow: vi.fn(), + toggleMagnifier: vi.fn(), + showShortcutsHelp: vi.fn(), + close: vi.fn(), + }; + + await TestBed.configureTestingModule({ + imports: [CbxHeaderComponent, getTranslocoModule()], + providers: [{provide: CbxHeaderService, useValue: headerService}], + }).compileComponents(); + + fixture = TestBed.createComponent(CbxHeaderComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + it('exposes the header service signals and default overflow state', () => { + expect(component.forceVisible()).toBe(true); + expect(component.bookTitle()).toBe('Chapter One'); + expect(component.state()).toEqual({ + isFullscreen: false, + isSlideshowActive: false, + isMagnifierActive: false, + }); + expect(component.overflowOpen).toBe(false); + }); + + it('delegates all header actions to the header service', () => { + component.onOpenSidebar(); + component.onOpenSettings(); + component.onToggleBookmark(); + component.onOpenNoteDialog(); + component.onToggleFullscreen(); + component.onToggleSlideshow(); + component.onToggleMagnifier(); + component.onShowShortcutsHelp(); + component.onClose(); + + expect(headerService.openSidebar).toHaveBeenCalledOnce(); + expect(headerService.openQuickSettings).toHaveBeenCalledOnce(); + expect(headerService.toggleBookmark).toHaveBeenCalledOnce(); + expect(headerService.openNoteDialog).toHaveBeenCalledOnce(); + expect(headerService.toggleFullscreen).toHaveBeenCalledOnce(); + expect(headerService.toggleSlideshow).toHaveBeenCalledOnce(); + expect(headerService.toggleMagnifier).toHaveBeenCalledOnce(); + expect(headerService.showShortcutsHelp).toHaveBeenCalledOnce(); + expect(headerService.close).toHaveBeenCalledOnce(); + }); +}); diff --git a/frontend/src/app/features/readers/cbx-reader/layout/header/cbx-header.service.spec.ts b/frontend/src/app/features/readers/cbx-reader/layout/header/cbx-header.service.spec.ts new file mode 100644 index 000000000..0102e8b33 --- /dev/null +++ b/frontend/src/app/features/readers/cbx-reader/layout/header/cbx-header.service.spec.ts @@ -0,0 +1,105 @@ +import {Location} from '@angular/common'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {CbxHeaderService} from './cbx-header.service'; +import {CbxSidebarService} from '../sidebar/cbx-sidebar.service'; + +describe('CbxHeaderService', () => { + let service: CbxHeaderService; + + const sidebarService = { + open: vi.fn(), + }; + + const location = { + back: vi.fn(), + }; + + beforeEach(() => { + sidebarService.open.mockReset(); + location.back.mockReset(); + + TestBed.configureTestingModule({ + providers: [ + CbxHeaderService, + {provide: CbxSidebarService, useValue: sidebarService}, + {provide: Location, useValue: location}, + ] + }); + + service = TestBed.inject(CbxHeaderService); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('tracks title, visibility, and state changes and resets to defaults', () => { + service.initialize('Saga'); + service.setForceVisible(false); + service.updateState({isFullscreen: true, isSlideshowActive: true}); + + expect(service.bookTitle()).toBe('Saga'); + expect(service.forceVisible()).toBe(false); + expect(service.state()).toEqual({ + isFullscreen: true, + isSlideshowActive: true, + isMagnifierActive: false + }); + + service.reset(); + + expect(service.bookTitle()).toBe(''); + expect(service.forceVisible()).toBe(true); + expect(service.state()).toEqual({ + isFullscreen: false, + isSlideshowActive: false, + isMagnifierActive: false + }); + }); + + it('falls back to an empty title when initialized without one', () => { + service.initialize(undefined); + + expect(service.bookTitle()).toBe(''); + }); + + it('delegates sidebar opening, close navigation, and emits header actions', () => { + const quickSettingsEvents: void[] = []; + const bookmarkEvents: void[] = []; + const noteEvents: void[] = []; + const fullscreenEvents: void[] = []; + const slideshowEvents: void[] = []; + const magnifierEvents: void[] = []; + const shortcutsEvents: void[] = []; + + service.showQuickSettings$.subscribe(() => quickSettingsEvents.push(undefined)); + service.toggleBookmark$.subscribe(() => bookmarkEvents.push(undefined)); + service.openNoteDialog$.subscribe(() => noteEvents.push(undefined)); + service.toggleFullscreen$.subscribe(() => fullscreenEvents.push(undefined)); + service.toggleSlideshow$.subscribe(() => slideshowEvents.push(undefined)); + service.toggleMagnifier$.subscribe(() => magnifierEvents.push(undefined)); + service.showShortcutsHelp$.subscribe(() => shortcutsEvents.push(undefined)); + + service.openSidebar(); + service.openQuickSettings(); + service.toggleBookmark(); + service.openNoteDialog(); + service.toggleFullscreen(); + service.toggleSlideshow(); + service.toggleMagnifier(); + service.showShortcutsHelp(); + service.close(); + + expect(sidebarService.open).toHaveBeenCalledOnce(); + expect(location.back).toHaveBeenCalledOnce(); + expect(quickSettingsEvents).toHaveLength(1); + expect(bookmarkEvents).toHaveLength(1); + expect(noteEvents).toHaveLength(1); + expect(fullscreenEvents).toHaveLength(1); + expect(slideshowEvents).toHaveLength(1); + expect(magnifierEvents).toHaveLength(1); + expect(shortcutsEvents).toHaveLength(1); + }); +}); diff --git a/frontend/src/app/features/readers/cbx-reader/layout/quick-settings/cbx-quick-settings.component.spec.ts b/frontend/src/app/features/readers/cbx-reader/layout/quick-settings/cbx-quick-settings.component.spec.ts new file mode 100644 index 000000000..86ae943ef --- /dev/null +++ b/frontend/src/app/features/readers/cbx-reader/layout/quick-settings/cbx-quick-settings.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around quick-settings service signals, +// viewport-dependent getters, and the large option matrix for fit, scroll, slideshow, and +// magnifier controls so behavior can be tested without mounting the full reader shell. +describe.skip('CbxQuickSettingsComponent', () => { + it('needs state seams to verify option labeling, page-view toggles, and current-label helpers', () => { + // TODO(seam): Cover the derived option getters and toggle helpers once the quick-settings service signal graph is isolated behind test doubles. + }); + + it('needs viewport seams to verify phone-layout gating and close-overlay behavior', () => { + // TODO(seam): Cover isPhonePortrait and onOverlayClick after extracting window-size and service-close interactions behind a deterministic seam. + }); +}); diff --git a/frontend/src/app/features/readers/cbx-reader/layout/quick-settings/cbx-quick-settings.service.spec.ts b/frontend/src/app/features/readers/cbx-reader/layout/quick-settings/cbx-quick-settings.service.spec.ts new file mode 100644 index 000000000..d4dd3f811 --- /dev/null +++ b/frontend/src/app/features/readers/cbx-reader/layout/quick-settings/cbx-quick-settings.service.spec.ts @@ -0,0 +1,104 @@ +import {describe, expect, it} from 'vitest'; + +import { + CbxBackgroundColor, + CbxFitMode, + CbxMagnifierLensSize, + CbxMagnifierZoom, + CbxPageSpread, + CbxPageViewMode, + CbxReadingDirection, + CbxScrollMode, + CbxSlideshowInterval, +} from '../../../../settings/user-management/user.service'; +import {CbxQuickSettingsService} from './cbx-quick-settings.service'; + +describe('CbxQuickSettingsService', () => { + it('tracks visibility and settings state and resets cleanly', () => { + const service = new CbxQuickSettingsService(); + + service.show(); + service.setFitMode(CbxFitMode.FIT_WIDTH); + service.setScrollMode(CbxScrollMode.INFINITE); + service.setPageViewMode(CbxPageViewMode.TWO_PAGE); + service.setPageSpread(CbxPageSpread.EVEN); + service.setBackgroundColor(CbxBackgroundColor.BLACK); + service.setReadingDirection(CbxReadingDirection.RTL); + service.setSlideshowInterval(CbxSlideshowInterval.TEN_SECONDS); + service.setMagnifierZoom(CbxMagnifierZoom.ZOOM_4X); + service.setMagnifierLensSize(CbxMagnifierLensSize.EXTRA_LARGE); + + expect(service.visible()).toBe(true); + expect(service.state()).toEqual({ + fitMode: CbxFitMode.FIT_WIDTH, + scrollMode: CbxScrollMode.INFINITE, + pageViewMode: CbxPageViewMode.TWO_PAGE, + pageSpread: CbxPageSpread.EVEN, + backgroundColor: CbxBackgroundColor.BLACK, + readingDirection: CbxReadingDirection.RTL, + slideshowInterval: CbxSlideshowInterval.TEN_SECONDS, + magnifierZoom: CbxMagnifierZoom.ZOOM_4X, + magnifierLensSize: CbxMagnifierLensSize.EXTRA_LARGE + }); + + service.close(); + expect(service.visible()).toBe(false); + + service.reset(); + expect(service.visible()).toBe(false); + expect(service.state()).toEqual({ + fitMode: CbxFitMode.FIT_PAGE, + scrollMode: CbxScrollMode.PAGINATED, + pageViewMode: CbxPageViewMode.SINGLE_PAGE, + pageSpread: CbxPageSpread.ODD, + backgroundColor: CbxBackgroundColor.GRAY, + readingDirection: CbxReadingDirection.LTR, + slideshowInterval: CbxSlideshowInterval.FIVE_SECONDS, + magnifierZoom: CbxMagnifierZoom.ZOOM_3X, + magnifierLensSize: CbxMagnifierLensSize.MEDIUM + }); + }); + + it('emits all quick settings change events', () => { + const service = new CbxQuickSettingsService(); + const fitModeEvents: CbxFitMode[] = []; + const scrollModeEvents: CbxScrollMode[] = []; + const pageViewEvents: CbxPageViewMode[] = []; + const pageSpreadEvents: CbxPageSpread[] = []; + const backgroundEvents: CbxBackgroundColor[] = []; + const directionEvents: CbxReadingDirection[] = []; + const slideshowEvents: CbxSlideshowInterval[] = []; + const zoomEvents: CbxMagnifierZoom[] = []; + const lensSizeEvents: CbxMagnifierLensSize[] = []; + + service.fitModeChange$.subscribe(value => fitModeEvents.push(value)); + service.scrollModeChange$.subscribe(value => scrollModeEvents.push(value)); + service.pageViewModeChange$.subscribe(value => pageViewEvents.push(value)); + service.pageSpreadChange$.subscribe(value => pageSpreadEvents.push(value)); + service.backgroundColorChange$.subscribe(value => backgroundEvents.push(value)); + service.readingDirectionChange$.subscribe(value => directionEvents.push(value)); + service.slideshowIntervalChange$.subscribe(value => slideshowEvents.push(value)); + service.magnifierZoomChange$.subscribe(value => zoomEvents.push(value)); + service.magnifierLensSizeChange$.subscribe(value => lensSizeEvents.push(value)); + + service.emitFitModeChange(CbxFitMode.ACTUAL_SIZE); + service.emitScrollModeChange(CbxScrollMode.LONG_STRIP); + service.emitPageViewModeChange(CbxPageViewMode.TWO_PAGE); + service.emitPageSpreadChange(CbxPageSpread.EVEN); + service.emitBackgroundColorChange(CbxBackgroundColor.WHITE); + service.emitReadingDirectionChange(CbxReadingDirection.RTL); + service.emitSlideshowIntervalChange(CbxSlideshowInterval.FIFTEEN_SECONDS); + service.emitMagnifierZoomChange(CbxMagnifierZoom.ZOOM_2X); + service.emitMagnifierLensSizeChange(CbxMagnifierLensSize.LARGE); + + expect(fitModeEvents).toEqual([CbxFitMode.ACTUAL_SIZE]); + expect(scrollModeEvents).toEqual([CbxScrollMode.LONG_STRIP]); + expect(pageViewEvents).toEqual([CbxPageViewMode.TWO_PAGE]); + expect(pageSpreadEvents).toEqual([CbxPageSpread.EVEN]); + expect(backgroundEvents).toEqual([CbxBackgroundColor.WHITE]); + expect(directionEvents).toEqual([CbxReadingDirection.RTL]); + expect(slideshowEvents).toEqual([CbxSlideshowInterval.FIFTEEN_SECONDS]); + expect(zoomEvents).toEqual([CbxMagnifierZoom.ZOOM_2X]); + expect(lensSizeEvents).toEqual([CbxMagnifierLensSize.LARGE]); + }); +}); diff --git a/frontend/src/app/features/readers/cbx-reader/layout/sidebar/cbx-sidebar.component.spec.ts b/frontend/src/app/features/readers/cbx-reader/layout/sidebar/cbx-sidebar.component.spec.ts new file mode 100644 index 000000000..dbbeb9a8e --- /dev/null +++ b/frontend/src/app/features/readers/cbx-reader/layout/sidebar/cbx-sidebar.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around animation timing, signal-driven +// sidebar state, and note/bookmark editing callbacks so open/close and sidebar interaction flows +// can be asserted without the full reader shell runtime. +describe.skip('CbxSidebarComponent', () => { + it('needs animation seams to verify delayed close behavior and overlay interactions', () => { + // TODO(seam): Cover closeWithAnimation and onOverlayClick once timeout scheduling and service open-state signals are isolated behind deterministic doubles. + }); + + it('needs sidebar-service seams to verify page, bookmark, note, and search interactions', () => { + // TODO(seam): Cover navigation, delete, edit, and search delegation after the sidebar service signal graph is exposed through a stable test harness. + }); +}); diff --git a/frontend/src/app/features/readers/cbx-reader/layout/sidebar/cbx-sidebar.service.spec.ts b/frontend/src/app/features/readers/cbx-reader/layout/sidebar/cbx-sidebar.service.spec.ts new file mode 100644 index 000000000..944ddf45c --- /dev/null +++ b/frontend/src/app/features/readers/cbx-reader/layout/sidebar/cbx-sidebar.service.spec.ts @@ -0,0 +1,244 @@ +import {TestBed} from '@angular/core/testing'; +import {TranslocoService} from '@jsverse/transloco'; +import {of, Subject} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {CbxPageInfo, CbxReaderService} from '../../../../book/service/cbx-reader.service'; +import {Book} from '../../../../book/model/book.model'; +import {BookMark, BookMarkService} from '../../../../../shared/service/book-mark.service'; +import {BookNoteV2, BookNoteV2Service} from '../../../../../shared/service/book-note-v2.service'; +import {UrlHelperService} from '../../../../../shared/service/url-helper.service'; +import {CbxSidebarService} from './cbx-sidebar.service'; + +describe('CbxSidebarService', () => { + let service: CbxSidebarService; + let destroy$: Subject; + + const pageInfo: CbxPageInfo[] = [ + {pageNumber: 1, displayName: 'Page 1'}, + {pageNumber: 2, displayName: 'Page 2'}, + ]; + + const bookmarks: BookMark[] = [ + {id: 10, bookId: 7, cfi: '2', title: 'Page 2', createdAt: '2026-03-26T00:00:00Z'}, + ]; + + const notes: BookNoteV2[] = [ + {id: 20, bookId: 7, cfi: '3', noteContent: 'Highlight', chapterTitle: 'Battle', createdAt: '2026-03-26T00:00:00Z'}, + {id: 21, bookId: 7, cfi: '4', noteContent: 'Quiet scene', chapterTitle: 'Interlude', createdAt: '2026-03-26T00:00:00Z'}, + ]; + + const cbxReaderService = { + getPageInfo: vi.fn(), + }; + + const bookMarkService = { + getBookmarksForBook: vi.fn(), + createBookmark: vi.fn(), + deleteBookmark: vi.fn(), + }; + + const bookNoteV2Service = { + getNotesForBook: vi.fn(), + createNote: vi.fn(), + updateNote: vi.fn(), + deleteNote: vi.fn(), + }; + + const urlHelper = { + getThumbnailUrl: vi.fn(), + }; + + const translocoService = { + translate: vi.fn((key: string) => { + if (key === 'readerCbx.sidebar.untitled') { + return 'Untitled'; + } + if (key === 'readerCbx.sidebar.page') { + return 'Page'; + } + return key; + }), + }; + + const createBook = (overrides: Partial = {}): Book => ({ + id: 7, + libraryId: 11, + libraryName: 'Library', + fileName: 'issue.cbz', + metadata: { + bookId: 7, + title: 'Issue 7', + authors: ['Alice', 'Bob'], + coverUpdatedOn: '2026-03-26T00:00:00Z', + }, + ...overrides, + } as Book); + + beforeEach(() => { + destroy$ = new Subject(); + cbxReaderService.getPageInfo.mockReset(); + cbxReaderService.getPageInfo.mockReturnValue(of(pageInfo)); + bookMarkService.getBookmarksForBook.mockReset(); + bookMarkService.getBookmarksForBook.mockReturnValue(of(bookmarks)); + bookMarkService.createBookmark.mockReset(); + bookMarkService.createBookmark.mockReturnValue(of(bookmarks[0])); + bookMarkService.deleteBookmark.mockReset(); + bookMarkService.deleteBookmark.mockReturnValue(of(void 0)); + bookNoteV2Service.getNotesForBook.mockReset(); + bookNoteV2Service.getNotesForBook.mockReturnValue(of(notes)); + bookNoteV2Service.createNote.mockReset(); + bookNoteV2Service.createNote.mockReturnValue(of(notes[0])); + bookNoteV2Service.updateNote.mockReset(); + bookNoteV2Service.updateNote.mockReturnValue(of(notes[0])); + bookNoteV2Service.deleteNote.mockReset(); + bookNoteV2Service.deleteNote.mockReturnValue(of(void 0)); + urlHelper.getThumbnailUrl.mockReset(); + urlHelper.getThumbnailUrl.mockReturnValue('/thumb.jpg'); + translocoService.translate.mockClear(); + + TestBed.configureTestingModule({ + providers: [ + CbxSidebarService, + {provide: UrlHelperService, useValue: urlHelper}, + {provide: CbxReaderService, useValue: cbxReaderService}, + {provide: BookMarkService, useValue: bookMarkService}, + {provide: BookNoteV2Service, useValue: bookNoteV2Service}, + {provide: TranslocoService, useValue: translocoService}, + ] + }); + + service = TestBed.inject(CbxSidebarService); + }); + + afterEach(() => { + destroy$.complete(); + TestBed.resetTestingModule(); + }); + + it('initializes book info and loads pages, bookmarks, and notes', () => { + service.initialize(7, createBook(), destroy$, 'CBX'); + + expect(cbxReaderService.getPageInfo).toHaveBeenCalledWith(7, 'CBX'); + expect(bookMarkService.getBookmarksForBook).toHaveBeenCalledWith(7); + expect(bookNoteV2Service.getNotesForBook).toHaveBeenCalledWith(7); + expect(urlHelper.getThumbnailUrl).toHaveBeenCalledWith(7, '2026-03-26T00:00:00Z'); + expect(service.bookInfo()).toEqual({ + id: 7, + title: 'Issue 7', + authors: 'Alice, Bob', + coverUrl: '/thumb.jpg' + }); + expect(service.pages()).toEqual(pageInfo); + expect(service.bookmarks()).toEqual(bookmarks); + expect(service.notes()).toEqual(notes); + }); + + it('falls back to translated untitled book info when metadata is missing', () => { + service.initialize(7, createBook({metadata: undefined, fileName: undefined}), destroy$); + + expect(service.bookInfo()).toEqual({ + id: 7, + title: 'Untitled', + authors: '', + coverUrl: '/thumb.jpg' + }); + }); + + it('tracks tabs, open state, current page, and page navigation emissions', () => { + const pageEvents: number[] = []; + service.navigateToPage$.subscribe(value => pageEvents.push(value)); + + service.setCurrentPage(5); + service.setActiveTab('notes'); + service.open('bookmarks'); + service.navigateToPage(8); + + expect(service.currentPage()).toBe(5); + expect(service.activeTab()).toBe('bookmarks'); + expect(service.isOpen()).toBe(false); + expect(pageEvents).toEqual([8]); + }); + + it('supports bookmark lookups, creation, deletion, and toggle branches', () => { + service.initialize(7, createBook(), destroy$); + + expect(service.isPageBookmarked(2)).toBe(true); + expect(service.isPageBookmarked(9)).toBe(false); + expect(service.getBookmarkForPage(2)?.id).toBe(10); + + service.toggleBookmark(2); + expect(bookMarkService.deleteBookmark).toHaveBeenCalledWith(10); + + service.toggleBookmark(5); + expect(bookMarkService.createBookmark).toHaveBeenCalledWith({ + bookId: 7, + cfi: '5', + title: 'Page 5' + }); + expect(bookMarkService.getBookmarksForBook).toHaveBeenCalledTimes(3); + }); + + it('navigates to bookmarks only when the cfi parses to a page number', () => { + const pageEvents: number[] = []; + service.navigateToPage$.subscribe(value => pageEvents.push(value)); + service.open(); + + service.navigateToBookmark('4'); + service.navigateToBookmark('not-a-page'); + + expect(pageEvents).toEqual([4]); + expect(service.isOpen()).toBe(false); + }); + + it('filters notes by content or chapter title and clears the query', () => { + service.initialize(7, createBook(), destroy$); + + service.setNotesSearchQuery('battle'); + expect(service.filteredNotes()).toEqual([notes[0]]); + + service.setNotesSearchQuery('quiet'); + expect(service.filteredNotes()).toEqual([notes[1]]); + + service.setNotesSearchQuery(''); + expect(service.filteredNotes()).toEqual(notes); + }); + + it('creates, updates, edits, deletes, and navigates notes', () => { + const pageEvents: number[] = []; + const editEvents: BookNoteV2[] = []; + service.navigateToPage$.subscribe(value => pageEvents.push(value)); + service.editNote$.subscribe(value => editEvents.push(value)); + service.initialize(7, createBook(), destroy$); + + service.createNote(6, 'Remember this', '#fff000'); + expect(bookNoteV2Service.createNote).toHaveBeenCalledWith({ + bookId: 7, + cfi: '6', + noteContent: 'Remember this', + color: '#fff000', + chapterTitle: 'Page 6' + }); + + service.updateNote(20, 'Updated', '#000000'); + expect(bookNoteV2Service.updateNote).toHaveBeenCalledWith(20, { + noteContent: 'Updated', + color: '#000000' + }); + + service.open(); + service.editNote(notes[0]); + expect(editEvents).toEqual([notes[0]]); + expect(service.isOpen()).toBe(false); + + service.navigateToNote('3'); + service.navigateToNote('invalid'); + expect(pageEvents).toEqual([3]); + + service.deleteNote(20); + expect(bookNoteV2Service.deleteNote).toHaveBeenCalledWith(20); + expect(service.notes()).toEqual([notes[1]]); + expect(service.pageHasNotes(4)).toBe(true); + expect(service.pageHasNotes(20)).toBe(false); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/core/epub-streaming.service.spec.ts b/frontend/src/app/features/readers/ebook-reader/core/epub-streaming.service.spec.ts new file mode 100644 index 000000000..94360d041 --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/core/epub-streaming.service.spec.ts @@ -0,0 +1,65 @@ +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {provideHttpClient} from '@angular/common/http'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {API_CONFIG} from '../../../../core/config/api-config'; +import {AuthService} from '../../../../shared/service/auth.service'; +import {EpubStreamingService} from './epub-streaming.service'; + +describe('EpubStreamingService', () => { + let service: EpubStreamingService; + let httpTestingController: HttpTestingController; + const authService = { + getInternalAccessToken: vi.fn(() => 'internal-token'), + }; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + EpubStreamingService, + {provide: AuthService, useValue: authService}, + ] + }); + + service = TestBed.inject(EpubStreamingService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + it('returns the epub api base url and auth token', () => { + expect(service.getBaseUrl()).toBe(`${API_CONFIG.BASE_URL}/api/v1/epub`); + expect(service.getAuthToken()).toBe('internal-token'); + }); + + it('loads book info without a book type query parameter', () => { + service.getBookInfo(42).subscribe(info => { + expect(info).toEqual({containerPath: 'container', rootPath: 'root', spine: [], manifest: [], toc: {label: 'toc', href: 'toc'}, metadata: {}}); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/epub/42/info`); + expect(request.request.method).toBe('GET'); + expect(request.request.params.keys()).toEqual([]); + request.flush({containerPath: 'container', rootPath: 'root', spine: [], manifest: [], toc: {label: 'toc', href: 'toc'}, metadata: {}}); + }); + + it('loads book info with a book type query parameter', () => { + service.getBookInfo(7, 'EPUB').subscribe(info => { + expect(info.rootPath).toBe('ops'); + }); + + const request = httpTestingController.expectOne(req => + req.url === `${API_CONFIG.BASE_URL}/api/v1/epub/7/info` && + req.params.get('bookType') === 'EPUB' + ); + expect(request.request.method).toBe('GET'); + request.flush({containerPath: 'container', rootPath: 'ops', spine: [], manifest: [], toc: {label: 'toc', href: 'toc'}, metadata: {}}); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/core/event.service.spec.ts b/frontend/src/app/features/readers/ebook-reader/core/event.service.spec.ts new file mode 100644 index 000000000..0e2f78af7 --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/core/event.service.spec.ts @@ -0,0 +1,389 @@ +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {ReaderAnnotationService} from '../features/annotations/annotation-renderer.service'; +import {ReaderEventService, ViewEvent} from './event.service'; + +interface TestView extends HTMLDivElement { + addAnnotation: (annotation: {value: string}) => void; + addAnnotationSpy: (annotation: {value: string}) => void; +} + +interface RangeLike { + toString: () => string; + getBoundingClientRect: () => DOMRect; +} + +interface TestSelection { + isCollapsed: boolean; + rangeCount: number; + getRangeAt: (index: number) => RangeLike; +} + +interface PrivateReaderEventService { + longHoldTimeout: ReturnType | null; + isNavigating: boolean; + touchStartX: number; + touchStartY: number; + touchStartTime: number; + selectionChangeTimeout: ReturnType | null; + handleIframeClickMessage: (data: { + type: 'iframe-click'; + clientX: number; + clientY: number; + iframeLeft: number; + iframeWidth: number; + eventClientX: number; + target?: string; + }) => void; + processIframeClick: (data: { + type: 'iframe-click'; + clientX: number; + clientY: number; + iframeLeft: number; + iframeWidth: number; + eventClientX: number; + target?: string; + }) => void; + handleSelectionEnd: (doc: Document) => void; + handleSelectionChange: (doc: Document) => void; + handleTouchEnd: (event: TouchEvent, doc: Document) => void; +} + +describe('ReaderEventService', () => { + const getAllAnnotations = vi.fn(() => [] as {value: string}[]); + const getAnnotationStyle = vi.fn(); + const getOverlayerDrawFunction = vi.fn(() => vi.fn(() => document.createElementNS('http://www.w3.org/2000/svg', 'path'))); + const prev = vi.fn(); + const next = vi.fn(); + const getCFI = vi.fn(); + const getContents = vi.fn(); + const postMessageSpy = vi.spyOn(window, 'postMessage').mockImplementation(() => undefined); + + let service: ReaderEventService; + let privateService: PrivateReaderEventService; + let view: TestView; + let emittedEvents: ViewEvent[]; + let defaultSelection: TestSelection; + let defaultView: { + frameElement: HTMLIFrameElement; + getSelection: () => TestSelection; + }; + let doc: Document; + let iframe: HTMLIFrameElement; + + function createView(width = 600): TestView { + const element = document.createElement('div') as TestView; + element.addAnnotationSpy = vi.fn(); + element.addAnnotation = annotation => { + element.addAnnotationSpy(annotation); + }; + Object.defineProperty(element, 'getBoundingClientRect', { + value: () => new DOMRect(20, 10, width, 400), + }); + return element; + } + + function installSelection(targetDoc: Document, selection: TestSelection): void { + const currentDefaultView = targetDoc.defaultView; + if (!currentDefaultView) { + throw new Error('expected defaultView'); + } + Object.defineProperty(currentDefaultView, 'getSelection', { + value: () => selection, + configurable: true, + }); + } + + function createTouchEvent( + type: string, + changed: {clientX: number; clientY: number}[], + active: {clientX: number; clientY: number}[] = changed, + ): TouchEvent { + const event = new Event(type, {bubbles: true, cancelable: true}) as TouchEvent; + Object.defineProperty(event, 'changedTouches', {value: changed, configurable: true}); + Object.defineProperty(event, 'touches', {value: active, configurable: true}); + return event; + } + + beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-03-27T03:30:00Z')); + Reflect.deleteProperty(window, 'ontouchstart'); + Object.defineProperty(navigator, 'maxTouchPoints', { + value: 0, + configurable: true, + }); + + getAllAnnotations.mockReset(); + getAllAnnotations.mockReturnValue([]); + getAnnotationStyle.mockReset(); + getOverlayerDrawFunction.mockReset(); + getOverlayerDrawFunction.mockReturnValue(vi.fn(() => document.createElementNS('http://www.w3.org/2000/svg', 'path'))); + prev.mockReset(); + next.mockReset(); + getCFI.mockReset(); + getContents.mockReset(); + postMessageSpy.mockClear(); + + doc = document.implementation.createHTMLDocument('reader-doc'); + iframe = doc.createElement('iframe'); + Object.defineProperty(iframe, 'getBoundingClientRect', { + value: () => new DOMRect(120, 80, 500, 400), + }); + + defaultSelection = { + isCollapsed: true, + rangeCount: 0, + getRangeAt: () => ({ + toString: () => '', + getBoundingClientRect: () => new DOMRect(0, 0, 0, 0), + }), + }; + defaultView = { + frameElement: iframe, + getSelection: () => defaultSelection, + }; + Object.defineProperty(doc, 'defaultView', { + value: defaultView, + configurable: true, + }); + installSelection(doc, defaultSelection); + + TestBed.configureTestingModule({ + providers: [ + { + provide: ReaderAnnotationService, + useValue: { + getAllAnnotations, + getAnnotationStyle, + getOverlayerDrawFunction, + }, + }, + ], + }); + + service = TestBed.inject(ReaderEventService); + privateService = service as unknown as PrivateReaderEventService; + view = createView(); + emittedEvents = []; + service.events$.subscribe(event => emittedEvents.push(event)); + service.initialize(view, {prev, next, getCFI, getContents}); + }); + + afterEach(() => { + vi.useRealTimers(); + service.destroy(); + }); + + it('hydrates annotations on load and forwards load events', () => { + getAllAnnotations.mockReturnValue([{value: 'cfi-1'}, {value: 'cfi-2'}]); + + view.dispatchEvent(new CustomEvent('load', {detail: {doc}})); + vi.advanceTimersByTime(100); + + expect(view.addAnnotationSpy).toHaveBeenNthCalledWith(1, {value: 'cfi-1'}); + expect(view.addAnnotationSpy).toHaveBeenNthCalledWith(2, {value: 'cfi-2'}); + expect(emittedEvents).toContainEqual({type: 'load', detail: {doc}}); + }); + + it('navigates and emits keyboard events for reader shortcuts while ignoring editable targets', () => { + const input = document.createElement('input'); + input.dispatchEvent(new KeyboardEvent('keydown', {key: 'ArrowLeft', bubbles: true})); + expect(prev).not.toHaveBeenCalled(); + + document.dispatchEvent(new KeyboardEvent('keydown', {key: 'ArrowLeft', bubbles: true})); + document.dispatchEvent(new KeyboardEvent('keydown', {key: 'ArrowRight', bubbles: true})); + document.dispatchEvent(new KeyboardEvent('keydown', {key: ' ', shiftKey: true, bubbles: true})); + document.dispatchEvent(new KeyboardEvent('keydown', {key: ' ', bubbles: true})); + document.dispatchEvent(new KeyboardEvent('keydown', {key: 'Home', bubbles: true})); + document.dispatchEvent(new KeyboardEvent('keydown', {key: 'End', bubbles: true})); + document.dispatchEvent(new KeyboardEvent('keydown', {key: 'f', bubbles: true})); + document.dispatchEvent(new KeyboardEvent('keydown', {key: 't', bubbles: true})); + document.dispatchEvent(new KeyboardEvent('keydown', {key: 's', bubbles: true})); + document.dispatchEvent(new KeyboardEvent('keydown', {key: 'n', bubbles: true})); + document.dispatchEvent(new KeyboardEvent('keydown', {key: '?', bubbles: true})); + document.dispatchEvent(new KeyboardEvent('keydown', {key: 'Escape', bubbles: true})); + + expect(prev).toHaveBeenCalledTimes(2); + expect(next).toHaveBeenCalledTimes(2); + expect(emittedEvents.map(event => event.type)).toEqual(expect.arrayContaining([ + 'go-first-section', + 'go-last-section', + 'toggle-fullscreen', + 'toggle-toc', + 'toggle-search', + 'toggle-notes', + 'toggle-shortcuts-help', + 'escape-pressed', + ])); + }); + + it('handles iframe clicks with double-click suppression and middle tap fallback', () => { + privateService.longHoldTimeout = setTimeout(() => undefined, 1_000); + + privateService.handleIframeClickMessage({ + type: 'iframe-click', + clientX: 40, + clientY: 100, + iframeLeft: 0, + iframeWidth: 600, + eventClientX: 20, + }); + vi.advanceTimersByTime(300); + expect(prev).toHaveBeenCalledTimes(1); + + vi.setSystemTime(new Date('2026-03-27T03:30:01Z')); + privateService.handleIframeClickMessage({ + type: 'iframe-click', + clientX: 280, + clientY: 100, + iframeLeft: 0, + iframeWidth: 600, + eventClientX: 260, + }); + vi.setSystemTime(new Date('2026-03-27T03:30:01.100Z')); + privateService.handleIframeClickMessage({ + type: 'iframe-click', + clientX: 285, + clientY: 100, + iframeLeft: 0, + iframeWidth: 600, + eventClientX: 265, + }); + vi.advanceTimersByTime(300); + + expect(emittedEvents.filter(event => event.type === 'middle-single-tap')).toHaveLength(1); + + vi.setSystemTime(new Date('2026-03-27T03:30:02Z')); + privateService.handleIframeClickMessage({ + type: 'iframe-click', + clientX: 300, + clientY: 100, + iframeLeft: 0, + iframeWidth: 600, + eventClientX: 280, + target: 'SPAN', + }); + vi.advanceTimersByTime(300); + + expect(emittedEvents.filter(event => event.type === 'middle-single-tap')).toHaveLength(2); + expect(emittedEvents.at(-1)?.type).toBe('middle-single-tap'); + }); + + it('processes touch gestures for swipe navigation, short taps, and selected text', () => { + privateService.longHoldTimeout = setTimeout(() => undefined, 1_000); + privateService.touchStartX = 150; + privateService.touchStartY = 120; + privateService.touchStartTime = Date.now() - 100; + + const swipeLeft = createTouchEvent('touchend', [{clientX: 60, clientY: 120}]); + privateService.handleTouchEnd(swipeLeft, doc); + expect(next).toHaveBeenCalledTimes(1); + + privateService.isNavigating = false; + privateService.touchStartX = 120; + privateService.touchStartY = 90; + privateService.touchStartTime = Date.now() - 100; + + const tap = createTouchEvent('touchend', [{clientX: 122, clientY: 92}]); + privateService.handleTouchEnd(tap, doc); + expect(postMessageSpy).toHaveBeenCalledWith(expect.objectContaining({ + type: 'iframe-click', + target: undefined, + }), '*'); + + const selectedRange: RangeLike = { + toString: () => 'Highlighted text', + getBoundingClientRect: () => new DOMRect(20, 15, 80, 20), + }; + installSelection(doc, { + isCollapsed: false, + rangeCount: 1, + getRangeAt: () => selectedRange, + }); + getContents.mockReturnValue([{index: 7, doc}]); + getCFI.mockReturnValue('epubcfi(/6/2!/4/2:0)'); + + const selectedTouch = createTouchEvent('touchend', [{clientX: 140, clientY: 120}]); + privateService.handleTouchEnd(selectedTouch, doc); + vi.advanceTimersByTime(50); + vi.advanceTimersByTime(10); + + expect(emittedEvents.at(-1)).toMatchObject({ + type: 'text-selected', + detail: { + text: 'Highlighted text', + cfi: 'epubcfi(/6/2!/4/2:0)', + index: 7, + }, + }); + }); + + it('debounces selection changes and only emits when selection text and CFI are available', () => { + const emptyRange: RangeLike = { + toString: () => ' ', + getBoundingClientRect: () => new DOMRect(0, 0, 0, 0), + }; + installSelection(doc, { + isCollapsed: false, + rangeCount: 1, + getRangeAt: () => emptyRange, + }); + + privateService.handleSelectionChange(doc); + vi.advanceTimersByTime(300); + expect(emittedEvents).toHaveLength(0); + + const visibleRange: RangeLike = { + toString: () => 'Visible note', + getBoundingClientRect: () => new DOMRect(10, 10, 60, 25), + }; + installSelection(doc, { + isCollapsed: false, + rangeCount: 1, + getRangeAt: () => visibleRange, + }); + getContents.mockReturnValue([{index: 3, doc}]); + getCFI.mockReturnValueOnce(null).mockReturnValueOnce('epubcfi(/6/8!/4/2:0)'); + + privateService.handleSelectionEnd(doc); + vi.advanceTimersByTime(10); + expect(emittedEvents).toHaveLength(0); + + privateService.handleSelectionEnd(doc); + vi.advanceTimersByTime(10); + expect(emittedEvents.at(-1)).toMatchObject({ + type: 'text-selected', + detail: { + text: 'Visible note', + cfi: 'epubcfi(/6/8!/4/2:0)', + index: 3, + }, + popupPosition: { + showBelow: true, + }, + }); + }); + + it('styles draw-annotation events when a stored annotation style exists', () => { + const draw = vi.fn(); + const overlayer = vi.fn(() => document.createElementNS('http://www.w3.org/2000/svg', 'rect')); + + getAnnotationStyle.mockReturnValue({color: '#0f0', style: 'highlight'}); + getOverlayerDrawFunction.mockReturnValue(overlayer); + + view.dispatchEvent(new CustomEvent('draw-annotation', { + detail: { + draw, + annotation: {value: 'epubcfi(/6/2!/4/2:0)'}, + doc, + range: document.createRange(), + }, + })); + + expect(getAnnotationStyle).toHaveBeenCalledWith('epubcfi(/6/2!/4/2:0)'); + expect(draw).toHaveBeenCalledWith(overlayer, {color: '#0f0'}); + expect(emittedEvents.at(-1)?.type).toBe('draw-annotation'); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/core/loader.service.spec.ts b/frontend/src/app/features/readers/ebook-reader/core/loader.service.spec.ts new file mode 100644 index 000000000..00a45891a --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/core/loader.service.spec.ts @@ -0,0 +1,70 @@ +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {firstValueFrom} from 'rxjs'; + +import {ReaderLoaderService} from './loader.service'; + +describe('ReaderLoaderService', () => { + let service: ReaderLoaderService; + + beforeEach(() => { + service = new ReaderLoaderService(); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it('returns immediately when the custom element already exists', async () => { + const getSpy = vi.spyOn(customElements, 'get').mockReturnValue(class FoliateView extends HTMLElement {}); + const appendSpy = vi.spyOn(document.head, 'appendChild'); + + await expect(firstValueFrom(service.loadFoliateScript())).resolves.toBeUndefined(); + + expect(getSpy).toHaveBeenCalledWith('foliate-view'); + expect(appendSpy).not.toHaveBeenCalled(); + }); + + it('loads the foliate script once and waits for the delayed completion', async () => { + vi.useFakeTimers(); + vi.spyOn(customElements, 'get').mockReturnValue(undefined); + const appendSpy = vi.spyOn(document.head, 'appendChild'); + + const loadPromise = firstValueFrom(service.loadFoliateScript()); + const script = appendSpy.mock.calls[0]?.[0] as HTMLScriptElement; + + expect(script).toBeDefined(); + expect(script.type).toBe('module'); + expect(script.src).toContain('/assets/foliate/view.js'); + + script.onload?.(new Event('load') as never); + await vi.advanceTimersByTimeAsync(100); + + await expect(loadPromise).resolves.toBeUndefined(); + + appendSpy.mockClear(); + await expect(firstValueFrom(service.loadFoliateScript())).resolves.toBeUndefined(); + expect(appendSpy).not.toHaveBeenCalled(); + }); + + it('surfaces script loading failures', async () => { + vi.useFakeTimers(); + vi.spyOn(customElements, 'get').mockReturnValue(undefined); + const appendSpy = vi.spyOn(document.head, 'appendChild'); + + const loadPromise = firstValueFrom(service.loadFoliateScript()); + const script = appendSpy.mock.calls[0]?.[0] as HTMLScriptElement; + + script.onerror?.(new Event('error') as never); + + await expect(loadPromise).rejects.toThrow('Failed to load foliate.js'); + }); + + it('waits for the custom element definition', async () => { + const whenDefinedSpy = vi.spyOn(customElements, 'whenDefined').mockResolvedValue(class FoliateView extends HTMLElement {}); + + await expect(firstValueFrom(service.waitForCustomElement())).resolves.toBeUndefined(); + + expect(whenDefinedSpy).toHaveBeenCalledWith('foliate-view'); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/core/style.service.spec.ts b/frontend/src/app/features/readers/ebook-reader/core/style.service.spec.ts new file mode 100644 index 000000000..c325f83f7 --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/core/style.service.spec.ts @@ -0,0 +1,148 @@ +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {themes} from '../state/themes.constant'; +import {EpubCustomFontService} from '../features/fonts/custom-font.service'; +import {ReaderStyleService} from './style.service'; + +describe('ReaderStyleService', () => { + const epubCustomFontService = { + getCustomFontById: vi.fn(), + getBlobUrl: vi.fn(), + sanitizeFontName: vi.fn(), + }; + + let service: ReaderStyleService; + + beforeEach(() => { + epubCustomFontService.getCustomFontById.mockReset(); + epubCustomFontService.getBlobUrl.mockReset(); + epubCustomFontService.sanitizeFontName.mockReset(); + epubCustomFontService.sanitizeFontName.mockImplementation((fontName: string) => fontName.replace(/\W+/g, '-')); + + TestBed.configureTestingModule({ + providers: [ + ReaderStyleService, + {provide: EpubCustomFontService, useValue: epubCustomFontService}, + ] + }); + + service = TestBed.inject(ReaderStyleService); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('generates custom font css when a cached custom font is selected', () => { + epubCustomFontService.getCustomFontById.mockReturnValue({fontName: 'Fancy Serif.otf'}); + epubCustomFontService.getBlobUrl.mockReturnValue('blob:fancy-serif'); + + const css = service.generateCSS({ + lineHeight: 1.6, + justify: false, + hyphenate: true, + maxColumnCount: 2, + gap: 0.05, + fontSize: 18, + theme: {...themes[0], fg: themes[0].dark.fg, bg: themes[0].dark.bg, link: themes[0].dark.link}, + maxInlineSize: 720, + maxBlockSize: 1440, + fontFamily: 'custom:7', + isDark: true, + flow: 'paginated', + }); + + expect(epubCustomFontService.getCustomFontById).toHaveBeenCalledWith(7); + expect(epubCustomFontService.getBlobUrl).toHaveBeenCalledWith(7); + expect(css).toContain('@font-face'); + expect(css).toContain('font-family: "Fancy-Serif-otf", sans-serif !important;'); + expect(css).toContain('font-size: 18px;'); + expect(css).toContain('text-align: start !important;'); + expect(css).toContain('hyphens: auto;'); + }); + + it('falls back to plain font families when the font value is not a cached custom font', () => { + const css = service.generateCSS({ + lineHeight: 1.4, + justify: true, + hyphenate: false, + maxColumnCount: 2, + gap: 0.05, + fontSize: 16, + theme: {...themes[1], fg: themes[1].light.fg, bg: themes[1].light.bg, link: themes[1].light.link}, + maxInlineSize: 720, + maxBlockSize: 1440, + fontFamily: 'serif', + isDark: false, + flow: 'scrolled', + }); + + expect(epubCustomFontService.getCustomFontById).not.toHaveBeenCalled(); + expect(css).not.toContain('@font-face'); + expect(css).toContain('font-family: serif !important;'); + expect(css).toContain('text-align: justify !important;'); + expect(css).toContain('hyphens: none;'); + }); + + it('applies renderer attributes and paginated margins only when a renderer exists', () => { + const renderer = { + setAttribute: vi.fn(), + removeAttribute: vi.fn(), + setStyles: vi.fn(), + }; + + service.applyStylesToRenderer(renderer, { + lineHeight: 1.5, + justify: true, + hyphenate: true, + maxColumnCount: 3, + gap: 0.2, + fontSize: 20, + theme: {...themes[0], fg: themes[0].dark.fg, bg: themes[0].dark.bg, link: themes[0].dark.link}, + maxInlineSize: 800, + maxBlockSize: 1500, + fontFamily: null, + isDark: true, + flow: 'paginated', + }); + + expect(renderer.setAttribute).toHaveBeenCalledWith('max-column-count', 3); + expect(renderer.setAttribute).toHaveBeenCalledWith('gap', '20%'); + expect(renderer.setAttribute).toHaveBeenCalledWith('max-inline-size', '800px'); + expect(renderer.setAttribute).toHaveBeenCalledWith('max-block-size', '1500px'); + expect(renderer.setAttribute).toHaveBeenCalledWith('margin', '40px'); + expect(renderer.setStyles).toHaveBeenCalledOnce(); + + service.applyStylesToRenderer(renderer, { + lineHeight: 1.5, + justify: true, + hyphenate: true, + maxColumnCount: 3, + gap: 0.2, + fontSize: 20, + theme: {...themes[0], fg: themes[0].dark.fg, bg: themes[0].dark.bg, link: themes[0].dark.link}, + maxInlineSize: 800, + maxBlockSize: 1500, + fontFamily: null, + isDark: true, + flow: 'scrolled', + }); + + expect(renderer.removeAttribute).toHaveBeenCalledWith('margin'); + expect(() => service.applyStylesToRenderer(null, { + lineHeight: 1.5, + justify: true, + hyphenate: true, + maxColumnCount: 3, + gap: 0.2, + fontSize: 20, + theme: {...themes[0], fg: themes[0].dark.fg, bg: themes[0].dark.bg, link: themes[0].dark.link}, + maxInlineSize: 800, + maxBlockSize: 1500, + fontFamily: null, + isDark: true, + flow: 'scrolled', + })).not.toThrow(); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/core/view-manager.service.spec.ts b/frontend/src/app/features/readers/ebook-reader/core/view-manager.service.spec.ts new file mode 100644 index 000000000..646d9e34e --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/core/view-manager.service.spec.ts @@ -0,0 +1,9 @@ +import {describe, expect, it} from 'vitest'; + +// TODO(seam): The view manager requires a real Foliate custom element, DOM selection APIs, +// and streaming book factory hooks to cover its navigation and annotation branches honestly. +describe.skip('ReaderViewManagerService', () => { + it('needs a DOM and foliate harness for view creation, navigation, and streaming flows', () => { + expect.hasAssertions(); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/dialogs/metadata-dialog.component.spec.ts b/frontend/src/app/features/readers/ebook-reader/dialogs/metadata-dialog.component.spec.ts new file mode 100644 index 000000000..38245a55d --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/dialogs/metadata-dialog.component.spec.ts @@ -0,0 +1,60 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {getTranslocoModule} from '../../../../core/testing/transloco-testing'; +import {UrlHelperService} from '../../../../shared/service/url-helper.service'; +import {ReaderBookMetadataDialogComponent} from './metadata-dialog.component'; + +describe('ReaderBookMetadataDialogComponent', () => { + let fixture: ComponentFixture; + let component: ReaderBookMetadataDialogComponent; + let urlHelperService: {getCoverUrl: ReturnType}; + + beforeEach(async () => { + urlHelperService = { + getCoverUrl: vi.fn(() => '/covers/12?v=1'), + }; + + await TestBed.configureTestingModule({ + imports: [ReaderBookMetadataDialogComponent, getTranslocoModule()], + providers: [{provide: UrlHelperService, useValue: urlHelperService}], + }).compileComponents(); + + fixture = TestBed.createComponent(ReaderBookMetadataDialogComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + it('exposes metadata and builds a cover url when a book id is available', () => { + component.book = { + id: 12, + metadata: { + title: 'Atlas', + coverUpdatedOn: '2024-01-02', + }, + } as never; + + expect(component.metadata?.title).toBe('Atlas'); + expect(component.bookCoverUrl).toBe('/covers/12?v=1'); + expect(urlHelperService.getCoverUrl).toHaveBeenCalledWith(12, '2024-01-02'); + }); + + it('formats missing and present metadata fields safely', () => { + expect(component.formatAuthors(undefined)).toBeTruthy(); + expect(component.formatAuthors(['One', 'Two'])).toBe('One, Two'); + expect(component.formatFileSize(undefined)).toBeTruthy(); + expect(component.formatFileSize(512)).toBe('512.0 KB'); + expect(component.formatFileSize(2048)).toBe('2.00 MB'); + expect(component.formatDate(undefined)).toBeTruthy(); + expect(component.formatDate('2024-06-15')).toContain('2024'); + }); + + it('returns the raw date when parsing falls back after an invalid date string', () => { + expect(component.formatDate('not-a-date')).toBe('Invalid Date'); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/dialogs/note-dialog.component.spec.ts b/frontend/src/app/features/readers/ebook-reader/dialogs/note-dialog.component.spec.ts new file mode 100644 index 000000000..3531bd1b5 --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/dialogs/note-dialog.component.spec.ts @@ -0,0 +1,71 @@ +import {SimpleChange} from '@angular/core'; +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {getTranslocoModule} from '../../../../core/testing/transloco-testing'; +import {ReaderNoteDialogComponent} from './note-dialog.component'; + +describe('ReaderNoteDialogComponent', () => { + let fixture: ComponentFixture; + let component: ReaderNoteDialogComponent; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [ReaderNoteDialogComponent, getTranslocoModule()], + }).compileComponents(); + + fixture = TestBed.createComponent(ReaderNoteDialogComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + it('hydrates note state from incoming data and exposes edit mode', () => { + component.data = { + cfi: 'epubcfi(/6/2)', + noteId: 7, + noteContent: 'Draft note', + color: '#4CAF50', + }; + + component.ngOnChanges({ + data: new SimpleChange(null, component.data, false), + }); + + expect(component.isEditing).toBe(true); + expect(component.noteContent).toBe('Draft note'); + expect(component.selectedColor).toBe('#4CAF50'); + }); + + it('emits trimmed save payloads and updates the selected color', () => { + const savedSpy = vi.fn(); + component.saved.subscribe(savedSpy); + component.noteContent = ' keep this quote '; + + component.selectColor('#9C27B0'); + component.onSave(); + + expect(savedSpy).toHaveBeenCalledWith({ + noteContent: 'keep this quote', + color: '#9C27B0', + }); + }); + + it('ignores blank saves and emits cancellation when asked', () => { + const savedSpy = vi.fn(); + const cancelSpy = vi.fn(); + component.saved.subscribe(savedSpy); + component.cancelled.subscribe(cancelSpy); + + component.noteContent = ' '; + component.onSave(); + component.onCancel(); + + expect(savedSpy).not.toHaveBeenCalled(); + expect(cancelSpy).toHaveBeenCalledOnce(); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/dialogs/settings-dialog.component.spec.ts b/frontend/src/app/features/readers/ebook-reader/dialogs/settings-dialog.component.spec.ts new file mode 100644 index 000000000..1ce0142f8 --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/dialogs/settings-dialog.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around reader-state signals, view-manager +// renderer integration, localStorage persistence, and backend sync calls so reader settings can +// be asserted without the full ebook runtime. +describe.skip('ReaderSettingsDialogComponent', () => { + it('needs reader-state seams to verify typography, layout, and theme updates', () => { + // TODO(seam): Cover the update and toggle handlers once ReaderStateService and BookService can be driven through deterministic doubles. + }); + + it('needs browser seams to verify annotation-color persistence and flow changes', () => { + // TODO(seam): Cover localStorage-backed annotation color and renderer flow changes after browser globals and renderer access are isolated for testing. + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/dialogs/shortcuts-help.component.spec.ts b/frontend/src/app/features/readers/ebook-reader/dialogs/shortcuts-help.component.spec.ts new file mode 100644 index 000000000..302fae1a4 --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/dialogs/shortcuts-help.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around the translated shortcut collection, +// duplicate-key template tracking, and responsive overlay behavior so the ebook shortcuts dialog +// can be tested without depending on the current template structure. +describe.skip('EbookShortcutsHelpComponent', () => { + it('needs template seams to verify translated shortcut grouping and mobile gesture labeling without tripping duplicate-key rendering issues', () => { + // TODO(seam): Cover shortcutGroups once the template tracking strategy is isolated or corrected for deterministic unit assertions. + }); + + it('needs overlay seams to verify close emission and background-click behavior without mounting the full dialog shell', () => { + // TODO(seam): Cover onClose and onOverlayClick after extracting the current overlay template interactions behind a test seam. + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/ebook-reader.component.spec.ts b/frontend/src/app/features/readers/ebook-reader/ebook-reader.component.spec.ts new file mode 100644 index 000000000..5d8a85be7 --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/ebook-reader.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around the Foliate custom element runtime, +// DOM container bootstrapping, route-derived file loading, and the large injected reader service +// graph so the ebook reader can be tested without a browser-backed integration harness. +describe.skip('EbookReaderComponent', () => { + it('needs loader seams to verify Foliate initialization, font loading, and view setup failure handling', () => { + // TODO(seam): Cover ngOnInit and setupView once the DOM container and custom element runtime are wrapped behind adapters. + }); + + it('needs orchestration seams to verify route-based book loading, selection and note flows, and destroy-time cleanup', () => { + // TODO(seam): Cover loadBookFromAPI and ngOnDestroy after extracting the reader service graph and URL object lifecycle behind test seams. + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/features/annotations/annotation-renderer.service.spec.ts b/frontend/src/app/features/readers/ebook-reader/features/annotations/annotation-renderer.service.spec.ts new file mode 100644 index 000000000..1959f745e --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/features/annotations/annotation-renderer.service.spec.ts @@ -0,0 +1,207 @@ +import {firstValueFrom} from 'rxjs'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; + +import {AnnotationStyle} from '../../../../../shared/service/annotation.service'; +import {Annotation, ReaderAnnotationService} from './annotation-renderer.service'; + +describe('ReaderAnnotationService', () => { + let service: ReaderAnnotationService; + + const asRectList = ( + rects: { left: number; top?: number; bottom?: number; width: number; height?: number }[] + ): DOMRectList => rects as unknown as DOMRectList; + + beforeEach(() => { + service = new ReaderAnnotationService(); + }); + + it('adds annotations lazily and replaces existing entries without duplication', async () => { + const view = { + addAnnotation: vi.fn().mockResolvedValue({index: 4, label: 'Annotation 4'}), + deleteAnnotation: vi.fn().mockResolvedValue(undefined), + showAnnotation: vi.fn().mockResolvedValue(undefined), + }; + + const initialAnnotation: Annotation = {value: 'epubcfi(/6/2[first]!/4/1:0)'}; + const observable = service.addAnnotation(view, initialAnnotation); + + expect(view.addAnnotation).not.toHaveBeenCalled(); + + await expect(firstValueFrom(observable)).resolves.toEqual({index: 4, label: 'Annotation 4'}); + expect(view.addAnnotation).toHaveBeenCalledWith({value: initialAnnotation.value}); + expect(service.getAnnotationStyle(initialAnnotation.value)).toEqual({ + color: '#FACC15', + style: 'highlight', + }); + expect(service.getAllAnnotations()).toEqual([initialAnnotation]); + + const updatedAnnotation: Annotation = { + value: initialAnnotation.value, + color: '#2563eb', + style: 'underline', + }; + + await firstValueFrom(service.addAnnotation(view, updatedAnnotation)); + + expect(service.getAnnotationStyle(initialAnnotation.value)).toEqual({ + color: '#2563eb', + style: 'underline', + }); + expect(service.getAllAnnotations()).toEqual([updatedAnnotation]); + }); + + it('returns undefined and leaves caches untouched when addAnnotation has no view', async () => { + const annotation: Annotation = { + value: 'epubcfi(/6/4!/2/4:10)', + color: '#f97316', + style: 'strikethrough', + }; + + await expect(firstValueFrom(service.addAnnotation(undefined, annotation))).resolves.toBeUndefined(); + + expect(service.getAnnotationStyle(annotation.value)).toBeUndefined(); + expect(service.getAllAnnotations()).toEqual([]); + }); + + it('deletes annotations only when a view exists and showAnnotation stays lazy', async () => { + service.addAnnotations(undefined, [{ + value: 'epubcfi(/6/8!/4/2:0)', + color: '#16a34a', + style: 'squiggly', + }]); + + await expect(firstValueFrom(service.deleteAnnotation(undefined, 'epubcfi(/6/8!/4/2:0)'))).resolves.toBeUndefined(); + expect(service.getAnnotationStyle('epubcfi(/6/8!/4/2:0)')).toEqual({ + color: '#16a34a', + style: 'squiggly', + }); + + const view = { + addAnnotation: vi.fn().mockResolvedValue(undefined), + deleteAnnotation: vi.fn().mockResolvedValue(undefined), + showAnnotation: vi.fn().mockResolvedValue(undefined), + }; + + const show$ = service.showAnnotation(view, 'epubcfi(/6/8!/4/2:0)'); + expect(view.showAnnotation).not.toHaveBeenCalled(); + + await firstValueFrom(show$); + expect(view.showAnnotation).toHaveBeenCalledWith({value: 'epubcfi(/6/8!/4/2:0)'}); + + await firstValueFrom(service.deleteAnnotation(view, 'epubcfi(/6/8!/4/2:0)')); + expect(view.deleteAnnotation).toHaveBeenCalledWith({value: 'epubcfi(/6/8!/4/2:0)'}); + expect(service.getAnnotationStyle('epubcfi(/6/8!/4/2:0)')).toBeUndefined(); + expect(service.getAllAnnotations()).toEqual([]); + }); + + it('adds batches with default styles, replaces duplicates, and tolerates missing views', () => { + const view = { + addAnnotation: vi.fn(), + deleteAnnotation: vi.fn().mockResolvedValue(undefined), + showAnnotation: vi.fn().mockResolvedValue(undefined), + }; + + service.addAnnotations(view, [ + {value: 'epubcfi(/6/2!/4/2:0)'}, + {value: 'epubcfi(/6/2!/4/4:0)', color: '#dc2626', style: 'underline'}, + ]); + + service.addAnnotations(undefined, [ + {value: 'epubcfi(/6/2!/4/2:0)', color: '#0891b2', style: 'strikethrough'}, + ]); + + expect(view.addAnnotation).toHaveBeenNthCalledWith(1, {value: 'epubcfi(/6/2!/4/2:0)'}); + expect(view.addAnnotation).toHaveBeenNthCalledWith(2, {value: 'epubcfi(/6/2!/4/4:0)'}); + expect(service.getAnnotationStyle('epubcfi(/6/2!/4/2:0)')).toEqual({ + color: '#0891b2', + style: 'strikethrough', + }); + expect(service.getAnnotationStyle('epubcfi(/6/2!/4/4:0)')).toEqual({ + color: '#dc2626', + style: 'underline', + }); + expect(service.getAllAnnotations()).toEqual([ + {value: 'epubcfi(/6/2!/4/2:0)', color: '#0891b2', style: 'strikethrough'}, + {value: 'epubcfi(/6/2!/4/4:0)', color: '#dc2626', style: 'underline'}, + ]); + }); + + it('builds underline and strikethrough overlay groups with expected geometry', () => { + const underline = service.getOverlayerDrawFunction('underline') as unknown as ( + rects: DOMRectList, + options: {color?: string; width?: number} + ) => SVGElement; + const underlineGroup = underline(asRectList([{left: 10, bottom: 24, width: 80}]), { + color: '#1d4ed8', + width: 3, + }); + + expect(underlineGroup.nodeName).toBe('g'); + expect(underlineGroup.getAttribute('fill')).toBe('#1d4ed8'); + expect(underlineGroup.children).toHaveLength(1); + expect(underlineGroup.children[0].getAttribute('x')).toBe('10'); + expect(underlineGroup.children[0].getAttribute('y')).toBe('21'); + expect(underlineGroup.children[0].getAttribute('height')).toBe('3'); + expect(underlineGroup.children[0].getAttribute('width')).toBe('80'); + + const strike = service.getOverlayerDrawFunction('strikethrough') as unknown as ( + rects: DOMRectList, + options: {color?: string; width?: number} + ) => SVGElement; + const strikeGroup = strike(asRectList([{left: 6, top: 12, bottom: 20, width: 44}]), { + color: '#dc2626', + width: 4, + }); + + expect(strikeGroup.getAttribute('fill')).toBe('#dc2626'); + expect(strikeGroup.children).toHaveLength(1); + expect(strikeGroup.children[0].getAttribute('y')).toBe('16'); + expect(strikeGroup.children[0].getAttribute('height')).toBe('4'); + }); + + it('builds squiggly and highlight overlay groups with defaults and fallback styles', () => { + const squiggly = service.getOverlayerDrawFunction('squiggly') as unknown as ( + rects: DOMRectList, + options: {color?: string; width?: number} + ) => SVGElement; + const squigglyGroup = squiggly(asRectList([{left: 1, bottom: 8, width: 18}]), { + color: '#7c3aed', + width: 3, + }); + + expect(squigglyGroup.getAttribute('fill')).toBe('none'); + expect(squigglyGroup.getAttribute('stroke')).toBe('#7c3aed'); + expect(squigglyGroup.getAttribute('stroke-width')).toBe('3'); + expect(squigglyGroup.children).toHaveLength(1); + expect(squigglyGroup.children[0].getAttribute('d')).toBe('M1 8l6 -4.5l6 4.5l6 -4.5'); + + const highlight = service.getOverlayerDrawFunction('highlight'); + const highlightGroup = highlight(asRectList([{left: 4, top: 5, width: 30, height: 12}]), { + color: '#fde047', + }); + + expect(highlightGroup.getAttribute('fill')).toBe('#fde047'); + expect(highlightGroup.style.opacity).toBe('var(--overlayer-highlight-opacity, .3)'); + expect(highlightGroup.style.mixBlendMode).toBe('var(--overlayer-highlight-blend-mode, multiply)'); + expect(highlightGroup.children[0].getAttribute('x')).toBe('4'); + expect(highlightGroup.children[0].getAttribute('height')).toBe('12'); + + const fallback = service.getOverlayerDrawFunction('unsupported' as AnnotationStyle); + const fallbackGroup = fallback(asRectList([{left: 2, top: 3, width: 9, height: 6}]), {}); + + expect(fallbackGroup.getAttribute('fill')).toBe('yellow'); + }); + + it('resets all cached annotations and styles', () => { + service.addAnnotations(undefined, [ + {value: 'epubcfi(/6/10!/4/2:0)', color: '#22c55e', style: 'highlight'}, + {value: 'epubcfi(/6/10!/4/6:0)', color: '#f59e0b', style: 'underline'}, + ]); + + service.resetAnnotations(); + + expect(service.getAllAnnotations()).toEqual([]); + expect(service.getAnnotationStyle('epubcfi(/6/10!/4/2:0)')).toBeUndefined(); + expect(service.getAnnotationStyle('epubcfi(/6/10!/4/6:0)')).toBeUndefined(); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/features/annotations/annotation.service.spec.ts b/frontend/src/app/features/readers/ebook-reader/features/annotations/annotation.service.spec.ts new file mode 100644 index 000000000..e97ddf544 --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/features/annotations/annotation.service.spec.ts @@ -0,0 +1,147 @@ +import {TestBed} from '@angular/core/testing'; +import {firstValueFrom, of, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {TranslocoService} from '@jsverse/transloco'; +import {MessageService} from 'primeng/api'; + +import {AnnotationService} from '../../../../../shared/service/annotation.service'; +import {ReaderAnnotationService} from './annotation-renderer.service'; +import {ReaderAnnotationHttpService} from './annotation.service'; + +describe('ReaderAnnotationHttpService', () => { + let service: ReaderAnnotationHttpService; + let annotationService: { + createAnnotation: ReturnType; + getAnnotationsForBook: ReturnType; + deleteAnnotation: ReturnType; + updateAnnotation: ReturnType; + }; + let messageService: {add: ReturnType}; + let readerAnnotationService: {resetAnnotations: ReturnType}; + + beforeEach(() => { + annotationService = { + createAnnotation: vi.fn(), + getAnnotationsForBook: vi.fn(), + deleteAnnotation: vi.fn(), + updateAnnotation: vi.fn(), + }; + messageService = {add: vi.fn()}; + readerAnnotationService = {resetAnnotations: vi.fn()}; + + TestBed.configureTestingModule({ + providers: [ + ReaderAnnotationHttpService, + {provide: AnnotationService, useValue: annotationService}, + {provide: MessageService, useValue: messageService}, + {provide: ReaderAnnotationService, useValue: readerAnnotationService}, + {provide: TranslocoService, useValue: {translate: (key: string) => key}}, + ], + }); + + service = TestBed.inject(ReaderAnnotationHttpService); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('creates annotations with the current chapter title', async () => { + const createdAnnotation = { + id: 4, + bookId: 8, + cfi: 'epubcfi(/6/2)', + text: 'Highlighted text', + color: '#FACC15', + style: 'highlight' as const, + createdAt: '2026-03-26T00:00:00Z', + }; + annotationService.createAnnotation.mockReturnValue(of(createdAnnotation)); + service.updateCurrentChapter('Chapter One'); + + const result = await firstValueFrom(service.createAnnotation(8, 'epubcfi(/6/2)', 'Highlighted text')); + + expect(result).toEqual(createdAnnotation); + expect(annotationService.createAnnotation).toHaveBeenCalledWith( + expect.objectContaining({ + bookId: 8, + cfi: 'epubcfi(/6/2)', + text: 'Highlighted text', + chapterTitle: 'Chapter One', + }) + ); + expect(messageService.add).toHaveBeenCalledWith( + expect.objectContaining({severity: 'success'}) + ); + }); + + it('returns null and warns when the backend reports a duplicate annotation', async () => { + annotationService.createAnnotation.mockReturnValue( + throwError(() => ({status: 409})) + ); + + const result = await firstValueFrom(service.createAnnotation(3, 'cfi', 'text')); + + expect(result).toBeNull(); + expect(messageService.add).toHaveBeenCalledWith( + expect.objectContaining({severity: 'warn'}) + ); + }); + + it('falls back to an empty annotation list on load errors', async () => { + annotationService.getAnnotationsForBook.mockReturnValue( + throwError(() => new Error('load failed')) + ); + + const result = await firstValueFrom(service.getAnnotations(42)); + + expect(result).toEqual([]); + }); + + it('returns true and shows a success toast after deleting an annotation', async () => { + annotationService.deleteAnnotation.mockReturnValue(of(undefined)); + + const result = await firstValueFrom(service.deleteAnnotation(11)); + + expect(result).toBe(true); + expect(messageService.add).toHaveBeenCalledWith( + expect.objectContaining({severity: 'success'}) + ); + }); + + it('returns null when note updates fail', async () => { + annotationService.updateAnnotation.mockReturnValue( + throwError(() => new Error('update failed')) + ); + + const result = await firstValueFrom(service.updateAnnotationNote(9, 'new note')); + + expect(result).toBeNull(); + expect(messageService.add).toHaveBeenCalledWith( + expect.objectContaining({severity: 'error'}) + ); + }); + + it('clears the tracked chapter when reset is called', async () => { + const createdAnnotation = { + id: 5, + bookId: 12, + cfi: 'epubcfi(/6/4)', + text: 'Reset text', + color: '#FACC15', + style: 'highlight' as const, + createdAt: '2026-03-26T00:00:00Z', + }; + annotationService.createAnnotation.mockReturnValue(of(createdAnnotation)); + service.updateCurrentChapter('Old Chapter'); + service.reset(); + + await firstValueFrom(service.createAnnotation(12, 'epubcfi(/6/4)', 'Reset text')); + + expect(readerAnnotationService.resetAnnotations).toHaveBeenCalled(); + expect(annotationService.createAnnotation).toHaveBeenCalledWith( + expect.not.objectContaining({chapterTitle: 'Old Chapter'}) + ); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/features/bookmarks/bookmark.service.spec.ts b/frontend/src/app/features/readers/ebook-reader/features/bookmarks/bookmark.service.spec.ts new file mode 100644 index 000000000..32a55f33d --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/features/bookmarks/bookmark.service.spec.ts @@ -0,0 +1,109 @@ +import {TestBed} from '@angular/core/testing'; +import {TranslocoService} from '@jsverse/transloco'; +import {MessageService} from 'primeng/api'; +import {firstValueFrom, of, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {BookMarkService} from '../../../../../shared/service/book-mark.service'; +import {ReaderBookmarkService} from './bookmark.service'; + +describe('ReaderBookmarkService', () => { + let service: ReaderBookmarkService; + const bookMarkService = { + createBookmark: vi.fn(), + }; + const messageService = { + add: vi.fn(), + }; + const translocoService = { + translate: vi.fn((key: string) => key), + }; + + beforeEach(() => { + bookMarkService.createBookmark.mockReset(); + messageService.add.mockReset(); + translocoService.translate.mockClear(); + + TestBed.configureTestingModule({ + providers: [ + ReaderBookmarkService, + {provide: BookMarkService, useValue: bookMarkService}, + {provide: MessageService, useValue: messageService}, + {provide: TranslocoService, useValue: translocoService}, + ] + }); + + service = TestBed.inject(ReaderBookmarkService); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('returns false when no current position is set', async () => { + await expect(firstValueFrom(service.createBookmarkAtCurrentPosition(10))).resolves.toBe(false); + expect(bookMarkService.createBookmark).not.toHaveBeenCalled(); + expect(messageService.add).not.toHaveBeenCalled(); + }); + + it('creates a bookmark at the current position and shows a success toast', async () => { + bookMarkService.createBookmark.mockReturnValue(of({id: 1})); + service.updateCurrentPosition('epubcfi(/6/2)', 'Chapter One'); + + await expect(firstValueFrom(service.createBookmarkAtCurrentPosition(10))).resolves.toBe(true); + + expect(bookMarkService.createBookmark).toHaveBeenCalledWith({ + bookId: 10, + cfi: 'epubcfi(/6/2)', + title: 'Chapter One' + }); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'readerEbook.toast.bookmarkAddedSummary', + detail: 'readerEbook.toast.bookmarkAddedDetail' + }); + }); + + it('falls back to a default bookmark title when the chapter name is missing', async () => { + bookMarkService.createBookmark.mockReturnValue(of({id: 1})); + service.updateCurrentPosition('epubcfi(/6/4)'); + + await firstValueFrom(service.createBookmarkAtCurrentPosition(22)); + + expect(bookMarkService.createBookmark).toHaveBeenCalledWith({ + bookId: 22, + cfi: 'epubcfi(/6/4)', + title: 'Bookmark' + }); + }); + + it('shows a warning toast when the bookmark already exists', async () => { + bookMarkService.createBookmark.mockReturnValue(throwError(() => ({status: 409}))); + service.updateCurrentPosition('epubcfi(/6/6)', 'Chapter Two'); + + await expect(firstValueFrom(service.createBookmarkAtCurrentPosition(33))).resolves.toBe(false); + + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'warn', + summary: 'readerEbook.toast.bookmarkExistsSummary', + detail: 'readerEbook.toast.bookmarkExistsDetail' + }); + }); + + it('shows an error toast for non-duplicate bookmark failures and reset clears the saved position', async () => { + bookMarkService.createBookmark.mockReturnValue(throwError(() => ({status: 500}))); + service.updateCurrentPosition('epubcfi(/6/8)', 'Chapter Three'); + + await expect(firstValueFrom(service.createBookmarkAtCurrentPosition(44))).resolves.toBe(false); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'readerEbook.toast.bookmarkFailedSummary', + detail: 'readerEbook.toast.bookmarkFailedDetail' + }); + + service.reset(); + + await expect(firstValueFrom(service.createBookmarkAtCurrentPosition(44))).resolves.toBe(false); + expect(bookMarkService.createBookmark).toHaveBeenCalledTimes(1); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/features/fonts/custom-font.service.spec.ts b/frontend/src/app/features/readers/ebook-reader/features/fonts/custom-font.service.spec.ts new file mode 100644 index 000000000..e39a3ddfd --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/features/fonts/custom-font.service.spec.ts @@ -0,0 +1,160 @@ +import {TestBed} from '@angular/core/testing'; +import {Renderer2} from '@angular/core'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {firstValueFrom} from 'rxjs'; + +import {CustomFontService} from '../../../../../shared/service/custom-font.service'; +import {FontFormat} from '../../../../../shared/model/custom-font.model'; +import {EpubCustomFontService} from './custom-font.service'; + +describe('EpubCustomFontService', () => { + const fonts = [ + { + id: 7, + fontName: 'Fancy Serif (Display).otf', + originalFileName: 'Fancy Serif (Display).otf', + format: FontFormat.OTF, + fileSize: 1024, + uploadedAt: '2026-03-26T00:00:00Z', + }, + ]; + + const customFontService = { + ensureFonts: vi.fn(), + loadAllFonts: vi.fn(), + getFontUrl: vi.fn(), + appendToken: vi.fn(), + }; + + let service: EpubCustomFontService; + let fetchMock: ReturnType; + let createObjectUrlSpy: ReturnType; + let revokeObjectUrlSpy: ReturnType; + + beforeEach(() => { + customFontService.ensureFonts.mockReset(); + customFontService.loadAllFonts.mockReset(); + customFontService.getFontUrl.mockReset(); + customFontService.appendToken.mockReset(); + + customFontService.ensureFonts.mockResolvedValue(fonts); + customFontService.loadAllFonts.mockResolvedValue(undefined); + customFontService.getFontUrl.mockImplementation((fontId: number) => `https://fonts.test/${fontId}`); + customFontService.appendToken.mockImplementation((url: string) => `${url}?token=abc`); + + fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + + createObjectUrlSpy = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:font-7'); + revokeObjectUrlSpy = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined); + + TestBed.configureTestingModule({ + providers: [ + EpubCustomFontService, + {provide: CustomFontService, useValue: customFontService}, + ] + }); + + service = TestBed.inject(EpubCustomFontService); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + it('loads fonts, caches blob urls, and exposes preview metadata', async () => { + fetchMock.mockResolvedValue({ + blob: () => Promise.resolve(new Blob(['font-bytes'], {type: 'font/otf'})), + }); + + await expect(firstValueFrom(service.loadAndCacheFonts())).resolves.toEqual(fonts); + + expect(customFontService.ensureFonts).toHaveBeenCalledOnce(); + expect(customFontService.loadAllFonts).toHaveBeenCalledWith(fonts); + expect(fetchMock).toHaveBeenCalledWith('https://fonts.test/7?token=abc'); + expect(service.getBlobUrl(7)).toBe('blob:font-7'); + expect(service.getCustomFonts()).toEqual(fonts); + expect(service.getCustomFontById(7)).toEqual(fonts[0]); + expect(service.getCustomFontById(999)).toBeUndefined(); + expect(service.sanitizeFontName('Fancy Serif (Display).otf')).toBe('Fancy-Serif-Display'); + expect(service.getFontFamilyForPreview('custom:7')).toBe('"Fancy-Serif-Display", sans-serif'); + expect(service.getFontFamilyForPreview('sans-serif')).toBe('sans-serif'); + }); + + it('returns an empty list when the underlying font load fails', async () => { + customFontService.ensureFonts.mockRejectedValue(new Error('offline')); + + await expect(firstValueFrom(service.loadAndCacheFonts())).resolves.toEqual([]); + + expect(customFontService.loadAllFonts).not.toHaveBeenCalled(); + }); + + it('skips blob caching when there are no fonts', async () => { + customFontService.ensureFonts.mockResolvedValue([]); + customFontService.loadAllFonts.mockResolvedValue(undefined); + + await expect(firstValueFrom(service.loadAndCacheFonts())).resolves.toEqual([]); + + expect(fetchMock).not.toHaveBeenCalled(); + expect(createObjectUrlSpy).not.toHaveBeenCalled(); + }); + + it('continues when one font blob fetch fails and injects stylesheet output for cached fonts', async () => { + const secondFont = { + id: 9, + fontName: 'Mono Sans.woff2', + originalFileName: 'Mono Sans.woff2', + format: FontFormat.WOFF2, + fileSize: 2048, + uploadedAt: '2026-03-26T00:00:00Z', + }; + + customFontService.ensureFonts.mockResolvedValue([fonts[0], secondFont]); + customFontService.loadAllFonts.mockResolvedValue(undefined); + customFontService.getFontUrl.mockImplementation((fontId: number) => `https://fonts.test/${fontId}`); + customFontService.appendToken.mockImplementation((url: string) => `${url}?token=abc`); + + fetchMock + .mockResolvedValueOnce({ + blob: () => Promise.resolve(new Blob(['font-one'], {type: 'font/otf'})), + }) + .mockRejectedValueOnce(new Error('missing blob')); + + createObjectUrlSpy + .mockReturnValueOnce('blob:font-7') + .mockReturnValueOnce('blob:font-9'); + + await expect(firstValueFrom(service.loadAndCacheFonts())).resolves.toEqual([fonts[0], secondFont]); + + const stylesheet = service.generateCustomFontsStylesheet(); + expect(stylesheet).toContain('font-family: "Fancy-Serif-Display"'); + expect(stylesheet).toContain('src: url("blob:font-7")'); + expect(stylesheet).not.toContain('Mono-Sans'); + + const renderer = { + createElement: vi.fn(() => document.createElement('style')), + appendChild: vi.fn(), + } as unknown as Renderer2; + + service.injectCustomFontsStylesheet(renderer, document); + + expect(renderer.createElement).toHaveBeenCalledWith('style'); + expect(renderer.appendChild).toHaveBeenCalledOnce(); + }); + + it('cleans up blob urls and returns empty css when nothing is cached', async () => { + fetchMock.mockResolvedValue({ + blob: () => Promise.resolve(new Blob(['font-bytes'], {type: 'font/otf'})), + }); + + await firstValueFrom(service.loadAndCacheFonts()); + + service.cleanup(); + + expect(revokeObjectUrlSpy).toHaveBeenCalledWith('blob:font-7'); + expect(service.getBlobUrl(7)).toBeUndefined(); + expect(service.generateCustomFontsStylesheet()).toBe(''); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/features/notes/note.service.spec.ts b/frontend/src/app/features/readers/ebook-reader/features/notes/note.service.spec.ts new file mode 100644 index 000000000..92d89151c --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/features/notes/note.service.spec.ts @@ -0,0 +1,231 @@ +import {TestBed} from '@angular/core/testing'; +import {MessageService} from 'primeng/api'; +import {of, Subject, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {BookNoteV2Service} from '../../../../../shared/service/book-note-v2.service'; +import {ReaderSelectionService} from '../selection/selection.service'; +import {ReaderProgressService} from '../../state/progress.service'; +import {ReaderLeftSidebarService} from '../../layout/panel/panel.service'; +import {ReaderViewManagerService} from '../../core/view-manager.service'; +import {TranslocoService} from '@jsverse/transloco'; +import {ReaderNoteService} from './note.service'; + +describe('ReaderNoteService', () => { + const bookNoteV2Service = { + createNote: vi.fn(), + updateNote: vi.fn(), + }; + + const messageService = { + add: vi.fn(), + }; + + const selectionService = { + getCurrentSelection: vi.fn(), + hidePopup: vi.fn(), + }; + + const progressService = { + currentChapterName: 'Chapter 4', + }; + + const editNote$ = new Subject<{ + id: number; + cfi: string; + selectedText?: string; + chapterTitle?: string; + noteContent?: string; + color?: string; + }>(); + + const leftSidebarService = { + editNote$, + refreshNotes: vi.fn(), + }; + + const viewManager = { + clearSelection: vi.fn(), + }; + + const translocoService = { + translate: vi.fn((key: string) => key), + }; + + let service: ReaderNoteService; + let destroy$: Subject; + + beforeEach(() => { + destroy$ = new Subject(); + bookNoteV2Service.createNote.mockReset(); + bookNoteV2Service.updateNote.mockReset(); + messageService.add.mockReset(); + selectionService.getCurrentSelection.mockReset(); + selectionService.hidePopup.mockReset(); + leftSidebarService.refreshNotes.mockReset(); + viewManager.clearSelection.mockReset(); + translocoService.translate.mockClear(); + + TestBed.configureTestingModule({ + providers: [ + ReaderNoteService, + {provide: BookNoteV2Service, useValue: bookNoteV2Service}, + {provide: MessageService, useValue: messageService}, + {provide: ReaderSelectionService, useValue: selectionService}, + {provide: ReaderProgressService, useValue: progressService}, + {provide: ReaderLeftSidebarService, useValue: leftSidebarService}, + {provide: ReaderViewManagerService, useValue: viewManager}, + {provide: TranslocoService, useValue: translocoService}, + ] + }); + + service = TestBed.inject(ReaderNoteService); + service.initialize(14, destroy$); + }); + + afterEach(() => { + destroy$.next(); + destroy$.complete(); + TestBed.resetTestingModule(); + }); + + it('opens a new note dialog from the current selection and hides the popup', () => { + selectionService.getCurrentSelection.mockReturnValue({ + cfi: 'epubcfi(/6/2)', + text: 'Quoted text', + }); + + service.openNewNoteDialog(); + + expect(selectionService.hidePopup).toHaveBeenCalledOnce(); + expect(service.dialogState()).toEqual({ + visible: true, + data: { + cfi: 'epubcfi(/6/2)', + selectedText: 'Quoted text', + chapterTitle: 'Chapter 4', + } + }); + }); + + it('does nothing when opening a new note dialog without a selection', () => { + selectionService.getCurrentSelection.mockReturnValue(null); + + service.openNewNoteDialog(); + + expect(selectionService.hidePopup).not.toHaveBeenCalled(); + expect(service.dialogState()).toEqual({visible: false, data: null}); + }); + + it('creates a note, clears selection, refreshes notes, and shows a success toast', () => { + bookNoteV2Service.createNote.mockReturnValue(of({id: 9})); + service.openEditDialog({ + cfi: 'epubcfi(/6/2)', + selectedText: 'Quoted text', + chapterTitle: 'Chapter 4', + }); + + service.saveNote({noteContent: 'Important thought', color: '#FFC107'}); + + expect(bookNoteV2Service.createNote).toHaveBeenCalledWith({ + bookId: 14, + cfi: 'epubcfi(/6/2)', + selectedText: 'Quoted text', + noteContent: 'Important thought', + color: '#FFC107', + chapterTitle: 'Chapter 4', + }); + expect(viewManager.clearSelection).toHaveBeenCalledOnce(); + expect(leftSidebarService.refreshNotes).toHaveBeenCalledOnce(); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'readerEbook.toast.noteSavedSummary', + detail: 'readerEbook.toast.noteSavedDetail' + }); + expect(service.dialogState()).toEqual({visible: false, data: null}); + }); + + it('updates an existing note and shows the update toast', () => { + bookNoteV2Service.updateNote.mockReturnValue(of({id: 12})); + service.openEditDialog({ + cfi: 'epubcfi(/6/4)', + noteId: 12, + noteContent: 'Old', + color: '#2196F3', + }); + + service.saveNote({noteContent: 'New content', color: '#4CAF50'}); + + expect(bookNoteV2Service.updateNote).toHaveBeenCalledWith(12, { + noteContent: 'New content', + color: '#4CAF50', + }); + expect(leftSidebarService.refreshNotes).toHaveBeenCalledOnce(); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'readerEbook.toast.noteUpdatedSummary', + detail: 'readerEbook.toast.noteUpdatedDetail' + }); + }); + + it('shows error toasts for create and update failures and leaves the dialog open', () => { + bookNoteV2Service.createNote.mockReturnValue(throwError(() => new Error('save failed'))); + service.openEditDialog({ + cfi: 'epubcfi(/6/2)', + selectedText: 'Quoted text', + }); + + service.saveNote({noteContent: 'Important thought', color: '#FFC107'}); + + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'readerEbook.toast.saveFailedSummary', + detail: 'readerEbook.toast.saveFailedDetail' + }); + expect(service.dialogState().visible).toBe(true); + + bookNoteV2Service.updateNote.mockReturnValue(throwError(() => new Error('update failed'))); + service.openEditDialog({ + cfi: 'epubcfi(/6/4)', + noteId: 12, + noteContent: 'Old', + }); + + service.saveNote({noteContent: 'New content', color: '#4CAF50'}); + + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'readerEbook.toast.updateFailedSummary', + detail: 'readerEbook.toast.updateFailedDetail' + }); + }); + + it('opens the edit dialog from sidebar events and resets cleanly', () => { + editNote$.next({ + id: 25, + cfi: 'epubcfi(/6/10)', + selectedText: 'Selected', + chapterTitle: 'Chapter 9', + noteContent: 'Existing note', + color: '#2196F3', + }); + + expect(service.dialogState()).toEqual({ + visible: true, + data: { + cfi: 'epubcfi(/6/10)', + selectedText: 'Selected', + chapterTitle: 'Chapter 9', + noteId: 25, + noteContent: 'Existing note', + color: '#2196F3', + } + }); + + service.closeDialog(); + expect(service.dialogState()).toEqual({visible: false, data: null}); + + service.reset(); + expect(service.dialogState()).toEqual({visible: false, data: null}); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/features/selection/selection.service.spec.ts b/frontend/src/app/features/readers/ebook-reader/features/selection/selection.service.spec.ts new file mode 100644 index 000000000..f5d2a7d74 --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/features/selection/selection.service.spec.ts @@ -0,0 +1,201 @@ +import {TestBed} from '@angular/core/testing'; +import {of, Subject} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {Annotation} from '../../../../../shared/service/annotation.service'; +import {ReaderLeftSidebarService} from '../../layout/panel/panel.service'; +import {ReaderAnnotationHttpService} from '../annotations/annotation.service'; +import {ReaderViewManagerService} from '../../core/view-manager.service'; +import {ReaderSelectionService} from './selection.service'; + +describe('ReaderSelectionService', () => { + const destroy$ = new Subject(); + + const viewManager = { + addAnnotation: vi.fn(() => of({index: 1, label: 'Annotation 1'})), + deleteAnnotation: vi.fn(() => of(void 0)), + clearSelection: vi.fn(), + }; + + const annotationService = { + createAnnotation: vi.fn(), + deleteAnnotation: vi.fn(), + }; + + const leftSidebarService = { + openWithSearch: vi.fn(), + }; + + let service: ReaderSelectionService; + + beforeEach(() => { + viewManager.addAnnotation.mockReset(); + viewManager.addAnnotation.mockReturnValue(of({index: 1, label: 'Annotation 1'})); + viewManager.deleteAnnotation.mockReset(); + viewManager.deleteAnnotation.mockReturnValue(of(void 0)); + viewManager.clearSelection.mockReset(); + + annotationService.createAnnotation.mockReset(); + annotationService.deleteAnnotation.mockReset(); + leftSidebarService.openWithSearch.mockReset(); + + TestBed.configureTestingModule({ + providers: [ + ReaderSelectionService, + {provide: ReaderViewManagerService, useValue: viewManager}, + {provide: ReaderAnnotationHttpService, useValue: annotationService}, + {provide: ReaderLeftSidebarService, useValue: leftSidebarService}, + ] + }); + + service = TestBed.inject(ReaderSelectionService); + service.initialize(41, destroy$); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('tracks text selection state and identifies overlapping annotations', () => { + const overlappingAnnotation: Annotation = { + id: 8, + bookId: 41, + cfi: 'epubcfi(/6/2!/4/2,/4/2:4,/4/2:12)', + text: 'existing highlight', + color: '#f59e0b', + style: 'highlight', + createdAt: '2026-03-26T00:00:00Z', + }; + service.setAnnotations([overlappingAnnotation]); + + service.handleTextSelected({ + text: 'selected text', + cfi: 'epubcfi(/6/2!/4/2,/4/2:6,/4/2:10)', + range: document.createRange(), + index: 3 + }, {x: 120, y: 80, showBelow: true}); + + expect(service.state()).toEqual({ + visible: true, + position: {x: 120, y: 80, showBelow: true}, + showBelow: true, + overlappingAnnotationId: 8, + selectedText: 'selected text' + }); + }); + + it('previews, selects, searches, and dismisses the active selection', () => { + const clipboardWrite = vi.fn(); + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: {writeText: clipboardWrite}, + }); + + service.handleTextSelected({ + text: 'searchable snippet', + cfi: 'epubcfi(/6/2!/4/2:1,/4/2/4:9)', + range: document.createRange(), + index: 1 + }); + + service.handleAction({type: 'preview', color: '#16a34a', style: 'underline'}); + expect(viewManager.addAnnotation).toHaveBeenCalledWith({ + value: 'epubcfi(/6/2!/4/2:1,/4/2/4:9)', + color: '#16a34a', + style: 'underline' + }); + + service.handleAction({type: 'select'}); + expect(clipboardWrite).toHaveBeenCalledWith('searchable snippet'); + expect(viewManager.clearSelection).toHaveBeenCalled(); + + service.handleTextSelected({ + text: 'searchable snippet', + cfi: 'epubcfi(/6/2!/4/2:1,/4/2/4:9)', + range: document.createRange(), + index: 1 + }); + + service.handleAction({type: 'search', searchText: 'searchable snippet'}); + expect(leftSidebarService.openWithSearch).toHaveBeenCalledWith('searchable snippet'); + + service.handleAction({type: 'dismiss'}); + + expect(service.state()).toEqual({ + visible: false, + position: {x: 0, y: 0}, + showBelow: false, + overlappingAnnotationId: null, + selectedText: '' + }); + }); + + it('creates annotations, ignores missing deletions, and clears preview state on hide', () => { + const annotationsChanged: Annotation[][] = []; + service.annotationsChanged$.subscribe(value => annotationsChanged.push(value)); + + annotationService.createAnnotation.mockReturnValue(of({ + id: 99, + bookId: 41, + cfi: 'epubcfi(/6/2!/4/2:0,/4/2/4:4)', + text: 'note text', + color: '#f97316', + style: 'highlight', + createdAt: '2026-03-26T00:00:00Z', + } satisfies Annotation)); + + service.handleTextSelected({ + text: 'note text', + cfi: 'epubcfi(/6/2!/4/2:0,/4/2/4:4)', + range: document.createRange(), + index: 1 + }); + + service.handleAction({type: 'annotate', color: '#f97316', style: 'highlight'}); + + expect(annotationService.createAnnotation).toHaveBeenCalledWith( + 41, + 'epubcfi(/6/2!/4/2:0,/4/2/4:4)', + 'note text', + '#f97316', + 'highlight' + ); + expect(annotationsChanged).toHaveLength(1); + expect(annotationsChanged[0]).toEqual([ + { + id: 99, + bookId: 41, + cfi: 'epubcfi(/6/2!/4/2:0,/4/2/4:4)', + text: 'note text', + color: '#f97316', + style: 'highlight', + createdAt: '2026-03-26T00:00:00Z', + } + ]); + expect(viewManager.clearSelection).toHaveBeenCalled(); + + annotationService.deleteAnnotation.mockReturnValue(of(false)); + service.deleteAnnotation(99); + + expect(annotationService.deleteAnnotation).toHaveBeenCalledWith(99); + expect(viewManager.deleteAnnotation).not.toHaveBeenCalled(); + + service.handleTextSelected({ + text: 'preview text', + cfi: 'epubcfi(/6/2!/4/2,/4/2:12,/4/2:20)', + range: document.createRange(), + index: 1 + }); + service.handleAction({type: 'preview', color: '#60a5fa', style: 'squiggly'}); + service.hidePopup(); + + expect(viewManager.deleteAnnotation).toHaveBeenCalledWith('epubcfi(/6/2!/4/2,/4/2:12,/4/2:20)'); + expect(service.state()).toEqual({ + visible: false, + position: {x: 0, y: 0}, + showBelow: false, + overlappingAnnotationId: null, + selectedText: 'preview text' + }); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/index.spec.ts b/frontend/src/app/features/readers/ebook-reader/index.spec.ts new file mode 100644 index 000000000..65b692608 --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/index.spec.ts @@ -0,0 +1,13 @@ +import {describe, expect, it} from 'vitest'; + +import * as readerExports from './index'; + +describe('ebook-reader index barrel', () => { + it('re-exports the primary reader entrypoints', () => { + expect(readerExports.EbookReaderComponent).toBeDefined(); + expect(readerExports.ReaderViewManagerService).toBeDefined(); + expect(readerExports.ReaderEventService).toBeDefined(); + expect(readerExports.ReaderAnnotationHttpService).toBeDefined(); + expect(readerExports.ReaderIconComponent).toBeDefined(); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/layout/footer/footer.component.spec.ts b/frontend/src/app/features/readers/ebook-reader/layout/footer/footer.component.spec.ts new file mode 100644 index 000000000..d5ee459dc --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/layout/footer/footer.component.spec.ts @@ -0,0 +1,9 @@ +import {describe, expect, it} from 'vitest'; + +// TODO(seam): The ebook footer is driven by reader state signals, progress controls, and +// layout actions that need a mounted reader harness instead of a shallow class test. +describe.skip('EbookFooterComponent', () => { + it('needs a mounted reader harness for progress, navigation, and selection footer branches', () => { + expect.hasAssertions(); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/layout/header/header.component.spec.ts b/frontend/src/app/features/readers/ebook-reader/layout/header/header.component.spec.ts new file mode 100644 index 000000000..79c0e3a50 --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/layout/header/header.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around header-service signals, router +// fallback behavior, and the reader shell template so ebook-header interactions can be tested +// without mounting the full reader layout runtime. +describe.skip('ReaderHeaderComponent', () => { + it('needs service seams to verify sidebar, notes, search, bookmark, controls, fullscreen, and help actions', () => { + // TODO(seam): Cover the delegation methods once the header-service signal graph is isolated behind direct test doubles. + }); + + it('needs browser-history seams to verify dashboard fallback versus close delegation', () => { + // TODO(seam): Cover onClose after extracting window.history and router interactions behind a deterministic test seam. + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/layout/header/header.service.spec.ts b/frontend/src/app/features/readers/ebook-reader/layout/header/header.service.spec.ts new file mode 100644 index 000000000..7d904c6be --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/layout/header/header.service.spec.ts @@ -0,0 +1,155 @@ +import {Location} from '@angular/common'; +import {TestBed} from '@angular/core/testing'; +import {of} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {BookService} from '../../../../book/service/book.service'; +import {ReaderSidebarService} from '../sidebar/sidebar.service'; +import {ReaderLeftSidebarService} from '../panel/panel.service'; +import {ReaderStateService} from '../../state/reader-state.service'; +import {themes} from '../../state/themes.constant'; +import {ReaderHeaderService} from './header.service'; + +describe('ReaderHeaderService', () => { + const readerState = { + state: vi.fn(() => ({ + lineHeight: 1.5, + justify: true, + hyphenate: true, + maxColumnCount: 2, + gap: 0.05, + fontSize: 16, + theme: {...themes[0], fg: themes[0].dark.fg, bg: themes[0].dark.bg, link: themes[0].dark.link}, + maxInlineSize: 720, + maxBlockSize: 1440, + fontFamily: null, + isDark: true, + flow: 'paginated', + })), + toggleDarkMode: vi.fn(), + updateFontSize: vi.fn(), + }; + + const sidebarService = { + open: vi.fn(), + toggleBookmark: vi.fn(), + }; + + const leftSidebarService = { + open: vi.fn(), + }; + + const bookService = { + updateViewerSetting: vi.fn(() => of(void 0)), + }; + + const location = { + back: vi.fn(), + }; + + let service: ReaderHeaderService; + + beforeEach(() => { + readerState.state.mockClear(); + readerState.toggleDarkMode.mockReset(); + readerState.updateFontSize.mockReset(); + sidebarService.open.mockReset(); + sidebarService.toggleBookmark.mockReset(); + leftSidebarService.open.mockReset(); + bookService.updateViewerSetting.mockReset(); + bookService.updateViewerSetting.mockReturnValue(of(void 0)); + location.back.mockReset(); + + TestBed.configureTestingModule({ + providers: [ + ReaderHeaderService, + {provide: ReaderStateService, useValue: readerState}, + {provide: ReaderSidebarService, useValue: sidebarService}, + {provide: ReaderLeftSidebarService, useValue: leftSidebarService}, + {provide: BookService, useValue: bookService}, + {provide: Location, useValue: location}, + ] + }); + + service = TestBed.inject(ReaderHeaderService); + service.initialize(12, 'Book Title'); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('tracks title, visibility, bookmarks, fullscreen, and resets cleanly', () => { + service.setForceVisible(true); + service.setCurrentCfiBookmarked(true); + service.setFullscreen(true); + + expect(service.bookTitle()).toBe('Book Title'); + expect(service.forceVisible()).toBe(true); + expect(service.isCurrentCfiBookmarked()).toBe(true); + expect(service.isFullscreen()).toBe(true); + expect(service.theme()).toMatchObject({name: 'default'}); + + service.reset(); + + expect(service.bookTitle()).toBe(''); + expect(service.forceVisible()).toBe(false); + expect(service.isCurrentCfiBookmarked()).toBe(false); + expect(service.isFullscreen()).toBe(false); + }); + + it('delegates sidebar and metadata actions and emits UI events', () => { + const controlsEvents: void[] = []; + const metadataEvents: void[] = []; + const fullscreenEvents: void[] = []; + const shortcutsEvents: void[] = []; + + service.showControls$.subscribe(() => controlsEvents.push(undefined)); + service.showMetadata$.subscribe(() => metadataEvents.push(undefined)); + service.toggleFullscreen$.subscribe(() => fullscreenEvents.push(undefined)); + service.showShortcutsHelp$.subscribe(() => shortcutsEvents.push(undefined)); + + service.openSidebar(); + service.openLeftSidebar('notes'); + service.createBookmark(); + service.openControls(); + service.openMetadata(); + service.toggleFullscreen(); + service.showShortcutsHelp(); + service.close(); + + expect(sidebarService.open).toHaveBeenCalledOnce(); + expect(leftSidebarService.open).toHaveBeenCalledWith('notes'); + expect(sidebarService.toggleBookmark).toHaveBeenCalledOnce(); + expect(controlsEvents).toHaveLength(1); + expect(metadataEvents).toHaveLength(1); + expect(fullscreenEvents).toHaveLength(1); + expect(shortcutsEvents).toHaveLength(1); + expect(location.back).toHaveBeenCalledOnce(); + }); + + it('syncs dark mode and font size updates back to the viewer settings endpoint', () => { + service.toggleDarkMode(); + service.increaseFontSize(); + + expect(readerState.toggleDarkMode).toHaveBeenCalledOnce(); + expect(readerState.updateFontSize).toHaveBeenCalledWith(1); + expect(bookService.updateViewerSetting).toHaveBeenCalledTimes(2); + expect(bookService.updateViewerSetting).toHaveBeenCalledWith({ + ebookSettings: { + lineHeight: 1.5, + justify: true, + hyphenate: true, + maxColumnCount: 2, + gap: 0.05, + fontSize: 16, + theme: 'default', + maxInlineSize: 720, + maxBlockSize: 1440, + fontFamily: null, + isDark: true, + flow: 'paginated', + } + }, 12); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/layout/header/quick-settings.component.spec.ts b/frontend/src/app/features/readers/ebook-reader/layout/header/quick-settings.component.spec.ts new file mode 100644 index 000000000..b1df46eda --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/layout/header/quick-settings.component.spec.ts @@ -0,0 +1,9 @@ +import {describe, expect, it} from 'vitest'; + +// TODO(seam): Quick settings need a reader-state harness with overlay controls and persisted +// preference services to cover the font, theme, and flow branches without brittle mocks. +describe.skip('QuickSettingsComponent', () => { + it('needs a mounted reader harness for quick-settings interactions and persistence branches', () => { + expect.hasAssertions(); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/layout/panel/panel.component.spec.ts b/frontend/src/app/features/readers/ebook-reader/layout/panel/panel.component.spec.ts new file mode 100644 index 000000000..d0b7b50b9 --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/layout/panel/panel.component.spec.ts @@ -0,0 +1,9 @@ +import {describe, expect, it} from 'vitest'; + +// TODO(seam): The panel component coordinates injected panel services, projected overlays, +// and reader-layout state that should be exercised in a mounted reader shell. +describe.skip('ReaderPanelComponent', () => { + it('needs a mounted reader shell to cover panel open, close, and switching flows', () => { + expect.hasAssertions(); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/layout/panel/panel.service.spec.ts b/frontend/src/app/features/readers/ebook-reader/layout/panel/panel.service.spec.ts new file mode 100644 index 000000000..551a124f2 --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/layout/panel/panel.service.spec.ts @@ -0,0 +1,179 @@ +import {TestBed} from '@angular/core/testing'; +import {of, Subject} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {BookNoteV2, BookNoteV2Service} from '../../../../../shared/service/book-note-v2.service'; +import {ReaderViewManagerService} from '../../core/view-manager.service'; +import {ReaderLeftSidebarService} from './panel.service'; + +describe('ReaderLeftSidebarService', () => { + let service: ReaderLeftSidebarService; + let destroy$: Subject; + + const notes = [ + {id: 1, bookId: 9, cfi: 'epubcfi(/6/2)', noteContent: 'Alpha', selectedText: 'Quote', chapterTitle: 'Intro', createdAt: '2026-03-26T00:00:00Z'}, + {id: 2, bookId: 9, cfi: 'epubcfi(/6/4)', noteContent: 'Beta', selectedText: 'Passage', chapterTitle: 'Middle', createdAt: '2026-03-26T00:00:00Z'}, + ]; + + const bookNoteV2Service = { + getNotesForBook: vi.fn(), + deleteNote: vi.fn(), + }; + + const asyncSearch = async function* () { + yield {progress: 0.4}; + yield { + label: 'Chapter 1', + subitems: [ + { + cfi: 'epubcfi(/6/8)', + excerpt: {pre: 'before', match: 'match', post: 'after'}, + }, + ], + }; + yield 'done' as const; + }; + + const viewManager = { + goTo: vi.fn(() => of(void 0)), + search: vi.fn(() => asyncSearch()), + clearSearch: vi.fn(), + }; + + beforeEach(() => { + destroy$ = new Subject(); + bookNoteV2Service.getNotesForBook.mockReset(); + bookNoteV2Service.getNotesForBook.mockReturnValue(of(notes)); + bookNoteV2Service.deleteNote.mockReset(); + bookNoteV2Service.deleteNote.mockReturnValue(of(void 0)); + viewManager.goTo.mockReset(); + viewManager.goTo.mockReturnValue(of(void 0)); + viewManager.search.mockReset(); + viewManager.search.mockImplementation(() => asyncSearch()); + viewManager.clearSearch.mockReset(); + + TestBed.configureTestingModule({ + providers: [ + ReaderLeftSidebarService, + {provide: BookNoteV2Service, useValue: bookNoteV2Service}, + {provide: ReaderViewManagerService, useValue: viewManager}, + ] + }); + + service = TestBed.inject(ReaderLeftSidebarService); + service.initialize(9, destroy$); + }); + + afterEach(() => { + vi.useRealTimers(); + destroy$.next(); + destroy$.complete(); + TestBed.resetTestingModule(); + }); + + it('initializes and filters notes', () => { + expect(bookNoteV2Service.getNotesForBook).toHaveBeenCalledWith(9); + expect(service.notes()).toEqual(notes); + + service.setNotesSearchQuery('quote'); + expect(service.filteredNotes()).toEqual([notes[0]]); + + service.setNotesSearchQuery('middle'); + expect(service.filteredNotes()).toEqual([notes[1]]); + }); + + it('opens, closes, toggles, and schedules search from openWithSearch', async () => { + vi.useFakeTimers(); + const searchSpy = vi.spyOn(service, 'search').mockResolvedValue(undefined); + + service.open('notes'); + expect(service.isOpen()).toBe(true); + expect(service.activeTab()).toBe('notes'); + + service.toggle('notes'); + expect(service.isOpen()).toBe(false); + + service.openWithSearch('magic'); + await vi.advanceTimersByTimeAsync(100); + + expect(service.isOpen()).toBe(true); + expect(service.activeTab()).toBe('search'); + expect(searchSpy).toHaveBeenCalledWith('magic'); + }); + + it('searches, tracks progress, and clears when the query is blank', async () => { + await service.search('magic'); + + expect(viewManager.search).toHaveBeenCalledWith({query: 'magic'}); + expect(service.searchState()).toEqual({ + query: 'magic', + results: [ + { + cfi: 'epubcfi(/6/8)', + excerpt: {pre: 'before', match: 'match', post: 'after'}, + sectionLabel: 'Chapter 1', + }, + ], + isSearching: false, + progress: 1, + }); + + await service.search(' '); + expect(viewManager.clearSearch).toHaveBeenCalledOnce(); + expect(service.searchState()).toEqual({ + query: '', + results: [], + isSearching: false, + progress: 0, + }); + }); + + it('handles search errors without leaving the searching flag stuck', async () => { + viewManager.search.mockImplementation(async function* () { + yield {progress: 0}; + throw new Error('search failed'); + }); + + await service.search('broken'); + + expect(service.searchState()).toEqual({ + query: 'broken', + results: [], + isSearching: false, + progress: 0, + }); + }); + + it('navigates to notes and search results, deletes notes, emits edit events, and resets', () => { + const editEvents: BookNoteV2[] = []; + service.editNote$.subscribe(note => editEvents.push(note)); + + service.open(); + service.navigateToNote('epubcfi(/6/2)'); + service.navigateToSearchResult('epubcfi(/6/8)'); + expect(viewManager.goTo).toHaveBeenNthCalledWith(1, 'epubcfi(/6/2)'); + expect(viewManager.goTo).toHaveBeenNthCalledWith(2, 'epubcfi(/6/8)'); + expect(service.isOpen()).toBe(false); + + service.deleteNote(1); + expect(bookNoteV2Service.deleteNote).toHaveBeenCalledWith(1); + expect(service.notes()).toEqual([notes[1]]); + + service.open(); + service.editNote(notes[1]); + expect(editEvents).toEqual([notes[1]]); + expect(service.isOpen()).toBe(false); + + service.reset(); + expect(service.isOpen()).toBe(false); + expect(service.activeTab()).toBe('search'); + expect(service.notes()).toEqual([]); + expect(service.notesSearchQuery()).toBe(''); + expect(service.searchState()).toEqual({ + query: '', + results: [], + isSearching: false, + progress: 0, + }); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.component.spec.ts b/frontend/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.component.spec.ts new file mode 100644 index 000000000..6e65c348a --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.component.spec.ts @@ -0,0 +1,9 @@ +import {describe, expect, it} from 'vitest'; + +// TODO(seam): Sidebar coverage needs a mounted ebook reader harness with TOC, search, and +// bookmark state services so the navigation and search-result branches stay realistic. +describe.skip('ReaderSidebarComponent', () => { + it('needs a mounted reader harness for TOC, search, and bookmark sidebar branches', () => { + expect.hasAssertions(); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.service.spec.ts b/frontend/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.service.spec.ts new file mode 100644 index 000000000..6f4fac459 --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.service.spec.ts @@ -0,0 +1,256 @@ +import {Injector} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {of, Subject} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {BookMarkService} from '../../../../../shared/service/book-mark.service'; +import {ReaderAnnotationHttpService} from '../../features/annotations/annotation.service'; +import {ReaderBookmarkService} from '../../features/bookmarks/bookmark.service'; +import {ReaderSelectionService} from '../../features/selection/selection.service'; +import {ReaderProgressService} from '../../state/progress.service'; +import {ReaderViewManagerService} from '../../core/view-manager.service'; +import {UrlHelperService} from '../../../../../shared/service/url-helper.service'; +import {Book} from '../../../../book/model/book.model'; +import {ReaderSidebarService} from './sidebar.service'; + +describe('ReaderSidebarService', () => { + const destroy$ = new Subject(); + + const selectionAnnotations$ = new Subject<{id: number; cfi: string}[]>(); + const selectionService = { + annotationsChanged$: selectionAnnotations$.asObservable(), + setAnnotations: vi.fn(), + }; + + const urlHelper = { + getThumbnailUrl: vi.fn(() => '/cover.jpg'), + }; + + const viewManager = { + getChapters: vi.fn(), + goTo: vi.fn(() => of(void 0)), + addAnnotations: vi.fn(), + deleteAnnotation: vi.fn(() => of(void 0)), + }; + + const progressService: { currentChapterHref: string | null; currentCfi: string | null } = { + currentChapterHref: '/ops/chapter-2.xhtml#frag', + currentCfi: 'epubcfi(/6/4)', + }; + + const bookmarkService = { + createBookmarkAtCurrentPosition: vi.fn(), + }; + + const bookmarkHttpService = { + getBookmarksForBook: vi.fn(), + deleteBookmark: vi.fn(() => of(void 0)), + }; + + const annotationService = { + getAnnotations: vi.fn(), + toViewAnnotations: vi.fn(), + deleteAnnotation: vi.fn(() => of(true)), + }; + + const book = { + id: 7, + libraryId: 2, + libraryName: 'Library', + fileName: 'book.epub', + metadata: { + bookId: 7, + title: 'Reader Book', + authors: ['Alice', 'Bob'], + coverUpdatedOn: '2026-03-26T00:00:00Z', + }, + } as Book; + + const chapters = [ + { + label: 'Part 1', + href: '/ops/part-1.xhtml', + subitems: [ + {label: 'Chapter 1', href: '/ops/chapter-1.xhtml', subitems: []}, + {label: 'Chapter 2', href: '/ops/chapter-2.xhtml#frag', subitems: []}, + ], + }, + ]; + + const bookmarks = [ + {id: 10, bookId: 7, cfi: 'epubcfi(/6/4)', title: 'Current', createdAt: '2026-03-26T00:00:00Z'}, + ]; + + const annotations = [ + {id: 22, bookId: 7, cfi: 'epubcfi(/6/6)', text: 'Quote', color: '#ff0', style: 'highlight' as const, createdAt: '2026-03-26T00:00:00Z'}, + ]; + + let service: ReaderSidebarService; + + beforeEach(() => { + viewManager.getChapters.mockReset(); + viewManager.getChapters.mockReturnValue(chapters); + viewManager.goTo.mockReset(); + viewManager.goTo.mockReturnValue(of(void 0)); + viewManager.addAnnotations.mockReset(); + viewManager.deleteAnnotation.mockReset(); + viewManager.deleteAnnotation.mockReturnValue(of(void 0)); + + bookmarkService.createBookmarkAtCurrentPosition.mockReset(); + bookmarkService.createBookmarkAtCurrentPosition.mockReturnValue(of(true)); + bookmarkHttpService.getBookmarksForBook.mockReset(); + bookmarkHttpService.getBookmarksForBook.mockReturnValue(of(bookmarks)); + bookmarkHttpService.deleteBookmark.mockReset(); + bookmarkHttpService.deleteBookmark.mockReturnValue(of(void 0)); + + annotationService.getAnnotations.mockReset(); + annotationService.getAnnotations.mockReturnValue(of(annotations)); + annotationService.toViewAnnotations.mockReset(); + annotationService.toViewAnnotations.mockReturnValue([{value: annotations[0].cfi, color: annotations[0].color, style: annotations[0].style}]); + annotationService.deleteAnnotation.mockReset(); + annotationService.deleteAnnotation.mockReturnValue(of(true)); + + selectionService.setAnnotations.mockReset(); + urlHelper.getThumbnailUrl.mockClear(); + + TestBed.configureTestingModule({ + providers: [ + ReaderSidebarService, + {provide: UrlHelperService, useValue: urlHelper}, + {provide: ReaderViewManagerService, useValue: viewManager}, + {provide: ReaderProgressService, useValue: progressService}, + {provide: ReaderBookmarkService, useValue: bookmarkService}, + {provide: BookMarkService, useValue: bookmarkHttpService}, + {provide: ReaderAnnotationHttpService, useValue: annotationService}, + {provide: ReaderSelectionService, useValue: selectionService}, + { + provide: Injector, + useFactory: () => ({ + get: (token: unknown) => token === ReaderSelectionService ? selectionService : undefined, + }), + }, + ] + }); + + service = TestBed.inject(ReaderSidebarService); + service.initialize(7, book, destroy$); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('initializes book info, chapters, bookmarks, and annotations', () => { + expect(urlHelper.getThumbnailUrl).toHaveBeenCalledWith(7, '2026-03-26T00:00:00Z'); + expect(service.bookInfo()).toEqual({ + id: 7, + title: 'Reader Book', + authors: 'Alice, Bob', + coverUrl: '/cover.jpg', + }); + expect(service.chapters()).toEqual(chapters); + expect(service.bookmarks()).toEqual(bookmarks); + expect(service.annotations()).toEqual(annotations); + expect(selectionService.setAnnotations).toHaveBeenCalledWith(annotations); + expect(viewManager.addAnnotations).toHaveBeenCalledWith([{value: 'epubcfi(/6/6)', color: '#ff0', style: 'highlight'}]); + }); + + it('opens tabs, auto-expands the current chapter path, and detects active chapters', () => { + service.open('bookmarks'); + + expect(service.isOpen()).toBe(true); + expect(service.activeTab()).toBe('bookmarks'); + expect(service.isChapterExpanded('/ops/part-1.xhtml')).toBe(true); + expect(service.isChapterActive('/ops/chapter-2.xhtml')).toBe(true); + expect(service.isChapterActive('/ops/chapter-9.xhtml')).toBe(false); + + service.toggleChapterExpand('/ops/chapter-1.xhtml'); + expect(service.isChapterExpanded('/ops/chapter-1.xhtml')).toBe(true); + service.toggleChapterExpand('/ops/chapter-1.xhtml'); + expect(service.isChapterExpanded('/ops/chapter-1.xhtml')).toBe(false); + }); + + it('toggles sidebar visibility and can update the chapter list', () => { + const nextChapters = [{label: 'New Chapter', href: '/ops/new.xhtml', subitems: []}]; + viewManager.getChapters.mockReturnValue(nextChapters); + + service.toggle(); + expect(service.isOpen()).toBe(true); + + service.toggle(); + expect(service.isOpen()).toBe(false); + + service.setActiveTab('highlights'); + service.updateChapters(); + expect(service.activeTab()).toBe('highlights'); + expect(service.chapters()).toEqual(nextChapters); + }); + + it('navigates to chapters, bookmarks, and annotations and closes afterwards', () => { + service.open(); + + service.navigateToChapter('/ops/chapter-1.xhtml'); + service.navigateToBookmark('epubcfi(/6/8)'); + service.navigateToAnnotation('epubcfi(/6/10)'); + + expect(viewManager.goTo).toHaveBeenNthCalledWith(1, '/ops/chapter-1.xhtml'); + expect(viewManager.goTo).toHaveBeenNthCalledWith(2, 'epubcfi(/6/8)'); + expect(viewManager.goTo).toHaveBeenNthCalledWith(3, 'epubcfi(/6/10)'); + expect(service.isOpen()).toBe(false); + }); + + it('creates and deletes bookmarks through the current cfi branches', () => { + service.createBookmark(); + expect(bookmarkService.createBookmarkAtCurrentPosition).toHaveBeenCalledWith(7); + expect(bookmarkHttpService.getBookmarksForBook).toHaveBeenCalledTimes(2); + + service.toggleBookmark(); + expect(bookmarkHttpService.deleteBookmark).toHaveBeenCalledWith(10); + + progressService.currentCfi = 'epubcfi(/6/12)'; + service.toggleBookmark(); + expect(bookmarkService.createBookmarkAtCurrentPosition).toHaveBeenCalledTimes(2); + + progressService.currentCfi = null; + service.toggleBookmark(); + expect(bookmarkService.createBookmarkAtCurrentPosition).toHaveBeenCalledTimes(2); + }); + + it('removes annotations only when delete succeeds and syncs external changes', () => { + service.deleteAnnotation(22); + + expect(annotationService.deleteAnnotation).toHaveBeenCalledWith(22); + expect(viewManager.deleteAnnotation).toHaveBeenCalledWith('epubcfi(/6/6)'); + expect(service.annotations()).toEqual([]); + expect(selectionService.setAnnotations).toHaveBeenCalledWith([]); + + selectionAnnotations$.next([{id: 31, cfi: 'epubcfi(/6/14)'}]); + expect(service.annotations()).toEqual([{id: 31, cfi: 'epubcfi(/6/14)'}]); + + annotationService.deleteAnnotation.mockReturnValue(of(false)); + service.setAnnotations(annotations); + service.deleteAnnotation(22); + expect(viewManager.deleteAnnotation).toHaveBeenCalledTimes(1); + + service.deleteAnnotation(999); + expect(annotationService.deleteAnnotation).toHaveBeenCalledTimes(2); + }); + + it('emits metadata requests and resets back to defaults', () => { + const metadataEvents: void[] = []; + service.showMetadata$.subscribe(() => metadataEvents.push(undefined)); + + service.open(); + service.openMetadata(); + + expect(metadataEvents).toHaveLength(1); + expect(service.isOpen()).toBe(false); + + service.reset(); + expect(service.activeTab()).toBe('chapters'); + expect(service.bookInfo()).toEqual({id: null, title: '', authors: '', coverUrl: null}); + expect(service.chapters()).toEqual([]); + expect(service.bookmarks()).toEqual([]); + expect(service.annotations()).toEqual([]); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/shared/header-footer.util.spec.ts b/frontend/src/app/features/readers/ebook-reader/shared/header-footer.util.spec.ts new file mode 100644 index 000000000..71d9098a7 --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/shared/header-footer.util.spec.ts @@ -0,0 +1,67 @@ +import {describe, expect, it} from 'vitest'; + +import {PageDecorator} from './header-footer.util'; + +describe('PageDecorator', () => { + it('ignores missing renderers and missing footer page info', () => { + expect(() => PageDecorator.updateHeadersAndFooters(null, 'Chapter 1')).not.toThrow(); + + const head = document.createElement('div'); + const foot = document.createElement('div'); + + PageDecorator.updateHeadersAndFooters({heads: [head], feet: [foot]}, 'Chapter 1'); + + expect(head.textContent).toBe('Chapter 1'); + expect(foot.childElementCount).toBe(0); + }); + + it('renders single-column headers and footers with theme-aware styling', () => { + const head = document.createElement('div'); + const foot = document.createElement('div'); + + PageDecorator.updateHeadersAndFooters( + {heads: [head], feet: [foot]}, + 'Chapter 7', + {percentCompleted: 42, sectionTimeText: '3m 10s'}, + {fg: '#111111', bg: '#ffffff'}, + '2m left' + ); + + const headerContent = head.firstElementChild as HTMLElement | null; + const footerContent = foot.firstElementChild as HTMLElement | null; + + expect(head.style.visibility).toBe('visible'); + expect(headerContent?.textContent).toContain('Chapter 7'); + expect(headerContent?.style.color).toBe('rgb(17, 17, 17)'); + expect(headerContent?.children).toHaveLength(2); + expect(footerContent?.children).toHaveLength(2); + expect(footerContent?.textContent).toContain('2m left'); + expect(footerContent?.textContent).toContain('42%'); + }); + + it('renders multi-column header and footer content only on the outer columns', () => { + const leftHead = document.createElement('div'); + const rightHead = document.createElement('div'); + const leftFoot = document.createElement('div'); + const rightFoot = document.createElement('div'); + + PageDecorator.updateHeadersAndFooters( + {heads: [leftHead, rightHead], feet: [leftFoot, rightFoot]}, + 'Chapter 12', + {percentCompleted: 88, sectionTimeText: '45s'} + ); + + const leftHeaderContent = leftHead.firstElementChild as HTMLElement | null; + const rightHeaderContent = rightHead.firstElementChild as HTMLElement | null; + const leftFooterContent = leftFoot.firstElementChild as HTMLElement | null; + const rightFooterContent = rightFoot.firstElementChild as HTMLElement | null; + + expect(leftHeaderContent?.textContent).toContain('Chapter 12'); + expect(rightHeaderContent?.textContent).toBe(''); + + expect(leftFooterContent?.textContent).toContain('Time remaining in section: 45s'); + expect(leftFooterContent?.children).toHaveLength(2); + expect(rightFooterContent?.textContent).toContain('88%'); + expect(rightFooterContent?.children).toHaveLength(2); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/shared/icon.component.spec.ts b/frontend/src/app/features/readers/ebook-reader/shared/icon.component.spec.ts new file mode 100644 index 000000000..bea48699c --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/shared/icon.component.spec.ts @@ -0,0 +1,20 @@ +import {describe, expect, it} from 'vitest'; + +import {ReaderIconComponent} from './icon.component'; + +describe('ReaderIconComponent', () => { + it('exposes SVG path metadata for a known icon name', () => { + const component = new ReaderIconComponent(); + component.name = 'bookmark'; + + expect(component.paths.length).toBeGreaterThan(0); + expect(component.paths[0]?.d).toContain('M19 21'); + }); + + it('returns zero coordinates when the line descriptor is incomplete', () => { + const component = new ReaderIconComponent(); + + expect(component.getLineCoords('M3,6 L21,6', 0)).toBe('3'); + expect(component.getLineCoords('M3,6 L21,6', 10)).toBe('0'); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/shared/selection-popup.component.spec.ts b/frontend/src/app/features/readers/ebook-reader/shared/selection-popup.component.spec.ts new file mode 100644 index 000000000..a181ebc3b --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/shared/selection-popup.component.spec.ts @@ -0,0 +1,9 @@ +import {describe, expect, it} from 'vitest'; + +// TODO(seam): Selection popups depend on live DOM ranges, reader selection state, and +// annotation actions that should be tested against a mounted reader document. +describe.skip('SelectionPopupComponent', () => { + it('needs a mounted reader document to cover highlight, note, and dismiss branches', () => { + expect.hasAssertions(); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/shared/visibility.util.spec.ts b/frontend/src/app/features/readers/ebook-reader/shared/visibility.util.spec.ts new file mode 100644 index 000000000..cadc656b9 --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/shared/visibility.util.spec.ts @@ -0,0 +1,55 @@ +import {describe, expect, it, vi} from 'vitest'; + +import {ReaderHeaderFooterVisibilityManager} from './visibility.util'; + +describe('ReaderHeaderFooterVisibilityManager', () => { + it('shows and hides the header and footer based on pointer movement', () => { + const manager = new ReaderHeaderFooterVisibilityManager(1000); + const callback = vi.fn(); + manager.onStateChange(callback); + + expect(manager.getVisibilityState()).toEqual({headerVisible: false, footerVisible: false}); + + manager.handleMouseMove(5); + expect(manager.getVisibilityState()).toEqual({headerVisible: true, footerVisible: false}); + + manager.handleMouseMove(990); + expect(manager.getVisibilityState()).toEqual({headerVisible: false, footerVisible: true}); + + manager.handleMouseLeave(); + expect(manager.getVisibilityState()).toEqual({headerVisible: false, footerVisible: false}); + expect(callback).toHaveBeenCalled(); + }); + + it('keeps both zones visible while pinned', () => { + const manager = new ReaderHeaderFooterVisibilityManager(1000); + + manager.togglePinned(); + manager.handleMouseMove(500); + + expect(manager.getVisibilityState()).toEqual({headerVisible: true, footerVisible: true}); + + manager.handleMouseLeave(); + + expect(manager.getVisibilityState()).toEqual({headerVisible: true, footerVisible: true}); + }); + + it('shows each zone independently when the explicit enter handlers run', () => { + const manager = new ReaderHeaderFooterVisibilityManager(1000); + + manager.handleHeaderZoneEnter(); + expect(manager.getVisibilityState()).toEqual({headerVisible: true, footerVisible: false}); + + manager.handleFooterZoneEnter(); + expect(manager.getVisibilityState()).toEqual({headerVisible: true, footerVisible: true}); + }); + + it('uses the updated window height for the footer trigger zone', () => { + const manager = new ReaderHeaderFooterVisibilityManager(1000); + + manager.updateWindowHeight(200); + manager.handleMouseMove(175); + + expect(manager.getVisibilityState()).toEqual({headerVisible: false, footerVisible: true}); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/state/progress.service.spec.ts b/frontend/src/app/features/readers/ebook-reader/state/progress.service.spec.ts new file mode 100644 index 000000000..afe468eb3 --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/state/progress.service.spec.ts @@ -0,0 +1,248 @@ +import {TestBed} from '@angular/core/testing'; +import {describe, expect, it, beforeEach, afterEach, vi} from 'vitest'; + +import {ReaderProgressService} from './progress.service'; +import {ReaderStateService} from './reader-state.service'; +import {ReaderViewManagerService, type FoliateRenderer} from '../core/view-manager.service'; +import {ReaderAnnotationHttpService} from '../features/annotations/annotation.service'; +import {ReaderBookmarkService} from '../features/bookmarks/bookmark.service'; +import {BookPatchService} from '../../../book/service/book-patch.service'; +import {ReadingSessionService} from '../../../../shared/service/reading-session.service'; +import {TranslocoService} from '@jsverse/transloco'; + +describe('ReaderProgressService', () => { + const renderer: FoliateRenderer = { + heads: [], + feet: [], + getContents: vi.fn(() => []), + setAttribute: vi.fn(), + removeAttribute: vi.fn(), + }; + + const bookPatchService = { + saveEpubProgress: vi.fn(), + }; + + const readingSessionService = { + startSession: vi.fn(), + updateProgress: vi.fn(), + endSession: vi.fn(), + isSessionActive: vi.fn(() => true), + }; + + const viewManagerService = { + getRenderer: vi.fn<() => FoliateRenderer | null>(), + updateHeadersAndFooters: vi.fn(), + }; + + const stateService = { + state: vi.fn(() => ({ + flow: 'paginated', + theme: { + fg: '#111111', + bg: '#222222', + light: {fg: '#333333', bg: '#444444'}, + } + })), + }; + + const annotationService = { + updateCurrentChapter: vi.fn(), + }; + + const bookmarkService = { + updateCurrentPosition: vi.fn(), + }; + + const translocoService = { + translate: vi.fn(() => 'Time remaining in section: 1m 30s'), + }; + + let service: ReaderProgressService; + + beforeEach(() => { + bookPatchService.saveEpubProgress.mockReset(); + readingSessionService.startSession.mockReset(); + readingSessionService.updateProgress.mockReset(); + readingSessionService.endSession.mockReset(); + readingSessionService.isSessionActive.mockReset(); + readingSessionService.isSessionActive.mockReturnValue(true); + viewManagerService.getRenderer.mockReset(); + viewManagerService.getRenderer.mockReturnValue(renderer); + viewManagerService.updateHeadersAndFooters.mockReset(); + stateService.state.mockReset(); + annotationService.updateCurrentChapter.mockReset(); + bookmarkService.updateCurrentPosition.mockReset(); + translocoService.translate.mockReset(); + translocoService.translate.mockReturnValue('Time remaining in section: 1m 30s'); + + TestBed.configureTestingModule({ + providers: [ + ReaderProgressService, + {provide: BookPatchService, useValue: bookPatchService}, + {provide: ReadingSessionService, useValue: readingSessionService}, + {provide: ReaderViewManagerService, useValue: viewManagerService}, + {provide: ReaderStateService, useValue: stateService}, + {provide: ReaderAnnotationHttpService, useValue: annotationService}, + {provide: ReaderBookmarkService, useValue: bookmarkService}, + {provide: TranslocoService, useValue: translocoService}, + ] + }); + + service = TestBed.inject(ReaderProgressService); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('records relocate progress and updates reader services', () => { + const emissions: unknown[] = []; + service.progress$.subscribe(value => emissions.push(value)); + + service.initialize(17, 'EPUB', 23); + service.handleRelocateEvent({ + cfi: 'epubcfi(/6/2)', + fraction: 0.254, + pageItem: {href: 'chapter.xhtml'}, + tocItem: {label: 'Chapter 1', href: 'chapter.xhtml'}, + section: {current: 1, total: 10}, + time: {section: 90}, + }); + + expect(readingSessionService.startSession).toHaveBeenCalledWith(17, 'EPUB', 'epubcfi(/6/2)', 25.4); + expect(bookPatchService.saveEpubProgress).toHaveBeenCalledWith(17, 'epubcfi(/6/2)', 'chapter.xhtml', 25.4, 23); + expect(readingSessionService.updateProgress).toHaveBeenCalledWith('epubcfi(/6/2)', 25.4); + expect(annotationService.updateCurrentChapter).toHaveBeenCalledWith('Chapter 1'); + expect(bookmarkService.updateCurrentPosition).toHaveBeenCalledWith('epubcfi(/6/2)', 'Chapter 1'); + expect(viewManagerService.updateHeadersAndFooters).toHaveBeenCalledWith( + 'Chapter 1', + {percentCompleted: 25.4, sectionTimeText: '1h 30m'}, + {fg: '#111111', bg: '#222222'}, + 'Time remaining in section: 1m 30s' + ); + expect(emissions).toHaveLength(1); + expect(emissions[0]).toMatchObject({ + cfi: 'epubcfi(/6/2)', + href: 'chapter.xhtml', + chapterName: 'Chapter 1', + chapterHref: 'chapter.xhtml', + fraction: 0.254, + }); + }); + + it('ends an active session with rounded progress', () => { + service.initialize(17, 'EPUB'); + service.handleRelocateEvent({ + cfi: 'epubcfi(/6/2)', + fraction: 0.257, + tocItem: {label: 'Chapter 1', href: 'chapter.xhtml'}, + }); + + service.endSession(); + + expect(readingSessionService.endSession).toHaveBeenCalledWith('epubcfi(/6/2)', 25.7); + }); + + it('does not end a session when the reading session is inactive', () => { + readingSessionService.isSessionActive.mockReturnValue(false); + + service.endSession(); + + expect(readingSessionService.endSession).not.toHaveBeenCalled(); + }); + + it('skips header and footer updates when the reader is not in paginated flow', () => { + stateService.state.mockReturnValue({ + flow: 'scrolled', + theme: { + fg: '#111111', + bg: '#222222', + light: {fg: '#333333', bg: '#444444'}, + } + }); + + service.initialize(17, 'EPUB'); + service.handleRelocateEvent({ + cfi: 'epubcfi(/6/2)', + fraction: 0.2, + tocItem: {label: 'Chapter 1', href: 'chapter.xhtml'}, + section: {current: 1, total: 10}, + time: {section: 0.5}, + }); + + expect(viewManagerService.updateHeadersAndFooters).not.toHaveBeenCalled(); + }); + + it('does not persist progress when the relocate payload has no cfi', () => { + service.initialize(17, 'EPUB', 23); + + service.handleRelocateEvent({ + fraction: 0.2, + pageItem: {href: 'chapter.xhtml'}, + tocItem: {label: 'Chapter 1', href: 'chapter.xhtml'}, + }); + + expect(readingSessionService.startSession).not.toHaveBeenCalled(); + expect(bookPatchService.saveEpubProgress).not.toHaveBeenCalled(); + expect(readingSessionService.updateProgress).not.toHaveBeenCalled(); + expect(bookmarkService.updateCurrentPosition).not.toHaveBeenCalled(); + }); + + it('falls back to light theme colors when the active theme colors are blank', () => { + stateService.state.mockReturnValue({ + flow: 'paginated', + theme: { + fg: '', + bg: '', + light: {fg: '#aaaaaa', bg: '#bbbbbb'}, + } + }); + + service.initialize(17, 'EPUB'); + service.handleRelocateEvent({ + cfi: 'epubcfi(/6/2)', + fraction: 0.33, + tocItem: {label: 'Chapter 1', href: 'chapter.xhtml'}, + section: {current: 1, total: 10}, + time: {section: 0}, + }); + + expect(viewManagerService.updateHeadersAndFooters).toHaveBeenCalledWith( + 'Chapter 1', + {percentCompleted: 33, sectionTimeText: '0s'}, + {fg: '#aaaaaa', bg: '#bbbbbb'}, + 'Time remaining in section: 1m 30s' + ); + }); + + it('returns early when there is no renderer to update', () => { + viewManagerService.getRenderer.mockReturnValue(null); + service.initialize(17, 'EPUB'); + + service.handleRelocateEvent({ + tocItem: {label: 'Chapter 1', href: 'chapter.xhtml'}, + section: {current: 1, total: 10}, + time: {section: 1}, + }); + + expect(viewManagerService.updateHeadersAndFooters).not.toHaveBeenCalled(); + }); + + it('resets progress state back to nullish defaults', () => { + service.initialize(17, 'EPUB'); + service.handleRelocateEvent({ + cfi: 'epubcfi(/6/2)', + fraction: 0.1, + tocItem: {label: 'Chapter 1', href: 'chapter.xhtml'}, + }); + + service.reset(); + + expect(service.currentCfi).toBeNull(); + expect(service.currentChapterName).toBeNull(); + expect(service.currentChapterHref).toBeNull(); + expect(service.currentProgressData).toBeNull(); + expect(service.currentPageInfo).toBeUndefined(); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/state/reader-state.service.spec.ts b/frontend/src/app/features/readers/ebook-reader/state/reader-state.service.spec.ts new file mode 100644 index 000000000..bbf676eb9 --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/state/reader-state.service.spec.ts @@ -0,0 +1,190 @@ +import {TestBed} from '@angular/core/testing'; +import {of, firstValueFrom} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {BookService} from '../../../book/service/book.service'; +import {UserService} from '../../../settings/user-management/user.service'; +import {EpubCustomFontService} from '../features/fonts/custom-font.service'; +import {ReaderStateService} from './reader-state.service'; +import {themes} from './themes.constant'; + +describe('ReaderStateService', () => { + const customFonts = [ + {id: 2, fontName: 'Fancy Serif.otf', originalFileName: 'Fancy Serif.otf', format: 'OTF', fileSize: 1024, uploadedAt: '2026-03-26T00:00:00Z'}, + ]; + + const epubCustomFontService = { + getCustomFonts: vi.fn(() => customFonts), + }; + + const bookService = { + getBookSetting: vi.fn(), + }; + + const userService = { + getMyself: vi.fn(), + }; + + let service: ReaderStateService; + + beforeEach(() => { + bookService.getBookSetting.mockReset(); + userService.getMyself.mockReset(); + epubCustomFontService.getCustomFonts.mockReset(); + epubCustomFontService.getCustomFonts.mockReturnValue(customFonts); + + TestBed.configureTestingModule({ + providers: [ + ReaderStateService, + {provide: BookService, useValue: bookService}, + {provide: UserService, useValue: userService}, + {provide: EpubCustomFontService, useValue: epubCustomFontService}, + ] + }); + + service = TestBed.inject(ReaderStateService); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('loads custom fonts into the reader font list on construction and refresh', () => { + expect(service.fonts()).toContainEqual({name: 'Fancy Serif', value: 'custom:2'}); + + epubCustomFontService.getCustomFonts.mockReturnValue([ + {id: 8, fontName: 'Display Sans.woff2', originalFileName: 'Display Sans.woff2', format: 'WOFF2', fileSize: 2048, uploadedAt: '2026-03-26T00:00:00Z'}, + ]); + + service.refreshCustomFonts(); + + expect(service.fonts()).toContainEqual({name: 'Display Sans', value: 'custom:8'}); + expect(service.fonts()).not.toContainEqual({name: 'Fancy Serif', value: 'custom:2'}); + }); + + it('applies global reader settings from the user profile', async () => { + userService.getMyself.mockReturnValue(of({ + userSettings: { + perBookSetting: {epub: 'Global'}, + ebookReaderSetting: { + fontSize: 18, + lineHeight: 1.75, + fontFamily: '5', + gap: 0.75, + hyphenate: false, + justify: false, + maxColumnCount: 4, + maxInlineSize: 900, + maxBlockSize: 1800, + isDark: false, + flow: 'scrolled', + theme: 'gray', + } + } + })); + bookService.getBookSetting.mockReturnValue(of({ebookSettings: {fontSize: 22}})); + + await firstValueFrom(service.initializeState(11, 22)); + + const grayTheme = themes.find(theme => theme.name === 'gray'); + + expect(bookService.getBookSetting).toHaveBeenCalledWith(11, 22); + expect(service.state().fontSize).toBe(18); + expect(service.state().lineHeight).toBe(1.75); + expect(service.state().fontFamily).toBe('custom:5'); + expect(service.state().gap).toBe(0.5); + expect(service.state().hyphenate).toBe(false); + expect(service.state().justify).toBe(false); + expect(service.state().maxColumnCount).toBe(4); + expect(service.state().maxInlineSize).toBe(900); + expect(service.state().maxBlockSize).toBe(1800); + expect(service.state().isDark).toBe(false); + expect(service.state().flow).toBe('scrolled'); + expect(service.state().theme.name).toBe('gray'); + expect(service.state().theme.fg).toBe(grayTheme?.light.fg); + }); + + it('applies per-book settings and legacy custom font ids', async () => { + userService.getMyself.mockReturnValue(of({ + userSettings: { + perBookSetting: {epub: 'PerBook'}, + ebookReaderSetting: { + fontSize: 16, + lineHeight: 1.5, + gap: 0.05, + hyphenate: true, + justify: true, + maxColumnCount: 2, + maxInlineSize: 720, + maxBlockSize: 1440, + isDark: true, + flow: 'paginated', + theme: 'default', + } + } + })); + bookService.getBookSetting.mockReturnValue(of({ + ebookSettings: { + customFontId: 12, + fontSize: 20, + lineHeight: 2, + gap: 0.3, + hyphenate: false, + justify: false, + maxColumnCount: 3, + maxInlineSize: 800, + maxBlockSize: 1500, + isDark: true, + flow: 'paginated', + theme: 'ember', + } + })); + + await firstValueFrom(service.initializeState(8, 9)); + + const emberTheme = themes.find(theme => theme.name === 'ember'); + + expect(service.state().fontFamily).toBe('custom:12'); + expect(service.state().fontSize).toBe(20); + expect(service.state().lineHeight).toBe(2); + expect(service.state().gap).toBe(0.3); + expect(service.state().theme.name).toBe('ember'); + expect(service.state().theme.fg).toBe(emberTheme?.dark.fg); + }); + + it('supports the small state mutators and clamps values', () => { + service.updateLineHeight(-10); + service.updateMaxColumnCount(20); + service.updateGap(1); + service.toggleJustify(); + service.toggleHyphenate(); + service.updateFontSize(20); + service.updateMaxInlineSize(-500); + service.updateMaxBlockSize(2000); + service.setThemeByName('sepia'); + service.setFontFamily('12'); + service.toggleDarkMode(); + service.setFlow('scrolled'); + + expect(service.state().lineHeight).toBe(0.8); + expect(service.state().maxColumnCount).toBe(10); + expect(service.state().gap).toBe(0.5); + expect(service.state().justify).toBe(false); + expect(service.state().hyphenate).toBe(false); + expect(service.state().fontSize).toBe(32); + expect(service.state().maxInlineSize).toBe(400); + expect(service.state().maxBlockSize).toBe(2400); + expect(service.state().theme.name).toBe('sepia'); + expect(service.state().fontFamily).toBe('custom:12'); + expect(service.state().isDark).toBe(false); + expect(service.state().flow).toBe('scrolled'); + }); + + it('ignores unknown theme names', () => { + const initialTheme = service.state().theme; + + service.setThemeByName('does-not-exist'); + + expect(service.state().theme).toEqual(initialTheme); + }); +}); diff --git a/frontend/src/app/features/readers/ebook-reader/state/themes.constant.spec.ts b/frontend/src/app/features/readers/ebook-reader/state/themes.constant.spec.ts new file mode 100644 index 000000000..2eadd87bf --- /dev/null +++ b/frontend/src/app/features/readers/ebook-reader/state/themes.constant.spec.ts @@ -0,0 +1,32 @@ +import {describe, expect, it} from 'vitest'; + +import {themes, Theme} from './themes.constant'; + +describe('themes.constant', () => { + it('defines unique theme names', () => { + const names = themes.map((theme) => theme.name); + expect(new Set(names).size).toBe(names.length); + }); + + it('includes the expected default and amoled themes', () => { + expect(themes.find((theme) => theme.name === 'default')?.label).toBe('Default'); + expect(themes.find((theme) => theme.name === 'amoled')?.dark.bg).toBe('#000000'); + }); + + it('provides light and dark palettes with link colors for every theme', () => { + for (const theme of themes) { + expect(theme).toMatchObject>({ + light: expect.objectContaining({ + fg: expect.any(String), + bg: expect.any(String), + link: expect.any(String) + }), + dark: expect.objectContaining({ + fg: expect.any(String), + bg: expect.any(String), + link: expect.any(String) + }) + }); + } + }); +}); diff --git a/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.spec.ts b/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.spec.ts new file mode 100644 index 000000000..8e7fd9259 --- /dev/null +++ b/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around ngx-extended-pdf-viewer, +// reader-session lifecycle, route-driven book loading, and annotation persistence so the +// component can be tested without booting the full PDF runtime and browser document hooks. +describe.skip('PdfReaderComponent', () => { + it('needs a viewer-runtime seam to verify page, zoom, spread, and annotation flows deterministically', () => { + // TODO(seam): Cover load, navigation, and annotation persistence after wrapping the PDF viewer and reader-session integrations. + }); + + it('needs a route-and-session seam to verify startup and teardown side effects without real browser navigation', () => { + // TODO(seam): Cover session start/end and progress persistence once route/book-detail dependencies are injectable test adapters. + }); +}); diff --git a/frontend/src/app/features/series-browser/components/series-browser/series-browser.component.spec.ts b/frontend/src/app/features/series-browser/components/series-browser/series-browser.component.spec.ts new file mode 100644 index 000000000..d4291cd47 --- /dev/null +++ b/frontend/src/app/features/series-browser/components/series-browser/series-browser.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around virtual-scroller rendering, page +// title initialization, and signal-driven search and filter state so the series browser can be +// tested without mounting the full browser shell. +describe.skip('SeriesBrowserComponent', () => { + it('needs filter seams to verify search, status filtering, and sort ordering across the derived series list', () => { + // TODO(seam): Cover applyStatusFilter and applySort once the series-data and book-service signals are isolated behind test doubles. + }); + + it('needs browser-shell seams to verify responsive card sizing, route navigation, and page-title behavior', () => { + // TODO(seam): Cover ngOnInit and navigateToSeries after extracting router and virtual-scroller concerns behind adapters. + }); +}); diff --git a/frontend/src/app/features/series-browser/components/series-card/series-card.component.spec.ts b/frontend/src/app/features/series-browser/components/series-card/series-card.component.spec.ts new file mode 100644 index 000000000..ad20a89be --- /dev/null +++ b/frontend/src/app/features/series-browser/components/series-card/series-card.component.spec.ts @@ -0,0 +1,123 @@ +import {NO_ERRORS_SCHEMA} from '@angular/core'; +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {getTranslocoModule} from '../../../../core/testing/transloco-testing'; +import {Book} from '../../../book/model/book.model'; +import {ReadStatus} from '../../../book/model/book.model'; +import {BookService} from '../../../book/service/book.service'; +import {UrlHelperService} from '../../../../shared/service/url-helper.service'; +import {SeriesSummary} from '../../model/series.model'; +import {SeriesCardComponent} from './series-card.component'; + +function makeBook(id: number, bookType: Book['primaryFile'] extends infer T ? T extends {bookType?: infer U} ? U : never : never = 'EPUB'): Book { + return { + id, + libraryId: 1, + libraryName: 'Library', + primaryFile: { + id, + bookId: id, + bookType, + }, + metadata: { + bookId: id, + title: `Book ${id}`, + coverUpdatedOn: '2026-03-01', + audiobookCoverUpdatedOn: '2026-03-02', + }, + }; +} + +function makeSeries(overrides: Partial = {}): SeriesSummary { + return { + seriesName: 'Dune', + books: [], + authors: ['Frank Herbert', 'Brian Herbert', 'Kevin J. Anderson'], + categories: ['Sci-Fi'], + bookCount: 4, + readCount: 2, + progress: 0.48, + seriesStatus: ReadStatus.READING, + nextUnread: makeBook(11), + lastReadTime: null, + coverBooks: [makeBook(1), makeBook(2, 'AUDIOBOOK')], + addedOn: null, + ...overrides, + }; +} + +describe('SeriesCardComponent', () => { + let fixture: ComponentFixture; + let component: SeriesCardComponent; + let bookService: {readBook: ReturnType}; + let urlHelper: { + getThumbnailUrl: ReturnType; + getAudiobookThumbnailUrl: ReturnType; + }; + + beforeEach(async () => { + bookService = { + readBook: vi.fn(), + }; + urlHelper = { + getThumbnailUrl: vi.fn((bookId: number, updatedOn?: string) => `thumb:${bookId}:${updatedOn ?? 'none'}`), + getAudiobookThumbnailUrl: vi.fn((bookId: number, updatedOn?: string) => `audio:${bookId}:${updatedOn ?? 'none'}`), + }; + + await TestBed.configureTestingModule({ + imports: [SeriesCardComponent, getTranslocoModule()], + providers: [ + {provide: BookService, useValue: bookService}, + {provide: UrlHelperService, useValue: urlHelper}, + ], + schemas: [NO_ERRORS_SCHEMA], + }).compileComponents(); + + fixture = TestBed.createComponent(SeriesCardComponent); + component = fixture.componentInstance; + component.series = makeSeries(); + fixture.detectChanges(); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('derives progress and author summaries for compact display', () => { + expect(component.progressPercent).toBe(48); + expect(component.authorsDisplay).toBe('Frank Herbert, Brian Herbert +1'); + }); + + it('builds thumbnail URLs from ebook and audiobook covers', () => { + expect(component.getCoverUrl(0)).toBe('thumb:1:2026-03-01'); + expect(component.getCoverUrl(1)).toBe('audio:2:2026-03-02'); + expect(component.getCoverUrl(99)).toBe(''); + }); + + it('emits a card click and stops propagation', () => { + const emitSpy = vi.spyOn(component.cardClick, 'emit'); + const event = {stopPropagation: vi.fn()} as unknown as Event; + + component.onCardClick(event); + + expect(event.stopPropagation).toHaveBeenCalled(); + expect(emitSpy).toHaveBeenCalledWith(component.series); + }); + + it('reads the next unread book when present', () => { + const event = {stopPropagation: vi.fn()} as unknown as MouseEvent; + + component.readNext(event); + + expect(event.stopPropagation).toHaveBeenCalled(); + expect(bookService.readBook).toHaveBeenCalledWith(11); + }); + + it('renders the series name and progress label', () => { + const text = fixture.nativeElement.textContent as string; + expect(text).toContain('Dune'); + expect(text).toContain('2/4'); + }); +}); diff --git a/frontend/src/app/features/series-browser/components/series-scroller/series-scroller.component.spec.ts b/frontend/src/app/features/series-browser/components/series-scroller/series-scroller.component.spec.ts new file mode 100644 index 000000000..7c1df2a2b --- /dev/null +++ b/frontend/src/app/features/series-browser/components/series-scroller/series-scroller.component.spec.ts @@ -0,0 +1,10 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here is blocked by the current template binding `[compact]="true"` +// into `app-series-card` even though `SeriesCardComponent` does not expose that input. Until the +// runtime surface is corrected, importing this component in a spec fails Angular template compilation. +describe.skip('SeriesScrollerComponent', () => { + it('needs the template/input contract corrected before empty-state and series-click rendering can be covered', () => { + // TODO(seam): Cover title rendering, empty state, and card click forwarding once the card input contract is valid. + }); +}); diff --git a/frontend/src/app/features/series-browser/model/series.model.spec.ts b/frontend/src/app/features/series-browser/model/series.model.spec.ts new file mode 100644 index 000000000..b84bb37ae --- /dev/null +++ b/frontend/src/app/features/series-browser/model/series.model.spec.ts @@ -0,0 +1,27 @@ +import {describe, expect, expectTypeOf, it} from 'vitest'; + +import {ReadStatus} from '../../book/model/book.model'; +import {SeriesSummary} from './series.model'; + +describe('series.model', () => { + it('supports summary state for a series browser entry', () => { + const summary: SeriesSummary = { + seriesName: 'Earthsea', + books: [], + authors: ['Ursula K. Le Guin'], + categories: ['Fantasy'], + bookCount: 6, + readCount: 4, + progress: 66, + seriesStatus: ReadStatus.READING, + nextUnread: null, + lastReadTime: null, + coverBooks: [], + addedOn: '2026-03-01' + }; + + expect(summary.seriesStatus).toBe(ReadStatus.READING); + expect(summary.authors[0]).toContain('Le Guin'); + expectTypeOf(summary.nextUnread).toEqualTypeOf(); + }); +}); diff --git a/frontend/src/app/features/series-browser/service/series-data.service.spec.ts b/frontend/src/app/features/series-browser/service/series-data.service.spec.ts new file mode 100644 index 000000000..05b6f122e --- /dev/null +++ b/frontend/src/app/features/series-browser/service/series-data.service.spec.ts @@ -0,0 +1,156 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, describe, expect, it} from 'vitest'; + +import {BookService} from '../../book/service/book.service'; +import {ReadStatus, type Book} from '../../book/model/book.model'; +import {SeriesDataService} from './series-data.service'; + +function makeBook(partial: Partial & Pick): Book { + return { + ...partial, + libraryId: partial.libraryId, + libraryName: partial.libraryName, + } as Book; +} + +describe('SeriesDataService', () => { + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('groups books by normalized series name and derives summary fields', () => { + const books = signal([ + makeBook({ + id: 1, + libraryId: 1, + libraryName: 'Lib', + readStatus: ReadStatus.UNREAD, + metadata: { + bookId: 1, + seriesName: ' Alpha ', + seriesNumber: 2, + authors: ['Ada', 'Bert'], + categories: ['Sci-Fi'], + }, + lastReadTime: '2026-03-25T10:00:00Z', + addedOn: '2026-03-25T09:00:00Z', + }), + makeBook({ + id: 2, + libraryId: 1, + libraryName: 'Lib', + readStatus: ReadStatus.READ, + metadata: { + bookId: 2, + seriesName: 'alpha', + seriesNumber: 1, + authors: ['Bert', 'Cy'], + categories: ['Fantasy', 'Sci-Fi'], + }, + lastReadTime: '2026-03-26T10:00:00Z', + addedOn: '2026-03-26T09:00:00Z', + }), + ]); + + TestBed.configureTestingModule({ + providers: [ + SeriesDataService, + {provide: BookService, useValue: {books: books.asReadonly()}}, + ], + }); + + const service = TestBed.inject(SeriesDataService); + const summaries = service.allSeries(); + + expect(summaries).toHaveLength(1); + expect(summaries[0]).toMatchObject({ + seriesName: 'alpha', + bookCount: 2, + readCount: 1, + progress: 0.5, + seriesStatus: ReadStatus.PARTIALLY_READ, + lastReadTime: '2026-03-26T10:00:00Z', + addedOn: '2026-03-26T09:00:00Z', + }); + expect(summaries[0].books.map(book => book.id)).toEqual([2, 1]); + expect(summaries[0].authors).toEqual(['Bert', 'Cy', 'Ada']); + expect(summaries[0].categories).toEqual(['Fantasy', 'Sci-Fi']); + expect(summaries[0].nextUnread?.id).toBe(1); + expect(summaries[0].coverBooks.map(book => book.id)).toEqual([2, 1]); + }); + + it('skips books without a series and honors series status precedence', () => { + const books = signal([ + makeBook({id: 10, libraryId: 1, libraryName: 'Lib', metadata: {bookId: 10}}), + makeBook({ + id: 11, + libraryId: 1, + libraryName: 'Lib', + readStatus: ReadStatus.WONT_READ, + metadata: {bookId: 11, seriesName: 'Wont Read'}, + }), + makeBook({ + id: 12, + libraryId: 1, + libraryName: 'Lib', + readStatus: ReadStatus.ABANDONED, + metadata: {bookId: 12, seriesName: 'Abandoned'}, + }), + makeBook({ + id: 13, + libraryId: 1, + libraryName: 'Lib', + readStatus: ReadStatus.READ, + metadata: {bookId: 13, seriesName: 'Read'}, + }), + makeBook({ + id: 14, + libraryId: 1, + libraryName: 'Lib', + readStatus: ReadStatus.READING, + metadata: {bookId: 14, seriesName: 'Reading'}, + }), + makeBook({ + id: 15, + libraryId: 1, + libraryName: 'Lib', + readStatus: ReadStatus.READ, + metadata: {bookId: 15, seriesName: 'Partial'}, + }), + makeBook({ + id: 16, + libraryId: 1, + libraryName: 'Lib', + readStatus: ReadStatus.UNREAD, + metadata: {bookId: 16, seriesName: 'Partial'}, + }), + makeBook({ + id: 17, + libraryId: 1, + libraryName: 'Lib', + readStatus: ReadStatus.UNREAD, + metadata: {bookId: 17, seriesName: 'Unread'}, + }), + ]); + + TestBed.configureTestingModule({ + providers: [ + SeriesDataService, + {provide: BookService, useValue: {books: books.asReadonly()}}, + ], + }); + + const service = TestBed.inject(SeriesDataService); + const summaries = Object.fromEntries(service.allSeries().map(summary => [summary.seriesName, summary.seriesStatus])); + + expect(summaries).toEqual({ + 'Wont Read': ReadStatus.WONT_READ, + 'Abandoned': ReadStatus.ABANDONED, + 'Read': ReadStatus.READ, + 'Reading': ReadStatus.READING, + 'Partial': ReadStatus.PARTIALLY_READ, + 'Unread': ReadStatus.UNREAD, + }); + }); +}); diff --git a/frontend/src/app/features/series-browser/service/series-scale-preference.service.spec.ts b/frontend/src/app/features/series-browser/service/series-scale-preference.service.spec.ts new file mode 100644 index 000000000..79aad66e2 --- /dev/null +++ b/frontend/src/app/features/series-browser/service/series-scale-preference.service.spec.ts @@ -0,0 +1,63 @@ +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {LocalStorageService} from '../../../shared/service/local-storage.service'; +import {SeriesScalePreferenceService} from './series-scale-preference.service'; + +describe('SeriesScalePreferenceService', () => { + const localStorageService = { + get: vi.fn(), + set: vi.fn(), + }; + + beforeEach(() => { + vi.useFakeTimers(); + vi.restoreAllMocks(); + localStorageService.get.mockReset(); + localStorageService.set.mockReset(); + localStorageService.get.mockReturnValue(0.75); + + TestBed.configureTestingModule({ + providers: [ + SeriesScalePreferenceService, + {provide: LocalStorageService, useValue: localStorageService}, + ], + }); + }); + + afterEach(() => { + vi.useRealTimers(); + TestBed.resetTestingModule(); + }); + + it('loads the persisted scale and does not persist unchanged values', () => { + const service = TestBed.inject(SeriesScalePreferenceService); + + expect(service.scaleFactor()).toBe(0.75); + + service.setScale(0.75); + vi.runAllTimers(); + + expect(localStorageService.set).not.toHaveBeenCalled(); + }); + + it('debounces and persists the most recent scale value', () => { + const service = TestBed.inject(SeriesScalePreferenceService); + + service.setScale(0.9); + service.setScale(1.1); + + vi.advanceTimersByTime(1000); + + expect(localStorageService.set).toHaveBeenCalledOnce(); + expect(localStorageService.set).toHaveBeenCalledWith('seriesScalePreference', 1.1); + }); + + it('falls back to the default scale when storage contains an invalid value', () => { + localStorageService.get.mockReturnValue(undefined); + + const service = TestBed.inject(SeriesScalePreferenceService); + + expect(service.scaleFactor()).toBe(1); + }); +}); diff --git a/frontend/src/app/features/settings/audit-logs/audit-log.service.spec.ts b/frontend/src/app/features/settings/audit-logs/audit-log.service.spec.ts new file mode 100644 index 000000000..317a667f9 --- /dev/null +++ b/frontend/src/app/features/settings/audit-logs/audit-log.service.spec.ts @@ -0,0 +1,94 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {AuditLog, AuditLogService, PageableResponse} from './audit-log.service'; + +describe('AuditLogService', () => { + let service: AuditLogService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + AuditLogService, + ], + }); + + service = TestBed.inject(AuditLogService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('requests paged audit logs with the default pagination', () => { + const response: PageableResponse = { + content: [], + page: { + totalElements: 0, + totalPages: 0, + number: 0, + size: 25, + }, + }; + + let result: PageableResponse | undefined; + service.getAuditLogs().subscribe(value => { + result = value; + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/audit-logs')); + expect(request.request.method).toBe('GET'); + expect(request.request.params.get('page')).toBe('0'); + expect(request.request.params.get('size')).toBe('25'); + expect(request.request.params.has('action')).toBe(false); + expect(request.request.params.has('username')).toBe(false); + expect(request.request.params.has('from')).toBe(false); + expect(request.request.params.has('to')).toBe(false); + request.flush(response); + + expect(result).toEqual(response); + }); + + it('includes optional filters when they are provided', () => { + service.getAuditLogs(2, 50, 'DELETE', 'alice', '2026-01-01', '2026-01-31').subscribe(); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/audit-logs')); + expect(request.request.params.get('page')).toBe('2'); + expect(request.request.params.get('size')).toBe('50'); + expect(request.request.params.get('action')).toBe('DELETE'); + expect(request.request.params.get('username')).toBe('alice'); + expect(request.request.params.get('from')).toBe('2026-01-01'); + expect(request.request.params.get('to')).toBe('2026-01-31'); + request.flush({ + content: [], + page: { + totalElements: 0, + totalPages: 0, + number: 2, + size: 50, + }, + } satisfies PageableResponse); + }); + + it('requests distinct usernames from the dedicated endpoint', () => { + const response = ['alice', 'bob']; + + let result: string[] | undefined; + service.getDistinctUsernames().subscribe(value => { + result = value; + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/audit-logs/usernames')); + expect(request.request.method).toBe('GET'); + request.flush(response); + + expect(result).toEqual(response); + }); +}); diff --git a/frontend/src/app/features/settings/audit-logs/audit-logs.component.spec.ts b/frontend/src/app/features/settings/audit-logs/audit-logs.component.spec.ts new file mode 100644 index 000000000..590578442 --- /dev/null +++ b/frontend/src/app/features/settings/audit-logs/audit-logs.component.spec.ts @@ -0,0 +1,10 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around route query-param restoration, +// Prime table lazy-load events, interval-based auto-refresh, and router writes so the audit log +// page can be exercised without a brittle integration harness for timers and navigation state. +describe.skip('AuditLogsComponent', () => { + it('needs route and timer seams to verify filter restoration, pagination, and auto-refresh behavior', () => { + // TODO(seam): Cover query-param sync, table lazy loading, and interval refresh once route/timer dependencies are isolated. + }); +}); diff --git a/frontend/src/app/features/settings/custom-fonts/custom-fonts.component.spec.ts b/frontend/src/app/features/settings/custom-fonts/custom-fonts.component.spec.ts new file mode 100644 index 000000000..eb2f407c3 --- /dev/null +++ b/frontend/src/app/features/settings/custom-fonts/custom-fonts.component.spec.ts @@ -0,0 +1,16 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): This component orchestrates async font discovery/loading, dialog-driven +// uploads, confirmation flows, browser font registration, and toast reporting. Real coverage +// needs a dedicated font-runtime seam around `CustomFontService` and the dialog/confirm stack. +describe.skip('CustomFontsComponent', () => { + it('needs a custom-font runtime seam to verify load success vs failure and browser font readiness', () => { + // TODO(seam): Cover ensureFonts/loadAllFonts success and failure paths once browser-font + // registration is exposed behind a stable service seam. + }); + + it('needs a dialog-confirm seam to verify quota checks, upload additions, and delete flows', () => { + // TODO(seam): Cover upload dialog close handling and confirmed delete behavior after the + // dialog/confirmation interactions can be driven without full PrimeNG runtime wiring. + }); +}); diff --git a/frontend/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.spec.ts b/frontend/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.spec.ts new file mode 100644 index 000000000..dd7a67f73 --- /dev/null +++ b/frontend/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.spec.ts @@ -0,0 +1,10 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs browser seams around `document.fonts`, `FontFace`, +// drag-and-drop file objects, and the DynamicDialog upload lifecycle so preview cancellation and +// upload teardown can be asserted without depending on DOM font APIs that Vitest does not provide. +describe.skip('FontUploadDialogComponent', () => { + it('needs a font-preview seam to verify preview cleanup, drag-drop handling, and upload completion deterministically', () => { + // TODO(seam): Cover preview token cancellation and dialog close behavior once font loading is wrapped in an injectable adapter. + }); +}); diff --git a/frontend/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-settings-component.spec.ts b/frontend/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-settings-component.spec.ts new file mode 100644 index 000000000..f43fcab31 --- /dev/null +++ b/frontend/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-settings-component.spec.ts @@ -0,0 +1,9 @@ +import {describe, expect, it} from 'vitest'; + +// TODO(seam): This component mixes permission-driven effects, clipboard access, PrimeNG +// toast wiring, and service persistence, so it needs a mounted settings harness. +describe.skip('HardcoverSettingsComponent', () => { + it('needs a mounted settings harness for permission hydration, save, and clipboard flows', () => { + expect.hasAssertions(); + }); +}); diff --git a/frontend/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-sync-settings.service.spec.ts b/frontend/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-sync-settings.service.spec.ts new file mode 100644 index 000000000..cd7784318 --- /dev/null +++ b/frontend/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-sync-settings.service.spec.ts @@ -0,0 +1,65 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {HardcoverSyncSettingsService} from './hardcover-sync-settings.service'; + +describe('HardcoverSyncSettingsService', () => { + let service: HardcoverSyncSettingsService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + HardcoverSyncSettingsService, + ], + }); + + service = TestBed.inject(HardcoverSyncSettingsService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('loads the saved hardcover sync settings', () => { + let responseBody: unknown; + + service.getSettings().subscribe(response => { + responseBody = response; + }); + + const request = httpTestingController.expectOne(req => + req.method === 'GET' && req.url.endsWith('/api/v1/hardcover-sync-settings') + ); + request.flush({ + hardcoverApiKey: 'hardcover-key', + hardcoverSyncEnabled: true, + }); + + expect(responseBody).toEqual({ + hardcoverApiKey: 'hardcover-key', + hardcoverSyncEnabled: true, + }); + }); + + it('persists updated hardcover sync settings', () => { + const payload = { + hardcoverApiKey: 'next-key', + hardcoverSyncEnabled: false, + }; + + service.updateSettings(payload).subscribe(); + + const request = httpTestingController.expectOne(req => + req.method === 'PUT' && req.url.endsWith('/api/v1/hardcover-sync-settings') + ); + expect(request.request.body).toEqual(payload); + request.flush(payload); + }); +}); diff --git a/frontend/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo-sync-settings-component.spec.ts b/frontend/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo-sync-settings-component.spec.ts new file mode 100644 index 000000000..5bada5b50 --- /dev/null +++ b/frontend/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo-sync-settings-component.spec.ts @@ -0,0 +1,9 @@ +import {describe, expect, it} from 'vitest'; + +// TODO(seam): Kobo settings rely on user-permission effects, debounced slider saves, +// confirm-dialog callbacks, clipboard access, and app-setting persistence. +describe.skip('KoboSyncSettingsComponent', () => { + it('needs a mounted settings harness for slider debounce, token regeneration, and save flows', () => { + expect.hasAssertions(); + }); +}); diff --git a/frontend/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo.service.spec.ts b/frontend/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo.service.spec.ts new file mode 100644 index 000000000..f913ae005 --- /dev/null +++ b/frontend/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo.service.spec.ts @@ -0,0 +1,88 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {KoboService} from './kobo.service'; + +describe('KoboService', () => { + let service: KoboService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + KoboService, + ], + }); + + service = TestBed.inject(KoboService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('loads the current kobo sync settings', () => { + let responseBody: unknown; + + service.getUser().subscribe(response => { + responseBody = response; + }); + + const request = httpTestingController.expectOne(req => + req.method === 'GET' && req.url.endsWith('/api/v1/kobo-settings') + ); + request.flush({ + token: 'abc123', + syncEnabled: true, + autoAddToShelf: false, + twoWayProgressSync: true, + }); + + expect(responseBody).toEqual({ + token: 'abc123', + syncEnabled: true, + autoAddToShelf: false, + twoWayProgressSync: true, + }); + }); + + it('creates or refreshes the kobo token through the token endpoint', () => { + service.createOrUpdateToken().subscribe(); + + const request = httpTestingController.expectOne(req => + req.method === 'PUT' && req.url.endsWith('/api/v1/kobo-settings/token') + ); + expect(request.request.body).toBeNull(); + request.flush({ + token: 'new-token', + syncEnabled: false, + autoAddToShelf: true, + twoWayProgressSync: false, + }); + }); + + it('persists updated kobo settings with a PUT request', () => { + const payload = { + token: 'abc123', + syncEnabled: true, + autoAddToShelf: true, + twoWayProgressSync: false, + progressMarkAsReadingThreshold: 25, + progressMarkAsFinishedThreshold: 95, + }; + + service.updateSettings(payload).subscribe(); + + const request = httpTestingController.expectOne(req => + req.method === 'PUT' && req.url.endsWith('/api/v1/kobo-settings') + ); + expect(request.request.body).toEqual(payload); + request.flush(payload); + }); +}); diff --git a/frontend/src/app/features/settings/device-settings/component/koreader-settings/koreader-settings-component.spec.ts b/frontend/src/app/features/settings/device-settings/component/koreader-settings/koreader-settings-component.spec.ts new file mode 100644 index 000000000..c4c530e7d --- /dev/null +++ b/frontend/src/app/features/settings/device-settings/component/koreader-settings/koreader-settings-component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around effect-driven permission hydration, +// clipboard/browser globals, and message-service side effects so credential save, toggle, and +// copy flows can be asserted without mounting the full KOReader settings runtime. +describe.skip('KoreaderSettingsComponent', () => { + it('needs permission seams to verify initial settings load and edit/save transitions', () => { + // TODO(seam): Cover permission-gated loadKoreaderSettings and onEditSave once the current-user signal and side-effect services are isolated behind deterministic doubles. + }); + + it('needs browser seams to verify sync toggles, copy-to-clipboard success, and error reporting', () => { + // TODO(seam): Cover toggle and copyText flows after navigator.clipboard, window.location, and toast dispatch are extracted into testable adapters. + }); +}); diff --git a/frontend/src/app/features/settings/device-settings/component/koreader-settings/koreader.service.spec.ts b/frontend/src/app/features/settings/device-settings/component/koreader-settings/koreader.service.spec.ts new file mode 100644 index 000000000..17ee51fc3 --- /dev/null +++ b/frontend/src/app/features/settings/device-settings/component/koreader-settings/koreader.service.spec.ts @@ -0,0 +1,115 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {KoreaderService} from './koreader.service'; + +describe('KoreaderService', () => { + let service: KoreaderService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + KoreaderService, + ], + }); + + service = TestBed.inject(KoreaderService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('creates a KOReader user with the expected payload', () => { + let responseBody: unknown; + + service.createUser('reader', 'secret123').subscribe(response => { + responseBody = response; + }); + + const request = httpTestingController.expectOne(req => + req.method === 'PUT' && req.url.endsWith('/api/v1/koreader-users/me') + ); + expect(request.request.body).toEqual({ + username: 'reader', + password: 'secret123', + }); + + request.flush({ + username: 'reader', + password: 'secret123', + syncEnabled: true, + }); + + expect(responseBody).toEqual({ + username: 'reader', + password: 'secret123', + syncEnabled: true, + }); + }); + + it('loads the current KOReader user from the profile endpoint', () => { + let responseBody: unknown; + + service.getUser().subscribe(response => { + responseBody = response; + }); + + const request = httpTestingController.expectOne(req => + req.method === 'GET' && req.url.endsWith('/api/v1/koreader-users/me') + ); + request.flush({ + username: 'reader', + password: 'secret123', + syncEnabled: false, + syncWithGrimmoryReader: true, + }); + + expect(responseBody).toEqual({ + username: 'reader', + password: 'secret123', + syncEnabled: false, + syncWithGrimmoryReader: true, + }); + }); + + it('patches the sync-enabled flag using the enabled query parameter', () => { + service.toggleSync(true).subscribe(); + + const request = httpTestingController.expectOne(req => + req.method === 'PATCH' && req.url.endsWith('/api/v1/koreader-users/me/sync') + ); + expect(request.request.params.get('enabled')).toBe('true'); + expect(request.request.body).toBeNull(); + request.flush(null); + }); + + it('uses the Grimmory sync-progress endpoint before falling back to the legacy Booklore route', () => { + let completed = false; + + service.toggleSyncProgressWithGrimmoryReader(false).subscribe(() => { + completed = true; + }); + + const grimmoryRequest = httpTestingController.expectOne(req => + req.method === 'PATCH' && req.url.endsWith('/api/v1/koreader-users/me/sync-progress-with-grimmory') + ); + expect(grimmoryRequest.request.params.get('enabled')).toBe('false'); + grimmoryRequest.flush('missing route', {status: 404, statusText: 'Not Found'}); + + const legacyRequest = httpTestingController.expectOne(req => + req.method === 'PATCH' && req.url.endsWith('/api/v1/koreader-users/me/sync-progress-with-booklore') + ); + expect(legacyRequest.request.params.get('enabled')).toBe('false'); + legacyRequest.flush(null); + + expect(completed).toBe(true); + }); +}); diff --git a/frontend/src/app/features/settings/device-settings/device-settings-component.spec.ts b/frontend/src/app/features/settings/device-settings/device-settings-component.spec.ts new file mode 100644 index 000000000..a45d2ae92 --- /dev/null +++ b/frontend/src/app/features/settings/device-settings/device-settings-component.spec.ts @@ -0,0 +1,10 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around the nested device-settings shell and +// child standalone panels so device preference composition can be asserted without the full +// settings page runtime. +describe.skip('DeviceSettingsComponent', () => { + it('needs composition seams to verify KOReader, email, and send-to-device panel inclusion', () => { + // TODO(seam): Cover child-panel composition after the shell template is isolated from the broader settings runtime and its lazy imports. + }); +}); diff --git a/frontend/src/app/features/settings/email-v2/create-email-provider-dialog/create-email-provider-dialog.component.spec.ts b/frontend/src/app/features/settings/email-v2/create-email-provider-dialog/create-email-provider-dialog.component.spec.ts new file mode 100644 index 000000000..7ecffc6de --- /dev/null +++ b/frontend/src/app/features/settings/email-v2/create-email-provider-dialog/create-email-provider-dialog.component.spec.ts @@ -0,0 +1,215 @@ +import {TestBed} from '@angular/core/testing'; +import {ReactiveFormsModule} from '@angular/forms'; +import {TranslocoService} from '@jsverse/transloco'; +import {of, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import { + createDynamicDialogHarness, + createMessageServiceProvider, + createMessageServiceSpy, +} from '../../../../core/testing/dialog-testing'; +import {EmailV2ProviderService} from '../email-v2-provider/email-v2-provider.service'; +import {CreateEmailProviderDialogComponent} from './create-email-provider-dialog.component'; + +describe('CreateEmailProviderDialogComponent', () => { + let createEmailProvider: ReturnType; + let dialogHarness: ReturnType>; + let messageService: ReturnType; + let translate: TranslocoService['translate']; + + beforeEach(() => { + createEmailProvider = vi.fn(() => of({ + id: 9, + name: 'Primary SMTP', + host: 'smtp.example.com', + port: 587, + username: 'mailer', + password: 'secret', + fromAddress: 'mailer@example.com', + auth: true, + startTls: true, + })); + dialogHarness = createDynamicDialogHarness(null); + messageService = createMessageServiceSpy(); + translate = ((key: string, params?: Record) => { + if (!params) { + return `translated:${key}` as T; + } + + return `translated:${key}:${JSON.stringify(params)}` as T; + }) as TranslocoService['translate']; + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + function createComponent() { + TestBed.configureTestingModule({ + imports: [ReactiveFormsModule], + providers: [ + ...dialogHarness.providers, + { + provide: EmailV2ProviderService, + useValue: { + createEmailProvider, + }, + }, + createMessageServiceProvider(messageService), + { + provide: TranslocoService, + useValue: { + translate, + }, + }, + ], + }); + + const component = TestBed.runInInjectionContext(() => new CreateEmailProviderDialogComponent()); + component.ngOnInit(); + return component; + } + + it('initializes the reactive form with the expected defaults and validators', () => { + const component = createComponent(); + + expect(component.emailProviderForm.getRawValue()).toEqual({ + name: '', + host: '', + port: null, + username: '', + password: '', + fromAddress: '', + auth: false, + startTls: false, + }); + + component.emailProviderForm.patchValue({ + name: 'ab', + host: '', + port: 0, + fromAddress: 'not-an-email', + }); + + expect(component.emailProviderForm.invalid).toBe(true); + expect(component.emailProviderForm.controls['name'].hasError('minlength')).toBe(true); + expect(component.emailProviderForm.controls['host'].hasError('required')).toBe(true); + expect(component.emailProviderForm.controls['port'].hasError('min')).toBe(true); + expect(component.emailProviderForm.controls['fromAddress'].hasError('email')).toBe(true); + }); + + it('shows a warning toast and skips the mutation when the form is invalid', () => { + const component = createComponent(); + component.emailProviderForm.patchValue({ + name: 'ab', + host: 'smtp.example.com', + port: 587, + }); + + component.createEmailProvider(); + + expect(createEmailProvider).not.toHaveBeenCalled(); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'warn', + summary: 'translated:settingsEmail.provider.create.validationError', + detail: 'translated:settingsEmail.provider.create.validationErrorDetail', + }); + expect(dialogHarness.dialogRef.close).not.toHaveBeenCalled(); + }); + + it('submits the form payload, shows a success toast, and closes the dialog on success', () => { + const component = createComponent(); + component.emailProviderForm.setValue({ + name: 'Primary SMTP', + host: 'smtp.example.com', + port: 587, + username: 'mailer', + password: 'secret', + fromAddress: 'mailer@example.com', + auth: true, + startTls: true, + }); + + component.createEmailProvider(); + + expect(createEmailProvider).toHaveBeenCalledWith({ + name: 'Primary SMTP', + host: 'smtp.example.com', + port: 587, + username: 'mailer', + password: 'secret', + fromAddress: 'mailer@example.com', + auth: true, + startTls: true, + }); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'translated:settingsEmail.provider.create.success', + detail: 'translated:settingsEmail.provider.create.successDetail', + }); + expect(dialogHarness.dialogRef.close).toHaveBeenCalledWith(true); + }); + + it('shows the translated backend error detail and keeps the dialog open when creation fails with a message', () => { + createEmailProvider.mockReturnValueOnce(throwError(() => ({ + error: { + message: 'SMTP rejected credentials', + }, + }))); + const component = createComponent(); + component.emailProviderForm.setValue({ + name: 'Broken SMTP', + host: 'smtp.example.com', + port: 465, + username: 'mailer', + password: 'bad-secret', + fromAddress: 'mailer@example.com', + auth: true, + startTls: false, + }); + + component.createEmailProvider(); + + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'translated:settingsEmail.provider.create.failed', + detail: 'translated:settingsEmail.provider.create.failedDetail:{"message":"SMTP rejected credentials"}', + }); + expect(dialogHarness.dialogRef.close).not.toHaveBeenCalled(); + }); + + it('falls back to the default failure detail when the backend does not return a message', () => { + createEmailProvider.mockReturnValueOnce(throwError(() => new Error('network down'))); + const component = createComponent(); + component.emailProviderForm.setValue({ + name: 'Fallback SMTP', + host: 'smtp.example.com', + port: 2525, + username: '', + password: '', + fromAddress: '', + auth: false, + startTls: false, + }); + + component.createEmailProvider(); + + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'translated:settingsEmail.provider.create.failed', + detail: 'translated:settingsEmail.provider.create.failedDefault', + }); + expect(dialogHarness.dialogRef.close).not.toHaveBeenCalled(); + }); + + it('closes the dialog without a result when dismissed explicitly', () => { + const component = createComponent(); + + component.closeDialog(); + + expect(dialogHarness.dialogRef.close).toHaveBeenCalledOnce(); + expect(dialogHarness.dialogRef.close).toHaveBeenCalledWith(); + }); +}); diff --git a/frontend/src/app/features/settings/email-v2/create-email-recipient-dialog/create-email-recipient-dialog.component.spec.ts b/frontend/src/app/features/settings/email-v2/create-email-recipient-dialog/create-email-recipient-dialog.component.spec.ts new file mode 100644 index 000000000..d457bcec8 --- /dev/null +++ b/frontend/src/app/features/settings/email-v2/create-email-recipient-dialog/create-email-recipient-dialog.component.spec.ts @@ -0,0 +1,9 @@ +import {describe, expect, it} from 'vitest'; + +// TODO(seam): Recipient creation also needs a mounted dialog harness around the reactive +// form, duplicate validation, and recipient persistence branches. +describe.skip('CreateEmailRecipientDialogComponent', () => { + it('needs a dialog harness for submit validation and recipient creation branches', () => { + expect.hasAssertions(); + }); +}); diff --git a/frontend/src/app/features/settings/email-v2/email-provider.model.spec.ts b/frontend/src/app/features/settings/email-v2/email-provider.model.spec.ts new file mode 100644 index 000000000..05c4b5e10 --- /dev/null +++ b/frontend/src/app/features/settings/email-v2/email-provider.model.spec.ts @@ -0,0 +1,27 @@ +import {describe, expect, expectTypeOf, it} from 'vitest'; + +import {EmailProvider} from './email-provider.model'; + +describe('email-provider.model', () => { + it('captures provider connection details and editing state', () => { + const provider: EmailProvider = { + isEditing: false, + id: 1, + userId: 9, + name: 'SMTP', + host: 'smtp.example.com', + port: 587, + username: 'user', + password: 'secret', + fromAddress: 'books@example.com', + auth: true, + startTls: true, + defaultProvider: true, + shared: false + }; + + expect(provider.port).toBe(587); + expect(provider.defaultProvider).toBe(true); + expectTypeOf(provider.startTls).toEqualTypeOf(); + }); +}); diff --git a/frontend/src/app/features/settings/email-v2/email-recipient.model.spec.ts b/frontend/src/app/features/settings/email-v2/email-recipient.model.spec.ts new file mode 100644 index 000000000..6d6d0409a --- /dev/null +++ b/frontend/src/app/features/settings/email-v2/email-recipient.model.spec.ts @@ -0,0 +1,19 @@ +import {describe, expect, expectTypeOf, it} from 'vitest'; + +import {EmailRecipient} from './email-recipient.model'; + +describe('email-recipient.model', () => { + it('captures recipient identity and editing state', () => { + const recipient: EmailRecipient = { + id: 2, + email: 'reader@example.com', + name: 'Reader', + defaultRecipient: true, + isEditing: false + }; + + expect(recipient.email).toBe('reader@example.com'); + expect(recipient.defaultRecipient).toBe(true); + expectTypeOf(recipient.isEditing).toEqualTypeOf(); + }); +}); diff --git a/frontend/src/app/features/settings/email-v2/email-v2-provider/email-v2-provider.component.spec.ts b/frontend/src/app/features/settings/email-v2/email-v2-provider/email-v2-provider.component.spec.ts new file mode 100644 index 000000000..162de3dd0 --- /dev/null +++ b/frontend/src/app/features/settings/email-v2/email-v2-provider/email-v2-provider.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around current-user bootstrapping, shared +// provider permission logic, dialog close streams, and confirm/toast side effects so provider +// management can be asserted without the full PrimeNG table runtime. +describe.skip('EmailV2ProviderComponent', () => { + it('needs service seams to verify provider loading, default assignment, sharing toggles, and delete/save outcomes', () => { + // TODO(seam): Cover loadCurrentUser, loadEmailProviders, saveProvider, deleteProvider, setDefaultProvider, and toggleShared once service streams are isolated behind deterministic doubles. + }); + + it('needs table-edit seams to verify row editing and create-provider dialog refresh behavior', () => { + // TODO(seam): Cover toggleEdit and openCreateProviderDialog after dialog onClose streams and provider-row state are extracted from the live table runtime. + }); +}); diff --git a/frontend/src/app/features/settings/email-v2/email-v2-provider/email-v2-provider.service.spec.ts b/frontend/src/app/features/settings/email-v2/email-v2-provider/email-v2-provider.service.spec.ts new file mode 100644 index 000000000..8edb88e88 --- /dev/null +++ b/frontend/src/app/features/settings/email-v2/email-v2-provider/email-v2-provider.service.spec.ts @@ -0,0 +1,87 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {API_CONFIG} from '../../../../core/config/api-config'; +import {EmailV2ProviderService} from './email-v2-provider.service'; + +describe('EmailV2ProviderService', () => { + let service: EmailV2ProviderService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + EmailV2ProviderService, + ] + }); + + service = TestBed.inject(EmailV2ProviderService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('loads providers', () => { + service.getEmailProviders().subscribe(providers => { + expect(providers).toEqual([{id: 1, userId: 10, name: 'SMTP', host: 'mail.test', port: 587, username: 'reader', password: 'secret', fromAddress: 'reader@test', auth: true, startTls: true, defaultProvider: true, shared: false, isEditing: false}]); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/providers`); + expect(request.request.method).toBe('GET'); + request.flush([{id: 1, userId: 10, name: 'SMTP', host: 'mail.test', port: 587, username: 'reader', password: 'secret', fromAddress: 'reader@test', auth: true, startTls: true, defaultProvider: true, shared: false, isEditing: false}]); + }); + + it('creates a provider', () => { + const provider = {id: 1, userId: 10, name: 'SMTP', host: 'mail.test', port: 587, username: 'reader', password: 'secret', fromAddress: 'reader@test', auth: true, startTls: true, defaultProvider: false, shared: false, isEditing: false}; + + service.createEmailProvider(provider).subscribe(result => { + expect(result).toEqual(provider); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/providers`); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual(provider); + request.flush(provider); + }); + + it('updates a provider', () => { + const provider = {id: 2, userId: 10, name: 'SMTP', host: 'mail.test', port: 587, username: 'reader', password: 'secret', fromAddress: 'reader@test', auth: true, startTls: true, defaultProvider: false, shared: false, isEditing: true}; + + service.updateProvider(provider).subscribe(result => { + expect(result).toEqual(provider); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/providers/2`); + expect(request.request.method).toBe('PUT'); + expect(request.request.body).toEqual(provider); + request.flush(provider); + }); + + it('deletes a provider', () => { + service.deleteProvider(3).subscribe(result => { + expect(result).toBeNull(); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/providers/3`); + expect(request.request.method).toBe('DELETE'); + request.flush(null); + }); + + it('marks a provider as default', () => { + service.setDefaultProvider(4).subscribe(result => { + expect(result).toBeNull(); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/providers/4/set-default`); + expect(request.request.method).toBe('PATCH'); + expect(request.request.body).toEqual({}); + request.flush(null); + }); +}); diff --git a/frontend/src/app/features/settings/email-v2/email-v2-recipient/email-v2-recipient.component.spec.ts b/frontend/src/app/features/settings/email-v2/email-v2-recipient/email-v2-recipient.component.spec.ts new file mode 100644 index 000000000..ad7367bd5 --- /dev/null +++ b/frontend/src/app/features/settings/email-v2/email-v2-recipient/email-v2-recipient.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around confirm dialogs, dialog-launcher +// close streams, and editable table row state so recipient CRUD behavior can be asserted without +// the full PrimeNG table runtime. +describe.skip('EmailV2RecipientComponent', () => { + it('needs service seams to verify recipient loading, default selection, and save/delete outcomes', () => { + // TODO(seam): Cover loadRecipientEmails, saveRecipient, deleteRecipient, and setDefaultRecipient once service streams and confirm behavior are isolated behind deterministic doubles. + }); + + it('needs table-edit seams to verify row edit toggling and create-dialog refresh behavior', () => { + // TODO(seam): Cover toggleEditRecipient and openAddRecipientDialog after dialog onClose streams and row-edit state are extracted from the live table runtime. + }); +}); diff --git a/frontend/src/app/features/settings/email-v2/email-v2-recipient/email-v2-recipient.service.spec.ts b/frontend/src/app/features/settings/email-v2/email-v2-recipient/email-v2-recipient.service.spec.ts new file mode 100644 index 000000000..3e57ebd1d --- /dev/null +++ b/frontend/src/app/features/settings/email-v2/email-v2-recipient/email-v2-recipient.service.spec.ts @@ -0,0 +1,87 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {API_CONFIG} from '../../../../core/config/api-config'; +import {EmailV2RecipientService} from './email-v2-recipient.service'; + +describe('EmailV2RecipientService', () => { + let service: EmailV2RecipientService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + EmailV2RecipientService, + ] + }); + + service = TestBed.inject(EmailV2RecipientService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('loads recipients', () => { + service.getRecipients().subscribe(recipients => { + expect(recipients).toEqual([{id: 1, email: 'reader@test', name: 'Reader', defaultRecipient: true, isEditing: false}]); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/recipients`); + expect(request.request.method).toBe('GET'); + request.flush([{id: 1, email: 'reader@test', name: 'Reader', defaultRecipient: true, isEditing: false}]); + }); + + it('creates a recipient', () => { + const recipient = {id: 1, email: 'reader@test', name: 'Reader', defaultRecipient: false, isEditing: false}; + + service.createRecipient(recipient).subscribe(result => { + expect(result).toEqual(recipient); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/recipients`); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual(recipient); + request.flush(recipient); + }); + + it('updates a recipient', () => { + const recipient = {id: 2, email: 'reader@test', name: 'Reader', defaultRecipient: false, isEditing: true}; + + service.updateRecipient(recipient).subscribe(result => { + expect(result).toEqual(recipient); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/recipients/2`); + expect(request.request.method).toBe('PUT'); + expect(request.request.body).toEqual(recipient); + request.flush(recipient); + }); + + it('deletes a recipient', () => { + service.deleteRecipient(3).subscribe(result => { + expect(result).toBeNull(); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/recipients/3`); + expect(request.request.method).toBe('DELETE'); + request.flush(null); + }); + + it('marks a recipient as default', () => { + service.setDefaultRecipient(4).subscribe(result => { + expect(result).toBeNull(); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/recipients/4/set-default`); + expect(request.request.method).toBe('PATCH'); + expect(request.request.body).toEqual({}); + request.flush(null); + }); +}); diff --git a/frontend/src/app/features/settings/email-v2/email-v2.component.spec.ts b/frontend/src/app/features/settings/email-v2/email-v2.component.spec.ts new file mode 100644 index 000000000..5367b7d31 --- /dev/null +++ b/frontend/src/app/features/settings/email-v2/email-v2.component.spec.ts @@ -0,0 +1,9 @@ +import {describe, expect, it} from 'vitest'; + +// TODO(seam): The email settings screen coordinates nested provider and recipient dialogs, +// permissions, and persisted settings, which needs a mounted settings harness. +describe.skip('EmailV2Component', () => { + it('needs a mounted settings harness for provider, recipient, and toggle flows', () => { + expect.hasAssertions(); + }); +}); diff --git a/frontend/src/app/features/settings/email-v2/email.service.spec.ts b/frontend/src/app/features/settings/email-v2/email.service.spec.ts new file mode 100644 index 000000000..572e20dab --- /dev/null +++ b/frontend/src/app/features/settings/email-v2/email.service.spec.ts @@ -0,0 +1,54 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {API_CONFIG} from '../../../core/config/api-config'; +import {EmailService} from './email.service'; + +describe('EmailService', () => { + let service: EmailService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + EmailService, + ] + }); + + service = TestBed.inject(EmailService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('emails a book with the detailed payload', () => { + const payload = {bookId: 1, providerId: 2, recipientId: 3, bookFileId: 4}; + + service.emailBook(payload).subscribe(result => { + expect(result).toBeNull(); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/book`); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual(payload); + request.flush(null); + }); + + it('emails a book quickly', () => { + service.emailBookQuick(99).subscribe(result => { + expect(result).toBeNull(); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/email/book/99`); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual({}); + request.flush(null); + }); +}); diff --git a/frontend/src/app/features/settings/file-naming-pattern/file-naming-pattern.component.spec.ts b/frontend/src/app/features/settings/file-naming-pattern/file-naming-pattern.component.spec.ts new file mode 100644 index 000000000..bdcba0da0 --- /dev/null +++ b/frontend/src/app/features/settings/file-naming-pattern/file-naming-pattern.component.spec.ts @@ -0,0 +1,85 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {of, throwError} from 'rxjs'; + +import {MessageService} from 'primeng/api'; + +import {getTranslocoModule} from '../../../core/testing/transloco-testing'; +import {AppSettingsService} from '../../../shared/service/app-settings.service'; +import {LibraryService} from '../../book/service/library.service'; +import {FileNamingPatternComponent} from './file-naming-pattern.component'; + +describe('FileNamingPatternComponent', () => { + let fixture: ComponentFixture; + let component: FileNamingPatternComponent; + let saveSettings: ReturnType; + let updateLibraryFileNamingPattern: ReturnType; + let messageService: {add: ReturnType}; + + beforeEach(async () => { + saveSettings = vi.fn(() => of(void 0)); + updateLibraryFileNamingPattern = vi.fn(() => of(void 0)); + messageService = {add: vi.fn()}; + + await TestBed.configureTestingModule({ + imports: [FileNamingPatternComponent, getTranslocoModule()], + providers: [ + {provide: AppSettingsService, useValue: {appSettings: () => ({uploadPattern: '{authors}/{title}'}), saveSettings}}, + { + provide: LibraryService, + useValue: { + libraries: () => [ + {id: 1, name: 'Main', fileNamingPattern: '{series}/{title}'}, + {id: 2, name: 'Side', fileNamingPattern: ''}, + ], + updateLibraryFileNamingPattern, + }, + }, + {provide: MessageService, useValue: messageService}, + ], + }).compileComponents(); + + fixture = TestBed.createComponent(FileNamingPatternComponent); + component = fixture.componentInstance; + component.ngOnInit(); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('hydrates the default pattern and generates previews with extensions', () => { + expect(component.defaultPattern).toBe('{authors}/{title}'); + expect(component.generateDefaultPreview()).toBe('/Patrick Rothfuss/The Name of the Wind.pdf'); + }); + + it('validates patterns and exposes invalid-character errors', () => { + component.onDefaultPatternChange('bad%^pattern'); + + expect(component.validatePattern('bad%^pattern')).toBe(false); + expect(component.defaultErrorMessage).toBeTruthy(); + }); + + it('persists the default upload pattern when validation passes', () => { + component.defaultPattern = '{title}/{series}'; + + component.savePatterns(); + + expect(saveSettings).toHaveBeenCalledWith([ + {key: 'UPLOAD_FILE_PATTERN', newValue: '{title}/{series}'}, + ]); + expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'})); + }); + + it('saves library overrides and reports partial failures', () => { + updateLibraryFileNamingPattern + .mockReturnValueOnce(of(void 0)) + .mockReturnValueOnce(throwError(() => new Error('boom'))); + + component.saveLibraryPatterns(); + + expect(updateLibraryFileNamingPattern).toHaveBeenCalledTimes(2); + expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'})); + }); +}); diff --git a/frontend/src/app/features/settings/global-preferences/global-preferences.component.spec.ts b/frontend/src/app/features/settings/global-preferences/global-preferences.component.spec.ts new file mode 100644 index 000000000..012bfb974 --- /dev/null +++ b/frontend/src/app/features/settings/global-preferences/global-preferences.component.spec.ts @@ -0,0 +1,10 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around Prime split-button/tiered-menu browser +// hooks such as `window.matchMedia`, plus effect-driven settings hydration and metadata-regeneration +// subscriptions, so preference saves can be asserted without depending on Prime runtime internals. +describe.skip('GlobalPreferencesComponent', () => { + it('needs a menu and settings seam to verify toggle persistence, file-size validation, and cover-regeneration actions', () => { + // TODO(seam): Cover saveSetting and regenerateCovers once the split-button/menu interactions are isolated behind a smaller adapter. + }); +}); diff --git a/frontend/src/app/features/settings/global-preferences/metadata-match-weights/metadata-match-weights-component.spec.ts b/frontend/src/app/features/settings/global-preferences/metadata-match-weights/metadata-match-weights-component.spec.ts new file mode 100644 index 000000000..a88697eda --- /dev/null +++ b/frontend/src/app/features/settings/global-preferences/metadata-match-weights/metadata-match-weights-component.spec.ts @@ -0,0 +1,114 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {of, throwError} from 'rxjs'; + +import {MessageService} from 'primeng/api'; + +import {getTranslocoModule} from '../../../../core/testing/transloco-testing'; +import {AppSettingsService} from '../../../../shared/service/app-settings.service'; +import {MetadataMatchWeightsService} from '../../../../shared/service/metadata-match-weights.service'; +import {AppSettingKey} from '../../../../shared/model/app-settings.model'; +import {MetadataMatchWeightsComponent} from './metadata-match-weights-component'; + +describe('MetadataMatchWeightsComponent', () => { + let fixture: ComponentFixture; + let component: MetadataMatchWeightsComponent; + let saveSettings: ReturnType; + let recalculateAll: ReturnType; + let messageService: {add: ReturnType}; + + beforeEach(async () => { + saveSettings = vi.fn(() => of(void 0)); + recalculateAll = vi.fn(() => of(void 0)); + messageService = {add: vi.fn()}; + + await TestBed.configureTestingModule({ + imports: [MetadataMatchWeightsComponent, getTranslocoModule()], + providers: [ + { + provide: AppSettingsService, + useValue: { + appSettings: () => ({ + metadataMatchWeights: { + title: 10, + subtitle: 5, + description: 3, + publisher: 2, + publishedDate: 1, + authors: 9, + categories: 4, + seriesName: 6, + seriesNumber: 2, + seriesTotal: 1, + isbn13: 8, + isbn10: 7, + pageCount: 2, + language: 1, + amazonRating: 2, + amazonReviewCount: 2, + goodreadsRating: 2, + goodreadsReviewCount: 2, + hardcoverRating: 2, + hardcoverReviewCount: 2, + doubanRating: 2, + doubanReviewCount: 2, + ranobedbRating: 2, + audibleRating: 2, + audibleReviewCount: 2, + coverImage: 3, + }, + }), + saveSettings, + }, + }, + {provide: MetadataMatchWeightsService, useValue: {recalculateAll}}, + {provide: MessageService, useValue: messageService}, + ], + }).compileComponents(); + + fixture = TestBed.createComponent(MetadataMatchWeightsComponent); + component = fixture.componentInstance; + component.ngOnInit(); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('hydrates the reactive form from saved match weights', () => { + expect(component.form.get('title')?.value).toBe(10); + expect(component.form.get('authors')?.value).toBe(9); + expect(component.orderedKeys[0]).toBe('title'); + }); + + it('persists valid form values through app settings', () => { + component.save(); + + expect(saveSettings).toHaveBeenCalledWith([ + { + key: AppSettingKey.METADATA_MATCH_WEIGHTS, + newValue: component.form.value, + }, + ]); + expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'})); + expect(component.isSaving).toBe(false); + }); + + it('does not save invalid forms', () => { + component.form.get('title')?.setValue(-1); + + component.save(); + + expect(saveSettings).toHaveBeenCalledTimes(0); + }); + + it('reports recalculate failures and resets the loading flag', () => { + recalculateAll.mockReturnValueOnce(throwError(() => new Error('boom'))); + + component.recalculate(); + + expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'})); + expect(component.isRecalculating).toBe(false); + }); +}); diff --git a/frontend/src/app/features/settings/global-preferences/metadata-provider-settings/metadata-provider-settings.component.spec.ts b/frontend/src/app/features/settings/global-preferences/metadata-provider-settings/metadata-provider-settings.component.spec.ts new file mode 100644 index 000000000..353d9a560 --- /dev/null +++ b/frontend/src/app/features/settings/global-preferences/metadata-provider-settings/metadata-provider-settings.component.spec.ts @@ -0,0 +1,10 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs a seam around effect-driven settings hydration and +// the large provider payload editor so save behavior can be asserted without coupling the spec to a +// brittle form snapshot across every provider toggle and token field. +describe.skip('MetadataProviderSettingsComponent', () => { + it('needs a provider-settings form seam to verify payload assembly and toggle/token interactions deterministically', () => { + // TODO(seam): Cover applySettings, token gating, and save payload composition once the provider editor state is extracted behind a smaller adapter. + }); +}); diff --git a/frontend/src/app/features/settings/library-metadata-settings/library-metadata-settings.component.spec.ts b/frontend/src/app/features/settings/library-metadata-settings/library-metadata-settings.component.spec.ts new file mode 100644 index 000000000..cbb7382a5 --- /dev/null +++ b/frontend/src/app/features/settings/library-metadata-settings/library-metadata-settings.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around app-settings signal hydration, +// library-sync service interactions, and the nested preference shell so save/reset behavior can +// be asserted without mounting the full settings runtime. +describe.skip('LibraryMetadataSettingsComponent', () => { + it('needs settings seams to verify sidecar preference synchronization and reset behavior', () => { + // TODO(seam): Cover the effect-driven settings bootstrap once app settings and sync updates are exposed through deterministic test doubles. + }); + + it('needs child-shell seams to verify save-state propagation across nested metadata preference panels', () => { + // TODO(seam): Cover panel composition and persistence actions after the settings shell is isolated from the live query-backed view model. + }); +}); diff --git a/frontend/src/app/features/settings/metadata-settings/metadata-persistence-settings/metadata-persistence-settings-component.spec.ts b/frontend/src/app/features/settings/metadata-settings/metadata-persistence-settings/metadata-persistence-settings-component.spec.ts new file mode 100644 index 000000000..036497f65 --- /dev/null +++ b/frontend/src/app/features/settings/metadata-settings/metadata-persistence-settings/metadata-persistence-settings-component.spec.ts @@ -0,0 +1,114 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {getTranslocoModule} from '../../../../core/testing/transloco-testing'; +import {AppSettingKey, type AppSettings, type MetadataPersistenceSettings} from '../../../../shared/model/app-settings.model'; +import {AppSettingsService} from '../../../../shared/service/app-settings.service'; +import {SettingsHelperService} from '../../../../shared/service/settings-helper.service'; +import {MetadataPersistenceSettingsComponent} from './metadata-persistence-settings-component'; + +describe('MetadataPersistenceSettingsComponent', () => { + let fixture: ComponentFixture; + let component: MetadataPersistenceSettingsComponent; + let appSettingsService: {appSettings: ReturnType}; + let settingsHelper: {saveSetting: ReturnType}; + + beforeEach(async () => { + appSettingsService = { + appSettings: vi.fn(() => buildSettings()), + }; + settingsHelper = { + saveSetting: vi.fn(), + }; + + await TestBed.configureTestingModule({ + imports: [MetadataPersistenceSettingsComponent, getTranslocoModule()], + providers: [ + {provide: AppSettingsService, useValue: appSettingsService}, + {provide: SettingsHelperService, useValue: settingsHelper}, + ], + }).compileComponents(); + + fixture = TestBed.createComponent(MetadataPersistenceSettingsComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('hydrates persistence settings and network-storage state from app settings', () => { + expect(component.isNetworkStorage).toBe(true); + expect(component.metadataPersistence.moveFilesToLibraryPattern).toBe(true); + expect(component.metadataPersistence.convertCbrCb7ToCbz).toBe(true); + expect(component.metadataPersistence.saveToOriginalFile.epub).toEqual({ + enabled: true, + maxFileSizeInMb: 123, + }); + expect(component.metadataPersistence.saveToOriginalFile.pdf).toEqual({ + enabled: false, + maxFileSizeInMb: 250, + }); + expect(component.metadataPersistence.sidecarSettings).toEqual({ + enabled: true, + writeOnUpdate: true, + writeOnScan: false, + includeCoverFile: false, + }); + }); + + it('toggles persistence flags and saves the updated settings', () => { + component.onPersistenceToggle('convertCbrCb7ToCbz'); + + expect(component.metadataPersistence.convertCbrCb7ToCbz).toBe(false); + expect(settingsHelper.saveSetting).toHaveBeenCalledWith( + AppSettingKey.METADATA_PERSISTENCE_SETTINGS, + component.metadataPersistence + ); + }); + + it('toggles save-to-original-file settings and persists the current metadata settings', () => { + component.onSaveToOriginalFileToggle('pdf'); + + expect(component.metadataPersistence.saveToOriginalFile.pdf.enabled).toBe(true); + expect(settingsHelper.saveSetting).toHaveBeenCalledWith( + AppSettingKey.METADATA_PERSISTENCE_SETTINGS, + component.metadataPersistence + ); + }); + + it('toggles sidecar settings and saves the updated state', () => { + component.onSidecarToggle('includeCoverFile'); + + expect(component.metadataPersistence.sidecarSettings?.includeCoverFile).toBe(true); + expect(settingsHelper.saveSetting).toHaveBeenCalledWith( + AppSettingKey.METADATA_PERSISTENCE_SETTINGS, + component.metadataPersistence + ); + }); +}); + +function buildSettings(): AppSettings { + const metadataPersistenceSettings: MetadataPersistenceSettings = { + moveFilesToLibraryPattern: true, + convertCbrCb7ToCbz: true, + saveToOriginalFile: { + epub: {enabled: true, maxFileSizeInMb: 123}, + pdf: {enabled: false, maxFileSizeInMb: 250}, + cbx: {enabled: true, maxFileSizeInMb: 64}, + audiobook: {enabled: false, maxFileSizeInMb: 1000}, + }, + sidecarSettings: { + enabled: true, + writeOnUpdate: true, + writeOnScan: false, + includeCoverFile: false, + }, + }; + + return { + diskType: 'NETWORK', + metadataPersistenceSettings, + } as AppSettings; +} diff --git a/frontend/src/app/features/settings/metadata-settings/metadata-settings-component.spec.ts b/frontend/src/app/features/settings/metadata-settings/metadata-settings-component.spec.ts new file mode 100644 index 000000000..e31725914 --- /dev/null +++ b/frontend/src/app/features/settings/metadata-settings/metadata-settings-component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around settings hydration and the composed +// metadata preference subpanels so the container shell can be asserted without mounting the full +// nested settings runtime. +describe.skip('MetadataSettingsComponent', () => { + it('needs settings seams to verify metadata option bootstrap and bookdrop-download toggling', () => { + // TODO(seam): Cover loadSettings, initializeSettings, and onMetadataDownloadOnBookdropToggle once app settings and save helpers are exposed through deterministic doubles. + }); + + it('needs child-panel seams to verify metadata option submissions across nested preferences', () => { + // TODO(seam): Cover onMetadataSubmit after the container shell is isolated from the provider, match-weight, persistence, and review child runtimes. + }); +}); diff --git a/frontend/src/app/features/settings/metadata-settings/public-reviews-settings/public-reviews-settings-component.spec.ts b/frontend/src/app/features/settings/metadata-settings/public-reviews-settings/public-reviews-settings-component.spec.ts new file mode 100644 index 000000000..4f8c67390 --- /dev/null +++ b/frontend/src/app/features/settings/metadata-settings/public-reviews-settings/public-reviews-settings-component.spec.ts @@ -0,0 +1,86 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {getTranslocoModule} from '../../../../core/testing/transloco-testing'; +import {AppSettingKey, type AppSettings} from '../../../../shared/model/app-settings.model'; +import {AppSettingsService} from '../../../../shared/service/app-settings.service'; +import {SettingsHelperService} from '../../../../shared/service/settings-helper.service'; +import {PublicReviewsSettingsComponent} from './public-reviews-settings-component'; + +describe('PublicReviewsSettingsComponent', () => { + let fixture: ComponentFixture; + let component: PublicReviewsSettingsComponent; + let appSettingsService: {appSettings: ReturnType}; + let settingsHelper: {saveSetting: ReturnType}; + + beforeEach(async () => { + appSettingsService = { + appSettings: vi.fn(() => ({ + metadataPublicReviewsSettings: { + downloadEnabled: false, + autoDownloadEnabled: true, + providers: [{provider: 'Amazon', enabled: true, maxReviews: 7}], + }, + } as AppSettings)), + }; + settingsHelper = { + saveSetting: vi.fn(), + }; + + await TestBed.configureTestingModule({ + imports: [PublicReviewsSettingsComponent, getTranslocoModule()], + providers: [ + {provide: AppSettingsService, useValue: appSettingsService}, + {provide: SettingsHelperService, useValue: settingsHelper}, + ], + }).compileComponents(); + + fixture = TestBed.createComponent(PublicReviewsSettingsComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('hydrates saved review settings and ensures all required providers exist', () => { + expect(component.publicReviewSettings.downloadEnabled).toBe(false); + expect(component.publicReviewSettings.autoDownloadEnabled).toBe(true); + expect(component.publicReviewSettings.providers).toEqual( + expect.arrayContaining([ + expect.objectContaining({provider: 'Amazon', enabled: true, maxReviews: 7}), + expect.objectContaining({provider: 'GoodReads', enabled: false, maxReviews: 10}), + expect.objectContaining({provider: 'Douban', enabled: false, maxReviews: 10}), + ]) + ); + }); + + it('persists top-level review toggles', () => { + component.onPublicReviewsToggle(true); + component.onAutoDownloadToggle(false); + + expect(settingsHelper.saveSetting).toHaveBeenNthCalledWith( + 1, + AppSettingKey.METADATA_PUBLIC_REVIEWS_SETTINGS, + component.publicReviewSettings + ); + expect(settingsHelper.saveSetting).toHaveBeenNthCalledWith( + 2, + AppSettingKey.METADATA_PUBLIC_REVIEWS_SETTINGS, + component.publicReviewSettings + ); + }); + + it('updates provider settings and persists them', () => { + component.onProviderToggle('Amazon', false); + component.onMaxReviewsChange('Amazon', 12); + + const amazon = component.publicReviewSettings.providers.find(provider => provider.provider === 'Amazon'); + expect(amazon).toEqual(expect.objectContaining({enabled: false, maxReviews: 12})); + expect(settingsHelper.saveSetting).toHaveBeenCalledWith( + AppSettingKey.METADATA_PUBLIC_REVIEWS_SETTINGS, + component.publicReviewSettings + ); + }); +}); diff --git a/frontend/src/app/features/settings/opds-settings/opds-settings.spec.ts b/frontend/src/app/features/settings/opds-settings/opds-settings.spec.ts new file mode 100644 index 000000000..8d75a487b --- /dev/null +++ b/frontend/src/app/features/settings/opds-settings/opds-settings.spec.ts @@ -0,0 +1,9 @@ +import {describe, expect, it} from 'vitest'; + +// TODO(seam): OPDS settings coordinate clipboard access, confirmation dialogs, PrimeNG +// tables, and remote user CRUD, so they should be exercised with a mounted settings harness. +describe.skip('OpdsSettings', () => { + it('needs a mounted settings harness for user CRUD and OPDS or Komga toggle branches', () => { + expect.hasAssertions(); + }); +}); diff --git a/frontend/src/app/features/settings/opds-settings/opds.service.spec.ts b/frontend/src/app/features/settings/opds-settings/opds.service.spec.ts new file mode 100644 index 000000000..ec9539d54 --- /dev/null +++ b/frontend/src/app/features/settings/opds-settings/opds.service.spec.ts @@ -0,0 +1,74 @@ +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {provideHttpClient} from '@angular/common/http'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {API_CONFIG} from '../../../core/config/api-config'; +import {OpdsService} from './opds.service'; + +describe('OpdsService', () => { + let service: OpdsService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + OpdsService, + ] + }); + + service = TestBed.inject(OpdsService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('loads OPDS users', () => { + service.getUser().subscribe(users => { + expect(users).toEqual([{id: 1, userId: 10, username: 'reader'}]); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v2/opds-users`); + expect(request.request.method).toBe('GET'); + request.flush([{id: 1, userId: 10, username: 'reader'}]); + }); + + it('creates an OPDS user', () => { + const payload = {username: 'reader', password: 'secret', sortOrder: 'TITLE_ASC' as const}; + + service.createUser(payload).subscribe(user => { + expect(user).toEqual({id: 1, userId: 10, username: 'reader', sortOrder: 'TITLE_ASC'}); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v2/opds-users`); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual(payload); + request.flush({id: 1, userId: 10, username: 'reader', sortOrder: 'TITLE_ASC'}); + }); + + it('updates an OPDS user sort order', () => { + service.updateUser(5, 'AUTHOR_DESC').subscribe(user => { + expect(user).toEqual({id: 5, userId: 10, username: 'reader', sortOrder: 'AUTHOR_DESC'}); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v2/opds-users/5`); + expect(request.request.method).toBe('PATCH'); + expect(request.request.body).toEqual({sortOrder: 'AUTHOR_DESC'}); + request.flush({id: 5, userId: 10, username: 'reader', sortOrder: 'AUTHOR_DESC'}); + }); + + it('deletes an OPDS credential', () => { + service.deleteCredential(7).subscribe(response => { + expect(response).toBeNull(); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v2/opds-users/7`); + expect(request.request.method).toBe('DELETE'); + request.flush(null); + }); +}); diff --git a/frontend/src/app/features/settings/reader-preferences/cbx-reader-preferences/cbx-reader-preferences-component.spec.ts b/frontend/src/app/features/settings/reader-preferences/cbx-reader-preferences/cbx-reader-preferences-component.spec.ts new file mode 100644 index 000000000..5774983f9 --- /dev/null +++ b/frontend/src/app/features/settings/reader-preferences/cbx-reader-preferences/cbx-reader-preferences-component.spec.ts @@ -0,0 +1,77 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {getTranslocoModule} from '../../../../core/testing/transloco-testing'; +import {ReaderPreferencesService} from '../reader-preferences.service'; +import {CbxBackgroundColor, CbxFitMode, CbxPageSpread, CbxPageViewMode, CbxScrollMode, UserSettings} from '../../user-management/user.service'; +import {CbxReaderPreferencesComponent} from './cbx-reader-preferences-component'; + +function createUserSettings(): UserSettings { + return { + perBookSetting: {pdf: 'Global', epub: 'Individual', cbx: 'Global'}, + pdfReaderSetting: {pageSpread: 'off', pageZoom: '100%', showSidebar: true}, + epubReaderSetting: {theme: 'light', font: 'serif', fontSize: 16, flow: 'paginated', spread: 'auto', lineHeight: 1.5, margin: 1, letterSpacing: 0}, + ebookReaderSetting: {lineHeight: 1.5, justify: true, hyphenate: true, maxColumnCount: 1, gap: 1, fontSize: 16, theme: 'light', maxInlineSize: 100, maxBlockSize: 100, fontFamily: 'serif', isDark: false, flow: 'paginated'}, + cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.AUTO}, + newPdfReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'}, + sidebarLibrarySorting: {field: 'name', order: 'ASC'}, + sidebarShelfSorting: {field: 'name', order: 'ASC'}, + sidebarMagicShelfSorting: {field: 'name', order: 'ASC'}, + filterMode: 'and', + metadataCenterViewMode: 'route', + enableSeriesView: true, + entityViewPreferences: {global: {sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 100, seriesCollapsed: false, overlayBookType: false}, overrides: []}, + koReaderEnabled: false, + autoSaveMetadata: true, + } as UserSettings; +} + +describe('CbxReaderPreferencesComponent', () => { + let fixture: ComponentFixture; + let updatePreference: ReturnType; + + beforeEach(() => { + updatePreference = vi.fn(); + + TestBed.configureTestingModule({ + imports: [CbxReaderPreferencesComponent, getTranslocoModule()], + providers: [ + {provide: ReaderPreferencesService, useValue: {updatePreference}}, + ], + }); + + fixture = TestBed.createComponent(CbxReaderPreferencesComponent); + fixture.componentInstance.userSettings = createUserSettings(); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('returns configured defaults from the supplied user settings', () => { + const component = fixture.componentInstance; + + expect(component.selectedCbxSpread).toBe(CbxPageSpread.EVEN); + expect(component.selectedCbxViewMode).toBe(CbxPageViewMode.SINGLE_PAGE); + expect(component.selectedCbxFitMode).toBe(CbxFitMode.AUTO); + expect(component.selectedCbxScrollMode).toBe(CbxScrollMode.PAGINATED); + expect(component.selectedCbxBackgroundColor).toBe(CbxBackgroundColor.GRAY); + }); + + it('persists each CBX reader preference through the shared preferences service', () => { + const component = fixture.componentInstance; + + component.selectedCbxSpread = CbxPageSpread.ODD; + component.selectedCbxViewMode = CbxPageViewMode.TWO_PAGE; + component.selectedCbxFitMode = CbxFitMode.FIT_WIDTH; + component.selectedCbxScrollMode = CbxScrollMode.INFINITE; + component.selectedCbxBackgroundColor = CbxBackgroundColor.BLACK; + + expect(updatePreference).toHaveBeenNthCalledWith(1, ['cbxReaderSetting', 'pageSpread'], CbxPageSpread.ODD); + expect(updatePreference).toHaveBeenNthCalledWith(2, ['cbxReaderSetting', 'pageViewMode'], CbxPageViewMode.TWO_PAGE); + expect(updatePreference).toHaveBeenNthCalledWith(3, ['cbxReaderSetting', 'fitMode'], CbxFitMode.FIT_WIDTH); + expect(updatePreference).toHaveBeenNthCalledWith(4, ['cbxReaderSetting', 'scrollMode'], CbxScrollMode.INFINITE); + expect(updatePreference).toHaveBeenNthCalledWith(5, ['cbxReaderSetting', 'backgroundColor'], CbxBackgroundColor.BLACK); + }); +}); diff --git a/frontend/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.spec.ts b/frontend/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.spec.ts new file mode 100644 index 000000000..432732210 --- /dev/null +++ b/frontend/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.spec.ts @@ -0,0 +1,9 @@ +import {describe, expect, it} from 'vitest'; + +// TODO(seam): EPUB reader preferences need a mounted settings harness around form controls, +// custom-font selection, and persisted user-setting mutations. +describe.skip('EpubReaderPreferencesComponent', () => { + it('needs a mounted settings harness for theme, flow, and font preference branches', () => { + expect.hasAssertions(); + }); +}); diff --git a/frontend/src/app/features/settings/reader-preferences/pdf-reader-preferences/pdf-reader-preferences-component.spec.ts b/frontend/src/app/features/settings/reader-preferences/pdf-reader-preferences/pdf-reader-preferences-component.spec.ts new file mode 100644 index 000000000..dceff9864 --- /dev/null +++ b/frontend/src/app/features/settings/reader-preferences/pdf-reader-preferences/pdf-reader-preferences-component.spec.ts @@ -0,0 +1,68 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {getTranslocoModule} from '../../../../core/testing/transloco-testing'; +import {ReaderPreferencesService} from '../reader-preferences.service'; +import {UserSettings} from '../../user-management/user.service'; +import {PdfReaderPreferencesComponent} from './pdf-reader-preferences-component'; + +function createUserSettings(): UserSettings { + return { + perBookSetting: {pdf: 'Global', epub: 'Individual', cbx: 'Global'}, + pdfReaderSetting: {pageSpread: 'off', pageZoom: 'page-fit', showSidebar: true}, + epubReaderSetting: {theme: 'light', font: 'serif', fontSize: 16, flow: 'paginated', spread: 'auto', lineHeight: 1.5, margin: 1, letterSpacing: 0}, + ebookReaderSetting: {lineHeight: 1.5, justify: true, hyphenate: true, maxColumnCount: 1, gap: 1, fontSize: 16, theme: 'light', maxInlineSize: 100, maxBlockSize: 100, fontFamily: 'serif', isDark: false, flow: 'paginated'}, + cbxReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'}, + newPdfReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'}, + sidebarLibrarySorting: {field: 'name', order: 'ASC'}, + sidebarShelfSorting: {field: 'name', order: 'ASC'}, + sidebarMagicShelfSorting: {field: 'name', order: 'ASC'}, + filterMode: 'and', + metadataCenterViewMode: 'route', + enableSeriesView: true, + entityViewPreferences: {global: {sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 100, seriesCollapsed: false, overlayBookType: false}, overrides: []}, + koReaderEnabled: false, + autoSaveMetadata: true, + } as UserSettings; +} + +describe('PdfReaderPreferencesComponent', () => { + let fixture: ComponentFixture; + let updatePreference: ReturnType; + + beforeEach(() => { + updatePreference = vi.fn(); + + TestBed.configureTestingModule({ + imports: [PdfReaderPreferencesComponent, getTranslocoModule()], + providers: [ + {provide: ReaderPreferencesService, useValue: {updatePreference}}, + ], + }); + + fixture = TestBed.createComponent(PdfReaderPreferencesComponent); + fixture.componentInstance.userSettings = createUserSettings(); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('reads the current spread and zoom from user settings', () => { + const component = fixture.componentInstance; + + expect(component.selectedSpread).toBe('off'); + expect(component.selectedZoom).toBe('page-fit'); + }); + + it('persists PDF reader preference changes through the shared preferences service', () => { + const component = fixture.componentInstance; + + component.selectedSpread = 'even'; + component.selectedZoom = 'page-width'; + + expect(updatePreference).toHaveBeenNthCalledWith(1, ['pdfReaderSetting', 'pageSpread'], 'even'); + expect(updatePreference).toHaveBeenNthCalledWith(2, ['pdfReaderSetting', 'pageZoom'], 'page-width'); + }); +}); diff --git a/frontend/src/app/features/settings/reader-preferences/reader-preferences.component.spec.ts b/frontend/src/app/features/settings/reader-preferences/reader-preferences.component.spec.ts new file mode 100644 index 000000000..00511b232 --- /dev/null +++ b/frontend/src/app/features/settings/reader-preferences/reader-preferences.component.spec.ts @@ -0,0 +1,38 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {UserService} from '../user-management/user.service'; +import {ReaderPreferences} from './reader-preferences.component'; + +describe('ReaderPreferences', () => { + beforeEach(() => { + const currentUser = signal({ + userSettings: { + theme: 'sepia', + }, + permissions: { + admin: false, + canManageFonts: true, + }, + }); + + TestBed.configureTestingModule({ + providers: [ + {provide: UserService, useValue: {currentUser}}, + ], + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('hydrates user settings and font management permission from the current user signal', () => { + const component = TestBed.runInInjectionContext(() => new ReaderPreferences()); + TestBed.flushEffects(); + + expect(component.userSettings).toEqual({theme: 'sepia'}); + expect(component.hasFontManagementPermission).toBe(true); + }); +}); diff --git a/frontend/src/app/features/settings/reader-preferences/reader-preferences.service.spec.ts b/frontend/src/app/features/settings/reader-preferences/reader-preferences.service.spec.ts new file mode 100644 index 000000000..0e787932a --- /dev/null +++ b/frontend/src/app/features/settings/reader-preferences/reader-preferences.service.spec.ts @@ -0,0 +1,176 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {describe, expect, it, vi} from 'vitest'; + +import {ReaderPreferencesService} from './reader-preferences.service'; +import {User, UserService, UserSettings} from '../user-management/user.service'; +import {MessageService} from 'primeng/api'; +import {TranslocoService} from '@jsverse/transloco'; + +describe('ReaderPreferencesService', () => { + function createUserSettings(): UserSettings { + return { + perBookSetting: {pdf: 'pdf', epub: 'epub', cbx: 'cbx'}, + pdfReaderSetting: {pageSpread: 'off', pageZoom: '100%', showSidebar: true}, + epubReaderSetting: {theme: 'light', font: 'serif', fontSize: 16, flow: 'paginated', spread: 'auto', lineHeight: 1.5, margin: 1, letterSpacing: 0}, + ebookReaderSetting: {lineHeight: 1.5, justify: true, hyphenate: true, maxColumnCount: 1, gap: 1, fontSize: 16, theme: 'light', maxInlineSize: 100, maxBlockSize: 100, fontFamily: 'serif', isDark: false, flow: 'paginated'}, + cbxReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'}, + newPdfReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'}, + sidebarLibrarySorting: {field: 'name', order: 'ASC'}, + sidebarShelfSorting: {field: 'name', order: 'ASC'}, + sidebarMagicShelfSorting: {field: 'name', order: 'ASC'}, + filterMode: 'and', + metadataCenterViewMode: 'route', + enableSeriesView: true, + entityViewPreferences: {global: {sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 100, seriesCollapsed: false, overlayBookType: false}, overrides: []}, + koReaderEnabled: false, + autoSaveMetadata: true, + } as UserSettings; + } + + it('updates a nested preference and notifies the backend', () => { + const userSettings = createUserSettings(); + const currentUser = signal({ + id: 7, + userSettings, + permissions: { + admin: false, + canUpload: false, + canDownload: false, + canEmailBook: false, + canDeleteBook: false, + canEditMetadata: false, + canManageLibrary: false, + canManageMetadataConfig: false, + canSyncKoReader: false, + canSyncKobo: false, + canAccessOpds: false, + canAccessBookdrop: false, + canAccessLibraryStats: false, + canAccessUserStats: false, + canAccessTaskManager: false, + canManageEmailConfig: false, + canManageGlobalPreferences: false, + canManageIcons: false, + canManageFonts: true, + demoUser: false, + canBulkAutoFetchMetadata: false, + canBulkCustomFetchMetadata: false, + canBulkEditMetadata: false, + canBulkRegenerateCover: false, + canMoveOrganizeFiles: false, + canBulkLockUnlockMetadata: false, + } as unknown as User['permissions'], + username: 'reader', + name: 'Reader', + email: 'reader@example.test', + assignedLibraries: [], + } as unknown as User); + const updateUserSetting = vi.fn(); + const messageAdd = vi.fn(); + const translate = vi.fn(key => key); + + TestBed.configureTestingModule({ + providers: [ + ReaderPreferencesService, + {provide: UserService, useValue: {currentUser, updateUserSetting}}, + {provide: MessageService, useValue: {add: messageAdd}}, + {provide: TranslocoService, useValue: {translate}}, + ] + }); + + const service = TestBed.inject(ReaderPreferencesService); + TestBed.flushEffects(); + + service.updatePreference(['ebookReaderSetting', 'fontSize'], 22); + + expect(updateUserSetting).toHaveBeenCalledWith(7, 'ebookReaderSetting', expect.objectContaining({fontSize: 22})); + expect(messageAdd).toHaveBeenCalledWith({ + severity: 'success', + summary: 'settingsReader.toast.preferencesUpdated', + detail: 'settingsReader.toast.preferencesUpdatedDetail', + life: 2000 + }); + }); + + it('ignores updates until the current user is available', () => { + const currentUser = signal(null); + const updateUserSetting = vi.fn(); + + TestBed.configureTestingModule({ + providers: [ + ReaderPreferencesService, + {provide: UserService, useValue: {currentUser, updateUserSetting}}, + {provide: MessageService, useValue: {add: vi.fn()}}, + {provide: TranslocoService, useValue: {translate: vi.fn()}}, + ] + }); + + const service = TestBed.inject(ReaderPreferencesService); + + expect(() => service.updatePreference(['ebookReaderSetting', 'fontSize'], 22)).not.toThrow(); + expect(updateUserSetting).not.toHaveBeenCalled(); + }); + + it('creates missing nested branches before persisting a preference', () => { + const userSettings = createUserSettings(); + const currentUser = signal({ + id: 7, + userSettings, + permissions: { + admin: false, + canUpload: false, + canDownload: false, + canEmailBook: false, + canDeleteBook: false, + canEditMetadata: false, + canManageLibrary: false, + canManageMetadataConfig: false, + canSyncKoReader: false, + canSyncKobo: false, + canAccessOpds: false, + canAccessBookdrop: false, + canAccessLibraryStats: false, + canAccessUserStats: false, + canAccessTaskManager: false, + canManageEmailConfig: false, + canManageGlobalPreferences: false, + canManageIcons: false, + canManageFonts: true, + demoUser: false, + canBulkAutoFetchMetadata: false, + canBulkCustomFetchMetadata: false, + canBulkEditMetadata: false, + canBulkRegenerateCover: false, + canMoveOrganizeFiles: false, + canBulkLockUnlockMetadata: false, + } as unknown as User['permissions'], + username: 'reader', + name: 'Reader', + email: 'reader@example.test', + assignedLibraries: [], + } as unknown as User); + const updateUserSetting = vi.fn(); + + TestBed.configureTestingModule({ + providers: [ + ReaderPreferencesService, + {provide: UserService, useValue: {currentUser, updateUserSetting}}, + {provide: MessageService, useValue: {add: vi.fn()}}, + {provide: TranslocoService, useValue: {translate: vi.fn()}}, + ] + }); + + const service = TestBed.inject(ReaderPreferencesService); + TestBed.flushEffects(); + + service.updatePreference(['ebookReaderSetting', 'advanced', 'fontSize'], 22); + + expect(updateUserSetting).toHaveBeenCalledWith(7, 'ebookReaderSetting', expect.objectContaining({ + advanced: {fontSize: 22} + })); + expect(userSettings.ebookReaderSetting).toEqual(expect.objectContaining({ + advanced: {fontSize: 22} + })); + }); +}); diff --git a/frontend/src/app/features/settings/reader-preferences/settings-application-mode/settings-application-mode.component.spec.ts b/frontend/src/app/features/settings/reader-preferences/settings-application-mode/settings-application-mode.component.spec.ts new file mode 100644 index 000000000..4feb4d857 --- /dev/null +++ b/frontend/src/app/features/settings/reader-preferences/settings-application-mode/settings-application-mode.component.spec.ts @@ -0,0 +1,73 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; + +import {SettingsApplicationModeComponent} from './settings-application-mode.component'; +import {ReaderPreferencesService} from '../reader-preferences.service'; +import {TranslocoService} from '@jsverse/transloco'; +import {UserSettings} from '../../user-management/user.service'; + +describe('SettingsApplicationModeComponent', () => { + function createUserSettings(): UserSettings { + return { + perBookSetting: {pdf: 'Global', epub: 'Individual', cbx: 'Global'}, + pdfReaderSetting: {pageSpread: 'off', pageZoom: '100%', showSidebar: true}, + epubReaderSetting: {theme: 'light', font: 'serif', fontSize: 16, flow: 'paginated', spread: 'auto', lineHeight: 1.5, margin: 1, letterSpacing: 0}, + ebookReaderSetting: {lineHeight: 1.5, justify: true, hyphenate: true, maxColumnCount: 1, gap: 1, fontSize: 16, theme: 'light', maxInlineSize: 100, maxBlockSize: 100, fontFamily: 'serif', isDark: false, flow: 'paginated'}, + cbxReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'}, + newPdfReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'}, + sidebarLibrarySorting: {field: 'name', order: 'ASC'}, + sidebarShelfSorting: {field: 'name', order: 'ASC'}, + sidebarMagicShelfSorting: {field: 'name', order: 'ASC'}, + filterMode: 'and', + metadataCenterViewMode: 'route', + enableSeriesView: true, + entityViewPreferences: {global: {sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 100, seriesCollapsed: false, overlayBookType: false}, overrides: []}, + koReaderEnabled: false, + autoSaveMetadata: true, + } as UserSettings; + } + + let fixture: ComponentFixture; + let updatePreference: ReturnType; + + beforeEach(() => { + updatePreference = vi.fn(); + + TestBed.configureTestingModule({ + imports: [SettingsApplicationModeComponent], + providers: [ + {provide: ReaderPreferencesService, useValue: {updatePreference}}, + {provide: TranslocoService, useValue: {translate: vi.fn((key: string) => key)}}, + ] + }); + + fixture = TestBed.createComponent(SettingsApplicationModeComponent); + fixture.componentInstance.userSettings = createUserSettings(); + }); + + it('loads preferences and forwards updates for each scope', () => { + const component = fixture.componentInstance; + + component.ngOnInit(); + + expect(component.selectedPdfScope).toBe('Global'); + expect(component.selectedNewPdfScope).toBe('Global'); + expect(component.selectedEpubScope).toBe('Individual'); + expect(component.selectedCbxScope).toBe('Global'); + + component.selectedPdfScope = 'Individual'; + component.selectedNewPdfScope = 'Individual'; + component.selectedEpubScope = 'Global'; + component.selectedCbxScope = 'Individual'; + + component.onPdfScopeChange(); + component.onNewPdfScopeChange(); + component.onEpubScopeChange(); + component.onCbxScopeChange(); + + expect(updatePreference).toHaveBeenNthCalledWith(1, ['perBookSetting', 'pdf'], 'Individual'); + expect(updatePreference).toHaveBeenNthCalledWith(2, ['perBookSetting', 'newPdf'], 'Individual'); + expect(updatePreference).toHaveBeenNthCalledWith(3, ['perBookSetting', 'epub'], 'Global'); + expect(updatePreference).toHaveBeenNthCalledWith(4, ['perBookSetting', 'cbx'], 'Individual'); + }); +}); diff --git a/frontend/src/app/features/settings/settings.component.spec.ts b/frontend/src/app/features/settings/settings.component.spec.ts new file mode 100644 index 000000000..9eead2a65 --- /dev/null +++ b/frontend/src/app/features/settings/settings.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around route/query-param synchronization, +// lazy tab composition, and nested settings child activation so tab selection can be asserted +// without mounting the full router-backed settings shell. +describe.skip('SettingsComponent', () => { + it('needs router seams to verify initial tab resolution and query-param updates', () => { + // TODO(seam): Cover activeTab bootstrapping and route synchronization once ActivatedRoute and Router state are isolated behind deterministic doubles. + }); + + it('needs shell seams to verify tab-switch navigation across the composed settings surface', () => { + // TODO(seam): Cover tab click behavior after the routed settings shell is extracted from PrimeNG tab and router outlet runtime concerns. + }); +}); diff --git a/frontend/src/app/features/settings/task-management/task-helper.service.spec.ts b/frontend/src/app/features/settings/task-management/task-helper.service.spec.ts new file mode 100644 index 000000000..6339cf868 --- /dev/null +++ b/frontend/src/app/features/settings/task-management/task-helper.service.spec.ts @@ -0,0 +1,89 @@ +import {TestBed} from '@angular/core/testing'; +import {describe, expect, it, vi} from 'vitest'; +import {firstValueFrom, of, throwError} from 'rxjs'; + +import {TaskHelperService} from './task-helper.service'; +import {TaskService, TaskType} from './task.service'; +import {MessageService} from 'primeng/api'; +import {TranslocoService} from '@jsverse/transloco'; + +describe('TaskHelperService', () => { + it('schedules metadata refresh tasks', async () => { + const startTask = vi.fn(() => of({type: TaskType.REFRESH_METADATA_MANUAL, status: 'ACCEPTED'})); + const messageAdd = vi.fn(); + const translate = vi.fn((key: string) => key); + + TestBed.configureTestingModule({ + providers: [ + TaskHelperService, + {provide: TaskService, useValue: {startTask}}, + {provide: MessageService, useValue: {add: messageAdd}}, + {provide: TranslocoService, useValue: {translate}}, + ] + }); + + const service = TestBed.inject(TaskHelperService); + + await expect(firstValueFrom(service.refreshMetadataTask({libraryIds: [1]} as never))).resolves.toEqual({success: true}); + expect(startTask).toHaveBeenCalledWith({ + taskType: TaskType.REFRESH_METADATA_MANUAL, + triggeredByCron: false, + options: {libraryIds: [1]} + }); + expect(messageAdd).toHaveBeenCalledWith({ + severity: 'success', + summary: 'settingsTasks.toast.metadataScheduled', + detail: 'settingsTasks.toast.metadataScheduledDetail' + }); + }); + + it('maps task conflicts to the already running error toast', async () => { + const startTask = vi.fn(() => throwError(() => ({status: 409}))); + const messageAdd = vi.fn(); + const translate = vi.fn((key: string) => key); + + TestBed.configureTestingModule({ + providers: [ + TaskHelperService, + {provide: TaskService, useValue: {startTask}}, + {provide: MessageService, useValue: {add: messageAdd}}, + {provide: TranslocoService, useValue: {translate}}, + ] + }); + + const service = TestBed.inject(TaskHelperService); + + await expect(firstValueFrom(service.refreshMetadataTask({libraryIds: [1]} as never))).resolves.toEqual({success: false}); + expect(messageAdd).toHaveBeenCalledWith({ + severity: 'error', + summary: 'settingsTasks.toast.alreadyRunning', + life: 5000, + detail: 'settingsTasks.toast.metadataAlreadyRunningDetail' + }); + }); + + it('maps non-conflict failures to the generic error toast', async () => { + const startTask = vi.fn(() => throwError(() => ({status: 500}))); + const messageAdd = vi.fn(); + const translate = vi.fn((key: string) => key); + + TestBed.configureTestingModule({ + providers: [ + TaskHelperService, + {provide: TaskService, useValue: {startTask}}, + {provide: MessageService, useValue: {add: messageAdd}}, + {provide: TranslocoService, useValue: {translate}}, + ] + }); + + const service = TestBed.inject(TaskHelperService); + + await expect(firstValueFrom(service.refreshMetadataTask({libraryIds: [1]} as never))).resolves.toEqual({success: false}); + expect(messageAdd).toHaveBeenCalledWith({ + severity: 'error', + summary: 'settingsTasks.toast.metadataFailed', + life: 5000, + detail: 'settingsTasks.toast.metadataFailedDetail' + }); + }); +}); diff --git a/frontend/src/app/features/settings/task-management/task-management.component.spec.ts b/frontend/src/app/features/settings/task-management/task-management.component.spec.ts new file mode 100644 index 000000000..921a8f90f --- /dev/null +++ b/frontend/src/app/features/settings/task-management/task-management.component.spec.ts @@ -0,0 +1,373 @@ +import {NO_ERRORS_SCHEMA} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {Observable, Subject, of, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {TranslocoService} from '@jsverse/transloco'; +import {MessageService} from 'primeng/api'; +import { + MetadataReplaceMode, + TaskHistory, + TaskInfo, + TaskProgressPayload, + TaskService, + TaskStatus, + TaskType, +} from './task.service'; +import {TaskManagementComponent} from './task-management.component'; + +describe('TaskManagementComponent', () => { + let component: TaskManagementComponent; + let taskService: { + getAvailableTasks: ReturnType; + getLatestTasksForEachType: ReturnType; + taskProgress$: Observable; + startTask: ReturnType; + cancelTask: ReturnType; + updateCronConfig: ReturnType; + }; + let taskProgressSubject: Subject; + let messageService: { + add: ReturnType; + }; + let translate: ReturnType; + + const clearPdfTask: TaskInfo = { + taskType: TaskType.CLEAR_PDF_CACHE, + name: 'Clear PDF cache', + description: 'Clear the cached PDF files.', + parallel: false, + async: false, + cronSupported: true, + cronConfig: { + id: 7, + taskType: TaskType.CLEAR_PDF_CACHE, + cronExpression: '0 0 * * * *', + enabled: true, + options: null, + createdAt: '2026-03-27T03:00:00Z', + updatedAt: '2026-03-27T03:00:00Z', + }, + metadata: ' cache cleanup ', + }; + + const refreshMetadataTask: TaskInfo = { + taskType: TaskType.REFRESH_LIBRARY_METADATA, + name: 'Refresh metadata', + description: 'Refresh library metadata.', + parallel: false, + async: true, + cronSupported: false, + cronConfig: null, + }; + + const pendingHistory: TaskHistory = { + id: 'task-1', + type: TaskType.CLEAR_PDF_CACHE, + status: TaskStatus.PENDING, + progressPercentage: 10, + message: 'working', + createdAt: '2026-03-27T03:00:00Z', + updatedAt: '2026-03-27T03:01:00Z', + completedAt: null, + }; + + const inProgressHistory: TaskHistory = { + ...pendingHistory, + status: TaskStatus.IN_PROGRESS, + updatedAt: '2026-03-27T02:55:00Z', + }; + + beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-03-27T03:06:00Z')); + + taskProgressSubject = new Subject(); + translate = vi.fn((key: string, params?: Record) => (params ? `${key}:${JSON.stringify(params)}` : key)); + messageService = { + add: vi.fn(), + }; + taskService = { + getAvailableTasks: vi.fn(() => of([refreshMetadataTask, clearPdfTask])), + getLatestTasksForEachType: vi.fn(() => of({ + taskHistories: [pendingHistory], + })), + taskProgress$: taskProgressSubject.asObservable(), + startTask: vi.fn(() => of({ + type: TaskType.CLEAR_PDF_CACHE, + status: TaskStatus.ACCEPTED, + })), + cancelTask: vi.fn(() => of({ + taskId: 'task-1', + cancelled: true, + message: 'cancelled', + })), + updateCronConfig: vi.fn(() => of({ + id: 7, + taskType: TaskType.CLEAR_PDF_CACHE, + cronExpression: '0 0 * * * *', + enabled: true, + options: null, + createdAt: '2026-03-27T03:00:00Z', + updatedAt: '2026-03-27T03:00:00Z', + })), + }; + + TestBed.configureTestingModule({ + imports: [TaskManagementComponent], + schemas: [NO_ERRORS_SCHEMA], + providers: [ + {provide: TaskService, useValue: taskService}, + {provide: MessageService, useValue: messageService}, + {provide: TranslocoService, useValue: {translate}}, + ], + }); + + component = TestBed.createComponent(TaskManagementComponent).componentInstance; + }); + + afterEach(() => { + vi.useRealTimers(); + TestBed.resetTestingModule(); + }); + + it('loads tasks, sorts them, and attaches latest task histories on init', () => { + component.ngOnInit(); + + expect(taskService.getAvailableTasks).toHaveBeenCalledTimes(1); + expect(taskService.getLatestTasksForEachType).toHaveBeenCalledTimes(1); + expect(component.taskInfos.map(task => task.taskType)).toEqual([ + TaskType.REFRESH_LIBRARY_METADATA, + TaskType.CLEAR_PDF_CACHE, + ]); + expect(component.getTaskHistory(TaskType.CLEAR_PDF_CACHE)).toMatchObject({ + id: 'task-1', + status: TaskStatus.PENDING, + }); + expect(component.loading).toBe(false); + }); + + it('reports load failures through the message service', () => { + taskService.getAvailableTasks = vi.fn(() => throwError(() => new Error('boom'))); + + component.ngOnInit(); + + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'common.error', + detail: 'settingsTasks.toast.loadError', + }); + }); + + it('tracks task progress updates and reloads after a completed task', () => { + const loadTasksSpy = vi.spyOn(component, 'loadTasks'); + + component.ngOnInit(); + expect(loadTasksSpy).toHaveBeenCalledTimes(1); + + taskProgressSubject.next({ + taskId: 'task-2', + taskType: TaskType.CLEAR_PDF_CACHE, + message: 'done', + progress: 100, + taskStatus: TaskStatus.COMPLETED, + }); + + expect(component.getTaskHistory(TaskType.CLEAR_PDF_CACHE)).toMatchObject({ + id: 'task-2', + status: TaskStatus.COMPLETED, + completedAt: expect.any(String), + }); + + vi.advanceTimersByTime(1000); + + expect(loadTasksSpy).toHaveBeenCalledTimes(2); + }); + + it('distinguishes running, stale, and cancellable tasks', () => { + component.taskHistories.set(TaskType.CLEAR_PDF_CACHE, inProgressHistory); + + expect(component.isTaskRunning(TaskType.CLEAR_PDF_CACHE)).toBe(true); + expect(component.canCancelTask(inProgressHistory)).toBe(true); + expect(component.canExecuteTask(TaskType.CLEAR_PDF_CACHE)).toBe(true); + expect(component.isTaskStale(inProgressHistory)).toBe(true); + expect(component.getTaskButtonLabel(TaskType.CLEAR_PDF_CACHE)).toBe('settingsTasks.buttons.rerun'); + + component.taskHistories.set(TaskType.CLEAR_PDF_CACHE, { + ...inProgressHistory, + updatedAt: '2026-03-27T03:05:45Z', + }); + + expect(component.isTaskStale(component.getTaskHistory(TaskType.CLEAR_PDF_CACHE))).toBe(false); + expect(component.canExecuteTask(TaskType.CLEAR_PDF_CACHE)).toBe(false); + expect(component.getTaskButtonLabel(TaskType.CLEAR_PDF_CACHE)).toBe('settingsTasks.buttons.run'); + }); + + it('blocks duplicate task execution when the task is still fresh', () => { + component.taskHistories.set(TaskType.CLEAR_PDF_CACHE, { + ...inProgressHistory, + updatedAt: '2026-03-27T03:05:45Z', + }); + + component.runTask(TaskType.CLEAR_PDF_CACHE); + + expect(taskService.startTask).not.toHaveBeenCalled(); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'warn', + summary: 'settingsTasks.toast.alreadyRunning', + detail: 'settingsTasks.toast.alreadyRunningDetail', + }); + }); + + it('queues async metadata refresh tasks with the selected replace mode', () => { + component.selectedMetadataReplaceMode = MetadataReplaceMode.REPLACE_ALL; + + component.runTask(TaskType.REFRESH_LIBRARY_METADATA); + + expect(taskService.startTask).toHaveBeenCalledWith({ + taskType: TaskType.REFRESH_LIBRARY_METADATA, + triggeredByCron: false, + options: { + metadataReplaceMode: MetadataReplaceMode.REPLACE_ALL, + }, + }); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'info', + summary: 'settingsTasks.toast.taskQueued', + detail: 'settingsTasks.toast.taskQueuedDetail:{"name":"Refresh Library Metadata"}', + }); + }); + + it('reports sync task completion and failure outcomes', () => { + component.taskHistories.set(TaskType.CLEAR_PDF_CACHE, { + ...pendingHistory, + status: TaskStatus.COMPLETED, + completedAt: '2026-03-27T03:05:50Z', + updatedAt: '2026-03-27T03:05:50Z', + }); + taskService.startTask = vi.fn(() => of({ + type: TaskType.CLEAR_PDF_CACHE, + status: TaskStatus.COMPLETED, + })); + component.runTask(TaskType.CLEAR_PDF_CACHE); + + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'settingsTasks.toast.taskCompleted', + detail: 'settingsTasks.toast.taskCompletedDetail:{"name":"Clear Pdf Cache"}', + }); + + messageService.add.mockClear(); + component.taskHistories.set(TaskType.CLEAR_PDF_CACHE, { + ...pendingHistory, + status: TaskStatus.COMPLETED, + completedAt: '2026-03-27T03:05:55Z', + updatedAt: '2026-03-27T03:05:55Z', + }); + taskService.startTask = vi.fn(() => of({ + type: TaskType.CLEAR_PDF_CACHE, + status: TaskStatus.FAILED, + message: 'nope', + })); + component.runTask(TaskType.CLEAR_PDF_CACHE); + + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'settingsTasks.toast.taskFailed', + detail: 'nope', + }); + }); + + it('cancels tasks and handles both success and failure paths', () => { + component.taskHistories.set(TaskType.CLEAR_PDF_CACHE, pendingHistory); + component.cancelTask(TaskType.CLEAR_PDF_CACHE); + + expect(taskService.cancelTask).toHaveBeenCalledWith('task-1'); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'settingsTasks.toast.taskCancelled', + detail: 'cancelled', + }); + + messageService.add.mockClear(); + taskService.cancelTask = vi.fn(() => of({ + taskId: 'task-1', + cancelled: false, + message: 'busy', + })); + component.cancelTask(TaskType.CLEAR_PDF_CACHE); + + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'settingsTasks.toast.cancelFailed', + detail: 'busy', + }); + }); + + it('validates cron expressions and saves trimmed updates', () => { + component.taskInfos = [clearPdfTask]; + + component.startEditingCron(TaskType.CLEAR_PDF_CACHE); + expect(component.isEditingCron(TaskType.CLEAR_PDF_CACHE)).toBe(true); + expect(component.editingCronExpression).toBe('0 0 * * * *'); + + component.editingCronExpression = '*/5 0-23 * * ? 0'; + component.onCronExpressionChange(); + expect(component.cronValidationError).toBeNull(); + + component.editingCronExpression = 'invalid'; + component.onCronExpressionChange(); + expect(component.cronValidationError).toBe('settingsTasks.cron.validationPrefix'); + + component.saveCronExpression(TaskType.CLEAR_PDF_CACHE); + expect(taskService.updateCronConfig).not.toHaveBeenCalled(); + + component.editingCronExpression = ' 0 15 * * * * '; + component.onCronExpressionChange(); + component.saveCronExpression(TaskType.CLEAR_PDF_CACHE); + + expect(taskService.updateCronConfig).toHaveBeenCalledWith(TaskType.CLEAR_PDF_CACHE, { + cronExpression: '0 15 * * * *', + }); + expect(component.isEditingCron(TaskType.CLEAR_PDF_CACHE)).toBe(false); + expect(component.cronValidationError).toBeNull(); + }); + + it('updates cron state and exposes helper text and metadata helpers', () => { + component.taskInfos = [clearPdfTask]; + component.taskHistories.set(TaskType.CLEAR_PDF_CACHE, { + ...pendingHistory, + status: TaskStatus.COMPLETED, + completedAt: '2026-03-27T03:05:50Z', + updatedAt: '2026-03-27T03:05:50Z', + }); + + component.toggleCronEnabled(TaskType.CLEAR_PDF_CACHE); + expect(taskService.updateCronConfig).toHaveBeenCalledWith(TaskType.CLEAR_PDF_CACHE, { + enabled: false, + }); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'common.success', + detail: 'settingsTasks.cron.updateSuccess', + }); + + expect(component.getCronConfig(TaskType.CLEAR_PDF_CACHE)).toEqual({ + enabled: true, + cronExpression: '0 0 * * * *', + }); + expect(component.getMetadataReplaceDescription(MetadataReplaceMode.REPLACE_ALL)).toBe('settingsTasks.metadataReplace.replaceAllDesc'); + expect(component.getMetadataReplaceDescription(MetadataReplaceMode.REPLACE_MISSING)).toBe('settingsTasks.metadataReplace.replaceMissingDesc'); + expect(component.getTaskDisplayName(TaskType.CLEAR_PDF_CACHE)).toBe('Clear PDF cache'); + expect(component.getTaskDescription(TaskType.CLEAR_PDF_CACHE)).toBe('Clear the cached PDF files.'); + expect(component.getTaskLabel(TaskType.CLEAR_PDF_CACHE)).toBe('8. Clear PDF cache'); + expect(component.getTaskIcon(TaskType.CLEAR_PDF_CACHE)).toBe('pi-database'); + expect(component.getMetadataIcon(TaskType.CLEAR_PDF_CACHE)).toBe('pi-database'); + expect(component.hasMetadata(TaskType.CLEAR_PDF_CACHE)).toBe(true); + expect(component.getLastRunMessage(TaskType.CLEAR_PDF_CACHE)).toBe('settingsTasks.status.justNow'); + expect(component.getLastRunInfoClass(TaskType.CLEAR_PDF_CACHE)).toBe('success'); + expect(component.getTaskButtonIcon(TaskType.CLEAR_PDF_CACHE)).toBe('pi pi-database'); + expect(component.getCancelButtonIcon(TaskType.CLEAR_PDF_CACHE)).toBe('pi pi-times'); + expect(component.formatDate('2026-03-27T03:00:00Z')).toContain('2026'); + }); +}); diff --git a/frontend/src/app/features/settings/task-management/task.service.spec.ts b/frontend/src/app/features/settings/task-management/task.service.spec.ts new file mode 100644 index 000000000..2d2f8dd3b --- /dev/null +++ b/frontend/src/app/features/settings/task-management/task.service.spec.ts @@ -0,0 +1,98 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; +import {firstValueFrom} from 'rxjs'; +import {skip} from 'rxjs/operators'; + +import {API_CONFIG} from '../../../core/config/api-config'; +import {MetadataReplaceMode, TaskService, TaskStatus, TaskType} from './task.service'; + +describe('TaskService', () => { + let service: TaskService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + TaskService, + ] + }); + + service = TestBed.inject(TaskService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('loads available tasks', async () => { + const resultPromise = firstValueFrom(service.getAvailableTasks()); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/tasks`); + expect(request.request.method).toBe('GET'); + request.flush([{taskType: TaskType.CLEAR_PDF_CACHE, name: 'Clear cache', description: 'desc', parallel: false, async: false, cronSupported: false, cronConfig: null}]); + + await expect(resultPromise).resolves.toEqual([{taskType: TaskType.CLEAR_PDF_CACHE, name: 'Clear cache', description: 'desc', parallel: false, async: false, cronSupported: false, cronConfig: null}]); + }); + + it('starts tasks with the provided options', async () => { + const requestPromise = firstValueFrom(service.startTask({ + taskType: TaskType.REFRESH_METADATA_MANUAL, + options: {metadataReplaceMode: MetadataReplaceMode.REPLACE_ALL} + })); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/tasks/start`); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual({ + taskType: TaskType.REFRESH_METADATA_MANUAL, + options: {metadataReplaceMode: MetadataReplaceMode.REPLACE_ALL} + }); + request.flush({type: TaskType.REFRESH_METADATA_MANUAL, status: TaskStatus.ACCEPTED}); + + await expect(requestPromise).resolves.toEqual({type: TaskType.REFRESH_METADATA_MANUAL, status: TaskStatus.ACCEPTED}); + }); + + it('loads the latest task for each type', async () => { + const requestPromise = firstValueFrom(service.getLatestTasksForEachType()); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/tasks/last`); + expect(request.request.method).toBe('GET'); + request.flush({taskHistories: []}); + + await expect(requestPromise).resolves.toEqual({taskHistories: []}); + }); + + it('cancels tasks', async () => { + const requestPromise = firstValueFrom(service.cancelTask('task-1')); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/tasks/task-1/cancel`); + expect(request.request.method).toBe('DELETE'); + request.flush({taskId: 'task-1', cancelled: true, message: 'done'}); + + await expect(requestPromise).resolves.toEqual({taskId: 'task-1', cancelled: true, message: 'done'}); + }); + + it('updates cron config', async () => { + const requestPromise = firstValueFrom(service.updateCronConfig('task-type', {cronExpression: '0 0 * * *', enabled: true})); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/tasks/task-type/cron`); + expect(request.request.method).toBe('PATCH'); + expect(request.request.body).toEqual({cronExpression: '0 0 * * *', enabled: true}); + request.flush({id: 1, taskType: 'task-type', cronExpression: '0 0 * * *', enabled: true, options: null, createdAt: null, updatedAt: null}); + + await expect(requestPromise).resolves.toEqual({id: 1, taskType: 'task-type', cronExpression: '0 0 * * *', enabled: true, options: null, createdAt: null, updatedAt: null}); + }); + + it('publishes task progress updates', async () => { + const progressPromise = firstValueFrom(service.taskProgress$.pipe(skip(1))); + + service.handleTaskProgress({taskId: 'task-1', taskType: 'refresh', message: 'working', progress: 25, taskStatus: TaskStatus.IN_PROGRESS}); + + await expect(progressPromise).resolves.toEqual({taskId: 'task-1', taskType: 'refresh', message: 'working', progress: 25, taskStatus: TaskStatus.IN_PROGRESS}); + }); +}); diff --git a/frontend/src/app/features/settings/user-management/content-restriction.model.spec.ts b/frontend/src/app/features/settings/user-management/content-restriction.model.spec.ts new file mode 100644 index 000000000..55d1c572a --- /dev/null +++ b/frontend/src/app/features/settings/user-management/content-restriction.model.spec.ts @@ -0,0 +1,37 @@ +import {describe, expect, it} from 'vitest'; + +import { + AGE_RATING_OPTIONS, + CONTENT_RATINGS, + ContentRating, + ContentRestriction, + ContentRestrictionMode, + ContentRestrictionType +} from './content-restriction.model'; + +describe('content-restriction.model', () => { + it('exposes supported restriction enums and derived content ratings', () => { + expect(ContentRestrictionType.CATEGORY).toBe('CATEGORY'); + expect(ContentRestrictionMode.ALLOW_ONLY).toBe('ALLOW_ONLY'); + expect(CONTENT_RATINGS).toEqual(Object.values(ContentRating)); + }); + + it('defines age rating options in ascending order', () => { + expect(AGE_RATING_OPTIONS[0]).toEqual({value: '0', label: 'All Ages'}); + expect(AGE_RATING_OPTIONS.at(-1)).toEqual({value: '21', label: '21+'}); + }); + + it('supports persisted restriction records', () => { + const restriction: ContentRestriction = { + id: 1, + userId: 99, + restrictionType: ContentRestrictionType.TAG, + mode: ContentRestrictionMode.EXCLUDE, + value: 'spoilers', + createdAt: '2026-03-26T10:00:00Z' + }; + + expect(restriction.value).toBe('spoilers'); + expect(restriction.mode).toBe(ContentRestrictionMode.EXCLUDE); + }); +}); diff --git a/frontend/src/app/features/settings/user-management/content-restriction.service.spec.ts b/frontend/src/app/features/settings/user-management/content-restriction.service.spec.ts new file mode 100644 index 000000000..a1b238907 --- /dev/null +++ b/frontend/src/app/features/settings/user-management/content-restriction.service.spec.ts @@ -0,0 +1,107 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {API_CONFIG} from '../../../core/config/api-config'; +import {ContentRestriction, ContentRestrictionMode, ContentRestrictionType} from './content-restriction.model'; +import {ContentRestrictionService} from './content-restriction.service'; + +describe('ContentRestrictionService', () => { + let service: ContentRestrictionService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + ContentRestrictionService, + ] + }); + + service = TestBed.inject(ContentRestrictionService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('loads content restrictions', () => { + const restrictions = [{ + id: 1, + userId: 11, + restrictionType: ContentRestrictionType.TAG, + mode: ContentRestrictionMode.EXCLUDE, + value: 'TAG' + } as ContentRestriction]; + + service.getUserRestrictions(11).subscribe(result => { + expect(result).toEqual(restrictions); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/users/11/content-restrictions`); + expect(request.request.method).toBe('GET'); + request.flush(restrictions); + }); + + it('adds a restriction', () => { + const restriction = { + id: 1, + userId: 11, + restrictionType: ContentRestrictionType.TAG, + mode: ContentRestrictionMode.EXCLUDE, + value: 'TAG' + } as ContentRestriction; + + service.addRestriction(11, restriction).subscribe(result => { + expect(result).toEqual(restriction); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/users/11/content-restrictions`); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual(restriction); + request.flush(restriction); + }); + + it('updates restrictions', () => { + const restrictions = [{ + id: 1, + userId: 11, + restrictionType: ContentRestrictionType.TAG, + mode: ContentRestrictionMode.EXCLUDE, + value: 'TAG' + } as ContentRestriction]; + + service.updateRestrictions(11, restrictions).subscribe(result => { + expect(result).toEqual(restrictions); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/users/11/content-restrictions`); + expect(request.request.method).toBe('PUT'); + expect(request.request.body).toEqual(restrictions); + request.flush(restrictions); + }); + + it('deletes a single restriction', () => { + service.deleteRestriction(11, 9).subscribe(result => { + expect(result).toBeNull(); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/users/11/content-restrictions/9`); + expect(request.request.method).toBe('DELETE'); + request.flush(null); + }); + + it('deletes all restrictions for a user', () => { + service.deleteAllRestrictions(11).subscribe(result => { + expect(result).toBeNull(); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/users/11/content-restrictions`); + expect(request.request.method).toBe('DELETE'); + request.flush(null); + }); +}); diff --git a/frontend/src/app/features/settings/user-management/content-restrictions-editor/content-restrictions-editor.component.spec.ts b/frontend/src/app/features/settings/user-management/content-restrictions-editor/content-restrictions-editor.component.spec.ts new file mode 100644 index 000000000..72365d815 --- /dev/null +++ b/frontend/src/app/features/settings/user-management/content-restrictions-editor/content-restrictions-editor.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around metadata-derived option lists, +// restriction-service mutations, and translated message flows so restriction editing can be +// asserted without mounting the full editable select stack. +describe.skip('ContentRestrictionsEditorComponent', () => { + it('needs metadata seams to verify option derivation, type-label helpers, and allow versus exclude grouping', () => { + // TODO(seam): Cover getValueOptions and the grouping helpers once the computed metadata signal is isolated for direct assertions. + }); + + it('needs mutation seams to verify loading, duplicate prevention, and add and remove restriction flows', () => { + // TODO(seam): Cover loadRestrictions, addRestriction, and removeRestriction after extracting service and toast side effects behind test doubles. + }); +}); diff --git a/frontend/src/app/features/settings/user-management/create-user-dialog/create-user-dialog.component.spec.ts b/frontend/src/app/features/settings/user-management/create-user-dialog/create-user-dialog.component.spec.ts new file mode 100644 index 000000000..06162d316 --- /dev/null +++ b/frontend/src/app/features/settings/user-management/create-user-dialog/create-user-dialog.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around the large reactive form, admin +// permission fan-out side effects, and dialog-close behavior so the create-user workflow can be +// tested without mounting the full Prime form stack. +describe.skip('CreateUserDialogComponent', () => { + it('needs form seams to verify validator setup, admin permission propagation, and library selection shaping', () => { + // TODO(seam): Cover ngOnInit once the reactive-form and valueChanges runtime is isolated for deterministic assertions. + }); + + it('needs mutation seams to verify invalid-form warnings and create-user success and failure flows', () => { + // TODO(seam): Cover createUser after extracting message and dialog-close side effects behind test doubles. + }); +}); diff --git a/frontend/src/app/features/settings/user-management/user-management.component.spec.ts b/frontend/src/app/features/settings/user-management/user-management.component.spec.ts new file mode 100644 index 000000000..0c7092dce --- /dev/null +++ b/frontend/src/app/features/settings/user-management/user-management.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around table row editing, confirm dialog +// usage, password dialog state, and dialog-launcher interactions so user administration can be +// exercised without building the full Prime table and modal stack. +describe.skip('UserManagementComponent', () => { + it('needs service seams to verify user loading, edit toggling, and save payload shaping', () => { + // TODO(seam): Cover loadUsers, toggleEdit, and saveUser once the table-editing state and async user-service flows are isolated. + }); + + it('needs dialog seams to verify create-user refresh, delete confirmation, and password-change validation', () => { + // TODO(seam): Cover openCreateUserDialog, deleteUser, and submitPasswordChange after extracting confirm and modal runtime concerns. + }); +}); diff --git a/frontend/src/app/features/settings/user-management/user-query-keys.spec.ts b/frontend/src/app/features/settings/user-management/user-query-keys.spec.ts new file mode 100644 index 000000000..85e44ddf8 --- /dev/null +++ b/frontend/src/app/features/settings/user-management/user-query-keys.spec.ts @@ -0,0 +1,9 @@ +import {describe, expect, it} from 'vitest'; + +import {CURRENT_USER_QUERY_KEY} from './user-query-keys'; + +describe('user-query-keys', () => { + it('uses a stable cache key for the current user record', () => { + expect(CURRENT_USER_QUERY_KEY).toEqual(['currentUser']); + }); +}); diff --git a/frontend/src/app/features/settings/user-management/user-stats.service.spec.ts b/frontend/src/app/features/settings/user-management/user-stats.service.spec.ts new file mode 100644 index 000000000..ed5f5c630 --- /dev/null +++ b/frontend/src/app/features/settings/user-management/user-stats.service.spec.ts @@ -0,0 +1,104 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {UserStatsService} from './user-stats.service'; + +describe('UserStatsService', () => { + let service: UserStatsService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + UserStatsService, + ], + }); + + service = TestBed.inject(UserStatsService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('requests the yearly heatmap with the year query param', () => { + let result: unknown; + service.getHeatmapForYear(2026).subscribe(value => { + result = value; + }); + + const request = httpTestingController.expectOne(req => + req.url.endsWith('/api/v1/user-stats/reading/heatmap') + && req.params.get('year') === '2026' + ); + expect(request.request.method).toBe('GET'); + request.flush([{date: '2026-03-26', count: 3}]); + + expect(result).toEqual([{date: '2026-03-26', count: 3}]); + }); + + it('requests the weekly reading timeline with both year and week params', () => { + service.getTimelineForWeek(2026, 13).subscribe(); + + const request = httpTestingController.expectOne(req => + req.url.endsWith('/api/v1/user-stats/reading/timeline') + && req.params.get('year') === '2026' + && req.params.get('week') === '13' + ); + expect(request.request.method).toBe('GET'); + request.flush([]); + }); + + it('omits optional params when requesting favorite days without filters', () => { + service.getFavoriteDays().subscribe(); + + const request = httpTestingController.expectOne(req => + req.url.endsWith('/api/v1/user-stats/reading/favorite-days') + ); + expect(request.request.params.keys()).toEqual([]); + request.flush([]); + }); + + it('includes optional params for peak hours when year and month are provided', () => { + service.getPeakHours(2026, 3).subscribe(); + + const request = httpTestingController.expectOne(req => + req.url.endsWith('/api/v1/user-stats/reading/peak-hours') + && req.params.get('year') === '2026' + && req.params.get('month') === '3' + ); + expect(request.request.method).toBe('GET'); + request.flush([]); + }); + + it('requests the remaining stats endpoints with the expected URLs', () => { + service.getGenreStats().subscribe(); + service.getCompletionTimelineForYear(2026).subscribe(); + service.getPageTurnerScores().subscribe(); + service.getCompletionRace(2026).subscribe(); + service.getReadingDates().subscribe(); + service.getSessionScatter(2026).subscribe(); + + httpTestingController.expectOne(req => req.url.endsWith('/api/v1/user-stats/reading/genres')).flush([]); + httpTestingController.expectOne(req => + req.url.endsWith('/api/v1/user-stats/reading/completion-timeline') + && req.params.get('year') === '2026' + ).flush([]); + httpTestingController.expectOne(req => req.url.endsWith('/api/v1/user-stats/reading/page-turner-scores')).flush([]); + httpTestingController.expectOne(req => + req.url.endsWith('/api/v1/user-stats/reading/completion-race') + && req.params.get('year') === '2026' + ).flush([]); + httpTestingController.expectOne(req => req.url.endsWith('/api/v1/user-stats/reading/dates')).flush([]); + httpTestingController.expectOne(req => + req.url.endsWith('/api/v1/user-stats/reading/session-scatter') + && req.params.get('year') === '2026' + ).flush([]); + }); +}); diff --git a/frontend/src/app/features/settings/user-management/user.service.spec.ts b/frontend/src/app/features/settings/user-management/user.service.spec.ts new file mode 100644 index 000000000..56567d271 --- /dev/null +++ b/frontend/src/app/features/settings/user-management/user.service.spec.ts @@ -0,0 +1,241 @@ +import {HttpTestingController} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {AuthService} from '../../../shared/service/auth.service'; +import {createAuthServiceStub, createQueryClientHarness, flushSignalAndQueryEffects} from '../../../core/testing/query-testing'; +import {CURRENT_USER_QUERY_KEY} from './user-query-keys'; +import {type User, type UserSettings, UserService} from './user.service'; + +type BuildUserOverrides = Omit, 'permissions' | 'userSettings'> & { + permissions?: Partial; + userSettings?: Partial; +}; + +function buildUserSettings(overrides: Partial = {}): UserSettings { + return { + perBookSetting: {pdf: 'pdf', epub: 'epub', cbx: 'cbx'}, + pdfReaderSetting: {pageSpread: 'off', pageZoom: '100%', showSidebar: true}, + epubReaderSetting: { + theme: 'light', + font: 'serif', + fontSize: 16, + flow: 'paginated', + spread: 'auto', + lineHeight: 1.5, + margin: 1, + letterSpacing: 0, + }, + ebookReaderSetting: { + lineHeight: 1.5, + justify: true, + hyphenate: true, + maxColumnCount: 1, + gap: 1, + fontSize: 16, + theme: 'light', + maxInlineSize: 100, + maxBlockSize: 100, + fontFamily: 'serif', + isDark: false, + flow: 'paginated', + }, + cbxReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'}, + newPdfReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'}, + sidebarLibrarySorting: {field: 'name', order: 'ASC'}, + sidebarShelfSorting: {field: 'name', order: 'ASC'}, + sidebarMagicShelfSorting: {field: 'name', order: 'ASC'}, + filterMode: 'and', + metadataCenterViewMode: 'route', + enableSeriesView: true, + entityViewPreferences: { + global: { + sortKey: 'title', + sortDir: 'ASC', + view: 'GRID', + coverSize: 100, + seriesCollapsed: false, + overlayBookType: false, + }, + overrides: [], + }, + koReaderEnabled: false, + autoSaveMetadata: true, + ...overrides, + } as UserSettings; +} + +function buildUser(overrides: BuildUserOverrides = {}): User { + const {permissions: permissionOverrides, userSettings, ...userOverrides} = overrides; + const permissions: User['permissions'] = { + admin: false, + canUpload: false, + canDownload: false, + canEmailBook: false, + canDeleteBook: false, + canEditMetadata: false, + canManageLibrary: false, + canManageMetadataConfig: false, + canSyncKoReader: false, + canSyncKobo: false, + canAccessOpds: false, + canAccessBookdrop: false, + canAccessLibraryStats: false, + canAccessUserStats: false, + canAccessTaskManager: false, + canManageEmailConfig: false, + canManageGlobalPreferences: false, + canManageIcons: false, + canManageFonts: false, + demoUser: false, + canBulkAutoFetchMetadata: false, + canBulkCustomFetchMetadata: false, + canBulkEditMetadata: false, + canBulkRegenerateCover: false, + canMoveOrganizeFiles: false, + canBulkLockUnlockMetadata: false, + canBulkResetGrimmoryReadProgress: false, + canBulkResetBookloreReadProgress: false, + canBulkResetKoReaderReadProgress: false, + canBulkResetBookReadStatus: false, + }; + + if (permissionOverrides) { + Object.assign(permissions, permissionOverrides); + } + + return { + id: 7, + username: 'reader', + name: 'Reader', + email: 'reader@example.test', + assignedLibraries: [], + permissions, + userSettings: buildUserSettings(userSettings), + ...userOverrides, + }; +} + +async function flushCurrentUserQuery(): Promise { + await Promise.resolve(); + flushSignalAndQueryEffects(); + await new Promise(resolve => setTimeout(resolve, 0)); + flushSignalAndQueryEffects(); + await Promise.resolve(); + flushSignalAndQueryEffects(); +} + +describe('UserService', () => { + let service: UserService; + let httpTestingController: HttpTestingController; + let authService: ReturnType; + let queryClientHarness: ReturnType; + + beforeEach(() => { + authService = createAuthServiceStub(); + queryClientHarness = createQueryClientHarness(); + queryClientHarness.queryClient.setDefaultOptions({ + queries: { + retry: false, + }, + }); + + TestBed.configureTestingModule({ + providers: [ + ...queryClientHarness.providers, + UserService, + {provide: AuthService, useValue: authService}, + ], + }); + + service = TestBed.inject(UserService); + httpTestingController = TestBed.inject(HttpTestingController); + flushSignalAndQueryEffects(); + }); + + afterEach(() => { + httpTestingController.verify(); + queryClientHarness.queryClient.clear(); + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('eagerly fetches /users/me and normalizes the permission alias into current-user state', async () => { + expect(service.currentUser()).toBeNull(); + expect(service.isUserLoading()).toBe(true); + expect(service.userError()).toBeNull(); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/users/me')); + expect(request.request.method).toBe('GET'); + request.flush(buildUser({ + permissions: { + canBulkResetGrimmoryReadProgress: undefined, + canBulkResetBookloreReadProgress: true, + }, + })); + await flushCurrentUserQuery(); + + expect(service.currentUser()).toEqual(expect.objectContaining({ + id: 7, + username: 'reader', + })); + expect(service.currentUser()?.permissions.canBulkResetGrimmoryReadProgress).toBe(true); + expect(service.currentUser()?.permissions.canBulkResetBookloreReadProgress).toBe(true); + expect(service.isUserLoading()).toBe(false); + expect(service.userError()).toBeNull(); + }); + + it('derives a query error when the eager current-user request fails', async () => { + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/users/me')); + request.flush({message: 'boom'}, {status: 500, statusText: 'Server Error'}); + await flushCurrentUserQuery(); + + expect(service.currentUser()).toBeNull(); + expect(service.isUserLoading()).toBe(false); + expect(service.userError()).toBe('Failed to load user'); + }); + + it('removes the current-user cache when the auth token is cleared', async () => { + const removeQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'removeQueries'); + + httpTestingController.expectOne(req => req.url.endsWith('/api/v1/users/me')).flush(buildUser()); + await flushCurrentUserQuery(); + expect(queryClientHarness.queryClient.getQueryData(CURRENT_USER_QUERY_KEY)).toEqual(expect.objectContaining({id: 7})); + + authService.token.set(null); + flushSignalAndQueryEffects(); + + expect(removeQueriesSpy).toHaveBeenCalledWith({queryKey: CURRENT_USER_QUERY_KEY}); + expect(queryClientHarness.queryClient.getQueryData(CURRENT_USER_QUERY_KEY)).toBeUndefined(); + expect(service.currentUser()).toBeNull(); + expect(service.isUserLoading()).toBe(false); + expect(service.userError()).toBeNull(); + }); + + it('updates the cached current user after updateUserSetting succeeds', async () => { + httpTestingController.expectOne(req => req.url.endsWith('/api/v1/users/me')).flush(buildUser()); + await flushCurrentUserQuery(); + service.setInitialUser(buildUser({ + id: 21, + userSettings: buildUserSettings({filterMode: 'and'}), + })); + await flushCurrentUserQuery(); + + service.updateUserSetting(21, 'filterMode', 'or'); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/users/21/settings')); + expect(request.request.method).toBe('PUT'); + expect(request.request.body).toEqual({key: 'filterMode', value: 'or'}); + expect(request.request.headers.get('Content-Type')).toBe('application/json'); + request.flush(''); + await flushCurrentUserQuery(); + + expect(service.currentUser()?.userSettings.filterMode).toBe('or'); + expect(queryClientHarness.queryClient.getQueryData(CURRENT_USER_QUERY_KEY)).toEqual( + expect.objectContaining({ + id: 21, + userSettings: expect.objectContaining({filterMode: 'or'}), + }), + ); + }); +}); diff --git a/frontend/src/app/features/settings/user-profile-dialog/user-profile-dialog.component.spec.ts b/frontend/src/app/features/settings/user-profile-dialog/user-profile-dialog.component.spec.ts new file mode 100644 index 000000000..732b0c126 --- /dev/null +++ b/frontend/src/app/features/settings/user-profile-dialog/user-profile-dialog.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around the user-service signal effect, +// PrimeNG password controls, and toast/dialog side effects so profile edit and password-change +// branches can be asserted without mounting the full dialog runtime. +describe.skip('UserProfileDialogComponent', () => { + it('needs user-signal seams to verify profile bootstrap, edit toggling, no-change exits, and update failures', () => { + // TODO(seam): Cover resetEditForm and updateProfile after the current-user signal and updateUser observable can be driven through deterministic doubles. + }); + + it('needs form and dialog seams to verify password validation, password-change outcomes, and close behavior', () => { + // TODO(seam): Cover passwordMatchValidator, submitPasswordChange, and closeDialog after the password inputs and message service are isolated behind a stable test harness. + }); +}); diff --git a/frontend/src/app/features/settings/view-preferences-parent/filter-preferences/filter-preferences.component.spec.ts b/frontend/src/app/features/settings/view-preferences-parent/filter-preferences/filter-preferences.component.spec.ts new file mode 100644 index 000000000..0fabae0b2 --- /dev/null +++ b/frontend/src/app/features/settings/view-preferences-parent/filter-preferences/filter-preferences.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around signal-backed user-preference +// hydration, drag/drop reorder behavior, and PrimeNG selection widgets so filter persistence can +// be asserted without the full view-preferences runtime. +describe.skip('FilterPreferencesComponent', () => { + it('needs preference seams to verify bootstrap, reset, and save behavior for filter visibility state', () => { + // TODO(seam): Cover the effect-driven settings sync once user preferences can be injected through deterministic doubles. + }); + + it('needs drag/drop seams to verify ordering and selection changes without CDK/PrimeNG widget runtime coupling', () => { + // TODO(seam): Cover reorder and toggle flows after the drag-drop and pick-list interactions are isolated behind a testable adapter. + }); +}); diff --git a/frontend/src/app/features/settings/view-preferences-parent/meta-center-view-mode/meta-center-view-mode-component.spec.ts b/frontend/src/app/features/settings/view-preferences-parent/meta-center-view-mode/meta-center-view-mode-component.spec.ts new file mode 100644 index 000000000..656bb7e85 --- /dev/null +++ b/frontend/src/app/features/settings/view-preferences-parent/meta-center-view-mode/meta-center-view-mode-component.spec.ts @@ -0,0 +1,115 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {of} from 'rxjs'; +import {describe, expect, it, vi} from 'vitest'; + +import {MetaCenterViewModeComponent} from './meta-center-view-mode-component'; +import {User, UserService} from '../../user-management/user.service'; +import {MessageService} from 'primeng/api'; +import {TranslocoService} from '@jsverse/transloco'; + +describe('MetaCenterViewModeComponent', () => { + function createUser(preferences: Partial = {}): User { + return { + id: 7, + userSettings: { + metadataCenterViewMode: 'dialog', + enableSeriesView: true, + perBookSetting: {pdf: 'Global', epub: 'Global', cbx: 'Global'}, + pdfReaderSetting: {pageSpread: 'off', pageZoom: '100%', showSidebar: true}, + epubReaderSetting: {theme: 'light', font: 'serif', fontSize: 16, flow: 'paginated', spread: 'auto', lineHeight: 1.5, margin: 1, letterSpacing: 0}, + ebookReaderSetting: {lineHeight: 1.5, justify: true, hyphenate: true, maxColumnCount: 1, gap: 1, fontSize: 16, theme: 'light', maxInlineSize: 100, maxBlockSize: 100, fontFamily: 'serif', isDark: false, flow: 'paginated'}, + cbxReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'}, + newPdfReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'}, + sidebarLibrarySorting: {field: 'name', order: 'ASC'}, + sidebarShelfSorting: {field: 'name', order: 'ASC'}, + sidebarMagicShelfSorting: {field: 'name', order: 'ASC'}, + filterMode: 'and', + entityViewPreferences: {global: {sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 100, seriesCollapsed: false, overlayBookType: false}, overrides: []}, + koReaderEnabled: false, + autoSaveMetadata: true, + ...preferences, + }, + permissions: {admin: false, canManageFonts: true}, + username: 'reader', + name: 'Reader', + email: 'reader@example.test', + assignedLibraries: [], + } as unknown as User; + } + + it('hydrates preferences from the current user and persists changes', () => { + const currentUser = signal(null); + const updateUserSetting = vi.fn(); + const messageAdd = vi.fn(); + const translate = vi.fn((key: string) => key); + + TestBed.configureTestingModule({ + imports: [MetaCenterViewModeComponent], + providers: [ + {provide: UserService, useValue: {currentUser, getCurrentUser: vi.fn(() => currentUser()), updateUserSetting}}, + {provide: MessageService, useValue: {add: messageAdd}}, + {provide: TranslocoService, useValue: { + translate, + config: {reRenderOnLangChange: false}, + langChanges$: of('en'), + _loadDependencies: vi.fn(() => of([])), + }}, + ] + }); + + currentUser.set(createUser()); + + const fixture = TestBed.createComponent(MetaCenterViewModeComponent); + fixture.detectChanges(); + const component = fixture.componentInstance; + + expect(component.viewMode).toBe('dialog'); + expect(component.seriesViewMode).toBe(true); + + component.onViewModeChange('route'); + component.onSeriesViewModeChange(false); + + expect(updateUserSetting).toHaveBeenNthCalledWith(1, 7, 'metadataCenterViewMode', 'route'); + expect(updateUserSetting).toHaveBeenNthCalledWith(2, 7, 'enableSeriesView', false); + expect(messageAdd).toHaveBeenNthCalledWith(1, { + severity: 'success', + summary: 'settingsView.metaCenter.prefsUpdated', + detail: 'settingsView.metaCenter.metaCenterSaved', + life: 1500, + }); + expect(messageAdd).toHaveBeenNthCalledWith(2, { + severity: 'success', + summary: 'settingsView.metaCenter.prefsUpdated', + detail: 'settingsView.metaCenter.seriesViewSaved', + life: 1500, + }); + }); + + it('ignores save attempts until a user is available', () => { + const currentUser = signal(null); + const updateUserSetting = vi.fn(); + + TestBed.configureTestingModule({ + imports: [MetaCenterViewModeComponent], + providers: [ + {provide: UserService, useValue: {currentUser, getCurrentUser: vi.fn(() => null), updateUserSetting}}, + {provide: MessageService, useValue: {add: vi.fn()}}, + {provide: TranslocoService, useValue: { + translate: vi.fn(), + config: {reRenderOnLangChange: false}, + langChanges$: of('en'), + _loadDependencies: vi.fn(() => of([])), + }}, + ] + }); + + const fixture = TestBed.createComponent(MetaCenterViewModeComponent); + const component = fixture.componentInstance; + + component.onViewModeChange('dialog'); + component.onSeriesViewModeChange(true); + + expect(updateUserSetting).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/app/features/settings/view-preferences-parent/sidebar-sorting-preferences/sidebar-sorting-preferences.component.spec.ts b/frontend/src/app/features/settings/view-preferences-parent/sidebar-sorting-preferences/sidebar-sorting-preferences.component.spec.ts new file mode 100644 index 000000000..ee2fb5d99 --- /dev/null +++ b/frontend/src/app/features/settings/view-preferences-parent/sidebar-sorting-preferences/sidebar-sorting-preferences.component.spec.ts @@ -0,0 +1,114 @@ +import {signal} from '@angular/core'; +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {MessageService} from 'primeng/api'; + +import {getTranslocoModule} from '../../../../core/testing/transloco-testing'; +import {User, UserService, UserSettings} from '../../user-management/user.service'; +import {SidebarSortingPreferencesComponent} from './sidebar-sorting-preferences.component'; + +function createUserSettings(): UserSettings { + return { + perBookSetting: {pdf: 'Global', epub: 'Individual', cbx: 'Global'}, + pdfReaderSetting: {pageSpread: 'off', pageZoom: '100%', showSidebar: true}, + epubReaderSetting: {theme: 'light', font: 'serif', fontSize: 16, flow: 'paginated', spread: 'auto', lineHeight: 1.5, margin: 1, letterSpacing: 0}, + ebookReaderSetting: {lineHeight: 1.5, justify: true, hyphenate: true, maxColumnCount: 1, gap: 1, fontSize: 16, theme: 'light', maxInlineSize: 100, maxBlockSize: 100, fontFamily: 'serif', isDark: false, flow: 'paginated'}, + cbxReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'}, + newPdfReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'}, + sidebarLibrarySorting: {field: 'name', order: 'asc'}, + sidebarShelfSorting: {field: 'id', order: 'desc'}, + sidebarMagicShelfSorting: {field: 'name', order: 'desc'}, + filterMode: 'and', + metadataCenterViewMode: 'route', + enableSeriesView: true, + entityViewPreferences: {global: {sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 100, seriesCollapsed: false, overlayBookType: false}, overrides: []}, + koReaderEnabled: false, + autoSaveMetadata: true, + } as UserSettings; +} + +function createUser(): User { + return { + id: 9, + username: 'tester', + name: 'Tester', + email: 'tester@example.com', + assignedLibraries: [], + permissions: { + admin: false, + canUpload: false, + canDownload: false, + canEmailBook: false, + canDeleteBook: false, + canEditMetadata: false, + canManageLibrary: false, + canManageMetadataConfig: false, + canSyncKoReader: false, + canSyncKobo: false, + canAccessOpds: false, + canAccessBookdrop: false, + canAccessLibraryStats: false, + canAccessUserStats: false, + canAccessTaskManager: false, + canManageEmailConfig: false, + canManageGlobalPreferences: false, + canManageIcons: false, + canManageFonts: false, + demoUser: false, + canBulkAutoFetchMetadata: false, + canBulkCustomFetchMetadata: false, + canBulkEditMetadata: false, + canBulkRegenerateCover: false, + canMoveOrganizeFiles: false, + canBulkLockUnlockMetadata: false, + }, + userSettings: createUserSettings(), + }; +} + +describe('SidebarSortingPreferencesComponent', () => { + let fixture: ComponentFixture; + let updateUserSetting: ReturnType; + let messageService: {add: ReturnType}; + + beforeEach(() => { + updateUserSetting = vi.fn(); + messageService = {add: vi.fn()}; + + TestBed.configureTestingModule({ + imports: [SidebarSortingPreferencesComponent, getTranslocoModule({translocoConfig: {reRenderOnLangChange: false}})], + providers: [ + {provide: UserService, useValue: {currentUser: signal(createUser()), updateUserSetting}}, + {provide: MessageService, useValue: messageService}, + ], + }); + + fixture = TestBed.createComponent(SidebarSortingPreferencesComponent); + TestBed.flushEffects(); + fixture.detectChanges(); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('hydrates sidebar sorting selections from the current user', () => { + const component = fixture.componentInstance; + + expect(component.selectedLibrarySorting).toEqual({field: 'name', order: 'asc'}); + expect(component.selectedShelfSorting).toEqual({field: 'id', order: 'desc'}); + expect(component.sortingOptions).not.toHaveLength(0); + }); + + it('persists library sorting changes and shows a success toast', () => { + const component = fixture.componentInstance; + component.selectedLibrarySorting = {field: 'id', order: 'asc'}; + + component.onLibrarySortingChange(); + + expect(updateUserSetting).toHaveBeenCalledWith(9, 'sidebarLibrarySorting', {field: 'id', order: 'asc'}); + expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'})); + }); +}); diff --git a/frontend/src/app/features/settings/view-preferences-parent/view-preferences-parent.component.spec.ts b/frontend/src/app/features/settings/view-preferences-parent/view-preferences-parent.component.spec.ts new file mode 100644 index 000000000..b93529d08 --- /dev/null +++ b/frontend/src/app/features/settings/view-preferences-parent/view-preferences-parent.component.spec.ts @@ -0,0 +1,79 @@ +import {TestBed} from '@angular/core/testing'; +import {describe, expect, it, vi} from 'vitest'; + +import {ViewPreferencesParentComponent} from './view-preferences-parent.component'; +import {LocalStorageService} from '../../../shared/service/local-storage.service'; +import {MessageService} from 'primeng/api'; +import {TranslocoService} from '@jsverse/transloco'; + +describe('ViewPreferencesParentComponent', () => { + it('loads and saves the sidebar width', () => { + const localStorageGet = vi.fn(() => 312); + const localStorageSet = vi.fn(); + const messageAdd = vi.fn(); + const translate = vi.fn(key => key); + + TestBed.configureTestingModule({ + imports: [ViewPreferencesParentComponent], + providers: [ + {provide: LocalStorageService, useValue: {get: localStorageGet, set: localStorageSet}}, + {provide: MessageService, useValue: {add: messageAdd}}, + {provide: TranslocoService, useValue: {translate}}, + ] + }); + + const fixture = TestBed.createComponent(ViewPreferencesParentComponent); + const component = fixture.componentInstance; + + component.ngOnInit(); + expect(component.sidebarWidth).toBe(312); + + component.saveSidebarWidth(); + + expect(localStorageSet).toHaveBeenCalledWith('sidebarWidth', 312); + expect(messageAdd).toHaveBeenCalledWith({ + severity: 'success', + summary: 'settingsView.layout.saved', + detail: 'settingsView.layout.savedDetail' + }); + }); + + it('updates the sidebar CSS variable when the width changes', () => { + const localStorageGet = vi.fn(() => 225); + + TestBed.configureTestingModule({ + imports: [ViewPreferencesParentComponent], + providers: [ + {provide: LocalStorageService, useValue: {get: localStorageGet, set: vi.fn()}}, + {provide: MessageService, useValue: {add: vi.fn()}}, + {provide: TranslocoService, useValue: {translate: vi.fn()}}, + ] + }); + + const fixture = TestBed.createComponent(ViewPreferencesParentComponent); + const component = fixture.componentInstance; + + component.sidebarWidth = 287; + component.onSidebarWidthChange(); + + expect(document.documentElement.style.getPropertyValue('--sidebar-width')).toBe('287px'); + }); + + it('falls back to the default width when no value is stored', () => { + TestBed.configureTestingModule({ + imports: [ViewPreferencesParentComponent], + providers: [ + {provide: LocalStorageService, useValue: {get: vi.fn(() => null), set: vi.fn()}}, + {provide: MessageService, useValue: {add: vi.fn()}}, + {provide: TranslocoService, useValue: {translate: vi.fn()}}, + ] + }); + + const fixture = TestBed.createComponent(ViewPreferencesParentComponent); + const component = fixture.componentInstance; + + component.ngOnInit(); + + expect(component.sidebarWidth).toBe(225); + }); +}); diff --git a/frontend/src/app/features/settings/view-preferences-parent/view-preferences/view-preferences.component.spec.ts b/frontend/src/app/features/settings/view-preferences-parent/view-preferences/view-preferences.component.spec.ts new file mode 100644 index 000000000..6694d68ef --- /dev/null +++ b/frontend/src/app/features/settings/view-preferences-parent/view-preferences/view-preferences.component.spec.ts @@ -0,0 +1,10 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around effect-driven user hydration, +// multiple live collection services, drag-drop ordering, and popover-driven multi-sort editing so +// preference persistence can be asserted without booting the full settings surface. +describe.skip('ViewPreferencesComponent', () => { + it('needs collection and drag-drop seams to verify global and override preference persistence deterministically', () => { + // TODO(seam): Cover visible-sort-field ordering, override creation, and auto-save interactions after the collection/popover flows are isolated. + }); +}); diff --git a/frontend/src/app/features/stats/component/library-stats/charts/author-universe-chart/author-universe-chart.component.spec.ts b/frontend/src/app/features/stats/component/library-stats/charts/author-universe-chart/author-universe-chart.component.spec.ts new file mode 100644 index 000000000..5cc07a4ef --- /dev/null +++ b/frontend/src/app/features/stats/component/library-stats/charts/author-universe-chart/author-universe-chart.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around effect-driven bubble-chart syncing, +// external tooltip DOM management, and author-stat aggregation so author-universe analysis can be +// asserted without a live Chart.js and document runtime. +describe.skip('AuthorUniverseChartComponent', () => { + it('needs aggregation seams to verify author-stat rollups, completion-rate buckets, and generated insights', () => { + // TODO(seam): Cover calculateAuthorStats and generateInsights once the computed chart output is isolated behind a deterministic adapter. + }); + + it('needs DOM seams to verify bubble dataset shaping and external tooltip lifecycle behavior', () => { + // TODO(seam): Cover updateChartData and handleExternalTooltip after extracting Chart.js and document interactions behind test seams. + }); +}); diff --git a/frontend/src/app/features/stats/component/library-stats/charts/book-formats-chart/book-formats-chart.component.spec.ts b/frontend/src/app/features/stats/component/library-stats/charts/book-formats-chart/book-formats-chart.component.spec.ts new file mode 100644 index 000000000..393f0061b --- /dev/null +++ b/frontend/src/app/features/stats/component/library-stats/charts/book-formats-chart/book-formats-chart.component.spec.ts @@ -0,0 +1,166 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {TranslocoService} from '@jsverse/transloco'; +import {Book, BookType} from '../../../../../book/model/book.model'; +import {BookService} from '../../../../../book/service/book.service'; +import {LibraryFilterService} from '../../service/library-filter.service'; +import {BookFormatsChartComponent} from './book-formats-chart.component'; + +const EXPECTED_FORMAT_COLORS = [ + '#0D9488', + '#E11D48', + '#6B7280', + '#6B7280', +]; + +interface BookFormatsTooltipContext { + parsed: number; + dataset: { + data: number[]; + }; + label: string; +} + +describe('BookFormatsChartComponent', () => { + const books = signal([]); + const isBooksLoading = signal(false); + const selectedLibrary = signal(null); + const translate = vi.fn((key: string, params?: Record) => { + if (!params) { + return key; + } + + return `${key}|${Object.entries(params).map(([name, value]) => `${name}=${value}`).join('|')}`; + }); + + beforeEach(() => { + books.set([]); + isBooksLoading.set(false); + selectedLibrary.set(null); + translate.mockClear(); + + TestBed.configureTestingModule({ + providers: [ + {provide: BookService, useValue: {books, isBooksLoading}}, + {provide: LibraryFilterService, useValue: {selectedLibrary}}, + {provide: TranslocoService, useValue: {translate}}, + ], + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + function createBook(id: number, libraryId: number, bookType?: BookType): Book { + return { + id, + title: `Book ${id}`, + libraryId, + libraryName: `Library ${libraryId}`, + primaryFile: bookType === undefined + ? undefined + : {id: id * 10, bookId: id, bookType}, + }; + } + + function createComponent(): BookFormatsChartComponent { + return TestBed.runInInjectionContext(() => new BookFormatsChartComponent()); + } + + function getTooltipLabelCallback(component: BookFormatsChartComponent): ((context: BookFormatsTooltipContext) => string) | undefined { + return component.chartOptions?.plugins?.tooltip?.callbacks?.label as + | ((context: BookFormatsTooltipContext) => string) + | undefined; + } + + it('filters books to the selected library and aggregates primary formats into descending stats', () => { + books.set([ + createBook(1, 1, 'EPUB'), + createBook(2, 1, 'EPUB'), + createBook(3, 1, 'EPUB'), + createBook(4, 1, 'EPUB'), + createBook(5, 1, 'PDF'), + createBook(6, 1, 'PDF'), + createBook(7, 1, 'PDF'), + createBook(8, 1, 'AUDIOBOOK'), + createBook(9, 1, 'AUDIOBOOK'), + createBook(10, 1), + createBook(11, 2, 'CBX'), + createBook(12, 2, 'CBX'), + ]); + selectedLibrary.set(1); + + const component = createComponent(); + + expect(component.totalBooks()).toBe(10); + expect(component.formatStats()).toEqual([ + {format: 'EPUB', count: 4, percentage: 40}, + {format: 'PDF', count: 3, percentage: 30}, + {format: 'AUDIOBOOK', count: 2, percentage: 20}, + {format: 'Unknown', count: 1, percentage: 10}, + ]); + }); + + it('builds deterministic pie chart labels, counts, and colors from computed format stats', () => { + books.set([ + createBook(1, 1, 'EPUB'), + createBook(2, 1, 'EPUB'), + createBook(3, 1, 'EPUB'), + createBook(4, 1, 'EPUB'), + createBook(5, 1, 'PDF'), + createBook(6, 1, 'PDF'), + createBook(7, 1, 'PDF'), + createBook(8, 1, 'AUDIOBOOK'), + createBook(9, 1, 'AUDIOBOOK'), + createBook(10, 1), + ]); + + const component = createComponent(); + const chartData = component.chartData(); + const dataset = chartData.datasets[0]; + + expect(chartData.labels).toEqual(['EPUB', 'PDF', 'AUDIOBOOK', 'Unknown']); + + expect(dataset).toBeDefined(); + if (!dataset) { + throw new Error('Expected a chart dataset'); + } + + expect(dataset.data).toEqual([4, 3, 2, 1]); + expect(dataset.backgroundColor).toEqual(EXPECTED_FORMAT_COLORS); + expect(dataset.borderColor).toEqual(EXPECTED_FORMAT_COLORS.map(() => 'rgba(255, 255, 255, 0.2)')); + expect(dataset.borderWidth).toBe(2); + expect(dataset.hoverBorderColor).toBe('#ffffff'); + expect(dataset.hoverBorderWidth).toBe(3); + }); + + it('formats the tooltip callback from computed chart data without a live Chart.js instance', () => { + books.set([ + createBook(1, 1, 'EPUB'), + createBook(2, 1, 'EPUB'), + createBook(3, 1, 'EPUB'), + createBook(4, 1, 'PDF'), + ]); + + const component = createComponent(); + const chartData = component.chartData(); + const dataset = chartData.datasets[0]; + const tooltipLabel = getTooltipLabelCallback(component); + + expect(dataset).toBeDefined(); + expect(tooltipLabel).toBeDefined(); + if (!dataset || !tooltipLabel) { + throw new Error('Expected tooltip callback and dataset'); + } + + expect(tooltipLabel({ + parsed: 3, + dataset: {data: dataset.data as number[]}, + label: 'EPUB', + })).toBe('statsLibrary.bookFormats.tooltipLabel|label=EPUB|value=3|percentage=75.0'); + }); +}); diff --git a/frontend/src/app/features/stats/component/library-stats/charts/language-chart/language-chart.component.spec.ts b/frontend/src/app/features/stats/component/library-stats/charts/language-chart/language-chart.component.spec.ts new file mode 100644 index 000000000..9f18fed70 --- /dev/null +++ b/frontend/src/app/features/stats/component/library-stats/charts/language-chart/language-chart.component.spec.ts @@ -0,0 +1,218 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {TranslocoService} from '@jsverse/transloco'; +import {Book} from '../../../../../book/model/book.model'; +import {BookService} from '../../../../../book/service/book.service'; +import {LanguageChartComponent} from './language-chart.component'; +import {LibraryFilterService} from '../../service/library-filter.service'; + +const EXPECTED_LANGUAGE_COLORS = [ + '#2563EB', + '#0D9488', + '#7C3AED', + '#DC2626', + '#F59E0B', + '#16A34A', + '#EC4899', + '#8B5CF6', + '#06B6D4', + '#EA580C', + '#6366F1', + '#14B8A6', + '#F43F5E', + '#84CC16', + '#A855F7', +]; + +interface LanguageTooltipContext { + parsed: number; + dataset: { + data: number[]; + }; + label: string; +} + +describe('LanguageChartComponent', () => { + const books = signal([]); + const isBooksLoading = signal(false); + const selectedLibrary = signal(null); + const translate = vi.fn((key: string, params?: Record) => { + if (!params) { + return key; + } + + return `${key}|${Object.entries(params).map(([name, value]) => `${name}=${value}`).join('|')}`; + }); + + beforeEach(() => { + books.set([]); + isBooksLoading.set(false); + selectedLibrary.set(null); + translate.mockClear(); + + TestBed.configureTestingModule({ + providers: [ + {provide: BookService, useValue: {books, isBooksLoading}}, + {provide: LibraryFilterService, useValue: {selectedLibrary}}, + {provide: TranslocoService, useValue: {translate}}, + ], + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + function createBook(id: number, libraryId: number, language?: string): Book { + return { + id, + title: `Book ${id}`, + libraryId, + libraryName: `Library ${libraryId}`, + metadata: language === undefined + ? {bookId: id} + : {bookId: id, language}, + }; + } + + function createComponent(): LanguageChartComponent { + return TestBed.runInInjectionContext(() => new LanguageChartComponent()); + } + + function getTooltipLabelCallback(component: LanguageChartComponent): ((context: LanguageTooltipContext) => string) | undefined { + return component.chartOptions?.plugins?.tooltip?.callbacks?.label as + | ((context: LanguageTooltipContext) => string) + | undefined; + } + + it('returns empty stats and chart data while books are still loading', () => { + books.set([ + createBook(1, 1, ' EN '), + createBook(2, 1, 'spa'), + ]); + isBooksLoading.set(true); + + const component = createComponent(); + + expect(component.totalBooks()).toBe(0); + expect(component.booksWithLanguage()).toBe(0); + expect(component.languageStats()).toEqual([]); + expect(component.chartData()).toEqual({labels: [], datasets: []}); + }); + + it('aggregates exact normalized keys, shapes mapped and fallback labels, and filters books to the selected library', () => { + books.set([ + createBook(1, 1, ' EN '), + createBook(2, 1, 'en'), + createBook(3, 1, 'eng'), + createBook(4, 1, ' English '), + createBook(5, 1, 'spa'), + createBook(6, 1, 'Spanish'), + createBook(7, 1, 'klingon'), + createBook(8, 1, ' '), + createBook(9, 1), + createBook(10, 2, 'en'), + ]); + selectedLibrary.set(1); + + const component = createComponent(); + + expect(component.totalBooks()).toBe(9); + expect(component.booksWithLanguage()).toBe(7); + expect(component.languageStats()).toEqual([ + {language: 'en', displayName: 'English', count: 2, percentage: (2 / 7) * 100}, + {language: 'eng', displayName: 'English', count: 1, percentage: (1 / 7) * 100}, + {language: 'english', displayName: 'English', count: 1, percentage: (1 / 7) * 100}, + {language: 'spa', displayName: 'Spanish', count: 1, percentage: (1 / 7) * 100}, + {language: 'spanish', displayName: 'Spanish', count: 1, percentage: (1 / 7) * 100}, + {language: 'klingon', displayName: 'Klingon', count: 1, percentage: (1 / 7) * 100}, + ]); + }); + + it('keeps only the top fifteen languages and exposes deterministic pie-chart labels, counts, and colors', () => { + const generatedBooks: Book[] = []; + let nextId = 1; + + Array.from({length: 17}, (_, index) => { + const language = `lang${String(index + 1).padStart(2, '0')}`; + const count = 17 - index; + + Array.from({length: count}, () => { + generatedBooks.push(createBook(nextId, 1, language)); + nextId += 1; + }); + }); + + books.set(generatedBooks); + + const component = createComponent(); + const chartData = component.chartData(); + const dataset = chartData.datasets[0]; + + expect(component.languageStats().length).toBe(15); + expect(chartData.labels).toEqual([ + 'Lang01', + 'Lang02', + 'Lang03', + 'Lang04', + 'Lang05', + 'Lang06', + 'Lang07', + 'Lang08', + 'Lang09', + 'Lang10', + 'Lang11', + 'Lang12', + 'Lang13', + 'Lang14', + 'Lang15', + ]); + + expect(dataset).toBeDefined(); + if (!dataset) { + throw new Error('Expected a chart dataset'); + } + + expect(dataset.data).toEqual([17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3]); + expect(dataset.backgroundColor).toEqual(EXPECTED_LANGUAGE_COLORS); + expect(dataset.borderColor).toEqual(EXPECTED_LANGUAGE_COLORS.map(() => 'rgba(255, 255, 255, 0.2)')); + expect(dataset.borderWidth).toBe(2); + expect(dataset.hoverBorderColor).toBe('#ffffff'); + expect(dataset.hoverBorderWidth).toBe(3); + }); + + it('formats the tooltip callback from computed chart data without a live Chart.js instance', () => { + books.set([ + createBook(1, 1, 'en'), + createBook(2, 1, ' EN '), + createBook(3, 1, 'en'), + createBook(4, 1, 'spa'), + createBook(5, 1, 'spanish'), + ]); + + const component = createComponent(); + const chartData = component.chartData(); + const dataset = chartData.datasets[0]; + const tooltipLabel = getTooltipLabelCallback(component); + + expect(dataset).toBeDefined(); + expect(tooltipLabel).toBeDefined(); + if (!dataset || !tooltipLabel) { + throw new Error('Expected tooltip callback and dataset'); + } + + expect(tooltipLabel({ + parsed: 3, + dataset: {data: dataset.data as number[]}, + label: 'English', + })).toBe('statsLibrary.language.tooltipLabel|label=English|value=3|percentage=60.0'); + expect(translate).toHaveBeenCalledWith('statsLibrary.language.tooltipLabel', { + label: 'English', + value: 3, + percentage: '60.0', + }); + }); +}); diff --git a/frontend/src/app/features/stats/component/library-stats/charts/metadata-score-chart/metadata-score-chart.component.spec.ts b/frontend/src/app/features/stats/component/library-stats/charts/metadata-score-chart/metadata-score-chart.component.spec.ts new file mode 100644 index 000000000..cd1233cdd --- /dev/null +++ b/frontend/src/app/features/stats/component/library-stats/charts/metadata-score-chart/metadata-score-chart.component.spec.ts @@ -0,0 +1,193 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {TranslocoService} from '@jsverse/transloco'; +import {Book} from '../../../../../book/model/book.model'; +import {BookService} from '../../../../../book/service/book.service'; +import {MetadataScoreChartComponent} from './metadata-score-chart.component'; +import {LibraryFilterService} from '../../service/library-filter.service'; + +const EXPECTED_SCORE_COLORS = [ + '#16A34A', + '#22C55E', + '#F59E0B', + '#F97316', + '#DC2626', +]; + +interface MetadataScoreTooltipContext { + parsed: number; + dataset: { + data: number[]; + }; +} + +describe('MetadataScoreChartComponent', () => { + const books = signal([]); + const isBooksLoading = signal(false); + const selectedLibrary = signal(null); + const translate = vi.fn((key: string, params?: Record) => { + if (!params) { + return key; + } + + return `${key}|${Object.entries(params).map(([name, value]) => `${name}=${value}`).join('|')}`; + }); + + beforeEach(() => { + books.set([]); + isBooksLoading.set(false); + selectedLibrary.set(null); + translate.mockClear(); + + TestBed.configureTestingModule({ + providers: [ + {provide: BookService, useValue: {books, isBooksLoading}}, + {provide: LibraryFilterService, useValue: {selectedLibrary}}, + {provide: TranslocoService, useValue: {translate}}, + ], + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + function createBook(id: number, libraryId: number, metadataMatchScore: number | null): Book { + return { + id, + title: `Book ${id}`, + libraryId, + libraryName: `Library ${libraryId}`, + metadataMatchScore, + }; + } + + function createComponent(): MetadataScoreChartComponent { + return TestBed.runInInjectionContext(() => new MetadataScoreChartComponent()); + } + + function getTooltipLabelCallback(component: MetadataScoreChartComponent): ((context: MetadataScoreTooltipContext) => string) | undefined { + return component.chartOptions?.plugins?.tooltip?.callbacks?.label as + | ((context: MetadataScoreTooltipContext) => string) + | undefined; + } + + it('returns empty computed stats while loading and when the selected library has no valid scores', () => { + books.set([ + createBook(1, 1, 95), + createBook(2, 2, -1), + createBook(3, 2, null), + ]); + selectedLibrary.set(2); + isBooksLoading.set(true); + + const component = createComponent(); + + expect(component.totalBooks()).toBe(0); + expect(component.averageScore()).toBe(0); + expect(component.scoreStats()).toEqual([]); + expect(component.chartData()).toEqual({labels: [], datasets: []}); + + isBooksLoading.set(false); + + expect(component.totalBooks()).toBe(0); + expect(component.averageScore()).toBe(0); + expect(component.scoreStats()).toEqual([]); + expect(component.chartData()).toEqual({labels: [], datasets: []}); + }); + + it('buckets scores by translated range, filters to the selected library, and rounds the average score', () => { + books.set([ + createBook(1, 1, 95), + createBook(2, 1, 89), + createBook(3, 1, 70), + createBook(4, 1, 69), + createBook(5, 1, 50), + createBook(6, 1, 49), + createBook(7, 1, 25), + createBook(8, 1, 24), + createBook(9, 1, 0), + createBook(10, 1, -1), + createBook(11, 1, null), + createBook(12, 2, 100), + ]); + selectedLibrary.set(1); + + const component = createComponent(); + + expect(component.totalBooks()).toBe(9); + expect(component.averageScore()).toBe(52); + expect(component.scoreStats()).toEqual([ + {range: 'statsLibrary.metadataScore.excellent', count: 1, percentage: 100 / 9, color: '#16A34A'}, + {range: 'statsLibrary.metadataScore.good', count: 2, percentage: 200 / 9, color: '#22C55E'}, + {range: 'statsLibrary.metadataScore.fair', count: 2, percentage: 200 / 9, color: '#F59E0B'}, + {range: 'statsLibrary.metadataScore.poor', count: 2, percentage: 200 / 9, color: '#F97316'}, + {range: 'statsLibrary.metadataScore.veryPoor', count: 2, percentage: 200 / 9, color: '#DC2626'}, + ]); + }); + + it('builds deterministic doughnut chart labels, counts, and colors from computed score stats', () => { + books.set([ + createBook(1, 1, 95), + createBook(2, 1, 89), + createBook(3, 1, 70), + createBook(4, 1, 69), + createBook(5, 1, 50), + createBook(6, 1, 49), + createBook(7, 1, 25), + createBook(8, 1, 24), + createBook(9, 1, 0), + ]); + + const component = createComponent(); + const chartData = component.chartData(); + const dataset = chartData.datasets[0]; + + expect(chartData.labels).toEqual([ + 'statsLibrary.metadataScore.excellent', + 'statsLibrary.metadataScore.good', + 'statsLibrary.metadataScore.fair', + 'statsLibrary.metadataScore.poor', + 'statsLibrary.metadataScore.veryPoor', + ]); + + expect(dataset).toBeDefined(); + if (!dataset) { + throw new Error('Expected a chart dataset'); + } + + expect(dataset.data).toEqual([1, 2, 2, 2, 2]); + expect(dataset.backgroundColor).toEqual(EXPECTED_SCORE_COLORS); + expect(dataset.borderColor).toEqual(EXPECTED_SCORE_COLORS.map(() => 'rgba(255, 255, 255, 0.2)')); + expect(dataset.borderWidth).toBe(2); + expect(dataset.hoverBorderColor).toBe('#ffffff'); + expect(dataset.hoverBorderWidth).toBe(3); + }); + + it('formats the tooltip callback from computed chart data without a live Chart.js instance', () => { + books.set([ + createBook(1, 1, 96), + createBook(2, 1, 90), + createBook(3, 1, 12), + ]); + + const component = createComponent(); + const chartData = component.chartData(); + const dataset = chartData.datasets[0]; + const tooltipLabel = getTooltipLabelCallback(component); + + expect(dataset).toBeDefined(); + expect(tooltipLabel).toBeDefined(); + if (!dataset || !tooltipLabel) { + throw new Error('Expected tooltip callback and dataset'); + } + + expect(tooltipLabel({ + parsed: 2, + dataset: {data: dataset.data as number[]}, + })).toBe('statsLibrary.metadataScore.tooltipLabel|value=2|percentage=66.7'); + }); +}); diff --git a/frontend/src/app/features/stats/component/library-stats/charts/page-count-chart/page-count-chart.component.spec.ts b/frontend/src/app/features/stats/component/library-stats/charts/page-count-chart/page-count-chart.component.spec.ts new file mode 100644 index 000000000..99ca64d80 --- /dev/null +++ b/frontend/src/app/features/stats/component/library-stats/charts/page-count-chart/page-count-chart.component.spec.ts @@ -0,0 +1,177 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {TranslocoService} from '@jsverse/transloco'; +import {Book} from '../../../../../book/model/book.model'; +import {BookService} from '../../../../../book/service/book.service'; +import {PageCountChartComponent} from './page-count-chart.component'; +import {LibraryFilterService} from '../../service/library-filter.service'; + +const EXPECTED_PAGE_RANGE_LABELS = [ + '0-100', + '101-200', + '201-300', + '301-500', + '501-750', + '751-1000', + '1000+', +]; + +const EXPECTED_PAGE_RANGE_COLORS = [ + '#06B6D4', + '#0EA5E9', + '#3B82F6', + '#6366F1', + '#8B5CF6', + '#A855F7', + '#D946EF', +]; + +interface PageCountTooltipTitleContext { + label: string; +} + +interface PageCountTooltipLabelContext { + parsed: { + y: number; + }; +} + +describe('PageCountChartComponent', () => { + const books = signal([]); + const isBooksLoading = signal(false); + const selectedLibrary = signal(null); + const translate = vi.fn((key: string, params?: Record) => { + if (!params) { + return key; + } + + return `${key}|${Object.entries(params).map(([name, value]) => `${name}=${value}`).join('|')}`; + }); + + beforeEach(() => { + books.set([]); + isBooksLoading.set(false); + selectedLibrary.set(null); + translate.mockClear(); + + TestBed.configureTestingModule({ + providers: [ + {provide: BookService, useValue: {books, isBooksLoading}}, + {provide: LibraryFilterService, useValue: {selectedLibrary}}, + {provide: TranslocoService, useValue: {translate}}, + ], + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + function createBook(id: number, libraryId: number, pageCount?: number | null): Book { + return { + id, + title: `Book ${id}`, + libraryId, + libraryName: `Library ${libraryId}`, + metadata: pageCount === undefined + ? {bookId: id} + : {bookId: id, pageCount}, + }; + } + + function createComponent(): PageCountChartComponent { + return TestBed.runInInjectionContext(() => new PageCountChartComponent()); + } + + function getTooltipTitleCallback(component: PageCountChartComponent): ((context: PageCountTooltipTitleContext[]) => string) | undefined { + return component.chartOptions?.plugins?.tooltip?.callbacks?.title as + | ((context: PageCountTooltipTitleContext[]) => string) + | undefined; + } + + function getTooltipLabelCallback(component: PageCountChartComponent): ((context: PageCountTooltipLabelContext) => string) | undefined { + return component.chartOptions?.plugins?.tooltip?.callbacks?.label as + | ((context: PageCountTooltipLabelContext) => string) + | undefined; + } + + it('filters books to the selected library and counts only positive page totals into the fixed buckets', () => { + books.set([ + createBook(1, 1, 50), + createBook(2, 1, 1000), + createBook(3, 1, 0), + createBook(4, 1, null), + createBook(5, 1), + createBook(6, 2, 75), + createBook(7, 2, 1200), + ]); + selectedLibrary.set(1); + + const component = createComponent(); + const chartData = component.chartData(); + const dataset = chartData.datasets[0]; + + expect(component.totalBooks()).toBe(2); + expect(dataset).toBeDefined(); + if (!dataset) { + throw new Error('Expected a chart dataset'); + } + + expect(dataset.data).toEqual([1, 0, 0, 0, 0, 1, 0]); + }); + + it('builds deterministic bar chart labels, counts, and colors for every page-count range', () => { + books.set([ + createBook(1, 1, 25), + createBook(2, 1, 100), + createBook(3, 1, 101), + createBook(4, 1, 200), + createBook(5, 1, 201), + createBook(6, 1, 300), + createBook(7, 1, 301), + createBook(8, 1, 500), + createBook(9, 1, 501), + createBook(10, 1, 750), + createBook(11, 1, 751), + createBook(12, 1, 1000), + createBook(13, 1, 1001), + ]); + + const component = createComponent(); + const chartData = component.chartData(); + const dataset = chartData.datasets[0]; + + expect(chartData.labels).toEqual(EXPECTED_PAGE_RANGE_LABELS); + expect(dataset).toBeDefined(); + if (!dataset) { + throw new Error('Expected a chart dataset'); + } + + expect(dataset.data).toEqual([2, 2, 2, 2, 2, 2, 1]); + expect(dataset.backgroundColor).toEqual(EXPECTED_PAGE_RANGE_COLORS); + expect(dataset.borderColor).toEqual(EXPECTED_PAGE_RANGE_COLORS.map(() => 'rgba(255, 255, 255, 0.2)')); + expect(dataset.borderWidth).toBe(1); + expect(dataset.borderRadius).toBe(4); + expect(dataset.barPercentage).toBe(0.8); + expect(dataset.categoryPercentage).toBe(0.7); + }); + + it('formats the tooltip title and singular-versus-plural labels without a live Chart.js instance', () => { + const component = createComponent(); + const tooltipTitle = getTooltipTitleCallback(component); + const tooltipLabel = getTooltipLabelCallback(component); + + expect(tooltipTitle).toBeDefined(); + expect(tooltipLabel).toBeDefined(); + if (!tooltipTitle || !tooltipLabel) { + throw new Error('Expected tooltip callbacks'); + } + + expect(tooltipTitle([{label: '301-500'}])).toBe('statsLibrary.pageCount.tooltipTitle|label=301-500'); + expect(tooltipLabel({parsed: {y: 1}})).toBe('statsLibrary.pageCount.tooltipLabel|value=1'); + expect(tooltipLabel({parsed: {y: 3}})).toBe('statsLibrary.pageCount.tooltipLabelPlural|value=3'); + }); +}); diff --git a/frontend/src/app/features/stats/component/library-stats/charts/publication-timeline-chart/publication-timeline-chart.component.spec.ts b/frontend/src/app/features/stats/component/library-stats/charts/publication-timeline-chart/publication-timeline-chart.component.spec.ts new file mode 100644 index 000000000..3be9c9f50 --- /dev/null +++ b/frontend/src/app/features/stats/component/library-stats/charts/publication-timeline-chart/publication-timeline-chart.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around decade bucketing, timeline insight +// generation, and translated tooltip callbacks so publication-history analysis can be asserted +// without a live Chart.js runtime. +describe.skip('PublicationTimelineChartComponent', () => { + it('needs aggregation seams to verify year extraction, decade ordering, and timeline insight calculations', () => { + // TODO(seam): Cover calculateDecadeStats and calculateInsights once the computed chart output is isolated behind a deterministic adapter. + }); + + it('needs callback seams to verify translated tooltip output and horizontal bar-chart dataset shaping', () => { + // TODO(seam): Cover chartData and chartOptions after extracting Chart.js callback metadata from the component runtime. + }); +}); diff --git a/frontend/src/app/features/stats/component/library-stats/charts/publication-trend-chart/publication-trend-chart.component.spec.ts b/frontend/src/app/features/stats/component/library-stats/charts/publication-trend-chart/publication-trend-chart.component.spec.ts new file mode 100644 index 000000000..8b57123b8 --- /dev/null +++ b/frontend/src/app/features/stats/component/library-stats/charts/publication-trend-chart/publication-trend-chart.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around year-count aggregation, trend-line +// dataset generation, and translated tooltip callbacks so publication-trend analysis can be +// asserted without relying on Chart.js metadata internals. +describe.skip('PublicationTrendChartComponent', () => { + it('needs aggregation seams to verify year extraction, contiguous year-range filling, and trend insights', () => { + // TODO(seam): Cover calculateYearCounts and calculateInsights once the computed chart output is isolated behind a deterministic adapter. + }); + + it('needs callback seams to verify translated tooltip output and line-dataset shaping across sparse publication years', () => { + // TODO(seam): Cover chartData and chartOptions after extracting Chart.js callback metadata from the component runtime. + }); +}); diff --git a/frontend/src/app/features/stats/component/library-stats/charts/reading-journey-chart/reading-journey-chart.component.spec.ts b/frontend/src/app/features/stats/component/library-stats/charts/reading-journey-chart/reading-journey-chart.component.spec.ts new file mode 100644 index 000000000..42c508718 --- /dev/null +++ b/frontend/src/app/features/stats/component/library-stats/charts/reading-journey-chart/reading-journey-chart.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around monthly acquisition/completion +// aggregation, cumulative line-dataset generation, and translated tooltip callbacks so reading +// journey analysis can be asserted without depending on chart metadata internals. +describe.skip('ReadingJourneyChartComponent', () => { + it('needs aggregation seams to verify monthly added and finished counts, date ranges, and journey insights', () => { + // TODO(seam): Cover calculateMonthlyData and calculateInsights once the computed chart output is isolated behind a deterministic adapter. + }); + + it('needs callback seams to verify cumulative dataset shaping and backlog tooltip formatting', () => { + // TODO(seam): Cover chartData and chartOptions after extracting Chart.js callback metadata from the component runtime. + }); +}); diff --git a/frontend/src/app/features/stats/component/library-stats/charts/top-items-chart/top-items-chart.component.spec.ts b/frontend/src/app/features/stats/component/library-stats/charts/top-items-chart/top-items-chart.component.spec.ts new file mode 100644 index 000000000..e9b3d24a5 --- /dev/null +++ b/frontend/src/app/features/stats/component/library-stats/charts/top-items-chart/top-items-chart.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around effect-driven chart syncing, +// stacked dataset generation, translated tooltip callbacks, and dynamic data-type selection so +// top-item aggregation can be asserted without depending on Chart.js metadata internals. +describe.skip('TopItemsChartComponent', () => { + it('needs aggregation seams to verify author, category, publisher, tag, mood, and series bucketing by read status', () => { + // TODO(seam): Cover loadAndProcessData and the item-stat calculation helpers once the computed chart output is isolated behind a deterministic adapter. + }); + + it('needs selector seams to verify data-type switching, insight generation, and stacked tooltip formatting', () => { + // TODO(seam): Cover onDataTypeChange and chartOptions after extracting Chart.js callback metadata and select-widget runtime concerns. + }); +}); diff --git a/frontend/src/app/features/stats/component/library-stats/library-stats.component.spec.ts b/frontend/src/app/features/stats/component/library-stats/library-stats.component.spec.ts new file mode 100644 index 000000000..8b4ac64c8 --- /dev/null +++ b/frontend/src/app/features/stats/component/library-stats/library-stats.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around drag-drop reorder events, computed +// chart enablement state, and child chart composition so library-stats orchestration can be tested +// without mounting the full dashboard shell. +describe.skip('LibraryStatsComponent', () => { + it('needs state seams to verify selected-library syncing, chart enablement toggles, and category grouping', () => { + // TODO(seam): Cover selectedLibrary, toggleChart, and getChartsByCategory once the computed service graph is isolated behind test doubles. + }); + + it('needs dashboard seams to verify drag-drop reorder and config reset behavior across the child chart layout', () => { + // TODO(seam): Cover onChartReorder and resetChartOrder after extracting drag-drop and child component composition concerns. + }); +}); diff --git a/frontend/src/app/features/stats/component/library-stats/service/libraries-summary.service.spec.ts b/frontend/src/app/features/stats/component/library-stats/service/libraries-summary.service.spec.ts new file mode 100644 index 000000000..785393c16 --- /dev/null +++ b/frontend/src/app/features/stats/component/library-stats/service/libraries-summary.service.spec.ts @@ -0,0 +1,97 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {LibrariesSummaryService} from './libraries-summary.service'; +import {LibraryFilterService} from './library-filter.service'; +import {BookService} from '../../../../book/service/book.service'; +import {Book} from '../../../../book/model/book.model'; + +describe('LibrariesSummaryService', () => { + const books = signal([]); + const selectedLibrary = signal(null); + + beforeEach(() => { + books.set([]); + selectedLibrary.set(null); + + TestBed.configureTestingModule({ + providers: [ + LibrariesSummaryService, + {provide: BookService, useValue: {books}}, + {provide: LibraryFilterService, useValue: {selectedLibrary}}, + ] + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('returns zeroed totals and zero size for an empty library set', () => { + const service = TestBed.inject(LibrariesSummaryService); + + expect(service.booksSummary()).toEqual({ + totalBooks: 0, + totalSizeKb: 0, + totalAuthors: 0, + totalSeries: 0, + totalPublishers: 0, + }); + expect(service.formattedSize()).toBe('0 KB'); + }); + + it('aggregates totals for the selected library and formats megabytes', () => { + books.set([ + { + id: 1, + libraryId: 1, + libraryName: 'Alpha', + fileSizeKb: 1024, + metadata: { + bookId: 1, + authors: ['Alice', 'Alice ', 'Bob'], + seriesName: 'Series A', + publisher: 'Publisher A', + }, + } as Book, + { + id: 2, + libraryId: 2, + libraryName: 'Beta', + fileSizeKb: 4096, + metadata: { + bookId: 2, + authors: ['Zed'], + seriesName: 'Series B', + publisher: 'Publisher B', + }, + } as Book, + { + id: 3, + libraryId: 1, + libraryName: 'Alpha', + fileSizeKb: 1024 * 1024, + metadata: { + bookId: 3, + authors: ['Carol'], + seriesName: 'Series A', + publisher: 'Publisher A', + }, + } as Book, + ]); + selectedLibrary.set(1); + + const service = TestBed.inject(LibrariesSummaryService); + const summary = service.booksSummary(); + + expect(summary).toEqual({ + totalBooks: 2, + totalSizeKb: 1024 + 1024 * 1024, + totalAuthors: 3, + totalSeries: 1, + totalPublishers: 1, + }); + expect(service.formattedSize()).toBe('1.00 GB'); + }); +}); diff --git a/frontend/src/app/features/stats/component/library-stats/service/library-filter.service.spec.ts b/frontend/src/app/features/stats/component/library-stats/service/library-filter.service.spec.ts new file mode 100644 index 000000000..935cdff4a --- /dev/null +++ b/frontend/src/app/features/stats/component/library-stats/service/library-filter.service.spec.ts @@ -0,0 +1,71 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {LibraryFilterService} from './library-filter.service'; +import {BookService} from '../../../../book/service/book.service'; +import {LibraryService} from '../../../../book/service/library.service'; +import {Book} from '../../../../book/model/book.model'; +import {Library} from '../../../../book/model/library.model'; +import {TranslocoService} from '@jsverse/transloco'; + +describe('LibraryFilterService', () => { + const books = signal([]); + const libraries = signal([]); + const translate = vi.fn((key: string, params?: Record) => + params?.['id'] ? `${key}:${params['id']}` : key + ); + + beforeEach(() => { + books.set([]); + libraries.set([]); + translate.mockClear(); + + TestBed.configureTestingModule({ + providers: [ + LibraryFilterService, + {provide: BookService, useValue: {books}}, + {provide: LibraryService, useValue: {libraries}}, + {provide: TranslocoService, useValue: {translate}}, + ] + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('shows the all libraries option when there are no books', () => { + const service = TestBed.inject(LibraryFilterService); + + expect(service.libraryOptions()).toEqual([ + {id: null, name: 'statsLibrary.libraryFilter.allLibraries'} + ]); + expect(service.selectedLibrary()).toBeNull(); + }); + + it('sorts library options and falls back when the library lookup is missing', () => { + books.set([ + {id: 1, libraryId: 2, libraryName: 'Beta'} as Book, + {id: 2, libraryId: 1, libraryName: 'Alpha'} as Book, + {id: 3, libraryId: 2, libraryName: 'Beta duplicate'} as Book, + ]); + libraries.set([ + {id: 1, name: 'Alpha', watch: false, paths: []} as Library, + ]); + + const service = TestBed.inject(LibraryFilterService); + + expect(service.libraryOptions()).toEqual([ + {id: null, name: 'statsLibrary.libraryFilter.allLibraries'}, + {id: 1, name: 'Alpha'}, + {id: 2, name: 'statsLibrary.libraryFilter.libraryFallback:2'}, + ]); + + service.setSelectedLibrary(2); + expect(service.selectedLibrary()).toBe(2); + + service.setSelectedLibrary(99); + expect(service.selectedLibrary()).toBeNull(); + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/book-flow-chart/book-flow-chart.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/book-flow-chart/book-flow-chart.component.spec.ts new file mode 100644 index 000000000..ffd83aa48 --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/book-flow-chart/book-flow-chart.component.spec.ts @@ -0,0 +1,10 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around canvas drawing, requestAnimationFrame, +// computed book-service state, and Sankey layout math so flow processing can be asserted without +// snapshotting imperative canvas output. +describe.skip('BookFlowChartComponent', () => { + it('needs canvas and layout seams to verify status bucketing, quarter aggregation, and render scheduling deterministically', () => { + // TODO(seam): Cover Sankey node/link generation once draw operations and animation scheduling are injectable. + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/book-length-chart/book-length-chart.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/book-length-chart/book-length-chart.component.spec.ts new file mode 100644 index 000000000..e4c6df376 --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/book-length-chart/book-length-chart.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around computed scatter datasets, +// trend-line generation, and translated tooltip callbacks so page-count versus rating analysis can +// be asserted without depending on Chart.js scatter metadata. +describe.skip('BookLengthChartComponent', () => { + it('needs metrics seams to verify rated-book filtering, status grouping, and sweet-spot calculations', () => { + // TODO(seam): Cover calculateMetrics and computeStats once the scatter-chart output is isolated from the component runtime. + }); + + it('needs chart-data seams to verify trend-line generation and translated tooltip output deterministically', () => { + // TODO(seam): Cover computeTrendLine and chartOptions callbacks after extracting Chart.js point metadata behind a test seam. + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/completion-race-chart/completion-race-chart.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/completion-race-chart/completion-race-chart.component.spec.ts new file mode 100644 index 000000000..0544c92df --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/completion-race-chart/completion-race-chart.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around the UserStatsService stream, date +// normalization, and Chart.js line-series assembly so yearly race aggregation can be tested +// without leaning on a full chart runtime. +describe.skip('CompletionRaceChartComponent', () => { + it('needs service and transformation seams to verify year changes, session grouping, and fastest/slowest book summaries', () => { + // TODO(seam): Cover loadData and processData once the observable subscription flow is isolated behind a test seam. + }); + + it('needs chart-adapter seams to verify line dataset generation and translated tooltip callbacks', () => { + // TODO(seam): Cover the chart dataset mapping after extracting Chart.js point metadata and callback wiring from the component. + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/completion-timeline-chart/completion-timeline-chart.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/completion-timeline-chart/completion-timeline-chart.component.spec.ts new file mode 100644 index 000000000..747d7eadc --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/completion-timeline-chart/completion-timeline-chart.component.spec.ts @@ -0,0 +1,10 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around Chart.js bar datasets, translated +// tooltip/axis callbacks, and year-based stats loading so completion timeline aggregation can be +// validated without depending on chart directive rendering internals. +describe.skip('CompletionTimelineChartComponent', () => { + it('needs chart-data seams to verify monthly completion aggregation and year navigation deterministically', () => { + // TODO(seam): Cover status-bucket folding and dataset updates once chart callbacks are decoupled from the rendering layer. + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/favorite-days-chart/favorite-days-chart.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/favorite-days-chart/favorite-days-chart.component.spec.ts new file mode 100644 index 000000000..66a0d413e --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/favorite-days-chart/favorite-days-chart.component.spec.ts @@ -0,0 +1,10 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around Chart.js bar datasets, translated +// axis/tooltip labels, and year/month filter state so favorite-day aggregation can be validated +// without coupling tests to the chart directive runtime. +describe.skip('FavoriteDaysChartComponent', () => { + it('needs chart and filter seams to verify favorite-day aggregation and dual-axis dataset construction', () => { + // TODO(seam): Cover filtered stats loading and chart dataset shaping once chart callbacks are wrapped behind a lightweight adapter. + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/genre-stats-chart/genre-stats-chart.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/genre-stats-chart/genre-stats-chart.component.spec.ts new file mode 100644 index 000000000..5451d857a --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/genre-stats-chart/genre-stats-chart.component.spec.ts @@ -0,0 +1,102 @@ +import {TestBed} from '@angular/core/testing'; +import type {Scale} from 'chart.js'; +import {of, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {TranslocoService} from '@jsverse/transloco'; +import {fakeChartTooltipContext, nextChartEmission} from '../../../../../../core/testing/chart-testing'; +import {UserStatsService, type GenreStatsResponse} from '../../../../../settings/user-management/user-stats.service'; +import {GenreStatsChartComponent} from './genre-stats-chart.component'; + +describe('GenreStatsChartComponent', () => { + let getGenreStats: ReturnType; + + beforeEach(() => { + getGenreStats = vi.fn(() => of([])); + + TestBed.configureTestingModule({ + providers: [ + {provide: UserStatsService, useValue: {getGenreStats}}, + {provide: TranslocoService, useValue: {translate: (key: string) => key}}, + ], + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + function getTooltipLabelCallback(component: GenreStatsChartComponent): ((context: ReturnType) => string) | undefined { + return component.chartOptions?.plugins?.tooltip?.callbacks?.label as + | ((context: ReturnType) => string) + | undefined; + } + + function getScaleTickCallback( + component: GenreStatsChartComponent, + axis: 'x' | 'y', + ): ((this: Scale, value: string | number, index: number, ticks: {value: number}[]) => string | string[] | number | null | undefined) | undefined { + const scale = component.chartOptions?.scales?.[axis] as { + ticks?: { + callback?: (this: Scale, value: string | number, index: number, ticks: {value: number}[]) => string | string[] | number | null | undefined; + }; + } | undefined; + + return scale?.ticks?.callback; + } + + it('sorts genres by duration, limits the list, and formats tooltip output without rendering a live chart', async () => { + const stats: GenreStatsResponse[] = [ + {genre: 'Very Long Genre Label', bookCount: 2, totalSessions: 5, totalDurationSeconds: 3600, averageSessionsPerBook: 2.5}, + {genre: 'Sci-Fi', bookCount: 4, totalSessions: 8, totalDurationSeconds: 5400, averageSessionsPerBook: 2}, + {genre: 'Fantasy', bookCount: 3, totalSessions: 7, totalDurationSeconds: 1800, averageSessionsPerBook: 2.3}, + ]; + getGenreStats.mockReturnValue(of(stats)); + + const component = TestBed.runInInjectionContext(() => new GenreStatsChartComponent()); + component.maxGenres = 2; + + const nextEmission = nextChartEmission(component.chartData$); + component.ngOnInit(); + const chartData = await nextEmission; + + expect(chartData.labels).toEqual(['Sci-Fi', 'Very Long Genre Label']); + expect(chartData.datasets[0]?.data).toEqual([5400, 3600]); + + const tooltipLabel = getTooltipLabelCallback(component)?.( + fakeChartTooltipContext({ + data: [5400, 3600], + labels: ['Sci-Fi', 'Very Long Genre Label'], + dataIndex: 1, + }) + ); + expect(tooltipLabel).toBe('Very Long Genre Label: 1h 0m'); + + const tickCallback = getScaleTickCallback(component, 'x'); + expect(tickCallback?.call({} as Scale, 0, 1, [])).toBe('Very Long Ge...'); + }); + + it('translates y-axis durations across seconds, minutes, hours, and days', () => { + const component = TestBed.runInInjectionContext(() => new GenreStatsChartComponent()); + const tickCallback = getScaleTickCallback(component, 'y'); + + expect(tickCallback?.call({} as Scale, 45, 0, [])).toBe('45 statsUser.genreStats.sec'); + expect(tickCallback?.call({} as Scale, 600, 0, [])).toBe('10 statsUser.genreStats.min'); + expect(tickCallback?.call({} as Scale, 7200, 0, [])).toBe('2 statsUser.genreStats.hrs'); + expect(tickCallback?.call({} as Scale, 90000, 0, [])).toBe('1 statsUser.genreStats.day 1 statsUser.genreStats.hr'); + }); + + it('logs and preserves the empty chart state when the stats request fails', () => { + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined); + getGenreStats.mockReturnValue(throwError(() => new Error('boom'))); + + const component = TestBed.runInInjectionContext(() => new GenreStatsChartComponent()); + + component.ngOnInit(); + + expect(errorSpy).toHaveBeenCalled(); + expect(component.chartOptions?.plugins?.legend?.display).toBe(false); + expect(component.chartOptions?.plugins?.tooltip?.enabled).toBe(true); + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/page-turner-chart/page-turner-chart.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/page-turner-chart/page-turner-chart.component.spec.ts new file mode 100644 index 000000000..0565e990e --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/page-turner-chart/page-turner-chart.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around the UserStatsService subscription +// flow, Chart.js tooltip callback mutation, and transloco-backed label generation so grip-score +// aggregation can be verified without relying on a live chart canvas. +describe.skip('PageTurnerChartComponent', () => { + it('needs chart-data seams to verify stat summaries, guilty-pleasure selection, and top-book slicing', () => { + // TODO(seam): Cover updateStats once the chart runtime and service subscription path are isolated for deterministic assertions. + }); + + it('needs tooltip seams to verify translated label callbacks and color generation for the top fifteen books', () => { + // TODO(seam): Cover updateChartData after extracting the Chart.js callback mutation behind a testable adapter. + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/peak-hours-chart/peak-hours-chart.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/peak-hours-chart/peak-hours-chart.component.spec.ts new file mode 100644 index 000000000..20b77e75c --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/peak-hours-chart/peak-hours-chart.component.spec.ts @@ -0,0 +1,10 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around Chart.js line datasets, translated +// tooltip/axis callbacks, and month/year filter state so peak-hour aggregation can be checked +// without entangling the spec with chart rendering details. +describe.skip('PeakHoursChartComponent', () => { + it('needs chart and filter seams to verify hourly session aggregation and dual-axis dataset shaping', () => { + // TODO(seam): Cover filtered stats loading and dataset production once the chart runtime is wrapped behind an adapter. + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/personal-rating-chart/personal-rating-chart.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/personal-rating-chart/personal-rating-chart.component.spec.ts new file mode 100644 index 000000000..008be389f --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/personal-rating-chart/personal-rating-chart.component.spec.ts @@ -0,0 +1,132 @@ +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {TranslocoService} from '@jsverse/transloco'; +import {BookService} from '../../../../../book/service/book.service'; +import type {Book} from '../../../../../book/model/book.model'; +import {PersonalRatingChartComponent} from './personal-rating-chart.component'; + +describe('PersonalRatingChartComponent', () => { + const allRatingLabels = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']; + + const translate = vi.fn((key: string, params?: Record) => + params ? `${key}:${JSON.stringify(params)}` : key + ); + const books = vi.fn(() => [] as Book[]); + const isBooksLoading = vi.fn(() => false); + + beforeEach(() => { + books.mockReset(); + books.mockReturnValue([]); + isBooksLoading.mockReset(); + isBooksLoading.mockReturnValue(false); + translate.mockClear(); + + TestBed.configureTestingModule({ + providers: [ + { + provide: BookService, + useValue: {books, isBooksLoading}, + }, + { + provide: TranslocoService, + useValue: {translate}, + }, + ], + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + function createComponent() { + return TestBed.runInInjectionContext(() => new PersonalRatingChartComponent()); + } + + function ratedBook(personalRating: number | null | undefined): Book { + return {personalRating} as Book; + } + + it('counts personal ratings across the 1-10 range and ignores invalid values', () => { + books.mockReturnValue([ + ratedBook(1), + ratedBook(2), + ratedBook(2), + ratedBook(10), + ratedBook(10), + ratedBook(10), + ratedBook(0), + ratedBook(11), + ratedBook(null), + ratedBook(undefined), + ]); + + const component = createComponent(); + const chartData = component.chartData(); + + expect(chartData.labels).toEqual(allRatingLabels); + expect(chartData.datasets[0]?.data).toEqual([1, 2, 0, 0, 0, 0, 0, 0, 0, 3]); + }); + + it('retains zero-count buckets in chartData for missing rating ranges', () => { + books.mockReturnValue([ratedBook(7)]); + + const component = createComponent(); + const chartData = component.chartData(); + + expect(chartData.labels).toEqual(allRatingLabels); + expect(chartData.datasets[0]?.data).toEqual([0, 0, 0, 0, 0, 0, 1, 0, 0, 0]); + }); + + it('builds tooltip title and singular/plural labels via translation callbacks', () => { + const component = createComponent(); + const callbacks = component.chartOptions?.plugins?.tooltip?.callbacks as + | { + title?: (context: {label?: string}[]) => string; + label?: (context: {parsed: {y: number}}) => string; + } + | undefined; + + translate.mockClear(); + + const title = callbacks?.title?.([{label: '8'}]); + const singularLabel = callbacks?.label?.({parsed: {y: 1}}); + const pluralLabel = callbacks?.label?.({parsed: {y: 4}}); + + expect(title).toBe('statsUser.personalRating.tooltipTitle:{"label":"8"}'); + expect(singularLabel).toBe('statsUser.personalRating.tooltipBook:{"value":1}'); + expect(pluralLabel).toBe('statsUser.personalRating.tooltipBooks:{"value":4}'); + expect(translate).toHaveBeenCalledWith('statsUser.personalRating.tooltipTitle', {label: '8'}); + expect(translate).toHaveBeenCalledWith('statsUser.personalRating.tooltipBook', {value: 1}); + expect(translate).toHaveBeenCalledWith('statsUser.personalRating.tooltipBooks', {value: 4}); + }); + + it('returns empty fallback chart data when chartData computation throws', () => { + const chartError = new Error('chart data failure'); + books.mockImplementation(() => { + throw chartError; + }); + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined); + + const component = createComponent(); + const chartData = component.chartData(); + + expect(errorSpy).toHaveBeenCalledWith('Error updating personal rating chart data:', chartError); + expect(chartData.labels).toEqual([]); + expect(chartData.datasets[0]?.data).toEqual([]); + expect(chartData.datasets[0]?.label).toBe('statsUser.personalRating.booksByPersonalRating'); + expect(chartData.datasets[0]?.backgroundColor).toEqual([ + '#DC2626', + '#EA580C', + '#F59E0B', + '#EAB308', + '#FACC15', + '#BEF264', + '#65A30D', + '#16A34A', + '#059669', + '#2563EB', + ]); + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/publication-era-chart/publication-era-chart.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/publication-era-chart/publication-era-chart.component.spec.ts new file mode 100644 index 000000000..e45ab7b15 --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/publication-era-chart/publication-era-chart.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around signal-driven chart syncing, +// decade bucketing, and Chart.js line-series output so publication-era analysis can be asserted +// without depending on a live chart runtime. +describe.skip('PublicationEraChartComponent', () => { + it('needs aggregation seams to verify rated-book filtering, decade bucketing, and best-decade selection', () => { + // TODO(seam): Cover processData once the signal effect and chart mutation are isolated for deterministic assertions. + }); + + it('needs chart seams to verify decade dataset generation and tooltip formatting', () => { + // TODO(seam): Cover chartData and chartOptions after extracting Chart.js callback metadata behind an adapter. + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/rating-taste-chart/rating-taste-chart.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/rating-taste-chart/rating-taste-chart.component.spec.ts new file mode 100644 index 000000000..3307d88cb --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/rating-taste-chart/rating-taste-chart.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around computed scatter-chart datasets, +// quadrant labeling, and tooltip formatting so rating deviation analysis can be asserted without +// coupling the spec to Chart.js scatter metadata. +describe.skip('RatingTasteChartComponent', () => { + it('needs metrics seams to verify library filtering, external-rating normalization, and quadrant classification', () => { + // TODO(seam): Cover calculateMetrics and categorizeBooks once the scatter-chart output is extracted behind a testable adapter. + }); + + it('needs callback seams to verify translated tooltip output and quadrant insight summaries deterministically', () => { + // TODO(seam): Cover chartOptions tooltip behavior after separating raw Chart.js point metadata from component logic. + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/read-status-chart/read-status-chart.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/read-status-chart/read-status-chart.component.spec.ts new file mode 100644 index 000000000..fd0cdad06 --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/read-status-chart/read-status-chart.component.spec.ts @@ -0,0 +1,10 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around computed Chart.js doughnut data, +// legend-generation callbacks, and tooltip formatting so read-status aggregation can be asserted +// without depending on chart metadata internals. +describe.skip('ReadStatusChartComponent', () => { + it('needs chart-data seams to verify status bucketing, legend generation, and tooltip formatting deterministically', () => { + // TODO(seam): Cover read-status aggregation once the Chart.js legend and tooltip callbacks are extracted behind a testable adapter. + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/reading-clock-chart/reading-clock-chart.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/reading-clock-chart/reading-clock-chart.component.spec.ts new file mode 100644 index 000000000..57a67190a --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/reading-clock-chart/reading-clock-chart.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around the UserStatsService observable, +// 24-hour polar-area dataset shaping, and translated tooltip callbacks so hourly reading patterns +// can be verified without binding the spec to chart rendering internals. +describe.skip('ReadingClockChartComponent', () => { + it('needs service and aggregation seams to verify peak hour selection, total hours, and reader-type classification', () => { + // TODO(seam): Cover processData once the service subscription flow and hour-bucket aggregation are isolated for direct assertions. + }); + + it('needs chart-output seams to verify color ramp generation and tooltip time formatting', () => { + // TODO(seam): Cover the polar-area dataset mapping after extracting Chart.js callback behavior behind an adapter. + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/reading-debt-chart/reading-debt-chart.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/reading-debt-chart/reading-debt-chart.component.spec.ts new file mode 100644 index 000000000..771b9f85f --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/reading-debt-chart/reading-debt-chart.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around signal-driven monthly aggregation, +// dual-axis Chart.js dataset generation, and translated trend labeling so backlog analysis can be +// tested without coupling the spec to chart rendering internals. +describe.skip('ReadingDebtChartComponent', () => { + it('needs aggregation seams to verify monthly added and finished counts, running backlog, and trend selection', () => { + // TODO(seam): Cover processData once the effect-driven chart update path is isolated behind a test seam. + }); + + it('needs chart seams to verify the combined bar-plus-line dataset output and translated labels', () => { + // TODO(seam): Cover chartData and chartOptions after extracting Chart.js dataset typing and callback behavior from the component runtime. + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/reading-dna-chart/reading-dna-chart.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/reading-dna-chart/reading-dna-chart.component.spec.ts new file mode 100644 index 000000000..fd5965fb7 --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/reading-dna-chart/reading-dna-chart.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around chart dataset derivation, +// translated radar-axis labels, and Chart.js option callbacks so the reading-profile output can +// be asserted without depending on Chart.js metadata internals. +describe.skip('ReadingDnaChartComponent', () => { + it('needs aggregation seams to verify mood, pace, genre, and completion-profile data mapping', () => { + // TODO(seam): Cover chartData construction once the radar dataset adapter is extracted from the live chart wrapper. + }); + + it('needs chart-option seams to verify tooltip and legend behavior for translated profile output', () => { + // TODO(seam): Cover chartOptions after the translated callback surface is isolated behind deterministic test seams. + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/reading-habits-chart/reading-habits-chart.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/reading-habits-chart/reading-habits-chart.component.spec.ts new file mode 100644 index 000000000..610fd2585 --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/reading-habits-chart/reading-habits-chart.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around the radar-chart label callbacks, +// emoji-decorated point labels, and the multi-score reading profile calculations so habit +// analysis can be asserted without depending on Chart.js label metadata. +describe.skip('ReadingHabitsChartComponent', () => { + it('needs profile seams to verify consistency, multitasking, completionism, and the other habit score calculations', () => { + // TODO(seam): Cover analyzeReadingHabits and the individual score helpers once the chart-facing computed state is decoupled from the component runtime. + }); + + it('needs callback seams to verify translated habit labels, insight descriptions, and radar tooltip output', () => { + // TODO(seam): Cover chartOptions point-label and tooltip behavior after extracting Chart.js callback metadata behind a test seam. + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/reading-heatmap-chart/reading-heatmap-chart.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/reading-heatmap-chart/reading-heatmap-chart.component.spec.ts new file mode 100644 index 000000000..591b90305 --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/reading-heatmap-chart/reading-heatmap-chart.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around signal-driven effect execution, +// matrix-chart cell sizing, and translated tooltip formatting so completion heatmap aggregation +// can be asserted without a live chart layout engine. +describe.skip('ReadingHeatmapChartComponent', () => { + it('needs effect and transformation seams to verify year-month counting across the rolling ten-year window', () => { + // TODO(seam): Cover calculateHeatmapData and processHeatmapData once the effect-driven chart sync is isolated from Angular and Chart.js runtime state. + }); + + it('needs chart-layout seams to verify year labels, alpha scaling, and matrix cell sizing callbacks deterministically', () => { + // TODO(seam): Cover updateChartData after extracting Chart.js matrix sizing and tooltip metadata behind an adapter. + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/reading-progress-chart/reading-progress-chart.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/reading-progress-chart/reading-progress-chart.component.spec.ts new file mode 100644 index 000000000..3be982269 --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/reading-progress-chart/reading-progress-chart.component.spec.ts @@ -0,0 +1,207 @@ +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {TranslocoService} from '@jsverse/transloco'; +import type {Book} from '../../../../../book/model/book.model'; +import {BookService} from '../../../../../book/service/book.service'; +import {ReadingProgressChartComponent} from './reading-progress-chart.component'; + +describe('ReadingProgressChartComponent', () => { + const chartColors = ['#6c757d', '#ffc107', '#fd7e14', '#17a2b8', '#6f42c1', '#28a745']; + + const translate = vi.fn((key: string, params?: Record) => + params ? `${key}:${JSON.stringify(params)}` : key + ); + const books = vi.fn(() => [] as Book[]); + const isBooksLoading = vi.fn(() => false); + + beforeEach(() => { + translate.mockClear(); + books.mockReset(); + books.mockReturnValue([]); + isBooksLoading.mockReset(); + isBooksLoading.mockReturnValue(false); + + TestBed.configureTestingModule({ + providers: [ + { + provide: BookService, + useValue: {books, isBooksLoading}, + }, + { + provide: TranslocoService, + useValue: {translate}, + }, + ], + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + function createComponent() { + return TestBed.runInInjectionContext(() => new ReadingProgressChartComponent()); + } + + function bookWithProgress(progress: Partial): Book { + return progress as Book; + } + + function getLegendGenerator(component: ReadingProgressChartComponent) { + return component.chartOptions?.plugins?.legend?.labels?.generateLabels as + | ((chart: { + data: {labels?: string[]; datasets?: {data: number[]; backgroundColor: string[]}[]}; + getDataVisibility?: (index: number) => boolean; + }) => { + text: string; + fillStyle: string; + strokeStyle: string; + lineWidth: number; + hidden: boolean; + index: number; + fontColor: string; + }[]) + | undefined; + } + + function getTooltipCallbacks(component: ReadingProgressChartComponent) { + return component.chartOptions?.plugins?.tooltip?.callbacks as + | { + title?: (context: {label?: string}[]) => string; + label?: (context: {parsed: number; dataset: {data: number[]}; label: string}) => string; + } + | undefined; + } + + it('buckets progress boundaries using reader-source precedence and deterministic chart colors', () => { + books.mockReturnValue([ + bookWithProgress({}), + bookWithProgress({pdfProgress: {page: 1, percentage: 0.1}, epubProgress: {cfi: 'epub-fallback', percentage: 100}}), + bookWithProgress({pdfProgress: {page: 25, percentage: 25}}), + bookWithProgress({pdfProgress: {page: 0, percentage: 0}, epubProgress: {cfi: 'epub-26', percentage: 26}}), + bookWithProgress({cbxProgress: {page: 50, percentage: 50}}), + bookWithProgress({epubProgress: {cfi: 'epub-51', percentage: 51}}), + bookWithProgress({pdfProgress: {page: 0, percentage: 0}, cbxProgress: {page: 75, percentage: 75}}), + bookWithProgress({koreaderProgress: {percentage: 76}}), + bookWithProgress({pdfProgress: {page: 0, percentage: 0}, koreaderProgress: {percentage: 99}, koboProgress: {percentage: 100}}), + bookWithProgress({koboProgress: {percentage: 100}}), + ]); + + const component = createComponent(); + const chartData = component.chartData(); + + expect(chartData.labels).toEqual(['0%', '1-25%', '26-50%', '51-75%', '76-99%', '100%']); + expect(chartData.datasets[0]?.data).toEqual([1, 2, 2, 2, 2, 1]); + expect(chartData.datasets[0]?.label).toBe('statsUser.readingProgress.booksByProgress'); + expect(chartData.datasets[0]?.backgroundColor).toEqual(chartColors); + expect(chartData.datasets[0]?.borderColor).toBe('#ffffff'); + expect(chartData.datasets[0]?.hoverBorderWidth).toBe(3); + }); + + it('retains zero-count buckets in a fixed order when only one progress range has books', () => { + books.mockReturnValue([ + bookWithProgress({koboProgress: {percentage: 100}}), + ]); + + const component = createComponent(); + const chartData = component.chartData(); + + expect(chartData.labels).toEqual(['0%', '1-25%', '26-50%', '51-75%', '76-99%', '100%']); + expect(chartData.datasets[0]?.data).toEqual([0, 0, 0, 0, 0, 1]); + expect(chartData.datasets[0]?.backgroundColor).toEqual(chartColors); + }); + + it('returns fallback empty chart data when chartData computation throws', () => { + const chartError = new Error('reading progress failure'); + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined); + books.mockImplementation(() => { + throw chartError; + }); + + const component = createComponent(); + const chartData = component.chartData(); + + expect(errorSpy).toHaveBeenCalledWith('Error updating reading progress chart data:', chartError); + expect(chartData.labels).toEqual([]); + expect(chartData.datasets[0]?.data).toEqual([]); + expect(chartData.datasets[0]?.label).toBe('statsUser.readingProgress.booksByProgress'); + expect(chartData.datasets[0]?.backgroundColor).toEqual(chartColors); + expect(chartData.datasets[0]?.borderWidth).toBe(1); + expect(chartData.datasets[0]?.hoverBorderWidth).toBe(2); + }); + + it('builds deterministic legend labels from the current doughnut dataset without rendering a chart', () => { + books.mockReturnValue([ + bookWithProgress({}), + bookWithProgress({epubProgress: {cfi: 'epub-20', percentage: 20}}), + bookWithProgress({cbxProgress: {page: 50, percentage: 50}}), + bookWithProgress({koreaderProgress: {percentage: 80}}), + bookWithProgress({koboProgress: {percentage: 100}}), + ]); + + const component = createComponent(); + const chartData = component.chartData(); + const legendItems = getLegendGenerator(component)?.({ + data: { + labels: chartData.labels as string[], + datasets: [{ + data: chartData.datasets[0]?.data as number[], + backgroundColor: chartData.datasets[0]?.backgroundColor as string[], + }], + }, + getDataVisibility: (index) => index !== 1, + }); + + expect(legendItems).toEqual([ + {text: '0%: 1', fillStyle: '#6c757d', strokeStyle: '#ffffff', lineWidth: 1, hidden: false, index: 0, fontColor: '#ffffff'}, + {text: '1-25%: 1', fillStyle: '#ffc107', strokeStyle: '#ffffff', lineWidth: 1, hidden: true, index: 1, fontColor: '#ffffff'}, + {text: '26-50%: 1', fillStyle: '#fd7e14', strokeStyle: '#ffffff', lineWidth: 1, hidden: false, index: 2, fontColor: '#ffffff'}, + {text: '51-75%: 0', fillStyle: '#17a2b8', strokeStyle: '#ffffff', lineWidth: 1, hidden: false, index: 3, fontColor: '#ffffff'}, + {text: '76-99%: 1', fillStyle: '#6f42c1', strokeStyle: '#ffffff', lineWidth: 1, hidden: false, index: 4, fontColor: '#ffffff'}, + {text: '100%: 1', fillStyle: '#28a745', strokeStyle: '#ffffff', lineWidth: 1, hidden: false, index: 5, fontColor: '#ffffff'}, + ]); + }); + + it('builds translated tooltip titles and labels with mapped descriptions and singular-plural output', () => { + const component = createComponent(); + const callbacks = getTooltipCallbacks(component); + + translate.mockClear(); + + const title = callbacks?.title?.([{label: '51-75%'}]); + const singularLabel = callbacks?.label?.({ + parsed: 1, + dataset: {data: [1, 4]}, + label: '51-75%', + }); + const pluralLabel = callbacks?.label?.({ + parsed: 4, + dataset: {data: [1, 4]}, + label: '100%', + }); + + expect(title).toBe('51-75%'); + expect(singularLabel).toBe( + 'statsUser.readingProgress.tooltipLabel:{"value":1,"plural":"","description":"statsUser.readingProgress.halfwayThrough","percentage":"20.0"}' + ); + expect(pluralLabel).toBe( + 'statsUser.readingProgress.tooltipLabel:{"value":4,"plural":"s","description":"statsUser.readingProgress.completed","percentage":"80.0"}' + ); + expect(translate).toHaveBeenCalledWith('statsUser.readingProgress.halfwayThrough'); + expect(translate).toHaveBeenCalledWith('statsUser.readingProgress.completed'); + expect(translate).toHaveBeenCalledWith('statsUser.readingProgress.tooltipLabel', { + value: 1, + plural: '', + description: 'statsUser.readingProgress.halfwayThrough', + percentage: '20.0', + }); + expect(translate).toHaveBeenCalledWith('statsUser.readingProgress.tooltipLabel', { + value: 4, + plural: 's', + description: 'statsUser.readingProgress.completed', + percentage: '80.0', + }); + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/reading-session-heatmap/reading-session-heatmap.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/reading-session-heatmap/reading-session-heatmap.component.spec.ts new file mode 100644 index 000000000..fcf4339db --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/reading-session-heatmap/reading-session-heatmap.component.spec.ts @@ -0,0 +1,10 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around Chart.js matrix registration, +// translated tooltip callbacks, streak-stat loading, and year navigation so heatmap processing can +// be exercised without relying on matrix controller rendering internals. +describe.skip('ReadingSessionHeatmapComponent', () => { + it('needs chart-runtime and streak seams to verify heatmap data shaping and milestone calculations deterministically', () => { + // TODO(seam): Cover heatmap cell construction and streak milestones once Chart.js matrix concerns are isolated. + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/reading-session-timeline/reading-session-timeline.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/reading-session-timeline/reading-session-timeline.component.spec.ts new file mode 100644 index 000000000..773a2b63c --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/reading-session-timeline/reading-session-timeline.component.spec.ts @@ -0,0 +1,10 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around date-fns week math, timeline layout +// calculations, stats-service loading, and translated select labels so week navigation and session +// stacking can be asserted without reproducing the full interactive timeline UI. +describe.skip('ReadingSessionTimelineComponent', () => { + it('needs timeline-layout and stats seams to verify week navigation, session grouping, and tooltip content deterministically', () => { + // TODO(seam): Cover timeline conversion and overlap layout once the date math and stats loading are extracted behind a smaller adapter. + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/reading-survival-chart/reading-survival-chart.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/reading-survival-chart/reading-survival-chart.component.spec.ts new file mode 100644 index 000000000..542105c9a --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/reading-survival-chart/reading-survival-chart.component.spec.ts @@ -0,0 +1,65 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {describe, expect, it} from 'vitest'; + +import {ReadingSurvivalChartComponent} from './reading-survival-chart.component'; +import {BookService} from '../../../../../book/service/book.service'; +import {TranslocoService} from '@jsverse/transloco'; +import {Book} from '../../../../../book/model/book.model'; + +describe('ReadingSurvivalChartComponent', () => { + function createComponent(books: Book[], loading = false) { + const booksSignal = signal(books); + const loadingSignal = signal(loading); + + TestBed.configureTestingModule({ + imports: [ReadingSurvivalChartComponent], + providers: [ + {provide: BookService, useValue: {books: booksSignal.asReadonly(), isBooksLoading: loadingSignal.asReadonly()}}, + {provide: TranslocoService, useValue: {translate: (key: string, params?: Record) => params ? `${key}:${Object.values(params).join(':')}` : key}}, + ] + }); + + return TestBed.createComponent(ReadingSurvivalChartComponent).componentInstance; + } + + it('returns empty metrics while books are loading', () => { + const component = createComponent([], true); + + expect(component.totalStarted()).toBe(0); + expect(component.completionRate()).toBe(0); + expect(component.medianDropout()).toBe(''); + expect(component.dangerZoneRange()).toBe(''); + expect(component.dangerZoneDrop()).toBe(''); + expect(component.chartData()).toEqual({labels: [], datasets: []}); + }); + + it('returns empty metrics when no books have been started', () => { + const component = createComponent([ + {id: 1, libraryId: 1, libraryName: 'Alpha', pdfProgress: {page: 1, percentage: 0}} as Book, + {id: 2, libraryId: 1, libraryName: 'Alpha', epubProgress: {cfi: 'cfi', percentage: 0}} as Book, + ]); + + expect(component.totalStarted()).toBe(0); + expect(component.completionRate()).toBe(0); + expect(component.chartData()).toEqual({labels: [], datasets: []}); + }); + + it('calculates survival metrics from all progress sources', () => { + const component = createComponent([ + {id: 1, libraryId: 1, libraryName: 'Alpha', pdfProgress: {page: 1, percentage: 5}} as Book, + {id: 2, libraryId: 1, libraryName: 'Alpha', epubProgress: {cfi: 'cfi', percentage: 15}} as Book, + {id: 3, libraryId: 1, libraryName: 'Alpha', cbxProgress: {page: 1, percentage: 35}} as Book, + {id: 4, libraryId: 1, libraryName: 'Alpha', koreaderProgress: {percentage: 80}} as Book, + {id: 5, libraryId: 1, libraryName: 'Alpha', koboProgress: {percentage: 100}} as Book, + ]); + + expect(component.totalStarted()).toBe(5); + expect(component.completionRate()).toBe(20); + expect(component.medianDropout()).toBe('25-50%'); + expect(component.dangerZoneRange()).toBe('0-10%'); + expect(component.dangerZoneDrop()).toBe('-20%'); + expect(component.chartData().labels).toEqual(['0%', '10%', '25%', '50%', '75%', '90%', '100%']); + expect(component.chartData().datasets[0]?.label).toBe('statsUser.readingSurvival.survivalRate'); + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/reading-survival-chart/reading-survival-chart.component.ts b/frontend/src/app/features/stats/component/user-stats/charts/reading-survival-chart/reading-survival-chart.component.ts index d4c9b71ed..67a5dc2b4 100644 --- a/frontend/src/app/features/stats/component/user-stats/charts/reading-survival-chart/reading-survival-chart.component.ts +++ b/frontend/src/app/features/stats/component/user-stats/charts/reading-survival-chart/reading-survival-chart.component.ts @@ -129,14 +129,11 @@ export class ReadingSurvivalChartComponent { const completionRate = Math.round(survivalValues[survivalValues.length - 1]); const medianIdx = survivalValues.findIndex(v => v < 50); - let medianDropout = ''; - if (medianIdx === -1) { - medianDropout = '100%+'; - } else if (medianIdx === 0) { - medianDropout = `${THRESHOLDS[0]}%`; - } else { - medianDropout = `${THRESHOLDS[medianIdx - 1]}-${THRESHOLDS[medianIdx]}%`; - } + const medianDropout = medianIdx === -1 + ? '100%+' + : medianIdx === 0 + ? `${THRESHOLDS[0]}%` + : `${THRESHOLDS[medianIdx - 1]}-${THRESHOLDS[medianIdx]}%`; let maxDrop = 0; let dangerIdx = 0; diff --git a/frontend/src/app/features/stats/component/user-stats/charts/series-progress-chart/series-progress-chart.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/series-progress-chart/series-progress-chart.component.spec.ts new file mode 100644 index 000000000..74fd0d85e --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/series-progress-chart/series-progress-chart.component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around signal-driven chart syncing, +// series aggregation, pagination/filter state, and translated tooltip callbacks so series +// progress analysis can be verified without a live Chart.js stack. +describe.skip('SeriesProgressChartComponent', () => { + it('needs aggregation seams to verify series status classification, ratings, next-unread selection, and summary stats', () => { + // TODO(seam): Cover calculateAndUpdateChart and the series aggregation helpers once the chart output is extracted behind a testable adapter. + }); + + it('needs pagination and callback seams to verify search, sorting, filtering, and tooltip body generation', () => { + // TODO(seam): Cover applyFiltersAndSort and chartOptions callbacks after separating Chart.js metadata and DOM event handling from the component logic. + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/charts/session-archetypes-chart/session-archetypes-chart.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/charts/session-archetypes-chart/session-archetypes-chart.component.spec.ts new file mode 100644 index 000000000..62bb4d11c --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/charts/session-archetypes-chart/session-archetypes-chart.component.spec.ts @@ -0,0 +1,10 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around Chart.js scatter datasets, translated +// tooltip callbacks, and stats-service loading so outlier filtering and dominant-archetype selection +// can be tested without binding to chart rendering internals. +describe.skip('SessionArchetypesChartComponent', () => { + it('needs chart-data seams to verify scatter dataset grouping and dominant archetype calculations', () => { + // TODO(seam): Cover filtering and dataset construction once chart callbacks and service responses are isolated from Chart.js runtime concerns. + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/service/user-chart-config.service.spec.ts b/frontend/src/app/features/stats/component/user-stats/service/user-chart-config.service.spec.ts new file mode 100644 index 000000000..9aa288a1d --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/service/user-chart-config.service.spec.ts @@ -0,0 +1,109 @@ +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {UserChartConfigService} from './user-chart-config.service'; + +describe('UserChartConfigService', () => { + const storageKey = 'userStatsChartConfig'; + + beforeEach(() => { + localStorage.clear(); + TestBed.configureTestingModule({ + providers: [UserChartConfigService] + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + localStorage.clear(); + }); + + it('loads the default chart layout when nothing has been saved', () => { + const service = TestBed.inject(UserChartConfigService); + + expect(service.charts()).toHaveLength(23); + expect(service.visibleCharts()).toHaveLength(23); + expect(service.charts()[0]).toEqual({ + id: 'heatmap', + enabled: true, + sizeClass: 'chart-full', + order: 0, + }); + expect(localStorage.getItem(storageKey)).toBeNull(); + }); + + it('merges saved chart state with the defaults', () => { + localStorage.setItem(storageKey, JSON.stringify([ + {id: 'heatmap', enabled: false, sizeClass: 'chart-small-square', order: 12}, + {id: 'timeline', enabled: true, sizeClass: 'chart-medium', order: 0}, + {id: 'reading-clock', enabled: false, sizeClass: 'chart-medium', order: 2}, + ])); + + const service = TestBed.inject(UserChartConfigService); + + expect(service.charts()[0]).toEqual({ + id: 'timeline', + enabled: true, + sizeClass: 'chart-medium', + order: 0, + }); + expect(service.charts().find(chart => chart.id === 'heatmap')).toEqual({ + id: 'heatmap', + enabled: false, + sizeClass: 'chart-small-square', + order: 12, + }); + expect(service.visibleCharts().map(chart => chart.id)).not.toContain('heatmap'); + }); + + it('falls back to defaults when the saved state is invalid', () => { + localStorage.setItem(storageKey, 'not-json'); + + const service = TestBed.inject(UserChartConfigService); + + expect(service.charts()[0].id).toBe('heatmap'); + expect(service.charts()[1].id).toBe('favorite-days'); + }); + + it('toggles charts, enables or disables all charts, and restores the default layout', () => { + const service = TestBed.inject(UserChartConfigService); + + service.toggleChart('timeline'); + expect(service.charts().find(chart => chart.id === 'timeline')?.enabled).toBe(false); + + service.setAllChartsEnabled(false); + expect(service.visibleCharts()).toEqual([]); + + service.resetLayout(); + expect(service.charts()[0]).toEqual({ + id: 'heatmap', + enabled: true, + sizeClass: 'chart-full', + order: 0, + }); + expect(service.visibleCharts()).toHaveLength(23); + }); + + it('reorders the selected chart subset and preserves normalized storage order', () => { + const service = TestBed.inject(UserChartConfigService); + + service.reorderCharts( + service.charts().filter(chart => chart.id === 'heatmap' || chart.id === 'timeline'), + 0, + 1 + ); + + expect(service.charts().slice(0, 4).map(chart => chart.id)).toEqual([ + 'timeline', + 'favorite-days', + 'peak-hours', + 'heatmap', + ]); + expect(JSON.parse(localStorage.getItem(storageKey) || '[]')[0]).toEqual({ + id: 'timeline', + enabled: true, + sizeClass: 'chart-full', + order: 0, + }); + }); +}); diff --git a/frontend/src/app/features/stats/component/user-stats/user-stats.component.spec.ts b/frontend/src/app/features/stats/component/user-stats/user-stats.component.spec.ts new file mode 100644 index 000000000..6b639af5c --- /dev/null +++ b/frontend/src/app/features/stats/component/user-stats/user-stats.component.spec.ts @@ -0,0 +1,75 @@ +import {computed, signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {UserService} from '../../../settings/user-management/user.service'; +import {UserChartConfigService} from './service/user-chart-config.service'; +import {UserStatsComponent} from './user-stats.component'; + +describe('UserStatsComponent', () => { + let chartConfigService: { + charts: ReturnType; + visibleCharts: ReturnType; + toggleChart: ReturnType; + reorderCharts: ReturnType; + resetLayout: ReturnType; + setAllChartsEnabled: ReturnType; + }; + + beforeEach(() => { + const chartSignal = signal([ + {id: 'reading-progress', enabled: true, sizeClass: 'chart-small-square', order: 0}, + ]); + chartConfigService = { + charts: chartSignal, + visibleCharts: computed(() => chartSignal().filter(chart => chart.enabled)), + toggleChart: vi.fn(), + reorderCharts: vi.fn(), + resetLayout: vi.fn(), + setAllChartsEnabled: vi.fn(), + }; + + TestBed.configureTestingModule({ + providers: [ + { + provide: UserService, + useValue: { + currentUser: signal({name: 'Alice Reader', username: 'alice'}), + }, + }, + {provide: UserChartConfigService, useValue: chartConfigService}, + ], + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('derives the display name and chart translation key from injected state', () => { + const component = TestBed.runInInjectionContext(() => new UserStatsComponent()); + + expect(component.userName()).toBe('Alice Reader'); + expect(component.chartNameKey('reading-progress')).toBe('chartNames.readingProgress'); + }); + + it('forwards chart actions to the chart config service', () => { + const component = TestBed.runInInjectionContext(() => new UserStatsComponent()); + + component.toggleChart('reading-progress'); + component.showAllCharts(); + component.hideAllCharts(); + component.resetLayout(); + component.drop({ + container: {data: chartConfigService.charts()}, + previousIndex: 0, + currentIndex: 0, + } as never); + + expect(chartConfigService.toggleChart).toHaveBeenCalledWith('reading-progress'); + expect(chartConfigService.setAllChartsEnabled).toHaveBeenNthCalledWith(1, true); + expect(chartConfigService.setAllChartsEnabled).toHaveBeenNthCalledWith(2, false); + expect(chartConfigService.resetLayout).toHaveBeenCalled(); + expect(chartConfigService.reorderCharts).toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/app/shared/components/book-uploader/book-uploader.component.spec.ts b/frontend/src/app/shared/components/book-uploader/book-uploader.component.spec.ts new file mode 100644 index 000000000..0712c2764 --- /dev/null +++ b/frontend/src/app/shared/components/book-uploader/book-uploader.component.spec.ts @@ -0,0 +1,17 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Honest coverage for this component needs a PrimeNG FileUpload host seam, +// controllable library/settings signals, and a stable upload-progress harness for `HttpRequest` +// event streams and dialog close behavior. The current surface mixes view-child state, effects, +// progress events, and UI messaging too tightly for a reliable low-noise unit spec tonight. +describe.skip('BookUploaderComponent', () => { + it('needs a file-upload seam to verify destination validation, duplicate filtering, and size failures', () => { + // TODO(seam): Cover file selection and validation after the PrimeNG file chooser state is + // wrapped behind a testable adapter instead of relying on the live FileUpload view child. + }); + + it('needs an upload-progress seam to verify request batching, status transitions, and bookdrop close behavior', () => { + // TODO(seam): Cover progress updates and terminal states once upload event streams can be + // driven without coupling the spec to the full PrimeNG/http runtime. + }); +}); diff --git a/frontend/src/app/shared/components/change-password/change-password.component.spec.ts b/frontend/src/app/shared/components/change-password/change-password.component.spec.ts new file mode 100644 index 000000000..ce5803ee3 --- /dev/null +++ b/frontend/src/app/shared/components/change-password/change-password.component.spec.ts @@ -0,0 +1,131 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {of, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {MessageService} from 'primeng/api'; +import {TranslocoService} from '@jsverse/transloco'; + +import {getTranslocoModule} from '../../../core/testing/transloco-testing'; +import {AuthService} from '../../service/auth.service'; +import {ChangePasswordComponent} from './change-password.component'; +import {UserService} from '../../../features/settings/user-management/user.service'; + +describe('ChangePasswordComponent', () => { + let fixture: ComponentFixture; + let component: ChangePasswordComponent; + let userService: {changePassword: ReturnType}; + let authService: {logout: ReturnType}; + let messageService: {add: ReturnType}; + let translocoService: TranslocoService; + + beforeEach(async () => { + userService = { + changePassword: vi.fn(() => of(void 0)), + }; + authService = { + logout: vi.fn(), + }; + messageService = { + add: vi.fn(), + }; + + await TestBed.configureTestingModule({ + imports: [ChangePasswordComponent, getTranslocoModule()], + providers: [ + {provide: UserService, useValue: userService}, + {provide: AuthService, useValue: authService}, + {provide: MessageService, useValue: messageService}, + ], + }).compileComponents(); + + fixture = TestBed.createComponent(ChangePasswordComponent); + component = fixture.componentInstance; + translocoService = TestBed.inject(TranslocoService); + }); + + afterEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + it('tracks whether the new passwords match', () => { + component.newPassword = 'new-password'; + component.confirmNewPassword = 'new-password'; + expect(component.passwordsMatch).toBe(true); + + component.confirmNewPassword = 'different'; + expect(component.passwordsMatch).toBe(false); + }); + + it('rejects submissions with missing fields before calling the service', () => { + component.currentPassword = 'current'; + component.newPassword = ''; + component.confirmNewPassword = 'new-password'; + + component.changePassword(); + + expect(component.errorMessage).toBe( + translocoService.translate('shared.changePassword.validation.allFieldsRequired') + ); + expect(userService.changePassword).not.toHaveBeenCalled(); + }); + + it('rejects submissions when the new passwords do not match', () => { + component.currentPassword = 'current'; + component.newPassword = 'new-password'; + component.confirmNewPassword = 'different'; + + component.changePassword(); + + expect(component.errorMessage).toBe( + translocoService.translate('shared.changePassword.validation.passwordsDoNotMatch') + ); + expect(userService.changePassword).not.toHaveBeenCalled(); + }); + + it('rejects submissions when the new password matches the current password', () => { + component.currentPassword = 'same-password'; + component.newPassword = 'same-password'; + component.confirmNewPassword = 'same-password'; + + component.changePassword(); + + expect(component.errorMessage).toBe( + translocoService.translate('shared.changePassword.validation.sameAsCurrentPassword') + ); + expect(userService.changePassword).not.toHaveBeenCalled(); + }); + + it('changes the password and logs the user out on success', () => { + component.currentPassword = 'current-password'; + component.newPassword = 'new-password'; + component.confirmNewPassword = 'new-password'; + + component.changePassword(); + + expect(userService.changePassword).toHaveBeenCalledWith('current-password', 'new-password'); + expect(component.successMessage).toBe( + translocoService.translate('shared.changePassword.toast.success') + ); + expect(authService.logout).toHaveBeenCalled(); + expect(messageService.add).not.toHaveBeenCalled(); + }); + + it('surfaces backend failures through the error message and toast service', () => { + userService.changePassword.mockReturnValueOnce( + throwError(() => ({message: 'Password update failed'})) + ); + component.currentPassword = 'current-password'; + component.newPassword = 'new-password'; + component.confirmNewPassword = 'new-password'; + + component.changePassword(); + + expect(component.errorMessage).toBe('Password update failed'); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: translocoService.translate('shared.changePassword.toast.failedSummary'), + detail: 'Password update failed', + }); + expect(authService.logout).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/app/shared/components/cover-generator/cover-generator.component.spec.ts b/frontend/src/app/shared/components/cover-generator/cover-generator.component.spec.ts new file mode 100644 index 000000000..5a1004d55 --- /dev/null +++ b/frontend/src/app/shared/components/cover-generator/cover-generator.component.spec.ts @@ -0,0 +1,76 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {CoverGeneratorComponent} from './cover-generator.component'; + +describe('CoverGeneratorComponent', () => { + let fixture: ComponentFixture; + let component: CoverGeneratorComponent; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [CoverGeneratorComponent], + }).compileComponents(); + + fixture = TestBed.createComponent(CoverGeneratorComponent); + component = fixture.componentInstance; + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + function decodeCover(dataUrl: string): string { + const encoded = dataUrl.replace('data:image/svg+xml;base64,', ''); + return decodeURIComponent( + Array.from(atob(encoded)) + .map(char => `%${char.charCodeAt(0).toString(16).padStart(2, '0')}`) + .join('') + ); + } + + it('generates a base64-encoded ebook cover with escaped title and author text', () => { + component.title = 'Dune & '; + component.author = 'Frank "Herbert"'; + + const svg = decodeCover(component.generateCover()); + + expect(svg).toContain(' { + component.title = 'Project Hail Mary'; + component.author = 'Andy Weir'; + component.isSquare = true; + + const svg = decodeCover(component.generateCover()); + + expect(svg).toContain('width="250" height="250"'); + expect(svg).toContain('L-6,8 L8,0 Z'); + }); + + it('wraps and truncates long titles into multiple lines', () => { + component.title = 'A Very Long Book Title That Keeps Going Beyond The Expected Width Of The Cover'; + component.author = 'Someone'; + + const svg = decodeCover(component.generateCover()); + + expect((svg.match(/ { + component.title = 'Dune'; + component.author = 'Frank Herbert'; + + const first = component.generateCover(); + const second = component.generateCover(); + + expect(first).toBe(second); + }); +}); diff --git a/frontend/src/app/shared/components/directory-picker/directory-picker.component.spec.ts b/frontend/src/app/shared/components/directory-picker/directory-picker.component.spec.ts new file mode 100644 index 000000000..84b3988a9 --- /dev/null +++ b/frontend/src/app/shared/components/directory-picker/directory-picker.component.spec.ts @@ -0,0 +1,138 @@ +import {of, throwError} from 'rxjs'; +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {DynamicDialogRef} from 'primeng/dynamicdialog'; + +import {getTranslocoModule} from '../../../core/testing/transloco-testing'; +import {DirectoryPickerComponent} from './directory-picker.component'; +import {UtilityService} from './utility.service'; + +describe('DirectoryPickerComponent', () => { + let fixture: ComponentFixture; + let component: DirectoryPickerComponent; + let utilityService: {getFolders: ReturnType}; + let dialogRef: {close: ReturnType}; + + beforeEach(async () => { + utilityService = { + getFolders: vi.fn(() => of(['/books', '/comics'])), + }; + dialogRef = { + close: vi.fn(), + }; + + vi.useFakeTimers(); + + await TestBed.configureTestingModule({ + imports: [DirectoryPickerComponent, getTranslocoModule()], + providers: [ + {provide: UtilityService, useValue: utilityService}, + {provide: DynamicDialogRef, useValue: dialogRef}, + ], + }).compileComponents(); + + fixture = TestBed.createComponent(DirectoryPickerComponent); + component = fixture.componentInstance; + }); + + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + it('loads the root folders on init and updates loading state after the delayed response', () => { + component.ngOnInit(); + + expect(utilityService.getFolders).toHaveBeenCalledWith('/'); + expect(component.isLoading).toBe(true); + + vi.advanceTimersByTime(100); + + expect(component.paths).toEqual(['/books', '/comics']); + expect(component.filteredPaths).toEqual(['/books', '/comics']); + expect(component.isLoading).toBe(false); + expect(component.breadcrumbItems).toEqual([]); + }); + + it('builds breadcrumb items for nested paths', () => { + component.updateBreadcrumb('/books/scifi/dune'); + + expect(component.breadcrumbItems.map(item => item.label)).toEqual(['books', 'scifi', 'dune']); + }); + + it('filters visible paths using a case-insensitive search', () => { + component.paths = ['/Books', '/Comics', '/Magazines']; + component.searchQuery = 'co'; + + component.onSearch(); + + expect(component.filteredPaths).toEqual(['/Comics']); + }); + + it('tracks checkbox selection and exposes the selection state', () => { + component.onCheckboxChange('/books', true); + expect(component.selectedFolders).toEqual(['/books']); + expect(component.isFolderSelected('/books')).toBe(true); + + component.onCheckboxChange('/books', false); + expect(component.selectedFolders).toEqual([]); + expect(component.isFolderSelected('/books')).toBe(false); + }); + + it('navigates up to the parent path and clears the active search', () => { + const getFoldersSpy = vi.spyOn(component, 'getFolders').mockImplementation(() => undefined); + component.selectedProductName = '/books/scifi'; + component.searchQuery = 'du'; + + component.goUp(); + + expect(component.selectedProductName).toBe('/books'); + expect(component.searchQuery).toBe(''); + expect(getFoldersSpy).toHaveBeenCalledWith('/books'); + }); + + it('selects all filtered folders and can clear them again', () => { + component.filteredPaths = ['/books', '/comics']; + + component.selectAll(); + expect(component.selectedFolders).toEqual(['/books', '/comics']); + expect(component.selectedFoldersMap).toMatchObject({ + '/books': true, + '/comics': true, + }); + + component.deselectAll(); + expect(component.selectedFolders).toEqual([]); + expect(component.selectedFoldersMap).toMatchObject({ + '/books': false, + '/comics': false, + }); + }); + + it('closes the dialog with the selected folders or null', () => { + component.selectedFolders = ['/books']; + + component.onSelect(); + component.onCancel(); + + expect(dialogRef.close).toHaveBeenNthCalledWith(1, ['/books']); + expect(dialogRef.close).toHaveBeenNthCalledWith(2, null); + }); + + it('clears loading state when folder loading fails', () => { + vi.spyOn(console, 'error').mockImplementation(() => undefined); + utilityService.getFolders.mockReturnValueOnce(throwError(() => new Error('boom'))); + + component.getFolders('/broken'); + + expect(component.isLoading).toBe(false); + expect(console.error).toHaveBeenCalled(); + }); + + it('extracts the final folder name from a path', () => { + expect(component.getFolderName('/books/scifi')).toBe('scifi'); + expect(component.getFolderName('/')).toBe('/'); + }); +}); diff --git a/frontend/src/app/shared/components/directory-picker/utility.service.spec.ts b/frontend/src/app/shared/components/directory-picker/utility.service.spec.ts new file mode 100644 index 000000000..fd04e050a --- /dev/null +++ b/frontend/src/app/shared/components/directory-picker/utility.service.spec.ts @@ -0,0 +1,45 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {UtilityService} from './utility.service'; + +describe('UtilityService', () => { + let service: UtilityService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + UtilityService, + ], + }); + + service = TestBed.inject(UtilityService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('requests folders for the provided path', () => { + const response = ['/books', '/books/scifi']; + + let result: string[] | undefined; + service.getFolders('/books').subscribe(value => { + result = value; + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/path')); + expect(request.request.method).toBe('GET'); + expect(request.request.params.get('path')).toBe('/books'); + request.flush(response); + + expect(result).toEqual(response); + }); +}); diff --git a/frontend/src/app/shared/components/empty/empty.component.spec.ts b/frontend/src/app/shared/components/empty/empty.component.spec.ts new file mode 100644 index 000000000..04ec62b1c --- /dev/null +++ b/frontend/src/app/shared/components/empty/empty.component.spec.ts @@ -0,0 +1,25 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {beforeEach, describe, expect, it} from 'vitest'; + +import {EmptyComponent} from './empty.component'; + +describe('EmptyComponent', () => { + let fixture: ComponentFixture; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [EmptyComponent], + }).compileComponents(); + + fixture = TestBed.createComponent(EmptyComponent); + fixture.detectChanges(); + }); + + it('creates successfully', () => { + expect(fixture.componentInstance).toBeTruthy(); + }); + + it('renders the empty state template', () => { + expect(fixture.nativeElement.textContent?.trim().length).toBeGreaterThan(0); + }); +}); diff --git a/frontend/src/app/shared/components/external-doc-link/external-doc-link.component.spec.ts b/frontend/src/app/shared/components/external-doc-link/external-doc-link.component.spec.ts new file mode 100644 index 000000000..ad14cf924 --- /dev/null +++ b/frontend/src/app/shared/components/external-doc-link/external-doc-link.component.spec.ts @@ -0,0 +1,53 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {ExternalDocLinkComponent} from './external-doc-link.component'; + +describe('ExternalDocLinkComponent', () => { + let fixture: ComponentFixture; + let component: ExternalDocLinkComponent; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [ExternalDocLinkComponent], + }).compileComponents(); + + fixture = TestBed.createComponent(ExternalDocLinkComponent); + component = fixture.componentInstance; + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('opens the configured documentation link in a new tab', () => { + const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null); + component.docType = 'taskManagement'; + + component.openLink(); + + expect(openSpy).toHaveBeenCalledWith('https://grimmory.org/docs/tools/task-manager', '_blank'); + }); + + it('does nothing when the doc type is unknown at runtime', () => { + const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null); + (component as unknown as {docType: string}).docType = 'unknown'; + + component.openLink(); + + expect(openSpy).not.toHaveBeenCalled(); + }); + + it('renders the clickable icon with the configured size', () => { + component.docType = 'authentication'; + component.tooltip = 'Read the docs'; + component.tooltipPosition = 'left'; + component.size = '1.5rem'; + fixture.detectChanges(); + + const icon = fixture.nativeElement.querySelector('i') as HTMLElement; + expect(icon.getAttribute('role')).toBe('button'); + expect(icon.getAttribute('tabindex')).toBe('0'); + expect(icon.style.fontSize).toBe('1.5rem'); + }); +}); diff --git a/frontend/src/app/shared/components/file-mover/file-mover-component.spec.ts b/frontend/src/app/shared/components/file-mover/file-mover-component.spec.ts new file mode 100644 index 000000000..da1d9184f --- /dev/null +++ b/frontend/src/app/shared/components/file-mover/file-mover-component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around dialog config input, +// library-query reactivity, placeholder resolution, and file-operation side effects so +// preview generation and move submission can be asserted without reproducing the full runtime graph. +describe.skip('FileMoverComponent', () => { + it('needs a query-and-dialog seam to verify preview generation and target-library path updates', () => { + // TODO(seam): Cover applyPattern and library/path change flows once dialog config and reactive library data are injectable test seams. + }); + + it('needs a file-operations seam to verify move submission and toast behavior without coupling to runtime app settings effects', () => { + // TODO(seam): Cover move execution, success/failure messaging, and pattern source selection after extracting the side-effectful workflow. + }); +}); diff --git a/frontend/src/app/shared/components/icon-display/icon-display.component.spec.ts b/frontend/src/app/shared/components/icon-display/icon-display.component.spec.ts new file mode 100644 index 000000000..829726383 --- /dev/null +++ b/frontend/src/app/shared/components/icon-display/icon-display.component.spec.ts @@ -0,0 +1,127 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {SafeHtml} from '@angular/platform-browser'; +import {of, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {IconDisplayComponent} from './icon-display.component'; +import {IconCacheService} from '../../services/icon-cache.service'; +import {IconService} from '../../services/icon.service'; + +describe('IconDisplayComponent', () => { + let fixture: ComponentFixture; + let component: IconDisplayComponent; + let iconCache: { + getCachedSanitized: ReturnType; + cacheIcon: ReturnType; + }; + let iconService: {getSanitizedSvgContent: ReturnType}; + + beforeEach(async () => { + iconCache = { + getCachedSanitized: vi.fn(() => null), + cacheIcon: vi.fn(), + }; + iconService = { + getSanitizedSvgContent: vi.fn(() => of('ok' as SafeHtml)), + }; + + await TestBed.configureTestingModule({ + imports: [IconDisplayComponent], + providers: [ + {provide: IconCacheService, useValue: iconCache}, + {provide: IconService, useValue: iconService}, + ], + }).compileComponents(); + + fixture = TestBed.createComponent(IconDisplayComponent); + component = fixture.componentInstance; + }); + + afterEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + it('normalizes PrimeNG icon class names', () => { + expect(component.getPrimeNgIconClass('pi pi-book')).toBe('pi pi-book'); + expect(component.getPrimeNgIconClass('pi-book')).toBe('pi pi-book'); + expect(component.getPrimeNgIconClass('book')).toBe('pi pi-book'); + }); + + it('builds PrimeNG styles from the configured size and extra icon style', () => { + component.size = '20px'; + component.iconStyle = {color: 'tomato'}; + + expect(component.getPrimeNgStyle()).toEqual({ + fontSize: '17px', + width: '20px', + height: '20px', + display: 'inline-flex', + alignItems: 'center', + justifyContent: 'center', + color: 'tomato', + }); + }); + + it('loads uncached custom SVG icons on initialization', () => { + component.icon = {type: 'CUSTOM_SVG', value: 'dragon'}; + + fixture.detectChanges(); + + expect(iconCache.getCachedSanitized).toHaveBeenCalledWith('dragon'); + expect(iconService.getSanitizedSvgContent).toHaveBeenCalledWith('dragon'); + }); + + it('does not reload the same custom SVG when the value has not changed', () => { + const loadSpy = vi.spyOn(component as never, 'loadIconIfNeeded'); + component.ngOnChanges({ + icon: { + currentValue: {type: 'CUSTOM_SVG', value: 'dragon'}, + previousValue: {type: 'CUSTOM_SVG', value: 'dragon'}, + firstChange: false, + isFirstChange: () => false, + }, + }); + + expect(loadSpy).not.toHaveBeenCalled(); + }); + + it('reloads when the custom SVG icon value changes', () => { + const loadSpy = vi.spyOn(component as never, 'loadIconIfNeeded'); + + component.ngOnChanges({ + icon: { + currentValue: {type: 'CUSTOM_SVG', value: 'dragon'}, + previousValue: {type: 'CUSTOM_SVG', value: 'phoenix'}, + firstChange: false, + isFirstChange: () => false, + }, + }); + + expect(loadSpy).toHaveBeenCalled(); + }); + + it('exposes cached SVG content and empty-icon dimensions', () => { + iconCache.getCachedSanitized.mockReturnValueOnce('cached' as SafeHtml); + component.size = '2rem'; + + expect(component.getSvgContent('cached')).toBe('cached' as SafeHtml); + expect(component.getEmptyIconStyle()).toEqual({ + width: '2rem', + height: '2rem', + }); + }); + + it('caches an error SVG when loading a custom icon fails', () => { + iconService.getSanitizedSvgContent.mockReturnValueOnce( + throwError(() => new Error('nope')) + ); + component.icon = {type: 'CUSTOM_SVG', value: 'broken'}; + + fixture.detectChanges(); + + expect(iconCache.cacheIcon).toHaveBeenCalledOnce(); + expect(iconCache.cacheIcon.mock.calls[0]?.[0]).toBe('broken'); + expect(iconCache.cacheIcon.mock.calls[0]?.[1]).toContain('stroke="red"'); + }); +}); diff --git a/frontend/src/app/shared/components/icon-picker/icon-picker-component.spec.ts b/frontend/src/app/shared/components/icon-picker/icon-picker-component.spec.ts new file mode 100644 index 000000000..bd3e50202 --- /dev/null +++ b/frontend/src/app/shared/components/icon-picker/icon-picker-component.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs seams around DOMPurify preview generation, +// batch-upload side effects, dialog closing, and drag/drop DOM events so the SVG-management +// flow can be proven without changing runtime code or reproducing browser-only behavior inline. +describe.skip('IconPickerComponent', () => { + it('needs a browser-event seam to verify SVG preview, validation, and drag-to-delete flows', () => { + // TODO(seam): Cover SVG parsing, preview generation, and drag/drop delete behavior once event/DOM seams exist. + }); + + it('needs an upload-result seam to verify partial-success batch messaging and cache refresh behavior', () => { + // TODO(seam): Cover saveAllSvgs and loadSvgIcons without coupling the spec to live DOMPurify and dialog runtime behavior. + }); +}); diff --git a/frontend/src/app/shared/components/live-notification-box/live-notification-box.component.spec.ts b/frontend/src/app/shared/components/live-notification-box/live-notification-box.component.spec.ts new file mode 100644 index 000000000..1f5d2ff28 --- /dev/null +++ b/frontend/src/app/shared/components/live-notification-box/live-notification-box.component.spec.ts @@ -0,0 +1,91 @@ +import {Subject} from 'rxjs'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {TranslocoService} from '@jsverse/transloco'; + +import {NotificationEventService} from '../../websocket/notification-event.service'; +import {LogNotification, Severity} from '../../websocket/model/log-notification.model'; +import {LiveNotificationBoxComponent} from './live-notification-box.component'; + +describe('LiveNotificationBoxComponent', () => { + let notifications$: Subject; + let langChanges$: Subject; + let component: LiveNotificationBoxComponent; + + beforeEach(() => { + notifications$ = new Subject(); + langChanges$ = new Subject(); + + TestBed.configureTestingModule({ + providers: [ + LiveNotificationBoxComponent, + { + provide: NotificationEventService, + useValue: {latestNotification$: notifications$}, + }, + { + provide: TranslocoService, + useValue: { + translate: (key: string) => `translated:${key}`, + langChanges$, + }, + }, + ], + }); + + component = TestBed.inject(LiveNotificationBoxComponent); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('starts with the translated default message', () => { + expect(component.latestNotification).toEqual({ + message: 'translated:shared.liveNotification.defaultMessage', + }); + }); + + it('replaces the latest notification when a websocket event arrives', () => { + notifications$.next({message: 'Metadata updated', severity: Severity.INFO}); + + expect(component.latestNotification).toEqual({ + message: 'Metadata updated', + severity: Severity.INFO, + }); + }); + + it('refreshes the default message on language changes until a notification arrives', () => { + langChanges$.next('fr'); + + expect(component.latestNotification).toEqual({ + message: 'translated:shared.liveNotification.defaultMessage', + }); + + notifications$.next({message: 'Build finished', severity: Severity.WARN}); + langChanges$.next('de'); + + expect(component.latestNotification).toEqual({ + message: 'Build finished', + severity: Severity.WARN, + }); + }); + + it('maps severities to the expected tag colors', () => { + expect(component.getSeverityColor(Severity.ERROR)).toBe('red'); + expect(component.getSeverityColor(Severity.WARN)).toBe('amber'); + expect(component.getSeverityColor(Severity.INFO)).toBe('green'); + expect(component.getSeverityColor(undefined)).toBe('gray'); + }); + + it('stops reacting to streams after destruction', () => { + component.ngOnDestroy(); + notifications$.next({message: 'Ignored', severity: Severity.ERROR}); + langChanges$.next('es'); + + expect(component.latestNotification).toEqual({ + message: 'translated:shared.liveNotification.defaultMessage', + }); + }); +}); diff --git a/frontend/src/app/shared/components/login/login.component.spec.ts b/frontend/src/app/shared/components/login/login.component.spec.ts new file mode 100644 index 000000000..352b7b942 --- /dev/null +++ b/frontend/src/app/shared/components/login/login.component.spec.ts @@ -0,0 +1,256 @@ +import {signal} from '@angular/core'; +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {ActivatedRoute, Router} from '@angular/router'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {of, throwError} from 'rxjs'; + +import {OidcService} from '../../../core/security/oidc.service'; +import {getTranslocoModule} from '../../../core/testing/transloco-testing'; +import {PublicAppSettings} from '../../service/app-settings.service'; +import {AuthService} from '../../service/auth.service'; +import {AppSettingsService} from '../../service/app-settings.service'; +import {LoginComponent} from './login.component'; + +function createPublicSettings(overrides: Partial = {}): PublicAppSettings { + return { + oidcEnabled: true, + remoteAuthEnabled: false, + oidcForceOnlyMode: false, + oidcProviderDetails: { + providerName: 'Pocket ID', + clientId: 'client-id', + issuerUri: 'https://issuer.example', + scopes: 'openid profile email', + claimMapping: { + username: 'preferred_username', + email: 'email', + name: 'name', + groups: 'groups', + } + }, + ...overrides + }; +} + +describe('LoginComponent', () => { + let fixture: ComponentFixture; + let component: LoginComponent; + let publicSettingsSignal: ReturnType>; + + const authService = { + clearSessionOnLoginPage: vi.fn(), + internalLogin: vi.fn(), + }; + + const router = { + navigate: vi.fn(() => Promise.resolve(true)), + }; + + const oidcService = { + generatePkce: vi.fn(), + fetchState: vi.fn(), + generateRandomString: vi.fn(), + storePkceState: vi.fn(), + buildAuthUrl: vi.fn(), + }; + + function configureComponent( + queryParams: Record = {}, + settingsOverrides: Partial = {}, + autoDetectChanges = true + ): void { + publicSettingsSignal = signal(createPublicSettings(settingsOverrides)); + + TestBed.configureTestingModule({ + imports: [ + LoginComponent, + getTranslocoModule(), + ], + providers: [ + {provide: AuthService, useValue: authService}, + {provide: Router, useValue: router}, + {provide: OidcService, useValue: oidcService}, + { + provide: AppSettingsService, + useValue: { + publicAppSettings: publicSettingsSignal, + } + }, + { + provide: ActivatedRoute, + useValue: { + queryParams: of(queryParams), + } + }, + ] + }); + + fixture = TestBed.createComponent(LoginComponent); + component = fixture.componentInstance; + if (autoDetectChanges) { + fixture.detectChanges(); + } + } + + beforeEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + sessionStorage.clear(); + + authService.clearSessionOnLoginPage.mockReset(); + authService.internalLogin.mockReset(); + router.navigate.mockClear(); + oidcService.generatePkce.mockReset(); + oidcService.fetchState.mockReset(); + oidcService.generateRandomString.mockReset(); + oidcService.storePkceState.mockReset(); + oidcService.buildAuthUrl.mockReset(); + }); + + afterEach(() => { + sessionStorage.clear(); + TestBed.resetTestingModule(); + }); + + it('clears the session and shows the session revoked message from query params', () => { + configureComponent({reason: 'session_revoked'}); + + expect(authService.clearSessionOnLoginPage).toHaveBeenCalledOnce(); + expect(component.infoMessage).toBe('auth.login.sessionRevoked'); + }); + + it('maps known OIDC callback errors to translated messages', () => { + configureComponent({oidcError: 'exchange_failed'}); + + expect(component.errorMessage).toBe('auth.login.oidcErrors.exchangeFailed'); + }); + + it('keeps the local login visible when OIDC-only mode is not enabled', () => { + configureComponent(); + + expect(component.oidcEnabled).toBe(true); + expect(component.oidcName).toBe('Pocket ID'); + expect(component.showLocalLogin).toBe(true); + }); + + it('auto-redirects to OIDC in force-only mode when there is no local override or callback error', async () => { + configureComponent({}, {oidcForceOnlyMode: true}, false); + const loginWithOidcSpy = vi.spyOn(component, 'loginWithOidc').mockResolvedValue(undefined); + + fixture.detectChanges(); + await fixture.whenStable(); + + expect(component.showLocalLogin).toBe(false); + expect(sessionStorage.getItem('oidc_redirect_count')).toBe('1'); + expect(loginWithOidcSpy).toHaveBeenCalledOnce(); + }); + + it('stops the OIDC auto-redirect loop after the maximum retry count', async () => { + sessionStorage.setItem('oidc_redirect_count', '3'); + configureComponent({}, {oidcForceOnlyMode: true}, false); + const loginWithOidcSpy = vi.spyOn(component, 'loginWithOidc').mockResolvedValue(undefined); + + fixture.detectChanges(); + await fixture.whenStable(); + + expect([ + 'auth.login.oidcOnlyRedirectFailed', + 'Unable to reach the identity provider. Please contact your administrator.' + ]).toContain(component.errorMessage); + expect(component.showLocalLogin).toBe(false); + expect(sessionStorage.getItem('oidc_redirect_count')).toBeNull(); + expect(loginWithOidcSpy).not.toHaveBeenCalled(); + }); + + it('navigates to change-password when the server marks the password as default', () => { + configureComponent(); + authService.internalLogin.mockReturnValue(of({isDefaultPassword: 'true'})); + + component.username = 'admin'; + component.password = 'password'; + component.login(); + + expect(router.navigate).toHaveBeenCalledWith(['/change-password']); + }); + + it('navigates to the dashboard after a successful non-default-password login', () => { + configureComponent(); + authService.internalLogin.mockReturnValue(of({isDefaultPassword: 'false'})); + + component.username = 'admin'; + component.password = 'password'; + component.login(); + + expect(router.navigate).toHaveBeenCalledWith(['/dashboard']); + }); + + it('shows translated messages for network and rate-limit login failures', () => { + configureComponent(); + + authService.internalLogin.mockReturnValueOnce(throwError(() => ({status: 0}))); + component.login(); + expect(component.errorMessage).toBe('Cannot connect to the server. Please check your connection and try again.'); + + authService.internalLogin.mockReturnValueOnce(throwError(() => ({status: 429}))); + component.login(); + expect(component.errorMessage).toBe('Too many failed login attempts. Please try again later.'); + }); + + it('uses the backend error message when login fails unexpectedly', () => { + configureComponent(); + authService.internalLogin.mockReturnValue( + throwError(() => ({status: 500, error: {message: 'Bad credentials'}})) + ); + + component.login(); + + expect(component.errorMessage).toBe('Bad credentials'); + }); + + it('requires provider details before starting the OIDC flow', async () => { + configureComponent(); + publicSettingsSignal.set(createPublicSettings({oidcProviderDetails: undefined as unknown as PublicAppSettings['oidcProviderDetails']})); + + await component.loginWithOidc(); + + expect(component.errorMessage).toBe('Failed to initiate OIDC login. Please try again or use local login.'); + expect(component.isOidcLoginInProgress).toBe(false); + }); + + it('builds the OIDC auth URL and redirects the browser', async () => { + configureComponent(); + oidcService.generatePkce.mockResolvedValue({codeVerifier: 'verifier', codeChallenge: 'challenge'}); + oidcService.fetchState.mockResolvedValue('state-token'); + oidcService.generateRandomString.mockReturnValue('nonce-token'); + oidcService.buildAuthUrl.mockResolvedValue('https://issuer.example/auth'); + + await component.loginWithOidc(); + + expect(oidcService.storePkceState).toHaveBeenCalledWith({ + codeVerifier: 'verifier', + state: 'state-token', + nonce: 'nonce-token', + }); + expect(oidcService.buildAuthUrl).toHaveBeenCalledWith( + 'https://issuer.example', + 'client-id', + 'challenge', + 'state-token', + 'nonce-token', + undefined, + 'openid profile email' + ); + expect(component.errorMessage).toBe(''); + }); + + it('shows a translated provider error when OIDC login initialization fails', async () => { + configureComponent(); + oidcService.generatePkce.mockRejectedValue(new Error('crypto unavailable')); + + await component.loginWithOidc(); + + expect(component.errorMessage).toBe('Could not reach the OIDC provider. Please try again later.'); + expect(component.isOidcLoginInProgress).toBe(false); + expect(component.showLocalLogin).toBe(true); + }); +}); diff --git a/frontend/src/app/shared/components/metadata-progress-widget/metadata-progress-widget-component.spec.ts b/frontend/src/app/shared/components/metadata-progress-widget/metadata-progress-widget-component.spec.ts new file mode 100644 index 000000000..235c7b714 --- /dev/null +++ b/frontend/src/app/shared/components/metadata-progress-widget/metadata-progress-widget-component.spec.ts @@ -0,0 +1,165 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {BehaviorSubject, of, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {MessageService} from 'primeng/api'; +import {TranslocoService} from '@jsverse/transloco'; + +import {MetadataBatchProgressNotification, MetadataBatchStatus} from '../../model/metadata-batch-progress.model'; +import {MetadataTaskService} from '../../../features/book/service/metadata-task'; +import {TaskService} from '../../../features/settings/task-management/task.service'; +import {getTranslocoModule} from '../../../core/testing/transloco-testing'; +import {MetadataProgressWidgetComponent} from './metadata-progress-widget-component'; +import {MetadataProgressService} from '../../service/metadata-progress.service'; +import {DialogLauncherService} from '../../services/dialog-launcher.service'; + +describe('MetadataProgressWidgetComponent', () => { + let fixture: ComponentFixture; + let component: MetadataProgressWidgetComponent; + let activeTasksSubject: BehaviorSubject>; + let metadataProgressService: { + activeTasks$: BehaviorSubject>; + clearTask: ReturnType; + }; + let metadataTaskService: {deleteTask: ReturnType}; + let taskService: {cancelTask: ReturnType}; + let dialogLauncherService: {openMetadataReviewDialog: ReturnType}; + let messageService: {add: ReturnType}; + let translocoService: TranslocoService; + + const task: MetadataBatchProgressNotification = { + taskId: 'task-1', + completed: 2, + total: 5, + message: 'Running', + status: MetadataBatchStatus.IN_PROGRESS, + review: false, + }; + + beforeEach(async () => { + activeTasksSubject = new BehaviorSubject>({}); + metadataProgressService = { + activeTasks$: activeTasksSubject, + clearTask: vi.fn(), + }; + metadataTaskService = { + deleteTask: vi.fn(() => of(void 0)), + }; + taskService = { + cancelTask: vi.fn(() => of({cancelled: true})), + }; + dialogLauncherService = { + openMetadataReviewDialog: vi.fn(), + }; + messageService = { + add: vi.fn(), + }; + + vi.useFakeTimers(); + + await TestBed.configureTestingModule({ + imports: [MetadataProgressWidgetComponent, getTranslocoModule()], + providers: [ + {provide: MetadataProgressService, useValue: metadataProgressService}, + {provide: MetadataTaskService, useValue: metadataTaskService}, + {provide: TaskService, useValue: taskService}, + {provide: DialogLauncherService, useValue: dialogLauncherService}, + {provide: MessageService, useValue: messageService}, + ], + }).compileComponents(); + + fixture = TestBed.createComponent(MetadataProgressWidgetComponent); + component = fixture.componentInstance; + translocoService = TestBed.inject(TranslocoService); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + it('tracks active tasks from the progress service and marks stalled tasks as errors', () => { + component.ngOnInit(); + + activeTasksSubject.next({[task.taskId]: task}); + expect(component.activeTasks).toEqual({[task.taskId]: task}); + + vi.advanceTimersByTime(60000); + + expect(component.activeTasks[task.taskId]).toMatchObject({ + status: MetadataBatchStatus.ERROR, + message: translocoService.translate('shared.metadataProgress.taskStalled'), + }); + }); + + it('computes progress percentages and tag severity values', () => { + expect(component.getProgressPercent({...task, total: 0})).toBe(0); + expect(component.getProgressPercent({...task, status: MetadataBatchStatus.COMPLETED})).toBe(100); + expect(component.getProgressPercent(task)).toBe(40); + expect(component.getTagSeverity(MetadataBatchStatus.IN_PROGRESS)).toBe('info'); + expect(component.getTagSeverity(MetadataBatchStatus.COMPLETED)).toBe('success'); + expect(component.getTagSeverity(MetadataBatchStatus.ERROR)).toBe('danger'); + expect(component.getTagSeverity(MetadataBatchStatus.CANCELLED)).toBe('warn'); + }); + + it('clears a task through the metadata task API and local progress store', () => { + component.ngOnInit(); + activeTasksSubject.next({[task.taskId]: task}); + + component.clearTask(task.taskId); + + expect(metadataTaskService.deleteTask).toHaveBeenCalledWith(task.taskId); + expect(metadataProgressService.clearTask).toHaveBeenCalledWith(task.taskId); + }); + + it('opens the review dialog for a task', () => { + component.reviewTask(task.taskId); + + expect(dialogLauncherService.openMetadataReviewDialog).toHaveBeenCalledWith(task.taskId); + }); + + it('marks tasks cancelled and shows a success toast when cancellation is scheduled', () => { + component.activeTasks = {[task.taskId]: task}; + + component.cancelTask(task.taskId); + + expect(taskService.cancelTask).toHaveBeenCalledWith(task.taskId); + expect(component.activeTasks[task.taskId]).toMatchObject({ + status: MetadataBatchStatus.CANCELLED, + message: translocoService.translate('shared.metadataProgress.taskCancelled'), + }); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: translocoService.translate('shared.metadataProgress.cancellationScheduledSummary'), + detail: translocoService.translate('shared.metadataProgress.cancellationScheduledDetail'), + }); + }); + + it('shows an error toast when cancellation fails', () => { + vi.spyOn(console, 'error').mockImplementation(() => undefined); + taskService.cancelTask.mockReturnValueOnce(throwError(() => new Error('boom'))); + + component.cancelTask(task.taskId); + + expect(console.error).toHaveBeenCalled(); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: translocoService.translate('shared.metadataProgress.cancelFailedSummary'), + detail: translocoService.translate('shared.metadataProgress.cancelFailedDetail'), + }); + }); + + it('returns translated status labels and clears timers on destroy', () => { + component.ngOnInit(); + activeTasksSubject.next({[task.taskId]: task}); + + expect(component.getStatusLabel(MetadataBatchStatus.ERROR)).toBe( + translocoService.translate('shared.metadataProgress.statusError') + ); + + component.ngOnDestroy(); + vi.advanceTimersByTime(60000); + + expect(component.activeTasks[task.taskId]).toEqual(task); + }); +}); diff --git a/frontend/src/app/shared/components/setup/login.guard.spec.ts b/frontend/src/app/shared/components/setup/login.guard.spec.ts new file mode 100644 index 000000000..3e844886a --- /dev/null +++ b/frontend/src/app/shared/components/setup/login.guard.spec.ts @@ -0,0 +1,62 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {Router} from '@angular/router'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {firstValueFrom} from 'rxjs'; + +import {API_CONFIG} from '../../../core/config/api-config'; +import {LoginGuard} from './login.guard'; + +describe('LoginGuard', () => { + const setupStatusUrl = `${API_CONFIG.BASE_URL}/api/v1/setup/status`; + const router = { + navigate: vi.fn(() => Promise.resolve(true)), + }; + + let guard: LoginGuard; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + router.navigate.mockClear(); + + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + {provide: Router, useValue: router}, + LoginGuard, + ] + }); + + guard = TestBed.inject(LoginGuard); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('allows access when setup has already completed', async () => { + const resultPromise = firstValueFrom(guard.canActivate()); + + const request = httpTestingController.expectOne(setupStatusUrl); + request.flush({data: true}); + + await expect(resultPromise).resolves.toBe(true); + expect(router.navigate).not.toHaveBeenCalled(); + }); + + it('redirects to setup when the setup status request fails', async () => { + const resultPromise = firstValueFrom(guard.canActivate()); + + const request = httpTestingController.expectOne(setupStatusUrl); + request.flush('boom', {status: 500, statusText: 'Server Error'}); + + await expect(resultPromise).resolves.toBe(false); + expect(router.navigate).toHaveBeenCalledWith(['/setup']); + }); +}); diff --git a/frontend/src/app/shared/components/setup/setup-guards.spec.ts b/frontend/src/app/shared/components/setup/setup-guards.spec.ts new file mode 100644 index 000000000..9af079ea5 --- /dev/null +++ b/frontend/src/app/shared/components/setup/setup-guards.spec.ts @@ -0,0 +1,114 @@ +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {provideHttpClient} from '@angular/common/http'; +import {TestBed} from '@angular/core/testing'; +import {Router, UrlTree} from '@angular/router'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {firstValueFrom} from 'rxjs'; + +import {API_CONFIG} from '../../../core/config/api-config'; +import {LoginGuard} from './login.guard'; +import {SetupGuard} from './setup.guard'; +import {SetupRedirectGuard} from './setup-redirect.guard'; + +describe('setup and login guards', () => { + const setupStatusUrl = `${API_CONFIG.BASE_URL}/api/v1/setup/status`; + const router = { + createUrlTree: vi.fn((commands: string[]) => ({commands}) as unknown as UrlTree), + navigate: vi.fn(() => Promise.resolve(true)), + }; + + let httpTestingController: HttpTestingController; + let setupGuard: SetupGuard; + let loginGuard: LoginGuard; + let setupRedirectGuard: SetupRedirectGuard; + + beforeEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + router.createUrlTree.mockClear(); + router.navigate.mockClear(); + + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + {provide: Router, useValue: router}, + SetupGuard, + LoginGuard, + SetupRedirectGuard, + ] + }); + + httpTestingController = TestBed.inject(HttpTestingController); + setupGuard = TestBed.inject(SetupGuard); + loginGuard = TestBed.inject(LoginGuard); + setupRedirectGuard = TestBed.inject(SetupRedirectGuard); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('allows setup when the instance is not configured yet', async () => { + const resultPromise = firstValueFrom(setupGuard.canActivate()); + const request = httpTestingController.expectOne(setupStatusUrl); + request.flush({data: false}); + + await expect(resultPromise).resolves.toBe(true); + }); + + it('redirects setup to login when setup is already complete', async () => { + const resultPromise = firstValueFrom(setupGuard.canActivate()); + const request = httpTestingController.expectOne(setupStatusUrl); + request.flush({data: true}); + + await expect(resultPromise).resolves.toEqual({commands: ['/login']}); + expect(router.createUrlTree).toHaveBeenCalledWith(['/login']); + }); + + it('allows login only after setup is complete', async () => { + const resultPromise = firstValueFrom(loginGuard.canActivate()); + const request = httpTestingController.expectOne(setupStatusUrl); + request.flush({data: true}); + + await expect(resultPromise).resolves.toBe(true); + expect(router.navigate).not.toHaveBeenCalled(); + }); + + it('redirects login to setup when setup is incomplete', async () => { + const resultPromise = firstValueFrom(loginGuard.canActivate()); + const request = httpTestingController.expectOne(setupStatusUrl); + request.flush({data: false}); + + await expect(resultPromise).resolves.toBe(false); + expect(router.navigate).toHaveBeenCalledWith(['/setup']); + }); + + it('redirects login to setup when the setup status request fails', async () => { + const resultPromise = firstValueFrom(loginGuard.canActivate()); + const request = httpTestingController.expectOne(setupStatusUrl); + request.flush('boom', {status: 500, statusText: 'Server Error'}); + + await expect(resultPromise).resolves.toBe(false); + expect(router.navigate).toHaveBeenCalledWith(['/setup']); + }); + + it('sends users from the root route to setup when configuration is missing', async () => { + const resultPromise = firstValueFrom(setupRedirectGuard.canActivate()); + const request = httpTestingController.expectOne(setupStatusUrl); + request.flush({data: false}); + + await expect(resultPromise).resolves.toBe(false); + expect(router.navigate).toHaveBeenCalledWith(['/setup']); + }); + + it('sends users from the root route to the dashboard when setup is complete', async () => { + const resultPromise = firstValueFrom(setupRedirectGuard.canActivate()); + const request = httpTestingController.expectOne(setupStatusUrl); + request.flush({data: true}); + + await expect(resultPromise).resolves.toBe(false); + expect(router.navigate).toHaveBeenCalledWith(['/dashboard']); + }); +}); diff --git a/frontend/src/app/shared/components/setup/setup-redirect.guard.spec.ts b/frontend/src/app/shared/components/setup/setup-redirect.guard.spec.ts new file mode 100644 index 000000000..2ee72df47 --- /dev/null +++ b/frontend/src/app/shared/components/setup/setup-redirect.guard.spec.ts @@ -0,0 +1,62 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {Router} from '@angular/router'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {firstValueFrom} from 'rxjs'; + +import {API_CONFIG} from '../../../core/config/api-config'; +import {SetupRedirectGuard} from './setup-redirect.guard'; + +describe('SetupRedirectGuard', () => { + const setupStatusUrl = `${API_CONFIG.BASE_URL}/api/v1/setup/status`; + const router = { + navigate: vi.fn(() => Promise.resolve(true)), + }; + + let guard: SetupRedirectGuard; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + router.navigate.mockClear(); + + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + {provide: Router, useValue: router}, + SetupRedirectGuard, + ] + }); + + guard = TestBed.inject(SetupRedirectGuard); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('sends users to setup when the instance is not configured', async () => { + const resultPromise = firstValueFrom(guard.canActivate()); + + const request = httpTestingController.expectOne(setupStatusUrl); + request.flush({data: false}); + + await expect(resultPromise).resolves.toBe(false); + expect(router.navigate).toHaveBeenCalledWith(['/setup']); + }); + + it('sends users to the dashboard when setup is complete', async () => { + const resultPromise = firstValueFrom(guard.canActivate()); + + const request = httpTestingController.expectOne(setupStatusUrl); + request.flush({data: true}); + + await expect(resultPromise).resolves.toBe(false); + expect(router.navigate).toHaveBeenCalledWith(['/dashboard']); + }); +}); diff --git a/frontend/src/app/shared/components/setup/setup.component.spec.ts b/frontend/src/app/shared/components/setup/setup.component.spec.ts new file mode 100644 index 000000000..faa4ce9de --- /dev/null +++ b/frontend/src/app/shared/components/setup/setup.component.spec.ts @@ -0,0 +1,122 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {Router} from '@angular/router'; +import {of, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {TranslocoService} from '@jsverse/transloco'; + +import {getTranslocoModule} from '../../../core/testing/transloco-testing'; +import {SetupComponent} from './setup.component'; +import {SetupService} from './setup.service'; + +describe('SetupComponent', () => { + let fixture: ComponentFixture; + let component: SetupComponent; + let setupService: {createAdmin: ReturnType}; + let router: {navigate: ReturnType}; + let translocoService: TranslocoService; + + beforeEach(async () => { + setupService = { + createAdmin: vi.fn(() => of(void 0)), + }; + router = { + navigate: vi.fn(() => Promise.resolve(true)), + }; + + vi.useFakeTimers(); + + await TestBed.configureTestingModule({ + imports: [SetupComponent, getTranslocoModule()], + providers: [ + {provide: SetupService, useValue: setupService}, + {provide: Router, useValue: router}, + ], + }).compileComponents(); + + fixture = TestBed.createComponent(SetupComponent); + component = fixture.componentInstance; + translocoService = TestBed.inject(TranslocoService); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + function fillValidForm() { + component.setupForm.setValue({ + name: 'Admin User', + username: 'admin', + email: 'admin@example.com', + password: 'supersecure', + confirmPassword: 'supersecure', + }); + } + + it('refuses to submit when the form is invalid', () => { + component.setupForm.patchValue({ + name: 'Admin User', + username: 'admin', + }); + + component.onSubmit(); + + expect(setupService.createAdmin).not.toHaveBeenCalled(); + expect(component.loading).toBe(false); + }); + + it('submits the admin payload without confirmPassword', () => { + fillValidForm(); + + component.onSubmit(); + + expect(component.loading).toBe(true); + expect(component.error).toBe(null); + expect(setupService.createAdmin).toHaveBeenCalledWith({ + name: 'Admin User', + username: 'admin', + email: 'admin@example.com', + password: 'supersecure', + }); + }); + + it('marks success and redirects to login after the delay', async () => { + fillValidForm(); + + component.onSubmit(); + + expect(component.success).toBe(true); + expect(component.loading).toBe(true); + expect(router.navigate).not.toHaveBeenCalled(); + + vi.advanceTimersByTime(1500); + await Promise.resolve(); + + expect(router.navigate).toHaveBeenCalledWith(['/login']); + }); + + it('surfaces backend error messages and clears loading', () => { + fillValidForm(); + setupService.createAdmin.mockReturnValueOnce( + throwError(() => ({error: {message: 'Setup failed'}})) + ); + + component.onSubmit(); + + expect(component.loading).toBe(false); + expect(component.error).toBe('Setup failed'); + expect(component.success).toBe(false); + }); + + it('uses the translated fallback error when the backend does not provide one', () => { + fillValidForm(); + setupService.createAdmin.mockReturnValueOnce(throwError(() => ({error: {}}))); + + component.onSubmit(); + + expect(component.error).toBe( + translocoService.translate('shared.setup.toast.createFailedDefault') + ); + }); +}); diff --git a/frontend/src/app/shared/components/setup/setup.guard.spec.ts b/frontend/src/app/shared/components/setup/setup.guard.spec.ts new file mode 100644 index 000000000..2208867a2 --- /dev/null +++ b/frontend/src/app/shared/components/setup/setup.guard.spec.ts @@ -0,0 +1,62 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {Router, UrlTree} from '@angular/router'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {firstValueFrom} from 'rxjs'; + +import {API_CONFIG} from '../../../core/config/api-config'; +import {SetupGuard} from './setup.guard'; + +describe('SetupGuard', () => { + const setupStatusUrl = `${API_CONFIG.BASE_URL}/api/v1/setup/status`; + const router = { + createUrlTree: vi.fn((commands: string[]) => ({commands}) as unknown as UrlTree), + }; + + let guard: SetupGuard; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + router.createUrlTree.mockClear(); + + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + {provide: Router, useValue: router}, + SetupGuard, + ] + }); + + guard = TestBed.inject(SetupGuard); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('allows access when setup is still incomplete', async () => { + const resultPromise = firstValueFrom(guard.canActivate()); + + const request = httpTestingController.expectOne(setupStatusUrl); + request.flush({data: false}); + + await expect(resultPromise).resolves.toBe(true); + expect(router.createUrlTree).not.toHaveBeenCalled(); + }); + + it('returns a login redirect tree once setup is complete', async () => { + const resultPromise = firstValueFrom(guard.canActivate()); + + const request = httpTestingController.expectOne(setupStatusUrl); + request.flush({data: true}); + + await expect(resultPromise).resolves.toEqual({commands: ['/login']}); + expect(router.createUrlTree).toHaveBeenCalledWith(['/login']); + }); +}); diff --git a/frontend/src/app/shared/components/setup/setup.service.spec.ts b/frontend/src/app/shared/components/setup/setup.service.spec.ts new file mode 100644 index 000000000..e354a808e --- /dev/null +++ b/frontend/src/app/shared/components/setup/setup.service.spec.ts @@ -0,0 +1,46 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {API_CONFIG} from '../../../core/config/api-config'; +import {SetupService} from './setup.service'; + +describe('SetupService', () => { + const setupUrl = `${API_CONFIG.BASE_URL}/api/v1/setup`; + + let service: SetupService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + SetupService, + ] + }); + + service = TestBed.inject(SetupService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('posts the admin setup payload to the setup endpoint', () => { + service.createAdmin({email: 'admin@example.com', password: 'secret'}).subscribe(); + + const request = httpTestingController.expectOne(setupUrl); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual({ + email: 'admin@example.com', + password: 'secret', + }); + + request.flush(null); + }); +}); diff --git a/frontend/src/app/shared/components/tag/tag.component.spec.ts b/frontend/src/app/shared/components/tag/tag.component.spec.ts new file mode 100644 index 000000000..3be189bb9 --- /dev/null +++ b/frontend/src/app/shared/components/tag/tag.component.spec.ts @@ -0,0 +1,75 @@ +import {Component} from '@angular/core'; +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {beforeEach, describe, expect, it} from 'vitest'; + +import {TagColor, TagComponent, TagSize, TagVariant} from './tag.component'; + +@Component({ + standalone: true, + imports: [TagComponent], + template: ` + + Test + + `, +}) +class TestHostComponent { + color: TagColor = 'primary'; + size: TagSize = 'm'; + variant: TagVariant = 'label'; + rounded = false; + pill = false; + customBgColor = '#112233'; + customTextColor = '#fefefe'; +} + +describe('TagComponent', () => { + let fixture: ComponentFixture; + let host: TestHostComponent; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [TestHostComponent], + }).compileComponents(); + + fixture = TestBed.createComponent(TestHostComponent); + host = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('renders the default color and size classes', () => { + const tag = fixture.nativeElement.querySelector('span') as HTMLSpanElement; + + expect(tag.className).toContain('app-tag'); + expect(tag.className).toContain('app-tag-primary'); + expect(tag.className).toContain('app-tag-m'); + expect(tag.textContent?.trim()).toBe('Test'); + }); + + it('adds pill and rounded classes when those inputs are enabled', () => { + host.variant = 'pill'; + host.rounded = true; + host.pill = true; + fixture.detectChanges(); + + const tag = fixture.nativeElement.querySelector('span') as HTMLSpanElement; + expect(tag.className).toContain('app-tag-variant-pill'); + expect(tag.className).toContain('app-tag-rounded'); + expect(tag.className).toContain('app-tag-pill'); + }); + + it('applies the provided custom colors inline', () => { + const tag = fixture.nativeElement.querySelector('span') as HTMLSpanElement; + + expect(tag.style.backgroundColor).toBe('rgb(17, 34, 51)'); + expect(tag.style.color).toBe('rgb(254, 254, 254)'); + }); +}); diff --git a/frontend/src/app/shared/components/unified-notification-popover/unified-notification-popover-component.spec.ts b/frontend/src/app/shared/components/unified-notification-popover/unified-notification-popover-component.spec.ts new file mode 100644 index 000000000..d0afb8668 --- /dev/null +++ b/frontend/src/app/shared/components/unified-notification-popover/unified-notification-popover-component.spec.ts @@ -0,0 +1,75 @@ +import {BehaviorSubject} from 'rxjs'; +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {BookdropFileService} from '../../../features/bookdrop/service/bookdrop-file.service'; +import {getTranslocoModule} from '../../../core/testing/transloco-testing'; +import {MetadataBatchStatus} from '../../model/metadata-batch-progress.model'; +import {MetadataProgressService} from '../../service/metadata-progress.service'; +import {UnifiedNotificationBoxComponent} from './unified-notification-popover-component'; + +describe('UnifiedNotificationBoxComponent', () => { + let fixture: ComponentFixture; + let component: UnifiedNotificationBoxComponent; + let activeTasks$: BehaviorSubject>; + let hasPendingFiles$: BehaviorSubject; + + beforeEach(async () => { + activeTasks$ = new BehaviorSubject>({}); + hasPendingFiles$ = new BehaviorSubject(false); + + await TestBed.configureTestingModule({ + imports: [UnifiedNotificationBoxComponent, getTranslocoModule()], + providers: [ + { + provide: MetadataProgressService, + useValue: {activeTasks$}, + }, + { + provide: BookdropFileService, + useValue: {hasPendingFiles$}, + }, + ], + }).compileComponents(); + + fixture = TestBed.createComponent(UnifiedNotificationBoxComponent); + component = fixture.componentInstance; + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('reports whether there are metadata tasks to show', () => { + let hasMetadataTasks: boolean | undefined; + component.hasMetadataTasks$.subscribe(value => { + hasMetadataTasks = value; + }); + + expect(hasMetadataTasks).toBe(false); + + activeTasks$.next({ + 'task-1': { + taskId: 'task-1', + completed: 1, + total: 2, + message: 'running', + status: MetadataBatchStatus.IN_PROGRESS, + review: false, + }, + }); + + expect(hasMetadataTasks).toBe(true); + }); + + it('forwards the bookdrop pending-file signal', () => { + let hasPendingFiles: boolean | undefined; + component.hasPendingBookdropFiles$.subscribe(value => { + hasPendingFiles = value; + }); + + expect(hasPendingFiles).toBe(false); + hasPendingFiles$.next(true); + expect(hasPendingFiles).toBe(true); + }); +}); diff --git a/frontend/src/app/shared/constants/reset-progress-type.spec.ts b/frontend/src/app/shared/constants/reset-progress-type.spec.ts new file mode 100644 index 000000000..56c3ef304 --- /dev/null +++ b/frontend/src/app/shared/constants/reset-progress-type.spec.ts @@ -0,0 +1,17 @@ +import {describe, expect, expectTypeOf, it} from 'vitest'; + +import {ResetProgressType, ResetProgressTypes} from './reset-progress-type'; + +describe('reset-progress-type', () => { + it('keeps the backend compatibility alias for the grimmory reset type', () => { + expect(ResetProgressTypes).toEqual({ + KOREADER: 'KOREADER', + GRIMMORY: 'BOOKLORE', + KOBO: 'KOBO' + }); + }); + + it('narrows the union to the exported reset progress values', () => { + expectTypeOf().toEqualTypeOf<'KOREADER' | 'BOOKLORE' | 'KOBO'>(); + }); +}); diff --git a/frontend/src/app/shared/helpers/icon-categories.helper.spec.ts b/frontend/src/app/shared/helpers/icon-categories.helper.spec.ts new file mode 100644 index 000000000..ac70346f6 --- /dev/null +++ b/frontend/src/app/shared/helpers/icon-categories.helper.spec.ts @@ -0,0 +1,15 @@ +import {describe, expect, it} from 'vitest'; + +import {IconCategoriesHelper} from './icon-categories.helper'; + +describe('IconCategoriesHelper', () => { + it('creates a prime icon class list from the static categories', () => { + const icons = IconCategoriesHelper.createIconList(); + + expect(icons[0]).toBe('pi pi-address-book'); + expect(icons.at(-1)).toBe('pi pi-youtube'); + expect(new Set(icons).size).toBe(icons.length); + expect(icons).toContain('pi pi-book'); + expect(icons).toContain('pi pi-shield'); + }); +}); diff --git a/frontend/src/app/shared/layout/api/menuchangeevent.spec.ts b/frontend/src/app/shared/layout/api/menuchangeevent.spec.ts new file mode 100644 index 000000000..f1fd6625a --- /dev/null +++ b/frontend/src/app/shared/layout/api/menuchangeevent.spec.ts @@ -0,0 +1,19 @@ +import {describe, expect, expectTypeOf, it} from 'vitest'; + +import {MenuChangeEvent} from './menuchangeevent'; + +describe('menuchangeevent', () => { + it('supports route-backed menu change events', () => { + const event: MenuChangeEvent = { + key: 'settings', + routeEvent: true + }; + + expect(event.key).toBe('settings'); + expect(event.routeEvent).toBe(true); + }); + + it('keeps routeEvent optional', () => { + expectTypeOf().toEqualTypeOf(); + }); +}); diff --git a/frontend/src/app/shared/layout/component/layout-main/app.layout.component.spec.ts b/frontend/src/app/shared/layout/component/layout-main/app.layout.component.spec.ts new file mode 100644 index 000000000..de08cf528 --- /dev/null +++ b/frontend/src/app/shared/layout/component/layout-main/app.layout.component.spec.ts @@ -0,0 +1,16 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Honest layout coverage needs a host harness for router events, renderer +// listeners, overlay subscriptions, body-scroll mutation, and view-child/sidebar interactions. +// In its current shape the component is mostly runtime orchestration around global DOM listeners. +describe.skip('AppLayoutComponent', () => { + it('needs a router-overlay seam to verify menu hiding on navigation and overlay clicks', () => { + // TODO(seam): Cover outside-click detection and overlay subscription behavior after router + // events and renderer listeners are exposed behind a testable boundary. + }); + + it('needs a document-style seam to verify sidebar width initialization and body scroll toggling', () => { + // TODO(seam): Cover local-storage width hydration and blocked-scroll lifecycle once global + // document mutations can be asserted without brittle DOM listener wiring. + }); +}); diff --git a/frontend/src/app/shared/layout/component/layout-main/service/app.layout.service.spec.ts b/frontend/src/app/shared/layout/component/layout-main/service/app.layout.service.spec.ts new file mode 100644 index 000000000..869cd2d05 --- /dev/null +++ b/frontend/src/app/shared/layout/component/layout-main/service/app.layout.service.spec.ts @@ -0,0 +1,93 @@ +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {LayoutService} from './app.layout.service'; + +describe('LayoutService', () => { + let service: LayoutService; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [LayoutService], + }); + + service = TestBed.inject(LayoutService); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('detects when the configured theme style changes', () => { + expect(service.updateStyle(service.config())).toBe(false); + + service.config.set({ + ...service.config(), + theme: 'lara-dark-indigo', + }); + + expect(service.updateStyle(service.config())).toBe(true); + }); + + it('toggles the overlay menu and emits overlay-open notifications on desktop', () => { + let overlayOpenCount = 0; + service.config.set({ + ...service.config(), + menuMode: 'overlay', + }); + service.overlayOpen$.subscribe(() => { + overlayOpenCount += 1; + }); + + Object.defineProperty(window, 'innerWidth', {configurable: true, value: 1280}); + service.onMenuToggle(); + + expect(service.state.overlayMenuActive).toBe(true); + expect(service.state.staticMenuDesktopInactive).toBe(true); + expect(overlayOpenCount).toBe(1); + }); + + it('toggles the mobile static menu and emits overlay-open notifications on small screens', () => { + let overlayOpenCount = 0; + service.overlayOpen$.subscribe(() => { + overlayOpenCount += 1; + }); + + Object.defineProperty(window, 'innerWidth', {configurable: true, value: 768}); + service.onMenuToggle(); + + expect(service.state.staticMenuMobileActive).toBe(true); + expect(overlayOpenCount).toBe(1); + }); + + it('derives the replacement theme href from the current config', () => { + const replaceThemeLinkSpy = vi.spyOn(service, 'replaceThemeLink').mockImplementation(() => undefined); + const themeLink = document.createElement('link'); + themeLink.id = 'theme-css'; + themeLink.setAttribute('href', '/themes/lara-light-indigo/theme-light/theme.css'); + document.body.appendChild(themeLink); + + service._config = { + ...service._config, + theme: 'lara-light-indigo', + colorScheme: 'light', + }; + service.config.set({ + ...service.config(), + theme: 'lara-dark-indigo', + colorScheme: 'dark', + }); + + service.changeTheme(); + + expect(replaceThemeLinkSpy).toHaveBeenCalledWith('/themes/lara-dark-indigo/theme-dark/theme.css'); + themeLink.remove(); + }); + + it('updates the document root font size when the scale changes', () => { + service.changeScale(18); + + expect(document.documentElement.style.fontSize).toBe('18px'); + }); +}); diff --git a/frontend/src/app/shared/layout/component/layout-main/service/app.layout.service.ts b/frontend/src/app/shared/layout/component/layout-main/service/app.layout.service.ts index e8c5a5ab4..1c2542ee9 100644 --- a/frontend/src/app/shared/layout/component/layout-main/service/app.layout.service.ts +++ b/frontend/src/app/shared/layout/component/layout-main/service/app.layout.service.ts @@ -104,9 +104,9 @@ export class LayoutService { .split('/') .map((el) => el == this._config.theme - ? (el = config.theme) + ? config.theme : el == `theme-${this._config.colorScheme}` - ? (el = `theme-${config.colorScheme}`) + ? `theme-${config.colorScheme}` : el ) .join('/'); diff --git a/frontend/src/app/shared/layout/component/layout-menu/app.menu.component.spec.ts b/frontend/src/app/shared/layout/component/layout-menu/app.menu.component.spec.ts new file mode 100644 index 000000000..d09bf1f24 --- /dev/null +++ b/frontend/src/app/shared/layout/component/layout-menu/app.menu.component.spec.ts @@ -0,0 +1,17 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real menu coverage needs coordinated signals for libraries, shelves, +// magic shelves, authors, books, user permissions, translation changes, and version/dialog +// behavior. The component is a large computed-menu assembler, and a low-value shallow spec would +// not honestly verify the menu trees that matter. +describe.skip('AppMenuComponent', () => { + it('needs a menu-data seam to verify computed home/library/shelf/magic-shelf menu trees', () => { + // TODO(seam): Cover computed menu composition once the dependent signals/services can be + // driven through a stable test harness rather than an all-up runtime mock graph. + }); + + it('needs a version-dialog and local-storage seam to verify side effects around dialogs and sidebar sizing', () => { + // TODO(seam): Cover version dialog and sidebar width behavior after those side effects are + // exposed behind a narrower facade. + }); +}); diff --git a/frontend/src/app/shared/layout/component/layout-menu/app.menuitem.component.spec.ts b/frontend/src/app/shared/layout/component/layout-menu/app.menuitem.component.spec.ts new file mode 100644 index 000000000..01dcbad60 --- /dev/null +++ b/frontend/src/app/shared/layout/component/layout-menu/app.menuitem.component.spec.ts @@ -0,0 +1,16 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): This menu item coordinates router state, menu-service broadcasts, user +// permission effects, dialog launchers, nested expansion state, and link/view-child behavior. +// Useful coverage needs a purpose-built menu host seam, not a brittle isolated mock tangle. +describe.skip('AppMenuitemComponent', () => { + it('needs a menu-service and router seam to verify active-state propagation and route activation', () => { + // TODO(seam): Cover route-driven activation, menu broadcasts, and nested expansion after the + // component can be exercised inside a stable menu host harness. + }); + + it('needs a dialog/link seam to verify openDialog, triggerLink, and icon/count formatting behavior', () => { + // TODO(seam): Cover command, dialog, and link behavior once those side effects are surfaced + // behind a narrower, test-friendly contract. + }); +}); diff --git a/frontend/src/app/shared/layout/component/layout-menu/service/app.menu.service.spec.ts b/frontend/src/app/shared/layout/component/layout-menu/service/app.menu.service.spec.ts new file mode 100644 index 000000000..f7f8843bb --- /dev/null +++ b/frontend/src/app/shared/layout/component/layout-menu/service/app.menu.service.spec.ts @@ -0,0 +1,23 @@ +import {describe, expect, it} from 'vitest'; + +import {MenuService} from './app.menu.service'; + +describe('MenuService', () => { + it('broadcasts menu state changes and reset events', () => { + const service = new MenuService(); + const menuEvents: unknown[] = []; + const resets: unknown[] = []; + + const menuSubscription = service.menuSource$.subscribe(event => menuEvents.push(event)); + const resetSubscription = service.resetSource$.subscribe(event => resets.push(event)); + + service.onMenuStateChange({key: 'settings'}); + service.reset(); + + expect(menuEvents).toEqual([{key: 'settings'}]); + expect(resets).toEqual([true]); + + menuSubscription.unsubscribe(); + resetSubscription.unsubscribe(); + }); +}); diff --git a/frontend/src/app/shared/layout/component/layout-menu/version-changelog-dialog/version-changelog-dialog.component.spec.ts b/frontend/src/app/shared/layout/component/layout-menu/version-changelog-dialog/version-changelog-dialog.component.spec.ts new file mode 100644 index 000000000..6b678d6d4 --- /dev/null +++ b/frontend/src/app/shared/layout/component/layout-menu/version-changelog-dialog/version-changelog-dialog.component.spec.ts @@ -0,0 +1,72 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {of, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {DynamicDialogRef} from 'primeng/dynamicdialog'; + +import {getTranslocoModule} from '../../../../../core/testing/transloco-testing'; +import {VersionService} from '../../../../service/version.service'; +import {VersionChangelogDialogComponent} from './version-changelog-dialog.component'; + +describe('VersionChangelogDialogComponent', () => { + let fixture: ComponentFixture; + let component: VersionChangelogDialogComponent; + let versionService: {getChangelog: ReturnType}; + + beforeEach(async () => { + versionService = { + getChangelog: vi.fn(() => of([ + { + version: '1.2.3', + name: 'Stable', + changelog: '## Added\n- New feature', + url: 'https://example.com/releases/1.2.3', + publishedAt: '2026-03-26T00:00:00Z', + }, + ])), + }; + + await TestBed.configureTestingModule({ + imports: [VersionChangelogDialogComponent, getTranslocoModule()], + providers: [ + {provide: VersionService, useValue: versionService}, + {provide: DynamicDialogRef, useValue: {close: vi.fn()}}, + ], + }).compileComponents(); + + fixture = TestBed.createComponent(VersionChangelogDialogComponent); + component = fixture.componentInstance; + }); + + afterEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + it('loads the changelog on init and clears the loading state', () => { + component.ngOnInit(); + + expect(versionService.getChangelog).toHaveBeenCalled(); + expect(component.changelog).toHaveLength(1); + expect(component.loading).toBe(false); + }); + + it('clears the loading state when the changelog request fails', () => { + versionService.getChangelog.mockReturnValueOnce( + throwError(() => new Error('failed')) + ); + + component.ngOnInit(); + + expect(component.changelog).toEqual([]); + expect(component.loading).toBe(false); + }); + + it('converts markdown to sanitized HTML and normalizes headings to h3', () => { + const html = component.markdownToHtml('## Heading\n\nSafe'); + + expect(html).toContain(''); + expect(html).toContain('Safe'); + }); +}); diff --git a/frontend/src/app/shared/layout/component/layout-sidebar/app.sidebar.component.spec.ts b/frontend/src/app/shared/layout/component/layout-sidebar/app.sidebar.component.spec.ts new file mode 100644 index 000000000..ce0d91955 --- /dev/null +++ b/frontend/src/app/shared/layout/component/layout-sidebar/app.sidebar.component.spec.ts @@ -0,0 +1,11 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): This component is effectively a thin runtime bridge to layout state plus +// a nested menu tree. A worthwhile spec should be written together with a host/layout seam rather +// than as an empty shell assertion. +describe.skip('AppSidebarComponent', () => { + it('needs a layout host seam to verify sidebar/menu integration without shallow shell noise', () => { + // TODO(seam): Cover layout state and nested menu rendering once the sidebar is exercised + // through the same host harness that will be needed for layout/menu behavior. + }); +}); diff --git a/frontend/src/app/shared/layout/component/layout-topbar/app.topbar.component.spec.ts b/frontend/src/app/shared/layout/component/layout-topbar/app.topbar.component.spec.ts new file mode 100644 index 000000000..20cca31f1 --- /dev/null +++ b/frontend/src/app/shared/layout/component/layout-topbar/app.topbar.component.spec.ts @@ -0,0 +1,17 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real topbar coverage needs a dedicated host harness for view queries, +// timer-driven pulse behavior, router navigation, auth/logout, user-permission signals, +// metadata/bookdrop streams, menu overlays, and transloco language switching. In the current +// shape those concerns are fused tightly enough that a shallow spec would be noisy and dishonest. +describe.skip('AppTopBarComponent', () => { + it('needs a host-view seam to verify menu visibility, pulse state, and notification/task aggregation', () => { + // TODO(seam): Cover timer-driven pulse resets, task counts, and bookdrop visibility after + // the component exposes a narrower facade over its view and timer dependencies. + }); + + it('needs a navigation and language seam to verify route actions and active language switching', () => { + // TODO(seam): Cover router commands, stats menu composition, and localStorage language writes + // once those side effects can be driven without mocking the entire topbar runtime. + }); +}); diff --git a/frontend/src/app/shared/layout/component/theme-configurator/background-upload.service.spec.ts b/frontend/src/app/shared/layout/component/theme-configurator/background-upload.service.spec.ts new file mode 100644 index 000000000..e07065816 --- /dev/null +++ b/frontend/src/app/shared/layout/component/theme-configurator/background-upload.service.spec.ts @@ -0,0 +1,66 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {BackgroundUploadService} from './background-upload.service'; + +describe('BackgroundUploadService', () => { + let service: BackgroundUploadService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + BackgroundUploadService, + ], + }); + + service = TestBed.inject(BackgroundUploadService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('uploads a file as multipart form data and maps the returned URL', () => { + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined); + const file = new File(['image-bytes'], 'background.png', {type: 'image/png'}); + let result: string | undefined; + + service.uploadFile(file).subscribe(value => { + result = value; + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/background/upload')); + expect(request.request.method).toBe('POST'); + expect(request.request.body instanceof FormData).toBe(true); + expect((request.request.body as FormData).get('file')).toBe(file); + request.flush({url: 'https://example.test/background.png'}); + + expect(result).toBe('https://example.test/background.png'); + expect(logSpy).toHaveBeenCalled(); + }); + + it('uploads a background URL and maps the returned URL', () => { + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined); + let result: string | undefined; + + service.uploadUrl('https://example.test/source.jpg').subscribe(value => { + result = value; + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/background/url')); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual({url: 'https://example.test/source.jpg'}); + request.flush({url: 'https://example.test/normalized.jpg'}); + + expect(result).toBe('https://example.test/normalized.jpg'); + expect(logSpy).toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/app/shared/layout/component/theme-configurator/favicon-service.spec.ts b/frontend/src/app/shared/layout/component/theme-configurator/favicon-service.spec.ts new file mode 100644 index 000000000..aafe491d2 --- /dev/null +++ b/frontend/src/app/shared/layout/component/theme-configurator/favicon-service.spec.ts @@ -0,0 +1,40 @@ +import {describe, expect, it, vi} from 'vitest'; + +import {FaviconService} from './favicon-service'; + +describe('FaviconService', () => { + it('updates an existing favicon link with a generated SVG URL', () => { + const favicon = {type: '', href: ''} as HTMLLinkElement; + const querySelectorSpy = vi.spyOn(document, 'querySelector').mockReturnValue(favicon); + const createObjectUrlSpy = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:favicon'); + + const service = new FaviconService(); + service.updateFavicon('#123456'); + + expect(querySelectorSpy).toHaveBeenCalledWith("link[rel*='icon']"); + expect(createObjectUrlSpy).toHaveBeenCalledOnce(); + expect(favicon.type).toBe('image/svg+xml'); + expect(favicon.href).toBe('blob:favicon'); + }); + + it('creates and appends a favicon link when one does not already exist', () => { + const appended: HTMLLinkElement[] = []; + const favicon = {rel: '', type: '', href: ''} as HTMLLinkElement; + + vi.spyOn(document, 'querySelector').mockReturnValue(null); + vi.spyOn(document, 'createElement').mockReturnValue(favicon); + vi.spyOn(document.head, 'appendChild').mockImplementation(node => { + appended.push(node as HTMLLinkElement); + return node; + }); + vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:new-favicon'); + + const service = new FaviconService(); + service.updateFavicon('#abcdef'); + + expect(appended).toEqual([favicon]); + expect(favicon.rel).toBe('icon'); + expect(favicon.type).toBe('image/svg+xml'); + expect(favicon.href).toBe('blob:new-favicon'); + }); +}); diff --git a/frontend/src/app/shared/layout/component/theme-configurator/theme-configurator.component.spec.ts b/frontend/src/app/shared/layout/component/theme-configurator/theme-configurator.component.spec.ts new file mode 100644 index 000000000..409bef286 --- /dev/null +++ b/frontend/src/app/shared/layout/component/theme-configurator/theme-configurator.component.spec.ts @@ -0,0 +1,17 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs a stable app-config signal seam plus favicon +// side-effect interception. The component is mostly computed/effect wiring over `AppConfigService` +// state, palette tokens, and `FaviconService`, so a useful spec should validate those reactions +// without reaching through private signal internals. +describe.skip('ThemeConfiguratorComponent', () => { + it('needs an app-config seam to verify selected palette derivation and color updates', () => { + // TODO(seam): Cover computed primary/surface selections and updateColors state writes once + // the config signal can be driven through a stable public harness. + }); + + it('needs a favicon side-effect seam to verify palette-to-favicon synchronization', () => { + // TODO(seam): Cover favicon updates after exposing a testable effect boundary around the + // config-driven favicon sync. + }); +}); diff --git a/frontend/src/app/shared/layout/component/theme-configurator/upload-dialog/upload-dialog.component.spec.ts b/frontend/src/app/shared/layout/component/theme-configurator/upload-dialog/upload-dialog.component.spec.ts new file mode 100644 index 000000000..fffa4d157 --- /dev/null +++ b/frontend/src/app/shared/layout/component/theme-configurator/upload-dialog/upload-dialog.component.spec.ts @@ -0,0 +1,125 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {of, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {DynamicDialogRef} from 'primeng/dynamicdialog'; +import {TranslocoService} from '@jsverse/transloco'; + +import {getTranslocoModule} from '../../../../../core/testing/transloco-testing'; +import {BackgroundUploadService} from '../background-upload.service'; +import {UploadDialogComponent} from './upload-dialog.component'; + +describe('UploadDialogComponent', () => { + let fixture: ComponentFixture; + let component: UploadDialogComponent; + let dialogRef: {close: ReturnType}; + let backgroundUploadService: { + uploadFile: ReturnType; + uploadUrl: ReturnType; + }; + let translocoService: TranslocoService; + + beforeEach(async () => { + dialogRef = { + close: vi.fn(), + }; + backgroundUploadService = { + uploadFile: vi.fn(() => of('https://example.com/uploaded.png')), + uploadUrl: vi.fn(() => of('https://example.com/from-url.png')), + }; + + await TestBed.configureTestingModule({ + imports: [UploadDialogComponent, getTranslocoModule()], + providers: [ + {provide: DynamicDialogRef, useValue: dialogRef}, + {provide: BackgroundUploadService, useValue: backgroundUploadService}, + ], + }).compileComponents(); + + fixture = TestBed.createComponent(UploadDialogComponent); + component = fixture.componentInstance; + translocoService = TestBed.inject(TranslocoService); + }); + + afterEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + }); + + it('stores the selected file and clears the URL field', () => { + const file = new File(['image'], 'cover.png', {type: 'image/png'}); + const event = { + target: { + files: [file], + }, + } as unknown as Event; + component.uploadImageUrl = 'https://example.com/old.png'; + + component.onFileSelected(event); + + expect(component.uploadFile).toBe(file); + expect(component.uploadImageUrl).toBe(''); + }); + + it('requires either a file or a URL before uploading', () => { + component.submit(); + + expect(component.uploadError).toBe( + translocoService.translate('layout.uploadDialog.errorNoInput') + ); + expect(backgroundUploadService.uploadFile).not.toHaveBeenCalled(); + expect(backgroundUploadService.uploadUrl).not.toHaveBeenCalled(); + }); + + it('uploads a selected file and closes the dialog with the returned URL', () => { + const file = new File(['image'], 'cover.png', {type: 'image/png'}); + component.uploadFile = file; + + component.submit(); + + expect(backgroundUploadService.uploadFile).toHaveBeenCalledWith(file); + expect(dialogRef.close).toHaveBeenCalledWith({ + imageUrl: 'https://example.com/uploaded.png', + }); + }); + + it('uploads a trimmed URL and closes the dialog with the returned value', () => { + component.uploadImageUrl = ' https://example.com/bg.png '; + + component.submit(); + + expect(backgroundUploadService.uploadUrl).toHaveBeenCalledWith('https://example.com/bg.png'); + expect(dialogRef.close).toHaveBeenCalledWith({ + imageUrl: 'https://example.com/from-url.png', + }); + }); + + it('shows an error when the upload succeeds without returning an image URL', () => { + backgroundUploadService.uploadUrl.mockReturnValueOnce(of('')); + component.uploadImageUrl = 'https://example.com/bg.png'; + + component.submit(); + + expect(component.uploadError).toBe('Failed to upload image.'); + expect(dialogRef.close).not.toHaveBeenCalled(); + }); + + it('shows a generic upload error when the upload request fails', () => { + vi.spyOn(console, 'error').mockImplementation(() => undefined); + backgroundUploadService.uploadFile.mockReturnValueOnce( + throwError(() => new Error('boom')) + ); + component.uploadFile = new File(['image'], 'cover.png', {type: 'image/png'}); + + component.submit(); + + expect(component.uploadError).toBe('Upload failed. Please try again.'); + expect(console.error).toHaveBeenCalled(); + expect(dialogRef.close).not.toHaveBeenCalled(); + }); + + it('closes the dialog when cancel is clicked', () => { + component.cancel(); + + expect(dialogRef.close).toHaveBeenCalledWith(); + }); +}); diff --git a/frontend/src/app/shared/layout/component/theme-palette-extend.spec.ts b/frontend/src/app/shared/layout/component/theme-palette-extend.spec.ts new file mode 100644 index 000000000..32ec54c3c --- /dev/null +++ b/frontend/src/app/shared/layout/component/theme-palette-extend.spec.ts @@ -0,0 +1,16 @@ +import Aura from '@primeuix/themes/aura'; +import {describe, expect, it} from 'vitest'; + +import ExtendedAura from './theme-palette-extend'; + +describe('theme-palette-extend', () => { + it('extends Aura with the custom primitive palettes', () => { + const primitive = Aura.primitive as Record>; + + expect(ExtendedAura).toBe(Aura); + expect(primitive).toBeTruthy(); + expect(primitive['coralSunset']['500']).toBe('#ef7550'); + expect(primitive['skyBlue']['700']).toBe('#2e88e6'); + expect(primitive['dustyNeutral']['950']).toBe('#2f2821'); + }); +}); diff --git a/frontend/src/app/shared/metadata/embeddable-fields.config.spec.ts b/frontend/src/app/shared/metadata/embeddable-fields.config.spec.ts new file mode 100644 index 000000000..d18067bf8 --- /dev/null +++ b/frontend/src/app/shared/metadata/embeddable-fields.config.spec.ts @@ -0,0 +1,22 @@ +import {describe, expect, it} from 'vitest'; + +import {hasMetadataWriter, isFieldEmbeddable} from './embeddable-fields.config'; + +describe('embeddable-fields.config', () => { + it('reports writer support only for embeddable book types', () => { + expect(hasMetadataWriter('EPUB')).toBe(true); + expect(hasMetadataWriter('PDF')).toBe(true); + expect(hasMetadataWriter('CBX')).toBe(true); + expect(hasMetadataWriter('AUDIOBOOK')).toBe(true); + expect(hasMetadataWriter('FB2')).toBe(false); + expect(hasMetadataWriter(undefined)).toBe(false); + }); + + it('checks embeddable field membership by book type', () => { + expect(isFieldEmbeddable('EPUB', 'title')).toBe(true); + expect(isFieldEmbeddable('EPUB', 'narrator')).toBe(false); + expect(isFieldEmbeddable('AUDIOBOOK', 'narrator')).toBe(true); + expect(isFieldEmbeddable('CBX', 'comicIssueNumber')).toBe(true); + expect(isFieldEmbeddable(undefined, 'title')).toBe(false); + }); +}); diff --git a/frontend/src/app/shared/metadata/index.spec.ts b/frontend/src/app/shared/metadata/index.spec.ts new file mode 100644 index 000000000..a2dc07d43 --- /dev/null +++ b/frontend/src/app/shared/metadata/index.spec.ts @@ -0,0 +1,15 @@ +import {describe, expect, it} from 'vitest'; + +import * as metadataIndex from './index'; +import {getTopFields} from './metadata-field.config'; +import {hasMetadataWriter} from './embeddable-fields.config'; + +describe('shared metadata index', () => { + it('re-exports metadata field helpers', () => { + expect(metadataIndex.getTopFields).toBe(getTopFields); + }); + + it('re-exports embeddable field helpers', () => { + expect(metadataIndex.hasMetadataWriter).toBe(hasMetadataWriter); + }); +}); diff --git a/frontend/src/app/shared/metadata/metadata-field.config.spec.ts b/frontend/src/app/shared/metadata/metadata-field.config.spec.ts new file mode 100644 index 000000000..f6b6a69f9 --- /dev/null +++ b/frontend/src/app/shared/metadata/metadata-field.config.spec.ts @@ -0,0 +1,74 @@ +import {describe, expect, it} from 'vitest'; + +import { + ALL_COMIC_METADATA_FIELDS, + ALL_METADATA_FIELDS, + COMIC_FORM_TO_MODEL_LOCK, + getArrayFields, + getBookDetailsFields, + getBottomFields, + getProviderFields, + getSeriesFields, + getTextareaFields, + getTopFields +} from './metadata-field.config'; + +describe('metadata-field.config', () => { + it('exposes stable grouped field selectors', () => { + expect(getTopFields().map((field) => field.controlName)).toEqual([ + 'title', + 'subtitle', + 'publisher', + 'publishedDate' + ]); + expect(getSeriesFields().map((field) => field.controlName)).toEqual([ + 'seriesName', + 'seriesNumber', + 'seriesTotal' + ]); + expect(getBookDetailsFields().map((field) => field.controlName)).toEqual([ + 'language', + 'isbn10', + 'isbn13', + 'pageCount' + ]); + }); + + it('splits array and textarea metadata fields correctly', () => { + expect(getArrayFields().map((field) => field.controlName)).toEqual(['authors', 'categories', 'moods', 'tags']); + expect(getTextareaFields().map((field) => field.controlName)).toEqual(['description']); + }); + + it('filters provider-backed fields when provider flags are supplied', () => { + const enabledFields = { + googleId: true, + asin: false, + amazonRating: false, + amazonReviewCount: false, + goodreadsId: false, + goodreadsRating: false, + goodreadsReviewCount: false, + hardcoverId: false, + hardcoverBookId: false, + hardcoverRating: false, + hardcoverReviewCount: false, + comicvineId: false, + lubimyczytacId: false, + lubimyczytacRating: false, + ranobedbId: false, + ranobedbRating: false, + audibleId: false, + audibleRating: false, + audibleReviewCount: false + }; + + expect(getProviderFields(enabledFields).map((field) => field.controlName)).toEqual(['googleId']); + expect(getBottomFields(enabledFields).some((field) => field.controlName === 'googleId')).toBe(true); + }); + + it('keeps comic metadata fields and lock mappings aligned', () => { + expect(ALL_COMIC_METADATA_FIELDS.length).toBeGreaterThan(0); + expect(COMIC_FORM_TO_MODEL_LOCK['comicIssueNumberLocked']).toBe('issueNumberLocked'); + expect(ALL_METADATA_FIELDS.some((field) => field.controlName === 'title')).toBe(true); + }); +}); diff --git a/frontend/src/app/shared/metadata/metadata-form.builder.spec.ts b/frontend/src/app/shared/metadata/metadata-form.builder.spec.ts new file mode 100644 index 000000000..8537ee92e --- /dev/null +++ b/frontend/src/app/shared/metadata/metadata-form.builder.spec.ts @@ -0,0 +1,87 @@ +import {FormControl, FormGroup} from '@angular/forms'; +import {describe, expect, it} from 'vitest'; + +import {MetadataFormBuilder} from './metadata-form.builder'; + +describe('MetadataFormBuilder', () => { + const builder = new MetadataFormBuilder(); + + it('builds controls with defaults for requested, audiobook, comic, and cover fields', () => { + const form = builder.buildForm(true, [ + {label: 'Title', controlName: 'title', lockedKey: 'titleLocked', fetchedKey: 'title', type: 'string'}, + {label: 'Authors', controlName: 'authors', lockedKey: 'authorsLocked', fetchedKey: 'authors', type: 'array'}, + {label: 'Series #', controlName: 'seriesNumber', lockedKey: 'seriesNumberLocked', fetchedKey: 'seriesNumber', type: 'number'}, + ]); + + expect(form.get('title')?.value).toBe(''); + expect(form.get('authors')?.value).toEqual([]); + expect(form.get('seriesNumber')?.value).toBeNull(); + expect(form.get('titleLocked')?.value).toBe(false); + expect(form.get('narrator')?.value).toBe(''); + expect(form.get('abridged')?.value).toBeNull(); + expect(form.get('comicIssueNumber')?.value).toBe(''); + expect(form.get('comicCharacters')?.value).toEqual([]); + expect(form.get('thumbnailUrl')?.value).toBe(''); + expect(form.get('coverLocked')?.value).toBe(false); + expect(form.get('audiobookCoverLocked')?.value).toBe(false); + }); + + it('omits locked controls when the caller disables them', () => { + const form = builder.buildForm(false, [ + {label: 'Title', controlName: 'title', lockedKey: 'titleLocked', fetchedKey: 'title', type: 'string'}, + ]); + + expect(form.get('title')).toBeTruthy(); + expect(form.get('titleLocked')).toBeNull(); + expect(form.get('coverLocked')).toBeNull(); + expect(form.get('audiobookCoverLocked')).toBeNull(); + }); + + it('applies lock states after re-enabling unlocked controls first', () => { + const form = new FormGroup({ + title: new FormControl('Title'), + titleLocked: new FormControl(false), + authors: new FormControl(['A']), + authorsLocked: new FormControl(false), + narrator: new FormControl('Narrator'), + narratorLocked: new FormControl(false), + comicIssueNumber: new FormControl('7'), + comicIssueNumberLocked: new FormControl(false), + }); + + form.get('title')?.disable(); + form.get('authors')?.disable(); + + builder.applyLockStates(form, { + titleLocked: true, + narratorLocked: true, + comicIssueNumberLocked: false, + }); + + expect(form.get('title')?.disabled).toBe(true); + expect(form.get('authors')?.enabled).toBe(true); + expect(form.get('narrator')?.disabled).toBe(true); + expect(form.get('comicIssueNumber')?.enabled).toBe(true); + }); + + it('toggles all locked fields and matching control enabled state together', () => { + const form = new FormGroup({ + title: new FormControl('Title'), + titleLocked: new FormControl(false), + authors: new FormControl(['A']), + authorsLocked: new FormControl(false), + }); + + builder.setAllFieldsLocked(form, true); + expect(form.get('titleLocked')?.value).toBe(true); + expect(form.get('authorsLocked')?.value).toBe(true); + expect(form.get('title')?.disabled).toBe(true); + expect(form.get('authors')?.disabled).toBe(true); + + builder.setAllFieldsLocked(form, false); + expect(form.get('titleLocked')?.value).toBe(false); + expect(form.get('authorsLocked')?.value).toBe(false); + expect(form.get('title')?.enabled).toBe(true); + expect(form.get('authors')?.enabled).toBe(true); + }); +}); diff --git a/frontend/src/app/shared/metadata/metadata-utils.service.spec.ts b/frontend/src/app/shared/metadata/metadata-utils.service.spec.ts new file mode 100644 index 000000000..f68ad88c0 --- /dev/null +++ b/frontend/src/app/shared/metadata/metadata-utils.service.spec.ts @@ -0,0 +1,157 @@ +import {FormControl, FormGroup} from '@angular/forms'; +import {describe, expect, it, vi} from 'vitest'; + +import {BookMetadata} from '../../features/book/model/book.model'; +import {MetadataUtilsService} from './metadata-utils.service'; + +describe('MetadataUtilsService', () => { + const service = new MetadataUtilsService(); + + function createForm(): FormGroup { + return new FormGroup({ + title: new FormControl(''), + titleLocked: new FormControl(false), + authors: new FormControl([]), + authorsLocked: new FormControl(false), + seriesName: new FormControl('Existing Series'), + seriesNameLocked: new FormControl(true), + pageCount: new FormControl(null), + pageCountLocked: new FormControl(false), + description: new FormControl(''), + descriptionLocked: new FormControl(false), + }); + } + + it('copies a non-empty fetched field into the form and marks it as copied', () => { + const form = createForm(); + const copiedFields: Record = {}; + const metadata = {title: 'Hyperion'} as BookMetadata; + + const copied = service.copyFieldToForm('title', metadata, form, copiedFields); + + expect(copied).toBe(true); + expect(form.get('title')?.value).toBe('Hyperion'); + expect(copiedFields['title']).toBe(true); + }); + + it('does not copy empty fetched values into the form', () => { + const form = createForm(); + const copiedFields: Record = {}; + const metadata = {title: ''} as BookMetadata; + + const copied = service.copyFieldToForm('title', metadata, form, copiedFields); + + expect(copied).toBe(false); + expect(form.get('title')?.value).toBe(''); + expect(copiedFields['title']).toBeUndefined(); + }); + + it('copies only unlocked empty fields that have fetched values', () => { + const form = createForm(); + const copyCallback = vi.fn(); + const metadata = { + title: 'Hyperion', + authors: ['Dan Simmons'], + seriesName: 'Should Stay Locked', + pageCount: null, + } as BookMetadata; + + service.copyMissingFields(metadata, form, {}, copyCallback); + + expect(copyCallback).toHaveBeenCalledTimes(2); + expect(copyCallback).toHaveBeenCalledWith('title'); + expect(copyCallback).toHaveBeenCalledWith('authors'); + }); + + it('copies all unlocked non-empty fields except excluded ones', () => { + const form = createForm(); + const copyCallback = vi.fn(); + const metadata = { + title: 'Hyperion', + authors: ['Dan Simmons'], + seriesName: 'Locked Series', + thumbnailUrl: 'https://example.test/cover.jpg', + } as BookMetadata; + + service.copyAllFields(metadata, form, copyCallback); + + expect(copyCallback).toHaveBeenCalledTimes(2); + expect(copyCallback).toHaveBeenCalledWith('title'); + expect(copyCallback).toHaveBeenCalledWith('authors'); + }); + + it('detects empty values consistently', () => { + expect(service.isValueEmpty(null)).toBe(true); + expect(service.isValueEmpty(undefined)).toBe(true); + expect(service.isValueEmpty('')).toBe(true); + expect(service.isValueEmpty([])).toBe(true); + expect(service.isValueEmpty(['value'])).toBe(false); + expect(service.isValueEmpty('value')).toBe(false); + }); + + it('normalizes arrays for comparison without caring about order', () => { + expect(service.areFieldsEqual(['b', 'a'], ['a', 'b'])).toBe(true); + expect(service.areFieldsEqual('3', 3)).toBe(true); + expect(service.areFieldsEqual(['a'], ['a', 'b'])).toBe(false); + }); + + it('tracks when form values differ from the original or fetched metadata', () => { + const form = createForm(); + form.get('authors')?.setValue(['beta', 'alpha']); + form.get('title')?.setValue('Edited Title'); + + const original = { + authors: ['alpha', 'beta'], + title: 'Original Title', + } as BookMetadata; + const fetched = { + authors: ['other'], + title: 'Fetched Title', + } as BookMetadata; + + expect(service.isValueChanged('authors', form, original)).toBe(false); + expect(service.isValueChanged('title', form, original)).toBe(true); + expect(service.isFetchedDifferent('authors', form, fetched)).toBe(true); + expect(service.isFetchedDifferent('title', form, fetched)).toBe(true); + }); + + it('resets a field to the original value and clears copied and hovered flags', () => { + const form = createForm(); + form.get('title')?.setValue('Edited Title'); + + const copiedFields = {title: true}; + const hoveredFields = {title: true}; + const original = {title: 'Original Title'} as BookMetadata; + + service.resetField('title', form, original, copiedFields, hoveredFields); + + expect(form.get('title')?.value).toBe('Original Title'); + expect(copiedFields['title']).toBe(false); + expect(hoveredFields['title']).toBe(false); + }); + + it('patches metadata arrays as sorted values and applies lock defaults', () => { + const form = new FormGroup({ + authors: new FormControl([]), + authorsLocked: new FormControl(false), + title: new FormControl(''), + titleLocked: new FormControl(false), + }); + const metadata = { + authors: ['zeta', 'alpha'], + authorsLocked: true, + title: 'Patched Title', + titleLocked: false, + } as BookMetadata; + + service.patchMetadataToForm(metadata, form, [ + {controlName: 'authors', lockedKey: 'authorsLocked', type: 'array'}, + {controlName: 'title', lockedKey: 'titleLocked', type: 'string'}, + ]); + + expect(form.get('authors')?.value).toEqual(['alpha', 'zeta']); + expect(form.get('authorsLocked')?.value).toBe(true); + expect(form.get('title')?.value).toBe('Patched Title'); + expect(form.get('titleLocked')?.value).toBe(false); + }); +}); diff --git a/frontend/src/app/shared/model/app-settings.model.spec.ts b/frontend/src/app/shared/model/app-settings.model.spec.ts new file mode 100644 index 000000000..e5604886f --- /dev/null +++ b/frontend/src/app/shared/model/app-settings.model.spec.ts @@ -0,0 +1,65 @@ +import {describe, expect, expectTypeOf, it} from 'vitest'; + +import { + AppSettingKey, + AppSettings, + MetadataMatchWeights, + OidcTestResult +} from './app-settings.model'; + +describe('app-settings.model', () => { + it('exposes stable keys for persisted app settings', () => { + expect(AppSettingKey.AUTO_BOOK_SEARCH).toBe('AUTO_BOOK_SEARCH'); + expect(AppSettingKey.METADATA_PROVIDER_SETTINGS).toBe('METADATA_PROVIDER_SETTINGS'); + expect(AppSettingKey.OIDC_FORCE_ONLY_MODE).toBe('OIDC_FORCE_ONLY_MODE'); + }); + + it('keeps metadata match weights numerically typed', () => { + const weights: MetadataMatchWeights = { + title: 10, + subtitle: 5, + description: 3, + authors: 10, + publisher: 2, + publishedDate: 2, + seriesName: 4, + seriesNumber: 4, + seriesTotal: 2, + isbn13: 8, + isbn10: 8, + language: 2, + pageCount: 1, + categories: 2, + amazonRating: 1, + amazonReviewCount: 1, + goodreadsRating: 1, + goodreadsReviewCount: 1, + hardcoverRating: 1, + hardcoverReviewCount: 1, + doubanRating: 1, + doubanReviewCount: 1, + lubimyczytacRating: 1, + ranobedbRating: 1, + audibleRating: 1, + audibleReviewCount: 1, + coverImage: 6 + }; + + expect(weights.title).toBeGreaterThan(weights.coverImage); + expectTypeOf(weights.coverImage).toEqualTypeOf(); + }); + + it('supports OIDC test results and app-setting contract typing', () => { + const result: OidcTestResult = { + success: false, + checks: [ + {name: 'issuer', status: 'PASS', message: 'reachable'}, + {name: 'jwks', status: 'WARN', message: 'slow'} + ] + }; + + expect(result.checks[1].status).toBe('WARN'); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + }); +}); diff --git a/frontend/src/app/shared/model/app-state.model.spec.ts b/frontend/src/app/shared/model/app-state.model.spec.ts new file mode 100644 index 000000000..2e4e48be7 --- /dev/null +++ b/frontend/src/app/shared/model/app-state.model.spec.ts @@ -0,0 +1,21 @@ +import {describe, expect, expectTypeOf, it} from 'vitest'; + +import {AppState} from './app-state.model'; + +describe('app-state.model', () => { + it('supports partially specified visual state presets', () => { + const appState: AppState = { + preset: 'midnight', + primary: '#112233' + }; + + expect(appState.preset).toBe('midnight'); + expect(appState.surface).toBeUndefined(); + }); + + it('keeps each field optional and string-based', () => { + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + }); +}); diff --git a/frontend/src/app/shared/model/custom-font.model.spec.ts b/frontend/src/app/shared/model/custom-font.model.spec.ts new file mode 100644 index 000000000..2ad5a9b38 --- /dev/null +++ b/frontend/src/app/shared/model/custom-font.model.spec.ts @@ -0,0 +1,19 @@ +import {describe, expect, it} from 'vitest'; + +import {FontFormat, formatFileSize} from './custom-font.model'; + +describe('custom-font model', () => { + it('exposes stable font format enums', () => { + expect(FontFormat.TTF).toBe('TTF'); + expect(FontFormat.OTF).toBe('OTF'); + expect(FontFormat.WOFF).toBe('WOFF'); + expect(FontFormat.WOFF2).toBe('WOFF2'); + }); + + it('formats file sizes across byte, kilobyte, and megabyte ranges', () => { + expect(formatFileSize(0)).toBe('0 Bytes'); + expect(formatFileSize(512)).toBe('512 Bytes'); + expect(formatFileSize(1536)).toBe('1.5 KB'); + expect(formatFileSize(2 * 1024 * 1024)).toBe('2 MB'); + }); +}); diff --git a/frontend/src/app/shared/model/metadata-batch-progress.model.spec.ts b/frontend/src/app/shared/model/metadata-batch-progress.model.spec.ts new file mode 100644 index 000000000..b29c018b2 --- /dev/null +++ b/frontend/src/app/shared/model/metadata-batch-progress.model.spec.ts @@ -0,0 +1,19 @@ +import {describe, expect, it} from 'vitest'; + +import {MetadataBatchStatus, MetadataBatchStatusLabels} from './metadata-batch-progress.model'; + +describe('metadata-batch-progress model', () => { + it('keeps the status enum and labels in sync', () => { + expect(MetadataBatchStatus.IN_PROGRESS).toBe('IN_PROGRESS'); + expect(MetadataBatchStatus.COMPLETED).toBe('COMPLETED'); + expect(MetadataBatchStatus.ERROR).toBe('ERROR'); + expect(MetadataBatchStatus.CANCELLED).toBe('CANCELLED'); + + expect(MetadataBatchStatusLabels).toEqual({ + [MetadataBatchStatus.IN_PROGRESS]: 'In Progress', + [MetadataBatchStatus.COMPLETED]: 'Completed', + [MetadataBatchStatus.ERROR]: 'Error', + [MetadataBatchStatus.CANCELLED]: 'Cancelled', + }); + }); +}); diff --git a/frontend/src/app/shared/model/oidc-group-mapping.model.spec.ts b/frontend/src/app/shared/model/oidc-group-mapping.model.spec.ts new file mode 100644 index 000000000..069ccb34d --- /dev/null +++ b/frontend/src/app/shared/model/oidc-group-mapping.model.spec.ts @@ -0,0 +1,20 @@ +import {describe, expect, expectTypeOf, it} from 'vitest'; + +import {OidcGroupMapping} from './oidc-group-mapping.model'; + +describe('oidc-group-mapping.model', () => { + it('supports group claims with library-specific permissions', () => { + const mapping: OidcGroupMapping = { + id: 1, + oidcGroupClaim: 'admins', + isAdmin: true, + permissions: ['books.read', 'books.write'], + libraryIds: [10, 11], + description: 'Admin access' + }; + + expect(mapping.libraryIds).toEqual([10, 11]); + expect(mapping.isAdmin).toBe(true); + expectTypeOf(mapping.permissions).toEqualTypeOf(); + }); +}); diff --git a/frontend/src/app/shared/models/api-exception.model.spec.ts b/frontend/src/app/shared/models/api-exception.model.spec.ts new file mode 100644 index 000000000..2ff34ee40 --- /dev/null +++ b/frontend/src/app/shared/models/api-exception.model.spec.ts @@ -0,0 +1,18 @@ +import {describe, expect, expectTypeOf, it} from 'vitest'; + +import {APIException} from './api-exception.model'; + +describe('api-exception.model', () => { + it('captures API exception payloads with optional details', () => { + const error: APIException = { + status: 500, + message: 'Boom', + timestamp: '2026-03-26T10:00:00Z', + error: 'Internal Server Error' + }; + + expect(error.status).toBe(500); + expect(error.message).toBe('Boom'); + expectTypeOf(error.timestamp).toEqualTypeOf(); + }); +}); diff --git a/frontend/src/app/shared/service/annotation.service.spec.ts b/frontend/src/app/shared/service/annotation.service.spec.ts new file mode 100644 index 000000000..311f008a0 --- /dev/null +++ b/frontend/src/app/shared/service/annotation.service.spec.ts @@ -0,0 +1,80 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {API_CONFIG} from '../../core/config/api-config'; +import {AnnotationService} from './annotation.service'; + +describe('AnnotationService', () => { + const baseUrl = `${API_CONFIG.BASE_URL}/api/v1/annotations`; + + let service: AnnotationService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + AnnotationService, + ] + }); + + service = TestBed.inject(AnnotationService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('loads annotations for a book', () => { + service.getAnnotationsForBook(5).subscribe(); + + const request = httpTestingController.expectOne(`${baseUrl}/book/5`); + expect(request.request.method).toBe('GET'); + request.flush([]); + }); + + it('creates and updates annotations', () => { + const createRequest = { + bookId: 5, + cfi: 'epubcfi(/6/8)', + text: 'Important passage', + }; + + service.createAnnotation(createRequest).subscribe(); + const createHttpRequest = httpTestingController.expectOne(baseUrl); + expect(createHttpRequest.request.method).toBe('POST'); + expect(createHttpRequest.request.body).toEqual(createRequest); + createHttpRequest.flush({...createRequest, id: 8, color: '#ff0', style: 'highlight', createdAt: '2024-01-01'}); + + const updateRequest = { + note: 'Review later', + style: 'underline' as const, + }; + + service.updateAnnotation(8, updateRequest).subscribe(); + const updateHttpRequest = httpTestingController.expectOne(`${baseUrl}/8`); + expect(updateHttpRequest.request.method).toBe('PUT'); + expect(updateHttpRequest.request.body).toEqual(updateRequest); + updateHttpRequest.flush({ + ...createRequest, + ...updateRequest, + id: 8, + color: '#ff0', + createdAt: '2024-01-01', + }); + }); + + it('deletes annotations by id', () => { + service.deleteAnnotation(8).subscribe(); + + const request = httpTestingController.expectOne(`${baseUrl}/8`); + expect(request.request.method).toBe('DELETE'); + request.flush(null); + }); +}); diff --git a/frontend/src/app/shared/service/app-config.service.spec.ts b/frontend/src/app/shared/service/app-config.service.spec.ts new file mode 100644 index 000000000..33ce09670 --- /dev/null +++ b/frontend/src/app/shared/service/app-config.service.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs a theme-runtime seam around Prime theme tokens, +// localStorage hydration, DOM mutation, and browser-only effects so app state initialization can be +// asserted without changing runtime code. +describe.skip('AppConfigService', () => { + it('needs a browser storage and theme-token seam to validate state hydration and persistence effects', () => { + // Intentionally skipped until storage and theme runtime hooks are controllable in tests. + }); + + it('needs a document mutation seam to validate theme updates without coupling the spec to runtime DOM side effects', () => { + // Intentionally skipped until DOM-side theme application can be driven deterministically. + }); +}); diff --git a/frontend/src/app/shared/service/app-settings-query-keys.spec.ts b/frontend/src/app/shared/service/app-settings-query-keys.spec.ts new file mode 100644 index 000000000..c875dbf60 --- /dev/null +++ b/frontend/src/app/shared/service/app-settings-query-keys.spec.ts @@ -0,0 +1,10 @@ +import {describe, expect, it} from 'vitest'; + +import {APP_SETTINGS_QUERY_KEY, PUBLIC_SETTINGS_QUERY_KEY} from './app-settings-query-keys'; + +describe('app-settings-query-keys', () => { + it('uses stable cache keys for private and public settings', () => { + expect(APP_SETTINGS_QUERY_KEY).toEqual(['appSettings']); + expect(PUBLIC_SETTINGS_QUERY_KEY).toEqual(['publicSettings']); + }); +}); diff --git a/frontend/src/app/shared/service/app-settings.service.spec.ts b/frontend/src/app/shared/service/app-settings.service.spec.ts new file mode 100644 index 000000000..f4cbf3b02 --- /dev/null +++ b/frontend/src/app/shared/service/app-settings.service.spec.ts @@ -0,0 +1,200 @@ +import {HttpTestingController} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {AuthService} from './auth.service'; +import {APP_SETTINGS_QUERY_KEY, PUBLIC_SETTINGS_QUERY_KEY} from './app-settings-query-keys'; +import {AppSettingsService, type PublicAppSettings} from './app-settings.service'; +import type {AppSettings} from '../model/app-settings.model'; +import {createAuthServiceStub, createQueryClientHarness, flushSignalAndQueryEffects} from '../../core/testing/query-testing'; + +function buildPublicSettings(overrides: Partial = {}): PublicAppSettings { + return { + oidcEnabled: true, + remoteAuthEnabled: true, + oidcProviderDetails: { + providerName: 'OIDC', + clientId: 'client-id', + issuerUri: 'https://issuer.example', + claimMapping: { + username: 'preferred_username', + email: 'email', + name: 'name', + groups: 'groups', + }, + }, + oidcForceOnlyMode: false, + ...overrides, + }; +} + +function buildAppSettings(overrides: Partial = {}): AppSettings { + const publicSettings = buildPublicSettings(); + + return { + autoBookSearch: true, + similarBookRecommendation: true, + defaultMetadataRefreshOptions: {} as never, + libraryMetadataRefreshOptions: [], + uploadPattern: '{Title}', + opdsServerEnabled: true, + komgaApiEnabled: false, + komgaGroupUnknown: false, + remoteAuthEnabled: publicSettings.remoteAuthEnabled, + oidcEnabled: publicSettings.oidcEnabled, + oidcProviderDetails: publicSettings.oidcProviderDetails, + oidcAutoProvisionDetails: { + enableAutoProvisioning: false, + allowLocalAccountLinking: false, + defaultPermissions: [], + defaultLibraryIds: [], + }, + maxFileUploadSizeInMb: 50, + metadataProviderSettings: {} as never, + metadataMatchWeights: {} as never, + metadataPersistenceSettings: {} as never, + metadataPublicReviewsSettings: { + downloadEnabled: false, + autoDownloadEnabled: false, + providers: [], + }, + koboSettings: {} as never, + coverCroppingSettings: {} as never, + metadataDownloadOnBookdrop: false, + metadataProviderSpecificFields: {} as never, + oidcSessionDurationHours: null, + oidcGroupSyncMode: null, + oidcForceOnlyMode: publicSettings.oidcForceOnlyMode, + diskType: 'LOCAL', + ...overrides, + }; +} + +function flushInitialSettingsRequests( + httpTestingController: HttpTestingController, + overrides: { + publicSettings?: Partial; + appSettings?: Partial; + } = {}, +): { + publicSettings: PublicAppSettings; + appSettings: AppSettings; +} { + const publicSettings = buildPublicSettings(overrides.publicSettings); + const appSettings = buildAppSettings({ + oidcEnabled: publicSettings.oidcEnabled, + remoteAuthEnabled: publicSettings.remoteAuthEnabled, + oidcProviderDetails: publicSettings.oidcProviderDetails, + oidcForceOnlyMode: publicSettings.oidcForceOnlyMode, + ...overrides.appSettings, + }); + + const publicRequests = httpTestingController.match(req => req.url.endsWith('/api/v1/public-settings')); + expect(publicRequests.length).toBeGreaterThan(0); + publicRequests.forEach(request => request.flush(publicSettings)); + + const appRequests = httpTestingController.match(req => req.url.endsWith('/api/v1/settings') && req.method === 'GET'); + expect(appRequests.length).toBeGreaterThan(0); + appRequests.forEach(request => request.flush(appSettings)); + + return {publicSettings, appSettings}; +} + +describe('AppSettingsService', () => { + let service: AppSettingsService; + let httpTestingController: HttpTestingController; + let authService: ReturnType; + let queryClientHarness: ReturnType; + + beforeEach(() => { + authService = createAuthServiceStub(); + queryClientHarness = createQueryClientHarness(); + vi.spyOn(queryClientHarness.queryClient, 'removeQueries').mockImplementation(() => undefined); + + TestBed.configureTestingModule({ + providers: [ + ...queryClientHarness.providers, + AppSettingsService, + {provide: AuthService, useValue: authService}, + ], + }); + + service = TestBed.inject(AppSettingsService); + httpTestingController = TestBed.inject(HttpTestingController); + flushSignalAndQueryEffects(); + }); + + afterEach(() => { + httpTestingController.verify(); + queryClientHarness.queryClient.clear(); + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('exposes a public-settings query option that fetches the expected payload', async () => { + const publicSettings = buildPublicSettings({ + oidcEnabled: false, + remoteAuthEnabled: false, + oidcForceOnlyMode: true, + }); + flushInitialSettingsRequests(httpTestingController); + const queryFn = service.getPublicSettingsQueryOptions().queryFn as (context: never) => Promise; + + const queryResultPromise = queryFn({} as never); + + httpTestingController.expectOne(req => req.url.endsWith('/api/v1/public-settings')).flush(publicSettings); + + await expect(queryResultPromise).resolves.toEqual(publicSettings); + }); + + it('removes authenticated settings queries when the auth token becomes null', () => { + const removeQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'removeQueries').mockImplementation(() => undefined); + flushInitialSettingsRequests(httpTestingController); + + authService.token.set(null); + flushSignalAndQueryEffects(); + + expect(removeQueriesSpy).toHaveBeenCalledWith({queryKey: APP_SETTINGS_QUERY_KEY}); + }); + + it('updates both caches when OIDC is toggled successfully', async () => { + const initialSettings = flushInitialSettingsRequests(httpTestingController, { + publicSettings: { + oidcEnabled: true, + remoteAuthEnabled: true, + oidcForceOnlyMode: false, + }, + appSettings: { + oidcEnabled: true, + remoteAuthEnabled: true, + oidcForceOnlyMode: false, + }, + }); + await Promise.resolve(); + flushSignalAndQueryEffects(); + + const setQueryDataSpy = vi.spyOn(queryClientHarness.queryClient, 'setQueryData'); + Object.assign(service, { + appSettings: () => initialSettings.appSettings, + }); + queryClientHarness.queryClient.setQueryData(PUBLIC_SETTINGS_QUERY_KEY, initialSettings.publicSettings); + + service.toggleOidcEnabled(false).subscribe(); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/settings') && req.method === 'PUT'); + expect(request.request.method).toBe('PUT'); + expect(request.request.body).toEqual([{name: 'OIDC_ENABLED', value: false}]); + request.flush(null); + await Promise.resolve(); + flushSignalAndQueryEffects(); + + expect(setQueryDataSpy).toHaveBeenCalledWith( + APP_SETTINGS_QUERY_KEY, + expect.objectContaining({oidcEnabled: false}), + ); + expect(setQueryDataSpy).toHaveBeenCalledWith( + PUBLIC_SETTINGS_QUERY_KEY, + expect.objectContaining({oidcEnabled: false}), + ); + }); +}); diff --git a/frontend/src/app/shared/service/audiobook-session.service.spec.ts b/frontend/src/app/shared/service/audiobook-session.service.spec.ts new file mode 100644 index 000000000..0e9529462 --- /dev/null +++ b/frontend/src/app/shared/service/audiobook-session.service.spec.ts @@ -0,0 +1,105 @@ +import {TestBed} from '@angular/core/testing'; +import {of} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {ReadingSessionApiService} from './reading-session-api.service'; +import {AudiobookSessionService} from './audiobook-session.service'; + +describe('AudiobookSessionService', () => { + let createSession: ReturnType; + let sendSessionBeacon: ReturnType; + let service: AudiobookSessionService; + + beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-03-26T00:00:00Z')); + + createSession = vi.fn(() => of(void 0)); + sendSessionBeacon = vi.fn(() => true); + + TestBed.configureTestingModule({ + providers: [ + AudiobookSessionService, + { + provide: ReadingSessionApiService, + useValue: { + createSession, + sendSessionBeacon, + }, + }, + ], + }); + + service = TestBed.inject(AudiobookSessionService); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it('starts a session and reports current listening time while playback is active', () => { + service.startSession(7, 0, 1); + + vi.advanceTimersByTime(12_000); + + expect(service.isSessionActive()).toBe(true); + expect(service.isPlaying()).toBe(true); + expect(service.getCurrentListeningTime()).toBe(12); + }); + + it('accumulates listening time on pause using the playback rate', () => { + service.startSession(7, 30_000, 1.5); + + vi.advanceTimersByTime(10_000); + service.pauseSession(45_000); + + expect(service.isPlaying()).toBe(false); + expect(service.getCurrentListeningTime()).toBe(15); + }); + + it('discards short sessions without sending them to the backend', () => { + service.startSession(8, 0, 1); + + vi.advanceTimersByTime(20_000); + service.endSession(20_000); + + expect(createSession).not.toHaveBeenCalled(); + expect(service.isSessionActive()).toBe(false); + }); + + it('sends completed sessions that meet the minimum duration threshold', () => { + service.startSession(11, 0, 1, 99, 2); + + vi.advanceTimersByTime(31_000); + service.endSession(90_000); + + expect(createSession).toHaveBeenCalledOnce(); + expect(createSession).toHaveBeenCalledWith(expect.objectContaining({ + bookId: 11, + bookType: 'AUDIOBOOK', + durationSeconds: 31, + durationFormatted: '31s', + startLocation: '0:00', + endLocation: '1:30', + })); + expect(service.isSessionActive()).toBe(false); + }); + + it('sends a beacon on unload for long enough active sessions', () => { + service.startSession(12, 65_000, 1); + + vi.advanceTimersByTime(35_000); + window.dispatchEvent(new Event('beforeunload')); + + expect(sendSessionBeacon).toHaveBeenCalledOnce(); + expect(sendSessionBeacon).toHaveBeenCalledWith(expect.objectContaining({ + bookId: 12, + bookType: 'AUDIOBOOK', + durationSeconds: 35, + startLocation: '1:05', + endLocation: '1:05', + })); + }); +}); diff --git a/frontend/src/app/shared/service/auth.service.spec.ts b/frontend/src/app/shared/service/auth.service.spec.ts new file mode 100644 index 000000000..db265dfa6 --- /dev/null +++ b/frontend/src/app/shared/service/auth.service.spec.ts @@ -0,0 +1,194 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {Router} from '@angular/router'; +import {of, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {API_CONFIG} from '../../core/config/api-config'; +import {PostLoginInitializerService} from '../../core/services/post-login-initializer.service'; +import {RxStompService} from '../websocket/rx-stomp.service'; +import {AuthService, websocketInitializer} from './auth.service'; + +describe('AuthService', () => { + const router = { + navigate: vi.fn(() => Promise.resolve(true)), + }; + const rxStompService = { + activate: vi.fn(), + deactivate: vi.fn(), + updateConfig: vi.fn(), + }; + const postLoginInitializer = { + initialize: vi.fn(() => of(undefined)), + }; + + let service: AuthService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + vi.restoreAllMocks(); + localStorage.clear(); + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + {provide: Router, useValue: router}, + {provide: RxStompService, useValue: rxStompService}, + {provide: PostLoginInitializerService, useValue: postLoginInitializer}, + AuthService, + ] + }); + + router.navigate.mockClear(); + rxStompService.activate.mockClear(); + rxStompService.deactivate.mockClear(); + rxStompService.updateConfig.mockClear(); + postLoginInitializer.initialize.mockClear(); + + service = TestBed.inject(AuthService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + localStorage.clear(); + TestBed.resetTestingModule(); + }); + + it('logs in with internal credentials and initializes the authenticated session', () => { + service.internalLogin({username: 'admin', password: 'secret'}).subscribe(); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/login`); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual({username: 'admin', password: 'secret'}); + request.flush({accessToken: 'access', refreshToken: 'refresh', isDefaultPassword: 'false'}); + + expect(service.getInternalAccessToken()).toBe('access'); + expect(service.getInternalRefreshToken()).toBe('refresh'); + expect(service.token()).toBe('access'); + expect(rxStompService.updateConfig).toHaveBeenCalledOnce(); + expect(rxStompService.activate).toHaveBeenCalledOnce(); + expect(postLoginInitializer.initialize).toHaveBeenCalledOnce(); + }); + + it('refreshes the token and persists the new values', () => { + localStorage.setItem('refreshToken_Internal', 'refresh-token'); + + service.internalRefreshToken().subscribe(); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/refresh`); + expect(request.request.body).toEqual({refreshToken: 'refresh-token'}); + request.flush({accessToken: 'new-access', refreshToken: 'new-refresh'}); + + expect(service.getInternalAccessToken()).toBe('new-access'); + expect(service.getInternalRefreshToken()).toBe('new-refresh'); + }); + + it('handles remote login the same way as an internal login', () => { + service.remoteLogin().subscribe(); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/remote`); + expect(request.request.method).toBe('GET'); + request.flush({accessToken: 'remote-access', refreshToken: 'remote-refresh', isDefaultPassword: 'false'}); + + expect(service.getInternalAccessToken()).toBe('remote-access'); + expect(rxStompService.activate).toHaveBeenCalledOnce(); + expect(postLoginInitializer.initialize).toHaveBeenCalledOnce(); + }); + + it('logs out locally when the backend does not return a remote logout url', async () => { + localStorage.setItem('accessToken_Internal', 'access'); + localStorage.setItem('refreshToken_Internal', 'refresh'); + + service.logout(); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/logout`); + request.flush({logoutUrl: null}); + + await Promise.resolve(); + + expect(service.token()).toBeNull(); + expect(rxStompService.deactivate).toHaveBeenCalledOnce(); + expect(router.navigate).toHaveBeenCalledWith(['/login']); + }); + + it('logs out locally when the backend logout request fails', async () => { + localStorage.setItem('accessToken_Internal', 'access'); + localStorage.setItem('refreshToken_Internal', 'refresh'); + + service.logout(); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/logout`); + request.flush('boom', {status: 500, statusText: 'Server Error'}); + + await Promise.resolve(); + + expect(service.token()).toBeNull(); + expect(rxStompService.deactivate).toHaveBeenCalledOnce(); + expect(router.navigate).toHaveBeenCalledWith(['/login']); + }); + + it('clears the session and navigates with a reason during force logout', () => { + localStorage.setItem('accessToken_Internal', 'access'); + localStorage.setItem('refreshToken_Internal', 'refresh'); + + service.forceLogout('session_revoked'); + + expect(service.token()).toBeNull(); + expect(rxStompService.deactivate).toHaveBeenCalledOnce(); + expect(router.navigate).toHaveBeenCalledWith(['/login'], { + queryParams: {reason: 'session_revoked'}, + }); + }); + + it('clears the session when the login page is opened', () => { + localStorage.setItem('accessToken_Internal', 'access'); + localStorage.setItem('refreshToken_Internal', 'refresh'); + + service.clearSessionOnLoginPage(); + + expect(service.token()).toBeNull(); + expect(rxStompService.deactivate).toHaveBeenCalledOnce(); + }); + + it('skips websocket initialization when there is no access token', () => { + service.initializeWebSocketConnection(); + + expect(rxStompService.updateConfig).not.toHaveBeenCalled(); + expect(postLoginInitializer.initialize).not.toHaveBeenCalled(); + }); + + it('initializes the websocket connection and post-login hooks only once', () => { + service.saveInternalTokens('access', 'refresh'); + + service.initializeWebSocketConnection(); + service.initializeWebSocketConnection(); + + expect(rxStompService.updateConfig).toHaveBeenCalledTimes(2); + expect(rxStompService.activate).toHaveBeenCalledTimes(2); + expect(postLoginInitializer.initialize).toHaveBeenCalledOnce(); + }); + + it('provides a websocket initializer wrapper', () => { + const initializeSpy = vi.spyOn(service, 'initializeWebSocketConnection').mockImplementation(() => undefined); + + websocketInitializer(service)(); + + expect(initializeSpy).toHaveBeenCalledOnce(); + }); + + it('continues after post-login initialization failures', () => { + postLoginInitializer.initialize.mockReturnValue( + throwError(() => new Error('initializer failed')) + ); + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined); + + service.saveInternalTokens('access', 'refresh'); + service.initializeWebSocketConnection(); + + expect(errorSpy).toHaveBeenCalledOnce(); + expect(rxStompService.activate).toHaveBeenCalledOnce(); + }); +}); diff --git a/frontend/src/app/shared/service/book-mark.service.spec.ts b/frontend/src/app/shared/service/book-mark.service.spec.ts new file mode 100644 index 000000000..9f253e3c8 --- /dev/null +++ b/frontend/src/app/shared/service/book-mark.service.spec.ts @@ -0,0 +1,74 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {API_CONFIG} from '../../core/config/api-config'; +import {BookMarkService} from './book-mark.service'; + +describe('BookMarkService', () => { + const baseUrl = `${API_CONFIG.BASE_URL}/api/v1/bookmarks`; + + let service: BookMarkService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + BookMarkService, + ] + }); + + service = TestBed.inject(BookMarkService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('loads bookmarks for a book', () => { + service.getBookmarksForBook(9).subscribe(); + + const request = httpTestingController.expectOne(`${baseUrl}/book/9`); + expect(request.request.method).toBe('GET'); + request.flush([]); + }); + + it('creates and updates bookmarks', () => { + const createRequest = { + bookId: 9, + cfi: 'epubcfi(/6/4)', + title: 'Great quote', + }; + + service.createBookmark(createRequest).subscribe(); + const createHttpRequest = httpTestingController.expectOne(baseUrl); + expect(createHttpRequest.request.method).toBe('POST'); + expect(createHttpRequest.request.body).toEqual(createRequest); + createHttpRequest.flush({...createRequest, id: 12, createdAt: '2024-01-01'}); + + const updateRequest = { + title: 'Updated quote', + notes: 'Look here again', + }; + + service.updateBookmark(12, updateRequest).subscribe(); + const updateHttpRequest = httpTestingController.expectOne(`${baseUrl}/12`); + expect(updateHttpRequest.request.method).toBe('PUT'); + expect(updateHttpRequest.request.body).toEqual(updateRequest); + updateHttpRequest.flush({...createRequest, ...updateRequest, id: 12, createdAt: '2024-01-01'}); + }); + + it('deletes bookmarks by id', () => { + service.deleteBookmark(12).subscribe(); + + const request = httpTestingController.expectOne(`${baseUrl}/12`); + expect(request.request.method).toBe('DELETE'); + request.flush(null); + }); +}); diff --git a/frontend/src/app/shared/service/book-metadata-host.service.spec.ts b/frontend/src/app/shared/service/book-metadata-host.service.spec.ts new file mode 100644 index 000000000..76194e333 --- /dev/null +++ b/frontend/src/app/shared/service/book-metadata-host.service.spec.ts @@ -0,0 +1,19 @@ +import {describe, expect, it} from 'vitest'; + +import {BookMetadataHostService} from './book-metadata-host.service'; + +describe('BookMetadataHostService', () => { + it('emits book switch requests through the shared subject', () => { + const service = new BookMetadataHostService(); + const received: number[] = []; + + const subscription = service.bookSwitches$.subscribe(bookId => received.push(bookId)); + + service.requestBookSwitch(42); + service.switchBook(84); + + expect(received).toEqual([42, 84]); + + subscription.unsubscribe(); + }); +}); diff --git a/frontend/src/app/shared/service/book-note-v2.service.spec.ts b/frontend/src/app/shared/service/book-note-v2.service.spec.ts new file mode 100644 index 000000000..4a1886ced --- /dev/null +++ b/frontend/src/app/shared/service/book-note-v2.service.spec.ts @@ -0,0 +1,74 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {API_CONFIG} from '../../core/config/api-config'; +import {BookNoteV2Service} from './book-note-v2.service'; + +describe('BookNoteV2Service', () => { + const baseUrl = `${API_CONFIG.BASE_URL}/api/v2/book-notes`; + + let service: BookNoteV2Service; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + BookNoteV2Service, + ] + }); + + service = TestBed.inject(BookNoteV2Service); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('loads v2 notes for a book', () => { + service.getNotesForBook(22).subscribe(); + + const request = httpTestingController.expectOne(`${baseUrl}/book/22`); + expect(request.request.method).toBe('GET'); + request.flush([]); + }); + + it('creates and updates v2 notes', () => { + const createRequest = { + bookId: 22, + cfi: 'epubcfi(/6/2[chapter1])', + noteContent: 'Remember this passage', + }; + + service.createNote(createRequest).subscribe(); + const createHttpRequest = httpTestingController.expectOne(baseUrl); + expect(createHttpRequest.request.method).toBe('POST'); + expect(createHttpRequest.request.body).toEqual(createRequest); + createHttpRequest.flush({...createRequest, id: 4, createdAt: '2024-01-01'}); + + const updateRequest = { + noteContent: 'Updated note', + color: '#ff0', + }; + + service.updateNote(4, updateRequest).subscribe(); + const updateHttpRequest = httpTestingController.expectOne(`${baseUrl}/4`); + expect(updateHttpRequest.request.method).toBe('PUT'); + expect(updateHttpRequest.request.body).toEqual(updateRequest); + updateHttpRequest.flush({...createRequest, ...updateRequest, id: 4, createdAt: '2024-01-01'}); + }); + + it('deletes v2 notes by id', () => { + service.deleteNote(4).subscribe(); + + const request = httpTestingController.expectOne(`${baseUrl}/4`); + expect(request.request.method).toBe('DELETE'); + request.flush(null); + }); +}); diff --git a/frontend/src/app/shared/service/book-note.service.spec.ts b/frontend/src/app/shared/service/book-note.service.spec.ts new file mode 100644 index 000000000..2d3b5c98b --- /dev/null +++ b/frontend/src/app/shared/service/book-note.service.spec.ts @@ -0,0 +1,64 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {API_CONFIG} from '../../core/config/api-config'; +import {BookNoteService} from './book-note.service'; + +describe('BookNoteService', () => { + const baseUrl = `${API_CONFIG.BASE_URL}/api/v1/book-notes`; + + let service: BookNoteService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + BookNoteService, + ] + }); + + service = TestBed.inject(BookNoteService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('loads notes for a book', () => { + service.getNotesForBook(15).subscribe(); + + const request = httpTestingController.expectOne(`${baseUrl}/book/15`); + expect(request.request.method).toBe('GET'); + request.flush([]); + }); + + it('creates or updates a note via POST', () => { + const requestBody = { + bookId: 15, + title: 'Chapter 1', + content: 'Important note', + }; + + service.createOrUpdateNote(requestBody).subscribe(); + + const request = httpTestingController.expectOne(baseUrl); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual(requestBody); + request.flush({...requestBody, id: 3, userId: 9, createdAt: '2024-01-01', updatedAt: '2024-01-02'}); + }); + + it('deletes a note by id', () => { + service.deleteNote(3).subscribe(); + + const request = httpTestingController.expectOne(`${baseUrl}/3`); + expect(request.request.method).toBe('DELETE'); + request.flush(null); + }); +}); diff --git a/frontend/src/app/shared/service/custom-font.service.spec.ts b/frontend/src/app/shared/service/custom-font.service.spec.ts new file mode 100644 index 000000000..d7bcbf137 --- /dev/null +++ b/frontend/src/app/shared/service/custom-font.service.spec.ts @@ -0,0 +1,14 @@ +import {describe, it} from 'vitest'; + +// NOTE(frontend-seam): Real coverage here needs a stable Angular Query harness plus a controllable +// FontFace/document.fonts environment so query cache mutation and browser font registration can be +// asserted without changing runtime code. +describe.skip('CustomFontService', () => { + it('needs a query-client and font-face seam to validate cache updates after upload and deletion', () => { + // Intentionally skipped until the service can be exercised without mutating runtime code. + }); + + it('needs a controllable browser font registry seam to validate loadFontFace and removeFontFace behavior', () => { + // Intentionally skipped until document.fonts and FontFace can be driven deterministically. + }); +}); diff --git a/frontend/src/app/shared/service/file-download.service.spec.ts b/frontend/src/app/shared/service/file-download.service.spec.ts new file mode 100644 index 000000000..b06bc40aa --- /dev/null +++ b/frontend/src/app/shared/service/file-download.service.spec.ts @@ -0,0 +1,74 @@ +import {HttpHeaders, provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {FileDownloadService} from './file-download.service'; + +describe('FileDownloadService', () => { + let service: FileDownloadService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + FileDownloadService, + ] + }); + + service = TestBed.inject(FileDownloadService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('downloads a blob using the filename from the response header', () => { + const click = vi.fn(); + const anchor = {href: '', download: '', click} as unknown as HTMLAnchorElement; + const createElementSpy = vi.spyOn(document, 'createElement').mockReturnValue(anchor); + const createObjectUrlSpy = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:download'); + const revokeObjectUrlSpy = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined); + + service.downloadFile('/files/1', 'fallback.epub'); + + const request = httpTestingController.expectOne('/files/1'); + expect(request.request.method).toBe('GET'); + expect(request.request.responseType).toBe('blob'); + request.flush(new Blob(['content']), { + headers: new HttpHeaders({ + 'Content-Disposition': "attachment; filename*=UTF-8''server%20name.epub", + }), + }); + + expect(createElementSpy).toHaveBeenCalledWith('a'); + expect(createObjectUrlSpy).toHaveBeenCalled(); + expect(anchor.download).toBe('server name.epub'); + expect(click).toHaveBeenCalledOnce(); + expect(revokeObjectUrlSpy).toHaveBeenCalledWith('blob:download'); + }); + + it('falls back to the provided filename when the response has no content-disposition header', () => { + const click = vi.fn(); + const anchor = {href: '', download: '', click} as unknown as HTMLAnchorElement; + const createElementSpy = vi.spyOn(document, 'createElement').mockReturnValue(anchor); + const createObjectUrlSpy = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:download'); + const revokeObjectUrlSpy = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined); + + service.downloadFile('/files/2', 'fallback.epub'); + + const request = httpTestingController.expectOne('/files/2'); + request.flush(new Blob(['content'])); + + expect(createElementSpy).toHaveBeenCalledWith('a'); + expect(createObjectUrlSpy).toHaveBeenCalled(); + expect(anchor.download).toBe('fallback.epub'); + expect(click).toHaveBeenCalledOnce(); + expect(revokeObjectUrlSpy).toHaveBeenCalledWith('blob:download'); + }); +}); diff --git a/frontend/src/app/shared/service/file-operations.service.spec.ts b/frontend/src/app/shared/service/file-operations.service.spec.ts new file mode 100644 index 000000000..3bc509e6b --- /dev/null +++ b/frontend/src/app/shared/service/file-operations.service.spec.ts @@ -0,0 +1,51 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {FileMoveRequest, FileOperationsService} from './file-operations.service'; + +describe('FileOperationsService', () => { + let service: FileOperationsService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + FileOperationsService, + ], + }); + + service = TestBed.inject(FileOperationsService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('posts move requests to the file operations endpoint', () => { + const requestBody: FileMoveRequest = { + bookIds: [4, 9], + moves: [ + {bookId: 4, targetLibraryId: 2, targetLibraryPathId: 10}, + {bookId: 9, targetLibraryId: null, targetLibraryPathId: null}, + ], + }; + + let completed = false; + service.moveFiles(requestBody).subscribe(() => { + completed = true; + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/files/move')); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual(requestBody); + request.flush(null); + + expect(completed).toBe(true); + }); +}); diff --git a/frontend/src/app/shared/service/icon-picker.service.spec.ts b/frontend/src/app/shared/service/icon-picker.service.spec.ts new file mode 100644 index 000000000..a79904a67 --- /dev/null +++ b/frontend/src/app/shared/service/icon-picker.service.spec.ts @@ -0,0 +1,40 @@ +import {TestBed} from '@angular/core/testing'; +import {firstValueFrom, of} from 'rxjs'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; + +import {DialogLauncherService} from '../services/dialog-launcher.service'; +import {IconPickerService} from './icon-picker.service'; + +describe('IconPickerService', () => { + const dialogLauncherService = { + openIconPickerDialog: vi.fn(), + }; + + let service: IconPickerService; + + beforeEach(() => { + vi.restoreAllMocks(); + dialogLauncherService.openIconPickerDialog.mockReset(); + + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + IconPickerService, + {provide: DialogLauncherService, useValue: dialogLauncherService}, + ] + }); + + service = TestBed.inject(IconPickerService); + }); + + it('returns the icon selected by the dialog', async () => { + dialogLauncherService.openIconPickerDialog.mockReturnValue({ + onClose: of({type: 'PRIME_NG', value: 'pi pi-book'}), + }); + + await expect(firstValueFrom(service.open())).resolves.toEqual({ + type: 'PRIME_NG', + value: 'pi pi-book', + }); + }); +}); diff --git a/frontend/src/app/shared/service/local-storage.service.spec.ts b/frontend/src/app/shared/service/local-storage.service.spec.ts new file mode 100644 index 000000000..e0130f8fc --- /dev/null +++ b/frontend/src/app/shared/service/local-storage.service.spec.ts @@ -0,0 +1,59 @@ +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {LocalStorageService} from './local-storage.service'; + +describe('LocalStorageService', () => { + let service: LocalStorageService; + + beforeEach(() => { + localStorage.clear(); + TestBed.configureTestingModule({ + providers: [LocalStorageService], + }); + + service = TestBed.inject(LocalStorageService); + }); + + afterEach(() => { + localStorage.clear(); + TestBed.resetTestingModule(); + }); + + it('reads parsed values from local storage', () => { + localStorage.setItem('settings', JSON.stringify({theme: 'aura'})); + + expect(service.get<{theme: string}>('settings')).toEqual({theme: 'aura'}); + }); + + it('returns null when the key is missing or invalid', () => { + localStorage.setItem('broken', '{not-json'); + + expect(service.get('missing')).toBeNull(); + expect(service.get('broken')).toBeNull(); + }); + + it('serializes values when writing to local storage', () => { + service.set('settings', {theme: 'aura'}); + + expect(localStorage.getItem('settings')).toBe(JSON.stringify({theme: 'aura'})); + }); + + it('swallows storage write errors', () => { + const setItemSpy = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new Error('quota exceeded'); + }); + + expect(() => service.set('settings', {theme: 'aura'})).not.toThrow(); + expect(setItemSpy).toHaveBeenCalled(); + setItemSpy.mockRestore(); + }); + + it('removes values from local storage', () => { + localStorage.setItem('settings', JSON.stringify({theme: 'aura'})); + + service.remove('settings'); + + expect(localStorage.getItem('settings')).toBeNull(); + }); +}); diff --git a/frontend/src/app/shared/service/metadata-match-weights.service.spec.ts b/frontend/src/app/shared/service/metadata-match-weights.service.spec.ts new file mode 100644 index 000000000..41dae6d9a --- /dev/null +++ b/frontend/src/app/shared/service/metadata-match-weights.service.spec.ts @@ -0,0 +1,44 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {API_CONFIG} from '../../core/config/api-config'; +import {MetadataMatchWeightsService} from './metadata-match-weights.service'; + +describe('MetadataMatchWeightsService', () => { + let service: MetadataMatchWeightsService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + MetadataMatchWeightsService, + ] + }); + + service = TestBed.inject(MetadataMatchWeightsService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('posts to the metadata score recalculation endpoint', () => { + service.recalculateAll().subscribe(); + + const request = httpTestingController.expectOne( + `${API_CONFIG.BASE_URL}/api/v1/books/metadata/recalculate-match-scores` + ); + + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual({}); + + request.flush(null); + }); +}); diff --git a/frontend/src/app/shared/service/metadata-progress.service.spec.ts b/frontend/src/app/shared/service/metadata-progress.service.spec.ts new file mode 100644 index 000000000..5c089bcad --- /dev/null +++ b/frontend/src/app/shared/service/metadata-progress.service.spec.ts @@ -0,0 +1,135 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {of, throwError} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {MetadataBatchProgressNotification, MetadataBatchStatus} from '../model/metadata-batch-progress.model'; +import {MetadataTaskService} from '../../features/book/service/metadata-task'; +import {UserService} from '../../features/settings/user-management/user.service'; +import {MetadataProgressService} from './metadata-progress.service'; + +describe('MetadataProgressService', () => { + const adminUser = { + permissions: { + admin: true, + canEditMetadata: false, + }, + }; + + let getActiveTasks: ReturnType; + let currentUser: ReturnType>; + let service: MetadataProgressService; + + const taskA: MetadataBatchProgressNotification = { + taskId: 'task-a', + completed: 1, + total: 4, + message: 'running', + status: MetadataBatchStatus.IN_PROGRESS, + review: false, + }; + + const taskB: MetadataBatchProgressNotification = { + taskId: 'task-b', + completed: 4, + total: 4, + message: 'done', + status: MetadataBatchStatus.COMPLETED, + review: true, + }; + + beforeEach(() => { + getActiveTasks = vi.fn(() => of([])); + currentUser = signal(adminUser); + + TestBed.configureTestingModule({ + providers: [ + MetadataProgressService, + { + provide: MetadataTaskService, + useValue: {getActiveTasks}, + }, + { + provide: UserService, + useValue: {currentUser}, + }, + ], + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('initializes active tasks once for users with metadata permissions', () => { + getActiveTasks.mockReturnValue(of([taskA])); + + service = TestBed.inject(MetadataProgressService); + TestBed.flushEffects(); + + expect(getActiveTasks).toHaveBeenCalledOnce(); + expect(service.getActiveTasks()).toEqual({[taskA.taskId]: taskA}); + }); + + it('does not initialize task loading when the current user lacks metadata permissions', () => { + currentUser.set({ + permissions: { + admin: false, + canEditMetadata: false, + }, + }); + + service = TestBed.inject(MetadataProgressService); + TestBed.flushEffects(); + + expect(getActiveTasks).not.toHaveBeenCalled(); + expect(service.getActiveTasks()).toEqual({}); + }); + + it('warns and keeps running when active-task initialization fails', () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + getActiveTasks.mockReturnValue(throwError(() => new Error('boom'))); + + service = TestBed.inject(MetadataProgressService); + TestBed.flushEffects(); + + expect(getActiveTasks).toHaveBeenCalledOnce(); + expect(warnSpy).toHaveBeenCalled(); + expect(service.getActiveTasks()).toEqual({}); + }); + + it('publishes incoming progress updates and keeps the latest task state', () => { + service = TestBed.inject(MetadataProgressService); + + const emissions: MetadataBatchProgressNotification[] = []; + service.progressUpdates$.subscribe(value => emissions.push(value)); + + service.handleIncomingProgress(taskA); + service.handleIncomingProgress({...taskA, completed: 3}); + + expect(emissions).toHaveLength(2); + expect(service.getActiveTasks()).toEqual({ + [taskA.taskId]: {...taskA, completed: 3}, + }); + }); + + it('clears tasks from the active task map', () => { + service = TestBed.inject(MetadataProgressService); + service.handleIncomingProgress(taskA); + service.handleIncomingProgress(taskB); + + service.clearTask(taskA.taskId); + + expect(service.getActiveTasks()).toEqual({[taskB.taskId]: taskB}); + }); + + it('unsubscribes cleanly on destroy', () => { + service = TestBed.inject(MetadataProgressService); + service.handleIncomingProgress(taskA); + + service.ngOnDestroy(); + + expect(() => service.getActiveTasks()).not.toThrow(); + }); +}); diff --git a/frontend/src/app/shared/service/oidc-group-mapping.service.spec.ts b/frontend/src/app/shared/service/oidc-group-mapping.service.spec.ts new file mode 100644 index 000000000..1ce59ea89 --- /dev/null +++ b/frontend/src/app/shared/service/oidc-group-mapping.service.spec.ts @@ -0,0 +1,79 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {API_CONFIG} from '../../core/config/api-config'; +import {OidcGroupMappingService} from './oidc-group-mapping.service'; + +describe('OidcGroupMappingService', () => { + const baseUrl = `${API_CONFIG.BASE_URL}/api/v1/admin/oidc-group-mappings`; + + let service: OidcGroupMappingService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + OidcGroupMappingService, + ] + }); + + service = TestBed.inject(OidcGroupMappingService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('fetches all mappings', () => { + service.getAll().subscribe(); + + const request = httpTestingController.expectOne(baseUrl); + expect(request.request.method).toBe('GET'); + request.flush([]); + }); + + it('creates a mapping', () => { + const mapping = { + oidcGroupClaim: 'admins', + isAdmin: true, + permissions: ['BOOK_EDIT'], + libraryIds: [1], + description: 'Admin group', + }; + + service.create(mapping).subscribe(); + + const request = httpTestingController.expectOne(baseUrl); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual(mapping); + request.flush(mapping); + }); + + it('updates and deletes mappings by id', () => { + const mapping = { + oidcGroupClaim: 'members', + isAdmin: false, + permissions: ['BOOK_VIEW'], + libraryIds: [2], + description: 'Member group', + }; + + service.update(7, mapping).subscribe(); + const updateRequest = httpTestingController.expectOne(`${baseUrl}/7`); + expect(updateRequest.request.method).toBe('PUT'); + expect(updateRequest.request.body).toEqual(mapping); + updateRequest.flush(mapping); + + service.delete(7).subscribe(); + const deleteRequest = httpTestingController.expectOne(`${baseUrl}/7`); + expect(deleteRequest.request.method).toBe('DELETE'); + deleteRequest.flush(null); + }); +}); diff --git a/frontend/src/app/shared/service/page-title.service.spec.ts b/frontend/src/app/shared/service/page-title.service.spec.ts new file mode 100644 index 000000000..48323fd86 --- /dev/null +++ b/frontend/src/app/shared/service/page-title.service.spec.ts @@ -0,0 +1,71 @@ +import {TestBed} from '@angular/core/testing'; +import {Title} from '@angular/platform-browser'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; + +import {Book} from '../../features/book/model/book.model'; +import {PageTitleService} from './page-title.service'; + +describe('PageTitleService', () => { + const titleService = { + setTitle: vi.fn(), + }; + + let service: PageTitleService; + + beforeEach(() => { + vi.restoreAllMocks(); + titleService.setTitle.mockClear(); + + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + PageTitleService, + {provide: Title, useValue: titleService}, + ] + }); + + service = TestBed.inject(PageTitleService); + }); + + it('appends the application name to a page title', () => { + service.setPageTitle('Dashboard'); + + expect(titleService.setTitle).toHaveBeenCalledWith('Dashboard - Grimmory'); + }); + + it('builds a book page title from the available book metadata', () => { + const book = { + libraryName: 'Central', + fileName: 'fallback.epub', + metadata: { + title: 'Dune', + seriesName: 'Chronicles', + authors: ['Frank Herbert', 'Brian Herbert'], + }, + primaryFile: { + bookType: 'EPUB', + }, + } as Book; + + service.setBookPageTitle(book); + + expect(titleService.setTitle).toHaveBeenCalledWith( + 'Central/Dune (Chronicles series) - by Frank Herbert and Brian Herbert (EPUB) - Grimmory' + ); + }); + + it('falls back to the filename when the metadata title is missing', () => { + const book = { + libraryName: 'Central', + fileName: 'fallback.epub', + metadata: {}, + primaryFile: { + bookType: 'PDF', + }, + } as Book; + + service.setBookPageTitle(book); + + expect(titleService.setTitle).toHaveBeenCalledWith('Central/fallback.epub (PDF) - Grimmory'); + }); +}); diff --git a/frontend/src/app/shared/service/pdf-annotation.service.spec.ts b/frontend/src/app/shared/service/pdf-annotation.service.spec.ts new file mode 100644 index 000000000..35304eb4b --- /dev/null +++ b/frontend/src/app/shared/service/pdf-annotation.service.spec.ts @@ -0,0 +1,69 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {PdfAnnotationService} from './pdf-annotation.service'; + +describe('PdfAnnotationService', () => { + let service: PdfAnnotationService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + PdfAnnotationService, + ], + }); + + service = TestBed.inject(PdfAnnotationService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('fetches annotations for a book', () => { + let result: {data: string} | undefined; + service.getAnnotations(42).subscribe(value => { + result = value; + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/pdf-annotations/book/42')); + expect(request.request.method).toBe('GET'); + request.flush({data: '{"annotations":[]}'}); + + expect(result).toEqual({data: '{"annotations":[]}'}); + }); + + it('saves annotations for a book', () => { + let completed = false; + service.saveAnnotations(7, '{"page":1}').subscribe(() => { + completed = true; + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/pdf-annotations/book/7')); + expect(request.request.method).toBe('PUT'); + expect(request.request.body).toEqual({data: '{"page":1}'}); + request.flush(null); + + expect(completed).toBe(true); + }); + + it('deletes annotations for a book', () => { + let completed = false; + service.deleteAnnotations(9).subscribe(() => { + completed = true; + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/pdf-annotations/book/9')); + expect(request.request.method).toBe('DELETE'); + request.flush(null); + + expect(completed).toBe(true); + }); +}); diff --git a/frontend/src/app/shared/service/reading-session-api.service.spec.ts b/frontend/src/app/shared/service/reading-session-api.service.spec.ts new file mode 100644 index 000000000..872ba4973 --- /dev/null +++ b/frontend/src/app/shared/service/reading-session-api.service.spec.ts @@ -0,0 +1,105 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {API_CONFIG} from '../../core/config/api-config'; +import {ReadingSessionApiService} from './reading-session-api.service'; + +describe('ReadingSessionApiService', () => { + const baseUrl = `${API_CONFIG.BASE_URL}/api/v1/reading-sessions`; + const originalSendBeaconDescriptor = Object.getOwnPropertyDescriptor(navigator, 'sendBeacon'); + + let service: ReadingSessionApiService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + ReadingSessionApiService, + ] + }); + + service = TestBed.inject(ReadingSessionApiService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + if (originalSendBeaconDescriptor) { + Object.defineProperty(navigator, 'sendBeacon', originalSendBeaconDescriptor); + } else { + Object.defineProperty(navigator, 'sendBeacon', { + configurable: true, + value: undefined, + }); + } + TestBed.resetTestingModule(); + }); + + it('creates a reading session', () => { + const session = { + bookId: 3, + bookType: 'EPUB' as const, + startTime: '2024-01-01T00:00:00Z', + endTime: '2024-01-01T00:10:00Z', + durationSeconds: 600, + durationFormatted: '10m 0s', + }; + + service.createSession(session).subscribe(); + + const request = httpTestingController.expectOne(baseUrl); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual(session); + request.flush(null); + }); + + it('loads paged sessions for a book', () => { + service.getSessionsByBookId(3, 2, 20).subscribe(); + + const request = httpTestingController.expectOne( + requestMatch => requestMatch.url === `${baseUrl}/book/3` + && requestMatch.params.get('page') === '2' + && requestMatch.params.get('size') === '20' + ); + + expect(request.request.method).toBe('GET'); + request.flush({ + content: [], + page: { + totalElements: 0, + totalPages: 0, + number: 2, + size: 20, + } + }); + }); + + it('uses sendBeacon when the browser supports it and returns false when it throws', () => { + const session = { + bookId: 3, + bookType: 'EPUB' as const, + startTime: '2024-01-01T00:00:00Z', + endTime: '2024-01-01T00:10:00Z', + durationSeconds: 600, + durationFormatted: '10m 0s', + }; + const sendBeaconSpy = vi.fn(); + Object.defineProperty(navigator, 'sendBeacon', { + configurable: true, + value: sendBeaconSpy, + }); + + sendBeaconSpy.mockReturnValue(true); + expect(service.sendSessionBeacon(session)).toBe(true); + + sendBeaconSpy.mockImplementation(() => { + throw new Error('unsupported'); + }); + expect(service.sendSessionBeacon(session)).toBe(false); + }); +}); diff --git a/frontend/src/app/shared/service/reading-session.service.spec.ts b/frontend/src/app/shared/service/reading-session.service.spec.ts new file mode 100644 index 000000000..0d55d6c17 --- /dev/null +++ b/frontend/src/app/shared/service/reading-session.service.spec.ts @@ -0,0 +1,123 @@ +import {TestBed} from '@angular/core/testing'; +import {of} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {ReadingSessionApiService} from './reading-session-api.service'; +import {ReadingSessionService} from './reading-session.service'; + +describe('ReadingSessionService', () => { + let createSession: ReturnType; + let sendSessionBeacon: ReturnType; + let service: ReadingSessionService; + let hidden = false; + + beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-03-26T00:00:00Z')); + hidden = false; + + Object.defineProperty(document, 'hidden', { + configurable: true, + get: () => hidden, + }); + + createSession = vi.fn(() => of(void 0)); + sendSessionBeacon = vi.fn(() => true); + + TestBed.configureTestingModule({ + providers: [ + ReadingSessionService, + { + provide: ReadingSessionApiService, + useValue: { + createSession, + sendSessionBeacon, + }, + }, + ], + }); + + service = TestBed.inject(ReadingSessionService); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it('starts and tracks an active reading session', () => { + service.startSession(4, 'EPUB', 'chapter-1', 12.345); + + expect(service.isSessionActive()).toBe(true); + }); + + it('discards sessions that are shorter than the minimum duration', () => { + service.startSession(5, 'EPUB', 'start', 10); + service.updateProgress('middle', 25); + + vi.advanceTimersByTime(20_000); + service.endSession('end', 35); + + expect(createSession).not.toHaveBeenCalled(); + expect(service.isSessionActive()).toBe(false); + }); + + it('sends completed sessions to the backend with rounded progress values', () => { + service.startSession(6, 'PDF', 'page-1', 12.3456); + service.updateProgress('page-9', 45.6789); + + vi.advanceTimersByTime(31_000); + service.endSession(); + + expect(createSession).toHaveBeenCalledOnce(); + expect(createSession).toHaveBeenCalledWith(expect.objectContaining({ + bookId: 6, + bookType: 'PDF', + durationSeconds: 31, + durationFormatted: '31s', + startLocation: 'page-1', + endLocation: 'page-9', + startProgress: 12.35, + endProgress: 45.68, + progressDelta: 33.33, + })); + expect(service.isSessionActive()).toBe(false); + }); + + it('sends a beacon on unload for long enough active sessions', () => { + service.startSession(7, 'EPUB', 'cfi-1', 5); + service.updateProgress('cfi-2', 9.5); + + vi.advanceTimersByTime(35_000); + window.dispatchEvent(new Event('beforeunload')); + + expect(sendSessionBeacon).toHaveBeenCalledOnce(); + expect(sendSessionBeacon).toHaveBeenCalledWith(expect.objectContaining({ + bookId: 7, + bookType: 'EPUB', + durationSeconds: 35, + startLocation: 'cfi-1', + endLocation: 'cfi-2', + startProgress: 5, + endProgress: 9.5, + progressDelta: undefined, + })); + }); + + it('ends sessions that stay hidden longer than the idle timeout once the tab becomes visible again', () => { + service.startSession(8, 'EPUB', 'cfi-1', 1); + service.updateProgress('cfi-2', 5); + + hidden = true; + document.dispatchEvent(new Event('visibilitychange')); + + vi.advanceTimersByTime(5 * 60 * 1000 + 5_000); + + hidden = false; + document.dispatchEvent(new Event('visibilitychange')); + + expect(createSession).toHaveBeenCalledOnce(); + expect(service.isSessionActive()).toBe(false); + }); +}); diff --git a/frontend/src/app/shared/service/settings-helper.service.spec.ts b/frontend/src/app/shared/service/settings-helper.service.spec.ts new file mode 100644 index 000000000..4afb37d35 --- /dev/null +++ b/frontend/src/app/shared/service/settings-helper.service.spec.ts @@ -0,0 +1,79 @@ +import {TestBed} from '@angular/core/testing'; +import {MessageService} from 'primeng/api'; +import {firstValueFrom, of, throwError} from 'rxjs'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TranslocoService} from '@jsverse/transloco'; + +import {AppSettingsService} from './app-settings.service'; +import {SettingsHelperService} from './settings-helper.service'; + +describe('SettingsHelperService', () => { + const appSettingsService = { + saveSettings: vi.fn(), + }; + const messageService = { + add: vi.fn(), + }; + const translocoService = { + translate: vi.fn((key: string) => `translated:${key}`), + }; + + let service: SettingsHelperService; + + beforeEach(() => { + vi.restoreAllMocks(); + appSettingsService.saveSettings.mockReset(); + messageService.add.mockClear(); + translocoService.translate.mockClear(); + + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + SettingsHelperService, + {provide: AppSettingsService, useValue: appSettingsService}, + {provide: MessageService, useValue: messageService}, + {provide: TranslocoService, useValue: translocoService}, + ] + }); + + service = TestBed.inject(SettingsHelperService); + }); + + it('saves a setting and shows a success message', async () => { + appSettingsService.saveSettings.mockReturnValue(of(undefined)); + + await firstValueFrom(service.saveSetting('theme', 'dark')); + + expect(appSettingsService.saveSettings).toHaveBeenCalledWith([{key: 'theme', newValue: 'dark'}]); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'translated:shared.settingsHelper.settingsSavedSummary', + detail: 'translated:shared.settingsHelper.settingsSavedDetail', + }); + }); + + it('shows an error message when saving fails', async () => { + const error = new Error('save failed'); + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined); + appSettingsService.saveSettings.mockReturnValue(throwError(() => error)); + + await expect(firstValueFrom(service.saveSetting('theme', 'dark'))).rejects.toThrow('save failed'); + + expect(errorSpy).toHaveBeenCalledWith('Failed to save setting:', error); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'translated:common.error', + detail: 'translated:shared.settingsHelper.saveErrorDetail', + }); + }); + + it('forwards ad-hoc messages through the message service', () => { + service.showMessage('success', 'Saved', 'Everything worked'); + + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'Saved', + detail: 'Everything worked', + }); + }); +}); diff --git a/frontend/src/app/shared/service/startup.service.spec.ts b/frontend/src/app/shared/service/startup.service.spec.ts new file mode 100644 index 000000000..b5f64be55 --- /dev/null +++ b/frontend/src/app/shared/service/startup.service.spec.ts @@ -0,0 +1,62 @@ +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {describe, expect, it, vi} from 'vitest'; +import {QueryClient, queryOptions} from '@tanstack/angular-query-experimental'; + +import {AuthService} from './auth.service'; +import {StartupService} from './startup.service'; +import {UserService} from '../../features/settings/user-management/user.service'; + +describe('StartupService', () => { + it('loads the current user when a token is present', async () => { + const fetchQuery = vi.fn().mockResolvedValue({username: 'admin'}); + + TestBed.configureTestingModule({ + providers: [ + StartupService, + {provide: AuthService, useValue: {token: signal('token')}}, + { + provide: UserService, + useValue: { + getUserQueryOptions: () => queryOptions({ + queryKey: ['user'], + queryFn: async () => ({username: 'admin'}), + }), + }, + }, + {provide: QueryClient, useValue: {fetchQuery}}, + ] + }); + + const service = TestBed.inject(StartupService); + + await expect(service.load()).resolves.toBeUndefined(); + expect(fetchQuery).toHaveBeenCalledOnce(); + }); + + it('resolves immediately when there is no token', async () => { + const fetchQuery = vi.fn(); + + TestBed.configureTestingModule({ + providers: [ + StartupService, + {provide: AuthService, useValue: {token: signal(null)}}, + { + provide: UserService, + useValue: { + getUserQueryOptions: () => queryOptions({ + queryKey: ['user'], + queryFn: async () => ({username: 'admin'}), + }), + }, + }, + {provide: QueryClient, useValue: {fetchQuery}}, + ] + }); + + const service = TestBed.inject(StartupService); + + await expect(service.load()).resolves.toBeUndefined(); + expect(fetchQuery).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/app/shared/service/url-helper.service.spec.ts b/frontend/src/app/shared/service/url-helper.service.spec.ts new file mode 100644 index 000000000..6799e2ca2 --- /dev/null +++ b/frontend/src/app/shared/service/url-helper.service.spec.ts @@ -0,0 +1,155 @@ +import {TestBed} from '@angular/core/testing'; +import {Router} from '@angular/router'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {API_CONFIG} from '../../core/config/api-config'; +import {Book, BookType} from '../../features/book/model/book.model'; +import {BookService} from '../../features/book/service/book.service'; +import {CoverGeneratorComponent} from '../components/cover-generator/cover-generator.component'; +import {AuthService} from './auth.service'; +import {UrlHelperService} from './url-helper.service'; + +describe('UrlHelperService', () => { + const authServiceStub = { + getInternalAccessToken: vi.fn(), + }; + + const bookServiceStub = { + findBookById: vi.fn(), + }; + + const routerStub = { + createUrlTree: vi.fn((commands: unknown[], extras?: unknown) => ({commands, extras})), + }; + + let service: UrlHelperService; + + const bookWithMetadata = { + id: 42, + metadata: { + title: 'The Testing Atlas', + authors: ['Ada Lovelace', 'Grace Hopper'], + }, + } as Book; + + const supportedReadingRoutes: {bookType: BookType; readerSegment: string}[] = [ + {bookType: 'PDF', readerSegment: 'pdf-reader'}, + {bookType: 'EPUB', readerSegment: 'ebook-reader'}, + {bookType: 'FB2', readerSegment: 'ebook-reader'}, + {bookType: 'MOBI', readerSegment: 'ebook-reader'}, + {bookType: 'AZW3', readerSegment: 'ebook-reader'}, + {bookType: 'CBX', readerSegment: 'cbx-reader'}, + {bookType: 'AUDIOBOOK', readerSegment: 'audiobook-player'}, + ]; + + beforeEach(() => { + authServiceStub.getInternalAccessToken.mockReturnValue('token-123'); + bookServiceStub.findBookById.mockReset(); + bookServiceStub.findBookById.mockReturnValue(undefined); + routerStub.createUrlTree.mockClear(); + + TestBed.configureTestingModule({ + providers: [ + UrlHelperService, + {provide: AuthService, useValue: authServiceStub}, + {provide: BookService, useValue: bookServiceStub}, + {provide: Router, useValue: routerStub}, + ], + }); + + service = TestBed.inject(UrlHelperService); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('generates a portrait cover when cached metadata exists and no updated marker is provided', () => { + bookServiceStub.findBookById.mockReturnValue(bookWithMetadata); + + const generateCoverSpy = vi.spyOn(CoverGeneratorComponent.prototype, 'generateCover').mockImplementation(function (this: CoverGeneratorComponent) { + return `${this.title}|${this.author}|${this.isSquare ? 'square' : 'portrait'}`; + }); + + const url = service.getThumbnailUrl(42); + + expect(generateCoverSpy).toHaveBeenCalledTimes(1); + expect(url).toBe('The Testing Atlas|Ada Lovelace, Grace Hopper|portrait'); + }); + + it('appends the token to thumbnail urls that already have a cache key', () => { + const url = service.getThumbnailUrl(42, 'updated-2024'); + + expect(url).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/book/42/thumbnail?updated-2024&token=token-123`); + }); + + it('returns direct thumbnail and backup urls without a token when auth is unavailable', () => { + authServiceStub.getInternalAccessToken.mockReturnValue(null); + + expect(service.getDirectThumbnailUrl(42)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/book/42/thumbnail`); + expect(service.getBackupCoverUrl(42)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/book/42/backup-cover`); + }); + + it('generates a square audiobook cover when cached metadata exists', () => { + bookServiceStub.findBookById.mockReturnValue(bookWithMetadata); + + const generateCoverSpy = vi.spyOn(CoverGeneratorComponent.prototype, 'generateCover').mockImplementation(function (this: CoverGeneratorComponent) { + return `${this.title}|${this.author}|${this.isSquare ? 'square' : 'portrait'}`; + }); + + const url = service.getAudiobookCoverUrl(42); + + expect(generateCoverSpy).toHaveBeenCalledTimes(1); + expect(url).toBe('The Testing Atlas|Ada Lovelace, Grace Hopper|square'); + }); + + it('uses the audiobook media url when an updated marker is present', () => { + expect(service.getAudiobookThumbnailUrl(42, 'updated-2024')).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/book/42/audiobook-thumbnail?updated-2024&token=token-123`); + }); + + it.each(supportedReadingRoutes)('routes %s books to the correct reader path', ({bookType, readerSegment}: {bookType: BookType; readerSegment: string}) => { + const book = { + id: 77, + primaryFile: {bookType}, + } as Book; + + expect(service.getBookPrimaryReadingUrl(book)).toEqual({ + commands: [`/${readerSegment}/book/77`], + extras: undefined, + }); + }); + + it('falls back to the book page for unsupported primary file types', () => { + const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined); + const book = { + id: 88, + primaryFile: {bookType: undefined}, + } as Book; + + expect(service.getBookPrimaryReadingUrl(book)).toEqual({ + commands: ['/book', 88], + extras: {queryParams: {tab: 'view'}}, + }); + expect(consoleErrorSpy).toHaveBeenCalledWith('Unsupported book type:', undefined); + }); + + it('builds series and generic book filters with the expected router shape', () => { + expect(service.filterBooksBy('series', 'The Wheel of Time')).toEqual({ + commands: ['/series', 'The Wheel of Time'], + extras: undefined, + }); + + expect(service.filterBooksBy('author', 'Ursula K. Le Guin')).toEqual({ + commands: ['/all-books'], + extras: { + queryParams: { + view: 'grid', + sort: 'title', + direction: 'asc', + sidebar: true, + filter: 'author:Ursula%20K.%20Le%20Guin', + }, + }, + }); + }); +}); diff --git a/frontend/src/app/shared/service/version.service.spec.ts b/frontend/src/app/shared/service/version.service.spec.ts new file mode 100644 index 000000000..4c17db7a2 --- /dev/null +++ b/frontend/src/app/shared/service/version.service.spec.ts @@ -0,0 +1,62 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {API_CONFIG} from '../../core/config/api-config'; +import {VersionService} from './version.service'; + +describe('VersionService', () => { + let service: VersionService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + VersionService, + ] + }); + + service = TestBed.inject(VersionService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('fetches the current application version', () => { + service.getVersion().subscribe(version => { + expect(version).toEqual({current: '1.0.0', latest: '1.0.1'}); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/version`); + expect(request.request.method).toBe('GET'); + request.flush({current: '1.0.0', latest: '1.0.1'}); + }); + + it('fetches the changelog entries', () => { + service.getChangelog().subscribe(entries => { + expect(entries).toEqual([{ + version: '1.0.1', + name: 'Patch release', + changelog: 'Bug fixes', + url: 'https://example.test/release/1.0.1', + publishedAt: '2026-03-26T00:00:00Z', + }]); + }); + + const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/version/changelog`); + expect(request.request.method).toBe('GET'); + request.flush([{ + version: '1.0.1', + name: 'Patch release', + changelog: 'Bug fixes', + url: 'https://example.test/release/1.0.1', + publishedAt: '2026-03-26T00:00:00Z', + }]); + }); +}); diff --git a/frontend/src/app/shared/services/book-cover.service.spec.ts b/frontend/src/app/shared/services/book-cover.service.spec.ts new file mode 100644 index 000000000..5ba14e3c3 --- /dev/null +++ b/frontend/src/app/shared/services/book-cover.service.spec.ts @@ -0,0 +1,53 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it} from 'vitest'; + +import {BookCoverService, CoverFetchRequest, CoverImage} from './book-cover.service'; + +describe('BookCoverService', () => { + let service: BookCoverService; + let httpTestingController: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + BookCoverService, + ], + }); + + service = TestBed.inject(BookCoverService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + }); + + it('posts the cover fetch request and returns the backend response', () => { + const requestBody: CoverFetchRequest = { + title: 'Dune', + author: 'Frank Herbert', + coverType: 'ebook', + }; + const response: CoverImage[] = [ + {url: 'https://example.test/cover-1.jpg', source: 'google', width: 600, height: 900, index: 0}, + {url: 'https://example.test/cover-2.jpg', source: 'openlibrary', index: 1}, + ]; + + let result: CoverImage[] | undefined; + service.fetchBookCovers(requestBody).subscribe(value => { + result = value; + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/1/metadata/covers')); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual(requestBody); + request.flush(response); + + expect(result).toEqual(response); + }); +}); diff --git a/frontend/src/app/shared/services/dialog-launcher.service.spec.ts b/frontend/src/app/shared/services/dialog-launcher.service.spec.ts new file mode 100644 index 000000000..0639f1d45 --- /dev/null +++ b/frontend/src/app/shared/services/dialog-launcher.service.spec.ts @@ -0,0 +1,81 @@ +import {TestBed} from '@angular/core/testing'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {DialogService} from 'primeng/dynamicdialog'; + +import {DashboardSettingsComponent} from '../../features/dashboard/components/dashboard-settings/dashboard-settings.component'; +import {LibraryCreatorComponent} from '../../features/library-creator/library-creator.component'; +import {DialogLauncherService, DialogSize, DialogStyle} from './dialog-launcher.service'; + +describe('DialogLauncherService', () => { + const dialogRef = {close: vi.fn()}; + const dialogService = { + open: vi.fn(() => dialogRef), + }; + + let service: DialogLauncherService; + + beforeEach(() => { + vi.restoreAllMocks(); + dialogService.open.mockClear(); + + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + DialogLauncherService, + {provide: DialogService, useValue: dialogService}, + ] + }); + + service = TestBed.inject(DialogLauncherService); + }); + + it('merges the default dialog options with caller overrides', () => { + service.openDialog(LibraryCreatorComponent, { + showHeader: false, + data: {mode: 'create'}, + }); + + expect(dialogService.open).toHaveBeenCalledWith( + LibraryCreatorComponent, + expect.objectContaining({ + baseZIndex: 10, + closable: true, + dismissableMask: true, + draggable: false, + modal: true, + resizable: false, + showHeader: false, + maximizable: false, + data: {mode: 'create'}, + }) + ); + }); + + it('opens the dashboard settings dialog with the expected style class', () => { + service.openDashboardSettingsDialog(); + + expect(dialogService.open).toHaveBeenCalledWith( + DashboardSettingsComponent, + expect.objectContaining({ + showHeader: false, + styleClass: `${DialogSize.XL} ${DialogStyle.MINIMAL}`, + }) + ); + }); + + it('passes the library id into the library edit dialog', () => { + service.openLibraryEditDialog(12); + + expect(dialogService.open).toHaveBeenCalledWith( + LibraryCreatorComponent, + expect.objectContaining({ + showHeader: false, + styleClass: `${DialogSize.MD} ${DialogStyle.MINIMAL}`, + data: { + mode: 'edit', + libraryId: 12, + }, + }) + ); + }); +}); diff --git a/frontend/src/app/shared/services/icon-cache.service.spec.ts b/frontend/src/app/shared/services/icon-cache.service.spec.ts new file mode 100644 index 000000000..7a6bf5d04 --- /dev/null +++ b/frontend/src/app/shared/services/icon-cache.service.spec.ts @@ -0,0 +1,21 @@ +import {describe, expect, it} from 'vitest'; + +import {IconCacheService} from './icon-cache.service'; + +describe('IconCacheService', () => { + it('stores, retrieves, removes, and sorts cached icon names', () => { + const service = new IconCacheService(); + const sanitized = {id: 'sanitized'} as never; + + expect(service.getCachedSanitized('missing')).toBeNull(); + + service.cacheIcon('beta', '', sanitized); + service.cacheIcon('alpha', '', sanitized); + + expect(service.getCachedSanitized('alpha')).toBe(sanitized); + expect(service.getAllIconNames()).toEqual(['alpha', 'beta']); + expect(service.removeIcon('beta')).toBe(true); + expect(service.getCachedSanitized('beta')).toBeNull(); + expect(service.removeIcon('beta')).toBe(false); + }); +}); diff --git a/frontend/src/app/shared/services/icon.service.spec.ts b/frontend/src/app/shared/services/icon.service.spec.ts new file mode 100644 index 000000000..c8e2116ca --- /dev/null +++ b/frontend/src/app/shared/services/icon.service.spec.ts @@ -0,0 +1,145 @@ +import {provideHttpClient} from '@angular/common/http'; +import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; +import {DomSanitizer, SafeHtml} from '@angular/platform-browser'; +import {TestBed} from '@angular/core/testing'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {IconCacheService} from './icon-cache.service'; +import {IconService} from './icon.service'; + +describe('IconService', () => { + let service: IconService; + let httpTestingController: HttpTestingController; + let iconCache: { + getCachedSanitized: ReturnType; + cacheIcon: ReturnType; + removeIcon: ReturnType; + }; + let bypassSecurityTrustHtml: ReturnType; + + beforeEach(() => { + iconCache = { + getCachedSanitized: vi.fn(() => null), + cacheIcon: vi.fn(), + removeIcon: vi.fn(), + }; + bypassSecurityTrustHtml = vi.fn(value => value as SafeHtml); + + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + IconService, + { + provide: IconCacheService, + useValue: iconCache, + }, + { + provide: DomSanitizer, + useValue: {bypassSecurityTrustHtml}, + }, + ], + }); + + service = TestBed.inject(IconService); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpTestingController.verify(); + TestBed.resetTestingModule(); + vi.restoreAllMocks(); + }); + + it('maps icon names from the paged response shape', () => { + let result: string[] | undefined; + service.getIconNames(2, 25).subscribe(value => { + result = value; + }); + + const request = httpTestingController.expectOne(req => req.url.includes('/api/v1/icons?page=2&size=25')); + expect(request.request.method).toBe('GET'); + request.flush({content: ['sun', 'moon']}); + + expect(result).toEqual(['sun', 'moon']); + }); + + it('short-circuits svg content requests when the sanitized icon is already cached', () => { + iconCache.getCachedSanitized.mockReturnValue('cached-safe-html' as SafeHtml); + + let result: string | undefined; + service.getSvgIconContent('sun').subscribe(value => { + result = value; + }); + + httpTestingController.expectNone(req => req.url.includes('/api/v1/icons/sun/content')); + expect(result).toBe(''); + }); + + it('fetches svg content, sanitizes it, and caches the result', () => { + let result: string | undefined; + service.getSvgIconContent('sun').subscribe(value => { + result = value; + }); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/icons/sun/content')); + expect(request.request.method).toBe('GET'); + expect(request.request.responseType).toBe('text'); + request.flush(''); + + expect(result).toBe(''); + expect(bypassSecurityTrustHtml).toHaveBeenCalled(); + expect(iconCache.cacheIcon).toHaveBeenCalledWith( + 'sun', + '', + expect.stringContaining('') + ); + }); + + it('returns cached sanitized svg content without issuing a request', () => { + iconCache.getCachedSanitized.mockReturnValue('cached-safe-html' as SafeHtml); + + let result: SafeHtml | undefined; + service.getSanitizedSvgContent('moon').subscribe(value => { + result = value; + }); + + httpTestingController.expectNone(req => req.url.includes('/api/v1/icons/moon/content')); + expect(result).toBe('cached-safe-html'); + }); + + it('removes icons from the cache after deletion', () => { + service.deleteSvgIcon('sun rise').subscribe(); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/icons/sun%20rise')); + expect(request.request.method).toBe('DELETE'); + request.flush(null); + + expect(iconCache.removeIcon).toHaveBeenCalledWith('sun rise'); + }); + + it('caches only successfully saved icons from batch saves', () => { + const icons = [ + {svgName: 'sun', svgData: 'sun'}, + {svgName: 'moon', svgData: 'moon'}, + ]; + + service.saveBatchSvgIcons(icons).subscribe(); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/icons/batch')); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual({icons}); + request.flush({ + totalRequested: 2, + successCount: 1, + failureCount: 1, + results: [ + {iconName: 'sun', success: true, errorMessage: ''}, + {iconName: 'moon', success: false, errorMessage: 'duplicate'}, + ], + }); + + expect(iconCache.cacheIcon).toHaveBeenCalledTimes(1); + expect(iconCache.cacheIcon).toHaveBeenCalledWith('sun', 'sun', 'sun'); + }); +}); diff --git a/frontend/src/app/shared/util/custom-font.util.spec.ts b/frontend/src/app/shared/util/custom-font.util.spec.ts new file mode 100644 index 000000000..4700bcc53 --- /dev/null +++ b/frontend/src/app/shared/util/custom-font.util.spec.ts @@ -0,0 +1,51 @@ +import {describe, expect, it} from 'vitest'; + +import {FontFormat} from '../model/custom-font.model'; +import {addCustomFontsToDropdown} from './custom-font.util'; + +describe('custom-font.util', () => { + it('does nothing when no custom fonts are supplied', () => { + const selectItems = [{label: 'System', value: 'system'}]; + const preferenceItems = [{name: 'System', displayName: 'System', key: 'system'}]; + + addCustomFontsToDropdown([], selectItems, 'select'); + addCustomFontsToDropdown([], preferenceItems, 'preference'); + + expect(selectItems).toEqual([{label: 'System', value: 'system'}]); + expect(preferenceItems).toEqual([{name: 'System', displayName: 'System', key: 'system'}]); + }); + + it('appends custom fonts to a select dropdown and removes stale separators', () => { + const selectItems = [ + {label: 'System', value: 'system'}, + {label: 'Separator', value: 'separator'}, + ]; + + addCustomFontsToDropdown([ + {id: 7, fontName: 'Bookerly', originalFileName: 'Bookerly.ttf', format: FontFormat.TTF, fileSize: 10, uploadedAt: '2026-03-26T00:00:00Z'}, + {id: 8, fontName: 'Atkinson Hyperlegible', originalFileName: 'Atkinson.ttf', format: FontFormat.TTF, fileSize: 10, uploadedAt: '2026-03-26T00:00:00Z'}, + ], selectItems, 'select'); + + expect(selectItems).toEqual([ + {label: 'System', value: 'system'}, + {label: 'Bookerly', value: 'custom:7'}, + {label: 'Atkinson Hyperlegible', value: 'custom:8'}, + ]); + }); + + it('appends custom fonts to a preference dropdown with truncated display names', () => { + const preferenceItems = [ + {name: 'System', displayName: 'System', key: 'system'}, + {name: 'Separator', displayName: 'Separator', key: 'separator'}, + ]; + + addCustomFontsToDropdown([ + {id: 9, fontName: 'Very Long Font Name', originalFileName: 'Font.ttf', format: FontFormat.TTF, fileSize: 10, uploadedAt: '2026-03-26T00:00:00Z'}, + ], preferenceItems, 'preference'); + + expect(preferenceItems).toEqual([ + {name: 'System', displayName: 'System', key: 'system'}, + {name: 'Very Long Font Name', displayName: 'Very Long Fo', key: 'custom:9'}, + ]); + }); +}); diff --git a/frontend/src/app/shared/util/pattern-resolver.spec.ts b/frontend/src/app/shared/util/pattern-resolver.spec.ts new file mode 100644 index 000000000..5de1ad241 --- /dev/null +++ b/frontend/src/app/shared/util/pattern-resolver.spec.ts @@ -0,0 +1,45 @@ +import {describe, expect, it} from 'vitest'; + +import {applyModifier, replacePlaceholders} from './pattern-resolver'; + +describe('pattern-resolver', () => { + it('returns the original value when the modifier is unknown or the value is empty', () => { + expect(applyModifier('', 'upper', 'title')).toBe(''); + expect(applyModifier('Alpha', 'unknown', 'title')).toBe('Alpha'); + }); + + it('applies the supported value modifiers', () => { + expect(applyModifier('Ada Lovelace, Grace Hopper', 'first', 'authors')).toBe('Ada Lovelace'); + expect(applyModifier('Ada Lovelace', 'sort', 'authors')).toBe('Lovelace, Ada'); + expect(applyModifier('Ada Lovelace', 'initial', 'authors')).toBe('L'); + expect(applyModifier('Chapter One', 'initial', 'title')).toBe('C'); + expect(applyModifier('Ada', 'upper', 'title')).toBe('ADA'); + expect(applyModifier('ADA', 'lower', 'title')).toBe('ada'); + }); + + it('replaces placeholders and respects optional fallback blocks', () => { + expect( + replacePlaceholders('<{title}|{fallback}> by {authors:first}', { + title: 'The Book', + authors: 'Ada Lovelace, Grace Hopper', + fallback: 'Fallback Title', + }) + ).toBe('The Book by Ada Lovelace'); + + expect( + replacePlaceholders('<{title}|{fallback}> by {authors:first}', { + authors: 'Ada Lovelace, Grace Hopper', + fallback: 'Fallback Title', + }) + ).toBe('Fallback Title by Ada Lovelace'); + }); + + it('handles nested modifier blocks and trims the final pattern', () => { + expect( + replacePlaceholders(' {authors:sort} - {title:upper} ', { + authors: 'Ada Lovelace, Grace Hopper', + title: 'calculus notes', + }) + ).toBe('Lovelace, Ada - CALCULUS NOTES'); + }); +}); diff --git a/frontend/src/app/shared/validators/password-match.validator.spec.ts b/frontend/src/app/shared/validators/password-match.validator.spec.ts new file mode 100644 index 000000000..96d94e2db --- /dev/null +++ b/frontend/src/app/shared/validators/password-match.validator.spec.ts @@ -0,0 +1,37 @@ +import {describe, expect, it} from 'vitest'; + +import {passwordMatchValidator} from './password-match.validator'; + +describe('passwordMatchValidator', () => { + it('returns null until both values are present', () => { + const validator = passwordMatchValidator('password', 'confirmPassword'); + const form = { + get: (name: string) => ({value: name === 'password' ? '' : ''}), + }; + + expect(validator(form as never)).toBeNull(); + + const withPassword = { + get: (name: string) => ({value: name === 'password' ? 'secret' : ''}), + }; + expect(validator(withPassword as never)).toBeNull(); + }); + + it('flags mismatched passwords', () => { + const validator = passwordMatchValidator('password', 'confirmPassword'); + const form = { + get: (name: string) => ({value: name === 'password' ? 'secret' : 'other'}), + }; + + expect(validator(form as never)).toEqual({passwordMismatch: true}); + }); + + it('returns null for matching passwords', () => { + const validator = passwordMatchValidator('password', 'confirmPassword'); + const form = { + get: (name: string) => ({value: name === 'password' ? 'secret' : 'secret'}), + }; + + expect(validator(form as never)).toBeNull(); + }); +}); diff --git a/frontend/src/app/shared/websocket/model/log-notification.model.spec.ts b/frontend/src/app/shared/websocket/model/log-notification.model.spec.ts new file mode 100644 index 000000000..8801fa9a2 --- /dev/null +++ b/frontend/src/app/shared/websocket/model/log-notification.model.spec.ts @@ -0,0 +1,29 @@ +import {describe, expect, it} from 'vitest'; + +import {parseLogNotification, Severity} from './log-notification.model'; + +describe('log-notification.model', () => { + it('parses message bodies with timestamp and severity', () => { + const parsed = parseLogNotification(JSON.stringify({ + timestamp: '2026-03-26T12:34:56.000Z', + message: 'Library scan completed', + severity: 'WARN' + })); + + expect(parsed.message).toBe('Library scan completed'); + expect(parsed.severity).toBe(Severity.WARN); + expect(parsed.timestamp).toMatch(/\d{1,2}:\d{2}:\d{2}/); + }); + + it('leaves optional fields undefined when they are not provided', () => { + expect(parseLogNotification(JSON.stringify({message: 'hello'}))).toEqual({ + message: 'hello', + severity: undefined, + timestamp: undefined + }); + }); + + it('throws on invalid JSON payloads', () => { + expect(() => parseLogNotification('not-json')).toThrow(SyntaxError); + }); +}); diff --git a/frontend/src/app/shared/websocket/notification-event.service.spec.ts b/frontend/src/app/shared/websocket/notification-event.service.spec.ts new file mode 100644 index 000000000..75e35a662 --- /dev/null +++ b/frontend/src/app/shared/websocket/notification-event.service.spec.ts @@ -0,0 +1,59 @@ +import {beforeEach, afterEach, describe, expect, it, vi} from 'vitest'; + +import {Severity} from './model/log-notification.model'; +import {NotificationEventService} from './notification-event.service'; + +describe('NotificationEventService', () => { + let service: NotificationEventService; + + beforeEach(() => { + vi.useFakeTimers(); + service = new NotificationEventService(); + }); + + afterEach(() => { + vi.runOnlyPendingTimers(); + vi.useRealTimers(); + }); + + it('emits the latest notification and highlights it immediately', () => { + const notifications: string[] = []; + const highlights: boolean[] = []; + + service.latestNotification$.subscribe(notification => notifications.push(notification.message)); + service.notificationHighlight$.subscribe(value => highlights.push(value)); + + service.handleNewNotification({message: 'Index updated', severity: Severity.INFO}); + + expect(notifications).toEqual(['Index updated']); + expect(highlights.at(-1)).toBe(true); + }); + + it('turns off the highlight after the timeout elapses', () => { + const highlights: boolean[] = []; + + service.notificationHighlight$.subscribe(value => highlights.push(value)); + service.handleNewNotification({message: 'Index updated', severity: Severity.INFO}); + + vi.advanceTimersByTime(7500); + + expect(highlights).toEqual([false, true, false]); + }); + + it('restarts the highlight timeout when a new notification arrives', () => { + const highlights: boolean[] = []; + + service.notificationHighlight$.subscribe(value => highlights.push(value)); + service.handleNewNotification({message: 'First', severity: Severity.INFO}); + vi.advanceTimersByTime(5000); + + service.handleNewNotification({message: 'Second', severity: Severity.WARN}); + vi.advanceTimersByTime(7499); + + expect(highlights.at(-1)).toBe(true); + + vi.advanceTimersByTime(1); + + expect(highlights.at(-1)).toBe(false); + }); +}); diff --git a/frontend/src/app/shared/websocket/rx-stomp-service-factory.spec.ts b/frontend/src/app/shared/websocket/rx-stomp-service-factory.spec.ts new file mode 100644 index 000000000..4cc0536a9 --- /dev/null +++ b/frontend/src/app/shared/websocket/rx-stomp-service-factory.spec.ts @@ -0,0 +1,38 @@ +import {Injector, runInInjectionContext} from '@angular/core'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; + +import {AuthService} from '../service/auth.service'; +import {rxStompServiceFactory} from './rx-stomp-service-factory'; +import {RxStompService} from './rx-stomp.service'; + +describe('rxStompServiceFactory', () => { + const authService = { + getInternalAccessToken: vi.fn<() => string | null>(), + }; + + beforeEach(() => { + vi.restoreAllMocks(); + authService.getInternalAccessToken.mockReset(); + }); + + it('creates an RxStompService and configures it from the auth service', () => { + const configureSpy = vi.spyOn(RxStompService.prototype, 'configure'); + const injector = Injector.create({ + providers: [ + {provide: AuthService, useValue: authService}, + ] + }); + + const service = runInInjectionContext( + injector, + () => rxStompServiceFactory(authService as unknown as AuthService) + ); + + expect(service).toBeInstanceOf(RxStompService); + expect(configureSpy).toHaveBeenCalled(); + + const lastConfig = configureSpy.mock.calls.at(-1)?.[0]; + expect(lastConfig?.brokerURL).toBeDefined(); + expect(lastConfig?.beforeConnect).toBeTypeOf('function'); + }); +}); diff --git a/frontend/src/app/shared/websocket/rx-stomp.config.spec.ts b/frontend/src/app/shared/websocket/rx-stomp.config.spec.ts new file mode 100644 index 000000000..400de4b52 --- /dev/null +++ b/frontend/src/app/shared/websocket/rx-stomp.config.spec.ts @@ -0,0 +1,57 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; + +import {API_CONFIG} from '../../core/config/api-config'; +import {AuthService} from '../service/auth.service'; +import {createRxStompConfig} from './rx-stomp.config'; + +type BeforeConnectTarget = Parameters['beforeConnect']>>[0]; + +describe('createRxStompConfig', () => { + const authService = { + getInternalAccessToken: vi.fn<() => string | null>(), + }; + + beforeEach(() => { + vi.restoreAllMocks(); + authService.getInternalAccessToken.mockReset(); + }); + + it('returns the expected connection defaults', () => { + const config = createRxStompConfig(authService as unknown as AuthService); + + expect(config.brokerURL).toBe(API_CONFIG.BROKER_URL); + expect(config.heartbeatIncoming).toBe(0); + expect(config.heartbeatOutgoing).toBe(20000); + expect(config.reconnectDelay).toBe(10000); + }); + + it('injects the bearer token into connect headers when one is available', () => { + authService.getInternalAccessToken.mockReturnValue('access-token'); + const config = createRxStompConfig(authService as unknown as AuthService); + const stomp = { + stompClient: { + connectHeaders: {}, + } + }; + + config.beforeConnect?.(stomp as unknown as BeforeConnectTarget); + + expect(stomp.stompClient.connectHeaders).toEqual({ + Authorization: 'Bearer access-token', + }); + }); + + it('does not add authorization headers when there is no access token', () => { + authService.getInternalAccessToken.mockReturnValue(null); + const config = createRxStompConfig(authService as unknown as AuthService); + const stomp = { + stompClient: { + connectHeaders: {}, + } + }; + + config.beforeConnect?.(stomp as unknown as BeforeConnectTarget); + + expect(stomp.stompClient.connectHeaders).toEqual({}); + }); +}); diff --git a/frontend/src/app/shared/websocket/rx-stomp.service.spec.ts b/frontend/src/app/shared/websocket/rx-stomp.service.spec.ts new file mode 100644 index 000000000..ea5816a33 --- /dev/null +++ b/frontend/src/app/shared/websocket/rx-stomp.service.spec.ts @@ -0,0 +1,45 @@ +import {TestBed} from '@angular/core/testing'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {RxStompConfig} from '@stomp/rx-stomp'; + +import {AuthService} from '../service/auth.service'; +import {RxStompService} from './rx-stomp.service'; + +describe('RxStompService', () => { + const authService = { + getInternalAccessToken: vi.fn<() => string | null>(), + }; + + beforeEach(() => { + vi.restoreAllMocks(); + authService.getInternalAccessToken.mockReset(); + + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + RxStompService, + {provide: AuthService, useValue: authService}, + ] + }); + }); + + it('configures the stomp client when it is created', () => { + const configureSpy = vi.spyOn(RxStompService.prototype, 'configure'); + const service = TestBed.inject(RxStompService); + + expect(service).toBeInstanceOf(RxStompService); + expect(configureSpy).toHaveBeenCalled(); + const initialConfig = configureSpy.mock.calls[0]?.[0]; + expect(initialConfig?.beforeConnect).toBeTypeOf('function'); + }); + + it('delegates updateConfig to configure', () => { + const service = TestBed.inject(RxStompService); + const configureSpy = vi.spyOn(service, 'configure'); + const config = {brokerURL: 'ws://example.test'} as RxStompConfig; + + service.updateConfig(config); + + expect(configureSpy).toHaveBeenCalledWith(config); + }); +}); diff --git a/frontend/src/chartjs-plugin-datalabels.d.ts b/frontend/src/chartjs-plugin-datalabels.d.ts new file mode 100644 index 000000000..8cfb39bc6 --- /dev/null +++ b/frontend/src/chartjs-plugin-datalabels.d.ts @@ -0,0 +1,3 @@ +import 'chartjs-plugin-datalabels'; + +export {}; diff --git a/frontend/src/test-setup.ts b/frontend/src/test-setup.ts index ad77e8484..6e7fdc837 100644 --- a/frontend/src/test-setup.ts +++ b/frontend/src/test-setup.ts @@ -1,5 +1,8 @@ +import '@angular/compiler'; import 'zone.js'; import 'zone.js/testing'; +import '@testing-library/jest-dom/vitest'; +import 'vitest-canvas-mock'; import {TestBed} from '@angular/core/testing'; import {BrowserDynamicTestingModule, platformBrowserDynamicTesting} from '@angular/platform-browser-dynamic/testing'; @@ -7,6 +10,91 @@ declare global { var __ANGULAR_TESTBED_INITIALIZED__: boolean | undefined; } +class MockResizeObserver { + observe(): undefined { return undefined; } + unobserve(): undefined { return undefined; } + disconnect(): undefined { return undefined; } +} + +class MockIntersectionObserver { + readonly root = null; + readonly rootMargin = ''; + readonly thresholds = [0]; + + observe(): undefined { return undefined; } + unobserve(): undefined { return undefined; } + disconnect(): undefined { return undefined; } + takeRecords(): IntersectionObserverEntry[] { + return []; + } +} + +if (!globalThis.matchMedia) { + globalThis.matchMedia = (query: string): MediaQueryList => ({ + matches: false, + media: query, + onchange: null, + addEventListener: () => undefined, + removeEventListener: () => undefined, + addListener: () => undefined, + removeListener: () => undefined, + dispatchEvent: () => false, + }); +} + +if (!globalThis.ResizeObserver) { + globalThis.ResizeObserver = MockResizeObserver as typeof ResizeObserver; +} + +if (!globalThis.IntersectionObserver) { + globalThis.IntersectionObserver = MockIntersectionObserver as typeof IntersectionObserver; +} + +if (!globalThis.PointerEvent) { + globalThis.PointerEvent = MouseEvent as typeof PointerEvent; +} + +if (!globalThis.DOMRect) { + globalThis.DOMRect = class DOMRectMock implements DOMRect { + bottom = 0; + height = 0; + left = 0; + right = 0; + top = 0; + width = 0; + x = 0; + y = 0; + toJSON(): Record { + return { + bottom: this.bottom, + height: this.height, + left: this.left, + right: this.right, + top: this.top, + width: this.width, + x: this.x, + y: this.y + }; + } + } as typeof DOMRect; +} + +if (!window.scrollTo) { + window.scrollTo = () => undefined; +} + +if (!window.HTMLElement.prototype.scrollIntoView) { + window.HTMLElement.prototype.scrollIntoView = () => undefined; +} + +if (!window.URL.createObjectURL) { + window.URL.createObjectURL = () => 'blob:mock-url'; +} + +if (!window.URL.revokeObjectURL) { + window.URL.revokeObjectURL = () => undefined; +} + // Only initialize if not already initialized if (!globalThis.__ANGULAR_TESTBED_INITIALIZED__) { globalThis.__ANGULAR_TESTBED_INITIALIZED__ = true; diff --git a/frontend/vitest-base.config.ts b/frontend/vitest-base.config.ts index dbad6285e..466daa710 100644 --- a/frontend/vitest-base.config.ts +++ b/frontend/vitest-base.config.ts @@ -1,12 +1,30 @@ import {defineConfig} from 'vitest/config'; +import angular from '@analogjs/vite-plugin-angular'; + +const shouldEnforceCoverageGate = process.env.COVERAGE_GATE === '1'; export default defineConfig({ + plugins: [angular({tsconfig: 'tsconfig.spec.json'})], test: { + globals: true, environment: 'jsdom', isolate: true, reporters: [ ['default', {summary: false}], ['junit', {outputFile: 'test-results/vitest-results.xml'}] - ] - }, + ], + coverage: { + provider: 'v8', + reporter: ['text', 'html', 'json', 'json-summary', 'lcov'], + reportsDirectory: 'coverage/grimmory', + include: ['src/app/**/*.ts', 'src/main.ts'], + exclude: ['src/app/**/*.spec.ts', 'src/app/**/*.module.ts', 'src/**/*.d.ts'], + thresholds: shouldEnforceCoverageGate ? { + statements: 90, + branches: 90, + functions: 90, + lines: 90 + } : undefined + } + } }); diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.ts index b08410299..fe6dad5b4 100644 --- a/frontend/vitest.config.ts +++ b/frontend/vitest.config.ts @@ -1,21 +1,10 @@ -import {defineConfig} from 'vitest/config'; -import angular from '@analogjs/vite-plugin-angular'; +import {defineConfig, mergeConfig} from 'vitest/config'; -export default defineConfig({ - plugins: [angular({tsconfig: 'tsconfig.spec.json'})], +import baseConfig from './vitest-base.config'; + +export default mergeConfig(baseConfig, defineConfig({ test: { - globals: true, - environment: 'jsdom', include: ['src/**/*.spec.ts'], setupFiles: ['./src/test-setup.ts'], - sequence: { - hooks: 'stack' - }, - coverage: { - provider: 'v8', - reporter: ['text', 'html'], - include: ['src/app/**/*.ts'], - exclude: ['src/app/**/*.spec.ts', 'src/app/**/*.module.ts'] - } } -}); +})); diff --git a/frontend/yarn.lock b/frontend/yarn.lock index 5e11cae4f..a3111d5b0 100644 --- a/frontend/yarn.lock +++ b/frontend/yarn.lock @@ -5,10 +5,10 @@ __metadata: version: 8 cacheKey: 10c0 -"@acemir/cssom@npm:^0.9.31": - version: 0.9.31 - resolution: "@acemir/cssom@npm:0.9.31" - checksum: 10c0/cbfff98812642104ec3b37de1ad3a53f216ddc437e7b9276a23f46f2453844ea3c3f46c200bc4656a2f747fb26567560b3cc5183d549d119a758926551b5f566 +"@adobe/css-tools@npm:^4.4.0": + version: 4.4.4 + resolution: "@adobe/css-tools@npm:4.4.4" + checksum: 10c0/8f3e6cfaa5e6286e6f05de01d91d060425be2ebaef490881f5fe6da8bbdb336835c5d373ea337b0c3b0a1af4be048ba18780f0f6021d30809b4545922a7e13d9 languageName: node linkType: hard @@ -176,7 +176,7 @@ __metadata: languageName: node linkType: hard -"@analogjs/vite-plugin-angular@npm:^2.3.0": +"@analogjs/vite-plugin-angular@npm:^2.3.1": version: 2.3.1 resolution: "@analogjs/vite-plugin-angular@npm:2.3.1" dependencies: @@ -194,7 +194,7 @@ __metadata: languageName: node linkType: hard -"@analogjs/vitest-angular@npm:^2.3.0": +"@analogjs/vitest-angular@npm:^2.3.1": version: 2.3.1 resolution: "@analogjs/vitest-angular@npm:2.3.1" peerDependencies: @@ -210,19 +210,19 @@ __metadata: languageName: node linkType: hard -"@angular-devkit/architect@npm:0.2102.0": - version: 0.2102.0 - resolution: "@angular-devkit/architect@npm:0.2102.0" +"@angular-devkit/architect@npm:0.2102.4": + version: 0.2102.4 + resolution: "@angular-devkit/architect@npm:0.2102.4" dependencies: - "@angular-devkit/core": "npm:21.2.0" + "@angular-devkit/core": "npm:21.2.4" rxjs: "npm:7.8.2" bin: architect: bin/cli.js - checksum: 10c0/84a9877ac4596cd794e605aba834877152ff5a4f0d3c9c953c03259478d2e22d4786d39c29d1f77a0c979c34c786c81985971e9d44e633999a82940b9f1538e1 + checksum: 10c0/c433769fcce3c36ef58d019971c85ad04b1e640467748012295f943277e8fa4de6e4e6c44ee39df1de689abb49273dfb79b613b06228d64584dfe010c527b6b8 languageName: node linkType: hard -"@angular-devkit/architect@npm:0.2102.3, @angular-devkit/architect@npm:>= 0.2100.0 < 0.2200.0": +"@angular-devkit/architect@npm:>= 0.2100.0 < 0.2200.0": version: 0.2102.3 resolution: "@angular-devkit/architect@npm:0.2102.3" dependencies: @@ -234,25 +234,6 @@ __metadata: languageName: node linkType: hard -"@angular-devkit/core@npm:21.2.0": - version: 21.2.0 - resolution: "@angular-devkit/core@npm:21.2.0" - dependencies: - ajv: "npm:8.18.0" - ajv-formats: "npm:3.0.1" - jsonc-parser: "npm:3.3.1" - picomatch: "npm:4.0.3" - rxjs: "npm:7.8.2" - source-map: "npm:0.7.6" - peerDependencies: - chokidar: ^5.0.0 - peerDependenciesMeta: - chokidar: - optional: true - checksum: 10c0/ad0dd0ecdf39d6093b6a2fd4a65a7d02c507f5710c70a856ea532bd9a3cedc9c05e57161a5e63b824692f25d2c10b9c05cf8000ec729dfa120ce53ee8e79e2c0 - languageName: node - linkType: hard - "@angular-devkit/core@npm:21.2.3, @angular-devkit/core@npm:>= 21.0.0 < 22.0.0": version: 21.2.3 resolution: "@angular-devkit/core@npm:21.2.3" @@ -272,20 +253,39 @@ __metadata: languageName: node linkType: hard -"@angular-devkit/schematics@npm:21.2.0": - version: 21.2.0 - resolution: "@angular-devkit/schematics@npm:21.2.0" +"@angular-devkit/core@npm:21.2.4": + version: 21.2.4 + resolution: "@angular-devkit/core@npm:21.2.4" dependencies: - "@angular-devkit/core": "npm:21.2.0" + ajv: "npm:8.18.0" + ajv-formats: "npm:3.0.1" + jsonc-parser: "npm:3.3.1" + picomatch: "npm:4.0.3" + rxjs: "npm:7.8.2" + source-map: "npm:0.7.6" + peerDependencies: + chokidar: ^5.0.0 + peerDependenciesMeta: + chokidar: + optional: true + checksum: 10c0/21df09004478e64deaeed5c223c3887c4ee1aad56bcb7709f2fa697496fe57fa9a0f4994fcc7387d307a2b090517f18a3ac95ad832ff4b1431aed4b637ba6ef4 + languageName: node + linkType: hard + +"@angular-devkit/schematics@npm:21.2.4": + version: 21.2.4 + resolution: "@angular-devkit/schematics@npm:21.2.4" + dependencies: + "@angular-devkit/core": "npm:21.2.4" jsonc-parser: "npm:3.3.1" magic-string: "npm:0.30.21" ora: "npm:9.3.0" rxjs: "npm:7.8.2" - checksum: 10c0/28d4a30fa10955eeb336017dd555bb77f0312a4daf5f3f3d6de96c380dee6dc1c88c5f5dd66e90c3020662ba6d054258734be3517c14134102d2ee1e4a7bc8b4 + checksum: 10c0/1af6d8f6a72dadf8e2ed70b4fb7965d032e7da0ebcd5aa5a03e03343c7bba3cd7529eec0c70946ed5eb9aea12d89719e211338f3165bd6727e0a708ac98a7643 languageName: node linkType: hard -"@angular-devkit/schematics@npm:21.2.3, @angular-devkit/schematics@npm:>= 21.0.0 < 22.0.0": +"@angular-devkit/schematics@npm:>= 21.0.0 < 22.0.0": version: 21.2.3 resolution: "@angular-devkit/schematics@npm:21.2.3" dependencies: @@ -395,23 +395,23 @@ __metadata: languageName: node linkType: hard -"@angular/animations@npm:^21.2.4": - version: 21.2.5 - resolution: "@angular/animations@npm:21.2.5" +"@angular/animations@npm:^21.2.6": + version: 21.2.6 + resolution: "@angular/animations@npm:21.2.6" dependencies: tslib: "npm:^2.3.0" peerDependencies: - "@angular/core": 21.2.5 - checksum: 10c0/1926d8199512cde4f399a915b50e096d6c13ea183fab31d035e05b6245b543deaf960ceeb0f8b6110a7e8c51e16935d3297e7fc13d37ce60453d4c3fa692fb71 + "@angular/core": 21.2.6 + checksum: 10c0/5e111f805a2ba5b96c0488a50589c07f810676320c87b3d9bb53ac30007df1a546cccd1ee88b8c270260adfe79f45136c3eaa8b8fba10a84733116a6b91aaf38 languageName: node linkType: hard -"@angular/build@npm:^21.2.0": - version: 21.2.3 - resolution: "@angular/build@npm:21.2.3" +"@angular/build@npm:^21.2.4": + version: 21.2.4 + resolution: "@angular/build@npm:21.2.4" dependencies: "@ampproject/remapping": "npm:2.3.0" - "@angular-devkit/architect": "npm:0.2102.3" + "@angular-devkit/architect": "npm:0.2102.4" "@babel/core": "npm:7.29.0" "@babel/helper-annotate-as-pure": "npm:7.27.3" "@babel/helper-split-export-declaration": "npm:7.24.7" @@ -435,7 +435,7 @@ __metadata: semver: "npm:7.7.4" source-map-support: "npm:0.5.21" tinyglobby: "npm:0.2.15" - undici: "npm:7.22.0" + undici: "npm:7.24.4" vite: "npm:7.3.1" watchpack: "npm:2.5.1" peerDependencies: @@ -446,7 +446,7 @@ __metadata: "@angular/platform-browser": ^21.0.0 "@angular/platform-server": ^21.0.0 "@angular/service-worker": ^21.0.0 - "@angular/ssr": ^21.2.3 + "@angular/ssr": ^21.2.4 karma: ^6.4.0 less: ^4.2.0 ng-packagr: ^21.0.0 @@ -483,11 +483,11 @@ __metadata: optional: true vitest: optional: true - checksum: 10c0/53d515747ad8877b49858e4d88e657d4bc859e6aa18f98d79498144d3f3b3f4b40976474d34f05b80459f0a98493eaa6d9f7a032ed67a543ff6351751c80e5b8 + checksum: 10c0/19bbdd15f6e606c6b1b6e293840012d6f988da541cda54b15f22ef63be11eaae80f18ea07a35470d9143811c935b5e409abca58252363c58f8719386166aac46 languageName: node linkType: hard -"@angular/cdk@npm:^21.2.0": +"@angular/cdk@npm:^21.2.4": version: 21.2.4 resolution: "@angular/cdk@npm:21.2.4" dependencies: @@ -502,17 +502,17 @@ __metadata: languageName: node linkType: hard -"@angular/cli@npm:^21.2.0": - version: 21.2.3 - resolution: "@angular/cli@npm:21.2.3" +"@angular/cli@npm:^21.2.4": + version: 21.2.4 + resolution: "@angular/cli@npm:21.2.4" dependencies: - "@angular-devkit/architect": "npm:0.2102.3" - "@angular-devkit/core": "npm:21.2.3" - "@angular-devkit/schematics": "npm:21.2.3" + "@angular-devkit/architect": "npm:0.2102.4" + "@angular-devkit/core": "npm:21.2.4" + "@angular-devkit/schematics": "npm:21.2.4" "@inquirer/prompts": "npm:7.10.1" "@listr2/prompt-adapter-inquirer": "npm:3.0.5" "@modelcontextprotocol/sdk": "npm:1.26.0" - "@schematics/angular": "npm:21.2.3" + "@schematics/angular": "npm:21.2.4" "@yarnpkg/lockfile": "npm:1.1.0" algoliasearch: "npm:5.48.1" ini: "npm:6.0.0" @@ -526,25 +526,25 @@ __metadata: zod: "npm:4.3.6" bin: ng: bin/ng.js - checksum: 10c0/1c2a1d2cd8c0233ee8913645d43c32ed3d103737a1d5c7108217c3ce2604e1ad05df6dc233038d799765d1332f20d6915c90a374c5bba72a068d0cbe6c2e2f78 + checksum: 10c0/e6e83b3ca10f8e4bd846bf244f8d87216012fa56d7329307bad4330170a9e5051172a7cea91da1f940d899a556b7ad4a0edd75daba7ce06494dcd0573015e018 languageName: node linkType: hard -"@angular/common@npm:^21.2.4": - version: 21.2.5 - resolution: "@angular/common@npm:21.2.5" +"@angular/common@npm:^21.2.6": + version: 21.2.6 + resolution: "@angular/common@npm:21.2.6" dependencies: tslib: "npm:^2.3.0" peerDependencies: - "@angular/core": 21.2.5 + "@angular/core": 21.2.6 rxjs: ^6.5.3 || ^7.4.0 - checksum: 10c0/218f980d263100659585435f2a1bf034d240269bf4cfecbbc1d0cb079932eae4a81531ca0d7e5e022774799017f1b355b503f1ea37a928ad7db666eae9c91557 + checksum: 10c0/e446878beede7fe88ad1225a8b503def77870d3746ad4878c407d9bdfcabf35a91feb32d0a0e06c22b23c7039e4899e063fd10d18e2b2040a599960c1782ec14 languageName: node linkType: hard -"@angular/compiler-cli@npm:^21.2.4": - version: 21.2.5 - resolution: "@angular/compiler-cli@npm:21.2.5" +"@angular/compiler-cli@npm:^21.2.6": + version: 21.2.6 + resolution: "@angular/compiler-cli@npm:21.2.6" dependencies: "@babel/core": "npm:7.29.0" "@jridgewell/sourcemap-codec": "npm:^1.4.14" @@ -555,7 +555,7 @@ __metadata: tslib: "npm:^2.3.0" yargs: "npm:^18.0.0" peerDependencies: - "@angular/compiler": 21.2.5 + "@angular/compiler": 21.2.6 typescript: ">=5.9 <6.1" peerDependenciesMeta: typescript: @@ -563,26 +563,26 @@ __metadata: bin: ng-xi18n: bundles/src/bin/ng_xi18n.js ngc: bundles/src/bin/ngc.js - checksum: 10c0/5ebff72ead3bb46065f2d713b7da83f800e8c50ac2400506ed4ed66c6f669379bb2e325eaefe37ea2c81c3003d362ce1128416ee9a8545b74afdb49555ab492c + checksum: 10c0/cd88331cbcaa0d6be577b5126722b8ef3a765809c33c5a0d19498b3b1736d951a18529a79bfe2eb8676f13774729b69e09cca27b250ad99acd63eb7c1b911943 languageName: node linkType: hard -"@angular/compiler@npm:^21.2.4": - version: 21.2.5 - resolution: "@angular/compiler@npm:21.2.5" +"@angular/compiler@npm:^21.2.6": + version: 21.2.6 + resolution: "@angular/compiler@npm:21.2.6" dependencies: tslib: "npm:^2.3.0" - checksum: 10c0/6300dec4cc388bfcba8b68485d52f7117a1752f6496699d7adf0d30bc6cc9275da0d6f5ee15743cf68309717323f032de68fb2fbbaad4dfdcc676e5f218d071a + checksum: 10c0/4c857d61856e9bed86bf81d7e442a6ce513667860d122159ba95dd5b6daed1cd248183645353f80f5872a936325e6142063f74fc5f3cc430294ef8bca1fcc167 languageName: node linkType: hard -"@angular/core@npm:^21.2.4": - version: 21.2.5 - resolution: "@angular/core@npm:21.2.5" +"@angular/core@npm:^21.2.6": + version: 21.2.6 + resolution: "@angular/core@npm:21.2.6" dependencies: tslib: "npm:^2.3.0" peerDependencies: - "@angular/compiler": 21.2.5 + "@angular/compiler": 21.2.6 rxjs: ^6.5.3 || ^7.4.0 zone.js: ~0.15.0 || ~0.16.0 peerDependenciesMeta: @@ -590,80 +590,80 @@ __metadata: optional: true zone.js: optional: true - checksum: 10c0/9f7e8ab66fd2bca021d479dbf7c8d0f7cfc06e6cbf4db842766c99f2d5bbc180a5b5455e928f2e2840ece37a579e3d8fe6bdd3b4d662db1ba9dae0cc792f5e15 + checksum: 10c0/270d5c2e562720d95c8bb8de4c76fb4446ad588ef4eeb226b258bb33f24d0d608170990e107302ffc74cb68ec46724fc657bcba26cff154e74da3d7cb2a0513d languageName: node linkType: hard -"@angular/forms@npm:^21.2.4": - version: 21.2.5 - resolution: "@angular/forms@npm:21.2.5" +"@angular/forms@npm:^21.2.6": + version: 21.2.6 + resolution: "@angular/forms@npm:21.2.6" dependencies: "@standard-schema/spec": "npm:^1.0.0" tslib: "npm:^2.3.0" peerDependencies: - "@angular/common": 21.2.5 - "@angular/core": 21.2.5 - "@angular/platform-browser": 21.2.5 + "@angular/common": 21.2.6 + "@angular/core": 21.2.6 + "@angular/platform-browser": 21.2.6 rxjs: ^6.5.3 || ^7.4.0 - checksum: 10c0/94b8d078b76c199803e40758cd471e923f9bfd0339f322d3f2b4901fa3cd6015a03964049507077b401ee75be6d3606ced9791f39e8ec3b26161714ee784a353 + checksum: 10c0/43a062f78bd300a240a2f73b90731bc4bd3ed1125460a5d8947676e3509c7cb3c3bd1852e56def643929a098b8b7254733607efc5af6a34f03429dac36f1e9b8 languageName: node linkType: hard -"@angular/platform-browser-dynamic@npm:^21.2.4": - version: 21.2.5 - resolution: "@angular/platform-browser-dynamic@npm:21.2.5" +"@angular/platform-browser-dynamic@npm:^21.2.6": + version: 21.2.6 + resolution: "@angular/platform-browser-dynamic@npm:21.2.6" dependencies: tslib: "npm:^2.3.0" peerDependencies: - "@angular/common": 21.2.5 - "@angular/compiler": 21.2.5 - "@angular/core": 21.2.5 - "@angular/platform-browser": 21.2.5 - checksum: 10c0/6ace288108027ee268979b3a8362afd84004914daa733354b470e9abeab82ded8054284fbccfc1f5b90de0f7f97586e06e734f03ea2a6e6edc2e41ea60417693 + "@angular/common": 21.2.6 + "@angular/compiler": 21.2.6 + "@angular/core": 21.2.6 + "@angular/platform-browser": 21.2.6 + checksum: 10c0/9ebc3ca30125bd5a9a1ff6bd3162d329dd332b36290d5dd97c9331b5e4794ee68aa41fed58ddf27d9bf53a5ed7805bf3562aee2fffb2bd71b328ed9fe422a8ae languageName: node linkType: hard -"@angular/platform-browser@npm:^21.2.4": - version: 21.2.5 - resolution: "@angular/platform-browser@npm:21.2.5" +"@angular/platform-browser@npm:^21.2.6": + version: 21.2.6 + resolution: "@angular/platform-browser@npm:21.2.6" dependencies: tslib: "npm:^2.3.0" peerDependencies: - "@angular/animations": 21.2.5 - "@angular/common": 21.2.5 - "@angular/core": 21.2.5 + "@angular/animations": 21.2.6 + "@angular/common": 21.2.6 + "@angular/core": 21.2.6 peerDependenciesMeta: "@angular/animations": optional: true - checksum: 10c0/e1e613533c36bd7b9901cc75bde43f1ffbe121d4ab5289b61b39049cebd4736648312d132d9e1ed88f8a1234afeccb5056b09026bb1210e772f286fc17ed9de7 + checksum: 10c0/b6a51972da6cc024292296a5159305de43739842eeedcd942a64419a5f4c853f5e07c8f6644864ecb6387917708a036ac3a4939ffa03ec363d845a83eacd9e12 languageName: node linkType: hard -"@angular/router@npm:^21.2.4": - version: 21.2.5 - resolution: "@angular/router@npm:21.2.5" +"@angular/router@npm:^21.2.6": + version: 21.2.6 + resolution: "@angular/router@npm:21.2.6" dependencies: tslib: "npm:^2.3.0" peerDependencies: - "@angular/common": 21.2.5 - "@angular/core": 21.2.5 - "@angular/platform-browser": 21.2.5 + "@angular/common": 21.2.6 + "@angular/core": 21.2.6 + "@angular/platform-browser": 21.2.6 rxjs: ^6.5.3 || ^7.4.0 - checksum: 10c0/bcdc82d2c25d3d585cd9084c359d4d30b91e492bfbcd0b58d0443b3724f453dbdcb6e39e2ec67597ea2aec48d318cd5e8c2e0cd529d795c3546242651d796806 + checksum: 10c0/083da0921865b57bc78b33621a905e90bea48c4d198a48e066e56334bf7f75bc466426b9fb5cfe6459b524b383451dc6ed8d12228452e1f7ce8ac2f0159ddd8d languageName: node linkType: hard -"@angular/service-worker@npm:^21.2.4": - version: 21.2.5 - resolution: "@angular/service-worker@npm:21.2.5" +"@angular/service-worker@npm:^21.2.6": + version: 21.2.6 + resolution: "@angular/service-worker@npm:21.2.6" dependencies: tslib: "npm:^2.3.0" peerDependencies: - "@angular/core": 21.2.5 + "@angular/core": 21.2.6 rxjs: ^6.5.3 || ^7.4.0 bin: ngsw-config: ngsw-config.js - checksum: 10c0/b2d581487102277ca8e5cfe96c9ccc2be07d94d9d56354acade729d4e5a8d77f1024569cf50860ad190c28438d09af6cecfc50d3c316a57e98b0b01bc2d94764 + checksum: 10c0/a8fdf842c5d3e9900f921c8b0e619f60a3712b4f9baa40914879ff01278afb3b19259c0cf076752050c8bc7ea324bcc9707bbe50f9e8c66d14ae9f323f818441 languageName: node linkType: hard @@ -680,16 +680,16 @@ __metadata: languageName: node linkType: hard -"@asamuzakjp/dom-selector@npm:^6.8.1": - version: 6.8.1 - resolution: "@asamuzakjp/dom-selector@npm:6.8.1" +"@asamuzakjp/dom-selector@npm:^7.0.3": + version: 7.0.4 + resolution: "@asamuzakjp/dom-selector@npm:7.0.4" dependencies: "@asamuzakjp/nwsapi": "npm:^2.3.9" bidi-js: "npm:^1.0.3" - css-tree: "npm:^3.1.0" + css-tree: "npm:^3.2.1" is-potential-custom-element-name: "npm:^1.0.1" - lru-cache: "npm:^11.2.6" - checksum: 10c0/635de2c3b11971c07e2d491fd2833d2499bafbab05b616f5d38041031718879c404456644f60c45e9ba4ca2423e5bb48bf3c46179b0c58a0ea68eaae8c61e85f + lru-cache: "npm:^11.2.7" + checksum: 10c0/6539422595ed445f182eda78554fd339ff06f6d5add0520ee7cc9715baeb361454c11ffe21a6e7461907182153f88852866c4ea12158b9c9202ccc44767bc749 languageName: node linkType: hard @@ -700,7 +700,7 @@ __metadata: languageName: node linkType: hard -"@babel/code-frame@npm:^7.0.0, @babel/code-frame@npm:^7.28.6, @babel/code-frame@npm:^7.29.0": +"@babel/code-frame@npm:^7.0.0, @babel/code-frame@npm:^7.10.4, @babel/code-frame@npm:^7.28.6, @babel/code-frame@npm:^7.29.0": version: 7.29.0 resolution: "@babel/code-frame@npm:7.29.0" dependencies: @@ -857,6 +857,13 @@ __metadata: languageName: node linkType: hard +"@babel/runtime@npm:^7.12.5": + version: 7.29.2 + resolution: "@babel/runtime@npm:7.29.2" + checksum: 10c0/30b80a0140d16467792e1bbeb06f655b0dab70407da38dfac7fedae9c859f9ae9d846ef14ad77bd3814c064295fe9b1bc551f1541ea14646ae9f22b71a8bc17a + languageName: node + linkType: hard + "@babel/template@npm:^7.28.6": version: 7.28.6 resolution: "@babel/template@npm:7.28.6" @@ -963,15 +970,6 @@ __metadata: languageName: node linkType: hard -"@csstools/css-parser-algorithms@npm:^3.0.5": - version: 3.0.5 - resolution: "@csstools/css-parser-algorithms@npm:3.0.5" - peerDependencies: - "@csstools/css-tokenizer": ^3.0.4 - checksum: 10c0/d9a1c888bd43849ae3437ca39251d5c95d2c8fd6b5ccdb7c45491dfd2c1cbdc3075645e80901d120e4d2c1993db9a5b2d83793b779dbbabcfb132adb142eb7f7 - languageName: node - linkType: hard - "@csstools/css-parser-algorithms@npm:^4.0.0": version: 4.0.0 resolution: "@csstools/css-parser-algorithms@npm:4.0.0" @@ -981,7 +979,7 @@ __metadata: languageName: node linkType: hard -"@csstools/css-syntax-patches-for-csstree@npm:^1.0.19, @csstools/css-syntax-patches-for-csstree@npm:^1.0.28": +"@csstools/css-syntax-patches-for-csstree@npm:^1.1.1": version: 1.1.1 resolution: "@csstools/css-syntax-patches-for-csstree@npm:1.1.1" peerDependencies: @@ -993,13 +991,6 @@ __metadata: languageName: node linkType: hard -"@csstools/css-tokenizer@npm:^3.0.4": - version: 3.0.4 - resolution: "@csstools/css-tokenizer@npm:3.0.4" - checksum: 10c0/3b589f8e9942075a642213b389bab75a2d50d05d203727fcdac6827648a5572674caff07907eff3f9a2389d86a4ee47308fafe4f8588f4a77b7167c588d2559f - languageName: node - linkType: hard - "@csstools/css-tokenizer@npm:^4.0.0": version: 4.0.0 resolution: "@csstools/css-tokenizer@npm:4.0.0" @@ -1007,29 +998,31 @@ __metadata: languageName: node linkType: hard -"@csstools/media-query-list-parser@npm:^4.0.3": - version: 4.0.3 - resolution: "@csstools/media-query-list-parser@npm:4.0.3" - peerDependencies: - "@csstools/css-parser-algorithms": ^3.0.5 - "@csstools/css-tokenizer": ^3.0.4 - checksum: 10c0/e29d856d57e9a036694662163179fc061a99579f05e7c3c35438b3e063790ae8a9ee9f1fb4b4693d8fc7672ae0801764fe83762ab7b9df2921fcc6172cfd5584 - languageName: node - linkType: hard - -"@csstools/selector-specificity@npm:^5.0.0": +"@csstools/media-query-list-parser@npm:^5.0.0": version: 5.0.0 - resolution: "@csstools/selector-specificity@npm:5.0.0" + resolution: "@csstools/media-query-list-parser@npm:5.0.0" peerDependencies: - postcss-selector-parser: ^7.0.0 - checksum: 10c0/186b444cabcdcdeb553bfe021f80c58bfe9ef38dcc444f2b1f34a5aab9be063ab4e753022b2d5792049c041c28cfbb78e4b707ec398459300e402030d35c07eb + "@csstools/css-parser-algorithms": ^4.0.0 + "@csstools/css-tokenizer": ^4.0.0 + checksum: 10c0/dbc22654769eca02c182f3a57be02cd5b8d0b958adc8397e66770b64b0e8fcd32faa93a3f6a99e1457bde11862485de3cd83a31dac7b03925d32f9891b31ccfd languageName: node linkType: hard -"@dual-bundle/import-meta-resolve@npm:^4.2.1": - version: 4.2.1 - resolution: "@dual-bundle/import-meta-resolve@npm:4.2.1" - checksum: 10c0/8f1e572c14c4d20ea35734635085213abd13bd440c251309cf8ae5ed1082f6759cefa1c2c52a631f76859c57e26062f78a8cee4acc239c0edc87cd316a5d3b5b +"@csstools/selector-resolve-nested@npm:^4.0.0": + version: 4.0.0 + resolution: "@csstools/selector-resolve-nested@npm:4.0.0" + peerDependencies: + postcss-selector-parser: ^7.1.1 + checksum: 10c0/f6bccfe24a47c3e55710d421740550b868bbe7f0820f32d14d1eb737eefe7ec26261fb726cc5cfdf8236b3173d0a657ebdc9602e0c53824603f719b14a76bcaf + languageName: node + linkType: hard + +"@csstools/selector-specificity@npm:^6.0.0": + version: 6.0.0 + resolution: "@csstools/selector-specificity@npm:6.0.0" + peerDependencies: + postcss-selector-parser: ^7.1.1 + checksum: 10c0/7a93973f9054f2e1f03c8543cde68e0b0c65e5e72da6e4e959974d28fe809e11bd2afa1ff2ca11a1690a4c9a2f2bbe00d00e2b07fb2108bf89c5e48fe441c432 languageName: node linkType: hard @@ -1436,84 +1429,72 @@ __metadata: languageName: node linkType: hard -"@eslint-community/regexpp@npm:^4.12.1, @eslint-community/regexpp@npm:^4.12.2": +"@eslint-community/regexpp@npm:^4.12.2": version: 4.12.2 resolution: "@eslint-community/regexpp@npm:4.12.2" checksum: 10c0/fddcbc66851b308478d04e302a4d771d6917a0b3740dc351513c0da9ca2eab8a1adf99f5e0aa7ab8b13fa0df005c81adeee7e63a92f3effd7d367a163b721c2d languageName: node linkType: hard -"@eslint/config-array@npm:^0.21.2": - version: 0.21.2 - resolution: "@eslint/config-array@npm:0.21.2" +"@eslint/config-array@npm:^0.23.3": + version: 0.23.3 + resolution: "@eslint/config-array@npm:0.23.3" dependencies: - "@eslint/object-schema": "npm:^2.1.7" + "@eslint/object-schema": "npm:^3.0.3" debug: "npm:^4.3.1" - minimatch: "npm:^3.1.5" - checksum: 10c0/89dfe815d18456177c0a1f238daf4593107fd20298b3598e0103054360d3b8d09d967defd8318f031185d68df1f95cfa68becf1390a9c5c6887665f1475142e3 + minimatch: "npm:^10.2.4" + checksum: 10c0/7c19027acf9110cc542513ff9f3ca73a61d127e900c24f0e8e4d5e18aa22baf08d1d5bc386563d2f9311095f3b7898fe9b627b590fe9232b745ef60d4443cf9f languageName: node linkType: hard -"@eslint/config-helpers@npm:^0.4.2": - version: 0.4.2 - resolution: "@eslint/config-helpers@npm:0.4.2" +"@eslint/config-helpers@npm:^0.5.3": + version: 0.5.3 + resolution: "@eslint/config-helpers@npm:0.5.3" dependencies: - "@eslint/core": "npm:^0.17.0" - checksum: 10c0/92efd7a527b2d17eb1a148409d71d80f9ac160b565ac73ee092252e8bf08ecd08670699f46b306b94f13d22e88ac88a612120e7847570dd7cdc72f234d50dcb4 + "@eslint/core": "npm:^1.1.1" + checksum: 10c0/c836476e839a79dcdc9f7e0013057cfe0341162180d50e5a08668edb4b4b6c520a3174011469f6ef02efd2affd092263c020e89d0a3452c801427b0ac003549a languageName: node linkType: hard -"@eslint/core@npm:^0.17.0": - version: 0.17.0 - resolution: "@eslint/core@npm:0.17.0" +"@eslint/core@npm:^1.1.1": + version: 1.1.1 + resolution: "@eslint/core@npm:1.1.1" dependencies: "@types/json-schema": "npm:^7.0.15" - checksum: 10c0/9a580f2246633bc752298e7440dd942ec421860d1946d0801f0423830e67887e4aeba10ab9a23d281727a978eb93d053d1922a587d502942a713607f40ed704e + checksum: 10c0/129c654c78afc1f6d61dccb0ce841be667f09f052f7d5642614b6ba5eeebd579ca6cc336d7b750d88625e61f7aad22fdd62bf83847fbfc10cc3e58cfe6c5072e languageName: node linkType: hard -"@eslint/eslintrc@npm:^3.3.5": - version: 3.3.5 - resolution: "@eslint/eslintrc@npm:3.3.5" +"@eslint/js@npm:^10.0.1": + version: 10.0.1 + resolution: "@eslint/js@npm:10.0.1" + peerDependencies: + eslint: ^10.0.0 + peerDependenciesMeta: + eslint: + optional: true + checksum: 10c0/9f3fcaf71ba7fdf65d82e8faad6ecfe97e11801cc3c362b306a88ea1ed1344ae0d35330dddb0e8ad18f010f6687a70b75491b9e01c8af57acd7987cee6b3ec6c + languageName: node + linkType: hard + +"@eslint/object-schema@npm:^3.0.3": + version: 3.0.3 + resolution: "@eslint/object-schema@npm:3.0.3" + checksum: 10c0/4abbb7cba5419dce46ae8aa8e979fa190f2e906a8e1b5a8e22e4489f62a68dea3967679f66acbc0c3ef89f33252a7460e39fc2d6f2b4f616a137f3514eda4784 + languageName: node + linkType: hard + +"@eslint/plugin-kit@npm:^0.6.1": + version: 0.6.1 + resolution: "@eslint/plugin-kit@npm:0.6.1" dependencies: - ajv: "npm:^6.14.0" - debug: "npm:^4.3.2" - espree: "npm:^10.0.1" - globals: "npm:^14.0.0" - ignore: "npm:^5.2.0" - import-fresh: "npm:^3.2.1" - js-yaml: "npm:^4.1.1" - minimatch: "npm:^3.1.5" - strip-json-comments: "npm:^3.1.1" - checksum: 10c0/9fb9f1ca65e46d6173966e3aaa5bd353e3a65d7f1f582bebf77f578fab7d7960a399fac1ecfb1e7d52bd61f5cefd6531087ca52a3a3c388f2e1b4f1ebd3da8b7 - languageName: node - linkType: hard - -"@eslint/js@npm:9.39.4": - version: 9.39.4 - resolution: "@eslint/js@npm:9.39.4" - checksum: 10c0/5aa7dea2cbc5decf7f5e3b0c6f86a084ccee0f792d288ca8e839f8bc1b64e03e227068968e49b26096e6f71fd857ab6e42691d1b993826b9a3883f1bdd7a0e46 - languageName: node - linkType: hard - -"@eslint/object-schema@npm:^2.1.7": - version: 2.1.7 - resolution: "@eslint/object-schema@npm:2.1.7" - checksum: 10c0/936b6e499853d1335803f556d526c86f5fe2259ed241bc665000e1d6353828edd913feed43120d150adb75570cae162cf000b5b0dfc9596726761c36b82f4e87 - languageName: node - linkType: hard - -"@eslint/plugin-kit@npm:^0.4.1": - version: 0.4.1 - resolution: "@eslint/plugin-kit@npm:0.4.1" - dependencies: - "@eslint/core": "npm:^0.17.0" + "@eslint/core": "npm:^1.1.1" levn: "npm:^0.4.1" - checksum: 10c0/51600f78b798f172a9915dffb295e2ffb44840d583427bc732baf12ecb963eb841b253300e657da91d890f4b323d10a1bd12934bf293e3018d8bb66fdce5217b + checksum: 10c0/f8354a7b92cc41e7a55d51986d192134be84f9dc0c91b5e649d075d733b56981c4ca8bf4460d54120c4c87b47984167bad2cb9bceb303f11b0a3bad22b3ed06a languageName: node linkType: hard -"@exodus/bytes@npm:^1.11.0, @exodus/bytes@npm:^1.6.0": +"@exodus/bytes@npm:^1.11.0, @exodus/bytes@npm:^1.15.0, @exodus/bytes@npm:^1.6.0": version: 1.15.0 resolution: "@exodus/bytes@npm:1.15.0" peerDependencies: @@ -1615,7 +1596,7 @@ __metadata: languageName: node linkType: hard -"@inquirer/confirm@npm:5.1.21, @inquirer/confirm@npm:^5.1.21": +"@inquirer/confirm@npm:5.1.21, @inquirer/confirm@npm:^5.0.0, @inquirer/confirm@npm:^5.1.21": version: 5.1.21 resolution: "@inquirer/confirm@npm:5.1.21" dependencies: @@ -2090,6 +2071,20 @@ __metadata: languageName: node linkType: hard +"@mswjs/interceptors@npm:^0.41.2": + version: 0.41.3 + resolution: "@mswjs/interceptors@npm:0.41.3" + dependencies: + "@open-draft/deferred-promise": "npm:^2.2.0" + "@open-draft/logger": "npm:^0.3.0" + "@open-draft/until": "npm:^2.0.0" + is-node-process: "npm:^1.2.0" + outvariant: "npm:^1.4.3" + strict-event-emitter: "npm:^0.5.1" + checksum: 10c0/a259bbfc3bb4caada7a9a3529cc830159818e838c152df89ac890e7203df615a5e070ca63aa1e70a39868322ff5c1441ab74bbadb4081ca55b0c3a462e2903c0 + languageName: node + linkType: hard + "@napi-rs/nice-android-arm-eabi@npm:1.1.1": version: 1.1.1 resolution: "@napi-rs/nice-android-arm-eabi@npm:1.1.1" @@ -2408,6 +2403,30 @@ __metadata: languageName: node linkType: hard +"@open-draft/deferred-promise@npm:^2.2.0": + version: 2.2.0 + resolution: "@open-draft/deferred-promise@npm:2.2.0" + checksum: 10c0/eafc1b1d0fc8edb5e1c753c5e0f3293410b40dde2f92688211a54806d4136887051f39b98c1950370be258483deac9dfd17cf8b96557553765198ef2547e4549 + languageName: node + linkType: hard + +"@open-draft/logger@npm:^0.3.0": + version: 0.3.0 + resolution: "@open-draft/logger@npm:0.3.0" + dependencies: + is-node-process: "npm:^1.2.0" + outvariant: "npm:^1.4.0" + checksum: 10c0/90010647b22e9693c16258f4f9adb034824d1771d3baa313057b9a37797f571181005bc50415a934eaf7c891d90ff71dcd7a9d5048b0b6bb438f31bef2c7c5c1 + languageName: node + linkType: hard + +"@open-draft/until@npm:^2.0.0": + version: 2.1.0 + resolution: "@open-draft/until@npm:2.1.0" + checksum: 10c0/61d3f99718dd86bb393fee2d7a785f961dcaf12f2055f0c693b27f4d0cd5f7a03d498a6d9289773b117590d794a43cd129366fd8e99222e4832f67b1653d54cf + languageName: node + linkType: hard + "@oxc-project/types@npm:=0.113.0": version: 0.113.0 resolution: "@oxc-project/types@npm:0.113.0" @@ -2566,6 +2585,17 @@ __metadata: languageName: node linkType: hard +"@playwright/test@npm:^1.58.2": + version: 1.58.2 + resolution: "@playwright/test@npm:1.58.2" + dependencies: + playwright: "npm:1.58.2" + bin: + playwright: cli.js + checksum: 10c0/2164c03ad97c3653ff02e8818a71f3b2bbc344ac07924c9d8e31cd57505d6d37596015a41f51396b3ed8de6840f59143eaa9c21bf65515963da20740119811da + languageName: node + linkType: hard + "@primeuix/motion@npm:^0.0.10": version: 0.0.10 resolution: "@primeuix/motion@npm:0.0.10" @@ -2998,14 +3028,14 @@ __metadata: languageName: node linkType: hard -"@schematics/angular@npm:21.2.3": - version: 21.2.3 - resolution: "@schematics/angular@npm:21.2.3" +"@schematics/angular@npm:21.2.4": + version: 21.2.4 + resolution: "@schematics/angular@npm:21.2.4" dependencies: - "@angular-devkit/core": "npm:21.2.3" - "@angular-devkit/schematics": "npm:21.2.3" + "@angular-devkit/core": "npm:21.2.4" + "@angular-devkit/schematics": "npm:21.2.4" jsonc-parser: "npm:3.3.1" - checksum: 10c0/6c4f3b45a6ce7a78ff3a612bf979ff3d50e4b80f56c176f0671e5abbe257be5f223573a2272f0bbe2757f3532cbdd39726081e0eddd0121e56de4ddf6027384e + checksum: 10c0/31b505a8e3986cf0824292555861f77e152669ad4e6eaf4ad85bc773fdb0ac7b90896a80cc8e5e8deb28f266fff0580d8c20d735b2398ba82f2c9a46ecd4ef4f languageName: node linkType: hard @@ -3067,6 +3097,13 @@ __metadata: languageName: node linkType: hard +"@sindresorhus/merge-streams@npm:^4.0.0": + version: 4.0.0 + resolution: "@sindresorhus/merge-streams@npm:4.0.0" + checksum: 10c0/482ee543629aa1933b332f811a1ae805a213681ecdd98c042b1c1b89387df63e7812248bb4df3910b02b3cc5589d3d73e4393f30e197c9dde18046ccd471fc6b + languageName: node + linkType: hard + "@standard-schema/spec@npm:^1.0.0, @standard-schema/spec@npm:^1.1.0": version: 1.1.0 resolution: "@standard-schema/spec@npm:1.1.0" @@ -3092,33 +3129,87 @@ __metadata: languageName: node linkType: hard -"@tanstack/angular-query-experimental@npm:5.90.26": - version: 5.90.26 - resolution: "@tanstack/angular-query-experimental@npm:5.90.26" +"@tanstack/angular-query-experimental@npm:5.95.2": + version: 5.95.2 + resolution: "@tanstack/angular-query-experimental@npm:5.95.2" dependencies: - "@tanstack/query-core": "npm:5.91.0" - "@tanstack/query-devtools": "npm:5.93.0" + "@tanstack/query-core": "npm:5.95.2" + "@tanstack/query-devtools": "npm:5.95.2" peerDependencies: "@angular/common": ">=16.0.0" "@angular/core": ">=16.0.0" dependenciesMeta: "@tanstack/query-devtools": optional: true - checksum: 10c0/bec8d7b6c51f7ef81e7f7df6e1a120de057490cfe32b2d61636a4b6d31dd8affa29c50f4d83dae23cadfa7a837a554447db9a37ff697b5a18216aaf02e5fbbaf + checksum: 10c0/1c725a9d3e9b5e7f14c9c7b32a47be4c94c540de03ddac2585e372da02abab0ee5f8567a080df2d71eb22d41b8c8cc17c9b6217edd47447aaa32e351702bdd7b languageName: node linkType: hard -"@tanstack/query-core@npm:5.91.0": - version: 5.91.0 - resolution: "@tanstack/query-core@npm:5.91.0" - checksum: 10c0/57f32122f970644b2b4b44e6e212712eadebdbd092d2fee00ecedfe1d8ff7827340d593da4c876303b5a2a7fbc94b58fbddb678b9dfc11fd29206cc9d250630f +"@tanstack/query-core@npm:5.95.2": + version: 5.95.2 + resolution: "@tanstack/query-core@npm:5.95.2" + checksum: 10c0/6559483b30dd9ce7fc5d466d54a7ebfe4ca5b5d7f8ce37833a4048516b55565d3072526d74264fa974afbe49a0ae11c9a99ecc1d9ab525966360565ebc600083 languageName: node linkType: hard -"@tanstack/query-devtools@npm:5.93.0": - version: 5.93.0 - resolution: "@tanstack/query-devtools@npm:5.93.0" - checksum: 10c0/0024cef103f48c50f3932f6bfe5d77b4fde25be49d43486f8ef7ec7108d2c1bd999ebc7a46309f0504bf081daa7217b36637e9436d67f9a1599c89a385d078ee +"@tanstack/query-devtools@npm:5.95.2": + version: 5.95.2 + resolution: "@tanstack/query-devtools@npm:5.95.2" + checksum: 10c0/33b9dc74b4807a9316d3c43df9acf3b99c19e72424f3efd78984350f114d6b03ccba3ca3a01e5ad01d9fb78c32b719fee4aa5dfd2c62c641430838903e2f7576 + languageName: node + linkType: hard + +"@testing-library/angular@npm:^19.2.1": + version: 19.2.1 + resolution: "@testing-library/angular@npm:19.2.1" + dependencies: + tslib: "npm:^2.3.1" + peerDependencies: + "@angular/common": ">= 21.0.0" + "@angular/core": ">= 21.0.0" + "@angular/platform-browser": ">= 21.0.0" + "@angular/router": ">= 21.0.0" + "@testing-library/dom": ^10.0.0 + checksum: 10c0/3962851d70ba39c3fa70df348f8da663be6cd8d7c65b62067a4c6627063ef13027b6c05d75b43afbdb227a5e7bbb3faa7910d7ebd72e5b63fc0da0835b8bd169 + languageName: node + linkType: hard + +"@testing-library/dom@npm:^10.4.1": + version: 10.4.1 + resolution: "@testing-library/dom@npm:10.4.1" + dependencies: + "@babel/code-frame": "npm:^7.10.4" + "@babel/runtime": "npm:^7.12.5" + "@types/aria-query": "npm:^5.0.1" + aria-query: "npm:5.3.0" + dom-accessibility-api: "npm:^0.5.9" + lz-string: "npm:^1.5.0" + picocolors: "npm:1.1.1" + pretty-format: "npm:^27.0.2" + checksum: 10c0/19ce048012d395ad0468b0dbcc4d0911f6f9e39464d7a8464a587b29707eed5482000dad728f5acc4ed314d2f4d54f34982999a114d2404f36d048278db815b1 + languageName: node + linkType: hard + +"@testing-library/jest-dom@npm:^6.9.1": + version: 6.9.1 + resolution: "@testing-library/jest-dom@npm:6.9.1" + dependencies: + "@adobe/css-tools": "npm:^4.4.0" + aria-query: "npm:^5.0.0" + css.escape: "npm:^1.5.1" + dom-accessibility-api: "npm:^0.6.3" + picocolors: "npm:^1.1.1" + redent: "npm:^3.0.0" + checksum: 10c0/4291ebd2f0f38d14cefac142c56c337941775a5807e2a3d6f1a14c2fbd6be76a18e498ed189e95bedc97d9e8cf1738049bc76c85b5bc5e23fae7c9e10f7b3a12 + languageName: node + linkType: hard + +"@testing-library/user-event@npm:^14.6.1": + version: 14.6.1 + resolution: "@testing-library/user-event@npm:14.6.1" + peerDependencies: + "@testing-library/dom": ">=7.21.4" + checksum: 10c0/75fea130a52bf320d35d46ed54f3eec77e71a56911b8b69a3fe29497b0b9947b2dc80d30f04054ad4ce7f577856ae3e5397ea7dff0ef14944d3909784c7a93fe languageName: node linkType: hard @@ -3167,6 +3258,13 @@ __metadata: languageName: node linkType: hard +"@types/aria-query@npm:^5.0.1": + version: 5.0.4 + resolution: "@types/aria-query@npm:5.0.4" + checksum: 10c0/dc667bc6a3acc7bba2bccf8c23d56cb1f2f4defaa704cfef595437107efaa972d3b3db9ec1d66bc2711bfc35086821edd32c302bffab36f2e79b97f312069f08 + languageName: node + linkType: hard + "@types/chai@npm:^5.2.2": version: 5.2.3 resolution: "@types/chai@npm:5.2.3" @@ -3214,7 +3312,7 @@ __metadata: languageName: node linkType: hard -"@types/node@npm:^25.3.2": +"@types/node@npm:^25.5.0": version: 25.5.0 resolution: "@types/node@npm:25.5.0" dependencies: @@ -3230,6 +3328,13 @@ __metadata: languageName: node linkType: hard +"@types/statuses@npm:^2.0.6": + version: 2.0.6 + resolution: "@types/statuses@npm:2.0.6" + checksum: 10c0/dd88c220b0e2c6315686289525fd61472d2204d2e4bef4941acfb76bda01d3066f749ac74782aab5b537a45314fcd7d6261eefa40b6ec872691f5803adaa608d + languageName: node + linkType: hard + "@types/trusted-types@npm:^2.0.7": version: 2.0.7 resolution: "@types/trusted-types@npm:2.0.7" @@ -3381,12 +3486,12 @@ __metadata: languageName: node linkType: hard -"@vitest/coverage-v8@npm:^4.0.17": - version: 4.1.1 - resolution: "@vitest/coverage-v8@npm:4.1.1" +"@vitest/coverage-v8@npm:^4.1.2": + version: 4.1.2 + resolution: "@vitest/coverage-v8@npm:4.1.2" dependencies: "@bcoe/v8-coverage": "npm:^1.0.2" - "@vitest/utils": "npm:4.1.1" + "@vitest/utils": "npm:4.1.2" ast-v8-to-istanbul: "npm:^1.0.0" istanbul-lib-coverage: "npm:^3.2.2" istanbul-lib-report: "npm:^3.0.1" @@ -3394,36 +3499,36 @@ __metadata: magicast: "npm:^0.5.2" obug: "npm:^2.1.1" std-env: "npm:^4.0.0-rc.1" - tinyrainbow: "npm:^3.0.3" + tinyrainbow: "npm:^3.1.0" peerDependencies: - "@vitest/browser": 4.1.1 - vitest: 4.1.1 + "@vitest/browser": 4.1.2 + vitest: 4.1.2 peerDependenciesMeta: "@vitest/browser": optional: true - checksum: 10c0/a0e9fd2a98aa8c5c41d5aa20c6a1f15616a1b07ce0905be1eeb6a3c8bd1f4220280cb97fe814d63799908e0a3cb563342707a3c0b813589b86de5fc0e840705c + checksum: 10c0/2f4488efb34a5d9e3a70631ba263e153eecba8ec0da52cb874cdc674c88369061706572b9fc0c302376fd1de58aedc86a2f9f75e5a521084e31a1446c85f2c40 languageName: node linkType: hard -"@vitest/expect@npm:4.1.1": - version: 4.1.1 - resolution: "@vitest/expect@npm:4.1.1" +"@vitest/expect@npm:4.1.2": + version: 4.1.2 + resolution: "@vitest/expect@npm:4.1.2" dependencies: "@standard-schema/spec": "npm:^1.1.0" "@types/chai": "npm:^5.2.2" - "@vitest/spy": "npm:4.1.1" - "@vitest/utils": "npm:4.1.1" + "@vitest/spy": "npm:4.1.2" + "@vitest/utils": "npm:4.1.2" chai: "npm:^6.2.2" - tinyrainbow: "npm:^3.0.3" - checksum: 10c0/1d64c061322f22dccbb4b28b40ce1515b47bc5b984a528d16660025801dafdfa5151f44b3c840ff1fb49b11f6fdee4150230a2e51ca8b16a0756bc980e112919 + tinyrainbow: "npm:^3.1.0" + checksum: 10c0/e238c833b5555d31b074545807956d5e874a1ef725525ecc99f1885b71b230b2127d40d8d142a7253666b8565d5806723853e85e0e99265520ec7506fdc5890c languageName: node linkType: hard -"@vitest/mocker@npm:4.1.1": - version: 4.1.1 - resolution: "@vitest/mocker@npm:4.1.1" +"@vitest/mocker@npm:4.1.2": + version: 4.1.2 + resolution: "@vitest/mocker@npm:4.1.2" dependencies: - "@vitest/spy": "npm:4.1.1" + "@vitest/spy": "npm:4.1.2" estree-walker: "npm:^3.0.3" magic-string: "npm:^0.30.21" peerDependencies: @@ -3434,56 +3539,56 @@ __metadata: optional: true vite: optional: true - checksum: 10c0/1226c505d2acf0afa00edb6a26ee23b5505ae2973f2aa507134b1b47b023ae63e6809ca3196d014299b06fd4393a1b315c07767bed23d579442272dec9e6da90 + checksum: 10c0/f23094f3c7e1e5af42e6a468f0815c1ecdcab85cb3a56ab6f3f214a9808a40271467d4352cae972482b9738cc31c62c7312d8b0da227d6ea03d2b3aacb8d385f languageName: node linkType: hard -"@vitest/pretty-format@npm:4.1.1": - version: 4.1.1 - resolution: "@vitest/pretty-format@npm:4.1.1" +"@vitest/pretty-format@npm:4.1.2": + version: 4.1.2 + resolution: "@vitest/pretty-format@npm:4.1.2" dependencies: - tinyrainbow: "npm:^3.0.3" - checksum: 10c0/346f6b5154a53e9422222b2be43cd860659f5b8694d65804367f1cfeb8f9db7317552a796ccf1031c2ce0fc0c86caab3f1367f2c4e9029681c2cef90721a4977 + tinyrainbow: "npm:^3.1.0" + checksum: 10c0/6f57519c707e6a3d1ff8630ca87ce78fda9bf7bb33f6e4a0c775a8b510f2a6cee109849e2cdb736b0280681c567bd03e4cff724cbf0962950c9ff81377f0b2bc languageName: node linkType: hard -"@vitest/runner@npm:4.1.1": - version: 4.1.1 - resolution: "@vitest/runner@npm:4.1.1" +"@vitest/runner@npm:4.1.2": + version: 4.1.2 + resolution: "@vitest/runner@npm:4.1.2" dependencies: - "@vitest/utils": "npm:4.1.1" + "@vitest/utils": "npm:4.1.2" pathe: "npm:^2.0.3" - checksum: 10c0/bb91380567f989d761d5c6abd469be5b0b09368f09d877f403499981fe2de20fda652811de9f15facb8b975a6ca93c850ee62673bb8877dda1a36ecfdbaf7790 + checksum: 10c0/35654a87bd27983443adc24d68529d624f7d70e0386176741dc5bcc4188b86a70af2c512405d7e97aa45c16d83e1c8566c1f99c8440430f95557275f18612d21 languageName: node linkType: hard -"@vitest/snapshot@npm:4.1.1": - version: 4.1.1 - resolution: "@vitest/snapshot@npm:4.1.1" +"@vitest/snapshot@npm:4.1.2": + version: 4.1.2 + resolution: "@vitest/snapshot@npm:4.1.2" dependencies: - "@vitest/pretty-format": "npm:4.1.1" - "@vitest/utils": "npm:4.1.1" + "@vitest/pretty-format": "npm:4.1.2" + "@vitest/utils": "npm:4.1.2" magic-string: "npm:^0.30.21" pathe: "npm:^2.0.3" - checksum: 10c0/2c2571dab0d999fc8aaaf0fd8dd927d164edc29334bec4c4481209662fdb7f6fd071681fe6a04c7bcdf3045df31de8c56fcb87455060d85db5527e4a7bbc1d99 + checksum: 10c0/6d20e92386937afddbc81344211e554b83a559e20fb10c1deb0b1c3532994dc9fc62d816706ac835bdb737eb1ab02e9c0bc9de80dd8316060e1e0aaa447ba48f languageName: node linkType: hard -"@vitest/spy@npm:4.1.1": - version: 4.1.1 - resolution: "@vitest/spy@npm:4.1.1" - checksum: 10c0/42ad4c8ef0638877448b976b38f63fd46c3d8cc338851962955486b868297693886e6ac87e4e5594367c4c1d0ffe5d1ba36585265660e8da489c4d9fb26ebee7 +"@vitest/spy@npm:4.1.2": + version: 4.1.2 + resolution: "@vitest/spy@npm:4.1.2" + checksum: 10c0/2b5888d536d3e2083c5f8939763e6d780c2c03cc60e1ab45f9d04eacf14467acb9724cae1c4778e4c06426d49d04517e190122882953054a4b13fda44780bb14 languageName: node linkType: hard -"@vitest/utils@npm:4.1.1": - version: 4.1.1 - resolution: "@vitest/utils@npm:4.1.1" +"@vitest/utils@npm:4.1.2": + version: 4.1.2 + resolution: "@vitest/utils@npm:4.1.2" dependencies: - "@vitest/pretty-format": "npm:4.1.1" + "@vitest/pretty-format": "npm:4.1.2" convert-source-map: "npm:^2.0.0" - tinyrainbow: "npm:^3.0.3" - checksum: 10c0/a206f424388fdbc6d09db4a0fc94df5e6b5fff2fe3ea8cdfa0de250f30635265593523641a40e2f58de3fc201b8f6510bebac651c36c792b28369eec209e429d + tinyrainbow: "npm:^3.1.0" + checksum: 10c0/d96475e0703b6e5208c6c0f570c1235278cbac3f3913a9aa4203a3e617c9eaca85a184bfd5d13cf366b84754df787ab8bc85242c5e0c63105ee7176c186a2136 languageName: node linkType: hard @@ -3520,7 +3625,7 @@ __metadata: languageName: node linkType: hard -"acorn@npm:^8.15.0": +"acorn@npm:^8.16.0": version: 8.16.0 resolution: "acorn@npm:8.16.0" bin: @@ -3641,7 +3746,7 @@ __metadata: languageName: node linkType: hard -"ansi-styles@npm:^4.0.0, ansi-styles@npm:^4.1.0": +"ansi-styles@npm:^4.0.0": version: 4.3.0 resolution: "ansi-styles@npm:4.3.0" dependencies: @@ -3650,6 +3755,13 @@ __metadata: languageName: node linkType: hard +"ansi-styles@npm:^5.0.0": + version: 5.2.0 + resolution: "ansi-styles@npm:5.2.0" + checksum: 10c0/9c4ca80eb3c2fb7b33841c210d2f20807f40865d27008d7c3f707b7f95cab7d67462a565e2388ac3285b71cb3d9bb2173de8da37c57692a362885ec34d6e27df + languageName: node + linkType: hard + "ansi-styles@npm:^6.2.1, ansi-styles@npm:^6.2.3": version: 6.2.3 resolution: "ansi-styles@npm:6.2.3" @@ -3664,17 +3776,19 @@ __metadata: languageName: node linkType: hard -"aria-query@npm:5.3.2": - version: 5.3.2 - resolution: "aria-query@npm:5.3.2" - checksum: 10c0/003c7e3e2cff5540bf7a7893775fc614de82b0c5dde8ae823d47b7a28a9d4da1f7ed85f340bdb93d5649caa927755f0e31ecc7ab63edfdfc00c8ef07e505e03e +"aria-query@npm:5.3.0": + version: 5.3.0 + resolution: "aria-query@npm:5.3.0" + dependencies: + dequal: "npm:^2.0.3" + checksum: 10c0/2bff0d4eba5852a9dd578ecf47eaef0e82cc52569b48469b0aac2db5145db0b17b7a58d9e01237706d1e14b7a1b0ac9b78e9c97027ad97679dd8f91b85da1469 languageName: node linkType: hard -"array-union@npm:^2.1.0": - version: 2.1.0 - resolution: "array-union@npm:2.1.0" - checksum: 10c0/429897e68110374f39b771ec47a7161fc6a8fc33e196857c0a396dc75df0b5f65e4d046674db764330b6bb66b39ef48dd7c53b6a2ee75cfb0681e0c1a7033962 +"aria-query@npm:5.3.2, aria-query@npm:^5.0.0": + version: 5.3.2 + resolution: "aria-query@npm:5.3.2" + checksum: 10c0/003c7e3e2cff5540bf7a7893775fc614de82b0c5dde8ae823d47b7a28a9d4da1f7ed85f340bdb93d5649caa927755f0e31ecc7ab63edfdfc00c8ef07e505e03e languageName: node linkType: hard @@ -3731,13 +3845,6 @@ __metadata: languageName: node linkType: hard -"balanced-match@npm:^2.0.0": - version: 2.0.0 - resolution: "balanced-match@npm:2.0.0" - checksum: 10c0/60a54e0b75a61674e16a7a336b805f06c72d6f8fc457639c24efc512ba2bf9cb5744b9f6f5225afcefb99da39714440c83c737208cc65c5d9ecd1f3093331ca3 - languageName: node - linkType: hard - "balanced-match@npm:^4.0.2": version: 4.0.4 resolution: "balanced-match@npm:4.0.4" @@ -3804,16 +3911,6 @@ __metadata: languageName: node linkType: hard -"brace-expansion@npm:^1.1.7": - version: 1.1.12 - resolution: "brace-expansion@npm:1.1.12" - dependencies: - balanced-match: "npm:^1.0.0" - concat-map: "npm:0.0.1" - checksum: 10c0/975fecac2bb7758c062c20d0b3b6288c7cc895219ee25f0a64a9de662dbac981ff0b6e89909c3897c1f84fa353113a721923afdec5f8b2350255b097f12b1f73 - languageName: node - linkType: hard - "brace-expansion@npm:^2.0.2": version: 2.0.2 resolution: "brace-expansion@npm:2.0.2" @@ -3942,16 +4039,6 @@ __metadata: languageName: node linkType: hard -"chalk@npm:^4.0.0": - version: 4.1.2 - resolution: "chalk@npm:4.1.2" - dependencies: - ansi-styles: "npm:^4.1.0" - supports-color: "npm:^7.1.0" - checksum: 10c0/4a3fef5cc34975c898ffe77141450f679721df9dde00f6c304353fa9c8b571929123b26a0e4617bde5018977eb655b31970c297b91b63ee83bb82aeb04666880 - languageName: node - linkType: hard - "chalk@npm:^5.6.2": version: 5.6.2 resolution: "chalk@npm:5.6.2" @@ -4051,6 +4138,17 @@ __metadata: languageName: node linkType: hard +"cliui@npm:^8.0.1": + version: 8.0.1 + resolution: "cliui@npm:8.0.1" + dependencies: + string-width: "npm:^4.2.0" + strip-ansi: "npm:^6.0.1" + wrap-ansi: "npm:^7.0.0" + checksum: 10c0/4bda0f09c340cbb6dfdc1ed508b3ca080f12992c18d68c6be4d9cf51756033d5266e61ec57529e610dacbf4da1c634423b0c1b11037709cc6b09045cbd815df5 + languageName: node + linkType: hard + "cliui@npm:^9.0.1": version: 9.0.1 resolution: "cliui@npm:9.0.1" @@ -4078,7 +4176,7 @@ __metadata: languageName: node linkType: hard -"color-name@npm:~1.1.4": +"color-name@npm:^1.1.4, color-name@npm:~1.1.4": version: 1.1.4 resolution: "color-name@npm:1.1.4" checksum: 10c0/a1a3f914156960902f46f7f56bc62effc6c94e84b2cae157a526b1c1f74b677a47ec602bf68a61abfa2b42d15b7c5651c6dbe72a43af720bc588dff885b10f95 @@ -4106,13 +4204,6 @@ __metadata: languageName: node linkType: hard -"concat-map@npm:0.0.1": - version: 0.0.1 - resolution: "concat-map@npm:0.0.1" - checksum: 10c0/c996b1cfdf95b6c90fee4dae37e332c8b6eb7d106430c17d538034c0ad9a1630cb194d2ab37293b1bdd4d779494beee7786d586a50bd9376fd6f7bcc2bd4c98f - languageName: node - linkType: hard - "content-disposition@npm:^1.0.0": version: 1.0.1 resolution: "content-disposition@npm:1.0.1" @@ -4155,6 +4246,13 @@ __metadata: languageName: node linkType: hard +"cookie@npm:^1.0.2": + version: 1.1.1 + resolution: "cookie@npm:1.1.1" + checksum: 10c0/79c4ddc0fcad9c4f045f826f42edf54bcc921a29586a4558b0898277fa89fb47be95bc384c2253f493af7b29500c830da28341274527328f18eba9f58afa112c + languageName: node + linkType: hard + "cors@npm:^2.8.5": version: 2.8.6 resolution: "cors@npm:2.8.6" @@ -4182,7 +4280,7 @@ __metadata: languageName: node linkType: hard -"cosmiconfig@npm:^9.0.0": +"cosmiconfig@npm:^9.0.1": version: 9.0.1 resolution: "cosmiconfig@npm:9.0.1" dependencies: @@ -4210,7 +4308,7 @@ __metadata: languageName: node linkType: hard -"css-functions-list@npm:^3.2.3": +"css-functions-list@npm:^3.3.3": version: 3.3.3 resolution: "css-functions-list@npm:3.3.3" checksum: 10c0/7b9e5dd94e0178b2edb0f3263de5ae7942e56ab0b73420d4adb8fea003367e1dbc94fe8ea300bf732d1423f7eafb523e695136f0a4e6ae4f0abec66848219ee6 @@ -4230,7 +4328,7 @@ __metadata: languageName: node linkType: hard -"css-tree@npm:^3.0.0, css-tree@npm:^3.0.1, css-tree@npm:^3.1.0": +"css-tree@npm:^3.0.0, css-tree@npm:^3.0.1, css-tree@npm:^3.2.1": version: 3.2.1 resolution: "css-tree@npm:3.2.1" dependencies: @@ -4247,6 +4345,13 @@ __metadata: languageName: node linkType: hard +"css.escape@npm:^1.5.1": + version: 1.5.1 + resolution: "css.escape@npm:1.5.1" + checksum: 10c0/5e09035e5bf6c2c422b40c6df2eb1529657a17df37fda5d0433d722609527ab98090baf25b13970ca754079a0f3161dd3dfc0e743563ded8cfa0749d861c1525 + languageName: node + linkType: hard + "cssesc@npm:^3.0.0": version: 3.0.0 resolution: "cssesc@npm:3.0.0" @@ -4256,15 +4361,10 @@ __metadata: languageName: node linkType: hard -"cssstyle@npm:^6.0.1": - version: 6.2.0 - resolution: "cssstyle@npm:6.2.0" - dependencies: - "@asamuzakjp/css-color": "npm:^5.0.1" - "@csstools/css-syntax-patches-for-csstree": "npm:^1.0.28" - css-tree: "npm:^3.1.0" - lru-cache: "npm:^11.2.6" - checksum: 10c0/d5e61973a8c1b4fb9727edddfb9f2677c9a91b1db63787fc0c8bed639a227a97fcf930e5aabc3c64c8280d63169c632015a39da4a84083d1731c949437d0a2a2 +"cssfontparser@npm:^1.2.1": + version: 1.2.1 + resolution: "cssfontparser@npm:1.2.1" + checksum: 10c0/ceb9b2976d503dbff3ac2aff0229b263affb4fb221a6947b357682cd8a952f6995253646ca5f820020d2fe05b5e29b56dbdd2343388c32203e8dd0ed15bdc1ca languageName: node linkType: hard @@ -4318,6 +4418,13 @@ __metadata: languageName: node linkType: hard +"dequal@npm:^2.0.3": + version: 2.0.3 + resolution: "dequal@npm:2.0.3" + checksum: 10c0/f98860cdf58b64991ae10205137c0e97d384c3a4edc7f807603887b7c4b850af1224a33d88012009f150861cbee4fa2d322c4cc04b9313bee312e47f6ecaa888 + languageName: node + linkType: hard + "detect-libc@npm:^2.0.1, detect-libc@npm:^2.0.3": version: 2.1.2 resolution: "detect-libc@npm:2.1.2" @@ -4325,12 +4432,17 @@ __metadata: languageName: node linkType: hard -"dir-glob@npm:^3.0.1": - version: 3.0.1 - resolution: "dir-glob@npm:3.0.1" - dependencies: - path-type: "npm:^4.0.0" - checksum: 10c0/dcac00920a4d503e38bb64001acb19df4efc14536ada475725e12f52c16777afdee4db827f55f13a908ee7efc0cb282e2e3dbaeeb98c0993dd93d1802d3bf00c +"dom-accessibility-api@npm:^0.5.9": + version: 0.5.16 + resolution: "dom-accessibility-api@npm:0.5.16" + checksum: 10c0/b2c2eda4fae568977cdac27a9f0c001edf4f95a6a6191dfa611e3721db2478d1badc01db5bb4fa8a848aeee13e442a6c2a4386d65ec65a1436f24715a2f8d053 + languageName: node + linkType: hard + +"dom-accessibility-api@npm:^0.6.3": + version: 0.6.3 + resolution: "dom-accessibility-api@npm:0.6.3" + checksum: 10c0/10bee5aa514b2a9a37c87cd81268db607a2e933a050074abc2f6fa3da9080ebed206a320cbc123567f2c3087d22292853bdfdceaffdd4334ffe2af9510b29360 languageName: node linkType: hard @@ -4361,7 +4473,7 @@ __metadata: languageName: node linkType: hard -"dompurify@npm:*, dompurify@npm:^3.3.1": +"dompurify@npm:*, dompurify@npm:^3.3.3": version: 3.3.3 resolution: "dompurify@npm:3.3.3" dependencies: @@ -4710,7 +4822,7 @@ __metadata: languageName: node linkType: hard -"eslint-scope@npm:9.1.2": +"eslint-scope@npm:9.1.2, eslint-scope@npm:^9.1.2": version: 9.1.2 resolution: "eslint-scope@npm:9.1.2" dependencies: @@ -4722,16 +4834,6 @@ __metadata: languageName: node linkType: hard -"eslint-scope@npm:^8.4.0": - version: 8.4.0 - resolution: "eslint-scope@npm:8.4.0" - dependencies: - esrecurse: "npm:^4.3.0" - estraverse: "npm:^5.2.0" - checksum: 10c0/407f6c600204d0f3705bd557f81bd0189e69cd7996f408f8971ab5779c0af733d1af2f1412066b40ee1588b085874fc37a2333986c6521669cdbdd36ca5058e0 - languageName: node - linkType: hard - "eslint-visitor-keys@npm:^3.4.3": version: 3.4.3 resolution: "eslint-visitor-keys@npm:3.4.3" @@ -4739,45 +4841,35 @@ __metadata: languageName: node linkType: hard -"eslint-visitor-keys@npm:^4.2.1": - version: 4.2.1 - resolution: "eslint-visitor-keys@npm:4.2.1" - checksum: 10c0/fcd43999199d6740db26c58dbe0c2594623e31ca307e616ac05153c9272f12f1364f5a0b1917a8e962268fdecc6f3622c1c2908b4fcc2e047a106fe6de69dc43 - languageName: node - linkType: hard - -"eslint-visitor-keys@npm:^5.0.0": +"eslint-visitor-keys@npm:^5.0.0, eslint-visitor-keys@npm:^5.0.1": version: 5.0.1 resolution: "eslint-visitor-keys@npm:5.0.1" checksum: 10c0/16190bdf2cbae40a1109384c94450c526a79b0b9c3cb21e544256ed85ac48a4b84db66b74a6561d20fe6ab77447f150d711c2ad5ad74df4fcc133736bce99678 languageName: node linkType: hard -"eslint@npm:^9.39.3": - version: 9.39.4 - resolution: "eslint@npm:9.39.4" +"eslint@npm:^10.1.0": + version: 10.1.0 + resolution: "eslint@npm:10.1.0" dependencies: "@eslint-community/eslint-utils": "npm:^4.8.0" - "@eslint-community/regexpp": "npm:^4.12.1" - "@eslint/config-array": "npm:^0.21.2" - "@eslint/config-helpers": "npm:^0.4.2" - "@eslint/core": "npm:^0.17.0" - "@eslint/eslintrc": "npm:^3.3.5" - "@eslint/js": "npm:9.39.4" - "@eslint/plugin-kit": "npm:^0.4.1" + "@eslint-community/regexpp": "npm:^4.12.2" + "@eslint/config-array": "npm:^0.23.3" + "@eslint/config-helpers": "npm:^0.5.3" + "@eslint/core": "npm:^1.1.1" + "@eslint/plugin-kit": "npm:^0.6.1" "@humanfs/node": "npm:^0.16.6" "@humanwhocodes/module-importer": "npm:^1.0.1" "@humanwhocodes/retry": "npm:^0.4.2" "@types/estree": "npm:^1.0.6" ajv: "npm:^6.14.0" - chalk: "npm:^4.0.0" cross-spawn: "npm:^7.0.6" debug: "npm:^4.3.2" escape-string-regexp: "npm:^4.0.0" - eslint-scope: "npm:^8.4.0" - eslint-visitor-keys: "npm:^4.2.1" - espree: "npm:^10.4.0" - esquery: "npm:^1.5.0" + eslint-scope: "npm:^9.1.2" + eslint-visitor-keys: "npm:^5.0.1" + espree: "npm:^11.2.0" + esquery: "npm:^1.7.0" esutils: "npm:^2.0.2" fast-deep-equal: "npm:^3.1.3" file-entry-cache: "npm:^8.0.0" @@ -4787,8 +4879,7 @@ __metadata: imurmurhash: "npm:^0.1.4" is-glob: "npm:^4.0.0" json-stable-stringify-without-jsonify: "npm:^1.0.1" - lodash.merge: "npm:^4.6.2" - minimatch: "npm:^3.1.5" + minimatch: "npm:^10.2.4" natural-compare: "npm:^1.4.0" optionator: "npm:^0.9.3" peerDependencies: @@ -4798,22 +4889,22 @@ __metadata: optional: true bin: eslint: bin/eslint.js - checksum: 10c0/1955067c2d991f0c84f4c4abfafe31bb47fa3b717a7fd3e43fe1e511c6f859d7700cbca969f85661dc4c130f7aeced5e5444884314198a54428f5e5141db9337 + checksum: 10c0/b784ac18905b663fa4a801b0baa7bfa636c2d7ac08dad60690b15338c9b2126c5fa9fd4f9269b4f584cb0b426e428c1e353e23ff5ab6d8f8c610a0bb365831d6 languageName: node linkType: hard -"espree@npm:^10.0.1, espree@npm:^10.4.0": - version: 10.4.0 - resolution: "espree@npm:10.4.0" +"espree@npm:^11.2.0": + version: 11.2.0 + resolution: "espree@npm:11.2.0" dependencies: - acorn: "npm:^8.15.0" + acorn: "npm:^8.16.0" acorn-jsx: "npm:^5.3.2" - eslint-visitor-keys: "npm:^4.2.1" - checksum: 10c0/c63fe06131c26c8157b4083313cb02a9a54720a08e21543300e55288c40e06c3fc284bdecf108d3a1372c5934a0a88644c98714f38b6ae8ed272b40d9ea08d6b + eslint-visitor-keys: "npm:^5.0.1" + checksum: 10c0/cf87e18ffd9dc113eb8d16588e7757701bc10c9934a71cce8b89c2611d51672681a918307bd6b19ac3ccd0e7ba1cbccc2f815b36b52fa7e73097b251014c3d81 languageName: node linkType: hard -"esquery@npm:^1.5.0": +"esquery@npm:^1.7.0": version: 1.7.0 resolution: "esquery@npm:1.7.0" dependencies: @@ -4952,7 +5043,7 @@ __metadata: languageName: node linkType: hard -"fast-glob@npm:^3.2.9, fast-glob@npm:^3.3.2, fast-glob@npm:^3.3.3": +"fast-glob@npm:^3.3.2, fast-glob@npm:^3.3.3": version: 3.3.3 resolution: "fast-glob@npm:3.3.3" dependencies: @@ -5014,7 +5105,7 @@ __metadata: languageName: node linkType: hard -"file-entry-cache@npm:^11.1.1": +"file-entry-cache@npm:^11.1.2": version: 11.1.2 resolution: "file-entry-cache@npm:11.1.2" dependencies: @@ -5116,6 +5207,16 @@ __metadata: languageName: node linkType: hard +"fsevents@npm:2.3.2": + version: 2.3.2 + resolution: "fsevents@npm:2.3.2" + dependencies: + node-gyp: "npm:latest" + checksum: 10c0/be78a3efa3e181cda3cf7a4637cb527bcebb0bd0ea0440105a3bb45b86f9245b307dc10a2507e8f4498a7d4ec349d1910f4d73e4d4495b16103106e07eee735b + conditions: os=darwin + languageName: node + linkType: hard + "fsevents@npm:~2.3.2, fsevents@npm:~2.3.3": version: 2.3.3 resolution: "fsevents@npm:2.3.3" @@ -5126,6 +5227,15 @@ __metadata: languageName: node linkType: hard +"fsevents@patch:fsevents@npm%3A2.3.2#optional!builtin": + version: 2.3.2 + resolution: "fsevents@patch:fsevents@npm%3A2.3.2#optional!builtin::version=2.3.2&hash=df0bf1" + dependencies: + node-gyp: "npm:latest" + conditions: os=darwin + languageName: node + linkType: hard + "fsevents@patch:fsevents@npm%3A~2.3.2#optional!builtin, fsevents@patch:fsevents@npm%3A~2.3.3#optional!builtin": version: 2.3.3 resolution: "fsevents@patch:fsevents@npm%3A2.3.3#optional!builtin::version=2.3.3&hash=df0bf1" @@ -5257,24 +5367,17 @@ __metadata: languageName: node linkType: hard -"globals@npm:^14.0.0": - version: 14.0.0 - resolution: "globals@npm:14.0.0" - checksum: 10c0/b96ff42620c9231ad468d4c58ff42afee7777ee1c963013ff8aabe095a451d0ceeb8dcd8ef4cbd64d2538cef45f787a78ba3a9574f4a634438963e334471302d - languageName: node - linkType: hard - -"globby@npm:^11.1.0": - version: 11.1.0 - resolution: "globby@npm:11.1.0" +"globby@npm:^16.1.1": + version: 16.1.1 + resolution: "globby@npm:16.1.1" dependencies: - array-union: "npm:^2.1.0" - dir-glob: "npm:^3.0.1" - fast-glob: "npm:^3.2.9" - ignore: "npm:^5.2.0" - merge2: "npm:^1.4.1" - slash: "npm:^3.0.0" - checksum: 10c0/b39511b4afe4bd8a7aead3a27c4ade2b9968649abab0a6c28b1a90141b96ca68ca5db1302f7c7bd29eab66bf51e13916b8e0a3d0ac08f75e1e84a39b35691189 + "@sindresorhus/merge-streams": "npm:^4.0.0" + fast-glob: "npm:^3.3.3" + ignore: "npm:^7.0.5" + is-path-inside: "npm:^4.0.0" + slash: "npm:^5.1.0" + unicorn-magic: "npm:^0.4.0" + checksum: 10c0/2fbed8e5c59639a98b9b9c700afe5bcedf14742b43c25950cfd34a032db0cce4b440d8436beb4a936d211744e0b7330646f086b95cd8054251162c5d83001600 languageName: node linkType: hard @@ -5299,65 +5402,81 @@ __metadata: languageName: node linkType: hard +"graphql@npm:^16.12.0": + version: 16.13.2 + resolution: "graphql@npm:16.13.2" + checksum: 10c0/64e822a0a0e4398781e4bc9765b88d370c08261498b517add4b878038ef7be2005b6b394a79a5102b9379d57052f60bc7f23fec8f39808d101984a74772ebd9d + languageName: node + linkType: hard + "grimmory@workspace:.": version: 0.0.0-use.local resolution: "grimmory@workspace:." dependencies: - "@analogjs/vite-plugin-angular": "npm:^2.3.0" - "@analogjs/vitest-angular": "npm:^2.3.0" - "@angular-devkit/architect": "npm:0.2102.0" - "@angular-devkit/schematics": "npm:21.2.0" - "@angular/animations": "npm:^21.2.4" - "@angular/build": "npm:^21.2.0" - "@angular/cdk": "npm:^21.2.0" - "@angular/cli": "npm:^21.2.0" - "@angular/common": "npm:^21.2.4" - "@angular/compiler": "npm:^21.2.4" - "@angular/compiler-cli": "npm:^21.2.4" - "@angular/core": "npm:^21.2.4" - "@angular/forms": "npm:^21.2.4" - "@angular/platform-browser": "npm:^21.2.4" - "@angular/platform-browser-dynamic": "npm:^21.2.4" - "@angular/router": "npm:^21.2.4" - "@angular/service-worker": "npm:^21.2.4" + "@analogjs/vite-plugin-angular": "npm:^2.3.1" + "@analogjs/vitest-angular": "npm:^2.3.1" + "@angular-devkit/architect": "npm:0.2102.4" + "@angular-devkit/schematics": "npm:21.2.4" + "@angular/animations": "npm:^21.2.6" + "@angular/build": "npm:^21.2.4" + "@angular/cdk": "npm:^21.2.4" + "@angular/cli": "npm:^21.2.4" + "@angular/common": "npm:^21.2.6" + "@angular/compiler": "npm:^21.2.6" + "@angular/compiler-cli": "npm:^21.2.6" + "@angular/core": "npm:^21.2.6" + "@angular/forms": "npm:^21.2.6" + "@angular/platform-browser": "npm:^21.2.6" + "@angular/platform-browser-dynamic": "npm:^21.2.6" + "@angular/router": "npm:^21.2.6" + "@angular/service-worker": "npm:^21.2.6" + "@eslint/js": "npm:^10.0.1" "@iharbeck/ngx-virtual-scroller": "npm:^20.0.0" "@jsverse/transloco": "npm:^8.2.1" + "@playwright/test": "npm:^1.58.2" "@primeuix/themes": "npm:^2.0.3" "@stomp/rx-stomp": "npm:^2.3.0" "@stomp/stompjs": "npm:^7.3.0" - "@tanstack/angular-query-experimental": "npm:5.90.26" + "@tanstack/angular-query-experimental": "npm:5.95.2" + "@testing-library/angular": "npm:^19.2.1" + "@testing-library/dom": "npm:^10.4.1" + "@testing-library/jest-dom": "npm:^6.9.1" + "@testing-library/user-event": "npm:^14.6.1" "@tweenjs/tween.js": "npm:^25.0.0" "@types/dompurify": "npm:^3.2.0" - "@types/node": "npm:^25.3.2" + "@types/node": "npm:^25.5.0" "@types/showdown": "npm:^2.0.6" - "@vitest/coverage-v8": "npm:^4.0.17" + "@vitest/coverage-v8": "npm:^4.1.2" angular-eslint: "npm:^21.3.1" chart.js: "npm:^4.5.1" chartjs-chart-matrix: "npm:^3.0.0" chartjs-plugin-datalabels: "npm:^2.2.0" date-fns: "npm:^4.1.0" - dompurify: "npm:^3.3.1" - eslint: "npm:^9.39.3" - jsdom: "npm:^28.1.0" + dompurify: "npm:^3.3.3" + eslint: "npm:^10.1.0" + jsdom: "npm:^29.0.1" jwt-decode: "npm:^4.0.0" + msw: "npm:^2.12.14" ng-lazyload-image: "npm:^9.1.3" + ng-mocks: "npm:^14.15.2" ng2-charts: "npm:^8.0.0" ngx-extended-pdf-viewer: "npm:^25.6.4" ngx-infinite-scroll: "npm:^21.0.0" ngx-sse-client: "npm:^20.0.1" - postcss: "npm:^8.5.6" + postcss: "npm:^8.5.8" primeicons: "npm:^7.0.0" - primeng: "npm:^21.1.1" + primeng: "npm:^21.1.3" rxjs: "npm:^7.8.2" showdown: "npm:^2.1.0" - stylelint: "npm:^16.25.0" - stylelint-config-standard-scss: "npm:^16.0.0" + stylelint: "npm:^17.6.0" + stylelint-config-standard-scss: "npm:^17.0.0" tslib: "npm:^2.8.1" typescript: "npm:~5.9.3" - typescript-eslint: "npm:^8.56.1" + typescript-eslint: "npm:^8.57.2" uuid: "npm:^11.0.0" - vitest: "npm:^4.0.17" - ws: "npm:^8.19.0" + vitest: "npm:^4.1.2" + vitest-canvas-mock: "npm:^1.1.4" + ws: "npm:^8.20.0" zone.js: "npm:^0.16.1" languageName: unknown linkType: soft @@ -5369,6 +5488,13 @@ __metadata: languageName: node linkType: hard +"has-flag@npm:^5.0.1": + version: 5.0.1 + resolution: "has-flag@npm:5.0.1" + checksum: 10c0/6c214902e9d829979ef0f906980599df1db5ca289a9c72cc1b1ebc2c8c924681c60b632a21bfc23728a1098a3f300029a8608f293fcc559962ecd495652aa250 + languageName: node + linkType: hard + "has-symbols@npm:^1.1.0": version: 1.1.0 resolution: "has-symbols@npm:1.1.0" @@ -5394,6 +5520,13 @@ __metadata: languageName: node linkType: hard +"headers-polyfill@npm:^4.0.2": + version: 4.0.3 + resolution: "headers-polyfill@npm:4.0.3" + checksum: 10c0/53e85b2c6385f8d411945fb890c5369f1469ce8aa32a6e8d28196df38568148de640c81cf88cbc7c67767103dd9acba48f4f891982da63178fc6e34560022afe + languageName: node + linkType: hard + "hono@npm:^4.11.4": version: 4.12.9 resolution: "hono@npm:4.12.9" @@ -5440,10 +5573,10 @@ __metadata: languageName: node linkType: hard -"html-tags@npm:^3.3.1": - version: 3.3.1 - resolution: "html-tags@npm:3.3.1" - checksum: 10c0/680165e12baa51bad7397452d247dbcc5a5c29dac0e6754b1187eee3bf26f514bc1907a431dd2f7eb56207611ae595ee76a0acc8eaa0d931e72c791dd6463d79 +"html-tags@npm:^5.1.0": + version: 5.1.0 + resolution: "html-tags@npm:5.1.0" + checksum: 10c0/2dda19bc07e75837d0c52984558d92e8b82768050e4d6421b3164b1cb6ca5e73719209c2b23c0fa71faf097a7a3d18cf7f2021b488f1b1f270fca516c4c634c9 languageName: node linkType: hard @@ -5479,7 +5612,7 @@ __metadata: languageName: node linkType: hard -"http-proxy-agent@npm:^7.0.0, http-proxy-agent@npm:^7.0.2": +"http-proxy-agent@npm:^7.0.0": version: 7.0.2 resolution: "http-proxy-agent@npm:7.0.2" dependencies: @@ -5489,7 +5622,7 @@ __metadata: languageName: node linkType: hard -"https-proxy-agent@npm:7.0.6, https-proxy-agent@npm:^7.0.1, https-proxy-agent@npm:^7.0.6": +"https-proxy-agent@npm:7.0.6, https-proxy-agent@npm:^7.0.1": version: 7.0.6 resolution: "https-proxy-agent@npm:7.0.6" dependencies: @@ -5538,7 +5671,7 @@ __metadata: languageName: node linkType: hard -"import-fresh@npm:^3.2.1, import-fresh@npm:^3.3.0": +"import-fresh@npm:^3.3.0": version: 3.3.1 resolution: "import-fresh@npm:3.3.1" dependencies: @@ -5548,6 +5681,13 @@ __metadata: languageName: node linkType: hard +"import-meta-resolve@npm:^4.2.0": + version: 4.2.0 + resolution: "import-meta-resolve@npm:4.2.0" + checksum: 10c0/3ee8aeecb61d19b49d2703987f977e9d1c7d4ba47db615a570eaa02fe414f40dfa63f7b953e842cbe8470d26df6371332bfcf21b2fd92b0112f9fea80dde2c4c + languageName: node + linkType: hard + "imurmurhash@npm:^0.1.4": version: 0.1.4 resolution: "imurmurhash@npm:0.1.4" @@ -5555,6 +5695,13 @@ __metadata: languageName: node linkType: hard +"indent-string@npm:^4.0.0": + version: 4.0.0 + resolution: "indent-string@npm:4.0.0" + checksum: 10c0/1e1904ddb0cb3d6cce7cd09e27a90184908b7a5d5c21b92e232c93579d314f0b83c246ffb035493d0504b1e9147ba2c9b21df0030f48673fba0496ecd698161f + languageName: node + linkType: hard + "inherits@npm:~2.0.4": version: 2.0.4 resolution: "inherits@npm:2.0.4" @@ -5636,6 +5783,13 @@ __metadata: languageName: node linkType: hard +"is-node-process@npm:^1.2.0": + version: 1.2.0 + resolution: "is-node-process@npm:1.2.0" + checksum: 10c0/5b24fda6776d00e42431d7bcd86bce81cb0b6cabeb944142fe7b077a54ada2e155066ad06dbe790abdb397884bdc3151e04a9707b8cd185099efbc79780573ed + languageName: node + linkType: hard + "is-number@npm:^7.0.0": version: 7.0.0 resolution: "is-number@npm:7.0.0" @@ -5643,6 +5797,13 @@ __metadata: languageName: node linkType: hard +"is-path-inside@npm:^4.0.0": + version: 4.0.0 + resolution: "is-path-inside@npm:4.0.0" + checksum: 10c0/51188d7e2b1d907a9a5f7c18d99a90b60870b951ed87cf97595d9aaa429d4c010652c3350bcbf31182e7f4b0eab9a1860b43e16729b13cb1a44baaa6cdb64c46 + languageName: node + linkType: hard + "is-plain-object@npm:^5.0.0": version: 5.0.0 resolution: "is-plain-object@npm:5.0.0" @@ -5747,7 +5908,7 @@ __metadata: languageName: node linkType: hard -"js-yaml@npm:^4.1.0, js-yaml@npm:^4.1.1": +"js-yaml@npm:^4.1.0": version: 4.1.1 resolution: "js-yaml@npm:4.1.1" dependencies: @@ -5758,37 +5919,37 @@ __metadata: languageName: node linkType: hard -"jsdom@npm:^28.1.0": - version: 28.1.0 - resolution: "jsdom@npm:28.1.0" +"jsdom@npm:^29.0.1": + version: 29.0.1 + resolution: "jsdom@npm:29.0.1" dependencies: - "@acemir/cssom": "npm:^0.9.31" - "@asamuzakjp/dom-selector": "npm:^6.8.1" + "@asamuzakjp/css-color": "npm:^5.0.1" + "@asamuzakjp/dom-selector": "npm:^7.0.3" "@bramus/specificity": "npm:^2.4.2" - "@exodus/bytes": "npm:^1.11.0" - cssstyle: "npm:^6.0.1" + "@csstools/css-syntax-patches-for-csstree": "npm:^1.1.1" + "@exodus/bytes": "npm:^1.15.0" + css-tree: "npm:^3.2.1" data-urls: "npm:^7.0.0" decimal.js: "npm:^10.6.0" html-encoding-sniffer: "npm:^6.0.0" - http-proxy-agent: "npm:^7.0.2" - https-proxy-agent: "npm:^7.0.6" is-potential-custom-element-name: "npm:^1.0.1" + lru-cache: "npm:^11.2.7" parse5: "npm:^8.0.0" saxes: "npm:^6.0.0" symbol-tree: "npm:^3.2.4" - tough-cookie: "npm:^6.0.0" - undici: "npm:^7.21.0" + tough-cookie: "npm:^6.0.1" + undici: "npm:^7.24.5" w3c-xmlserializer: "npm:^5.0.0" webidl-conversions: "npm:^8.0.1" whatwg-mimetype: "npm:^5.0.0" - whatwg-url: "npm:^16.0.0" + whatwg-url: "npm:^16.0.1" xml-name-validator: "npm:^5.0.0" peerDependencies: canvas: ^3.0.0 peerDependenciesMeta: canvas: optional: true - checksum: 10c0/341ecb4005be2dab3247dacc349a20285d7991b5cee3382301fcd69a4294b705b4147e7d9ae1ddfab466ba4b3aace97ded4f7b070de285262221cb2782965b25 + checksum: 10c0/f8eeadc9bb45fb5736501f855b5f8247c9eadcd7f52ef2e11677c3a2197284051b4623004889543eb9613ecdfb47ddb5405b822d9623b0524edd901288cc361d languageName: node linkType: hard @@ -6118,13 +6279,6 @@ __metadata: languageName: node linkType: hard -"lodash.merge@npm:^4.6.2": - version: 4.6.2 - resolution: "lodash.merge@npm:4.6.2" - checksum: 10c0/402fa16a1edd7538de5b5903a90228aa48eb5533986ba7fa26606a49db2572bf414ff73a2c9f5d5fd36b31c46a5d5c7e1527749c07cbcf965ccff5fbdf32c506 - languageName: node - linkType: hard - "lodash.truncate@npm:^4.4.2": version: 4.4.2 resolution: "lodash.truncate@npm:4.4.2" @@ -6155,7 +6309,7 @@ __metadata: languageName: node linkType: hard -"lru-cache@npm:^11.0.0, lru-cache@npm:^11.1.0, lru-cache@npm:^11.2.1, lru-cache@npm:^11.2.6": +"lru-cache@npm:^11.0.0, lru-cache@npm:^11.1.0, lru-cache@npm:^11.2.1, lru-cache@npm:^11.2.6, lru-cache@npm:^11.2.7": version: 11.2.7 resolution: "lru-cache@npm:11.2.7" checksum: 10c0/549cdb59488baa617135fc12159cafb1a97f91079f35093bb3bcad72e849fc64ace636d244212c181dfdf1a99bbfa90757ff303f98561958ee4d0f885d9bd5f7 @@ -6171,6 +6325,15 @@ __metadata: languageName: node linkType: hard +"lz-string@npm:^1.5.0": + version: 1.5.0 + resolution: "lz-string@npm:1.5.0" + bin: + lz-string: bin/bin.js + checksum: 10c0/36128e4de34791838abe979b19927c26e67201ca5acf00880377af7d765b38d1c60847e01c5ec61b1a260c48029084ab3893a3925fd6e48a04011364b089991b + languageName: node + linkType: hard + "magic-string@npm:0.30.21, magic-string@npm:^0.30.21": version: 0.30.21 resolution: "magic-string@npm:0.30.21" @@ -6227,10 +6390,10 @@ __metadata: languageName: node linkType: hard -"mathml-tag-names@npm:^2.1.3": - version: 2.1.3 - resolution: "mathml-tag-names@npm:2.1.3" - checksum: 10c0/e2b094658a2618433efd2678a5a3e551645e09ba17c7c777783cd8dfa0178b0195fda0a5c46a6be5e778923662cf8dde891c894c869ff14fbb4ea3208c31bc4d +"mathml-tag-names@npm:^4.0.0": + version: 4.0.0 + resolution: "mathml-tag-names@npm:4.0.0" + checksum: 10c0/2e928554c61b5e502ee551a23bb4157b99ffd042578e28fb4038ee67d19ea2b1a79c34a3c2ab1611437f668f6b29436e1c8f6fdc20eaf3c88d511ce5b8954fe8 languageName: node linkType: hard @@ -6248,10 +6411,10 @@ __metadata: languageName: node linkType: hard -"meow@npm:^13.2.0": - version: 13.2.0 - resolution: "meow@npm:13.2.0" - checksum: 10c0/d5b339ae314715bcd0b619dd2f8a266891928e21526b4800d49b4fba1cc3fff7e2c1ff5edd3344149fac841bc2306157f858e8c4d5eaee4d52ce52ad925664ce +"meow@npm:^14.1.0": + version: 14.1.0 + resolution: "meow@npm:14.1.0" + checksum: 10c0/f0ca4bb4fd08e4b9470fcbb7332deb61d72d40d4bda18ffb87c1a98e5014c0b44749ae9f0cab18fa532e26d61cef5d453831f9ae23ac09fa8ea0e0469be73ebc languageName: node linkType: hard @@ -6262,7 +6425,7 @@ __metadata: languageName: node linkType: hard -"merge2@npm:^1.3.0, merge2@npm:^1.4.1": +"merge2@npm:^1.3.0": version: 1.4.1 resolution: "merge2@npm:1.4.1" checksum: 10c0/254a8a4605b58f450308fc474c82ac9a094848081bf4c06778200207820e5193726dc563a0d2c16468810516a5c97d9d3ea0ca6585d23c58ccfff2403e8dbbeb @@ -6302,7 +6465,14 @@ __metadata: languageName: node linkType: hard -"minimatch@npm:^10.0.3, minimatch@npm:^10.1.1, minimatch@npm:^10.2.2": +"min-indent@npm:^1.0.0": + version: 1.0.1 + resolution: "min-indent@npm:1.0.1" + checksum: 10c0/7e207bd5c20401b292de291f02913230cb1163abca162044f7db1d951fa245b174dc00869d40dd9a9f32a885ad6a5f3e767ee104cf278f399cb4e92d3f582d5c + languageName: node + linkType: hard + +"minimatch@npm:^10.0.3, minimatch@npm:^10.1.1, minimatch@npm:^10.2.2, minimatch@npm:^10.2.4": version: 10.2.4 resolution: "minimatch@npm:10.2.4" dependencies: @@ -6311,15 +6481,6 @@ __metadata: languageName: node linkType: hard -"minimatch@npm:^3.1.5": - version: 3.1.5 - resolution: "minimatch@npm:3.1.5" - dependencies: - brace-expansion: "npm:^1.1.7" - checksum: 10c0/2ecbdc0d33f07bddb0315a8b5afbcb761307a8778b48f0b312418ccbced99f104a2d17d8aca7573433c70e8ccd1c56823a441897a45e384ea76ef401a26ace70 - languageName: node - linkType: hard - "minimatch@npm:^9.0.3": version: 9.0.9 resolution: "minimatch@npm:9.0.9" @@ -6414,6 +6575,15 @@ __metadata: languageName: node linkType: hard +"moo-color@npm:^1.0.3": + version: 1.0.3 + resolution: "moo-color@npm:1.0.3" + dependencies: + color-name: "npm:^1.1.4" + checksum: 10c0/778c82f67f638c03a1d0fa78dcd6ea376a9f17b5e78e349c7e34a290b496dbdb43fd0b1c38070e2062d5e784bcf08e57f499015fcbcf52b3a1887d7825ebb80d + languageName: node + linkType: hard + "mrmime@npm:2.0.1": version: 2.0.1 resolution: "mrmime@npm:2.0.1" @@ -6471,6 +6641,39 @@ __metadata: languageName: node linkType: hard +"msw@npm:^2.12.14": + version: 2.12.14 + resolution: "msw@npm:2.12.14" + dependencies: + "@inquirer/confirm": "npm:^5.0.0" + "@mswjs/interceptors": "npm:^0.41.2" + "@open-draft/deferred-promise": "npm:^2.2.0" + "@types/statuses": "npm:^2.0.6" + cookie: "npm:^1.0.2" + graphql: "npm:^16.12.0" + headers-polyfill: "npm:^4.0.2" + is-node-process: "npm:^1.2.0" + outvariant: "npm:^1.4.3" + path-to-regexp: "npm:^6.3.0" + picocolors: "npm:^1.1.1" + rettime: "npm:^0.10.1" + statuses: "npm:^2.0.2" + strict-event-emitter: "npm:^0.5.1" + tough-cookie: "npm:^6.0.0" + type-fest: "npm:^5.2.0" + until-async: "npm:^3.0.2" + yargs: "npm:^17.7.2" + peerDependencies: + typescript: ">= 4.8.x" + peerDependenciesMeta: + typescript: + optional: true + bin: + msw: cli/index.js + checksum: 10c0/73e2c08a74bac94036c75aa0340e48573a233d5060cb3098ead7ec0eaddaacef4de399b81e0e3f41ea73d5f92341adc9cf0ae908ad74583d294afa4667e7d277 + languageName: node + linkType: hard + "mute-stream@npm:^2.0.0": version: 2.0.0 resolution: "mute-stream@npm:2.0.0" @@ -6514,6 +6717,18 @@ __metadata: languageName: node linkType: hard +"ng-mocks@npm:^14.15.2": + version: 14.15.2 + resolution: "ng-mocks@npm:14.15.2" + peerDependencies: + "@angular/common": 5.0.0-alpha - 5 || 6.0.0-alpha - 6 || 7.0.0-alpha - 7 || 8.0.0-alpha - 8 || 9.0.0-alpha - 9 || 10.0.0-alpha - 10 || 11.0.0-alpha - 11 || 12.0.0-alpha - 12 || 13.0.0-alpha - 13 || 14.0.0-alpha - 14 || 15.0.0-alpha - 15 || 16.0.0-alpha - 16 || 17.0.0-alpha - 17 || 18.0.0-alpha - 18 || 19.0.0-alpha - 19 || 20.0.0-alpha - 20 || 21.0.0-alpha - 21 || 22.0.0-alpha - 22 + "@angular/core": 5.0.0-alpha - 5 || 6.0.0-alpha - 6 || 7.0.0-alpha - 7 || 8.0.0-alpha - 8 || 9.0.0-alpha - 9 || 10.0.0-alpha - 10 || 11.0.0-alpha - 11 || 12.0.0-alpha - 12 || 13.0.0-alpha - 13 || 14.0.0-alpha - 14 || 15.0.0-alpha - 15 || 16.0.0-alpha - 16 || 17.0.0-alpha - 17 || 18.0.0-alpha - 18 || 19.0.0-alpha - 19 || 20.0.0-alpha - 20 || 21.0.0-alpha - 21 || 22.0.0-alpha - 22 + "@angular/forms": 5.0.0-alpha - 5 || 6.0.0-alpha - 6 || 7.0.0-alpha - 7 || 8.0.0-alpha - 8 || 9.0.0-alpha - 9 || 10.0.0-alpha - 10 || 11.0.0-alpha - 11 || 12.0.0-alpha - 12 || 13.0.0-alpha - 13 || 14.0.0-alpha - 14 || 15.0.0-alpha - 15 || 16.0.0-alpha - 16 || 17.0.0-alpha - 17 || 18.0.0-alpha - 18 || 19.0.0-alpha - 19 || 20.0.0-alpha - 20 || 21.0.0-alpha - 21 || 22.0.0-alpha - 22 + "@angular/platform-browser": 5.0.0-alpha - 5 || 6.0.0-alpha - 6 || 7.0.0-alpha - 7 || 8.0.0-alpha - 8 || 9.0.0-alpha - 9 || 10.0.0-alpha - 10 || 11.0.0-alpha - 11 || 12.0.0-alpha - 12 || 13.0.0-alpha - 13 || 14.0.0-alpha - 14 || 15.0.0-alpha - 15 || 16.0.0-alpha - 16 || 17.0.0-alpha - 17 || 18.0.0-alpha - 18 || 19.0.0-alpha - 19 || 20.0.0-alpha - 20 || 21.0.0-alpha - 21 || 22.0.0-alpha - 22 + checksum: 10c0/625b03b2bb876207c4c78bacf481d3b1c5d7056f95281008d45fd06ef7625bf2e469245c71694d48cd3190ed4ea75d5293a24bbb64085b6aeb15b4b48924d551 + languageName: node + linkType: hard + "ng2-charts@npm:^8.0.0": version: 8.0.0 resolution: "ng2-charts@npm:8.0.0" @@ -6812,6 +7027,13 @@ __metadata: languageName: node linkType: hard +"outvariant@npm:^1.4.0, outvariant@npm:^1.4.3": + version: 1.4.3 + resolution: "outvariant@npm:1.4.3" + checksum: 10c0/5976ca7740349cb8c71bd3382e2a762b1aeca6f33dc984d9d896acdf3c61f78c3afcf1bfe9cc633a7b3c4b295ec94d292048f83ea2b2594fae4496656eba992c + languageName: node + linkType: hard + "p-limit@npm:^3.0.2": version: 3.1.0 resolution: "p-limit@npm:3.1.0" @@ -6952,6 +7174,13 @@ __metadata: languageName: node linkType: hard +"path-to-regexp@npm:^6.3.0": + version: 6.3.0 + resolution: "path-to-regexp@npm:6.3.0" + checksum: 10c0/73b67f4638b41cde56254e6354e46ae3a2ebc08279583f6af3d96fe4664fc75788f74ed0d18ca44fa4a98491b69434f9eee73b97bb5314bd1b5adb700f5c18d6 + languageName: node + linkType: hard + "path-to-regexp@npm:^8.0.0": version: 8.3.0 resolution: "path-to-regexp@npm:8.3.0" @@ -6973,7 +7202,7 @@ __metadata: languageName: node linkType: hard -"picocolors@npm:^1.1.1": +"picocolors@npm:1.1.1, picocolors@npm:^1.1.1": version: 1.1.1 resolution: "picocolors@npm:1.1.1" checksum: 10c0/e2e3e8170ab9d7c7421969adaa7e1b31434f789afb9b3f115f6b96d91945041ac3ceb02e9ec6fe6510ff036bcc0bf91e69a1772edc0b707e12b19c0f2d6bcf58 @@ -7020,6 +7249,30 @@ __metadata: languageName: node linkType: hard +"playwright-core@npm:1.58.2": + version: 1.58.2 + resolution: "playwright-core@npm:1.58.2" + bin: + playwright-core: cli.js + checksum: 10c0/5aa15b2b764e6ffe738293a09081a6f7023847a0dbf4cd05fe10eed2e25450d321baf7482f938f2d2eb330291e197fa23e57b29a5b552b89927ceb791266225b + languageName: node + linkType: hard + +"playwright@npm:1.58.2": + version: 1.58.2 + resolution: "playwright@npm:1.58.2" + dependencies: + fsevents: "npm:2.3.2" + playwright-core: "npm:1.58.2" + dependenciesMeta: + fsevents: + optional: true + bin: + playwright: cli.js + checksum: 10c0/d060d9b7cc124bd8b5dffebaab5e84f6b34654a553758fe7b19cc598dfbee93f6ecfbdc1832b40a6380ae04eade86ef3285ba03aa0b136799e83402246dc0727 + languageName: node + linkType: hard + "postcss-media-query-parser@npm:^0.2.3": version: 0.2.3 resolution: "postcss-media-query-parser@npm:0.2.3" @@ -7052,7 +7305,7 @@ __metadata: languageName: node linkType: hard -"postcss-selector-parser@npm:^7.1.0, postcss-selector-parser@npm:^7.1.1": +"postcss-selector-parser@npm:^7.1.1": version: 7.1.1 resolution: "postcss-selector-parser@npm:7.1.1" dependencies: @@ -7087,6 +7340,17 @@ __metadata: languageName: node linkType: hard +"pretty-format@npm:^27.0.2": + version: 27.5.1 + resolution: "pretty-format@npm:27.5.1" + dependencies: + ansi-regex: "npm:^5.0.1" + ansi-styles: "npm:^5.0.0" + react-is: "npm:^17.0.1" + checksum: 10c0/0cbda1031aa30c659e10921fa94e0dd3f903ecbbbe7184a729ad66f2b6e7f17891e8c7d7654c458fa4ccb1a411ffb695b4f17bbcd3fe075fabe181027c4040ed + languageName: node + linkType: hard + "primeicons@npm:^7.0.0": version: 7.0.0 resolution: "primeicons@npm:7.0.0" @@ -7094,7 +7358,7 @@ __metadata: languageName: node linkType: hard -"primeng@npm:^21.1.1": +"primeng@npm:^21.1.3": version: 21.1.3 resolution: "primeng@npm:21.1.3" dependencies: @@ -7193,6 +7457,13 @@ __metadata: languageName: node linkType: hard +"react-is@npm:^17.0.1": + version: 17.0.2 + resolution: "react-is@npm:17.0.2" + checksum: 10c0/2bdb6b93fbb1820b024b496042cce405c57e2f85e777c9aabd55f9b26d145408f9f74f5934676ffdc46f3dcff656d78413a6e43968e7b3f92eea35b3052e9053 + languageName: node + linkType: hard + "readdirp@npm:^4.0.1": version: 4.1.2 resolution: "readdirp@npm:4.1.2" @@ -7207,6 +7478,16 @@ __metadata: languageName: node linkType: hard +"redent@npm:^3.0.0": + version: 3.0.0 + resolution: "redent@npm:3.0.0" + dependencies: + indent-string: "npm:^4.0.0" + strip-indent: "npm:^3.0.0" + checksum: 10c0/d64a6b5c0b50eb3ddce3ab770f866658a2b9998c678f797919ceb1b586bab9259b311407280bd80b804e2a7c7539b19238ae6a2a20c843f1a7fcff21d48c2eae + languageName: node + linkType: hard + "reflect-metadata@npm:^0.2.0": version: 0.2.2 resolution: "reflect-metadata@npm:0.2.2" @@ -7214,6 +7495,13 @@ __metadata: languageName: node linkType: hard +"require-directory@npm:^2.1.1": + version: 2.1.1 + resolution: "require-directory@npm:2.1.1" + checksum: 10c0/83aa76a7bc1531f68d92c75a2ca2f54f1b01463cb566cf3fbc787d0de8be30c9dbc211d1d46be3497dac5785fe296f2dd11d531945ac29730643357978966e99 + languageName: node + linkType: hard + "require-from-string@npm:^2.0.2": version: 2.0.2 resolution: "require-from-string@npm:2.0.2" @@ -7228,13 +7516,6 @@ __metadata: languageName: node linkType: hard -"resolve-from@npm:^5.0.0": - version: 5.0.0 - resolution: "resolve-from@npm:5.0.0" - checksum: 10c0/b21cb7f1fb746de8107b9febab60095187781137fd803e6a59a76d421444b1531b641bba5857f5dc011974d8a5c635d61cec49e6bd3b7fc20e01f0fafc4efbf2 - languageName: node - linkType: hard - "restore-cursor@npm:^5.0.0": version: 5.1.0 resolution: "restore-cursor@npm:5.1.0" @@ -7252,6 +7533,13 @@ __metadata: languageName: node linkType: hard +"rettime@npm:^0.10.1": + version: 0.10.1 + resolution: "rettime@npm:0.10.1" + checksum: 10c0/94fb30cd13684386c70301c4cff4391bc0c6dc7aeac49364fdfeeaba167897bdb28a58bbb46d1a415f1c5c6240fda3f765cb329e471f37fdc513c739f0b04fbe + languageName: node + linkType: hard + "reusify@npm:^1.0.4": version: 1.1.0 resolution: "reusify@npm:1.1.0" @@ -7689,10 +7977,10 @@ __metadata: languageName: node linkType: hard -"slash@npm:^3.0.0": - version: 3.0.0 - resolution: "slash@npm:3.0.0" - checksum: 10c0/e18488c6a42bdfd4ac5be85b2ced3ccd0224773baae6ad42cfbb9ec74fc07f9fa8396bd35ee638084ead7a2a0818eb5e7151111544d4731ce843019dab4be47b +"slash@npm:^5.1.0": + version: 5.1.0 + resolution: "slash@npm:5.1.0" + checksum: 10c0/eb48b815caf0bdc390d0519d41b9e0556a14380f6799c72ba35caf03544d501d18befdeeef074bc9c052acf69654bc9e0d79d7f1de0866284137a40805299eb3 languageName: node linkType: hard @@ -7847,7 +8135,14 @@ __metadata: languageName: node linkType: hard -"string-width@npm:^4.1.0, string-width@npm:^4.2.3": +"strict-event-emitter@npm:^0.5.1": + version: 0.5.1 + resolution: "strict-event-emitter@npm:0.5.1" + checksum: 10c0/f5228a6e6b6393c57f52f62e673cfe3be3294b35d6f7842fc24b172ae0a6e6c209fa83241d0e433fc267c503bc2f4ffdbe41a9990ff8ffd5ac425ec0489417f7 + languageName: node + linkType: hard + +"string-width@npm:^4.1.0, string-width@npm:^4.2.0, string-width@npm:^4.2.3": version: 4.2.3 resolution: "string-width@npm:4.2.3" dependencies: @@ -7897,69 +8192,78 @@ __metadata: languageName: node linkType: hard -"strip-json-comments@npm:3.1.1, strip-json-comments@npm:^3.1.1": +"strip-indent@npm:^3.0.0": + version: 3.0.0 + resolution: "strip-indent@npm:3.0.0" + dependencies: + min-indent: "npm:^1.0.0" + checksum: 10c0/ae0deaf41c8d1001c5d4fbe16cb553865c1863da4fae036683b474fa926af9fc121e155cb3fc57a68262b2ae7d5b8420aa752c97a6428c315d00efe2a3875679 + languageName: node + linkType: hard + +"strip-json-comments@npm:3.1.1": version: 3.1.1 resolution: "strip-json-comments@npm:3.1.1" checksum: 10c0/9681a6257b925a7fa0f285851c0e613cc934a50661fa7bb41ca9cbbff89686bb4a0ee366e6ecedc4daafd01e83eee0720111ab294366fe7c185e935475ebcecd languageName: node linkType: hard -"stylelint-config-recommended-scss@npm:^16.0.1": - version: 16.0.2 - resolution: "stylelint-config-recommended-scss@npm:16.0.2" +"stylelint-config-recommended-scss@npm:^17.0.0": + version: 17.0.0 + resolution: "stylelint-config-recommended-scss@npm:17.0.0" dependencies: postcss-scss: "npm:^4.0.9" - stylelint-config-recommended: "npm:^17.0.0" - stylelint-scss: "npm:^6.12.1" + stylelint-config-recommended: "npm:^18.0.0" + stylelint-scss: "npm:^7.0.0" peerDependencies: postcss: ^8.3.3 - stylelint: ^16.24.0 + stylelint: ^17.0.0 peerDependenciesMeta: postcss: optional: true - checksum: 10c0/d4e30a881e248d8b039347bf967526f6afe6d6a07f18e2747e14568de32273e819ba478be7a61a0dd63178931b4e891050a34e73d296ab533aa434209a7f3146 + checksum: 10c0/05b2e8d4316c2a8cc66eed0a2a8f01237e0ee8966a2e73d0b3c6706694f7630be165daa5a0cef511bc51f7e3fcb07a84c55d948c15fe6193a7e13cf9bb67c913 languageName: node linkType: hard -"stylelint-config-recommended@npm:^17.0.0": +"stylelint-config-recommended@npm:^18.0.0": + version: 18.0.0 + resolution: "stylelint-config-recommended@npm:18.0.0" + peerDependencies: + stylelint: ^17.0.0 + checksum: 10c0/c7f8ff45c76ec23f4c8c0438894726976fd5e872c59d489f959b728d9879bba20dbf0040cd29ad3bbc00eb32befd95f5b6ca150002bb8aea74b0797bc42ccc17 + languageName: node + linkType: hard + +"stylelint-config-standard-scss@npm:^17.0.0": version: 17.0.0 - resolution: "stylelint-config-recommended@npm:17.0.0" - peerDependencies: - stylelint: ^16.23.0 - checksum: 10c0/49e5d1c0f58197b2c5585b85fad814fed9bdec44c9870368c46a762664c5ff158c1145b6337456ae194409d692992b5b87421d62880422f71d8a3360417f5ad1 - languageName: node - linkType: hard - -"stylelint-config-standard-scss@npm:^16.0.0": - version: 16.0.0 - resolution: "stylelint-config-standard-scss@npm:16.0.0" + resolution: "stylelint-config-standard-scss@npm:17.0.0" dependencies: - stylelint-config-recommended-scss: "npm:^16.0.1" - stylelint-config-standard: "npm:^39.0.0" + stylelint-config-recommended-scss: "npm:^17.0.0" + stylelint-config-standard: "npm:^40.0.0" peerDependencies: postcss: ^8.3.3 - stylelint: ^16.23.1 + stylelint: ^17.0.0 peerDependenciesMeta: postcss: optional: true - checksum: 10c0/eb77f23824c5d649b193cb71d7f9b538b32b8cc1769451b2993270361127243d4011baf891ec265711b8e34e69ce28acb57ab6c3947b51fa3713ac26f4276439 + checksum: 10c0/0506537ba896f3d5e0fb002608090fcb41aa8ba7b65f1de8533702ce7c70e3f92b275782788a8356b5b687c86c53468c223e082226dda62780294b1cba324a36 languageName: node linkType: hard -"stylelint-config-standard@npm:^39.0.0": - version: 39.0.1 - resolution: "stylelint-config-standard@npm:39.0.1" +"stylelint-config-standard@npm:^40.0.0": + version: 40.0.0 + resolution: "stylelint-config-standard@npm:40.0.0" dependencies: - stylelint-config-recommended: "npm:^17.0.0" + stylelint-config-recommended: "npm:^18.0.0" peerDependencies: - stylelint: ^16.23.0 - checksum: 10c0/70a9862a2cedcc2a1807bd92fc91c40877270cf8a39576b91ae056d6de51d3b68104b26f71056ff22461b4319e9ec988d009abf10ead513b2ec15569d82e865a + stylelint: ^17.0.0 + checksum: 10c0/d8942552d53a3afda59b64d0c49503bb626fe5cef39a9e8c9583fcd60869f21431125ef4480ff27a59f7f2cf0da8af810d377129ef1d670ddc5def4defe2880c languageName: node linkType: hard -"stylelint-scss@npm:^6.12.1": - version: 6.14.0 - resolution: "stylelint-scss@npm:6.14.0" +"stylelint-scss@npm:^7.0.0": + version: 7.0.0 + resolution: "stylelint-scss@npm:7.0.0" dependencies: css-tree: "npm:^3.0.1" is-plain-object: "npm:^5.0.0" @@ -7970,61 +8274,65 @@ __metadata: postcss-selector-parser: "npm:^7.1.1" postcss-value-parser: "npm:^4.2.0" peerDependencies: - stylelint: ^16.8.2 - checksum: 10c0/8bb49acc172347c644770939171d4e236dc35f5a2e9095d97ec8abbf8d1f4afe4a77a6c7b7e5e4113aa6feb0ece72d0d9b31b368183d98c9fdb040014cf2742d + stylelint: ^16.8.2 || ^17.0.0 + checksum: 10c0/07d0f20c6bcb34b8b0b6bfb1d4367b4825b52a7eef7dde2adfbaec11ebc67242e6b99dccf70dfbef1eb0a9bf8712fe0ab49d183ff6e4cca9c7f89752f7e27027 languageName: node linkType: hard -"stylelint@npm:^16.25.0": - version: 16.26.1 - resolution: "stylelint@npm:16.26.1" +"stylelint@npm:^17.6.0": + version: 17.6.0 + resolution: "stylelint@npm:17.6.0" dependencies: - "@csstools/css-parser-algorithms": "npm:^3.0.5" - "@csstools/css-syntax-patches-for-csstree": "npm:^1.0.19" - "@csstools/css-tokenizer": "npm:^3.0.4" - "@csstools/media-query-list-parser": "npm:^4.0.3" - "@csstools/selector-specificity": "npm:^5.0.0" - "@dual-bundle/import-meta-resolve": "npm:^4.2.1" - balanced-match: "npm:^2.0.0" + "@csstools/css-calc": "npm:^3.1.1" + "@csstools/css-parser-algorithms": "npm:^4.0.0" + "@csstools/css-syntax-patches-for-csstree": "npm:^1.1.1" + "@csstools/css-tokenizer": "npm:^4.0.0" + "@csstools/media-query-list-parser": "npm:^5.0.0" + "@csstools/selector-resolve-nested": "npm:^4.0.0" + "@csstools/selector-specificity": "npm:^6.0.0" colord: "npm:^2.9.3" - cosmiconfig: "npm:^9.0.0" - css-functions-list: "npm:^3.2.3" - css-tree: "npm:^3.1.0" + cosmiconfig: "npm:^9.0.1" + css-functions-list: "npm:^3.3.3" + css-tree: "npm:^3.2.1" debug: "npm:^4.4.3" fast-glob: "npm:^3.3.3" fastest-levenshtein: "npm:^1.0.16" - file-entry-cache: "npm:^11.1.1" + file-entry-cache: "npm:^11.1.2" global-modules: "npm:^2.0.0" - globby: "npm:^11.1.0" + globby: "npm:^16.1.1" globjoin: "npm:^0.1.4" - html-tags: "npm:^3.3.1" + html-tags: "npm:^5.1.0" ignore: "npm:^7.0.5" - imurmurhash: "npm:^0.1.4" + import-meta-resolve: "npm:^4.2.0" is-plain-object: "npm:^5.0.0" - known-css-properties: "npm:^0.37.0" - mathml-tag-names: "npm:^2.1.3" - meow: "npm:^13.2.0" + mathml-tag-names: "npm:^4.0.0" + meow: "npm:^14.1.0" micromatch: "npm:^4.0.8" normalize-path: "npm:^3.0.0" picocolors: "npm:^1.1.1" - postcss: "npm:^8.5.6" - postcss-resolve-nested-selector: "npm:^0.1.6" + postcss: "npm:^8.5.8" postcss-safe-parser: "npm:^7.0.1" - postcss-selector-parser: "npm:^7.1.0" + postcss-selector-parser: "npm:^7.1.1" postcss-value-parser: "npm:^4.2.0" - resolve-from: "npm:^5.0.0" - string-width: "npm:^4.2.3" - supports-hyperlinks: "npm:^3.2.0" + string-width: "npm:^8.2.0" + supports-hyperlinks: "npm:^4.4.0" svg-tags: "npm:^1.0.0" table: "npm:^6.9.0" - write-file-atomic: "npm:^5.0.1" + write-file-atomic: "npm:^7.0.1" bin: stylelint: bin/stylelint.mjs - checksum: 10c0/3805dfe868abdcc5a62e5726eebe5e950432cfadfc5b47c2f103ef4dede8ee1eb8a1247c9ceb01a1739c0aba68865d79899d33a707256365bb2004664524908b + checksum: 10c0/831aa281a4723f3fab3c653fae7bfc13e97458ea04d7eb3991ebd7fc3b1e4fefba24f920abb518390782ed9810b96f5652767f99a2ab537c4f6b14ea10846bc1 languageName: node linkType: hard -"supports-color@npm:^7.0.0, supports-color@npm:^7.1.0": +"supports-color@npm:^10.2.2": + version: 10.2.2 + resolution: "supports-color@npm:10.2.2" + checksum: 10c0/fb28dd7e0cdf80afb3f2a41df5e068d60c8b4f97f7140de2eaed5b42e075d82a0e980b20a2c0efd2b6d73cfacb55555285d8cc719fa0472220715aefeaa1da7c + languageName: node + linkType: hard + +"supports-color@npm:^7.1.0": version: 7.2.0 resolution: "supports-color@npm:7.2.0" dependencies: @@ -8033,13 +8341,13 @@ __metadata: languageName: node linkType: hard -"supports-hyperlinks@npm:^3.2.0": - version: 3.2.0 - resolution: "supports-hyperlinks@npm:3.2.0" +"supports-hyperlinks@npm:^4.4.0": + version: 4.4.0 + resolution: "supports-hyperlinks@npm:4.4.0" dependencies: - has-flag: "npm:^4.0.0" - supports-color: "npm:^7.0.0" - checksum: 10c0/bca527f38d4c45bc95d6a24225944675746c515ddb91e2456d00ae0b5c537658e9dd8155b996b191941b0c19036195a098251304b9082bbe00cd1781f3cd838e + has-flag: "npm:^5.0.1" + supports-color: "npm:^10.2.2" + checksum: 10c0/1172347b736e52f012506e162d5782d5fe9c64e22d286bd6daffbd182ca5696cc341fb0f66a550e2b96b5cdf31fc5217b009c6b92150843585debc6d8f1697bd languageName: node linkType: hard @@ -8070,6 +8378,13 @@ __metadata: languageName: node linkType: hard +"tagged-tag@npm:^1.0.0": + version: 1.0.0 + resolution: "tagged-tag@npm:1.0.0" + checksum: 10c0/91d25c9ffb86a91f20522cefb2cbec9b64caa1febe27ad0df52f08993ff60888022d771e868e6416cf2e72dab68449d2139e8709ba009b74c6c7ecd4000048d1 + languageName: node + linkType: hard + "tar@npm:^7.4.3, tar@npm:^7.5.4": version: 7.5.13 resolution: "tar@npm:7.5.13" @@ -8107,7 +8422,7 @@ __metadata: languageName: node linkType: hard -"tinyrainbow@npm:^3.0.3": +"tinyrainbow@npm:^3.1.0": version: 3.1.0 resolution: "tinyrainbow@npm:3.1.0" checksum: 10c0/f11cf387a26c5c9255bec141a90ac511b26172981b10c3e50053bc6700ea7d2336edcc4a3a21dbb8412fe7c013477d2ba4d7e4877800f3f8107be5105aad6511 @@ -8148,7 +8463,7 @@ __metadata: languageName: node linkType: hard -"tough-cookie@npm:^6.0.0": +"tough-cookie@npm:^6.0.0, tough-cookie@npm:^6.0.1": version: 6.0.1 resolution: "tough-cookie@npm:6.0.1" dependencies: @@ -8185,7 +8500,7 @@ __metadata: languageName: node linkType: hard -"tslib@npm:^2.1.0, tslib@npm:^2.2.0, tslib@npm:^2.3.0, tslib@npm:^2.4.0, tslib@npm:^2.8.1": +"tslib@npm:^2.1.0, tslib@npm:^2.2.0, tslib@npm:^2.3.0, tslib@npm:^2.3.1, tslib@npm:^2.4.0, tslib@npm:^2.8.1": version: 2.8.1 resolution: "tslib@npm:2.8.1" checksum: 10c0/9c4759110a19c53f992d9aae23aac5ced636e99887b51b9e61def52611732872ff7668757d4e4c61f19691e36f4da981cd9485e869b4a7408d689f6bf1f14e62 @@ -8212,6 +8527,15 @@ __metadata: languageName: node linkType: hard +"type-fest@npm:^5.2.0": + version: 5.5.0 + resolution: "type-fest@npm:5.5.0" + dependencies: + tagged-tag: "npm:^1.0.0" + checksum: 10c0/60bf79a8df45abf99490e3204eceb5cf7f915413f8a69fb578c75cab37ddcb7d29ee21f185f0e1617323ac0b2a441e001b8dc691e220d0b087e9c29ea205538c + languageName: node + linkType: hard + "type-is@npm:^2.0.1": version: 2.0.1 resolution: "type-is@npm:2.0.1" @@ -8223,7 +8547,7 @@ __metadata: languageName: node linkType: hard -"typescript-eslint@npm:^8.56.1": +"typescript-eslint@npm:^8.57.2": version: 8.57.2 resolution: "typescript-eslint@npm:8.57.2" dependencies: @@ -8265,20 +8589,27 @@ __metadata: languageName: node linkType: hard -"undici@npm:7.22.0": - version: 7.22.0 - resolution: "undici@npm:7.22.0" - checksum: 10c0/09777c06f3f18f761f03e3a4c9c04fd9fcca8ad02ccea43602ee4adf73fcba082806f1afb637f6ea714ef6279c5323c25b16d435814c63db720f63bfc20d316b +"undici@npm:7.24.4": + version: 7.24.4 + resolution: "undici@npm:7.24.4" + checksum: 10c0/cb302e81fadb7f0b7946ab77595715c0961b46a025ccecae79ba599432d0bc8d1e3da4dfe7ff66bc74f115c1b8ff0f099bc4e9bf313db4562da23995872c6d17 languageName: node linkType: hard -"undici@npm:^7.21.0": +"undici@npm:^7.24.5": version: 7.24.6 resolution: "undici@npm:7.24.6" checksum: 10c0/0f5413ccb20bafe27637a3a02cada731c53ee75f1df79029099db3af1eaaed410488489d9f430c09bd30bf0b925cb75fc30c39dff0689f656fd6fb7d75ded95f languageName: node linkType: hard +"unicorn-magic@npm:^0.4.0": + version: 0.4.0 + resolution: "unicorn-magic@npm:0.4.0" + checksum: 10c0/cd6eff90967a5528dfa2016bdb5b38b0cd64c8558f9ba04fb5c2c23f3a232a67dfe2bfa4c45af3685d5f1a40dbac6a36d48e053f80f97ae4da1e0f6a55431685 + languageName: node + linkType: hard + "unpipe@npm:~1.0.0": version: 1.0.0 resolution: "unpipe@npm:1.0.0" @@ -8286,6 +8617,13 @@ __metadata: languageName: node linkType: hard +"until-async@npm:^3.0.2": + version: 3.0.2 + resolution: "until-async@npm:3.0.2" + checksum: 10c0/61c8b03895dbe18fe3d90316d0a1894e0c131ea4b1673f6ce78eed993d0bb81bbf4b7adf8477e9ff7725782a76767eed9d077561cfc9f89b4a1ebe61f7c9828e + languageName: node + linkType: hard + "update-browserslist-db@npm:^1.2.0": version: 1.2.3 resolution: "update-browserslist-db@npm:1.2.3" @@ -8451,17 +8789,29 @@ __metadata: languageName: node linkType: hard -"vitest@npm:^4.0.17": - version: 4.1.1 - resolution: "vitest@npm:4.1.1" +"vitest-canvas-mock@npm:^1.1.4": + version: 1.1.4 + resolution: "vitest-canvas-mock@npm:1.1.4" dependencies: - "@vitest/expect": "npm:4.1.1" - "@vitest/mocker": "npm:4.1.1" - "@vitest/pretty-format": "npm:4.1.1" - "@vitest/runner": "npm:4.1.1" - "@vitest/snapshot": "npm:4.1.1" - "@vitest/spy": "npm:4.1.1" - "@vitest/utils": "npm:4.1.1" + cssfontparser: "npm:^1.2.1" + moo-color: "npm:^1.0.3" + peerDependencies: + vitest: ^3.0.0 || ^4.0.0 + checksum: 10c0/f0a6de8541533e0316dae7690d9ca8ee9cd3f775099a528e7ce21a3eb93ef7793ef4a7edee1fe65f6bdf92c771cf34602d2b7ad9f3bade4b1f040f584d0ba262 + languageName: node + linkType: hard + +"vitest@npm:^4.1.2": + version: 4.1.2 + resolution: "vitest@npm:4.1.2" + dependencies: + "@vitest/expect": "npm:4.1.2" + "@vitest/mocker": "npm:4.1.2" + "@vitest/pretty-format": "npm:4.1.2" + "@vitest/runner": "npm:4.1.2" + "@vitest/snapshot": "npm:4.1.2" + "@vitest/spy": "npm:4.1.2" + "@vitest/utils": "npm:4.1.2" es-module-lexer: "npm:^2.0.0" expect-type: "npm:^1.3.0" magic-string: "npm:^0.30.21" @@ -8472,17 +8822,17 @@ __metadata: tinybench: "npm:^2.9.0" tinyexec: "npm:^1.0.2" tinyglobby: "npm:^0.2.15" - tinyrainbow: "npm:^3.0.3" + tinyrainbow: "npm:^3.1.0" vite: "npm:^6.0.0 || ^7.0.0 || ^8.0.0" why-is-node-running: "npm:^2.3.0" peerDependencies: "@edge-runtime/vm": "*" "@opentelemetry/api": ^1.9.0 "@types/node": ^20.0.0 || ^22.0.0 || >=24.0.0 - "@vitest/browser-playwright": 4.1.1 - "@vitest/browser-preview": 4.1.1 - "@vitest/browser-webdriverio": 4.1.1 - "@vitest/ui": 4.1.1 + "@vitest/browser-playwright": 4.1.2 + "@vitest/browser-preview": 4.1.2 + "@vitest/browser-webdriverio": 4.1.2 + "@vitest/ui": 4.1.2 happy-dom: "*" jsdom: "*" vite: ^6.0.0 || ^7.0.0 || ^8.0.0 @@ -8509,7 +8859,7 @@ __metadata: optional: false bin: vitest: vitest.mjs - checksum: 10c0/ff9e0f2a0fcdf03cd9e0a73bd8c5c3f05e1c67bae577713d69473be312aca75f1f05482b1dc017cdf9a5315e0d40ffa10d01817633d9e84895c2b910545a2369 + checksum: 10c0/061fdd0319ba533c926b139b9377a7dbf91e63d815d86fe318a207bd19842b74ca6f6402ea61b26ed9d2924306bdb4d0b13f69c29e2a2a89b3b67602bcccb54c languageName: node linkType: hard @@ -8553,7 +8903,7 @@ __metadata: languageName: node linkType: hard -"whatwg-url@npm:^16.0.0": +"whatwg-url@npm:^16.0.0, whatwg-url@npm:^16.0.1": version: 16.0.1 resolution: "whatwg-url@npm:16.0.1" dependencies: @@ -8627,6 +8977,17 @@ __metadata: languageName: node linkType: hard +"wrap-ansi@npm:^7.0.0": + version: 7.0.0 + resolution: "wrap-ansi@npm:7.0.0" + dependencies: + ansi-styles: "npm:^4.0.0" + string-width: "npm:^4.1.0" + strip-ansi: "npm:^6.0.0" + checksum: 10c0/d15fc12c11e4cbc4044a552129ebc75ee3f57aa9c1958373a4db0292d72282f54373b536103987a4a7594db1ef6a4f10acf92978f79b98c49306a4b58c77d4da + languageName: node + linkType: hard + "wrap-ansi@npm:^9.0.0": version: 9.0.2 resolution: "wrap-ansi@npm:9.0.2" @@ -8645,17 +9006,16 @@ __metadata: languageName: node linkType: hard -"write-file-atomic@npm:^5.0.1": - version: 5.0.1 - resolution: "write-file-atomic@npm:5.0.1" +"write-file-atomic@npm:^7.0.1": + version: 7.0.1 + resolution: "write-file-atomic@npm:7.0.1" dependencies: - imurmurhash: "npm:^0.1.4" signal-exit: "npm:^4.0.1" - checksum: 10c0/e8c850a8e3e74eeadadb8ad23c9d9d63e4e792bd10f4836ed74189ef6e996763959f1249c5650e232f3c77c11169d239cbfc8342fc70f3fe401407d23810505d + checksum: 10c0/69cebb64945e22928a24ae7e2a55bf54438c92d6f657c1fa5e96b7c7a50f6c022e7454ab5c259079bb35f60296242f3a21234c79320d64a8ad57675b56a2098d languageName: node linkType: hard -"ws@npm:^8.19.0": +"ws@npm:^8.20.0": version: 8.20.0 resolution: "ws@npm:8.20.0" peerDependencies: @@ -8712,6 +9072,13 @@ __metadata: languageName: node linkType: hard +"yargs-parser@npm:^21.1.1": + version: 21.1.1 + resolution: "yargs-parser@npm:21.1.1" + checksum: 10c0/f84b5e48169479d2f402239c59f084cfd1c3acc197a05c59b98bab067452e6b3ea46d4dd8ba2985ba7b3d32a343d77df0debd6b343e5dae3da2aab2cdf5886b2 + languageName: node + linkType: hard + "yargs-parser@npm:^22.0.0": version: 22.0.0 resolution: "yargs-parser@npm:22.0.0" @@ -8733,6 +9100,21 @@ __metadata: languageName: node linkType: hard +"yargs@npm:^17.7.2": + version: 17.7.2 + resolution: "yargs@npm:17.7.2" + dependencies: + cliui: "npm:^8.0.1" + escalade: "npm:^3.1.1" + get-caller-file: "npm:^2.0.5" + require-directory: "npm:^2.1.1" + string-width: "npm:^4.2.3" + y18n: "npm:^5.0.5" + yargs-parser: "npm:^21.1.1" + checksum: 10c0/ccd7e723e61ad5965fffbb791366db689572b80cca80e0f96aad968dfff4156cd7cd1ad18607afe1046d8241e6fb2d6c08bf7fa7bfb5eaec818735d8feac8f05 + languageName: node + linkType: hard + "yocto-queue@npm:^0.1.0": version: 0.1.0 resolution: "yocto-queue@npm:0.1.0"