refactor(ui): paginated sidebar counts and removed dead book evaluator code (#2702)
This commit is contained in:
@@ -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;
|
||||
|
||||
@@ -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<typeof createAuthServiceStub>;
|
||||
let queryClientHarness: ReturnType<typeof createQueryClientHarness>;
|
||||
let bookService: {
|
||||
books: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
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', () => {
|
||||
|
||||
@@ -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<number, number>();
|
||||
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<Record<string, number>> {
|
||||
return from(this.queryClient.ensureQueryData(this.getLibraryFormatCountsQueryOptions(libraryId)));
|
||||
}
|
||||
|
||||
@@ -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> = {}): Shelf {
|
||||
};
|
||||
}
|
||||
|
||||
function buildBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Main Library',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('ShelfService', () => {
|
||||
let service: ShelfService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
let authService: ReturnType<typeof createAuthServiceStub>;
|
||||
let queryClientHarness: ReturnType<typeof createQueryClientHarness>;
|
||||
let bookService: {
|
||||
books: ReturnType<typeof vi.fn>;
|
||||
removeBooksFromShelf: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let userService: {
|
||||
getCurrentUser: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let currentUser: ReturnType<typeof signal<{id: number} | null>>;
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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<Book[]> {
|
||||
return this.http.get<Book[]>(`${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<number, number>();
|
||||
|
||||
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,
|
||||
|
||||
-533
@@ -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> = {}): 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);
|
||||
});
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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<string, unknown>)[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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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> = {}): GroupRule {
|
||||
};
|
||||
}
|
||||
|
||||
function buildBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Main Library',
|
||||
metadata: {
|
||||
bookId: id,
|
||||
title: `Book ${id}`,
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function flushShelvesQuery(): Promise<void> {
|
||||
await flushQueryAsync();
|
||||
}
|
||||
@@ -55,12 +39,6 @@ describe('MagicShelfService', () => {
|
||||
let httpTestingController: HttpTestingController;
|
||||
let authService: ReturnType<typeof createAuthServiceStub>;
|
||||
let queryClientHarness: ReturnType<typeof createQueryClientHarness>;
|
||||
let bookService: {
|
||||
books: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let ruleEvaluatorService: {
|
||||
evaluateGroup: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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<number, number>();
|
||||
for (const shelf of this.shelves()) {
|
||||
if (shelf.id != null) {
|
||||
counts.set(shelf.id, this.getBookCountValue(shelf.id));
|
||||
}
|
||||
}
|
||||
return counts;
|
||||
});
|
||||
|
||||
deleteShelf(id: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/${id}`).pipe(
|
||||
tap(() => {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
[class.menu-open]="menuOpen()"
|
||||
>
|
||||
@let currentItem = item();
|
||||
@let count = displayCount();
|
||||
|
||||
@if (currentItem.action) {
|
||||
<button
|
||||
@@ -25,8 +26,8 @@
|
||||
</span>
|
||||
<span class="layout-sidebar-item-text sidebar-item-text">
|
||||
<span class="sidebar-item-label">{{ currentItem.label }}</span>
|
||||
@if (currentItem.bookCount) {
|
||||
<span class="book-count book-count-inline">{{ formatCount(currentItem.bookCount) }}</span>
|
||||
@if (count) {
|
||||
<span class="book-count book-count-inline">{{ formatCount(count) }}</span>
|
||||
}
|
||||
</span>
|
||||
</span>
|
||||
@@ -62,8 +63,8 @@
|
||||
</span>
|
||||
<span class="layout-sidebar-item-text sidebar-item-text">
|
||||
<span class="sidebar-item-label">{{ currentItem.label }}</span>
|
||||
@if (currentItem.bookCount) {
|
||||
<span class="book-count book-count-inline">{{ formatCount(currentItem.bookCount) }}</span>
|
||||
@if (count) {
|
||||
<span class="book-count book-count-inline">{{ formatCount(count) }}</span>
|
||||
}
|
||||
</span>
|
||||
</span>
|
||||
@@ -88,14 +89,14 @@
|
||||
>
|
||||
<span class="entity-menu-button-content">
|
||||
<svg lucideEllipsisVertical class="entity-menu-icon" aria-hidden="true"></svg>
|
||||
<span class="entity-menu-count">{{ formatCount(currentItem.bookCount) }}</span>
|
||||
<span class="entity-menu-count">{{ formatCount(count) }}</span>
|
||||
</span>
|
||||
</button>
|
||||
} @else if (currentItem.bookCount) {
|
||||
<p class="book-count book-count-end">{{ formatCount(currentItem.bookCount) }}</p>
|
||||
} @else if (count) {
|
||||
<p class="book-count book-count-end">{{ formatCount(count) }}</p>
|
||||
}
|
||||
} @else if (currentItem.bookCount) {
|
||||
<p class="book-count book-count-end">{{ formatCount(currentItem.bookCount) }}</p>
|
||||
} @else if (count) {
|
||||
<p class="book-count book-count-end">{{ formatCount(count) }}</p>
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
+7
-1
@@ -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);
|
||||
|
||||
@@ -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<FacetValueMap | undefined>(() => {
|
||||
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];
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<SidebarSection[]>(() => {
|
||||
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,
|
||||
),
|
||||
|
||||
@@ -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'],
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -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<LibraryHealthService, 'isUnhealthy'>;
|
||||
}
|
||||
@@ -37,7 +37,7 @@ function sortByPref<T extends { id: number; name: string }>(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<number, number>,
|
||||
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<number, number>,
|
||||
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<Shelf>,
|
||||
bookCounts: ReadonlyMap<number, number>,
|
||||
): SidebarLeaf {
|
||||
function toShelfNavItem(shelf: WithId<Shelf>): 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<number, number>,
|
||||
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),
|
||||
})),
|
||||
}];
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user