diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/WebSocketAuthInterceptor.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/WebSocketAuthInterceptor.java index 4f85a7f91..a4c812cac 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/WebSocketAuthInterceptor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/WebSocketAuthInterceptor.java @@ -67,7 +67,7 @@ public class WebSocketAuthInterceptor implements ChannelInterceptor { return new UsernamePasswordAuthenticationToken(username, null, Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))); } } catch (Exception e) { - log.error("Token authentication failed", e); + log.debug("Token authentication failed", e); } return null; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/MagicShelfController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/MagicShelfController.java new file mode 100644 index 000000000..0451642be --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/MagicShelfController.java @@ -0,0 +1,41 @@ +package com.adityachandel.booklore.controller; + +import com.adityachandel.booklore.model.dto.MagicShelf; +import com.adityachandel.booklore.service.MagicShelfService; +import jakarta.validation.Valid; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/api/magic-shelves") +public class MagicShelfController { + + private final MagicShelfService magicShelfService; + + public MagicShelfController(MagicShelfService magicShelfService) { + this.magicShelfService = magicShelfService; + } + + @GetMapping + public ResponseEntity> getAllForUser() { + return ResponseEntity.ok(magicShelfService.getUserShelves()); + } + + @GetMapping("/{id}") + public ResponseEntity getShelf(@PathVariable Long id) { + return ResponseEntity.ok(magicShelfService.getShelf(id)); + } + + @PostMapping + public ResponseEntity createUpdateShelf(@Valid @RequestBody MagicShelf shelf) { + return ResponseEntity.ok(magicShelfService.createOrUpdateShelf(shelf)); + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteShelf(@PathVariable Long id) { + magicShelfService.deleteShelf(id); + return ResponseEntity.noContent().build(); + } +} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/MagicShelf.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/MagicShelf.java new file mode 100644 index 000000000..7aa84ff75 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/MagicShelf.java @@ -0,0 +1,24 @@ +package com.adityachandel.booklore.model.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import lombok.Data; + +@Data +public class MagicShelf { + + private Long id; + + @NotBlank(message = "Shelf name must not be blank") + @Size(max = 255, message = "Shelf name must not exceed 255 characters") + private String name; + + @NotBlank(message = "Icon must not be blank") + @Size(max = 64, message = "Icon must not exceed 64 characters") + private String icon; + + @NotNull(message = "Filter JSON must not be null") + @Size(min = 2, message = "Filter JSON must not be empty") + private String filterJson; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/MagicShelfEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/MagicShelfEntity.java new file mode 100644 index 000000000..227b278b2 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/MagicShelfEntity.java @@ -0,0 +1,45 @@ +package com.adityachandel.booklore.model.entity; + +import jakarta.persistence.*; +import lombok.*; + +import java.time.LocalDateTime; + +@Entity +@Getter +@Setter +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "magic_shelf", uniqueConstraints = { + @UniqueConstraint(columnNames = {"user_id", "name"}) +}) +public class MagicShelfEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "user_id", nullable = false) + private Long userId; + + @Column(nullable = false) + private String name; + + @Column(nullable = false) + private String icon; + + @Column(name = "filter_json", columnDefinition = "json", nullable = false) + private String filterJson; + + @Column(name = "created_at", nullable = false, updatable = false) + private LocalDateTime createdAt = LocalDateTime.now(); + + @Column(name = "updated_at", nullable = false) + private LocalDateTime updatedAt = LocalDateTime.now(); + + @PreUpdate + public void onUpdate() { + updatedAt = LocalDateTime.now(); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/MagicShelfRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/MagicShelfRepository.java new file mode 100644 index 000000000..5fb89864c --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/MagicShelfRepository.java @@ -0,0 +1,16 @@ +package com.adityachandel.booklore.repository; + +import com.adityachandel.booklore.model.entity.MagicShelfEntity; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; +import java.util.Optional; + +public interface MagicShelfRepository extends JpaRepository { + + List findAllByUserId(Long userId); + + Optional findByUserIdAndName(Long userId, String name); + + boolean existsByUserIdAndName(Long userId, String name); +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/MagicShelfService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/MagicShelfService.java new file mode 100644 index 000000000..285d76b22 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/MagicShelfService.java @@ -0,0 +1,79 @@ +package com.adityachandel.booklore.service; + +import com.adityachandel.booklore.config.security.AuthenticationService; +import com.adityachandel.booklore.model.dto.MagicShelf; +import com.adityachandel.booklore.model.entity.MagicShelfEntity; +import com.adityachandel.booklore.repository.MagicShelfRepository; +import lombok.AllArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@AllArgsConstructor +@Service +public class MagicShelfService { + + private final MagicShelfRepository repository; + private final AuthenticationService authenticationService; + + public List getUserShelves() { + Long userId = authenticationService.getAuthenticatedUser().getId(); + return repository.findAllByUserId(userId).stream() + .map(this::toDto) + .toList(); + } + + @Transactional + public MagicShelf createOrUpdateShelf(MagicShelf dto) { + Long userId = authenticationService.getAuthenticatedUser().getId(); + if (dto.getId() != null) { + MagicShelfEntity existing = repository.findById(dto.getId()).orElseThrow(() -> new IllegalArgumentException("Shelf not found")); + if (!existing.getUserId().equals(userId)) { + throw new SecurityException("You are not authorized to update this shelf"); + } + existing.setName(dto.getName()); + existing.setIcon(dto.getIcon()); + existing.setFilterJson(dto.getFilterJson()); + return toDto(repository.save(existing)); + } + if (repository.existsByUserIdAndName(userId, dto.getName())) { + throw new IllegalArgumentException("A shelf with the same name already exists for this user."); + } + return toDto(repository.save(toEntity(dto, userId))); + } + + @Transactional + public void deleteShelf(Long id) { + Long userId = authenticationService.getAuthenticatedUser().getId(); + MagicShelfEntity shelf = repository.findById(id).orElseThrow(() -> new IllegalArgumentException("Shelf not found")); + if (!shelf.getUserId().equals(userId)) { + throw new SecurityException("You are not authorized to delete this shelf"); + } + repository.deleteById(id); + } + + private MagicShelf toDto(MagicShelfEntity entity) { + MagicShelf dto = new MagicShelf(); + dto.setId(entity.getId()); + dto.setName(entity.getName()); + dto.setIcon(entity.getIcon()); + dto.setFilterJson(entity.getFilterJson()); + return dto; + } + + private MagicShelfEntity toEntity(MagicShelf dto, Long userId) { + MagicShelfEntity entity = new MagicShelfEntity(); + entity.setId(dto.getId()); + entity.setName(dto.getName()); + entity.setIcon(dto.getIcon()); + entity.setFilterJson(dto.getFilterJson()); + entity.setUserId(userId); + return entity; + } + + public MagicShelf getShelf(Long id) { + MagicShelfEntity shelf = repository.findById(id).orElseThrow(() -> new IllegalArgumentException("Shelf not found")); + return toDto(shelf); + } +} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataMatchService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataMatchService.java index d99b69c4f..fc52a8b75 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataMatchService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataMatchService.java @@ -63,7 +63,7 @@ public class MetadataMatchService { if (isPositive(metadata.getHardcoverReviewCount())) score += weights.getHardcoverReviewCount(); if (isPresent(metadata.getThumbnail())) score += weights.getCoverImage(); - return score / totalWeight; + return (score / totalWeight) * 100f; } private boolean isPresent(String value) { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/migration/AppMigrationService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/migration/AppMigrationService.java index c567a0756..9ee349c77 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/migration/AppMigrationService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/migration/AppMigrationService.java @@ -51,7 +51,7 @@ public class AppMigrationService { @Transactional public void populateMetadataScoresOnce() { - if (migrationRepository.existsById("populateMetadataScores")) return; + if (migrationRepository.existsById("populateMetadataScores_v2")) return; List books = bookQueryService.getAllFullBookEntities(); for (BookEntity book : books) { @@ -60,8 +60,8 @@ public class AppMigrationService { } bookRepository.saveAll(books); - log.info("Migration 'populateMetadataScores' applied to {} books.", books.size()); - migrationRepository.save(new AppMigrationEntity("populateMetadataScores", LocalDateTime.now(), "Calculate and store metadata match score for all books")); + log.info("Migration 'populateMetadataScores_v2' applied to {} books.", books.size()); + migrationRepository.save(new AppMigrationEntity("populateMetadataScores_v2", LocalDateTime.now(), "Calculate and store metadata match score for all books")); } @Transactional diff --git a/booklore-api/src/main/resources/db/migration/V39__Create_magic_shelf_table.sql b/booklore-api/src/main/resources/db/migration/V39__Create_magic_shelf_table.sql new file mode 100644 index 000000000..76cc0a9f9 --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V39__Create_magic_shelf_table.sql @@ -0,0 +1,11 @@ +CREATE TABLE magic_shelf +( + id BIGINT AUTO_INCREMENT PRIMARY KEY, + user_id BIGINT NOT NULL, + name VARCHAR(255) NOT NULL, + icon VARCHAR(64) NOT NULL, + filter_json JSON NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + UNIQUE KEY uq_user_name (user_id, name) +); \ No newline at end of file diff --git a/booklore-ui/src/app/app.routes.ts b/booklore-ui/src/app/app.routes.ts index 0897b4f80..b63c34b5d 100644 --- a/booklore-ui/src/app/app.routes.ts +++ b/booklore-ui/src/app/app.routes.ts @@ -1,6 +1,5 @@ import {Routes} from '@angular/router'; import {BookBrowserComponent} from './book/components/book-browser/book-browser.component'; -import {MainDashboardComponent} from './dashboard/components/main-dashboard/main-dashboard.component'; import {AppLayoutComponent} from './layout/component/layout-main/app.layout.component'; import {LoginComponent} from './core/component/login/login.component'; import {AuthGuard} from './auth.guard'; @@ -17,6 +16,8 @@ import {LoginGuard} from './core/setup/ login.guard'; import {OidcCallbackComponent} from './core/security/oidc-callback/oidc-callback.component'; import {CbxReaderComponent} from './book/components/cbx-reader/cbx-reader.component'; import {BookdropFileReviewComponent} from './bookdrop/bookdrop-file-review-component/bookdrop-file-review.component'; +import {MagicShelfComponent} from './magic-shelf-component/magic-shelf-component'; +import {MainDashboardComponent} from './dashboard/components/main-dashboard/main-dashboard.component'; export const routes: Routes = [ { @@ -41,6 +42,7 @@ export const routes: Routes = [ {path: 'library/:libraryId/books', component: BookBrowserComponent, canActivate: [AuthGuard]}, {path: 'shelf/:shelfId/books', component: BookBrowserComponent, canActivate: [AuthGuard]}, {path: 'unshelved-books', component: BookBrowserComponent, canActivate: [AuthGuard]}, + { path: 'magic-shelf/:magicShelfId/books', component: BookBrowserComponent, canActivate: [AuthGuard] }, {path: 'book/:bookId', component: BookMetadataCenterComponent, canActivate: [AuthGuard]}, {path: 'bookdrop', component: BookdropFileReviewComponent, canActivate: [AuthGuard]} ] diff --git a/booklore-ui/src/app/book-rule-evaluator.service.ts b/booklore-ui/src/app/book-rule-evaluator.service.ts new file mode 100644 index 000000000..3447b2a37 --- /dev/null +++ b/booklore-ui/src/app/book-rule-evaluator.service.ts @@ -0,0 +1,229 @@ +import {Injectable} from '@angular/core'; +import {Book} from './book/model/book.model'; +import {GroupRule, Rule, RuleField, RuleOperator} from './magic-shelf-component/magic-shelf-component'; + +@Injectable({providedIn: 'root'}) +export class BookRuleEvaluatorService { + + evaluateGroup(book: Book, group: GroupRule): boolean { + const results = group.rules.map(rule => { + if ('type' in rule && rule.type === 'group') { + return this.evaluateGroup(book, rule as GroupRule); + } else { + return this.evaluateRule(book, rule as Rule); + } + }); + return group.join === 'and' ? results.every(Boolean) : results.some(Boolean); + } + + private evaluateRule(book: Book, rule: Rule): boolean { + const rawValue = this.extractBookValue(book, rule.field); + + const normalize = (val: any): any => { + if (val === null || val === undefined) return val; + if (val instanceof Date) return val; + const date = new Date(val); + if (!isNaN(date.getTime())) return date; + if (typeof val === 'string') 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 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 'readStatus': + return [String(book.readStatus).toLowerCase()]; + case 'fileType': + return [String(this.getFileExtension(book.fileName) ?? '').toLowerCase()]; + case 'library': + return [String(book.libraryId)]; + 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()]; + default: + return []; + } + }; + + const ruleList = Array.isArray(rule.value) + ? rule.value.map(v => String(v).toLowerCase()) + : (rule.value ? [String(rule.value).toLowerCase()] : []); + + switch (rule.operator) { + case 'equals': + if (Array.isArray(value)) { + return value.some(v => ruleList.includes(v)); + } + if (value instanceof Date && ruleVal instanceof Date) { + return value.getTime() === ruleVal.getTime(); + } + return value === ruleVal; + + case 'not_equals': + if (Array.isArray(value)) { + return value.every(v => !ruleList.includes(v)); + } + if (value instanceof Date && ruleVal instanceof Date) { + return value.getTime() !== ruleVal.getTime(); + } + return value !== ruleVal; + + case 'contains': + if (typeof value !== 'string') return false; + if (typeof ruleVal !== 'string') return false; + return value.includes(ruleVal); + + case 'does_not_contain': + if (typeof value !== 'string') return true; + if (typeof ruleVal !== 'string') return true; + return !value.includes(ruleVal); + + case 'starts_with': + if (typeof value !== 'string') return false; + if (typeof ruleVal !== 'string') return false; + return value.startsWith(ruleVal); + + case 'ends_with': + 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': + if (value == null) return true; + if (typeof value === 'string') return value.trim() === ''; + if (Array.isArray(value)) return value.length === 0; + return false; + + case 'is_not_empty': + if (value == null) return false; + if (typeof value === 'string') return value.trim() !== ''; + if (Array.isArray(value)) return value.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)); + } + + default: + return false; + } + } + + private extractBookValue(book: Book, field: RuleField): any { + switch (field) { + case 'library': + return book.libraryId; + case 'readStatus': + return book.readStatus; + case 'fileType': + return this.getFileExtension(book.fileName)?.toLowerCase() ?? null; + case 'fileSize': + return book.fileSizeKb; + case 'metadataScore': + return book.metadataMatchScore; + case 'personalRating': + return book.metadata?.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 'publisher': + return book.metadata?.publisher?.toLowerCase() ?? null; + case 'publishedDate': + return book.metadata?.publishedDate ? new Date(book.metadata.publishedDate) : 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 '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; + default: + return (book as any)[field]; + } + } + + private getFileExtension(filePath?: string): string | null { + if (!filePath) return null; + const parts = filePath.split('.'); + if (parts.length < 2) return null; + return parts.pop() ?? null; + } +} diff --git a/booklore-ui/src/app/book/components/book-browser/book-browser.component.ts b/booklore-ui/src/app/book/components/book-browser/book-browser.component.ts index 9b8615b58..3de2b5352 100644 --- a/booklore-ui/src/app/book/components/book-browser/book-browser.component.ts +++ b/booklore-ui/src/app/book/components/book-browser/book-browser.component.ts @@ -3,7 +3,7 @@ import {ActivatedRoute, Router} from '@angular/router'; import {ConfirmationService, MenuItem, MessageService, PrimeTemplate} from 'primeng/api'; import {LibraryService} from '../../service/library.service'; import {BookService} from '../../service/book.service'; -import {debounceTime, filter, map, switchMap, take} from 'rxjs/operators'; +import {catchError, debounceTime, filter, map, switchMap, take} from 'rxjs/operators'; import {BehaviorSubject, combineLatest, Observable, of, Subject} from 'rxjs'; import {ShelfService} from '../../service/shelf.service'; import {DynamicDialogRef} from 'primeng/dynamicdialog'; @@ -45,10 +45,14 @@ import {MultiSelect} from 'primeng/multiselect'; import {TableColumnPreferenceService} from './table-column-preference-service'; import {TieredMenu} from 'primeng/tieredmenu'; import {BookMenuService} from '../../service/book-menu.service'; +import {MagicShelf, MagicShelfService} from '../../../magic-shelf-service'; +import {BookRuleEvaluatorService} from '../../../book-rule-evaluator.service'; +import {GroupRule} from '../../../magic-shelf-component/magic-shelf-component'; export enum EntityType { LIBRARY = 'Library', SHELF = 'Shelf', + MAGIC_SHELF = 'Magic Shelf', ALL_BOOKS = 'All Books', UNSHELVED = 'Unshelved Books', } @@ -98,11 +102,11 @@ const SORT_DIRECTION = { }) export class BookBrowserComponent implements OnInit, AfterViewInit { bookState$: Observable | undefined; - entity$: Observable | undefined; + entity$: Observable | undefined; entityType$: Observable | undefined; searchTerm$ = new BehaviorSubject(''); - entity: Library | Shelf | null = null; + entity: Library | Shelf | MagicShelf | null = null; entityType: EntityType | undefined; bookTitle: string = ''; entityOptions: MenuItem[] | undefined; @@ -143,6 +147,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { private libraryShelfMenuService = inject(LibraryShelfMenuService); protected seriesCollapseFilter = inject(SeriesCollapseFilter); protected confirmationService = inject(ConfirmationService); + protected magicShelfService = inject(MagicShelfService); + protected bookRuleEvaluatorService = inject(BookRuleEvaluatorService); private sideBarFilter = new SideBarFilter(this.selectedFilter, this.selectedFilterMode); private headerFilter = new HeaderFilter(this.searchTerm$); @@ -203,7 +209,9 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { this.entityOptions = entity ? this.isLibrary(entity) ? this.libraryShelfMenuService.initializeLibraryMenuItems(entity) - : this.libraryShelfMenuService.initializeShelfMenuItems(entity) + : this.isMagicShelf(entity) + ? this.libraryShelfMenuService.initializeMagicShelfMenuItems(entity) + : this.libraryShelfMenuService.initializeShelfMenuItems(entity) : []; }); } @@ -238,6 +246,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { const sortParam = paramMap.get(QUERY_PARAMS.SORT); const directionParam = paramMap.get(QUERY_PARAMS.DIRECTION); const filterParams = paramMap.get(QUERY_PARAMS.FILTER); + const sidebarParam = paramMap.get(QUERY_PARAMS.SIDEBAR); const parsedFilters: Record = {}; @@ -320,7 +329,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { : VIEW_MODES.GRID) : (effectivePrefs.view?.toLowerCase() ?? VIEW_MODES.GRID); - //this.showFilter = sidebarParam === 'true' || (sidebarParam === null && this.filterVisibility); + //this.showFilter = sidebarParam === 'true' || (sidebarParam === null && filterParams !== filterParams); this.bookSorter.updateSortOptions(); @@ -369,10 +378,14 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { }); } - private isLibrary(entity: Library | Shelf): entity is Library { + private isLibrary(entity: Library | Shelf | MagicShelf): entity is Library { return (entity as Library).paths !== undefined; } + private isMagicShelf(entity: any): entity is MagicShelf { + return entity && 'filterJson' in entity; + } + get viewIcon(): string { return this.currentViewMode === VIEW_MODES.GRID ? 'pi pi-objects-column' : 'pi pi-table'; } @@ -382,6 +395,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { map(params => { const libraryId = Number(params.get('libraryId') || NaN); const shelfId = Number(params.get('shelfId') || NaN); + const magicShelfId = Number(params.get('magicShelfId') || NaN); if (!isNaN(libraryId)) { this.entityType = EntityType.LIBRARY; @@ -389,6 +403,9 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { } else if (!isNaN(shelfId)) { this.entityType = EntityType.SHELF; return {entityId: shelfId, entityType: EntityType.SHELF}; + } else if (!isNaN(magicShelfId)) { + this.entityType = EntityType.MAGIC_SHELF; + return {entityId: magicShelfId, entityType: EntityType.MAGIC_SHELF}; } else { this.entityType = EntityType.ALL_BOOKS; return {entityId: NaN, entityType: EntityType.ALL_BOOKS}; @@ -397,12 +414,14 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { ); } - private fetchEntity(entityId: number, entityType: EntityType): Observable { + private fetchEntity(entityId: number, entityType: EntityType): Observable { switch (entityType) { case EntityType.LIBRARY: return this.fetchLibrary(entityId); case EntityType.SHELF: return this.fetchShelf(entityId); + case EntityType.MAGIC_SHELF: + return this.fetchMagicShelf(entityId); default: return of(null); } @@ -416,6 +435,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { return this.fetchBooks(book => book.shelves?.some(shelf => shelf.id === entityId) ?? false ); + case EntityType.MAGIC_SHELF: + return this.fetchBooksMagicShelfBooks(entityId); case EntityType.ALL_BOOKS: default: return this.fetchAllBooks(); @@ -440,6 +461,25 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { ); } + private fetchBooksMagicShelfBooks(magicShelfId: number): Observable { + return combineLatest([ + this.bookService.bookState$, + this.magicShelfService.getShelf(magicShelfId) + ]).pipe( + map(([bookState, magicShelf]) => { + if (!bookState.loaded || bookState.error || !magicShelf?.filterJson) { + return bookState; + } + const filteredBooks: Book[] | undefined = bookState.books?.filter(book => + this.bookRuleEvaluatorService.evaluateGroup(book, JSON.parse(magicShelf.filterJson!) as GroupRule) + ); + const sortedBooks = this.sortService.applySort(filteredBooks ?? [], this.bookSorter.selectedSort!); + return {...bookState, books: sortedBooks}; + }), + switchMap(bookState => this.applyBookFilters(bookState)) + ); + } + private fetchBooks(bookFilter: (book: Book) => boolean): Observable { return this.bookService.bookState$.pipe( map(bookState => { @@ -491,6 +531,22 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { ); } + private fetchMagicShelf(magicShelfId: number): Observable { + return this.magicShelfService.shelvesState$.pipe( + take(1), + switchMap((state) => { + const cached = state.shelves?.find(s => s.id === magicShelfId) ?? null; + if (cached) { + return of(cached); + } + return this.magicShelfService.getShelf(magicShelfId).pipe( + map(shelf => shelf ?? null), + catchError(() => of(null)) + ); + }) + ); + } + onCheckboxClicked(event: { index: number; bookId: number; selected: boolean; shiftKey: boolean }) { const {index, bookId, selected, shiftKey} = event; if (!shiftKey || this.lastSelectedIndex === null) { diff --git a/booklore-ui/src/app/book/components/book-browser/book-filter/book-filter.component.html b/booklore-ui/src/app/book/components/book-browser/book-filter/book-filter.component.html index a2c9cf9a9..541daa6d4 100644 --- a/booklore-ui/src/app/book/components/book-browser/book-filter/book-filter.component.html +++ b/booklore-ui/src/app/book/components/book-browser/book-filter/book-filter.component.html @@ -12,7 +12,6 @@ styleClass="h-8"> -
@for (filterType of filterTypes; track filterType; let i = $index) { @@ -30,7 +29,6 @@ @if (filterStreams[filterType] | async; as filters) { -
@@ -38,8 +36,7 @@
diff --git a/booklore-ui/src/app/book/components/book-browser/book-filter/book-filter.component.ts b/booklore-ui/src/app/book/components/book-browser/book-filter/book-filter.component.ts index 6cbc7c1aa..d8db2e82f 100644 --- a/booklore-ui/src/app/book/components/book-browser/book-filter/book-filter.component.ts +++ b/booklore-ui/src/app/book/components/book-browser/book-filter/book-filter.component.ts @@ -13,6 +13,9 @@ import {FormsModule} from '@angular/forms'; import {SelectButton} from 'primeng/selectbutton'; import {UserService} from '../../../../settings/user-management/user.service'; import {FilterSortPreferenceService} from '../filters/filter-sorting-preferences.service'; +import {MagicShelf} from '../../../../magic-shelf-service'; +import {GroupRule} from '../../../../magic-shelf-component/magic-shelf-component'; +import {BookRuleEvaluatorService} from '../../../../book-rule-evaluator.service'; type Filter = { value: T; bookCount: number }; @@ -148,7 +151,7 @@ export class BookFilterComponent implements OnInit, OnDestroy { @Output() filterSelected = new EventEmitter | null>(); @Output() filterModeChanged = new EventEmitter<'and' | 'or'>(); - @Input() entity$!: Observable | undefined; + @Input() entity$!: Observable | undefined; @Input() entityType$!: Observable | undefined; @Input() resetFilter$!: Subject; @Input() showFilter: boolean = false; @@ -185,6 +188,7 @@ export class BookFilterComponent implements OnInit, OnDestroy { bookService = inject(BookService); userService = inject(UserService); filterSortPreferenceService = inject(FilterSortPreferenceService); + bookRuleEvaluatorService = inject(BookRuleEvaluatorService); ngOnInit(): void { combineLatest([ @@ -283,9 +287,21 @@ export class BookFilterComponent implements OnInit, OnDestroy { if (entityType === EntityType.LIBRARY && entity && 'id' in entity) { return books.filter((book) => book.libraryId === entity.id); } + if (entityType === EntityType.SHELF && entity && 'id' in entity) { return books.filter((book) => book.shelves?.some((shelf) => shelf.id === entity.id)); } + + if (entityType === EntityType.MAGIC_SHELF && entity && 'filterJson' in entity) { + try { + const groupRule = JSON.parse(entity.filterJson) as GroupRule; + return books.filter((book) => this.bookRuleEvaluatorService.evaluateGroup(book, groupRule)); + } catch (e) { + console.warn('Invalid filterJson for MagicShelf:', e); + return []; + } + } + return books; } diff --git a/booklore-ui/src/app/book/service/book.service.ts b/booklore-ui/src/app/book/service/book.service.ts index bb5068ab7..6293a6f80 100644 --- a/booklore-ui/src/app/book/service/book.service.ts +++ b/booklore-ui/src/app/book/service/book.service.ts @@ -63,7 +63,7 @@ export class BookService { return currentState.books.filter(book => idSet.has(+book.id)); } - updateBookShelves(bookIds: Set, shelvesToAssign: Set, shelvesToUnassign: Set): Observable { + updateBookShelves(bookIds: Set, shelvesToAssign: Set, shelvesToUnassign: Set): Observable { const requestPayload = { bookIds: Array.from(bookIds), shelvesToAssign: Array.from(shelvesToAssign), @@ -422,6 +422,10 @@ export class BookService { ); } + getMagicShelfBookCount(number: number) { + + } + /*------------------ All the websocket handlers go below ------------------*/ diff --git a/booklore-ui/src/app/book/service/library-shelf-menu.service.ts b/booklore-ui/src/app/book/service/library-shelf-menu.service.ts index 709491919..36100a1a2 100644 --- a/booklore-ui/src/app/book/service/library-shelf-menu.service.ts +++ b/booklore-ui/src/app/book/service/library-shelf-menu.service.ts @@ -10,6 +10,8 @@ import {MetadataFetchOptionsComponent} from '../../metadata/metadata-options-dia import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum'; import {LibraryCreatorComponent} from '../components/library-creator/library-creator.component'; import {ShelfEditDialogComponent} from '../components/shelf-edit-dialog/shelf-edit-dialog.component'; +import {MagicShelf, MagicShelfService} from '../../magic-shelf-service'; +import {MagicShelfComponent} from '../../magic-shelf-component/magic-shelf-component'; @Injectable({ providedIn: 'root', @@ -22,8 +24,9 @@ export class LibraryShelfMenuService { private shelfService = inject(ShelfService); private router = inject(Router); private dialogService = inject(DialogService); + private magicShelfService = inject(MagicShelfService); - initializeLibraryMenuItems(entity: Library | Shelf | null): MenuItem[] { + initializeLibraryMenuItems(entity: Library | Shelf | MagicShelf | null): MenuItem[] { return [ { label: 'Options', @@ -184,4 +187,53 @@ export class LibraryShelfMenuService { } ]; } + + initializeMagicShelfMenuItems(entity: any): MenuItem[] { + return [ + { + label: 'Options', + items: [ + { + label: 'Edit Magic Shelf', + icon: 'pi pi-pen-to-square', + command: () => { + this.dialogService.open(MagicShelfComponent, { + header: 'Edit Magic Shelf', + modal: true, + closable: true, + data: { + id: entity?.id + } + }) + } + }, + { + label: 'Delete Magic Shelf', + icon: 'pi pi-trash', + command: () => { + this.confirmationService.confirm({ + message: `Are you sure you want to delete magic shelf: ${entity?.name}?`, + header: 'Confirmation', + accept: () => { + this.magicShelfService.deleteShelf(entity?.id!).subscribe({ + complete: () => { + this.router.navigate(['/']); + this.messageService.add({severity: 'info', summary: 'Success', detail: 'Magic shelf was deleted'}); + }, + error: () => { + this.messageService.add({ + severity: 'error', + summary: 'Failed', + detail: 'Failed to delete shelf', + }); + } + }); + } + }); + } + } + ] + } + ]; + } } diff --git a/booklore-ui/src/app/dialog-launcher.service.ts b/booklore-ui/src/app/dialog-launcher.service.ts new file mode 100644 index 000000000..fbf0f3890 --- /dev/null +++ b/booklore-ui/src/app/dialog-launcher.service.ts @@ -0,0 +1,80 @@ +import {inject, Injectable} from '@angular/core'; +import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog'; +import {GithubSupportDialog} from './utilities/component/github-support-dialog/github-support-dialog'; +import {LibraryCreatorComponent} from './book/components/library-creator/library-creator.component'; +import {BookUploaderComponent} from './utilities/component/book-uploader/book-uploader.component'; +import {UserProfileDialogComponent} from './settings/global-preferences/user-profile-dialog/user-profile-dialog.component'; +import {MagicShelfComponent} from './magic-shelf-component/magic-shelf-component'; + +@Injectable({ + providedIn: 'root', +}) +export class DialogLauncherService { + + dialogService = inject(DialogService); + + open(options: { component: any; header: string; top?: string; width?: string }): DynamicDialogRef { + const isMobile = window.innerWidth <= 768; + const {component, header, top, width} = options; + return this.dialogService.open(component, { + header, + modal: true, + closable: true, + contentStyle: { + overflowY: 'hidden', + }, + style: { + position: 'absolute', + ...(top ? {top} : {}), + ...(isMobile + ? { + width: '90vw', + maxWidth: '90vw', + minWidth: '90vw', + } + : width + ? {width} + : {}), + }, + }); + } + + openGithubSupportDialog(): void { + this.open({ + component: GithubSupportDialog, + header: 'Support BookLore on GitHub', + top: '25%' + }); + } + + openLibraryCreatorDialog(): void { + this.open({ + component: LibraryCreatorComponent, + header: 'Create New Library', + top: '15%' + }); + } + + openFileUploadDialog(): void { + this.open({ + component: BookUploaderComponent, + header: 'Book Uploader', + top: '10%' + }); + } + + openUserProfileDialog(): void { + this.open({ + component: UserProfileDialogComponent, + header: 'User Profile Information', + top: '10%' + }); + } + + openMagicShelfDialog(): void { + this.open({ + component: MagicShelfComponent, + header: 'Magic Shelf Creator' + }); + } +} diff --git a/booklore-ui/src/app/icon-picker-v2-component/icon-picker-v2-component.html b/booklore-ui/src/app/icon-picker-v2-component/icon-picker-v2-component.html new file mode 100644 index 000000000..824d67440 --- /dev/null +++ b/booklore-ui/src/app/icon-picker-v2-component/icon-picker-v2-component.html @@ -0,0 +1,12 @@ + + +
+ @for (icon of filteredIcons(); track icon) { +
+ +
+ } +
diff --git a/booklore-ui/src/app/icon-picker-v2-component/icon-picker-v2-component.scss b/booklore-ui/src/app/icon-picker-v2-component/icon-picker-v2-component.scss new file mode 100644 index 000000000..1e7731398 --- /dev/null +++ b/booklore-ui/src/app/icon-picker-v2-component/icon-picker-v2-component.scss @@ -0,0 +1,32 @@ +.icon-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(25px, 1fr)); + gap: 30px; +} + +.icon-item { + display: flex; + justify-content: center; + align-items: center; + cursor: pointer; +} + +.icon-search { + width: 100%; + padding: 8px 12px; + font-size: 16px; + border: 1px solid var(--text-color-secondary); + border-radius: 4px; + margin-bottom: 15px; + box-sizing: border-box; +} + +.icon-search:focus { + border-color: var(--primary-color); + outline: none; +} + +.icon-search::placeholder { + color: var(--text-color-secondary); + opacity: 1; +} diff --git a/booklore-ui/src/app/icon-picker-v2-component/icon-picker-v2-component.ts b/booklore-ui/src/app/icon-picker-v2-component/icon-picker-v2-component.ts new file mode 100644 index 000000000..44e43b0d2 --- /dev/null +++ b/booklore-ui/src/app/icon-picker-v2-component/icon-picker-v2-component.ts @@ -0,0 +1,71 @@ +import {Component, EventEmitter, inject, Output} from '@angular/core'; +import {FormsModule} from '@angular/forms'; +import {DynamicDialogRef} from 'primeng/dynamicdialog'; + +@Component({ + selector: 'app-icon-picker-v2-component', + imports: [ + FormsModule + ], + templateUrl: './icon-picker-v2-component.html', + styleUrl: './icon-picker-v2-component.scss' +}) +export class IconPickerV2Component { + + iconCategories: string[] = [ + "address-book", "align-center", "align-justify", "align-left", "align-right", "android", + "angle-double-down", "angle-double-left", "angle-double-right", "angle-double-up", "angle-down", "angle-left", + "angle-right", "angle-up", "apple", "arrow-circle-down", "arrow-circle-left", "arrow-circle-right", + "arrow-circle-up", "arrow-down-left-and-arrow-up-right-to-center", "arrow-down-left", "arrow-down-right", "arrow-down", "arrow-left", + "arrow-right-arrow-left", "arrow-right", "arrow-up-left", "arrow-up-right-and-arrow-down-left-from-center", "arrow-up-right", "arrow-up", + "arrows-alt", "arrows-h", "arrows-v", "asterisks", "at", "backward", "ban", "barcode", "bars", "bell-slash", "bell", "bitcoin", + "bolt", "book", "bookmark-fill", "bookmark", "box", "briefcase", "building-columns", "building", "bullseye", "calculator", "calendar-clock", "calendar-minus", + "calendar-plus", "calendar-times", "calendar", "camera", "car", "caret-down", "caret-left", "caret-right", "caret-up", "cart-arrow-down", "cart-minus", "cart-plus", + "chart-bar", "chart-line", "chart-pie", "chart-scatter", "check-circle", "check-square", "check", "chevron-circle-down", "chevron-circle-left", "chevron-circle-right", + "chevron-circle-up", "chevron-down", "chevron-left", "chevron-right", "chevron-up", "circle-fill", "circle-off", "circle-on", "circle", "clipboard", "clock", "clone", "cloud-download", "cloud-upload", + "cloud", "code", "cog", "comment", "comments", "compass", "copy", "credit-card", "crown", "database", "delete-left", "desktop", + "directions-alt", "directions", "discord", "dollar", "download", "eject", "ellipsis-h", "ellipsis-v", "envelope", "equals", "eraser", "ethereum", + "euro", "exclamation-circle", "exclamation-triangle", "expand", "external-link", "eye-slash", "eye", "face-smile", "facebook", "fast-backward", "fast-forward", "file-arrow-up", + "file-check", "file-edit", "file-excel", "file-export", "file-import", "file-o", "file-pdf", "file-plus", "file-word", "file", "filter-fill", "filter-slash", + "filter", "flag-fill", "flag", "folder-open", "folder-plus", "folder", "forward", "gauge", "gift", "github", "globe", "google", + "graduation-cap", "hammer", "hashtag", "headphones", "heart-fill", "heart", "history", "home", "hourglass", "id-card", "image", "images", + "inbox", "indian-rupee", "info-circle", "info", "instagram", "key", "language", "lightbulb", "link", "linkedin", "list-check", "list", + "lock-open", "lock", "map-marker", "map", "mars", "megaphone", "microchip-ai", "microchip", "microphone", "microsoft", "minus-circle", "minus", + "mobile", "money-bill", "moon", "objects-column", "palette", "paperclip", "pause-circle", "pause", "paypal", "pen-to-square", "pencil", "percentage", + "phone", "pinterest", "play-circle", "play", "plus-circle", "plus", "pound", "power-off", "prime", "print", "qrcode", "question-circle", + "question", "receipt", "reddit", "refresh", "replay", "reply", "save", "search-minus", "search-plus", "search", "send", "server", + "share-alt", "shield", "shop", "shopping-bag", "shopping-cart", "sign-in", "sign-out", "sitemap", "slack", "sliders-h", "sliders-v", "sort-alpha-alt-down", + "sort-alpha-alt-up", "sort-alpha-down", "sort-alpha-up", "sort-alt-slash", "sort-alt", "sort-amount-down-alt", "sort-amount-down", "sort-amount-up-alt", + "sort-amount-up", "sort-down-fill", "sort-down", "sort-numeric-alt-down", + "sort-numeric-alt-up", "sort-numeric-down", "sort-numeric-up", "sort-up-fill", "sort-up", "sort", "sparkles", "spinner-dotted", "spinner", "star-fill", "star-half-fill", "star-half", + "star", "step-backward-alt", "step-backward", "step-forward-alt", "step-forward", "stop-circle", "stop", "stopwatch", "sun", "sync", "table", "tablet", + "tag", "tags", "telegram", "th-large", "thumbs-down-fill", "thumbs-down", "thumbs-up-fill", "thumbs-up", "thumbtack", "ticket", "tiktok", "times-circle", + "times", "trash", "trophy", "truck", "turkish-lira", "twitch", "twitter", "undo", "unlock", "upload", "user-edit", "user-minus", + "user-plus", "user", "users", "venus", "verified", "video", "vimeo", "volume-down", "volume-off", "volume-up", "wallet", "warehouse", + "wave-pulse", "whatsapp", "wifi", "window-maximize", "window-minimize", "wrench", "youtube" + ]; + + searchText: string = ''; + selectedIcon: string | null = null; + icons: string[] = this.createIconList(this.iconCategories); + + ref = inject(DynamicDialogRef); + + createIconList(categories: string[]): string[] { + return categories.map(iconName => `pi pi-${iconName}`); + } + + filteredIcons(): string[] { + if (!this.searchText) return this.icons; + return this.icons.filter(icon => icon.toLowerCase().includes(this.searchText.toLowerCase())); + } + + selectIcon(icon: string) { + this.selectedIcon = icon; + this.ref.close(icon); + } + + cancel() { + this.ref.close(); + } +} diff --git a/booklore-ui/src/app/layout/component/layout-menu/app.menu.component.html b/booklore-ui/src/app/layout/component/layout-menu/app.menu.component.html index 317bf4f9c..fb4f88078 100644 --- a/booklore-ui/src/app/layout/component/layout-menu/app.menu.component.html +++ b/booklore-ui/src/app/layout/component/layout-menu/app.menu.component.html @@ -29,6 +29,16 @@ } } + +
    + @if (magicShelfMenu$ | async; as shelfMenu) { + @for (item of shelfMenu; track item; let i = $index) { + @if (!item.separator) { +
  • + } + } + } +
@if (versionInfo) { diff --git a/booklore-ui/src/app/layout/component/layout-menu/app.menu.component.ts b/booklore-ui/src/app/layout/component/layout-menu/app.menu.component.ts index c6430362f..57b81b184 100644 --- a/booklore-ui/src/app/layout/component/layout-menu/app.menu.component.ts +++ b/booklore-ui/src/app/layout/component/layout-menu/app.menu.component.ts @@ -12,6 +12,7 @@ import {AppVersion, VersionService} from '../../../core/service/version.service' import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog'; import {VersionChangelogDialogComponent} from './version-changelog-dialog/version-changelog-dialog.component'; import {UserService} from '../../../settings/user-management/user.service'; +import {MagicShelf, MagicShelfService, MagicShelfState} from '../../../magic-shelf-service'; @Component({ selector: 'app-menu', @@ -23,6 +24,7 @@ export class AppMenuComponent implements OnInit { libraryMenu$: Observable | undefined; shelfMenu$: Observable | undefined; homeMenu$: Observable | undefined; + magicShelfMenu$: Observable | undefined; versionInfo: AppVersion | null = null; dynamicDialogRef: DynamicDialogRef | undefined; @@ -34,6 +36,7 @@ export class AppMenuComponent implements OnInit { private libraryShelfMenuService = inject(LibraryShelfMenuService); private dialogService = inject(DialogService); private userService = inject(UserService); + private magicShelfService = inject(MagicShelfService); librarySortField: 'name' | 'id' = 'name'; librarySortOrder: 'asc' | 'desc' = 'desc'; @@ -41,7 +44,6 @@ export class AppMenuComponent implements OnInit { shelfSortOrder: 'asc' | 'desc' = 'asc'; - ngOnInit(): void { this.versionService.getVersion().subscribe((data) => { this.versionInfo = data; @@ -91,8 +93,10 @@ export class AppMenuComponent implements OnInit { const sortedLibraries = this.sortArray(libraries, this.librarySortField, this.librarySortOrder); return [ { - label: 'Library', + label: 'Libraries', + type: 'library', hasDropDown: true, + hasCreate: true, items: sortedLibraries.map((library) => ({ menu: this.libraryShelfMenuService.initializeLibraryMenuItems(library), label: library.name, @@ -106,6 +110,29 @@ export class AppMenuComponent implements OnInit { }) ); + this.magicShelfMenu$ = this.magicShelfService.shelvesState$.pipe( + map((state: MagicShelfState) => { + const shelves = state.shelves ?? []; + const sortedShelves = this.sortArray(shelves, 'name', 'asc'); + return [ + { + label: 'Magic Shelves', + type: 'magicShelf', + hasDropDown: true, + hasCreate: true, + items: sortedShelves.map((shelf) => ({ + label: shelf.name, + type: 'magicShelfItem', + icon: 'pi pi-' + shelf.icon, + menu: this.libraryShelfMenuService.initializeMagicShelfMenuItems(shelf), + routerLink: [`/magic-shelf/${shelf.id}/books`], + bookCount$: this.magicShelfService.getBookCount(shelf.id ?? 0), + })), + }, + ]; + }) + ); + this.shelfMenu$ = this.shelfService.shelfState$.pipe( map((state) => { const shelves = state.shelves ?? []; @@ -130,8 +157,10 @@ export class AppMenuComponent implements OnInit { return [ { + type: 'shelf', label: 'Shelves', hasDropDown: true, + hasCreate: false, items: [unshelvedItem, ...shelfItems], }, ]; diff --git a/booklore-ui/src/app/layout/component/layout-menu/app.menuitem.component.html b/booklore-ui/src/app/layout/component/layout-menu/app.menuitem.component.html index a74f505fe..1fa0eaea3 100644 --- a/booklore-ui/src/app/layout/component/layout-menu/app.menuitem.component.html +++ b/booklore-ui/src/app/layout/component/layout-menu/app.menuitem.component.html @@ -1,9 +1,20 @@ @if (root) { @if (item.hasDropDown) { -
-
{{ item.label }}
- +
+
{{ item.label }}
+ @if (item.hasCreate) { + + } +
+ { if (userData) { this.canManipulateLibrary = userData.permissions.canManipulateLibrary; @@ -143,4 +144,13 @@ export class AppMenuitemComponent implements OnInit, OnDestroy { this.menuResetSubscription.unsubscribe(); } } + + openDialog(item: any) { + if (item.type === 'library' && this.canManipulateLibrary) { + this.dialogLauncher.openLibraryCreatorDialog(); + } + if (item.type === 'magicShelf') { + this.dialogLauncher.openMagicShelfDialog(); + } + } } diff --git a/booklore-ui/src/app/layout/component/layout-topbar/app.topbar.component.ts b/booklore-ui/src/app/layout/component/layout-topbar/app.topbar.component.ts index 9534591d6..977d72635 100644 --- a/booklore-ui/src/app/layout/component/layout-topbar/app.topbar.component.ts +++ b/booklore-ui/src/app/layout/component/layout-topbar/app.topbar.component.ts @@ -3,7 +3,6 @@ import {MenuItem} from 'primeng/api'; import {LayoutService} from '../layout-main/service/app.layout.service'; import {Router, RouterLink} from '@angular/router'; import {DialogService as PrimeDialogService, DynamicDialogRef} from 'primeng/dynamicdialog'; -import {LibraryCreatorComponent} from '../../../book/components/library-creator/library-creator.component'; import {TooltipModule} from 'primeng/tooltip'; import {FormsModule} from '@angular/forms'; import {InputTextModule} from 'primeng/inputtext'; @@ -14,11 +13,8 @@ import {Button} from 'primeng/button'; import {StyleClass} from 'primeng/styleclass'; import {Divider} from 'primeng/divider'; import {ThemeConfiguratorComponent} from '../theme-configurator/theme-configurator.component'; -import {BookUploaderComponent} from '../../../utilities/component/book-uploader/book-uploader.component'; import {AuthService} from '../../../core/service/auth.service'; import {UserService} from '../../../settings/user-management/user.service'; -import {UserProfileDialogComponent} from '../../../settings/global-preferences/user-profile-dialog/user-profile-dialog.component'; -import {GithubSupportDialog} from '../../../utilities/component/github-support-dialog/github-support-dialog'; import {Popover} from 'primeng/popover'; import {MetadataProgressService} from '../../../core/service/metadata-progress-service'; import {takeUntil} from 'rxjs/operators'; @@ -26,6 +22,7 @@ import {Subject} from 'rxjs'; import {MetadataBatchProgressNotification} from '../../../core/model/metadata-batch-progress.model'; import {UnifiedNotificationBoxComponent} from '../../../core/component/unified-notification-popover-component/unified-notification-popover-component'; import {BookdropFileService} from '../../../bookdrop/bookdrop-file.service'; +import {DialogLauncherService} from '../../../dialog-launcher.service'; @Component({ selector: 'app-topbar', @@ -79,7 +76,8 @@ export class AppTopBarComponent implements OnDestroy { private authService: AuthService, protected userService: UserService, private metadataProgressService: MetadataProgressService, - private bookdropFileService: BookdropFileService + private bookdropFileService: BookdropFileService, + private dialogLauncher: DialogLauncherService ) { this.subscribeToMetadataProgress(); this.subscribeToNotifications(); @@ -116,19 +114,19 @@ export class AppTopBarComponent implements OnDestroy { } openGithubSupportDialog(): void { - this.openDialog(GithubSupportDialog, 'Support BookLore on GitHub', '25%'); + this.dialogLauncher.openGithubSupportDialog(); } openLibraryCreatorDialog(): void { - this.openDialog(LibraryCreatorComponent, 'Create New Library', '15%'); + this.dialogLauncher.openLibraryCreatorDialog(); } openFileUploadDialog(): void { - this.openDialog(BookUploaderComponent, 'Book Uploader', '10%'); + this.dialogLauncher.openFileUploadDialog(); } openUserProfileDialog(): void { - this.openDialog(UserProfileDialogComponent, 'User Profile Information', '10%'); + this.dialogLauncher.openUserProfileDialog(); } navigateToSettings() { @@ -139,24 +137,6 @@ export class AppTopBarComponent implements OnDestroy { this.authService.logout(); } - private openDialog(component: any, header: string, top: string) { - const isMobile = window.innerWidth <= 768; - this.ref = this.dialogService.open(component, { - header, - modal: true, - closable: true, - style: { - position: 'absolute', - top, - ...(isMobile && { - width: '90vw', - maxWidth: '90vw', - minWidth: '90vw', - }), - }, - }); - } - private subscribeToMetadataProgress() { this.metadataProgressService.progressUpdates$ .pipe(takeUntil(this.destroy$)) diff --git a/booklore-ui/src/app/magic-shelf-component/magic-shelf-component.html b/booklore-ui/src/app/magic-shelf-component/magic-shelf-component.html new file mode 100644 index 000000000..b6fa9fefb --- /dev/null +++ b/booklore-ui/src/app/magic-shelf-component/magic-shelf-component.html @@ -0,0 +1,112 @@ +
+ +
+ +
+
+ + +
+
+
+ + + +
+
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + + @if (group.parent) { + + } +
+ +
+ @for (ruleCtrl of group.get('rules')['controls']; let i = $index; track trackByFn(ruleCtrl, i)) { +
+ @if (isGroup(ruleCtrl)) { + + + + } @else { + + + + @if (!['is_empty', 'is_not_empty'].includes(ruleCtrl.get('operator')?.value)) { + @if (ruleCtrl.get('operator')?.value === 'in_between') { + @if (ruleCtrl.get('field')?.value === 'publishedDate') { + + + } @else if (numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.type === 'number') { + + + } @else if (numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.type === 'decimal') { + + + } @else { + + + } + } @else { + @if (ruleCtrl.get('field')?.value === 'publishedDate') { + + } @else if (numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.type === 'number') { + + } @else if (numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.type === 'decimal') { + + } @else if (['includes_any', 'includes_all', 'excludes_all'].includes(ruleCtrl.get('operator')?.value)) { + @if (ruleCtrl.get('field')?.value === 'readStatus') { + + } @else if (ruleCtrl.get('field')?.value === 'fileType') { + + } @else if (ruleCtrl.get('field')?.value === 'library') { + + } @else { +
+ +
+ } + } @else if (ruleCtrl.get('field')?.value === 'readStatus') { + + } @else if (ruleCtrl.get('field')?.value === 'fileType') { + + } @else if (ruleCtrl.get('field')?.value === 'library') { + + } @else { + + } + } + } + + } +
+ } +
+
+
+
diff --git a/booklore-ui/src/app/magic-shelf-component/magic-shelf-component.scss b/booklore-ui/src/app/magic-shelf-component/magic-shelf-component.scss new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/booklore-ui/src/app/magic-shelf-component/magic-shelf-component.scss @@ -0,0 +1 @@ + diff --git a/booklore-ui/src/app/magic-shelf-component/magic-shelf-component.ts b/booklore-ui/src/app/magic-shelf-component/magic-shelf-component.ts new file mode 100644 index 000000000..1d7ec4303 --- /dev/null +++ b/booklore-ui/src/app/magic-shelf-component/magic-shelf-component.ts @@ -0,0 +1,458 @@ +import {Component, inject, OnInit} from '@angular/core'; +import {AbstractControl, FormArray, FormControl, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms'; +import {DropdownModule} from 'primeng/dropdown'; +import {Button} from 'primeng/button'; +import {NgTemplateOutlet} from '@angular/common'; +import {InputText} from 'primeng/inputtext'; +import {Select} from 'primeng/select'; +import {DatePicker} from 'primeng/datepicker'; +import {InputNumber} from 'primeng/inputnumber'; +import {ReadStatus} from '../book/model/book.model'; +import {LibraryService} from '../book/service/library.service'; +import {Library} from '../book/model/library.model'; +import {MagicShelfService} from '../magic-shelf-service'; +import {MessageService} from 'primeng/api'; +import {IconPickerV2Component} from '../icon-picker-v2-component/icon-picker-v2-component'; +import {DialogService, DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; +import {Chips} from 'primeng/chips'; +import {MultiSelect} from 'primeng/multiselect'; +import {EMPTY_CHECK_OPERATORS, MULTI_VALUE_OPERATORS, parseValue, removeNulls, serializeDateRules} from '../magic-shelf-utils'; + +export type RuleOperator = + | 'equals' + | 'not_equals' + | 'contains' + | 'does_not_contain' + | 'starts_with' + | 'ends_with' + | 'greater_than' + | 'greater_than_equal_to' + | 'less_than' + | 'less_than_equal_to' + | 'in_between' + | 'is_empty' + | 'is_not_empty' + | 'includes_any' + | 'excludes_all' + | 'includes_all' + +export type RuleField = + | 'library' + | 'title' + | 'subtitle' + | 'authors' + | 'categories' + | 'publisher' + | 'publishedDate' + | 'seriesName' + | 'seriesNumber' + | 'seriesTotal' + | 'pageCount' + | 'language' + | 'amazonRating' + | 'amazonReviewCount' + | 'goodreadsRating' + | 'goodreadsReviewCount' + | 'hardcoverRating' + | 'hardcoverReviewCount' + | 'personalRating' + | 'fileType' + | 'fileSize' + | 'readStatus' + | 'metadataScore'; + + +interface FullFieldConfig { + label: string; + type?: FieldType; + max?: number; +} + +type FieldType = 'number' | 'decimal' | 'date' | undefined; + +export interface Rule { + field: RuleField; + operator: RuleOperator; + value: any; + valueStart?: any; + valueEnd?: any; +} + +export interface FieldConfig { + type: FieldType; + max?: number; +} + +export interface GroupRule { + name: string; + type: 'group'; + join: 'and' | 'or'; + rules: Array; +} + +export type RuleFormGroup = FormGroup<{ + field: FormControl<"" | RuleField | null>; + operator: FormControl<"" | RuleOperator | null>; + value: FormControl; + valueStart: FormControl; + valueEnd: FormControl; +}>; + +export type GroupFormGroup = FormGroup<{ + type: FormControl<'group'>; + join: FormControl<'and' | 'or'>; + rules: FormArray; +}>; + +const FIELD_CONFIGS: Record = { + library: {label: 'Library'}, + readStatus: {label: 'Read Status'}, + metadataScore: {label: 'Metadata Score', type: 'decimal', max: 100}, + title: {label: 'Title'}, + authors: {label: 'Authors'}, + categories: {label: 'Categories'}, + publisher: {label: 'Publisher'}, + publishedDate: {label: 'Published Date', type: 'date'}, + personalRating: {label: 'Personal Rating', type: 'decimal', max: 10}, + pageCount: {label: 'Page Count', type: 'number'}, + language: {label: 'Language'}, + seriesName: {label: 'Series Name'}, + seriesNumber: {label: 'Series Number', type: 'number'}, + seriesTotal: {label: 'Books in Series', type: 'number'}, + fileSize: {label: 'File Size (Kb)', type: 'number'}, + fileType: {label: 'File Type'}, + subtitle: {label: 'Subtitle'}, + amazonRating: {label: 'Amazon Rating', type: 'decimal', max: 5}, + amazonReviewCount: {label: 'Amazon Review Count', type: 'number'}, + goodreadsRating: {label: 'Goodreads Rating', type: 'decimal', max: 5}, + goodreadsReviewCount: {label: 'Goodreads Review Count', type: 'number'}, + hardcoverRating: {label: 'Hardcover Rating', type: 'decimal', max: 5}, + hardcoverReviewCount: {label: 'Hardcover Review Count', type: 'number'} +}; + +@Component({ + selector: 'app-magic-shelf', + templateUrl: './magic-shelf-component.html', + standalone: true, + imports: [ + ReactiveFormsModule, + DropdownModule, + NgTemplateOutlet, + InputText, + Select, + Button, + DatePicker, + InputNumber, + Chips, + MultiSelect + ] +}) +export class MagicShelfComponent implements OnInit { + + numericFieldConfigMap = new Map( + Object.entries(FIELD_CONFIGS) + .filter(([_, config]) => config.type) + .map(([key, config]) => [key as RuleField, {type: config.type!, max: config.max}]) + ); + + conditionOptions: { label: string; value: 'and' | 'or' }[] = [ + {label: 'AND', value: 'and'}, + {label: 'OR', value: 'or'}, + ]; + + fieldOptions = Object.entries(FIELD_CONFIGS).map(([key, config]) => ({ + label: config.label, + value: key as RuleField + })); + + fileType: { label: string; value: string }[] = [ + {label: 'PDF', value: 'pdf'}, + {label: 'EPUB', value: 'epub'}, + {label: 'CBR', value: 'cbr'}, + {label: 'CBZ', value: 'cbz'}, + {label: 'CB7', value: 'cb7'} + ]; + + readStatusOptions = Object.entries(ReadStatus).map(([key, value]) => ({ + label: key.replace(/_/g, ' ').toLowerCase().replace(/\b\w/g, l => l.toUpperCase()), + value + })); + + libraries: Library[] = []; + libraryOptions: { label: string; value: number }[] = []; + + form = new FormGroup({ + name: new FormControl(null), + icon: new FormControl(null), + group: this.createGroup() + }); + + shelfId: number | null = null; + + libraryService = inject(LibraryService); + magicShelfService = inject(MagicShelfService); + messageService = inject(MessageService); + dialogService = inject(DialogService); + config = inject(DynamicDialogConfig); + + trackByFn(ruleCtrl: AbstractControl, index: number): any { + return ruleCtrl; + } + + ngOnInit(): void { + const id = this.config?.data?.id; + + if (id) { + this.shelfId = id; + this.magicShelfService.getShelf(id).subscribe((data) => { + this.form = new FormGroup({ + name: new FormControl(data?.name ?? null, {nonNullable: true, validators: [Validators.required]}), + icon: new FormControl(data?.icon ?? null, {nonNullable: true, validators: [Validators.required]}), + group: data?.filterJson ? this.buildGroupFromData(JSON.parse(data.filterJson)) : this.createGroup() + }); + }); + } else { + this.form = new FormGroup({ + name: new FormControl(null, {nonNullable: true, validators: [Validators.required]}), + icon: new FormControl(null, {nonNullable: true, validators: [Validators.required]}), + group: this.createGroup() + }); + } + + this.libraries = this.libraryService.getLibrariesFromState(); + this.libraryOptions = this.libraries.map(lib => ({ + label: lib.name, + value: lib.id! + })); + } + + buildGroupFromData(data: GroupRule): GroupFormGroup { + const rulesArray = new FormArray([]); + + data.rules.forEach(rule => { + if ('type' in rule && rule.type === 'group') { + rulesArray.push(this.buildGroupFromData(rule)); + } else { + rulesArray.push(this.buildRuleFromData(rule as Rule)); + } + }); + + return new FormGroup({ + type: new FormControl<'group'>('group'), + join: new FormControl(data.join), + rules: rulesArray as FormArray + }) as GroupFormGroup; + } + + buildRuleFromData(data: Rule): RuleFormGroup { + const config = FIELD_CONFIGS[data.field]; + const type = config?.type; + + return new FormGroup({ + field: new FormControl(data.field), + operator: new FormControl(data.operator), + value: new FormControl(parseValue(data.value, type)), + valueStart: new FormControl(parseValue(data.valueStart, type)), + valueEnd: new FormControl(parseValue(data.valueEnd, type)), + }) as RuleFormGroup; + } + + get group(): GroupFormGroup { + return this.form.get('group') as GroupFormGroup; + } + + getOperatorOptionsForField(field: RuleField | null | undefined) { + const baseOperators = [ + {label: 'Equals', value: 'equals'}, + {label: '≠ Not Equal', value: 'not_equals'}, + {label: 'Empty', value: 'is_empty'}, + {label: 'Not Empty', value: 'is_not_empty'}, + ]; + + const multiValueOperators = [ + {label: 'Includes Any', value: 'includes_any'}, + {label: 'Excludes All', value: 'excludes_all'}, + {label: 'Includes All', value: 'includes_all'}, + ]; + + const textOperators = [ + {label: 'Contains', value: 'contains'}, + {label: 'Doesn\'t Contain', value: 'does_not_contain'}, + {label: 'Starts With', value: 'starts_with'}, + {label: 'Ends With', value: 'ends_with'}, + ]; + + const comparisonOperators = [ + {label: '> Greater Than', value: 'greater_than'}, + {label: '≥ Greater or Equal', value: 'greater_than_equal_to'}, + {label: '< Less Than', value: 'less_than'}, + {label: '≤ Less or Equal', value: 'less_than_equal_to'}, + {label: 'Between', value: 'in_between'}, + ]; + + if (!field) return [...baseOperators, ...multiValueOperators]; + + const config = FIELD_CONFIGS[field]; + const isMultiValueField = ['library', 'authors', 'categories', 'readStatus', 'fileType', 'language', 'title', 'subtitle', 'publisher', 'seriesName'].includes(field); + const operators = [...baseOperators]; + + if (isMultiValueField) { + operators.push(...multiValueOperators); + } + + const isTextEligible = !['library', 'readStatus', 'fileType'].includes(field); + + if (config.type === 'number' || config.type === 'decimal' || config.type === 'date') { + operators.push(...comparisonOperators); + } else if (isTextEligible) { + operators.push(...textOperators); + } + + return operators; + } + + createRule(): RuleFormGroup { + return new FormGroup({ + field: new FormControl(''), + operator: new FormControl(''), + value: new FormControl(null), + valueStart: new FormControl(null), + valueEnd: new FormControl(null), + }) as RuleFormGroup; + } + + createGroup(): GroupFormGroup { + return new FormGroup({ + type: new FormControl<'group'>('group' as 'group'), + join: new FormControl<'and' | 'or'>('and' as 'and' | 'or'), + rules: new FormArray([] as Array), + }) as GroupFormGroup; + } + + addGroup(group: GroupFormGroup) { + const rules = group.get('rules') as FormArray; + rules.push(this.createGroup()); + } + + addRule(group: GroupFormGroup) { + const rules = group.get('rules') as FormArray; + rules.push(this.createRule()); + } + + deleteGroup(group: GroupFormGroup) { + const parent = group.parent; + if (parent && parent instanceof FormArray) { + const index = parent.controls.indexOf(group); + if (index > -1) { + parent.removeAt(index); + } + } + } + + removeRule(group: GroupFormGroup, index: number) { + const rules = group.get('rules') as FormArray; + rules.removeAt(index); + } + + isGroup(control: AbstractControl): boolean { + return control instanceof FormGroup && control.get('rules') instanceof FormArray; + } + + onOperatorChange(ruleCtrl: FormGroup) { + const operator = ruleCtrl.get('operator')?.value as RuleOperator; + + const valueCtrl = ruleCtrl.get('value'); + const valueStartCtrl = ruleCtrl.get('valueStart'); + const valueEndCtrl = ruleCtrl.get('valueEnd'); + + if (MULTI_VALUE_OPERATORS.includes(operator)) { + valueCtrl?.setValue([]); + valueStartCtrl?.setValue(null); + valueEndCtrl?.setValue(null); + } else if (EMPTY_CHECK_OPERATORS.includes(operator)) { + valueCtrl?.setValue(null); + valueStartCtrl?.setValue(null); + valueEndCtrl?.setValue(null); + } else { + valueCtrl?.setValue(''); + valueStartCtrl?.setValue(null); + valueEndCtrl?.setValue(null); + } + } + + onFieldChange(ruleCtrl: RuleFormGroup) { + ruleCtrl.get('operator')?.setValue(''); + ruleCtrl.get('value')?.setValue(null); + ruleCtrl.get('valueStart')?.setValue(null); + ruleCtrl.get('valueEnd')?.setValue(null); + } + + openIconPicker() { + const isMobile = window.innerWidth <= 768; + const ref: DynamicDialogRef = this.dialogService.open(IconPickerV2Component, { + header: 'Choose an Icon', + style: { + position: 'absolute', + top: '10%', + bottom: '10%', + width: isMobile ? '90vw' : '800px', + maxWidth: isMobile ? '90vw' : '800px', + minWidth: isMobile ? '90vw' : '800px', + }, + dismissableMask: true, + }); + + ref.onClose.subscribe((icon: string) => { + if (icon) { + this.form.get('icon')?.setValue(icon); + } + }); + } + + private hasAtLeastOneValidRule(group: GroupFormGroup): boolean { + const rulesArray = group.get('rules') as FormArray; + + return rulesArray.controls.some(ctrl => { + const type = (ctrl.get('type') as FormControl<'group'> | null)?.value; + + if (type === 'group') { + return this.hasAtLeastOneValidRule(ctrl as GroupFormGroup); + } else { + const field = ctrl.get('field')?.value; + const operator = ctrl.get('operator')?.value; + return !!field && !!operator; + } + }); + } + + submit() { + if (!this.hasAtLeastOneValidRule(this.group)) { + this.messageService.add({severity: 'warn', summary: 'Validation Error', detail: 'You must add at least one valid rule before saving.'}); + return; + } + + const value = this.form.value as { name: string | null; icon: string | null; group: GroupRule }; + const cleanedGroup = removeNulls(serializeDateRules(value.group)); + + this.magicShelfService.saveShelf({ + id: this.shelfId ?? undefined, + name: value.name, + icon: value.icon, + group: cleanedGroup + }).subscribe({ + next: (savedShelf) => { + this.messageService.add({severity: 'success', summary: 'Success', detail: 'Magic shelf saved successfully.'}); + if (savedShelf?.id) { + this.shelfId = savedShelf.id; + } + }, + error: (err) => { + this.messageService.add({ + severity: 'error', + summary: 'Error', + detail: err?.error?.message || 'Failed to save magic shelf.' + }); + } + }); + } +} diff --git a/booklore-ui/src/app/magic-shelf-service.ts b/booklore-ui/src/app/magic-shelf-service.ts new file mode 100644 index 000000000..0c5dfec0a --- /dev/null +++ b/booklore-ui/src/app/magic-shelf-service.ts @@ -0,0 +1,139 @@ +import {inject, Injectable} from '@angular/core'; +import {API_CONFIG} from './config/api-config'; +import {HttpClient} from '@angular/common/http'; +import {BehaviorSubject, Observable, of} from 'rxjs'; +import {catchError, map, switchMap, tap} from 'rxjs/operators'; +import {BookService} from './book/service/book.service'; +import {GroupRule} from './magic-shelf-component/magic-shelf-component'; +import {BookRuleEvaluatorService} from './book-rule-evaluator.service'; + +export interface MagicShelf { + id?: number | null; + name: string; + icon?: string; + filterJson: string; +} + +export interface MagicShelfState { + shelves: MagicShelf[]; + loaded: boolean; + error: string | null; +} + +@Injectable({ + providedIn: 'root', +}) +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 shelvesStateSubject = new BehaviorSubject({ + shelves: [], + loaded: false, + error: null, + }); + public readonly shelvesState$ = this.shelvesStateSubject.asObservable(); + + constructor() { + this.loadUserShelves().subscribe(); + } + + private get state(): MagicShelfState { + return this.shelvesStateSubject.value; + } + + loadUserShelves(): Observable { + return this.http.get(this.url).pipe( + tap((shelves) => this.updateShelves(shelves)), + catchError((error) => { + this.updateError(error.message); + return of([]); + }) + ); + } + + saveShelf(data: { id?: number; name: string | null; icon: string | null; group: any }): Observable { + const payload: MagicShelf = { + id: data.id, + name: data.name ?? '', + icon: data.icon ?? 'pi pi-book', + filterJson: JSON.stringify(data.group), + }; + + return this.http.post(this.url, payload).pipe( + tap((newShelf) => { + const shelves = this.state.shelves; + const updated = shelves.some((s) => s.id === newShelf.id) + ? shelves.map((s) => (s.id === newShelf.id ? newShelf : s)) + : [...shelves, newShelf]; + + this.updateShelves(updated); + }), + catchError((error) => { + this.updateError(error.message); + throw error; + }) + ); + } + + getShelf(id: number): Observable { + return this.shelvesState$.pipe( + map(state => state.shelves.find(shelf => shelf.id === id)) + ); + } + + deleteShelf(id: number): Observable { + return this.http.delete(`${this.url}/${id}`).pipe( + tap(() => { + const updated = this.state.shelves.filter((s) => s.id !== id); + this.updateShelves(updated); + }), + catchError((error) => { + this.updateError(error.message); + throw error; + }) + ); + } + + private updateShelves(shelves: MagicShelf[]): void { + this.shelvesStateSubject.next({ + shelves, + loaded: true, + error: null, + }); + } + + private updateError(error: string): void { + this.shelvesStateSubject.next({ + ...this.state, + error, + loaded: true, + }); + } + + getBookCount(shelfId: number): Observable { + return this.getShelf(shelfId).pipe( + switchMap((shelf) => { + if (!shelf) return of(0); + let group: GroupRule; + try { + group = JSON.parse(shelf.filterJson); + } catch (e) { + console.error('Invalid filter JSON', e); + return of(0); + } + + return this.bookService.bookState$.pipe( + map((state) => + (state.books ?? []).filter((book) => + this.ruleEvaluatorService.evaluateGroup(book, group) + ).length + ) + ); + }) + ); + } +} diff --git a/booklore-ui/src/app/magic-shelf-utils.ts b/booklore-ui/src/app/magic-shelf-utils.ts new file mode 100644 index 000000000..f0402b642 --- /dev/null +++ b/booklore-ui/src/app/magic-shelf-utils.ts @@ -0,0 +1,61 @@ +// magic-shelf-utils.ts + +import {RuleOperator} from './magic-shelf-component/magic-shelf-component'; + +export const MULTI_VALUE_OPERATORS: RuleOperator[] = [ + 'includes_any', + 'includes_all', + 'excludes_all' +]; + +export const EMPTY_CHECK_OPERATORS: RuleOperator[] = [ + 'is_empty', + 'is_not_empty' +]; + +export function parseValue(val: any, type: 'string' | 'number' | 'decimal' | 'date' | undefined): any { + if (val == null) return null; + if (type === 'number' || type === 'decimal') { + const num = Number(val); + return isNaN(num) ? null : num; + } + if (type === 'date') { + const d = new Date(val); + return isNaN(d.getTime()) ? null : d; + } + return val; +} + +export function removeNulls(obj: any): any { + if (Array.isArray(obj)) { + return obj.map(removeNulls); + } else if (typeof obj === 'object' && obj !== null) { + return Object.entries(obj).reduce((acc, [key, value]) => { + const cleanedValue = removeNulls(value); + if (cleanedValue !== null && cleanedValue !== undefined) { + acc[key] = cleanedValue; + } + return acc; + }, {} as any); + } + return obj; +} + +export function serializeDateRules(ruleOrGroup: any): any { + if ('rules' in ruleOrGroup) { + return { + ...ruleOrGroup, + rules: ruleOrGroup.rules.map(serializeDateRules) + }; + } + + const isDateField = ruleOrGroup.field === 'publishedDate'; + const serialize = (val: any) => (val instanceof Date ? val.toISOString().split('T')[0] : val); + + return { + ...ruleOrGroup, + value: isDateField ? serialize(ruleOrGroup.value) : ruleOrGroup.value, + valueStart: isDateField ? serialize(ruleOrGroup.valueStart) : ruleOrGroup.valueStart, + valueEnd: isDateField ? serialize(ruleOrGroup.valueEnd) : ruleOrGroup.valueEnd + }; +} diff --git a/booklore-ui/src/app/metadata/book-metadata-center-component/metadata-viewer/metadata-viewer.component.html b/booklore-ui/src/app/metadata/book-metadata-center-component/metadata-viewer/metadata-viewer.component.html index db37d7185..ebf1c8a81 100644 --- a/booklore-ui/src/app/metadata/book-metadata-center-component/metadata-viewer/metadata-viewer.component.html +++ b/booklore-ui/src/app/metadata/book-metadata-center-component/metadata-viewer/metadata-viewer.component.html @@ -260,7 +260,7 @@ - {{ (book?.metadataMatchScore! * 100) | number:'1.0-0' }}% + {{ (book?.metadataMatchScore!) | number:'1.0-0' }}% } @else { - diff --git a/booklore-ui/src/app/settings/global-preferences/metadata-match-weights-component/metadata-match-weights-component.html b/booklore-ui/src/app/settings/global-preferences/metadata-match-weights-component/metadata-match-weights-component.html index 3e24ee32c..106f497c3 100644 --- a/booklore-ui/src/app/settings/global-preferences/metadata-match-weights-component/metadata-match-weights-component.html +++ b/booklore-ui/src/app/settings/global-preferences/metadata-match-weights-component/metadata-match-weights-component.html @@ -40,12 +40,12 @@ -
} diff --git a/booklore-ui/src/app/settings/global-preferences/metadata-match-weights-component/metadata-match-weights-component.ts b/booklore-ui/src/app/settings/global-preferences/metadata-match-weights-component/metadata-match-weights-component.ts index d53a9a540..5d41f5f6b 100644 --- a/booklore-ui/src/app/settings/global-preferences/metadata-match-weights-component/metadata-match-weights-component.ts +++ b/booklore-ui/src/app/settings/global-preferences/metadata-match-weights-component/metadata-match-weights-component.ts @@ -3,12 +3,12 @@ import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/ import {MessageService} from 'primeng/api'; import {MetadataMatchWeightsService} from '../../../utilities/service/metadata-match-weights-service'; import {Button} from 'primeng/button'; -import {InputText} from 'primeng/inputtext'; import {Tooltip} from 'primeng/tooltip'; import {filter, take} from 'rxjs/operators'; import {Observable} from 'rxjs'; import {AppSettingKey, AppSettings} from '../../../core/model/app-settings.model'; import {AppSettingsService} from '../../../core/service/app-settings.service'; +import {InputNumber} from 'primeng/inputnumber'; @Component({ @@ -16,8 +16,8 @@ import {AppSettingsService} from '../../../core/service/app-settings.service'; imports: [ ReactiveFormsModule, Button, - InputText, - Tooltip + Tooltip, + InputNumber ], templateUrl: './metadata-match-weights-component.html', styleUrl: './metadata-match-weights-component.scss' diff --git a/booklore-ui/src/app/sql-filter-builder.ts b/booklore-ui/src/app/sql-filter-builder.ts new file mode 100644 index 000000000..ab8d875f2 --- /dev/null +++ b/booklore-ui/src/app/sql-filter-builder.ts @@ -0,0 +1,112 @@ +import {AbstractControl, FormArray} from '@angular/forms'; + +export class SqlFilterBuilder { + static toSQL(group: AbstractControl): string { + const condition: 'and' | 'or' = group.get('join')?.value ?? 'and'; + const rules = group.get('rules') as FormArray; + + const parts: string[] = []; + + rules.controls.forEach((ctrl: AbstractControl) => { + if (this.isGroup(ctrl)) { + parts.push(`(${this.toSQL(ctrl)})`); + return; + } + + const field = ctrl.get('field')?.value; + const operator = ctrl.get('operator')?.value; + const value = ctrl.get('value')?.value; + const valueStart = ctrl.get('valueStart')?.value; + const valueEnd = ctrl.get('valueEnd')?.value; + + if (!field || !operator) return; + + if (operator === 'in_between') { + parts.push(`${field} BETWEEN ${this.formatSQLValue(valueStart)} AND ${this.formatSQLValue(valueEnd)}`); + return; + } + + if (field === 'library') { + parts.push(`${field} = ${value}`); + return; + } + + let sqlOperator = ''; + let sqlValue = ''; + + switch (operator) { + case 'equals': + sqlOperator = '='; + sqlValue = this.formatSQLValue(value); + break; + case 'not_equals': + sqlOperator = '!='; + sqlValue = this.formatSQLValue(value); + break; + case 'contains': + sqlOperator = 'LIKE'; + sqlValue = `'%${String(value).replace(/'/g, "''")}%'`; + break; + case 'starts_with': + sqlOperator = 'LIKE'; + sqlValue = `'${String(value).replace(/'/g, "''")}%'`; + break; + case 'ends_with': + sqlOperator = 'LIKE'; + sqlValue = `'%${String(value).replace(/'/g, "''")}'`; + break; + case 'greater_than': + sqlOperator = '>'; + sqlValue = this.formatSQLValue(value); + break; + case 'less_than': + sqlOperator = '<'; + sqlValue = this.formatSQLValue(value); + break; + case 'is_empty': + parts.push(`(${field} IS NULL OR ${field} = '')`); + return; + case 'is_not_empty': + parts.push(`(${field} IS NOT NULL AND ${field} != '')`); + return; + case 'in_list': + sqlOperator = 'IN'; + sqlValue = `(${(value as string)?.split(',').map(v => this.formatSQLValue(v.trim())).join(', ')})`; + break; + case 'not_in_list': + sqlOperator = 'NOT IN'; + sqlValue = `(${(value as string)?.split(',').map(v => this.formatSQLValue(v.trim())).join(', ')})`; + break; + default: + return; + } + + parts.push(`${field} ${sqlOperator} ${sqlValue}`); + }); + + return parts.join(` ${condition.toUpperCase()} `); + } + + private static isGroup(ctrl: AbstractControl): boolean { + return ctrl.get('rules') instanceof FormArray; + } + + private static formatSQLValue(val: any): string { + if (val == null || val === '') return 'NULL'; + + // Handle boolean + if (typeof val === 'boolean') return val ? 'true' : 'false'; + + // Handle numeric + if (!isNaN(val) && typeof val !== 'object') return String(val); + + // Handle dates + const date = new Date(val); + if (!isNaN(date.getTime())) { + return `'${date.toISOString().slice(0, 10)}'`; + } + + // Handle strings (with escaped single quotes) + return `'${String(val).replace(/'/g, "''")}'`; + } +} diff --git a/booklore-ui/src/assets/layout/styles/layout/_menu.scss b/booklore-ui/src/assets/layout/styles/layout/_menu.scss index c5e905284..fdddd1130 100644 --- a/booklore-ui/src/assets/layout/styles/layout/_menu.scss +++ b/booklore-ui/src/assets/layout/styles/layout/_menu.scss @@ -76,7 +76,7 @@ outline: 0 none; color: var(--text-color); cursor: pointer; - padding: 0.75rem 0.5rem 0.75rem 1rem; + padding: 0.6rem 0.4rem 0.6rem 0.75rem; border-radius: variables.$borderRadius; transition: background-color variables.$transitionDuration, box-shadow variables.$transitionDuration; diff --git a/booklore-ui/src/styles.scss b/booklore-ui/src/styles.scss index 41fe97a70..9004bf1a6 100644 --- a/booklore-ui/src/styles.scss +++ b/booklore-ui/src/styles.scss @@ -15,3 +15,15 @@ html { .p-toast { top: 4rem !important; } + +.p-inputchips { + width: 100% !important; +} + +.p-inputchips .p-inputchips-input { + width: 100% !important; +} + +.p-inputchips input.p-inputtext { + width: 100% !important; +}