diff --git a/frontend/src/app/features/book/browse/book-browse-scope.ts b/frontend/src/app/features/book/browse/book-browse-scope.ts index 9887ddff3..1f034446e 100644 --- a/frontend/src/app/features/book/browse/book-browse-scope.ts +++ b/frontend/src/app/features/book/browse/book-browse-scope.ts @@ -22,32 +22,42 @@ export const validBookBrowseScope: CanActivateChildFn = route => { return invalid ? inject(Router).createUrlTree(['/dashboard']) : true; }; +export const UNSHELVED_BROWSE_SCOPE: BookBrowseScope = + {kind: 'unshelved', facetKey: 'shelf_status', facetValue: 'unshelved'}; + +export function libraryBrowseScope(entityId: number): BookBrowseScope { + return {kind: 'library', entityId, facetKey: 'library', facetValue: `${entityId}`}; +} + +export function shelfBrowseScope(entityId: number): BookBrowseScope { + return {kind: 'shelf', entityId, facetKey: 'shelf', facetValue: `${entityId}`}; +} + +export function magicShelfBrowseScope(entityId: number): BookBrowseScope { + return {kind: 'magicShelf', entityId, facetKey: 'shelf', facetValue: `magic:${entityId}`}; +} + export function bookBrowseScope( paramMap: ParamMap, routeData: BookBrowseRouteData, ): BookBrowseScope | null { const libraryId = positiveId(paramMap.get('libraryId')); if (libraryId !== null) { - return {kind: 'library', entityId: libraryId, facetKey: 'library', facetValue: `${libraryId}`}; + return libraryBrowseScope(libraryId); } const shelfId = positiveId(paramMap.get('shelfId')); if (shelfId !== null) { - return {kind: 'shelf', entityId: shelfId, facetKey: 'shelf', facetValue: `${shelfId}`}; + return shelfBrowseScope(shelfId); } const magicShelfId = positiveId(paramMap.get('magicShelfId')); if (magicShelfId !== null) { - return { - kind: 'magicShelf', - entityId: magicShelfId, - facetKey: 'shelf', - facetValue: `magic:${magicShelfId}`, - }; + return magicShelfBrowseScope(magicShelfId); } if (routeData.browseScope === 'unshelved') { - return {kind: 'unshelved', facetKey: 'shelf_status', facetValue: 'unshelved'}; + return UNSHELVED_BROWSE_SCOPE; } return null; diff --git a/frontend/src/app/features/book/service/library.service.spec.ts b/frontend/src/app/features/book/service/library.service.spec.ts index a1aa6c6ad..4d10bac57 100644 --- a/frontend/src/app/features/book/service/library.service.spec.ts +++ b/frontend/src/app/features/book/service/library.service.spec.ts @@ -5,7 +5,6 @@ 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 {bookQueryKeys} from '../data/book-query-keys'; import {shelfDefinitionQueryKeys} from '../data/shelf-definition-query-keys'; import {AUTHORS_QUERY_KEY} from '../../author-browser/service/author-query-keys'; @@ -29,17 +28,10 @@ describe('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); @@ -48,7 +40,6 @@ describe('LibraryService', () => { ...queryClientHarness.providers, LibraryService, {provide: AuthService, useValue: authService}, - {provide: BookService, useValue: bookService}, ], }); @@ -124,13 +115,6 @@ describe('LibraryService', () => { request.flush({EPUB: 7, PDF: 2}); await expect(resultPromise).resolves.toEqual({EPUB: 7, PDF: 2}); - - 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', () => { diff --git a/frontend/src/app/features/book/service/library.service.ts b/frontend/src/app/features/book/service/library.service.ts index 6eb575214..e56be65ad 100644 --- a/frontend/src/app/features/book/service/library.service.ts +++ b/frontend/src/app/features/book/service/library.service.ts @@ -5,7 +5,6 @@ import {tap} from 'rxjs/operators'; import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental'; import {Library} from '../model/library.model'; -import {BookService} from './book.service'; import {API_CONFIG} from '../../../core/config/api-config'; import {AuthService} from '../../../shared/service/auth.service'; import {LIBRARIES_QUERY_KEY, libraryFormatCountsQueryKey} from './library-query-keys'; @@ -18,7 +17,6 @@ import {SHELVES_QUERY_KEY} from './shelf-query-keys'; export class LibraryService { private readonly url = `${API_CONFIG.BASE_URL}/api/v1/libraries`; private http = inject(HttpClient); - private bookService = inject(BookService); private authService = inject(AuthService); private queryClient = inject(QueryClient); private readonly token = this.authService.token; @@ -127,20 +125,6 @@ export class LibraryService { return this.libraries().find(library => library.id === id); } - getBookCountValue(libraryId: number): number { - return this.bookService.books().filter(book => book.libraryId === libraryId).length; - } - - readonly bookCountByLibraryId = computed(() => { - const counts = new Map(); - for (const book of this.bookService.books()) { - if (book.libraryId != null) { - counts.set(book.libraryId, (counts.get(book.libraryId) ?? 0) + 1); - } - } - return counts; - }); - getBookCountsByFormat(libraryId: number): Observable> { return from(this.queryClient.ensureQueryData(this.getLibraryFormatCountsQueryOptions(libraryId))); } diff --git a/frontend/src/app/features/book/service/shelf.service.spec.ts b/frontend/src/app/features/book/service/shelf.service.spec.ts index dd3a5cb16..916f112f4 100644 --- a/frontend/src/app/features/book/service/shelf.service.spec.ts +++ b/frontend/src/app/features/book/service/shelf.service.spec.ts @@ -1,15 +1,12 @@ import {HttpTestingController} from '@angular/common/http/testing'; -import {signal} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import {createAuthServiceStub, createQueryClientHarness, flushQueryAsync, flushSignalAndQueryEffects} from '../../../core/testing/query-testing'; -import type {Book} from '../model/book.model'; import type {Shelf} from '../model/shelf.model'; import {shelfDefinitionQueryKeys} from '../data/shelf-definition-query-keys'; import {bookQueryKeys} from '../data/book-query-keys'; 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'; @@ -23,40 +20,21 @@ function buildShelf(overrides: Partial = {}): Shelf { }; } -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; - }; - let currentUser: ReturnType>; beforeEach(() => { authService = createAuthServiceStub(); queryClientHarness = createQueryClientHarness(); bookService = { - books: vi.fn(() => []), removeBooksFromShelf: vi.fn(), }; - currentUser = signal<{id: number} | null>(null); - userService = { - getCurrentUser: vi.fn(() => currentUser()), - }; vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined); vi.spyOn(queryClientHarness.queryClient, 'removeQueries').mockImplementation(() => undefined); @@ -67,7 +45,6 @@ describe('ShelfService', () => { ShelfService, {provide: AuthService, useValue: authService}, {provide: BookService, useValue: bookService}, - {provide: UserService, useValue: userService}, ], }); @@ -185,58 +162,4 @@ describe('ShelfService', () => { 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'})]}), - ]); - - currentUser.set({id: 7}); - expect(service.getBookCountValue(1)).toBe(2); - - currentUser.set({id: 42}); - expect(service.getBookCountValue(2)).toBe(6); - expect(service.getBookCountValue(999)).toBe(0); - }); - - it('builds shelf count maps with local counts for the owner and persisted counts for shared shelves', 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'})]}), - ]); - - currentUser.set({id: 7}); - flushSignalAndQueryEffects(); - - const counts = service.bookCountByShelfId(); - - expect(counts.get(1)).toBe(2); - expect(counts.get(2)).toBe(6); - }); - - 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/shelf.service.ts b/frontend/src/app/features/book/service/shelf.service.ts index b8f7ae8b4..481740376 100644 --- a/frontend/src/app/features/book/service/shelf.service.ts +++ b/frontend/src/app/features/book/service/shelf.service.ts @@ -11,7 +11,6 @@ import {SHELVES_QUERY_KEY} from './shelf-query-keys'; import {BookService} from './book.service'; import {API_CONFIG} from '../../../core/config/api-config'; import {Book} from '../model/book.model'; -import {UserService} from '../../settings/user-management/user.service'; import {AuthService} from '../../../shared/service/auth.service'; const KOBO_SHELF_NAME = 'Kobo'; @@ -22,7 +21,6 @@ export class ShelfService { private readonly url = `${API_CONFIG.BASE_URL}/api/v1/shelves`; private http = inject(HttpClient); private bookService = inject(BookService); - private userService = inject(UserService); private authService = inject(AuthService); private queryClient = inject(QueryClient); private readonly token = this.authService.token; @@ -94,55 +92,10 @@ export class ShelfService { ); } - getBookCountValue(shelfId: number): number { - const shelf = this.shelves().find(currentShelf => currentShelf.id === shelfId); - if (!shelf) return 0; - - const currentUserId = this.userService.getCurrentUser()?.id; - const isOwner = currentUserId === shelf.userId; - - if (isOwner) { - return this.bookService.books().filter(book => - book.shelves?.some(currentShelf => currentShelf.id === shelfId) - ).length; - } - - return shelf.bookCount || 0; - } - getBooksOnShelf(shelfId: number): Observable { return this.http.get(`${this.url}/${shelfId}/books`); } - getUnshelvedBookCountValue(): number { - return this.bookService.books().filter(book => !book.shelves || book.shelves.length === 0).length; - } - - readonly bookCountByShelfId = computed(() => { - const currentUserId = this.userService.getCurrentUser()?.id; - const counts = new Map(); - - for (const book of this.bookService.books()) { - for (const shelf of book.shelves ?? []) { - if (shelf.id != null) { - counts.set(shelf.id, (counts.get(shelf.id) ?? 0) + 1); - } - } - } - - for (const shelf of this.shelves()) { - if (shelf.userId !== currentUserId && shelf.id != null) { - counts.set(shelf.id, shelf.bookCount ?? 0); - } - } - - return counts; - }); - - readonly unshelvedBookCount = computed(() => - this.bookService.books().filter(book => !book.shelves || book.shelves.length === 0).length - ); - private decorateShelves(shelves: Shelf[]): Shelf[] { return shelves.map((shelf) => ({ ...shelf, diff --git a/frontend/src/app/features/magic-shelf/service/book-rule-evaluator-metadata-presence.spec.ts b/frontend/src/app/features/magic-shelf/service/book-rule-evaluator-metadata-presence.spec.ts deleted file mode 100644 index d1110c339..000000000 --- a/frontend/src/app/features/magic-shelf/service/book-rule-evaluator-metadata-presence.spec.ts +++ /dev/null @@ -1,533 +0,0 @@ -import {beforeEach, describe, expect, it} from 'vitest'; -import {TestBed} from '@angular/core/testing'; -import {BookRuleEvaluatorService} from './book-rule-evaluator.service'; -import {Book, ReadStatus} from '../../book/model/book.model'; -import {GroupRule} from '../component/magic-shelf-component'; - -describe('BookRuleEvaluatorService - metadataPresence', () => { - let service: BookRuleEvaluatorService; - - beforeEach(() => { - TestBed.configureTestingModule({}); - service = TestBed.inject(BookRuleEvaluatorService); - }); - - const createBook = (overrides: Partial = {}): Book => ({ - id: 1, - bookType: 'EPUB', - libraryId: 1, - libraryName: 'Test Library', - fileName: 'test.epub', - filePath: '/path/to/test.epub', - readStatus: ReadStatus.UNREAD, - shelves: [], - metadata: { - bookId: 1, - title: 'Test Book', - authors: ['Test Author'], - categories: ['Fiction'], - language: 'en' - }, - ...overrides - }); - - const rule = (operator: string, value: string): GroupRule => ({ - name: 'test', type: 'group', join: 'and', - rules: [{field: 'metadataPresence', operator, value} as never] - }); - - describe('string fields', () => { - it('should detect present title', () => { - const book = createBook({metadata: {bookId: 1, title: 'A Book'}}); - expect(service.evaluateGroup(book, rule('equals', 'title'))).toBe(true); - expect(service.evaluateGroup(book, rule('not_equals', 'title'))).toBe(false); - }); - - it('should detect missing title', () => { - const book = createBook({metadata: {bookId: 1, title: undefined}}); - expect(service.evaluateGroup(book, rule('equals', 'title'))).toBe(false); - expect(service.evaluateGroup(book, rule('not_equals', 'title'))).toBe(true); - }); - - it('should treat empty string as absent', () => { - const book = createBook({metadata: {bookId: 1, title: ''}}); - expect(service.evaluateGroup(book, rule('equals', 'title'))).toBe(false); - }); - - it('should treat whitespace-only string as absent', () => { - const book = createBook({metadata: {bookId: 1, title: ' '}}); - expect(service.evaluateGroup(book, rule('equals', 'title'))).toBe(false); - }); - - it('should detect present subtitle', () => { - const book = createBook({metadata: {bookId: 1, subtitle: 'A Novel'}}); - expect(service.evaluateGroup(book, rule('equals', 'subtitle'))).toBe(true); - }); - - it('should detect missing subtitle', () => { - const book = createBook({metadata: {bookId: 1}}); - expect(service.evaluateGroup(book, rule('equals', 'subtitle'))).toBe(false); - }); - - it('should detect present description', () => { - const book = createBook({metadata: {bookId: 1, description: 'A tale of adventure'}}); - expect(service.evaluateGroup(book, rule('equals', 'description'))).toBe(true); - }); - - it('should detect missing description', () => { - const book = createBook({metadata: {bookId: 1}}); - expect(service.evaluateGroup(book, rule('not_equals', 'description'))).toBe(true); - }); - - it('should detect present publisher', () => { - const book = createBook({metadata: {bookId: 1, publisher: 'Tor Books'}}); - expect(service.evaluateGroup(book, rule('equals', 'publisher'))).toBe(true); - }); - - it('should detect present publishedDate', () => { - const book = createBook({metadata: {bookId: 1, publishedDate: '2024-01-01'}}); - expect(service.evaluateGroup(book, rule('equals', 'publishedDate'))).toBe(true); - }); - - it('should detect missing publishedDate', () => { - const book = createBook({metadata: {bookId: 1}}); - expect(service.evaluateGroup(book, rule('equals', 'publishedDate'))).toBe(false); - }); - - it('should detect present language', () => { - const book = createBook({metadata: {bookId: 1, language: 'en'}}); - expect(service.evaluateGroup(book, rule('equals', 'language'))).toBe(true); - }); - - it('should detect present thumbnailUrl', () => { - const book = createBook({metadata: {bookId: 1, thumbnailUrl: 'https://example.com/cover.jpg'}}); - expect(service.evaluateGroup(book, rule('equals', 'thumbnailUrl'))).toBe(true); - }); - - it('should detect missing thumbnailUrl', () => { - const book = createBook({metadata: {bookId: 1}}); - expect(service.evaluateGroup(book, rule('not_equals', 'thumbnailUrl'))).toBe(true); - }); - - it('should detect present narrator', () => { - const book = createBook({metadata: {bookId: 1, narrator: 'Stephen Fry'}}); - expect(service.evaluateGroup(book, rule('equals', 'narrator'))).toBe(true); - }); - - it('should detect present contentRating', () => { - const book = createBook({metadata: {bookId: 1, contentRating: 'MATURE'}}); - expect(service.evaluateGroup(book, rule('equals', 'contentRating'))).toBe(true); - }); - - it('should detect present seriesName', () => { - const book = createBook({metadata: {bookId: 1, seriesName: 'Dune'}}); - expect(service.evaluateGroup(book, rule('equals', 'seriesName'))).toBe(true); - }); - - it('should detect missing seriesName', () => { - const book = createBook({metadata: {bookId: 1}}); - expect(service.evaluateGroup(book, rule('equals', 'seriesName'))).toBe(false); - }); - }); - - describe('identifier fields', () => { - it('should detect present isbn13', () => { - const book = createBook({metadata: {bookId: 1, isbn13: '9780123456789'}}); - expect(service.evaluateGroup(book, rule('equals', 'isbn13'))).toBe(true); - }); - - it('should detect missing isbn13', () => { - const book = createBook({metadata: {bookId: 1}}); - expect(service.evaluateGroup(book, rule('not_equals', 'isbn13'))).toBe(true); - }); - - it('should detect present isbn10', () => { - const book = createBook({metadata: {bookId: 1, isbn10: '0123456789'}}); - expect(service.evaluateGroup(book, rule('equals', 'isbn10'))).toBe(true); - }); - - it('should detect present asin', () => { - const book = createBook({metadata: {bookId: 1, asin: 'B08N5WRWNW'}}); - expect(service.evaluateGroup(book, rule('equals', 'asin'))).toBe(true); - }); - - it('should detect missing asin', () => { - const book = createBook({metadata: {bookId: 1}}); - expect(service.evaluateGroup(book, rule('not_equals', 'asin'))).toBe(true); - }); - }); - - describe('numeric fields', () => { - it('should detect present pageCount', () => { - const book = createBook({metadata: {bookId: 1, pageCount: 350}}); - expect(service.evaluateGroup(book, rule('equals', 'pageCount'))).toBe(true); - }); - - it('should detect missing pageCount', () => { - const book = createBook({metadata: {bookId: 1}}); - expect(service.evaluateGroup(book, rule('equals', 'pageCount'))).toBe(false); - }); - - it('should treat zero pageCount as present', () => { - const book = createBook({metadata: {bookId: 1, pageCount: 0}}); - expect(service.evaluateGroup(book, rule('equals', 'pageCount'))).toBe(true); - }); - - it('should detect present seriesNumber', () => { - const book = createBook({metadata: {bookId: 1, seriesNumber: 3}}); - expect(service.evaluateGroup(book, rule('equals', 'seriesNumber'))).toBe(true); - }); - - it('should detect present seriesTotal', () => { - const book = createBook({metadata: {bookId: 1, seriesTotal: 10}}); - expect(service.evaluateGroup(book, rule('equals', 'seriesTotal'))).toBe(true); - }); - - it('should detect present ageRating', () => { - const book = createBook({metadata: {bookId: 1, ageRating: 16}}); - expect(service.evaluateGroup(book, rule('equals', 'ageRating'))).toBe(true); - }); - }); - - describe('array fields', () => { - it('should detect present authors', () => { - const book = createBook({metadata: {bookId: 1, authors: ['Author One']}}); - expect(service.evaluateGroup(book, rule('equals', 'authors'))).toBe(true); - }); - - it('should detect empty authors as absent', () => { - const book = createBook({metadata: {bookId: 1, authors: []}}); - expect(service.evaluateGroup(book, rule('equals', 'authors'))).toBe(false); - expect(service.evaluateGroup(book, rule('not_equals', 'authors'))).toBe(true); - }); - - it('should detect missing authors (undefined) as absent', () => { - const book = createBook({metadata: {bookId: 1, authors: undefined}}); - expect(service.evaluateGroup(book, rule('equals', 'authors'))).toBe(false); - }); - - it('should detect present categories', () => { - const book = createBook({metadata: {bookId: 1, categories: ['Fantasy']}}); - expect(service.evaluateGroup(book, rule('equals', 'categories'))).toBe(true); - }); - - it('should detect empty categories as absent', () => { - const book = createBook({metadata: {bookId: 1, categories: []}}); - expect(service.evaluateGroup(book, rule('equals', 'categories'))).toBe(false); - }); - - it('should detect present moods', () => { - const book = createBook({metadata: {bookId: 1, moods: ['Dark', 'Atmospheric']}}); - expect(service.evaluateGroup(book, rule('equals', 'moods'))).toBe(true); - }); - - it('should detect missing moods as absent', () => { - const book = createBook({metadata: {bookId: 1}}); - expect(service.evaluateGroup(book, rule('not_equals', 'moods'))).toBe(true); - }); - - it('should detect present tags', () => { - const book = createBook({metadata: {bookId: 1, tags: ['favorite']}}); - expect(service.evaluateGroup(book, rule('equals', 'tags'))).toBe(true); - }); - - it('should detect missing tags as absent', () => { - const book = createBook({metadata: {bookId: 1}}); - expect(service.evaluateGroup(book, rule('not_equals', 'tags'))).toBe(true); - }); - }); - - describe('rating fields', () => { - it('should detect present personalRating', () => { - const book = createBook({personalRating: 8}); - expect(service.evaluateGroup(book, rule('equals', 'personalRating'))).toBe(true); - }); - - it('should detect missing personalRating', () => { - const book = createBook({personalRating: undefined}); - expect(service.evaluateGroup(book, rule('equals', 'personalRating'))).toBe(false); - expect(service.evaluateGroup(book, rule('not_equals', 'personalRating'))).toBe(true); - }); - - it('should detect present amazonRating', () => { - const book = createBook({metadata: {bookId: 1, amazonRating: 4.5}}); - expect(service.evaluateGroup(book, rule('equals', 'amazonRating'))).toBe(true); - }); - - it('should detect missing amazonRating', () => { - const book = createBook({metadata: {bookId: 1}}); - expect(service.evaluateGroup(book, rule('not_equals', 'amazonRating'))).toBe(true); - }); - - it('should detect present goodreadsRating', () => { - const book = createBook({metadata: {bookId: 1, goodreadsRating: 4.1}}); - expect(service.evaluateGroup(book, rule('equals', 'goodreadsRating'))).toBe(true); - }); - - it('should detect present hardcoverRating', () => { - const book = createBook({metadata: {bookId: 1, hardcoverRating: 3.9}}); - expect(service.evaluateGroup(book, rule('equals', 'hardcoverRating'))).toBe(true); - }); - - it('should detect present ranobedbRating', () => { - const book = createBook({metadata: {bookId: 1, ranobedbRating: 4.0}}); - expect(service.evaluateGroup(book, rule('equals', 'ranobedbRating'))).toBe(true); - }); - - it('should detect present lubimyczytacRating', () => { - const book = createBook({metadata: {bookId: 1, lubimyczytacRating: 4.2}}); - expect(service.evaluateGroup(book, rule('equals', 'lubimyczytacRating'))).toBe(true); - }); - - it('should detect present audibleRating', () => { - const book = createBook({metadata: {bookId: 1, audibleRating: 4.7}}); - expect(service.evaluateGroup(book, rule('equals', 'audibleRating'))).toBe(true); - }); - }); - - describe('review count fields', () => { - it('should detect present amazonReviewCount', () => { - const book = createBook({metadata: {bookId: 1, amazonReviewCount: 1200}}); - expect(service.evaluateGroup(book, rule('equals', 'amazonReviewCount'))).toBe(true); - }); - - it('should detect missing amazonReviewCount', () => { - const book = createBook({metadata: {bookId: 1}}); - expect(service.evaluateGroup(book, rule('not_equals', 'amazonReviewCount'))).toBe(true); - }); - - it('should detect present goodreadsReviewCount', () => { - const book = createBook({metadata: {bookId: 1, goodreadsReviewCount: 5000}}); - expect(service.evaluateGroup(book, rule('equals', 'goodreadsReviewCount'))).toBe(true); - }); - - it('should detect present hardcoverReviewCount', () => { - const book = createBook({metadata: {bookId: 1, hardcoverReviewCount: 300}}); - expect(service.evaluateGroup(book, rule('equals', 'hardcoverReviewCount'))).toBe(true); - }); - - it('should detect present audibleReviewCount', () => { - const book = createBook({metadata: {bookId: 1, audibleReviewCount: 500}}); - expect(service.evaluateGroup(book, rule('equals', 'audibleReviewCount'))).toBe(true); - }); - }); - - describe('external ID fields', () => { - it('should detect present goodreadsId', () => { - const book = createBook({metadata: {bookId: 1, goodreadsId: '12345'}}); - expect(service.evaluateGroup(book, rule('equals', 'goodreadsId'))).toBe(true); - }); - - it('should detect missing goodreadsId', () => { - const book = createBook({metadata: {bookId: 1}}); - expect(service.evaluateGroup(book, rule('not_equals', 'goodreadsId'))).toBe(true); - }); - - it('should detect present hardcoverId', () => { - const book = createBook({metadata: {bookId: 1, hardcoverId: 'hc-123'}}); - expect(service.evaluateGroup(book, rule('equals', 'hardcoverId'))).toBe(true); - }); - - it('should detect present googleId', () => { - const book = createBook({metadata: {bookId: 1, googleId: 'gid-456'}}); - expect(service.evaluateGroup(book, rule('equals', 'googleId'))).toBe(true); - }); - - it('should detect present audibleId', () => { - const book = createBook({metadata: {bookId: 1, audibleId: 'aud-789'}}); - expect(service.evaluateGroup(book, rule('equals', 'audibleId'))).toBe(true); - }); - - it('should detect present lubimyczytacId', () => { - const book = createBook({metadata: {bookId: 1, lubimyczytacId: 'lub-321'}}); - expect(service.evaluateGroup(book, rule('equals', 'lubimyczytacId'))).toBe(true); - }); - - it('should detect present ranobedbId', () => { - const book = createBook({metadata: {bookId: 1, ranobedbId: 'ran-654'}}); - expect(service.evaluateGroup(book, rule('equals', 'ranobedbId'))).toBe(true); - }); - - it('should detect present comicvineId', () => { - const book = createBook({metadata: {bookId: 1, comicvineId: 'cv-987'}}); - expect(service.evaluateGroup(book, rule('equals', 'comicvineId'))).toBe(true); - }); - - it('should detect missing comicvineId', () => { - const book = createBook({metadata: {bookId: 1}}); - expect(service.evaluateGroup(book, rule('not_equals', 'comicvineId'))).toBe(true); - }); - }); - - describe('boolean fields', () => { - it('should detect present abridged (true)', () => { - const book = createBook({metadata: {bookId: 1, abridged: true}}); - expect(service.evaluateGroup(book, rule('equals', 'abridged'))).toBe(true); - }); - - it('should detect present abridged (false)', () => { - const book = createBook({metadata: {bookId: 1, abridged: false}}); - expect(service.evaluateGroup(book, rule('equals', 'abridged'))).toBe(true); - }); - - it('should detect missing abridged', () => { - const book = createBook({metadata: {bookId: 1}}); - expect(service.evaluateGroup(book, rule('equals', 'abridged'))).toBe(false); - expect(service.evaluateGroup(book, rule('not_equals', 'abridged'))).toBe(true); - }); - }); - - describe('audiobook fields', () => { - it('should detect present audiobookDuration', () => { - const book = createBook({metadata: {bookId: 1, audiobookMetadata: {durationSeconds: 36000}}}); - expect(service.evaluateGroup(book, rule('equals', 'audiobookDuration'))).toBe(true); - }); - - it('should detect missing audiobookDuration (no audiobookMetadata)', () => { - const book = createBook({metadata: {bookId: 1}}); - expect(service.evaluateGroup(book, rule('not_equals', 'audiobookDuration'))).toBe(true); - }); - - it('should detect zero audiobookDuration as present', () => { - const book = createBook({metadata: {bookId: 1, audiobookMetadata: {durationSeconds: 0}}}); - expect(service.evaluateGroup(book, rule('equals', 'audiobookDuration'))).toBe(true); - }); - }); - - describe('comic metadata fields', () => { - it('should detect present comicCharacters', () => { - const book = createBook({metadata: {bookId: 1, comicMetadata: {characters: ['Batman', 'Joker']}}}); - expect(service.evaluateGroup(book, rule('equals', 'comicCharacters'))).toBe(true); - }); - - it('should detect empty comicCharacters as absent', () => { - const book = createBook({metadata: {bookId: 1, comicMetadata: {characters: []}}}); - expect(service.evaluateGroup(book, rule('equals', 'comicCharacters'))).toBe(false); - }); - - it('should detect missing comicCharacters (no comicMetadata)', () => { - const book = createBook({metadata: {bookId: 1}}); - expect(service.evaluateGroup(book, rule('not_equals', 'comicCharacters'))).toBe(true); - }); - - it('should detect present comicTeams', () => { - const book = createBook({metadata: {bookId: 1, comicMetadata: {teams: ['Justice League']}}}); - expect(service.evaluateGroup(book, rule('equals', 'comicTeams'))).toBe(true); - }); - - it('should detect present comicLocations', () => { - const book = createBook({metadata: {bookId: 1, comicMetadata: {locations: ['Gotham City']}}}); - expect(service.evaluateGroup(book, rule('equals', 'comicLocations'))).toBe(true); - }); - - it('should detect present comicPencillers', () => { - const book = createBook({metadata: {bookId: 1, comicMetadata: {pencillers: ['Jim Lee']}}}); - expect(service.evaluateGroup(book, rule('equals', 'comicPencillers'))).toBe(true); - }); - - it('should detect present comicInkers', () => { - const book = createBook({metadata: {bookId: 1, comicMetadata: {inkers: ['Scott Williams']}}}); - expect(service.evaluateGroup(book, rule('equals', 'comicInkers'))).toBe(true); - }); - - it('should detect present comicColorists', () => { - const book = createBook({metadata: {bookId: 1, comicMetadata: {colorists: ['Alex Sinclair']}}}); - expect(service.evaluateGroup(book, rule('equals', 'comicColorists'))).toBe(true); - }); - - it('should detect present comicLetterers', () => { - const book = createBook({metadata: {bookId: 1, comicMetadata: {letterers: ['Todd Klein']}}}); - expect(service.evaluateGroup(book, rule('equals', 'comicLetterers'))).toBe(true); - }); - - it('should detect present comicCoverArtists', () => { - const book = createBook({metadata: {bookId: 1, comicMetadata: {coverArtists: ['Alex Ross']}}}); - expect(service.evaluateGroup(book, rule('equals', 'comicCoverArtists'))).toBe(true); - }); - - it('should detect present comicEditors', () => { - const book = createBook({metadata: {bookId: 1, comicMetadata: {editors: ['Mark Doyle']}}}); - expect(service.evaluateGroup(book, rule('equals', 'comicEditors'))).toBe(true); - }); - }); - - describe('edge cases', () => { - it('should return false for unknown metadata field', () => { - const book = createBook(); - expect(service.evaluateGroup(book, rule('equals', 'nonExistentField'))).toBe(false); - }); - - it('should handle book with no metadata', () => { - const book = createBook({metadata: undefined}); - expect(service.evaluateGroup(book, rule('equals', 'title'))).toBe(false); - expect(service.evaluateGroup(book, rule('not_equals', 'title'))).toBe(true); - }); - - it('should handle non-string rule value gracefully', () => { - const book = createBook({metadata: {bookId: 1, title: 'Test'}}); - const g: GroupRule = { - name: 'test', type: 'group', join: 'and', - rules: [{field: 'metadataPresence', operator: 'equals', value: null} as never] - }; - expect(service.evaluateGroup(book, g)).toBe(false); - }); - - it('should not require allBooks parameter', () => { - const book = createBook({metadata: {bookId: 1, title: 'Test'}}); - expect(service.evaluateGroup(book, rule('equals', 'title'))).toBe(true); - }); - }); - - describe('combined rules', () => { - it('should match books missing cover OR description', () => { - const bookNoCover = createBook({metadata: {bookId: 1, title: 'Test', description: 'Has desc'}}); - const bookNoDesc = createBook({metadata: {bookId: 2, title: 'Test', thumbnailUrl: 'http://cover.jpg'}}); - const bookHasBoth = createBook({metadata: {bookId: 3, title: 'Test', description: 'Has desc', thumbnailUrl: 'http://cover.jpg'}}); - - const group: GroupRule = { - name: 'test', type: 'group', join: 'or', - rules: [ - {field: 'metadataPresence', operator: 'not_equals', value: 'thumbnailUrl'}, - {field: 'metadataPresence', operator: 'not_equals', value: 'description'} - ] - }; - - expect(service.evaluateGroup(bookNoCover, group)).toBe(true); - expect(service.evaluateGroup(bookNoDesc, group)).toBe(true); - expect(service.evaluateGroup(bookHasBoth, group)).toBe(false); - }); - - it('should match books with complete identifiers', () => { - const bookComplete = createBook({metadata: {bookId: 1, isbn13: '9780123456789', goodreadsId: '12345'}}); - const bookPartial = createBook({metadata: {bookId: 2, isbn13: '9780123456789'}}); - - const group: GroupRule = { - name: 'test', type: 'group', join: 'and', - rules: [ - {field: 'metadataPresence', operator: 'equals', value: 'isbn13'}, - {field: 'metadataPresence', operator: 'equals', value: 'goodreadsId'} - ] - }; - - expect(service.evaluateGroup(bookComplete, group)).toBe(true); - expect(service.evaluateGroup(bookPartial, group)).toBe(false); - }); - - it('should work with non-metadataPresence rules in same group', () => { - const book = createBook({ - readStatus: ReadStatus.UNREAD, - metadata: {bookId: 1, title: 'Test'} - }); - - const group: GroupRule = { - name: 'test', type: 'group', join: 'and', - rules: [ - {field: 'readStatus', operator: 'equals', value: 'UNREAD'}, - {field: 'metadataPresence', operator: 'not_equals', value: 'thumbnailUrl'} - ] - }; - - expect(service.evaluateGroup(book, group)).toBe(true); - }); - }); -}); diff --git a/frontend/src/app/features/magic-shelf/service/book-rule-evaluator.service.spec.ts b/frontend/src/app/features/magic-shelf/service/book-rule-evaluator.service.spec.ts deleted file mode 100644 index 005c2a601..000000000 --- a/frontend/src/app/features/magic-shelf/service/book-rule-evaluator.service.spec.ts +++ /dev/null @@ -1,1484 +0,0 @@ -import {beforeEach, describe, expect, it} from 'vitest'; -import {TestBed} from '@angular/core/testing'; -import {BookRuleEvaluatorService} from './book-rule-evaluator.service'; -import {Book, ReadStatus} from '../../book/model/book.model'; -import {GroupRule} from '../component/magic-shelf-component'; - -describe('BookRuleEvaluatorService', () => { - let service: BookRuleEvaluatorService; - - beforeEach(() => { - TestBed.configureTestingModule({}); - service = TestBed.inject(BookRuleEvaluatorService); - }); - - const createBook = (overrides: Partial = {}): Book => ({ - id: 1, - primaryFile: {id: 1, bookId: 1, bookType: 'EPUB', fileName: 'test.epub', filePath: '/path/to/test.epub', fileSizeKb: 1024}, - libraryId: 1, - libraryName: 'Test Library', - readStatus: ReadStatus.UNREAD, - shelves: [], - metadata: { - bookId: 1, - title: 'Test Book', - authors: ['Test Author'], - categories: ['Fiction'], - language: 'en' - }, - ...overrides - }); - - describe('fileType filtering', () => { - it('should filter EPUB books correctly when rule uses "epub"', () => { - const book = createBook({primaryFile: {id: 1, bookId: 1, bookType: 'EPUB'}}); - const group: GroupRule = { - name: 'test', - type: 'group', - join: 'and', - rules: [ - { - field: 'fileType', - operator: 'equals', - value: 'epub' - } - ] - }; - - const result = service.evaluateGroup(book, group); - expect(result).toBe(true); - }); - - it('should filter PDF books correctly when rule uses "pdf"', () => { - const book = createBook({primaryFile: {id: 1, bookId: 1, bookType: 'PDF'}}); - const group: GroupRule = { - name: 'test', - type: 'group', - join: 'and', - rules: [ - { - field: 'fileType', - operator: 'equals', - value: 'pdf' - } - ] - }; - - const result = service.evaluateGroup(book, group); - expect(result).toBe(true); - }); - - it('should handle CBX books correctly for cbr, cbz, and cb7 rules', () => { - const book = createBook({primaryFile: {id: 1, bookId: 1, bookType: 'CBX'}}); - - const cbrGroup: GroupRule = { - name: 'test', - type: 'group', - join: 'and', - rules: [ - { - field: 'fileType', - operator: 'equals', - value: 'cbr' - } - ] - }; - expect(service.evaluateGroup(book, cbrGroup)).toBe(true); - - const cbzGroup: GroupRule = { - name: 'test', - type: 'group', - join: 'and', - rules: [ - { - field: 'fileType', - operator: 'equals', - value: 'cbz' - } - ] - }; - expect(service.evaluateGroup(book, cbzGroup)).toBe(true); - - const cb7Group: GroupRule = { - name: 'test', - type: 'group', - join: 'and', - rules: [ - { - field: 'fileType', - operator: 'equals', - value: 'cb7' - } - ] - }; - expect(service.evaluateGroup(book, cb7Group)).toBe(true); - }); - - it('should handle not_equals operator correctly', () => { - const epubBook = createBook({primaryFile: {id: 1, bookId: 1, bookType: 'EPUB'}}); - const group: GroupRule = { - name: 'test', - type: 'group', - join: 'and', - rules: [ - { - field: 'fileType', - operator: 'not_equals', - value: 'pdf' - } - ] - }; - - const result = service.evaluateGroup(epubBook, group); - expect(result).toBe(true); - - const pdfBook = createBook({primaryFile: {id: 1, bookId: 1, bookType: 'PDF'}}); - const result2 = service.evaluateGroup(pdfBook, group); - expect(result2).toBe(false); - }); - - it('should filter EPUB books correctly when rule uses "not_equals" with "epub"', () => { - const epubBook = createBook({primaryFile: {id: 1, bookId: 1, bookType: 'EPUB'}}); - const pdfBook = createBook({primaryFile: {id: 1, bookId: 1, bookType: 'PDF'}}); - - const group: GroupRule = { - name: 'test', - type: 'group', - join: 'and', - rules: [ - { - field: 'fileType', - operator: 'not_equals', - value: 'epub' - } - ] - }; - - expect(service.evaluateGroup(epubBook, group)).toBe(false); - - expect(service.evaluateGroup(pdfBook, group)).toBe(true); - }); - }); - - describe('evaluateGroup', () => { - it('should evaluate group rules with AND logic', () => { - const book = createBook({ - primaryFile: {id: 1, bookId: 1, bookType: 'EPUB'} - }); - - const group: GroupRule = { - name: 'test', - type: 'group', - join: 'and', - rules: [ - {field: 'fileType', operator: 'equals', value: 'epub'}, - {field: 'language', operator: 'equals', value: 'en'} - ] - }; - - const result = service.evaluateGroup(book, group); - expect(result).toBe(true); - }); - - it('should evaluate group rules with OR logic', () => { - const book = createBook({primaryFile: {id: 1, bookId: 1, bookType: 'PDF'}}); - - const group: GroupRule = { - name: 'test', - type: 'group', - join: 'or', - rules: [ - {field: 'fileType', operator: 'equals', value: 'epub'}, - {field: 'fileType', operator: 'equals', value: 'pdf'} - ] - }; - - const result = service.evaluateGroup(book, group); - expect(result).toBe(true); - }); - }); - - const rule = (field: string, operator: string, value: unknown, valueEnd?: unknown): GroupRule => ({ - name: 'test', type: 'group', join: 'and', - rules: [{field, operator, value, valueEnd} as never] - }); - - const seriesBook = (num: number, status: ReadStatus, extra: Partial = {}): Book => createBook({ - id: num * 100, - readStatus: status, - metadata: { - bookId: num * 100, - title: `Book ${num}`, - seriesName: 'Dune', - seriesNumber: num, - authors: [], - categories: [], - ...extra.metadata - }, - ...extra - }); - - describe('within_last operator', () => { - it('should match addedOn within last 30 days', () => { - const book = createBook({addedOn: new Date().toISOString()}); - expect(service.evaluateGroup(book, rule('addedOn', 'within_last', 30, 'days'))).toBe(true); - }); - - it('should not match addedOn older than 30 days for within_last 30 days', () => { - const old = new Date(); - old.setDate(old.getDate() - 60); - const book = createBook({addedOn: old.toISOString()}); - expect(service.evaluateGroup(book, rule('addedOn', 'within_last', 30, 'days'))).toBe(false); - }); - - it('should work with weeks unit', () => { - const book = createBook({addedOn: new Date().toISOString()}); - expect(service.evaluateGroup(book, rule('addedOn', 'within_last', 2, 'weeks'))).toBe(true); - }); - - it('should work with months unit', () => { - const book = createBook({addedOn: new Date().toISOString()}); - expect(service.evaluateGroup(book, rule('addedOn', 'within_last', 3, 'months'))).toBe(true); - }); - - it('should work with years unit', () => { - const book = createBook({addedOn: new Date().toISOString()}); - expect(service.evaluateGroup(book, rule('addedOn', 'within_last', 1, 'years'))).toBe(true); - }); - - it('should work with dateFinished', () => { - const book = createBook({dateFinished: new Date().toISOString()}); - expect(service.evaluateGroup(book, rule('dateFinished', 'within_last', 7, 'days'))).toBe(true); - }); - - it('should work with lastReadTime', () => { - const book = createBook({lastReadTime: new Date().toISOString()}); - expect(service.evaluateGroup(book, rule('lastReadTime', 'within_last', 7, 'days'))).toBe(true); - }); - - it('should work with publishedDate', () => { - const book = createBook({metadata: {bookId: 1, publishedDate: new Date().toISOString().split('T')[0]}}); - expect(service.evaluateGroup(book, rule('publishedDate', 'within_last', 30, 'days'))).toBe(true); - }); - - it('should return false for null date', () => { - const book = createBook({addedOn: undefined}); - expect(service.evaluateGroup(book, rule('addedOn', 'within_last', 30, 'days'))).toBe(false); - }); - - it('should return false for non-date field', () => { - const book = createBook({metadata: {bookId: 1, title: 'Test', pageCount: 300}}); - expect(service.evaluateGroup(book, rule('pageCount', 'within_last', 30, 'days'))).toBe(false); - }); - }); - - describe('older_than operator', () => { - it('should match addedOn older than 30 days', () => { - const old = new Date(); - old.setDate(old.getDate() - 60); - const book = createBook({addedOn: old.toISOString()}); - expect(service.evaluateGroup(book, rule('addedOn', 'older_than', 30, 'days'))).toBe(true); - }); - - it('should not match recent addedOn for older_than 30 days', () => { - const book = createBook({addedOn: new Date().toISOString()}); - expect(service.evaluateGroup(book, rule('addedOn', 'older_than', 30, 'days'))).toBe(false); - }); - - it('should work with months unit', () => { - const old = new Date(); - old.setFullYear(old.getFullYear() - 1); - const book = createBook({addedOn: old.toISOString()}); - expect(service.evaluateGroup(book, rule('addedOn', 'older_than', 6, 'months'))).toBe(true); - }); - - it('should work with lastReadTime', () => { - const old = new Date(); - old.setMonth(old.getMonth() - 4); - const book = createBook({lastReadTime: old.toISOString()}); - expect(service.evaluateGroup(book, rule('lastReadTime', 'older_than', 3, 'months'))).toBe(true); - }); - - it('should return false for null date', () => { - const book = createBook({lastReadTime: undefined}); - expect(service.evaluateGroup(book, rule('lastReadTime', 'older_than', 3, 'months'))).toBe(false); - }); - }); - - describe('this_period operator', () => { - it('should match dateFinished this year', () => { - const book = createBook({dateFinished: new Date().toISOString()}); - expect(service.evaluateGroup(book, rule('dateFinished', 'this_period', 'year'))).toBe(true); - }); - - it('should not match dateFinished from last year for this_period year', () => { - const old = new Date(); - old.setFullYear(old.getFullYear() - 2); - const book = createBook({dateFinished: old.toISOString()}); - expect(service.evaluateGroup(book, rule('dateFinished', 'this_period', 'year'))).toBe(false); - }); - - it('should match addedOn this month', () => { - const book = createBook({addedOn: new Date().toISOString()}); - expect(service.evaluateGroup(book, rule('addedOn', 'this_period', 'month'))).toBe(true); - }); - - it('should match addedOn this week', () => { - const book = createBook({addedOn: new Date().toISOString()}); - expect(service.evaluateGroup(book, rule('addedOn', 'this_period', 'week'))).toBe(true); - }); - - it('should work with publishedDate', () => { - const book = createBook({metadata: {bookId: 1, publishedDate: new Date().toISOString().split('T')[0]}}); - expect(service.evaluateGroup(book, rule('publishedDate', 'this_period', 'year'))).toBe(true); - }); - - it('should return false for null date', () => { - const book = createBook({dateFinished: undefined}); - expect(service.evaluateGroup(book, rule('dateFinished', 'this_period', 'year'))).toBe(false); - }); - }); - - describe('seriesStatus', () => { - it('should match "reading" when a series book is READING', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.READING); - const allBooks = [b1, b2]; - expect(service.evaluateGroup(b1, rule('seriesStatus', 'equals', 'reading'), allBooks)).toBe(true); - }); - - it('should match "reading" when a series book is RE_READING', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.RE_READING); - const allBooks = [b1, b2]; - expect(service.evaluateGroup(b1, rule('seriesStatus', 'equals', 'reading'), allBooks)).toBe(true); - }); - - it('should not match "reading" when no book is READING or RE_READING', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const allBooks = [b1, b2]; - expect(service.evaluateGroup(b1, rule('seriesStatus', 'equals', 'reading'), allBooks)).toBe(false); - }); - - it('should match "not_started" when no book has been read', () => { - const b1 = seriesBook(1, ReadStatus.UNREAD); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const allBooks = [b1, b2]; - expect(service.evaluateGroup(b1, rule('seriesStatus', 'equals', 'not_started'), allBooks)).toBe(true); - }); - - it('should not match "not_started" when a book is READING', () => { - const b1 = seriesBook(1, ReadStatus.UNREAD); - const b2 = seriesBook(2, ReadStatus.READING); - const allBooks = [b1, b2]; - expect(service.evaluateGroup(b1, rule('seriesStatus', 'equals', 'not_started'), allBooks)).toBe(false); - }); - - it('should match "fully_read" when all books are READ', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.READ); - const allBooks = [b1, b2]; - expect(service.evaluateGroup(b1, rule('seriesStatus', 'equals', 'fully_read'), allBooks)).toBe(true); - }); - - it('should not match "fully_read" when some books are not READ', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const allBooks = [b1, b2]; - expect(service.evaluateGroup(b1, rule('seriesStatus', 'equals', 'fully_read'), allBooks)).toBe(false); - }); - - it('should match "completed" when own last book in series', () => { - const b1 = seriesBook(1, ReadStatus.READ, {metadata: {bookId: 100, seriesName: 'Dune', seriesNumber: 1, seriesTotal: 3}}); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const b3 = seriesBook(3, ReadStatus.UNREAD); - const allBooks = [b1, b2, b3]; - expect(service.evaluateGroup(b1, rule('seriesStatus', 'equals', 'completed'), allBooks)).toBe(true); - }); - - it('should not match "completed" when missing last book', () => { - const b1 = seriesBook(1, ReadStatus.READ, {metadata: {bookId: 100, seriesName: 'Dune', seriesNumber: 1, seriesTotal: 5}}); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const allBooks = [b1, b2]; - expect(service.evaluateGroup(b1, rule('seriesStatus', 'equals', 'completed'), allBooks)).toBe(false); - }); - - it('should match "ongoing" when missing last book', () => { - const b1 = seriesBook(1, ReadStatus.READ, {metadata: {bookId: 100, seriesName: 'Dune', seriesNumber: 1, seriesTotal: 5}}); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const allBooks = [b1, b2]; - expect(service.evaluateGroup(b1, rule('seriesStatus', 'equals', 'ongoing'), allBooks)).toBe(true); - }); - - it('should not match "ongoing" when own last book', () => { - const b1 = seriesBook(1, ReadStatus.READ, {metadata: {bookId: 100, seriesName: 'Dune', seriesNumber: 1, seriesTotal: 3}}); - const b3 = seriesBook(3, ReadStatus.UNREAD); - const allBooks = [b1, b3]; - expect(service.evaluateGroup(b1, rule('seriesStatus', 'equals', 'ongoing'), allBooks)).toBe(false); - }); - - it('should negate with not_equals', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.READING); - const allBooks = [b1, b2]; - expect(service.evaluateGroup(b1, rule('seriesStatus', 'not_equals', 'reading'), allBooks)).toBe(false); - }); - - it('should return false for book without series', () => { - const book = createBook(); - expect(service.evaluateGroup(book, rule('seriesStatus', 'equals', 'reading'), [book])).toBe(false); - }); - }); - - describe('seriesGaps', () => { - it('should match "any_gap" when series has a missing number', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b3 = seriesBook(3, ReadStatus.UNREAD); - const allBooks = [b1, b3]; - expect(service.evaluateGroup(b1, rule('seriesGaps', 'equals', 'any_gap'), allBooks)).toBe(true); - }); - - it('should not match "any_gap" when series is contiguous', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const b3 = seriesBook(3, ReadStatus.UNREAD); - const allBooks = [b1, b2, b3]; - expect(service.evaluateGroup(b1, rule('seriesGaps', 'equals', 'any_gap'), allBooks)).toBe(false); - }); - - it('should match "missing_first" when book 1 is absent', () => { - const b2 = seriesBook(2, ReadStatus.READ); - const b3 = seriesBook(3, ReadStatus.UNREAD); - const allBooks = [b2, b3]; - expect(service.evaluateGroup(b2, rule('seriesGaps', 'equals', 'missing_first'), allBooks)).toBe(true); - }); - - it('should not match "missing_first" when book 1 exists', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const allBooks = [b1, b2]; - expect(service.evaluateGroup(b1, rule('seriesGaps', 'equals', 'missing_first'), allBooks)).toBe(false); - }); - - it('should match "missing_latest" when final book is absent', () => { - const b1 = seriesBook(1, ReadStatus.READ, {metadata: {bookId: 100, seriesName: 'Dune', seriesNumber: 1, seriesTotal: 5}}); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const allBooks = [b1, b2]; - expect(service.evaluateGroup(b1, rule('seriesGaps', 'equals', 'missing_latest'), allBooks)).toBe(true); - }); - - it('should not match "missing_latest" when final book is present', () => { - const b1 = seriesBook(1, ReadStatus.READ, {metadata: {bookId: 100, seriesName: 'Dune', seriesNumber: 1, seriesTotal: 3}}); - const b3 = seriesBook(3, ReadStatus.UNREAD); - const allBooks = [b1, b3]; - expect(service.evaluateGroup(b1, rule('seriesGaps', 'equals', 'missing_latest'), allBooks)).toBe(false); - }); - - it('should not match "missing_latest" when no seriesTotal is set', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const allBooks = [b1, b2]; - expect(service.evaluateGroup(b1, rule('seriesGaps', 'equals', 'missing_latest'), allBooks)).toBe(false); - }); - - it('should match "duplicate_number" when two books share a number', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b1dup = seriesBook(1, ReadStatus.UNREAD); - b1dup.id = 999; - const allBooks = [b1, b1dup]; - expect(service.evaluateGroup(b1, rule('seriesGaps', 'equals', 'duplicate_number'), allBooks)).toBe(true); - }); - - it('should not match "duplicate_number" when all numbers are unique', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const allBooks = [b1, b2]; - expect(service.evaluateGroup(b1, rule('seriesGaps', 'equals', 'duplicate_number'), allBooks)).toBe(false); - }); - - it('should return false for book without series', () => { - const book = createBook(); - expect(service.evaluateGroup(book, rule('seriesGaps', 'equals', 'any_gap'), [book])).toBe(false); - }); - }); - - describe('seriesPosition', () => { - it('should match "first_in_series" for lowest numbered book', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const b3 = seriesBook(3, ReadStatus.UNREAD); - const allBooks = [b1, b2, b3]; - expect(service.evaluateGroup(b1, rule('seriesPosition', 'equals', 'first_in_series'), allBooks)).toBe(true); - expect(service.evaluateGroup(b2, rule('seriesPosition', 'equals', 'first_in_series'), allBooks)).toBe(false); - }); - - it('should match "last_in_series" for highest numbered book', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const b3 = seriesBook(3, ReadStatus.UNREAD); - const allBooks = [b1, b2, b3]; - expect(service.evaluateGroup(b3, rule('seriesPosition', 'equals', 'last_in_series'), allBooks)).toBe(true); - expect(service.evaluateGroup(b2, rule('seriesPosition', 'equals', 'last_in_series'), allBooks)).toBe(false); - }); - - it('should match "next_unread" for the first unread after a read book', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const b3 = seriesBook(3, ReadStatus.UNREAD); - const allBooks = [b1, b2, b3]; - expect(service.evaluateGroup(b2, rule('seriesPosition', 'equals', 'next_unread'), allBooks)).toBe(true); - }); - - it('should not match "next_unread" for a later unread book', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const b3 = seriesBook(3, ReadStatus.UNREAD); - const allBooks = [b1, b2, b3]; - expect(service.evaluateGroup(b3, rule('seriesPosition', 'equals', 'next_unread'), allBooks)).toBe(false); - }); - - it('should not match "next_unread" for a READ book', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const allBooks = [b1, b2]; - expect(service.evaluateGroup(b1, rule('seriesPosition', 'equals', 'next_unread'), allBooks)).toBe(false); - }); - - it('should not match "next_unread" when no prior book is read', () => { - const b1 = seriesBook(1, ReadStatus.UNREAD); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const allBooks = [b1, b2]; - expect(service.evaluateGroup(b1, rule('seriesPosition', 'equals', 'next_unread'), allBooks)).toBe(false); - }); - - it('should negate with not_equals', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const allBooks = [b1, b2]; - expect(service.evaluateGroup(b1, rule('seriesPosition', 'not_equals', 'first_in_series'), allBooks)).toBe(false); - }); - - it('should return false for book without seriesNumber', () => { - const book = createBook({metadata: {bookId: 1, seriesName: 'Dune'}}); - expect(service.evaluateGroup(book, rule('seriesPosition', 'equals', 'first_in_series'), [book])).toBe(false); - }); - - it('should return false for book without series', () => { - const book = createBook(); - expect(service.evaluateGroup(book, rule('seriesPosition', 'equals', 'first_in_series'), [book])).toBe(false); - }); - }); - - describe('readingProgress', () => { - it('should return max of all progress sources', () => { - const book = createBook({ - epubProgress: {cfi: '', percentage: 45}, - pdfProgress: {page: 10, percentage: 20}, - koreaderProgress: {percentage: 80} - }); - expect(service.evaluateGroup(book, rule('readingProgress', 'greater_than', 70))).toBe(true); - expect(service.evaluateGroup(book, rule('readingProgress', 'greater_than', 85))).toBe(false); - }); - - it('should return 0 when no progress exists', () => { - const book = createBook(); - expect(service.evaluateGroup(book, rule('readingProgress', 'equals', 0))).toBe(true); - }); - - it('should work with less_than', () => { - const book = createBook({epubProgress: {cfi: '', percentage: 5}}); - expect(service.evaluateGroup(book, rule('readingProgress', 'less_than', 10))).toBe(true); - }); - - it('should work with in_between', () => { - const book = createBook({pdfProgress: {page: 50, percentage: 50}}); - const g: GroupRule = { - name: 'test', type: 'group', join: 'and', - rules: [{field: 'readingProgress', operator: 'in_between', value: null, valueStart: 40, valueEnd: 60}] - }; - expect(service.evaluateGroup(book, g)).toBe(true); - }); - - it('should pick kobo progress when it is the highest', () => { - const book = createBook({koboProgress: {percentage: 95}}); - expect(service.evaluateGroup(book, rule('readingProgress', 'greater_than', 90))).toBe(true); - }); - - it('should pick cbx progress when it is the highest', () => { - const book = createBook({cbxProgress: {page: 5, percentage: 60}}); - expect(service.evaluateGroup(book, rule('readingProgress', 'greater_than_equal_to', 60))).toBe(true); - }); - - it('should pick audiobook progress when it is the highest', () => { - const book = createBook({audiobookProgress: {positionMs: 1000, percentage: 75}}); - expect(service.evaluateGroup(book, rule('readingProgress', 'greater_than', 70))).toBe(true); - }); - }); - - describe('new fields', () => { - it('should filter by addedOn with equals', () => { - const date = '2025-06-15T10:00:00Z'; - const book = createBook({addedOn: date}); - expect(service.evaluateGroup(book, rule('addedOn', 'equals', date))).toBe(true); - }); - - it('should filter by description with contains', () => { - const book = createBook({metadata: {bookId: 1, description: 'A tale of dragons and fire'}}); - expect(service.evaluateGroup(book, rule('description', 'contains', 'dragon'))).toBe(true); - }); - - it('should filter by narrator with contains', () => { - const book = createBook({metadata: {bookId: 1, narrator: 'Stephen Fry'}}); - expect(service.evaluateGroup(book, rule('narrator', 'contains', 'fry'))).toBe(true); - }); - - it('should filter by ageRating with greater_than', () => { - const book = createBook({metadata: {bookId: 1, ageRating: 16}}); - expect(service.evaluateGroup(book, rule('ageRating', 'greater_than', 13))).toBe(true); - }); - - it('should filter by contentRating with equals', () => { - const book = createBook({metadata: {bookId: 1, contentRating: 'MATURE'}}); - expect(service.evaluateGroup(book, rule('contentRating', 'equals', 'MATURE'))).toBe(true); - }); - - it('should filter by audibleRating with greater_than_equal_to', () => { - const book = createBook({metadata: {bookId: 1, audibleRating: 4.5}}); - expect(service.evaluateGroup(book, rule('audibleRating', 'greater_than_equal_to', 4))).toBe(true); - }); - - it('should filter by audibleReviewCount', () => { - const book = createBook({metadata: {bookId: 1, audibleReviewCount: 500}}); - expect(service.evaluateGroup(book, rule('audibleReviewCount', 'greater_than', 100))).toBe(true); - }); - - it('should filter by abridged with equals true', () => { - const book = createBook({metadata: {bookId: 1, abridged: true}}); - expect(service.evaluateGroup(book, rule('abridged', 'equals', true))).toBe(true); - }); - - it('should filter by abridged with equals false', () => { - const book = createBook({metadata: {bookId: 1, abridged: false}}); - expect(service.evaluateGroup(book, rule('abridged', 'equals', false))).toBe(true); - }); - - it('should filter by audiobookDuration', () => { - const book = createBook({ - metadata: {bookId: 1, audiobookMetadata: {durationSeconds: 36000}} - }); - expect(service.evaluateGroup(book, rule('audiobookDuration', 'greater_than', 30000))).toBe(true); - }); - - it('should return null for audiobookDuration when no metadata', () => { - const book = createBook(); - expect(service.evaluateGroup(book, rule('audiobookDuration', 'is_empty', null))).toBe(true); - }); - - it('should filter by isPhysical with string value from UI', () => { - const physical = createBook({isPhysical: true}); - const digital = createBook({isPhysical: false}); - expect(service.evaluateGroup(physical, rule('isPhysical', 'equals', 'true'))).toBe(true); - expect(service.evaluateGroup(digital, rule('isPhysical', 'equals', 'true'))).toBe(false); - expect(service.evaluateGroup(digital, rule('isPhysical', 'equals', 'false'))).toBe(true); - expect(service.evaluateGroup(physical, rule('isPhysical', 'not_equals', 'true'))).toBe(false); - }); - - it('should filter by lubimyczytacRating', () => { - const book = createBook({metadata: {bookId: 1, lubimyczytacRating: 4.2}}); - expect(service.evaluateGroup(book, rule('lubimyczytacRating', 'greater_than', 4))).toBe(true); - }); - - it('should filter by categories with includes_any', () => { - const book = createBook({metadata: {bookId: 1, categories: ['Science Fiction', 'Fantasy']}}); - expect(service.evaluateGroup(book, rule('categories', 'includes_any', ['fantasy']))).toBe(true); - }); - - it('should handle categories with includes_all', () => { - const book = createBook({metadata: {bookId: 1, categories: ['Science Fiction', 'Fantasy']}}); - expect(service.evaluateGroup(book, rule('categories', 'includes_all', ['science fiction', 'fantasy']))).toBe(true); - }); - - it('should handle categories with excludes_all', () => { - const book = createBook({metadata: {bookId: 1, categories: ['Science Fiction']}}); - expect(service.evaluateGroup(book, rule('categories', 'excludes_all', ['horror', 'romance']))).toBe(true); - }); - - it('should filter by description is_empty', () => { - const book = createBook({metadata: {bookId: 1}}); - expect(service.evaluateGroup(book, rule('description', 'is_empty', null))).toBe(true); - }); - - it('should filter by narrator is_not_empty', () => { - const book = createBook({metadata: {bookId: 1, narrator: 'John Smith'}}); - expect(service.evaluateGroup(book, rule('narrator', 'is_not_empty', null))).toBe(true); - }); - }); - - describe('combined Part 3 rules', () => { - it('should evaluate "Gathering Dust": UNREAD AND addedOn older_than 1 year', () => { - const old = new Date(); - old.setFullYear(old.getFullYear() - 2); - const book = createBook({readStatus: ReadStatus.UNREAD, addedOn: old.toISOString()}); - const group: GroupRule = { - name: 'test', type: 'group', join: 'and', - rules: [ - {field: 'readStatus', operator: 'equals', value: 'UNREAD'}, - {field: 'addedOn', operator: 'older_than', value: 1, valueEnd: 'years'} - ] - }; - expect(service.evaluateGroup(book, group)).toBe(true); - }); - - it('should evaluate "Barely Started": readingProgress < 10 AND READING/RE_READING', () => { - const book = createBook({ - readStatus: ReadStatus.READING, - epubProgress: {cfi: '', percentage: 5} - }); - const group: GroupRule = { - name: 'test', type: 'group', join: 'and', - rules: [ - {field: 'readingProgress', operator: 'less_than', value: 10}, - {field: 'readStatus', operator: 'includes_any', value: ['READING', 'RE_READING']} - ] - }; - expect(service.evaluateGroup(book, group)).toBe(true); - }); - - it('should evaluate "Completed Series Not Started": completed AND not_started', () => { - const b1 = seriesBook(1, ReadStatus.UNREAD, {metadata: {bookId: 100, seriesName: 'Dune', seriesNumber: 1, seriesTotal: 3}}); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const b3 = seriesBook(3, ReadStatus.UNREAD); - const allBooks = [b1, b2, b3]; - const group: GroupRule = { - name: 'test', type: 'group', join: 'and', - rules: [ - {field: 'seriesStatus', operator: 'equals', value: 'completed'}, - {field: 'seriesStatus', operator: 'equals', value: 'not_started'} - ] - }; - expect(service.evaluateGroup(b1, group, allBooks)).toBe(true); - }); - - it('should evaluate "Ongoing Series Im Behind On": ongoing AND NOT reading', () => { - const b1 = seriesBook(1, ReadStatus.READ, {metadata: {bookId: 100, seriesName: 'Dune', seriesNumber: 1, seriesTotal: 5}}); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const allBooks = [b1, b2]; - const group: GroupRule = { - name: 'test', type: 'group', join: 'and', - rules: [ - {field: 'seriesStatus', operator: 'equals', value: 'ongoing'}, - {field: 'seriesStatus', operator: 'not_equals', value: 'reading'} - ] - }; - expect(service.evaluateGroup(b1, group, allBooks)).toBe(true); - }); - }); - - describe('evaluateGroup edge cases', () => { - it('should handle nested groups', () => { - const book = createBook({readStatus: ReadStatus.READING, metadata: {bookId: 1, title: 'Epic', language: 'en', categories: ['Fantasy']}}); - const group: GroupRule = { - name: 'test', type: 'group', join: 'and', - rules: [ - {field: 'language', operator: 'equals', value: 'en'}, - { - type: 'group', join: 'or', rules: [ - {field: 'readStatus', operator: 'equals', value: 'READ'}, - {field: 'readStatus', operator: 'equals', value: 'READING'} - ] - } as never - ] - }; - expect(service.evaluateGroup(book, group)).toBe(true); - }); - - it('should pass allBooks through to nested groups', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.READING); - const allBooks = [b1, b2]; - const group: GroupRule = { - name: 'test', type: 'group', join: 'and', - rules: [ - { - type: 'group', join: 'and', rules: [ - {field: 'seriesStatus', operator: 'equals', value: 'reading'} - ] - } as never - ] - }; - expect(service.evaluateGroup(b1, group, allBooks)).toBe(true); - }); - - it('should return true for AND with empty rules', () => { - const book = createBook(); - const group: GroupRule = {name: 'test', type: 'group', join: 'and', rules: []}; - expect(service.evaluateGroup(book, group)).toBe(true); - }); - - it('should return false for OR with empty rules', () => { - const book = createBook(); - const group: GroupRule = {name: 'test', type: 'group', join: 'or', rules: []}; - expect(service.evaluateGroup(book, group)).toBe(false); - }); - - it('should fail AND when one rule fails', () => { - const book = createBook({readStatus: ReadStatus.READING}); - const group: GroupRule = { - name: 'test', type: 'group', join: 'and', - rules: [ - {field: 'readStatus', operator: 'equals', value: 'READING'}, - {field: 'readStatus', operator: 'equals', value: 'READ'} - ] - }; - expect(service.evaluateGroup(book, group)).toBe(false); - }); - - it('should pass OR when one rule passes', () => { - const book = createBook({readStatus: ReadStatus.READING}); - const group: GroupRule = { - name: 'test', type: 'group', join: 'or', - rules: [ - {field: 'readStatus', operator: 'equals', value: 'READ'}, - {field: 'readStatus', operator: 'equals', value: 'READING'} - ] - }; - expect(service.evaluateGroup(book, group)).toBe(true); - }); - }); - - describe('equals and not_equals edge cases', () => { - it('should match equals on array field (authors)', () => { - const book = createBook({metadata: {bookId: 1, authors: ['Brandon Sanderson', 'Robert Jordan']}}); - expect(service.evaluateGroup(book, rule('authors', 'equals', 'brandon sanderson'))).toBe(true); - }); - - it('should not match equals on array when value absent', () => { - const book = createBook({metadata: {bookId: 1, authors: ['Brandon Sanderson']}}); - expect(service.evaluateGroup(book, rule('authors', 'equals', 'patrick rothfuss'))).toBe(false); - }); - - it('should match not_equals on array field (all must differ)', () => { - const book = createBook({metadata: {bookId: 1, authors: ['Brandon Sanderson']}}); - expect(service.evaluateGroup(book, rule('authors', 'not_equals', 'patrick rothfuss'))).toBe(true); - }); - - it('should not match not_equals on array when value present', () => { - const book = createBook({metadata: {bookId: 1, authors: ['Brandon Sanderson']}}); - expect(service.evaluateGroup(book, rule('authors', 'not_equals', 'brandon sanderson'))).toBe(false); - }); - - it('should compare dates with equals', () => { - const date = '2024-06-15T00:00:00Z'; - const book = createBook({dateFinished: date}); - expect(service.evaluateGroup(book, rule('dateFinished', 'equals', date))).toBe(true); - }); - - it('should compare dates with not_equals', () => { - const book = createBook({dateFinished: '2024-06-15T00:00:00Z'}); - expect(service.evaluateGroup(book, rule('dateFinished', 'not_equals', '2024-01-01T00:00:00Z'))).toBe(true); - }); - - it('should compare strings case-insensitively', () => { - const book = createBook({metadata: {bookId: 1, title: 'The Great Gatsby'}}); - expect(service.evaluateGroup(book, rule('title', 'equals', 'THE GREAT GATSBY'))).toBe(true); - }); - - it('should compare numbers with equals', () => { - const book = createBook({metadata: {bookId: 1, pageCount: 350}}); - expect(service.evaluateGroup(book, rule('pageCount', 'equals', 350))).toBe(true); - }); - - it('should handle library id (numeric id field) with equals', () => { - const book = createBook({libraryId: 42}); - expect(service.evaluateGroup(book, rule('library', 'equals', 42))).toBe(true); - }); - - it('should handle shelf id (numeric id field) with includes_any', () => { - const book = createBook({shelves: [{id: 5, name: 'Fav', icon: ''}]}); - expect(service.evaluateGroup(book, rule('shelf', 'includes_any', [5]))).toBe(true); - }); - - it('should handle shelf with excludes_all', () => { - const book = createBook({shelves: [{id: 5, name: 'Fav', icon: ''}]}); - expect(service.evaluateGroup(book, rule('shelf', 'excludes_all', [99]))).toBe(true); - expect(service.evaluateGroup(book, rule('shelf', 'excludes_all', [5]))).toBe(false); - }); - - it('should handle readStatus UNSET when book has no readStatus', () => { - const book = createBook({readStatus: undefined}); - expect(service.evaluateGroup(book, rule('readStatus', 'equals', 'UNSET'))).toBe(true); - }); - }); - - describe('text operators', () => { - it('should match contains on array field (authors)', () => { - const book = createBook({metadata: {bookId: 1, authors: ['Brandon Sanderson']}}); - expect(service.evaluateGroup(book, rule('authors', 'contains', 'sanderson'))).toBe(true); - }); - - it('should not match contains on array when no element matches', () => { - const book = createBook({metadata: {bookId: 1, authors: ['Brandon Sanderson']}}); - expect(service.evaluateGroup(book, rule('authors', 'contains', 'rothfuss'))).toBe(false); - }); - - it('should match does_not_contain on string', () => { - const book = createBook({metadata: {bookId: 1, title: 'The Great Gatsby'}}); - expect(service.evaluateGroup(book, rule('title', 'does_not_contain', 'hobbit'))).toBe(true); - }); - - it('should not match does_not_contain when string matches', () => { - const book = createBook({metadata: {bookId: 1, title: 'The Great Gatsby'}}); - expect(service.evaluateGroup(book, rule('title', 'does_not_contain', 'gatsby'))).toBe(false); - }); - - it('should match does_not_contain on array field', () => { - const book = createBook({metadata: {bookId: 1, authors: ['Brandon Sanderson']}}); - expect(service.evaluateGroup(book, rule('authors', 'does_not_contain', 'rothfuss'))).toBe(true); - }); - - it('should not match does_not_contain on array when any element matches', () => { - const book = createBook({metadata: {bookId: 1, authors: ['Brandon Sanderson', 'Robert Jordan']}}); - expect(service.evaluateGroup(book, rule('authors', 'does_not_contain', 'jordan'))).toBe(false); - }); - - it('should match starts_with on string', () => { - const book = createBook({metadata: {bookId: 1, title: 'The Great Gatsby'}}); - expect(service.evaluateGroup(book, rule('title', 'starts_with', 'the great'))).toBe(true); - }); - - it('should not match starts_with when prefix differs', () => { - const book = createBook({metadata: {bookId: 1, title: 'The Great Gatsby'}}); - expect(service.evaluateGroup(book, rule('title', 'starts_with', 'gatsby'))).toBe(false); - }); - - it('should match starts_with on array (authors)', () => { - const book = createBook({metadata: {bookId: 1, authors: ['Brandon Sanderson']}}); - expect(service.evaluateGroup(book, rule('authors', 'starts_with', 'brandon'))).toBe(true); - }); - - it('should match ends_with on string', () => { - const book = createBook({metadata: {bookId: 1, title: 'The Great Gatsby'}}); - expect(service.evaluateGroup(book, rule('title', 'ends_with', 'gatsby'))).toBe(true); - }); - - it('should not match ends_with when suffix differs', () => { - const book = createBook({metadata: {bookId: 1, title: 'The Great Gatsby'}}); - expect(service.evaluateGroup(book, rule('title', 'ends_with', 'great'))).toBe(false); - }); - - it('should match ends_with on array (authors)', () => { - const book = createBook({metadata: {bookId: 1, authors: ['Brandon Sanderson']}}); - expect(service.evaluateGroup(book, rule('authors', 'ends_with', 'sanderson'))).toBe(true); - }); - - it('should return false for contains on non-string value', () => { - const book = createBook({metadata: {bookId: 1, pageCount: 350}}); - expect(service.evaluateGroup(book, rule('pageCount', 'contains', '35'))).toBe(false); - }); - - it('should return true for does_not_contain on non-string value', () => { - const book = createBook({metadata: {bookId: 1, pageCount: 350}}); - expect(service.evaluateGroup(book, rule('pageCount', 'does_not_contain', '35'))).toBe(true); - }); - - it('should return false for starts_with on non-string value', () => { - const book = createBook({metadata: {bookId: 1, pageCount: 350}}); - expect(service.evaluateGroup(book, rule('pageCount', 'starts_with', '3'))).toBe(false); - }); - - it('should return false for ends_with on non-string value', () => { - const book = createBook({metadata: {bookId: 1, pageCount: 350}}); - expect(service.evaluateGroup(book, rule('pageCount', 'ends_with', '0'))).toBe(false); - }); - }); - - describe('date comparison operators', () => { - it('should match greater_than on dates', () => { - const book = createBook({dateFinished: '2024-06-15T00:00:00Z'}); - expect(service.evaluateGroup(book, rule('dateFinished', 'greater_than', '2024-01-01T00:00:00Z'))).toBe(true); - }); - - it('should not match greater_than when date is earlier', () => { - const book = createBook({dateFinished: '2024-01-01T00:00:00Z'}); - expect(service.evaluateGroup(book, rule('dateFinished', 'greater_than', '2024-06-15T00:00:00Z'))).toBe(false); - }); - - it('should match greater_than_equal_to on exact date', () => { - const date = '2024-06-15T00:00:00Z'; - const book = createBook({dateFinished: date}); - expect(service.evaluateGroup(book, rule('dateFinished', 'greater_than_equal_to', date))).toBe(true); - }); - - it('should match less_than on dates', () => { - const book = createBook({dateFinished: '2024-01-01T00:00:00Z'}); - expect(service.evaluateGroup(book, rule('dateFinished', 'less_than', '2024-06-15T00:00:00Z'))).toBe(true); - }); - - it('should match less_than_equal_to on exact date', () => { - const date = '2024-06-15T00:00:00Z'; - const book = createBook({dateFinished: date}); - expect(service.evaluateGroup(book, rule('dateFinished', 'less_than_equal_to', date))).toBe(true); - }); - - it('should match in_between on dates', () => { - const book = createBook({dateFinished: '2024-06-15T00:00:00Z'}); - const g: GroupRule = { - name: 'test', type: 'group', join: 'and', - rules: [{field: 'dateFinished', operator: 'in_between', value: null, valueStart: '2024-01-01T00:00:00Z', valueEnd: '2024-12-31T00:00:00Z'}] - }; - expect(service.evaluateGroup(book, g)).toBe(true); - }); - - it('should not match in_between when date outside range', () => { - const book = createBook({dateFinished: '2023-06-15T00:00:00Z'}); - const g: GroupRule = { - name: 'test', type: 'group', join: 'and', - rules: [{field: 'dateFinished', operator: 'in_between', value: null, valueStart: '2024-01-01T00:00:00Z', valueEnd: '2024-12-31T00:00:00Z'}] - }; - expect(service.evaluateGroup(book, g)).toBe(false); - }); - - it('should return false for in_between when value is null', () => { - const book = createBook({dateFinished: undefined}); - const g: GroupRule = { - name: 'test', type: 'group', join: 'and', - rules: [{field: 'dateFinished', operator: 'in_between', value: null, valueStart: '2024-01-01T00:00:00Z', valueEnd: '2024-12-31T00:00:00Z'}] - }; - expect(service.evaluateGroup(book, g)).toBe(false); - }); - }); - - describe('numeric comparison edge cases', () => { - it('should match less_than_equal_to on number', () => { - const book = createBook({metadata: {bookId: 1, pageCount: 200}}); - expect(service.evaluateGroup(book, rule('pageCount', 'less_than_equal_to', 200))).toBe(true); - expect(service.evaluateGroup(book, rule('pageCount', 'less_than_equal_to', 199))).toBe(false); - }); - - it('should match in_between on number', () => { - const book = createBook({metadata: {bookId: 1, pageCount: 300}}); - const g: GroupRule = { - name: 'test', type: 'group', join: 'and', - rules: [{field: 'pageCount', operator: 'in_between', value: null, valueStart: 100, valueEnd: 500}] - }; - expect(service.evaluateGroup(book, g)).toBe(true); - }); - - it('should match fileSize with greater_than', () => { - const book = createBook({fileSizeKb: 5000}); - expect(service.evaluateGroup(book, rule('fileSize', 'greater_than', 1000))).toBe(true); - }); - - it('should match metadataScore with less_than', () => { - const book = createBook({metadataMatchScore: 45}); - expect(service.evaluateGroup(book, rule('metadataScore', 'less_than', 50))).toBe(true); - }); - - it('should match personalRating with equals', () => { - const book = createBook({personalRating: 8}); - expect(service.evaluateGroup(book, rule('personalRating', 'equals', 8))).toBe(true); - }); - - it('should match seriesNumber with greater_than', () => { - const book = createBook({metadata: {bookId: 1, seriesName: 'Dune', seriesNumber: 5}}); - expect(service.evaluateGroup(book, rule('seriesNumber', 'greater_than', 3))).toBe(true); - }); - - it('should match seriesTotal with equals', () => { - const book = createBook({metadata: {bookId: 1, seriesName: 'Dune', seriesTotal: 10}}); - expect(service.evaluateGroup(book, rule('seriesTotal', 'equals', 10))).toBe(true); - }); - }); - - describe('is_empty and is_not_empty edge cases', () => { - it('should match is_empty on empty string', () => { - const book = createBook({metadata: {bookId: 1, title: ' '}}); - expect(service.evaluateGroup(book, rule('title', 'is_empty', null))).toBe(true); - }); - - it('should not match is_empty on non-empty string', () => { - const book = createBook({metadata: {bookId: 1, title: 'Test'}}); - expect(service.evaluateGroup(book, rule('title', 'is_empty', null))).toBe(false); - }); - - it('should match is_empty on empty array', () => { - const book = createBook({metadata: {bookId: 1, authors: []}}); - expect(service.evaluateGroup(book, rule('authors', 'is_empty', null))).toBe(true); - }); - - it('should not match is_empty on non-empty array', () => { - const book = createBook({metadata: {bookId: 1, authors: ['Author']}}); - expect(service.evaluateGroup(book, rule('authors', 'is_empty', null))).toBe(false); - }); - - it('should match is_empty on null value', () => { - const book = createBook({metadata: {bookId: 1, publisher: undefined}}); - expect(service.evaluateGroup(book, rule('publisher', 'is_empty', null))).toBe(true); - }); - - it('should return false for is_empty on a number', () => { - const book = createBook({metadata: {bookId: 1, pageCount: 0}}); - expect(service.evaluateGroup(book, rule('pageCount', 'is_empty', null))).toBe(false); - }); - - it('should match is_not_empty on non-empty array', () => { - const book = createBook({metadata: {bookId: 1, tags: ['sci-fi']}}); - expect(service.evaluateGroup(book, rule('tags', 'is_not_empty', null))).toBe(true); - }); - - it('should not match is_not_empty on null', () => { - const book = createBook({metadata: {bookId: 1, isbn13: undefined}}); - expect(service.evaluateGroup(book, rule('isbn13', 'is_not_empty', null))).toBe(false); - }); - - it('should return true for is_not_empty on a number', () => { - const book = createBook({metadata: {bookId: 1, pageCount: 100}}); - expect(service.evaluateGroup(book, rule('pageCount', 'is_not_empty', null))).toBe(true); - }); - }); - - describe('multi-value operator edge cases', () => { - it('should not match includes_any when no values match', () => { - const book = createBook({metadata: {bookId: 1, categories: ['Fiction']}}); - expect(service.evaluateGroup(book, rule('categories', 'includes_any', ['horror', 'romance']))).toBe(false); - }); - - it('should match includes_all when all present', () => { - const book = createBook({metadata: {bookId: 1, moods: ['dark', 'atmospheric', 'tense']}}); - expect(service.evaluateGroup(book, rule('moods', 'includes_all', ['dark', 'tense']))).toBe(true); - }); - - it('should not match includes_all when one is missing', () => { - const book = createBook({metadata: {bookId: 1, moods: ['dark', 'atmospheric']}}); - expect(service.evaluateGroup(book, rule('moods', 'includes_all', ['dark', 'tense']))).toBe(false); - }); - - it('should not match excludes_all when one value matches', () => { - const book = createBook({metadata: {bookId: 1, tags: ['sci-fi', 'space']}}); - expect(service.evaluateGroup(book, rule('tags', 'excludes_all', ['space', 'western']))).toBe(false); - }); - - it('should match excludes_all when no values match', () => { - const book = createBook({metadata: {bookId: 1, tags: ['sci-fi', 'space']}}); - expect(service.evaluateGroup(book, rule('tags', 'excludes_all', ['western', 'noir']))).toBe(true); - }); - - it('should handle includes_any on readStatus', () => { - const book = createBook({readStatus: ReadStatus.PAUSED}); - expect(service.evaluateGroup(book, rule('readStatus', 'includes_any', ['PAUSED', 'ABANDONED']))).toBe(true); - }); - - it('should handle includes_any on language', () => { - const book = createBook({metadata: {bookId: 1, language: 'en'}}); - expect(service.evaluateGroup(book, rule('language', 'includes_any', ['en', 'fr']))).toBe(true); - }); - - it('should handle includes_any with fileType mapping', () => { - const book = createBook({primaryFile: {id: 1, bookId: 1, bookType: 'CBX'}}); - expect(service.evaluateGroup(book, rule('fileType', 'includes_any', ['cbr', 'pdf']))).toBe(true); - }); - - it('should handle null rule value as empty list', () => { - const book = createBook({metadata: {bookId: 1, authors: ['Author']}}); - expect(service.evaluateGroup(book, rule('authors', 'includes_any', null))).toBe(false); - }); - }); - - describe('fileType mapping edge cases', () => { - it('should map azw to azw3', () => { - const book = createBook({primaryFile: {id: 1, bookId: 1, bookType: 'AZW3'}}); - expect(service.evaluateGroup(book, rule('fileType', 'equals', 'azw'))).toBe(true); - }); - - it('should handle MOBI bookType', () => { - const book = createBook({primaryFile: {id: 1, bookId: 1, bookType: 'MOBI'}}); - expect(service.evaluateGroup(book, rule('fileType', 'equals', 'mobi'))).toBe(true); - }); - - it('should handle not_equals with fileType cbr mapping', () => { - const book = createBook({primaryFile: {id: 1, bookId: 1, bookType: 'PDF'}}); - expect(service.evaluateGroup(book, rule('fileType', 'not_equals', 'cbr'))).toBe(true); - }); - }); - - describe('extractBookValue coverage', () => { - it('should extract subtitle', () => { - const book = createBook({metadata: {bookId: 1, subtitle: 'A Novel'}}); - expect(service.evaluateGroup(book, rule('subtitle', 'equals', 'a novel'))).toBe(true); - }); - - it('should extract isbn13', () => { - const book = createBook({metadata: {bookId: 1, isbn13: '9780123456789'}}); - expect(service.evaluateGroup(book, rule('isbn13', 'equals', '9780123456789'))).toBe(true); - }); - - it('should extract isbn10', () => { - const book = createBook({metadata: {bookId: 1, isbn10: '0123456789'}}); - expect(service.evaluateGroup(book, rule('isbn10', 'equals', '0123456789'))).toBe(true); - }); - - it('should extract seriesName', () => { - const book = createBook({metadata: {bookId: 1, seriesName: 'Wheel of Time'}}); - expect(service.evaluateGroup(book, rule('seriesName', 'contains', 'wheel'))).toBe(true); - }); - - it('should extract amazonRating', () => { - const book = createBook({metadata: {bookId: 1, amazonRating: 4.3}}); - expect(service.evaluateGroup(book, rule('amazonRating', 'greater_than', 4))).toBe(true); - }); - - it('should extract goodreadsRating', () => { - const book = createBook({metadata: {bookId: 1, goodreadsRating: 4.1}}); - expect(service.evaluateGroup(book, rule('goodreadsRating', 'greater_than', 4))).toBe(true); - }); - - it('should extract hardcoverRating', () => { - const book = createBook({metadata: {bookId: 1, hardcoverRating: 3.8}}); - expect(service.evaluateGroup(book, rule('hardcoverRating', 'less_than', 4))).toBe(true); - }); - - it('should extract ranobedbRating', () => { - const book = createBook({metadata: {bookId: 1, ranobedbRating: 4.5}}); - expect(service.evaluateGroup(book, rule('ranobedbRating', 'equals', 4.5))).toBe(true); - }); - - it('should extract amazonReviewCount', () => { - const book = createBook({metadata: {bookId: 1, amazonReviewCount: 1200}}); - expect(service.evaluateGroup(book, rule('amazonReviewCount', 'greater_than', 1000))).toBe(true); - }); - - it('should extract goodreadsReviewCount', () => { - const book = createBook({metadata: {bookId: 1, goodreadsReviewCount: 5000}}); - expect(service.evaluateGroup(book, rule('goodreadsReviewCount', 'greater_than', 1000))).toBe(true); - }); - - it('should extract hardcoverReviewCount', () => { - const book = createBook({metadata: {bookId: 1, hardcoverReviewCount: 300}}); - expect(service.evaluateGroup(book, rule('hardcoverReviewCount', 'less_than', 500))).toBe(true); - }); - - it('should return null for publishedDate when missing', () => { - const book = createBook({metadata: {bookId: 1}}); - expect(service.evaluateGroup(book, rule('publishedDate', 'is_empty', null))).toBe(true); - }); - - it('should return null for dateFinished when missing', () => { - const book = createBook({dateFinished: undefined}); - expect(service.evaluateGroup(book, rule('dateFinished', 'is_empty', null))).toBe(true); - }); - - it('should return null for lastReadTime when missing', () => { - const book = createBook({lastReadTime: undefined}); - expect(service.evaluateGroup(book, rule('lastReadTime', 'is_empty', null))).toBe(true); - }); - - it('should handle default field via dynamic property', () => { - const book = createBook(); - (book as Record)['customField'] = 'hello'; - expect(service.evaluateGroup(book, rule('customField' as never, 'equals', 'hello'))).toBe(true); - }); - }); - - describe('seriesStatus edge cases', () => { - it('should not match "not_started" when a book is PARTIALLY_READ', () => { - const b1 = seriesBook(1, ReadStatus.UNREAD); - const b2 = seriesBook(2, ReadStatus.PARTIALLY_READ); - const allBooks = [b1, b2]; - expect(service.evaluateGroup(b1, rule('seriesStatus', 'equals', 'not_started'), allBooks)).toBe(false); - }); - - it('should not match "completed" when no seriesTotal exists', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.READ); - const allBooks = [b1, b2]; - expect(service.evaluateGroup(b1, rule('seriesStatus', 'equals', 'completed'), allBooks)).toBe(false); - }); - - it('should not match "ongoing" when no seriesTotal exists', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.READ); - const allBooks = [b1, b2]; - expect(service.evaluateGroup(b1, rule('seriesStatus', 'equals', 'ongoing'), allBooks)).toBe(false); - }); - - it('should return false for unknown status value', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const allBooks = [b1]; - expect(service.evaluateGroup(b1, rule('seriesStatus', 'equals', 'bogus'), allBooks)).toBe(false); - }); - - it('should handle completed with fractional seriesNumber matching floor(total)', () => { - const b1 = seriesBook(1, ReadStatus.READ, {metadata: {bookId: 100, seriesName: 'Dune', seriesNumber: 1, seriesTotal: 3}}); - const b3 = createBook({ - id: 300, readStatus: ReadStatus.UNREAD, - metadata: {bookId: 300, seriesName: 'Dune', seriesNumber: 3.5} - }); - const allBooks = [b1, b3]; - expect(service.evaluateGroup(b1, rule('seriesStatus', 'equals', 'completed'), allBooks)).toBe(true); - }); - - it('should only match series books from same series name', () => { - const dune1 = seriesBook(1, ReadStatus.READING); - const other = createBook({ - id: 200, readStatus: ReadStatus.UNREAD, - metadata: {bookId: 200, seriesName: 'Foundation', seriesNumber: 1} - }); - const allBooks = [dune1, other]; - expect(service.evaluateGroup(other, rule('seriesStatus', 'equals', 'not_started'), allBooks)).toBe(true); - expect(service.evaluateGroup(dune1, rule('seriesStatus', 'equals', 'reading'), allBooks)).toBe(true); - }); - }); - - describe('seriesGaps edge cases', () => { - it('should handle fractional series numbers with floor for any_gap', () => { - const b1 = createBook({ - id: 100, readStatus: ReadStatus.READ, - metadata: {bookId: 100, seriesName: 'Dune', seriesNumber: 1.5} - }); - const b3 = seriesBook(3, ReadStatus.UNREAD); - const allBooks = [b1, b3]; - expect(service.evaluateGroup(b1, rule('seriesGaps', 'equals', 'any_gap'), allBooks)).toBe(true); - }); - - it('should return false for unknown gap value', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const allBooks = [b1]; - expect(service.evaluateGroup(b1, rule('seriesGaps', 'equals', 'bogus'), allBooks)).toBe(false); - }); - - it('should return false when series has no numbered books', () => { - const book = createBook({metadata: {bookId: 1, seriesName: 'Dune'}}); - expect(service.evaluateGroup(book, rule('seriesGaps', 'equals', 'any_gap'), [book])).toBe(false); - }); - - it('should negate gaps with not_equals', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const b3 = seriesBook(3, ReadStatus.UNREAD); - const allBooks = [b1, b2, b3]; - expect(service.evaluateGroup(b1, rule('seriesGaps', 'not_equals', 'any_gap'), allBooks)).toBe(true); - }); - }); - - describe('seriesPosition edge cases', () => { - it('should handle next_unread when all books are read', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.READ); - const allBooks = [b1, b2]; - expect(service.evaluateGroup(b1, rule('seriesPosition', 'equals', 'next_unread'), allBooks)).toBe(false); - expect(service.evaluateGroup(b2, rule('seriesPosition', 'equals', 'next_unread'), allBooks)).toBe(false); - }); - - it('should handle next_unread with multiple read then first unread', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.READ); - const b3 = seriesBook(3, ReadStatus.UNREAD); - const b4 = seriesBook(4, ReadStatus.UNREAD); - const allBooks = [b1, b2, b3, b4]; - expect(service.evaluateGroup(b3, rule('seriesPosition', 'equals', 'next_unread'), allBooks)).toBe(true); - expect(service.evaluateGroup(b4, rule('seriesPosition', 'equals', 'next_unread'), allBooks)).toBe(false); - }); - - it('should return false for unknown position value', () => { - const b1 = seriesBook(1, ReadStatus.READ); - const allBooks = [b1]; - expect(service.evaluateGroup(b1, rule('seriesPosition', 'equals', 'bogus'), allBooks)).toBe(false); - }); - - it('should handle single-book series for first and last', () => { - const b1 = seriesBook(1, ReadStatus.UNREAD); - const allBooks = [b1]; - expect(service.evaluateGroup(b1, rule('seriesPosition', 'equals', 'first_in_series'), allBooks)).toBe(true); - expect(service.evaluateGroup(b1, rule('seriesPosition', 'equals', 'last_in_series'), allBooks)).toBe(true); - }); - - it('should handle fractional series numbers for first/last', () => { - const b05 = createBook({ - id: 50, readStatus: ReadStatus.UNREAD, - metadata: {bookId: 50, seriesName: 'Dune', seriesNumber: 0.5} - }); - const b1 = seriesBook(1, ReadStatus.READ); - const b2 = seriesBook(2, ReadStatus.UNREAD); - const allBooks = [b05, b1, b2]; - expect(service.evaluateGroup(b05, rule('seriesPosition', 'equals', 'first_in_series'), allBooks)).toBe(true); - expect(service.evaluateGroup(b2, rule('seriesPosition', 'equals', 'last_in_series'), allBooks)).toBe(true); - }); - }); - - describe('relative date default/edge cases', () => { - it('should default to days when valueEnd is missing for within_last', () => { - const book = createBook({addedOn: new Date().toISOString()}); - const g: GroupRule = { - name: 'test', type: 'group', join: 'and', - rules: [{field: 'addedOn', operator: 'within_last', value: 30}] - }; - expect(service.evaluateGroup(book, g)).toBe(true); - }); - - it('should default to days when valueEnd is missing for older_than', () => { - const old = new Date(); - old.setDate(old.getDate() - 60); - const book = createBook({addedOn: old.toISOString()}); - const g: GroupRule = { - name: 'test', type: 'group', join: 'and', - rules: [{field: 'addedOn', operator: 'older_than', value: 30}] - }; - expect(service.evaluateGroup(book, g)).toBe(true); - }); - - it('should default to year when value is missing for this_period', () => { - const book = createBook({addedOn: new Date().toISOString()}); - const g: GroupRule = { - name: 'test', type: 'group', join: 'and', - rules: [{field: 'addedOn', operator: 'this_period', value: null}] - }; - expect(service.evaluateGroup(book, g)).toBe(true); - }); - - it('should handle older_than with weeks unit', () => { - const old = new Date(); - old.setDate(old.getDate() - 30); - const book = createBook({addedOn: old.toISOString()}); - expect(service.evaluateGroup(book, rule('addedOn', 'older_than', 2, 'weeks'))).toBe(true); - }); - - it('should handle older_than with years unit', () => { - const old = new Date(); - old.setFullYear(old.getFullYear() - 3); - const book = createBook({addedOn: old.toISOString()}); - expect(service.evaluateGroup(book, rule('addedOn', 'older_than', 2, 'years'))).toBe(true); - }); - }); - - describe('readStatus is_empty / is_not_empty parity', () => { - it('should match is_empty when book has no readStatus', () => { - const book = createBook({readStatus: undefined}); - expect(service.evaluateGroup(book, rule('readStatus', 'is_empty', null))).toBe(true); - }); - - it('should not match is_empty when book has a readStatus', () => { - const book = createBook({readStatus: ReadStatus.READING}); - expect(service.evaluateGroup(book, rule('readStatus', 'is_empty', null))).toBe(false); - }); - - it('should not match is_not_empty when book has no readStatus', () => { - const book = createBook({readStatus: undefined}); - expect(service.evaluateGroup(book, rule('readStatus', 'is_not_empty', null))).toBe(false); - }); - - it('should match is_not_empty when book has a readStatus', () => { - const book = createBook({readStatus: ReadStatus.READ}); - expect(service.evaluateGroup(book, rule('readStatus', 'is_not_empty', null))).toBe(true); - }); - }); - - describe('unknown operator', () => { - it('should return false for an unrecognized operator', () => { - const book = createBook(); - expect(service.evaluateGroup(book, rule('title', 'regex_match' as never, '.*'))).toBe(false); - }); - }); -}); - - diff --git a/frontend/src/app/features/magic-shelf/service/book-rule-evaluator.service.ts b/frontend/src/app/features/magic-shelf/service/book-rule-evaluator.service.ts deleted file mode 100644 index 55dc33aa3..000000000 --- a/frontend/src/app/features/magic-shelf/service/book-rule-evaluator.service.ts +++ /dev/null @@ -1,604 +0,0 @@ -import {Injectable} from '@angular/core'; -import {Book} from '../../book/model/book.model'; -import {GroupRule, Rule, RuleField} from '../component/magic-shelf-component'; -import {parseValue} from './magic-shelf-utils'; - -@Injectable({providedIn: 'root'}) -export class BookRuleEvaluatorService { - - evaluateGroup(book: Book, group: GroupRule, allBooks: Book[] = []): boolean { - const results = group.rules.map(rule => { - if ('type' in rule && rule.type === 'group') { - return this.evaluateGroup(book, rule as GroupRule, allBooks); - } else { - return this.evaluateRule(book, rule as Rule, allBooks); - } - }); - return group.join === 'and' ? results.every(Boolean) : results.some(Boolean); - } - - private evaluateRule(book: Book, rule: Rule, allBooks: Book[]): boolean { - if (rule.field === 'metadataPresence') { - return this.evaluateMetadataPresence(book, rule); - } - - if (rule.field === 'seriesStatus' || rule.field === 'seriesGaps' || rule.field === 'seriesPosition') { - return this.evaluateCompositeField(book, rule, allBooks); - } - - const rawValue = this.extractBookValue(book, rule.field); - const isDateField = rule.field === 'publishedDate' || rule.field === 'dateFinished' || - rule.field === 'lastReadTime' || rule.field === 'addedOn'; - const withoutTime = (date: Date): Date => - new Date(date.getFullYear(), date.getMonth(), date.getDate()); - - const normalize = (val: unknown): unknown => { - if (val === null || val === undefined) return val; - if (val instanceof Date) return isDateField ? withoutTime(val) : val; - if (typeof val === 'boolean') return String(val); - if (typeof val === 'string') { - const date = parseValue(val, 'date'); - if (date instanceof Date) return isDateField ? withoutTime(date) : date; - return val.toLowerCase(); - } - return val; - }; - - const value = normalize(rawValue); - const ruleVal = normalize(rule.value); - const ruleStart = normalize(rule.valueStart); - const ruleEnd = normalize(rule.valueEnd); - - const mapFileTypeValue = (uiValue: string): string => { - const lowerValue = uiValue.toLowerCase(); - switch (lowerValue) { - case 'cbr': - case 'cbz': - case 'cb7': - return 'cbx'; - case 'azw': - return 'azw3'; - default: - return lowerValue; - } - }; - - const getArrayField = (field: RuleField): string[] => { - switch (field) { - case 'authors': - return (book.metadata?.authors ?? []).map(a => a.toLowerCase()); - case 'categories': - return (book.metadata?.categories ?? []).map(c => c.toLowerCase()); - case 'moods': - return (book.metadata?.moods ?? []).map(m => m.toLowerCase()); - case 'tags': - return (book.metadata?.tags ?? []).map(t => t.toLowerCase()); - case 'readStatus': - return [String(book.readStatus ?? 'UNSET').toLowerCase()]; - case 'fileType': - return [String(book.primaryFile?.bookType ?? '').toLowerCase()]; - case 'library': - return [String(book.libraryId)]; - case 'shelf': - return (book.shelves ?? []).map(s => String(s.id)); - case 'language': - return [String(book.metadata?.language ?? '').toLowerCase()]; - case 'title': - return [String(book.metadata?.title ?? '').toLowerCase()]; - case 'subtitle': - return [String(book.metadata?.subtitle ?? '').toLowerCase()]; - case 'publisher': - return [String(book.metadata?.publisher ?? '').toLowerCase()]; - case 'seriesName': - return [String(book.metadata?.seriesName ?? '').toLowerCase()]; - case 'isbn13': - return [String(book.metadata?.isbn13 ?? '').toLowerCase()]; - case 'isbn10': - return [String(book.metadata?.isbn10 ?? '').toLowerCase()]; - case 'narrator': - return [String(book.metadata?.narrator ?? '').toLowerCase()]; - case 'description': - return [String(book.metadata?.description ?? '').toLowerCase()]; - case 'contentRating': - return [String(book.metadata?.contentRating ?? '').toLowerCase()]; - default: - return []; - } - }; - - const isNumericIdField = rule.field === 'library' || rule.field === 'shelf'; - const isFileTypeField = rule.field === 'fileType'; - - const ruleList = Array.isArray(rule.value) - ? rule.value.map(v => { - if (isNumericIdField) return String(v); - const lowerValue = String(v).toLowerCase(); - return isFileTypeField ? mapFileTypeValue(lowerValue) : lowerValue; - }) - : (rule.value ? [ - isNumericIdField - ? String(rule.value) - : isFileTypeField - ? mapFileTypeValue(String(rule.value).toLowerCase()) - : String(rule.value).toLowerCase() - ] : []); - - switch (rule.operator) { - case 'equals': - if (Array.isArray(value)) { - return value.some(v => ruleList.includes(isNumericIdField ? String(v) : String(v).toLowerCase())); - } - if (value instanceof Date && ruleVal instanceof Date) { - return value.getTime() === ruleVal.getTime(); - } - if (isFileTypeField && typeof ruleVal === 'string') { - const mappedRuleVal = mapFileTypeValue(ruleVal.toLowerCase()); - return value === mappedRuleVal; - } - return value === ruleVal; - - case 'not_equals': - if (Array.isArray(value)) { - return value.every(v => !ruleList.includes(isNumericIdField ? String(v) : String(v).toLowerCase())); - } - if (value instanceof Date && ruleVal instanceof Date) { - return value.getTime() !== ruleVal.getTime(); - } - if (isFileTypeField && typeof ruleVal === 'string') { - const mappedRuleVal = mapFileTypeValue(ruleVal.toLowerCase()); - return value !== mappedRuleVal; - } - return value !== ruleVal; - - case 'contains': - if (Array.isArray(value)) { - if (typeof ruleVal !== 'string') return false; - return value.some(v => String(v).includes(ruleVal)); - } - if (typeof value !== 'string') return false; - if (typeof ruleVal !== 'string') return false; - return value.includes(ruleVal); - - case 'does_not_contain': - if (Array.isArray(value)) { - if (typeof ruleVal !== 'string') return true; - return value.every(v => !String(v).includes(ruleVal)); - } - if (typeof value !== 'string') return true; - if (typeof ruleVal !== 'string') return true; - return !value.includes(ruleVal); - - case 'starts_with': - if (Array.isArray(value)) { - if (typeof ruleVal !== 'string') return false; - return value.some(v => String(v).startsWith(ruleVal)); - } - if (typeof value !== 'string') return false; - if (typeof ruleVal !== 'string') return false; - return value.startsWith(ruleVal); - - case 'ends_with': - if (Array.isArray(value)) { - if (typeof ruleVal !== 'string') return false; - return value.some(v => String(v).endsWith(ruleVal)); - } - if (typeof value !== 'string') return false; - if (typeof ruleVal !== 'string') return false; - return value.endsWith(ruleVal); - - case 'greater_than': - if (value instanceof Date && ruleVal instanceof Date) { - return value > ruleVal; - } - return Number(value) > Number(ruleVal); - - case 'greater_than_equal_to': - if (value instanceof Date && ruleVal instanceof Date) { - return value >= ruleVal; - } - return Number(value) >= Number(ruleVal); - - case 'less_than': - if (value instanceof Date && ruleVal instanceof Date) { - return value < ruleVal; - } - return Number(value) < Number(ruleVal); - - case 'less_than_equal_to': - if (value instanceof Date && ruleVal instanceof Date) { - return value <= ruleVal; - } - return Number(value) <= Number(ruleVal); - - case 'in_between': - if (value == null || ruleStart == null || ruleEnd == null) return false; - if (value instanceof Date && ruleStart instanceof Date && ruleEnd instanceof Date) { - return value >= ruleStart && value <= ruleEnd; - } - return Number(value) >= Number(ruleStart) && Number(value) <= Number(ruleEnd); - - case 'is_empty': { - const emptyVal = rule.field === 'readStatus' ? book.readStatus : value; - if (emptyVal == null) return true; - if (typeof emptyVal === 'string') return emptyVal.trim() === ''; - if (Array.isArray(emptyVal)) return emptyVal.length === 0; - return false; - } - - case 'is_not_empty': { - const notEmptyVal = rule.field === 'readStatus' ? book.readStatus : value; - if (notEmptyVal == null) return false; - if (typeof notEmptyVal === 'string') return notEmptyVal.trim() !== ''; - if (Array.isArray(notEmptyVal)) return notEmptyVal.length > 0; - return true; - } - - case 'includes_all': { - const bookList = getArrayField(rule.field); - return ruleList.every(v => bookList.includes(v)); - } - - case 'excludes_all': { - const bookList = getArrayField(rule.field); - return ruleList.every(v => !bookList.includes(v)); - } - - case 'includes_any': { - const bookList = getArrayField(rule.field); - return ruleList.some(v => bookList.includes(v)); - } - - case 'within_last': { - if (!(value instanceof Date)) return false; - const threshold = this.computeDateThreshold(Number(rule.value), String(rule.valueEnd ?? 'days')); - return value >= threshold; - } - - case 'older_than': { - if (!(value instanceof Date)) return false; - const threshold = this.computeDateThreshold(Number(rule.value), String(rule.valueEnd ?? 'days')); - return value < threshold; - } - - case 'this_period': { - if (!(value instanceof Date)) return false; - const start = this.getStartOfPeriod(String(rule.value ?? 'year')); - return value >= start; - } - - default: - return false; - } - } - - private extractBookValue(book: Book, field: RuleField): unknown { - switch (field) { - case 'library': - return book.libraryId; - case 'shelf': - return (book.shelves ?? []).map(s => s.id); - case 'readStatus': - return book.readStatus ?? 'UNSET'; - case 'fileType': - return (book.primaryFile?.bookType as string)?.toLowerCase() ?? null; - case 'fileSize': - return book.primaryFile?.fileSizeKb; - case 'metadataScore': - return book.metadataMatchScore; - case 'personalRating': - return book.personalRating; - case 'title': - return book.metadata?.title?.toLowerCase() ?? null; - case 'subtitle': - return book.metadata?.subtitle?.toLowerCase() ?? null; - case 'authors': - return (book.metadata?.authors ?? []).map(a => a.toLowerCase()); - case 'categories': - return (book.metadata?.categories ?? []).map(c => c.toLowerCase()); - case 'moods': - return (book.metadata?.moods ?? []).map(m => m.toLowerCase()); - case 'tags': - return (book.metadata?.tags ?? []).map(t => t.toLowerCase()); - case 'publisher': - return book.metadata?.publisher?.toLowerCase() ?? null; - case 'publishedDate': - return parseValue(book.metadata?.publishedDate, 'date') ?? null; - case 'dateFinished': - return book.dateFinished ? new Date(book.dateFinished) : null; - case 'lastReadTime': - return book.lastReadTime ? new Date(book.lastReadTime) : null; - case 'seriesName': - return book.metadata?.seriesName?.toLowerCase() ?? null; - case 'seriesNumber': - return book.metadata?.seriesNumber; - case 'seriesTotal': - return book.metadata?.seriesTotal; - case 'pageCount': - return book.metadata?.pageCount; - case 'language': - return book.metadata?.language?.toLowerCase() ?? null; - case 'isbn13': - return book.metadata?.isbn13?.toLowerCase() ?? null; - case 'isbn10': - return book.metadata?.isbn10?.toLowerCase() ?? null; - case 'amazonRating': - return book.metadata?.amazonRating; - case 'amazonReviewCount': - return book.metadata?.amazonReviewCount; - case 'goodreadsRating': - return book.metadata?.goodreadsRating; - case 'goodreadsReviewCount': - return book.metadata?.goodreadsReviewCount; - case 'hardcoverRating': - return book.metadata?.hardcoverRating; - case 'hardcoverReviewCount': - return book.metadata?.hardcoverReviewCount; - case 'ranobedbRating': - return book.metadata?.ranobedbRating; - case 'addedOn': - return book.addedOn ? new Date(book.addedOn) : null; - case 'description': - return book.metadata?.description?.toLowerCase() ?? null; - case 'narrator': - return book.metadata?.narrator?.toLowerCase() ?? null; - case 'ageRating': - return book.metadata?.ageRating; - case 'contentRating': - return book.metadata?.contentRating?.toLowerCase() ?? null; - case 'audibleRating': - return book.metadata?.audibleRating; - case 'audibleReviewCount': - return book.metadata?.audibleReviewCount; - case 'applebooksRating': - return book.metadata?.applebooksRating; - case 'applebooksReviewCount': - return book.metadata?.applebooksReviewCount; - case 'abridged': - return book.metadata?.abridged; - case 'audiobookDuration': - return book.metadata?.audiobookMetadata?.durationSeconds ?? null; - case 'audiobookCodec': - return book.metadata?.audiobookMetadata?.codec?.toLowerCase() ?? null; - case 'audiobookChapterCount': - return book.metadata?.audiobookMetadata?.chapterCount ?? null; - case 'audiobookBitrate': - return book.metadata?.audiobookMetadata?.bitrate ?? null; - case 'isPhysical': - return book.isPhysical; - case 'lubimyczytacRating': - return book.metadata?.lubimyczytacRating; - case 'readingProgress': { - const prg = [ - book.koreaderProgress?.percentage ?? 0, - book.koboProgress?.percentage ?? 0, - book.pdfProgress?.percentage ?? 0, - book.epubProgress?.percentage ?? 0, - book.cbxProgress?.percentage ?? 0, - book.audiobookProgress?.percentage ?? 0, - ]; - return Math.max(...prg); - } - default: - return (book as Record)[field]; - } - } - - private evaluateCompositeField(book: Book, rule: Rule, allBooks: Book[]): boolean { - const seriesName = book.metadata?.seriesName; - if (!seriesName) return false; - - const seriesBooks = allBooks.filter(b => b.metadata?.seriesName === seriesName); - const value = typeof rule.value === 'string' ? rule.value.toLowerCase() : ''; - const negate = rule.operator === 'not_equals'; - - let result: boolean; - switch (rule.field) { - case 'seriesStatus': - result = this.evaluateSeriesStatus(seriesBooks, value); - break; - case 'seriesGaps': - result = this.evaluateSeriesGaps(seriesBooks, value); - break; - case 'seriesPosition': - result = this.evaluateSeriesPosition(book, seriesBooks, value); - break; - default: - result = false; - } - - return negate ? !result : result; - } - - private evaluateSeriesStatus(seriesBooks: Book[], value: string): boolean { - switch (value) { - case 'reading': - return seriesBooks.some(b => b.readStatus === 'READING' || b.readStatus === 'RE_READING'); - case 'not_started': - return !seriesBooks.some(b => - b.readStatus === 'READ' || b.readStatus === 'READING' || - b.readStatus === 'RE_READING' || b.readStatus === 'PARTIALLY_READ' - ); - case 'fully_read': - return seriesBooks.length > 0 && seriesBooks.every(b => b.readStatus === 'READ'); - case 'completed': { - const totals = seriesBooks.map(b => b.metadata?.seriesTotal).filter((t): t is number => t != null); - if (totals.length === 0) return false; - const maxTotal = Math.max(...totals); - return seriesBooks.some(b => b.metadata?.seriesNumber != null && Math.floor(b.metadata.seriesNumber) === maxTotal); - } - case 'ongoing': { - const totals = seriesBooks.map(b => b.metadata?.seriesTotal).filter((t): t is number => t != null); - if (totals.length === 0) return false; - const maxTotal = Math.max(...totals); - return !seriesBooks.some(b => b.metadata?.seriesNumber != null && Math.floor(b.metadata.seriesNumber) === maxTotal); - } - default: - return false; - } - } - - private evaluateSeriesGaps(seriesBooks: Book[], value: string): boolean { - const numberedBooks = seriesBooks - .filter(b => b.metadata?.seriesNumber != null) - .map(b => b.metadata!.seriesNumber!); - - if (numberedBooks.length === 0) return false; - - switch (value) { - case 'any_gap': { - const uniqueFloors = new Set(numberedBooks.map(n => Math.floor(n))); - const maxFloor = Math.max(...numberedBooks.map(n => Math.floor(n))); - return uniqueFloors.size < maxFloor; - } - case 'missing_first': - return !numberedBooks.some(n => Math.floor(n) === 1); - case 'missing_latest': { - const totals = seriesBooks.map(b => b.metadata?.seriesTotal).filter((t): t is number => t != null); - if (totals.length === 0) return false; - const maxTotal = Math.max(...totals); - return !numberedBooks.some(n => Math.floor(n) === maxTotal); - } - case 'duplicate_number': - return numberedBooks.length > new Set(numberedBooks).size; - default: - return false; - } - } - - private evaluateSeriesPosition(book: Book, seriesBooks: Book[], value: string): boolean { - if (book.metadata?.seriesNumber == null) return false; - - const numberedBooks = seriesBooks.filter(b => b.metadata?.seriesNumber != null); - - switch (value) { - case 'first_in_series': { - const minNumber = Math.min(...numberedBooks.map(b => b.metadata!.seriesNumber!)); - return book.metadata.seriesNumber === minNumber; - } - case 'last_in_series': { - const maxNumber = Math.max(...numberedBooks.map(b => b.metadata!.seriesNumber!)); - return book.metadata.seriesNumber === maxNumber; - } - case 'next_unread': { - if (book.readStatus === 'READ') return false; - const hasLowerUnread = numberedBooks.some(b => - b.metadata!.seriesNumber! < book.metadata!.seriesNumber! && - b.readStatus !== 'READ' - ); - if (hasLowerUnread) return false; - return numberedBooks.some(b => - b.metadata!.seriesNumber! < book.metadata!.seriesNumber! && - b.readStatus === 'READ' - ); - } - default: - return false; - } - } - - private evaluateMetadataPresence(book: Book, rule: Rule): boolean { - const metadataField = typeof rule.value === 'string' ? rule.value : ''; - const isPresent = this.isMetadataFieldPresent(book, metadataField); - return rule.operator === 'equals' ? isPresent : !isPresent; - } - - private isMetadataFieldPresent(book: Book, field: string): boolean { - const val = this.getMetadataFieldValue(book, field); - if (val == null) return false; - if (typeof val === 'string') return val.trim() !== ''; - if (Array.isArray(val)) return val.length > 0; - return true; - } - - private getMetadataFieldValue(book: Book, field: string): unknown { - switch (field) { - case 'title': return book.metadata?.title; - case 'subtitle': return book.metadata?.subtitle; - case 'description': return book.metadata?.description; - case 'publisher': return book.metadata?.publisher; - case 'publishedDate': return book.metadata?.publishedDate; - case 'language': return book.metadata?.language; - case 'thumbnailUrl': return book.metadata?.thumbnailUrl; - case 'narrator': return book.metadata?.narrator; - case 'contentRating': return book.metadata?.contentRating; - case 'pageCount': return book.metadata?.pageCount; - case 'seriesNumber': return book.metadata?.seriesNumber; - case 'seriesTotal': return book.metadata?.seriesTotal; - case 'ageRating': return book.metadata?.ageRating; - case 'seriesName': return book.metadata?.seriesName; - case 'isbn13': return book.metadata?.isbn13; - case 'isbn10': return book.metadata?.isbn10; - case 'openlibraryId': return book.metadata?.openlibraryId; - case 'asin': return book.metadata?.asin; - case 'authors': return book.metadata?.authors; - case 'categories': return book.metadata?.categories; - case 'moods': return book.metadata?.moods; - case 'tags': return book.metadata?.tags; - case 'personalRating': return book.personalRating; - case 'amazonRating': return book.metadata?.amazonRating; - case 'goodreadsRating': return book.metadata?.goodreadsRating; - case 'hardcoverRating': return book.metadata?.hardcoverRating; - case 'ranobedbRating': return book.metadata?.ranobedbRating; - case 'lubimyczytacRating': return book.metadata?.lubimyczytacRating; - case 'audibleRating': return book.metadata?.audibleRating; - case 'applebooksRating': return book.metadata?.applebooksRating; - case 'amazonReviewCount': return book.metadata?.amazonReviewCount; - case 'goodreadsReviewCount': return book.metadata?.goodreadsReviewCount; - case 'hardcoverReviewCount': return book.metadata?.hardcoverReviewCount; - case 'audibleReviewCount': return book.metadata?.audibleReviewCount; - case 'applebooksReviewCount': return book.metadata?.applebooksReviewCount; - case 'goodreadsId': return book.metadata?.goodreadsId; - case 'hardcoverId': return book.metadata?.hardcoverId; - case 'googleId': return book.metadata?.googleId; - case 'audibleId': return book.metadata?.audibleId; - case 'applebooksId': return book.metadata?.applebooksId; - case 'lubimyczytacId': return book.metadata?.lubimyczytacId; - case 'ranobedbId': return book.metadata?.ranobedbId; - case 'comicvineId': return book.metadata?.comicvineId; - case 'abridged': return book.metadata?.abridged; - case 'audiobookDuration': return book.metadata?.audiobookMetadata?.durationSeconds; - case 'audiobookCodec': return book.metadata?.audiobookMetadata?.codec; - case 'audiobookChapterCount': return book.metadata?.audiobookMetadata?.chapterCount; - case 'audiobookBitrate': return book.metadata?.audiobookMetadata?.bitrate; - case 'comicCharacters': return book.metadata?.comicMetadata?.characters; - case 'comicTeams': return book.metadata?.comicMetadata?.teams; - case 'comicLocations': return book.metadata?.comicMetadata?.locations; - case 'comicPencillers': return book.metadata?.comicMetadata?.pencillers; - case 'comicInkers': return book.metadata?.comicMetadata?.inkers; - case 'comicColorists': return book.metadata?.comicMetadata?.colorists; - case 'comicLetterers': return book.metadata?.comicMetadata?.letterers; - case 'comicCoverArtists': return book.metadata?.comicMetadata?.coverArtists; - case 'comicEditors': return book.metadata?.comicMetadata?.editors; - default: return null; - } - } - - private computeDateThreshold(amount: number, unit: string): Date { - const now = new Date(); - switch (unit.toLowerCase()) { - case 'weeks': - return new Date(now.getTime() - amount * 7 * 24 * 60 * 60 * 1000); - case 'months': - return new Date(now.getFullYear(), now.getMonth() - amount, now.getDate()); - case 'years': - return new Date(now.getFullYear() - amount, now.getMonth(), now.getDate()); - default: - return new Date(now.getTime() - amount * 24 * 60 * 60 * 1000); - } - } - - private getStartOfPeriod(period: string): Date { - const now = new Date(); - switch (period.toLowerCase()) { - case 'week': { - const day = now.getDay(); - const diff = day === 0 ? 6 : day - 1; - return new Date(now.getFullYear(), now.getMonth(), now.getDate() - diff); - } - case 'month': - return new Date(now.getFullYear(), now.getMonth(), 1); - default: - return new Date(now.getFullYear(), 0, 1); - } - } -} 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 index 7522a8c6c..ce4471169 100644 --- 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 @@ -3,11 +3,8 @@ import {TestBed} from '@angular/core/testing'; import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import {createAuthServiceStub, createQueryClientHarness, flushSignalAndQueryEffects, flushQueryAsync} 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'; import {bookQueryKeys} from '../../book/data/book-query-keys'; @@ -33,19 +30,6 @@ function buildGroupRule(overrides: Partial = {}): GroupRule { }; } -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 flushQueryAsync(); } @@ -55,12 +39,6 @@ describe('MagicShelfService', () => { let httpTestingController: HttpTestingController; let authService: ReturnType; let queryClientHarness: ReturnType; - let bookService: { - books: ReturnType; - }; - let ruleEvaluatorService: { - evaluateGroup: ReturnType; - }; beforeEach(() => { authService = createAuthServiceStub(); @@ -71,13 +49,6 @@ describe('MagicShelfService', () => { }, }); - bookService = { - books: vi.fn(() => []), - }; - ruleEvaluatorService = { - evaluateGroup: vi.fn(() => false), - }; - vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined); vi.spyOn(queryClientHarness.queryClient, 'removeQueries').mockImplementation(() => undefined); @@ -86,8 +57,6 @@ describe('MagicShelfService', () => { ...queryClientHarness.providers, MagicShelfService, {provide: AuthService, useValue: authService}, - {provide: BookService, useValue: bookService}, - {provide: BookRuleEvaluatorService, useValue: ruleEvaluatorService}, ], }); @@ -222,50 +191,4 @@ describe('MagicShelfService', () => { 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/magic-shelf/service/magic-shelf.service.ts b/frontend/src/app/features/magic-shelf/service/magic-shelf.service.ts index 6696b77a4..cd7efb143 100644 --- a/frontend/src/app/features/magic-shelf/service/magic-shelf.service.ts +++ b/frontend/src/app/features/magic-shelf/service/magic-shelf.service.ts @@ -5,10 +5,7 @@ import {tap} from 'rxjs/operators'; import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental'; import {API_CONFIG} from '../../../core/config/api-config'; -import {BookService} from '../../book/service/book.service'; -import {BookRuleEvaluatorService} from './book-rule-evaluator.service'; import {AuthService} from '../../../shared/service/auth.service'; -import {GroupRule} from '../component/magic-shelf-component'; import {IconType} from '../../../shared/icons/icon-selection'; import {invalidateBookCollections} from '../../book/data/book-query-cache'; @@ -30,8 +27,6 @@ export class MagicShelfService { private readonly url = `${API_CONFIG.BASE_URL}/api/magic-shelves`; private readonly http = inject(HttpClient); - private readonly bookService = inject(BookService); - private readonly ruleEvaluatorService = inject(BookRuleEvaluatorService); private readonly authService = inject(AuthService); private readonly queryClient = inject(QueryClient); private readonly token = this.authService.token; @@ -101,36 +96,6 @@ export class MagicShelfService { return this.shelves().find(shelf => shelf.id === id); } - getBookCountValue(shelfId: number): number { - const shelf = this.findShelfById(shelfId); - if (!shelf) { - return 0; - } - - let group: GroupRule; - try { - group = JSON.parse(shelf.filterJson); - } catch (error) { - console.error('Invalid filter JSON', error); - return 0; - } - - const allBooks = this.bookService.books(); - return allBooks.filter(book => - this.ruleEvaluatorService.evaluateGroup(book, group, allBooks) - ).length; - } - - readonly bookCountByMagicShelfId = computed(() => { - const counts = new Map(); - for (const shelf of this.shelves()) { - if (shelf.id != null) { - counts.set(shelf.id, this.getBookCountValue(shelf.id)); - } - } - return counts; - }); - deleteShelf(id: number): Observable { return this.http.delete(`${this.url}/${id}`).pipe( tap(() => { diff --git a/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.html b/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.html index 584cd055a..041c00a8b 100644 --- a/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.html +++ b/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.html @@ -4,6 +4,7 @@ [class.menu-open]="menuOpen()" > @let currentItem = item(); + @let count = displayCount(); @if (currentItem.action) { - } @else if (currentItem.bookCount) { -

{{ formatCount(currentItem.bookCount) }}

+ } @else if (count) { +

{{ formatCount(count) }}

} - } @else if (currentItem.bookCount) { -

{{ formatCount(currentItem.bookCount) }}

+ } @else if (count) { +

{{ formatCount(count) }}

} diff --git a/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.spec.ts b/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.spec.ts index 14e8cb3c9..bf356ae32 100644 --- a/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.spec.ts +++ b/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.spec.ts @@ -2,6 +2,8 @@ import {signal} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {beforeEach, describe, expect, it} from 'vitest'; +import {createQueryClientHarness} from '../../../core/testing/query-testing'; +import {AuthService} from '../../service/auth.service'; import {LayoutService} from '../layout.service'; import {AppSidebarItemRowComponent} from './app.sidebar-item-row.component'; @@ -13,7 +15,11 @@ describe('AppSidebarItemRowComponent', () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [AppSidebarItemRowComponent], - providers: [{provide: LayoutService, useValue: {currentPath}}], + providers: [ + ...createQueryClientHarness().providers, + {provide: LayoutService, useValue: {currentPath, areSidebarCountsVisible: () => false}}, + {provide: AuthService, useValue: {token: signal('token'), isAuthenticated: () => true}}, + ], }); TestBed.overrideComponent(AppSidebarItemRowComponent, {set: {template: ''}}); fixture = TestBed.createComponent(AppSidebarItemRowComponent); diff --git a/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.ts b/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.ts index 6d5aff63f..874637f59 100644 --- a/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.ts +++ b/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.ts @@ -3,6 +3,11 @@ import { RouterLink } from '@angular/router'; import { Tooltip } from '@openng/optimus-ui/tooltip'; import { TranslocoPipe } from '@jsverse/transloco'; import { LucideEllipsisVertical } from '@lucide/angular'; +import {injectQuery} from '@tanstack/angular-query-experimental'; +import {scopedFacetSelection} from '../../../features/book/browse/book-browse-scope'; +import {BookQueryService} from '../../../features/book/data/book-query.service'; +import {EMPTY_FACET_SELECTION, type FacetValueMap} from '../../../features/book/data/book-query-params'; +import {AuthService} from '../../service/auth.service'; import { IconSelection, toIconSelection } from '../../icons/icon-selection'; import { IconDisplayComponent } from '../../components/icon-display/icon-display.component'; @@ -37,6 +42,20 @@ export class AppSidebarItemRowComponent { readonly key = computed(() => `${this.parentKey()}-${this.index()}`); readonly layoutService = inject(LayoutService); + private readonly bookQuery = inject(BookQueryService); + private readonly authService = inject(AuthService); + private readonly countFacets = computed(() => { + const scope = this.item().bookScope; + return scope === undefined ? undefined : scopedFacetSelection(EMPTY_FACET_SELECTION, scope); + }); + private readonly bookCountQuery = injectQuery(() => ({ + ...this.bookQuery.page({facets: this.countFacets() ?? {}, facetLogic: 'or', sort: [], size: 1}), + enabled: this.countFacets() !== undefined && this.authService.isAuthenticated() + && this.layoutService.areSidebarCountsVisible(this.parentKey()), + })); + readonly displayCount = computed(() => this.countFacets() === undefined + ? this.item().bookCount + : this.bookCountQuery.data()?.page.totalElements); readonly isRouteActive = computed(() => { const route = this.item().routerLink?.[0]; diff --git a/frontend/src/app/shared/layout/layout-sidebar/app.sidebar.component.spec.ts b/frontend/src/app/shared/layout/layout-sidebar/app.sidebar.component.spec.ts index 72c0c729b..59b538336 100644 --- a/frontend/src/app/shared/layout/layout-sidebar/app.sidebar.component.spec.ts +++ b/frontend/src/app/shared/layout/layout-sidebar/app.sidebar.component.spec.ts @@ -6,14 +6,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { MessageService } from '@openng/optimus-ui/api'; import { getTranslocoModule } from '../../../core/testing/transloco-testing'; +import {createQueryClientHarness} from '../../../core/testing/query-testing'; import { BookDialogHelperService } from '../../../features/book/service/book-dialog-helper.service'; -import { BookService } from '../../../features/book/service/book.service'; import { LibraryHealthService } from '../../../features/book/service/library-health.service'; import { LibraryService } from '../../../features/book/service/library.service'; import { ShelfService } from '../../../features/book/service/shelf.service'; -import { AuthorService } from '../../../features/author-browser/service/author.service'; import { MagicShelfService } from '../../../features/magic-shelf/service/magic-shelf.service'; -import { SeriesDataService } from '../../../features/series-browser/service/series-data.service'; import { UserService } from '../../../features/settings/user-management/user.service'; import { CommandPaletteService } from '../../../features/command-palette/command-palette.service'; import { BookdropFileService } from '../../../features/bookdrop/service/bookdrop-file.service'; @@ -59,6 +57,7 @@ describe('AppSidebarComponent', () => { shelfSort: signal({ field: 'name', order: 'asc' }), magicShelfSort: signal({ field: 'name', order: 'asc' }), closeMobileSidebar: vi.fn(), + areSidebarCountsVisible: () => false, }; beforeEach(() => { @@ -84,10 +83,10 @@ describe('AppSidebarComponent', () => { TestBed.configureTestingModule({ imports: [AppSidebarComponent, getTranslocoModule()], providers: [ - { provide: LibraryService, useValue: { libraries: signal([]), bookCountByLibraryId: signal(new Map()) } }, + ...createQueryClientHarness().providers, + { provide: LibraryService, useValue: { libraries: signal([]) } }, { provide: LibraryHealthService, useValue: { isUnhealthy: vi.fn(() => false) } }, - { provide: ShelfService, useValue: { shelves: signal([]), bookCountByShelfId: signal(new Map()), unshelvedBookCount: signal(0) } }, - { provide: BookService, useValue: { books: signal([]) } }, + { provide: ShelfService, useValue: { shelves: signal([]) } }, { provide: DialogLauncherService, useValue: { @@ -98,16 +97,14 @@ describe('AppSidebarComponent', () => { }, { provide: CommandPaletteService, useValue: commandPaletteService }, { provide: BookDialogHelperService, useValue: { openShelfCreatorDialog: vi.fn(() => Promise.resolve(null)) } }, - { provide: AuthService, useValue: { logout: vi.fn() } }, + { provide: AuthService, useValue: { logout: vi.fn(), isAuthenticated: () => false } }, { provide: MetadataProgressService, useValue: { activeTasks$, progressUpdates$ } }, { provide: BookdropFileService, useValue: { hasPendingFiles } }, { provide: LibraryImportProgressService, useValue: { hasActiveImport } }, { provide: VersionService, useValue: { getVersion: vi.fn(() => versionInfo) } }, { provide: LayoutService, useValue: layoutService }, { provide: UserService, useValue: { currentUser } }, - { provide: MagicShelfService, useValue: { shelves: signal([]), bookCountByMagicShelfId: signal(new Map()) } }, - { provide: SeriesDataService, useValue: { allSeries: signal([]) } }, - { provide: AuthorService, useValue: { allAuthors: signal([]) } }, + { provide: MagicShelfService, useValue: { shelves: signal([]) } }, { provide: MessageService, useValue: { add: vi.fn() } }, { provide: AppThemeService, diff --git a/frontend/src/app/shared/layout/layout-sidebar/app.sidebar.component.ts b/frontend/src/app/shared/layout/layout-sidebar/app.sidebar.component.ts index 5713f2b77..c2657dd8d 100644 --- a/frontend/src/app/shared/layout/layout-sidebar/app.sidebar.component.ts +++ b/frontend/src/app/shared/layout/layout-sidebar/app.sidebar.component.ts @@ -28,11 +28,8 @@ import { import { LibraryService } from '../../../features/book/service/library.service'; import { LibraryHealthService } from '../../../features/book/service/library-health.service'; import { ShelfService } from '../../../features/book/service/shelf.service'; -import { BookService } from '../../../features/book/service/book.service'; import { UserService } from '../../../features/settings/user-management/user.service'; import { MagicShelfService } from '../../../features/magic-shelf/service/magic-shelf.service'; -import { SeriesDataService } from '../../../features/series-browser/service/series-data.service'; -import { AuthorService } from '../../../features/author-browser/service/author.service'; import { DialogLauncherService } from '../../services/dialog-launcher.service'; import { CommandPaletteService } from '../../../features/command-palette/command-palette.service'; import { AuthService } from '../../service/auth.service'; @@ -163,7 +160,6 @@ export class AppSidebarComponent { private readonly libraryService = inject(LibraryService); private readonly libraryHealthService = inject(LibraryHealthService); private readonly shelfService = inject(ShelfService); - private readonly bookService = inject(BookService); protected readonly dialogLauncherService = inject(DialogLauncherService); private readonly commandPaletteService = inject(CommandPaletteService); protected readonly bookDialogHelperService = inject(BookDialogHelperService); @@ -173,8 +169,6 @@ export class AppSidebarComponent { private readonly userService = inject(UserService); private readonly versionService = inject(VersionService); private readonly magicShelfService = inject(MagicShelfService); - private readonly seriesDataService = inject(SeriesDataService); - private readonly authorService = inject(AuthorService); private readonly t = inject(TranslocoService); private readonly metadataProgressService = inject(MetadataProgressService); private readonly bookdropFileService = inject(BookdropFileService); @@ -182,7 +176,6 @@ export class AppSidebarComponent { private readonly themeService = inject(AppThemeService); readonly currentUser = this.userService.currentUser; - private readonly allAuthors = this.authorService.allAuthors; protected readonly activeLang = toSignal(this.t.langChanges$, { initialValue: this.t.getActiveLang() }); protected readonly versionInfo = toSignal(this.versionService.getVersion(), { initialValue: null }); protected readonly appVersionLabel = computed(() => formatVersionLabel(this.versionInfo()?.current ?? '...')); @@ -220,28 +213,20 @@ export class AppSidebarComponent { readonly sections = computed(() => { this.activeLang(); return [ - ...buildHomeSection(this.translate, { - allBooks: this.bookService.books().length, - series: this.seriesDataService.allSeries().length, - authors: this.allAuthors()?.length ?? 0, - }), + ...buildHomeSection(this.translate), ...buildLibrarySection( this.libraryService.libraries(), - this.libraryService.bookCountByLibraryId(), this.layoutService.librarySort(), this.translate, { health: this.libraryHealthService }, ), ...buildShelfSection( this.shelfService.shelves(), - this.shelfService.bookCountByShelfId(), - this.shelfService.unshelvedBookCount(), this.layoutService.shelfSort(), this.translate, ), ...buildMagicShelfSection( this.magicShelfService.shelves(), - this.magicShelfService.bookCountByMagicShelfId(), this.layoutService.magicShelfSort(), this.translate, ), diff --git a/frontend/src/app/shared/layout/layout-sidebar/sidebar-sections.spec.ts b/frontend/src/app/shared/layout/layout-sidebar/sidebar-sections.spec.ts index 2158c8fa6..dc4e7553a 100644 --- a/frontend/src/app/shared/layout/layout-sidebar/sidebar-sections.spec.ts +++ b/frontend/src/app/shared/layout/layout-sidebar/sidebar-sections.spec.ts @@ -39,8 +39,8 @@ describe('normalizeSortPref', () => { }); describe('buildHomeSection', () => { - it('emits the standard home items and attaches counts only to counted entries', () => { - const [section] = buildHomeSection(translate, { allBooks: 12, series: 3, authors: 7 }); + it('emits the standard home items and scopes the all-books count', () => { + const [section] = buildHomeSection(translate); expect(section.id).toBe('home'); expect(section.expandable).toBe(true); @@ -48,16 +48,8 @@ describe('buildHomeSection', () => { 'dashboard', 'allBooks', 'series', 'authors', 'notebook', ]); - const counts = Object.fromEntries( - (section.items ?? []).map((item) => [item.id, item.bookCount]), - ); - expect(counts).toEqual({ - dashboard: undefined, - allBooks: 12, - series: 3, - authors: 7, - notebook: undefined, - }); + expect(section.items?.find((item) => item.id === 'allBooks')?.bookScope).toBeNull(); + expect(section.items?.every((item) => item.bookCount === undefined)).toBe(true); }); }); @@ -86,10 +78,9 @@ describe('buildToolsSection', () => { describe('buildLibrarySection', () => { it('returns no section when no libraries are persisted', () => { - expect(buildLibrarySection([], new Map(), { field: 'name', order: 'asc' }, translate, libraryDeps)).toEqual([]); + expect(buildLibrarySection([], { field: 'name', order: 'asc' }, translate, libraryDeps)).toEqual([]); expect(buildLibrarySection( [library({ name: 'pending' })], - new Map(), { field: 'name', order: 'asc' }, translate, libraryDeps, @@ -103,10 +94,10 @@ describe('buildLibrarySection', () => { library({ id: 3, name: 'Bravo' }), ]; - const asc = buildLibrarySection(libs, new Map(), { field: 'name', order: 'asc' }, translate, libraryDeps); + const asc = buildLibrarySection(libs, { field: 'name', order: 'asc' }, translate, libraryDeps); expect(asc[0].items?.map((item) => item.label)).toEqual(['Alpha', 'Bravo', 'Charlie']); - const desc = buildLibrarySection(libs, new Map(), { field: 'name', order: 'desc' }, translate, libraryDeps); + const desc = buildLibrarySection(libs, { field: 'name', order: 'desc' }, translate, libraryDeps); expect(desc[0].items?.map((item) => item.label)).toEqual(['Charlie', 'Bravo', 'Alpha']); }); @@ -117,15 +108,14 @@ describe('buildLibrarySection', () => { library({ id: 2, name: 'Beta' }), ]; - const result = buildLibrarySection(libs, new Map(), { field: 'id', order: 'asc' }, translate, libraryDeps); + const result = buildLibrarySection(libs, { field: 'id', order: 'asc' }, translate, libraryDeps); expect(result[0].items?.map((item) => item.id)).toEqual(['library:1', 'library:2', 'library:3']); }); - it('renders each library with route, count, health, and icon metadata', () => { + it('renders each library with route, health, and icon metadata', () => { const libs = [library({ id: 5, name: 'Fiction', icon: 'book', iconType: 'LUCIDE' })]; - const counts = new Map([[5, 42]]); - const [section] = buildLibrarySection(libs, counts, { field: 'name', order: 'asc' }, translate, libraryDeps); + const [section] = buildLibrarySection(libs, { field: 'name', order: 'asc' }, translate, libraryDeps); expect(section.items?.[0]).toMatchObject({ id: 'library:5', label: 'Fiction', @@ -134,7 +124,6 @@ describe('buildLibrarySection', () => { icon: 'book', iconType: 'LUCIDE', routerLink: ['/library/5/books'], - bookCount: 42, unhealthy: false, }); }); @@ -142,7 +131,7 @@ describe('buildLibrarySection', () => { it('flags unhealthy libraries via the injected health service', () => { const libs = [library({ id: 99, name: 'Broken' })]; - const [section] = buildLibrarySection(libs, new Map(), { field: 'name', order: 'asc' }, translate, libraryDeps); + const [section] = buildLibrarySection(libs, { field: 'name', order: 'asc' }, translate, libraryDeps); expect(section.items?.[0].unhealthy).toBe(true); }); }); @@ -151,25 +140,23 @@ describe('buildShelfSection', () => { const sort = { field: 'name', order: 'asc' } as const; it('renders Unshelved even when no shelves are persisted', () => { - const [section] = buildShelfSection([], new Map(), 5, sort, translate); + const [section] = buildShelfSection([], sort, translate); expect(section.items).toEqual([ expect.objectContaining({ id: 'shelfUnshelved', routerLink: ['/unshelved-books'], - bookCount: 5, }), ]); }); it('always renders Unshelved as the first item when shelves exist', () => { const shelves = [shelf({ id: 1, name: 'Reading' })]; - const [section] = buildShelfSection(shelves, new Map(), 9, sort, translate); + const [section] = buildShelfSection(shelves, sort, translate); expect(section.items?.[0]).toMatchObject({ id: 'shelfUnshelved', routerLink: ['/unshelved-books'], - bookCount: 9, }); }); @@ -179,7 +166,7 @@ describe('buildShelfSection', () => { shelf({ id: 2, name: 'Kobo', systemKey: 'kobo' }), shelf({ id: 3, name: 'Archive' }), ]; - const [section] = buildShelfSection(shelves, new Map(), 0, sort, translate); + const [section] = buildShelfSection(shelves, sort, translate); expect(section.items?.map((item) => item.label)) .toEqual(['layout.menu.unshelved', 'Kobo', 'Archive', 'Reading']); @@ -193,7 +180,7 @@ describe('buildShelfSection', () => { shelf({ id: 2, name: 'Kobo' }), shelf({ id: 3, name: 'Archive' }), ]; - const [section] = buildShelfSection(shelves, new Map(), 0, sort, translate); + const [section] = buildShelfSection(shelves, sort, translate); expect(section.items?.map((item) => item.label)) .toEqual(['layout.menu.unshelved', 'Archive', 'Kobo', 'Reading']); @@ -205,26 +192,25 @@ describe('buildMagicShelfSection', () => { const sort = { field: 'name', order: 'asc' } as const; it('returns no section when no magic shelves are persisted', () => { - expect(buildMagicShelfSection([], new Map(), sort, translate)).toEqual([]); + expect(buildMagicShelfSection([], sort, translate)).toEqual([]); }); - it('renders sorted magic shelves with route, icon, and count', () => { + it('renders sorted magic shelves with route and icon metadata', () => { const shelves = [ magicShelf({ id: 2, name: 'Beta', icon: 'sparkles', iconType: 'LUCIDE' }), magicShelf({ id: 1, name: 'Alpha' }), ]; - const counts = new Map([[1, 4], [2, 7]]); - const [section] = buildMagicShelfSection(shelves, counts, sort, translate); + const [section] = buildMagicShelfSection(shelves, sort, translate); expect(section.items).toEqual([ expect.objectContaining({ - id: 'magicShelf:1', label: 'Alpha', routerLink: ['/magic-shelf/1/books'], bookCount: 4, + id: 'magicShelf:1', label: 'Alpha', routerLink: ['/magic-shelf/1/books'], menuTarget: {type: 'magicShelf', entity: shelves[1]}, }), expect.objectContaining({ id: 'magicShelf:2', label: 'Beta', icon: 'sparkles', iconType: 'LUCIDE', menuTarget: {type: 'magicShelf', entity: shelves[0]}, - routerLink: ['/magic-shelf/2/books'], bookCount: 7, + routerLink: ['/magic-shelf/2/books'], }), ]); }); diff --git a/frontend/src/app/shared/layout/layout-sidebar/sidebar-sections.ts b/frontend/src/app/shared/layout/layout-sidebar/sidebar-sections.ts index 643751c5a..46e6089fb 100644 --- a/frontend/src/app/shared/layout/layout-sidebar/sidebar-sections.ts +++ b/frontend/src/app/shared/layout/layout-sidebar/sidebar-sections.ts @@ -4,15 +4,15 @@ import { MagicShelf } from '../../../features/magic-shelf/service/magic-shelf.se import { LibraryHealthService } from '../../../features/book/service/library-health.service'; import { SortPref } from '../sidebar-sort-preferences'; +import { + libraryBrowseScope, + magicShelfBrowseScope, + shelfBrowseScope, + UNSHELVED_BROWSE_SCOPE, +} from '../../../features/book/browse/book-browse-scope'; import { SidebarLeaf, SidebarSection } from '../navigation/nav-item.model'; import { buildHomeNavItems, findPageNavItem, ShellNavPermissions } from '../navigation/nav-catalog'; -export interface HomeCounts { - allBooks: number; - series: number; - authors: number; -} - export interface LibrarySectionDeps { health: Pick; } @@ -37,7 +37,7 @@ function sortByPref(items: T[], pref: So return pref.order === 'desc' ? sorted.reverse() : sorted; } -export function buildHomeSection(translate: TranslateFn, counts: HomeCounts): SidebarSection[] { +export function buildHomeSection(translate: TranslateFn): SidebarSection[] { return [{ id: 'home', menuKey: 'home', @@ -45,7 +45,7 @@ export function buildHomeSection(translate: TranslateFn, counts: HomeCounts): Si expandable: true, items: buildHomeNavItems(translate).map((item) => ({ ...item, - bookCount: homeItemBookCount(item.id, counts), + bookScope: item.id === 'allBooks' ? null : undefined, })), }]; } @@ -71,18 +71,8 @@ export function buildToolsSection( }]; } -function homeItemBookCount(itemId: string, counts: HomeCounts): number | undefined { - switch (itemId) { - case 'allBooks': return counts.allBooks; - case 'series': return counts.series; - case 'authors': return counts.authors; - default: return undefined; - } -} - export function buildLibrarySection( libraries: Library[], - bookCounts: ReadonlyMap, sort: SortPref, translate: TranslateFn, deps: LibrarySectionDeps, @@ -104,7 +94,7 @@ export function buildLibrarySection( icon: library.icon || undefined, iconType: library.iconType ?? undefined, routerLink: [`/library/${library.id}/books`], - bookCount: bookCounts.get(library.id) ?? 0, + bookScope: libraryBrowseScope(library.id), unhealthy: deps.health.isUnhealthy(library.id), })), }]; @@ -112,8 +102,6 @@ export function buildLibrarySection( export function buildShelfSection( shelves: Shelf[], - bookCounts: ReadonlyMap, - unshelvedCount: number, sort: SortPref, translate: TranslateFn, ): SidebarSection[] { @@ -127,15 +115,15 @@ export function buildShelfSection( type: 'shelf', icon: 'inbox', routerLink: ['/unshelved-books'], - bookCount: unshelvedCount, + bookScope: UNSHELVED_BROWSE_SCOPE, }]; if (pinned) { - items.push(toShelfNavItem(pinned, bookCounts)); + items.push(toShelfNavItem(pinned)); } for (const shelf of sorted) { - items.push(toShelfNavItem(shelf, bookCounts)); + items.push(toShelfNavItem(shelf)); } return [{ @@ -148,10 +136,7 @@ export function buildShelfSection( }]; } -function toShelfNavItem( - shelf: WithId, - bookCounts: ReadonlyMap, -): SidebarLeaf { +function toShelfNavItem(shelf: WithId): SidebarLeaf { return { id: `shelf:${shelf.id}`, label: shelf.name, @@ -160,13 +145,12 @@ function toShelfNavItem( icon: shelf.icon || undefined, iconType: shelf.iconType ?? undefined, routerLink: [`/shelf/${shelf.id}/books`], - bookCount: bookCounts.get(shelf.id) ?? 0, + bookScope: shelfBrowseScope(shelf.id), }; } export function buildMagicShelfSection( shelves: MagicShelf[], - bookCounts: ReadonlyMap, sort: SortPref, translate: TranslateFn, ): SidebarSection[] { @@ -187,7 +171,7 @@ export function buildMagicShelfSection( icon: shelf.icon || undefined, iconType: shelf.iconType ?? undefined, routerLink: [`/magic-shelf/${shelf.id}/books`], - bookCount: bookCounts.get(shelf.id) ?? 0, + bookScope: magicShelfBrowseScope(shelf.id), })), }]; } diff --git a/frontend/src/app/shared/layout/layout.service.ts b/frontend/src/app/shared/layout/layout.service.ts index 1f825616d..ce88df4db 100644 --- a/frontend/src/app/shared/layout/layout.service.ts +++ b/frontend/src/app/shared/layout/layout.service.ts @@ -125,6 +125,12 @@ export class LayoutService { return value === undefined ? defaultExpanded : value; } + areSidebarCountsVisible(sectionKey: string): boolean { + return (this.isDesktop() + ? this.sidebarVisible() && !this.sidebarCollapsed() + : this.mobileDrawerOpen()) && this.isSidebarExpanded(sectionKey, true); + } + setSidebarExpanded(key: string, expanded: boolean): void { const next = { ...this.sidebarExpandedState(), [key]: expanded }; this.sidebarExpandedState.set(next); diff --git a/frontend/src/app/shared/layout/navigation/nav-item.model.ts b/frontend/src/app/shared/layout/navigation/nav-item.model.ts index 32bd3ca4c..e3e58fddf 100644 --- a/frontend/src/app/shared/layout/navigation/nav-item.model.ts +++ b/frontend/src/app/shared/layout/navigation/nav-item.model.ts @@ -1,4 +1,5 @@ import { IconType } from '../../icons/icon-selection'; +import type {BookBrowseScope} from '../../../features/book/browse/book-browse-scope'; import type {LibraryShelfMenuTarget} from './library-shelf-menu-target.model'; export type NavItemType = @@ -18,6 +19,7 @@ export interface NavItem { /** A clickable row inside a sidebar section. */ export interface SidebarLeaf extends NavItem { menuTarget?: LibraryShelfMenuTarget; + bookScope?: BookBrowseScope | null; bookCount?: number; unhealthy?: boolean; }