diff --git a/booklore-api/src/main/java/org/booklore/service/BookRuleEvaluatorService.java b/booklore-api/src/main/java/org/booklore/service/BookRuleEvaluatorService.java index 431214e6e..de031f76a 100644 --- a/booklore-api/src/main/java/org/booklore/service/BookRuleEvaluatorService.java +++ b/booklore-api/src/main/java/org/booklore/service/BookRuleEvaluatorService.java @@ -139,8 +139,8 @@ public class BookRuleEvaluatorService { if (threshold == null) return cb.conjunction(); if (rule.getField() == RuleField.PUBLISHED_DATE) { - LocalDateTime ldt = threshold.atZone(ZoneId.systemDefault()).toLocalDateTime(); - return cb.greaterThanOrEqualTo(field.as(LocalDateTime.class), ldt); + LocalDate ld = threshold.atZone(ZoneId.systemDefault()).toLocalDate(); + return cb.greaterThanOrEqualTo(field.as(LocalDate.class), ld); } return cb.greaterThanOrEqualTo(field.as(Instant.class), threshold); } @@ -153,8 +153,8 @@ public class BookRuleEvaluatorService { if (threshold == null) return cb.conjunction(); if (rule.getField() == RuleField.PUBLISHED_DATE) { - LocalDateTime ldt = threshold.atZone(ZoneId.systemDefault()).toLocalDateTime(); - return cb.lessThan(field.as(LocalDateTime.class), ldt); + LocalDate ld = threshold.atZone(ZoneId.systemDefault()).toLocalDate(); + return cb.lessThan(field.as(LocalDate.class), ld); } return cb.lessThan(field.as(Instant.class), threshold); } @@ -174,8 +174,7 @@ public class BookRuleEvaluatorService { Instant startInstant = start.atStartOfDay(ZoneId.systemDefault()).toInstant(); if (rule.getField() == RuleField.PUBLISHED_DATE) { - LocalDateTime ldt = startInstant.atZone(ZoneId.systemDefault()).toLocalDateTime(); - return cb.greaterThanOrEqualTo(field.as(LocalDateTime.class), ldt); + return cb.greaterThanOrEqualTo(field.as(LocalDate.class), start); } return cb.greaterThanOrEqualTo(field.as(Instant.class), startInstant); } @@ -529,6 +528,8 @@ public class BookRuleEvaluatorService { if (value instanceof Boolean) { return cb.equal(field, value); + } else if (value instanceof LocalDate) { + return cb.equal(field, value); } else if (value instanceof LocalDateTime) { return cb.equal(field, value); } else if (rule.getField() == RuleField.READ_STATUS) { @@ -593,38 +594,46 @@ public class BookRuleEvaluatorService { private Predicate buildGreaterThan(Rule rule, CriteriaBuilder cb, Root root, Join progressJoin) { return buildComparisonPredicate(rule, cb, root, progressJoin, (field, dateValue) -> cb.greaterThan(field.as(LocalDateTime.class), dateValue), + (field, localDateValue) -> cb.greaterThan(field.as(LocalDate.class), localDateValue), (field, numValue) -> cb.gt(toNumericExpression(field), numValue)); } private Predicate buildGreaterThanEqual(Rule rule, CriteriaBuilder cb, Root root, Join progressJoin) { return buildComparisonPredicate(rule, cb, root, progressJoin, (field, dateValue) -> cb.greaterThanOrEqualTo(field.as(LocalDateTime.class), dateValue), + (field, localDateValue) -> cb.greaterThanOrEqualTo(field.as(LocalDate.class), localDateValue), (field, numValue) -> cb.ge(toNumericExpression(field), numValue)); } private Predicate buildLessThan(Rule rule, CriteriaBuilder cb, Root root, Join progressJoin) { return buildComparisonPredicate(rule, cb, root, progressJoin, (field, dateValue) -> cb.lessThan(field.as(LocalDateTime.class), dateValue), + (field, localDateValue) -> cb.lessThan(field.as(LocalDate.class), localDateValue), (field, numValue) -> cb.lt(toNumericExpression(field), numValue)); } private Predicate buildLessThanEqual(Rule rule, CriteriaBuilder cb, Root root, Join progressJoin) { return buildComparisonPredicate(rule, cb, root, progressJoin, (field, dateValue) -> cb.lessThanOrEqualTo(field.as(LocalDateTime.class), dateValue), + (field, localDateValue) -> cb.lessThanOrEqualTo(field.as(LocalDate.class), localDateValue), (field, numValue) -> cb.le(toNumericExpression(field), numValue)); } private Predicate buildComparisonPredicate(Rule rule, CriteriaBuilder cb, Root root, Join progressJoin, - BiFunction, LocalDateTime, Predicate> dateComparator, + BiFunction, LocalDateTime, Predicate> dateTimeComparator, + BiFunction, LocalDate, Predicate> dateComparator, BiFunction, Double, Predicate> numberComparator) { Expression field = getFieldExpression(rule.getField(), cb, root, progressJoin); if (field == null) return cb.conjunction(); Object value = normalizeValue(rule.getValue(), rule.getField()); + if (value instanceof LocalDate) { + return dateComparator.apply(field, (LocalDate) value); + } if (value instanceof LocalDateTime) { - return dateComparator.apply(field, (LocalDateTime) value); + return dateTimeComparator.apply(field, (LocalDateTime) value); } if (!(value instanceof Number)) return cb.conjunction(); return numberComparator.apply(field, ((Number) value).doubleValue()); @@ -639,6 +648,10 @@ public class BookRuleEvaluatorService { if (start == null || end == null) return cb.conjunction(); + if (start instanceof LocalDate && end instanceof LocalDate) { + return cb.between(field.as(LocalDate.class), (LocalDate) start, (LocalDate) end); + } + if (start instanceof LocalDateTime && end instanceof LocalDateTime) { return cb.between(field.as(LocalDateTime.class), (LocalDateTime) start, (LocalDateTime) end); } @@ -870,7 +883,8 @@ public class BookRuleEvaluatorService { if (value == null) return null; if (field == RuleField.PUBLISHED_DATE) { - return parseDate(value); + LocalDateTime parsed = parseDate(value); + return parsed != null ? parsed.toLocalDate() : null; } if (field == RuleField.DATE_FINISHED || field == RuleField.LAST_READ_TIME || field == RuleField.ADDED_ON) { diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-dialog-helper.service.ts b/booklore-ui/src/app/features/book/components/book-browser/book-dialog-helper.service.ts index 8b8923f7e..5399f35f3 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-dialog-helper.service.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-dialog-helper.service.ts @@ -17,6 +17,7 @@ import {Book} from '../../model/book.model'; import {AdditionalFileUploaderComponent} from '../additional-file-uploader/additional-file-uploader.component'; import {BookFileAttacherComponent} from '../book-file-attacher/book-file-attacher.component'; import {AddPhysicalBookDialogComponent} from '../add-physical-book-dialog/add-physical-book-dialog.component'; +import {BulkIsbnImportDialogComponent} from '../bulk-isbn-import-dialog/bulk-isbn-import-dialog.component'; import {DuplicateMergerComponent} from '../duplicate-merger/duplicate-merger.component'; @Injectable({providedIn: 'root'}) @@ -185,4 +186,14 @@ export class BookDialogHelperService { }, }); } + + openBulkIsbnImportDialog(libraryId?: number): DynamicDialogRef | null { + return this.openDialog(BulkIsbnImportDialogComponent, { + showHeader: false, + styleClass: `${DialogSize.LG} ${DialogStyle.MINIMAL}`, + data: { + libraryId: libraryId, + }, + }); + } } diff --git a/booklore-ui/src/app/features/book/components/bulk-isbn-import-dialog/bulk-isbn-import-dialog.component.html b/booklore-ui/src/app/features/book/components/bulk-isbn-import-dialog/bulk-isbn-import-dialog.component.html new file mode 100644 index 000000000..61630ae28 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/bulk-isbn-import-dialog/bulk-isbn-import-dialog.component.html @@ -0,0 +1,346 @@ + +
+
+
+ +
+
+

{{ t('title') }}

+

{{ t('description') }}

+
+ +
+ + + @if (phase === 'upload') { +
+
+ + +
+ +
+ + @if (entries.length === 0 && skipped.length === 0 && duplicatesRemoved === 0) { + + + {{ t('tabFile') }} + {{ t('tabPaste') }} + + + +
+ +

{{ t('fileFormatsHint') }}

+
+
+ +
+ + +
+
+
+
+ + @if (parseError === 'fileTooLarge') { +
+ + {{ t('errorFileTooLarge') }} +
+ } + @if (parseError === 'empty') { +
+ + {{ t('errorNoIsbns') }} +
+ } + } @else { +
+
+
+ + {{ t('validCount', { count: entries.length }) }} +
+ @if (skipped.length > 0) { +
+ + {{ t('skippedCount', { count: skipped.length }) }} + +
+ } + @if (duplicatesRemoved > 0) { +
+ + {{ t('duplicatesRemoved', { count: duplicatesRemoved }) }} +
+ } + @if (parseError === 'tooMany') { +
+ + {{ t('errorTooMany', { max: maxIsbnCount }) }} +
+ } +
+ + @if (showSkipped && skipped.length > 0) { +
+ @for (item of skipped; track item.value) { +
+ {{ item.value }} + {{ t('reason.' + item.reason) }} +
+ } +
+ } + +
+
+ {{ t('previewLabel') }} + +
+
+ @for (entry of entries; track entry.isbn; let i = $index) { +
+ {{ i + 1 }}. + {{ entry.isbn }} +
+ } +
+
+
+ } +
+ + + } + + + @if (phase === 'processing') { +
+
+
+ {{ t('processingLabel', { current: processedCount, total: entries.length }) }} + {{ progressPercent }}% +
+ +
+ {{ createdCount }} + + {{ failedCount }} +
+
+ +
+ @for (entry of entries; track entry.isbn) { +
+
+ @switch (entry.status) { + @case ('pending') { } + @case ('looking-up') { } + @case ('created') { } + @case ('created-no-metadata') { } + @case ('failed') { } + } +
+ {{ entry.isbn }} + + @if (entry.status === 'created' && entry.title) { + {{ entry.title }} + } @else if (entry.status === 'created-no-metadata') { + {{ t('createdNoMetadata') }} + } @else if (entry.status === 'failed') { + {{ entry.error || t('unknownError') }} + } @else if (entry.status === 'looking-up') { + {{ t('lookingUp') }} + } + +
+ } +
+
+ + + } + + + @if (phase === 'summary') { +
+
+ {{ t('summaryTitle') }} + @if (selectedLibraryName) { + + + {{ selectedLibraryName }} + + } +
+ +
+
+ +
+ {{ createdCount }} + {{ t('summaryCreated') }} +
+
+ @if (noMetadataCount > 0) { +
+ +
+ {{ noMetadataCount }} + {{ t('summaryNoMetadata') }} +
+
+ } + @if (failedCount > 0) { +
+ +
+ {{ failedCount }} + {{ t('summaryFailed') }} +
+
+ } + @if (cancelled) { +
+ +
+ {{ entries.length - processedCount }} + {{ t('summaryCancelled') }} +
+
+ } +
+ +
+ @for (entry of entries; track entry.isbn) { + @if (entry.status !== 'pending') { +
+
+ @switch (entry.status) { + @case ('created') { } + @case ('created-no-metadata') { } + @case ('failed') { } + } +
+ {{ entry.isbn }} + + @if (entry.status === 'created' && entry.title) { + {{ entry.title }} + } @else if (entry.status === 'created-no-metadata') { + {{ t('createdNoMetadata') }} + } @else if (entry.status === 'failed') { + {{ entry.error || t('unknownError') }} + } + +
+ } + } +
+
+ + + } +
+
diff --git a/booklore-ui/src/app/features/book/components/bulk-isbn-import-dialog/bulk-isbn-import-dialog.component.scss b/booklore-ui/src/app/features/book/components/bulk-isbn-import-dialog/bulk-isbn-import-dialog.component.scss new file mode 100644 index 000000000..f68ef1e4f --- /dev/null +++ b/booklore-ui/src/app/features/book/components/bulk-isbn-import-dialog/bulk-isbn-import-dialog.component.scss @@ -0,0 +1,514 @@ +@use '../../../../shared/styles/panel-shared' as panel; + +.bulk-isbn-import { + display: flex; + flex-direction: column; + min-width: 600px; + max-height: 90vh; + + @media (max-width: 768px) { + min-width: auto; + width: 100%; + } +} + +.panel-header { + @include panel.panel-header; +} + +.form-container { + display: flex; + flex-direction: column; + gap: 0.75rem; + padding: 1.25rem; + background: var(--card-background); + border: 1px solid var(--border-color); + border-top: none; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08); + overflow-y: auto; + max-height: calc(90vh - 200px); + + @media (max-width: 480px) { + padding: 0.75rem; + gap: 0.5rem; + } +} + +.form-group { + display: flex; + flex-direction: column; + gap: 0.25rem; + + &.highlight-group { + padding: 0.5rem; + } +} + +.form-label { + display: flex; + align-items: center; + gap: 0.375rem; + font-size: 0.9rem; + font-weight: 600; + color: var(--text-color); + + .label-icon { + color: var(--primary-color); + } + + .required-indicator { + color: var(--p-red-500); + margin-left: 0.125rem; + } +} + +.input-full { + width: 100%; + box-sizing: border-box; +} + +.gradient-divider { + height: 1px; + background: linear-gradient(to right, transparent, var(--border-color), transparent); + margin: 0.25rem 0; +} + +// Upload section +.upload-section { + display: flex; + flex-direction: column; + align-items: center; + gap: 0.75rem; + padding: 1.5rem; + + .upload-hint { + font-size: 0.8rem; + color: var(--text-secondary-color); + margin: 0; + text-align: center; + } +} + +.paste-section { + display: flex; + flex-direction: column; + gap: 0.75rem; + padding: 0.75rem 0; + + p-button { + align-self: flex-end; + } +} + +.parse-error { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.75rem 1rem; + background: rgba(239, 68, 68, 0.1); + border: 1px solid rgba(239, 68, 68, 0.3); + border-radius: 6px; + color: var(--p-red-500); + font-size: 0.875rem; +} + +// Parse results +.parse-results { + display: flex; + flex-direction: column; + gap: 0.75rem; +} + +.parse-summary { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; +} + +.summary-stat { + display: flex; + align-items: center; + gap: 0.375rem; + padding: 0.375rem 0.75rem; + border-radius: 6px; + font-size: 0.85rem; + font-weight: 500; + + &.success { + background: rgba(34, 197, 94, 0.1); + color: var(--p-green-500); + border: 1px solid rgba(34, 197, 94, 0.3); + } + + &.warn { + background: rgba(234, 179, 8, 0.1); + color: var(--p-yellow-500); + border: 1px solid rgba(234, 179, 8, 0.3); + cursor: pointer; + } + + &.info { + background: rgba(59, 130, 246, 0.1); + color: var(--p-blue-500); + border: 1px solid rgba(59, 130, 246, 0.3); + } +} + +.skipped-list { + display: flex; + flex-direction: column; + gap: 0.25rem; + padding: 0.5rem; + background: rgba(234, 179, 8, 0.05); + border: 1px solid rgba(234, 179, 8, 0.2); + border-radius: 6px; + max-height: 150px; + overflow-y: auto; +} + +.skipped-item { + display: flex; + align-items: center; + gap: 0.5rem; + font-size: 0.8rem; + + code { + color: var(--text-color); + background: var(--ground-background); + padding: 0.125rem 0.375rem; + border-radius: 3px; + } + + .skipped-reason { + color: var(--text-secondary-color); + font-style: italic; + } +} + +.isbn-preview { + display: flex; + flex-direction: column; + gap: 0.5rem; +} + +.preview-header { + display: flex; + justify-content: space-between; + align-items: center; + + .preview-label { + font-size: 0.875rem; + font-weight: 600; + color: var(--text-color); + } +} + +.preview-list { + display: flex; + flex-direction: column; + gap: 0.25rem; + max-height: 200px; + overflow-y: auto; + padding: 0.5rem; + background: var(--ground-background); + border: 1px solid var(--border-color); + border-radius: 6px; +} + +.preview-item { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.25rem 0.375rem; + font-size: 0.85rem; + + .preview-index { + color: var(--text-secondary-color); + min-width: 2rem; + text-align: right; + } + + .preview-isbn { + color: var(--text-color); + } +} + +// Processing phase +.processing-container { + max-height: calc(90vh - 180px); +} + +.progress-section { + display: flex; + flex-direction: column; + gap: 0.5rem; + padding: 0.5rem 0; +} + +.progress-header { + display: flex; + justify-content: space-between; + align-items: center; + + .progress-label { + font-size: 0.9rem; + font-weight: 500; + color: var(--text-color); + } + + .progress-percent { + font-size: 0.9rem; + font-weight: 600; + color: var(--primary-color); + } +} + +.progress-stats { + display: flex; + gap: 1rem; + font-size: 0.85rem; + + .stat-created { + color: var(--p-green-500); + } + + .stat-no-metadata { + color: var(--p-yellow-500); + } + + .stat-failed { + color: var(--p-red-500); + } + + i { + margin-right: 0.25rem; + } +} + +.isbn-progress-list { + display: flex; + flex-direction: column; + gap: 0.25rem; +} + +.progress-item { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.375rem 0.5rem; + border-radius: 4px; + font-size: 0.85rem; + transition: background-color 0.2s; + + &.status-pending { + opacity: 0.5; + } + + &.status-looking-up { + background: rgba(59, 130, 246, 0.05); + } + + &.status-created { + background: rgba(34, 197, 94, 0.05); + } + + &.status-created-no-metadata { + background: rgba(234, 179, 8, 0.05); + } + + &.status-failed { + background: rgba(239, 68, 68, 0.05); + } +} + +.progress-item-icon { + width: 1.25rem; + text-align: center; + flex-shrink: 0; + + .status-pending & { color: var(--text-secondary-color); } + .status-looking-up & { color: var(--p-blue-500); } + .status-created & { color: var(--p-green-500); } + .status-created-no-metadata & { color: var(--p-yellow-500); } + .status-failed & { color: var(--p-red-500); } +} + +.progress-item-isbn { + min-width: 8rem; + flex-shrink: 0; + color: var(--text-color); +} + +.progress-item-detail { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--text-secondary-color); + font-size: 0.8rem; +} + +// Summary phase +.summary-header-bar { + display: flex; + justify-content: space-between; + align-items: center; + padding: 0.25rem 0; + + .summary-title { + font-size: 1rem; + font-weight: 600; + color: var(--text-color); + } + + .summary-library { + display: flex; + align-items: center; + gap: 0.375rem; + font-size: 0.85rem; + color: var(--text-secondary-color); + + i { + color: var(--primary-color); + } + } +} + +.summary-results { + display: flex; + flex-wrap: wrap; + gap: 0.75rem; + padding: 0.25rem 0; +} + +.summary-card { + display: flex; + align-items: center; + gap: 0.75rem; + padding: 0.75rem 1rem; + border-radius: 8px; + flex: 1; + min-width: 120px; + + > i { + font-size: 1.25rem; + } + + &.success { + background: rgba(34, 197, 94, 0.1); + border: 1px solid rgba(34, 197, 94, 0.3); + > i { color: var(--p-green-500); } + } + + &.warn { + background: rgba(234, 179, 8, 0.1); + border: 1px solid rgba(234, 179, 8, 0.3); + > i { color: var(--p-yellow-500); } + } + + &.error { + background: rgba(239, 68, 68, 0.1); + border: 1px solid rgba(239, 68, 68, 0.3); + > i { color: var(--p-red-500); } + } + + &.info { + background: rgba(59, 130, 246, 0.1); + border: 1px solid rgba(59, 130, 246, 0.3); + > i { color: var(--p-blue-500); } + } +} + +.summary-card-content { + display: flex; + flex-direction: column; + + .summary-card-count { + font-size: 1.25rem; + font-weight: 700; + color: var(--text-color); + } + + .summary-card-label { + font-size: 0.75rem; + color: var(--text-secondary-color); + } +} + +.summary-detail-list { + display: flex; + flex-direction: column; + gap: 0.125rem; + margin-top: 0.25rem; +} + +.summary-detail-item { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.375rem 0.5rem; + border-radius: 4px; + font-size: 0.85rem; + + &.status-created { + background: rgba(34, 197, 94, 0.04); + } + + &.status-created-no-metadata { + background: rgba(234, 179, 8, 0.04); + } + + &.status-failed { + background: rgba(239, 68, 68, 0.04); + } +} + +.summary-detail-icon { + width: 1.25rem; + text-align: center; + flex-shrink: 0; + + .status-created & { color: var(--p-green-500); } + .status-created-no-metadata & { color: var(--p-yellow-500); } + .status-failed & { color: var(--p-red-500); } +} + +.summary-detail-isbn { + min-width: 8rem; + flex-shrink: 0; + color: var(--text-color); + font-size: 0.8rem; +} + +.summary-detail-info { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: 0.8rem; + + .status-created & { color: var(--text-color); } + .status-created-no-metadata & { color: var(--p-yellow-500); font-style: italic; } + .status-failed & { color: var(--p-red-500); font-style: italic; } +} + +.validation-message { + @include panel.validation-message; + + &.info { + background: rgba(59, 130, 246, 0.1); + color: var(--p-blue-500); + border: 1px solid rgba(59, 130, 246, 0.3); + + i { + color: var(--p-blue-500); + } + } +} + +.dialog-footer { + @include panel.dialog-footer; + border-top: none; +} diff --git a/booklore-ui/src/app/features/book/components/bulk-isbn-import-dialog/bulk-isbn-import-dialog.component.ts b/booklore-ui/src/app/features/book/components/bulk-isbn-import-dialog/bulk-isbn-import-dialog.component.ts new file mode 100644 index 000000000..6553daffe --- /dev/null +++ b/booklore-ui/src/app/features/book/components/bulk-isbn-import-dialog/bulk-isbn-import-dialog.component.ts @@ -0,0 +1,368 @@ +import {Component, DestroyRef, inject, OnInit} from '@angular/core'; +import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; +import {FormsModule} from '@angular/forms'; +import {Button} from 'primeng/button'; +import {Select} from 'primeng/select'; +import {Textarea} from 'primeng/textarea'; +import {Tooltip} from 'primeng/tooltip'; +import {ProgressBar} from 'primeng/progressbar'; +import {FileUpload, FileSelectEvent} from 'primeng/fileupload'; +import {BookService} from '../../service/book.service'; +import {BookMetadataService} from '../../service/book-metadata.service'; +import {LibraryService} from '../../service/library.service'; +import {Library} from '../../model/library.model'; +import {Book, CreatePhysicalBookRequest} from '../../model/book.model'; +import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; +import {TranslocoDirective} from '@jsverse/transloco'; +import {Tabs, TabList, Tab, TabPanels, TabPanel} from 'primeng/tabs'; + +const MAX_ISBN_COUNT = 500; +const MAX_FILE_SIZE_BYTES = 1_048_576; // 1 MB +const DELAY_BETWEEN_REQUESTS_MS = 300; +const RETRY_DELAY_MS = 2000; + +export type IsbnEntryStatus = 'pending' | 'looking-up' | 'created' | 'created-no-metadata' | 'failed'; + +export interface IsbnEntry { + isbn: string; + status: IsbnEntryStatus; + title?: string; + error?: string; +} + +export interface SkippedEntry { + value: string; + reason: string; +} + +type ImportPhase = 'upload' | 'processing' | 'summary'; + +@Component({ + selector: 'app-bulk-isbn-import-dialog', + standalone: true, + templateUrl: './bulk-isbn-import-dialog.component.html', + imports: [ + FormsModule, + Button, + Select, + Textarea, + Tooltip, + ProgressBar, + FileUpload, + TranslocoDirective, + Tabs, + TabList, + Tab, + TabPanels, + TabPanel, + ], + styleUrl: './bulk-isbn-import-dialog.component.scss', +}) +export class BulkIsbnImportDialogComponent implements OnInit { + private dynamicDialogRef = inject(DynamicDialogRef); + private dialogConfig = inject(DynamicDialogConfig); + private bookService = inject(BookService); + private bookMetadataService = inject(BookMetadataService); + private libraryService = inject(LibraryService); + private destroyRef = inject(DestroyRef); + + libraries: Library[] = []; + selectedLibraryId: number | null = null; + + phase: ImportPhase = 'upload'; + pasteText = ''; + entries: IsbnEntry[] = []; + skipped: SkippedEntry[] = []; + duplicatesRemoved = 0; + showSkipped = false; + + processedCount = 0; + createdCount = 0; + noMetadataCount = 0; + failedCount = 0; + cancelled = false; + + parseError = ''; + readonly maxIsbnCount = MAX_ISBN_COUNT; + + ngOnInit(): void { + this.libraryService.libraryState$ + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(state => { + if (state.loaded && state.libraries) { + this.libraries = state.libraries; + if (this.dialogConfig.data?.libraryId) { + this.selectedLibraryId = this.dialogConfig.data.libraryId; + } else if (this.libraries.length > 0 && this.libraries[0].id !== undefined) { + this.selectedLibraryId = this.libraries[0].id; + } + } + }); + } + + onFileSelect(event: FileSelectEvent): void { + const file = event.files?.[0]; + if (!file) return; + + if (file.size > MAX_FILE_SIZE_BYTES) { + this.parseError = 'fileTooLarge'; + return; + } + + const reader = new FileReader(); + reader.onload = () => { + const content = reader.result as string; + this.parseContent(content, file.name); + }; + reader.readAsText(file, 'UTF-8'); + } + + parsePastedText(): void { + if (!this.pasteText.trim()) return; + this.parseContent(this.pasteText, 'paste'); + } + + clearParsed(): void { + this.entries = []; + this.skipped = []; + this.duplicatesRemoved = 0; + this.parseError = ''; + this.pasteText = ''; + } + + canStartImport(): boolean { + return this.phase === 'upload' && this.entries.length > 0 && !!this.selectedLibraryId; + } + + async startImport(): Promise { + if (!this.canStartImport()) return; + + this.phase = 'processing'; + this.processedCount = 0; + this.createdCount = 0; + this.noMetadataCount = 0; + this.failedCount = 0; + this.cancelled = false; + + for (const entry of this.entries) { + if (this.cancelled) break; + + entry.status = 'looking-up'; + + try { + const metadata = await this.lookupIsbn(entry.isbn); + if (this.cancelled) break; + + const request: CreatePhysicalBookRequest = { + libraryId: this.selectedLibraryId!, + isbn: entry.isbn, + title: metadata?.title || undefined, + authors: metadata?.authors?.length ? [...metadata.authors] : undefined, + description: metadata?.description || undefined, + publisher: metadata?.publisher || undefined, + publishedDate: metadata?.publishedDate || undefined, + language: metadata?.language || undefined, + pageCount: metadata?.pageCount ?? undefined, + categories: metadata?.categories?.length ? [...metadata.categories] : undefined, + thumbnailUrl: metadata?.thumbnailUrl || undefined, + }; + + await this.createBook(request); + + if (metadata?.title) { + entry.status = 'created'; + entry.title = metadata.title; + this.createdCount++; + } else { + entry.status = 'created-no-metadata'; + this.noMetadataCount++; + } + } catch (err: any) { + entry.status = 'failed'; + entry.error = err?.message || 'Unknown error'; + this.failedCount++; + } + + this.processedCount++; + + if (!this.cancelled && entry !== this.entries[this.entries.length - 1]) { + await this.delay(DELAY_BETWEEN_REQUESTS_MS); + } + } + + this.phase = 'summary'; + } + + cancelImport(): void { + this.cancelled = true; + } + + close(): void { + this.dynamicDialogRef.close(); + } + + get progressPercent(): number { + return this.entries.length > 0 ? Math.round((this.processedCount / this.entries.length) * 100) : 0; + } + + get selectedLibraryName(): string { + return this.libraries.find(l => l.id === this.selectedLibraryId)?.name ?? ''; + } + + private parseContent(content: string, source: string): void { + this.parseError = ''; + this.skipped = []; + this.duplicatesRemoved = 0; + + // Strip BOM + const cleaned = content.replace(/^\uFEFF/, ''); + const lines = cleaned.split(/\r?\n|\r/); + + let isbns: string[]; + const extension = source.split('.').pop()?.toLowerCase(); + + if (extension === 'csv' || extension === 'tsv') { + isbns = this.parseCsvLines(lines, extension === 'tsv' ? '\t' : undefined); + } else if (source === 'paste') { + // Pasted text: split by newlines, commas, semicolons, or spaces + const tokens = cleaned.split(/[\n\r,;\s]+/); + isbns = tokens.map(t => t.trim()).filter(t => t.length > 0); + } else { + // Plain text: one per line + isbns = lines.map(l => l.trim()).filter(l => l.length > 0 && !l.startsWith('#')); + } + + const existingIsbns = this.getExistingIsbnsForLibrary(); + const validEntries: IsbnEntry[] = []; + const seen = new Set(); + + for (const raw of isbns) { + const normalized = this.normalizeIsbn(raw); + + if (!this.isValidIsbn(normalized)) { + this.skipped.push({value: raw, reason: 'invalid'}); + continue; + } + + if (seen.has(normalized)) { + this.duplicatesRemoved++; + continue; + } + + if (existingIsbns.has(normalized)) { + this.skipped.push({value: normalized, reason: 'alreadyExists'}); + continue; + } + + seen.add(normalized); + validEntries.push({isbn: normalized, status: 'pending'}); + } + + if (validEntries.length > MAX_ISBN_COUNT) { + this.parseError = 'tooMany'; + this.entries = validEntries.slice(0, MAX_ISBN_COUNT); + } else { + this.entries = validEntries; + } + + if (this.entries.length === 0 && this.skipped.length === 0) { + this.parseError = 'empty'; + } + } + + private parseCsvLines(lines: string[], delimiter?: string): string[] { + if (lines.length === 0) return []; + + // Auto-detect delimiter if not provided + if (!delimiter) { + const firstLine = lines[0]; + if (firstLine.includes('\t')) delimiter = '\t'; + else if (firstLine.includes(';')) delimiter = ';'; + else delimiter = ','; + } + + const headerFields = lines[0].split(delimiter).map(f => f.trim().replace(/^["']|["']$/g, '').toLowerCase()); + let isbnColIndex = headerFields.findIndex(h => h === 'isbn' || h === 'isbn13' || h === 'isbn10'); + + let startLine: number; + if (isbnColIndex >= 0) { + startLine = 1; // skip header + } else { + isbnColIndex = 0; // assume first column + startLine = 0; + } + + const result: string[] = []; + for (let i = startLine; i < lines.length; i++) { + const line = lines[i].trim(); + if (!line) continue; + + const fields = line.split(delimiter); + if (fields.length > isbnColIndex) { + const value = fields[isbnColIndex].trim().replace(/^["']|["']$/g, ''); + if (value) result.push(value); + } + } + return result; + } + + private getExistingIsbnsForLibrary(): Set { + const isbns = new Set(); + if (!this.selectedLibraryId) return isbns; + + const books: Book[] = this.bookService.getCurrentBookState().books ?? []; + for (const book of books) { + if (book.libraryId !== this.selectedLibraryId) continue; + const isbn13 = book.metadata?.isbn13; + const isbn10 = book.metadata?.isbn10; + if (isbn13) isbns.add(isbn13.toUpperCase()); + if (isbn10) isbns.add(isbn10.toUpperCase()); + } + return isbns; + } + + private normalizeIsbn(raw: string): string { + // Strip hyphens, spaces, surrounding whitespace; preserve trailing X + return raw.trim().replace(/[-\s]/g, '').toUpperCase(); + } + + private isValidIsbn(isbn: string): boolean { + if (/^\d{10}$/.test(isbn) || /^\d{9}X$/.test(isbn)) return true; + if (/^\d{13}$/.test(isbn) && (isbn.startsWith('978') || isbn.startsWith('979'))) return true; + return false; + } + + private lookupIsbn(isbn: string): Promise { + return new Promise((resolve, reject) => { + this.bookMetadataService.lookupByIsbn(isbn).subscribe({ + next: metadata => resolve(metadata), + error: err => { + // Retry once on potential rate limiting + if (err?.status === 429) { + setTimeout(() => { + this.bookMetadataService.lookupByIsbn(isbn).subscribe({ + next: metadata => resolve(metadata), + error: () => resolve(null), // Still create with ISBN only + }); + }, RETRY_DELAY_MS); + } else { + resolve(null); // No metadata found, still create with ISBN + } + }, + }); + }); + } + + private createBook(request: CreatePhysicalBookRequest): Promise { + return new Promise((resolve, reject) => { + this.bookService.createPhysicalBook(request).subscribe({ + next: () => resolve(), + error: err => reject(err), + }); + }); + } + + private delay(ms: number): Promise { + return new Promise(resolve => setTimeout(resolve, ms)); + } +} diff --git a/booklore-ui/src/app/features/book/service/library-shelf-menu.service.ts b/booklore-ui/src/app/features/book/service/library-shelf-menu.service.ts index 6b0eb9a62..50095d2f8 100644 --- a/booklore-ui/src/app/features/book/service/library-shelf-menu.service.ts +++ b/booklore-ui/src/app/features/book/service/library-shelf-menu.service.ts @@ -45,6 +45,13 @@ export class LibraryShelfMenuService { this.bookDialogHelperService.openAddPhysicalBookDialog(entity?.id as number); } }, + { + label: this.t.translate('book.shelfMenuService.library.bulkIsbnImport'), + icon: 'pi pi-barcode', + command: () => { + this.bookDialogHelperService.openBulkIsbnImportDialog(entity?.id as number); + } + }, { separator: true }, diff --git a/booklore-ui/src/i18n/en/book.json b/booklore-ui/src/i18n/en/book.json index 4a8890d44..188b8f4fa 100644 --- a/booklore-ui/src/i18n/en/book.json +++ b/booklore-ui/src/i18n/en/book.json @@ -262,6 +262,7 @@ "library": { "optionsLabel": "Options", "addPhysicalBook": "Add Physical Book", + "bulkIsbnImport": "Import ISBNs from File", "editLibrary": "Edit Library", "rescanLibrary": "Re-scan Library", "customFetchMetadata": "Custom Fetch Metadata", @@ -438,6 +439,49 @@ "addButton": "Add Physical Book", "fetchMetadataTooltip": "Fetch metadata by ISBN" }, + "bulkIsbnImport": { + "title": "Import ISBNs", + "description": "Import multiple physical books from a list of ISBNs", + "closeTooltip": "Close", + "libraryLabel": "Library", + "libraryPlaceholder": "Select a library", + "tabFile": "Upload File", + "tabPaste": "Paste ISBNs", + "chooseFile": "Choose File", + "fileFormatsHint": "Supported formats: .txt, .csv, .tsv (max 1 MB)", + "pastePlaceholder": "Paste ISBNs here, one per line or comma-separated...", + "parseButton": "Parse", + "errorFileTooLarge": "File exceeds the 1 MB size limit.", + "errorNoIsbns": "No ISBNs found in the input.", + "errorTooMany": "Only the first {{ max }} ISBNs will be imported. Split your file for the rest.", + "validCount": "{{ count }} valid ISBN(s)", + "skippedCount": "{{ count }} skipped", + "duplicatesRemoved": "{{ count }} duplicate(s) removed", + "reason": { + "invalid": "Invalid ISBN format", + "alreadyExists": "Already in this library" + }, + "previewLabel": "ISBNs to import", + "clearButton": "Clear", + "validationLibraryRequired": "Select a library", + "validationNoIsbns": "Upload a file or paste ISBNs to begin", + "validationReady": "Ready to import {{ count }} ISBN(s)", + "cancelButton": "Cancel", + "startImportButton": "Start Import", + "processingLabel": "Processing {{ current }} of {{ total }}", + "lookingUp": "Looking up metadata...", + "createdNoMetadata": "Created (no metadata found)", + "unknownError": "Unknown error", + "processingHint": "Books already created will be kept if you cancel.", + "cancelImportButton": "Stop Import", + "summaryTitle": "Import Complete", + "summaryCreated": "Created with metadata", + "summaryNoMetadata": "Created (ISBN only)", + "summaryFailed": "Failed", + "summaryCancelled": "Skipped (cancelled)", + "failedIsbnsLabel": "Failed ISBNs", + "doneButton": "Done" + }, "fileUploader": { "title": "Upload Additional File", "unknownTitle": "Unknown Title", diff --git a/booklore-ui/src/i18n/es/book.json b/booklore-ui/src/i18n/es/book.json index cf0920365..0c22bdb96 100644 --- a/booklore-ui/src/i18n/es/book.json +++ b/booklore-ui/src/i18n/es/book.json @@ -262,6 +262,7 @@ "library": { "optionsLabel": "Opciones", "addPhysicalBook": "Añadir libro físico", + "bulkIsbnImport": "Importar ISBNs desde archivo", "editLibrary": "Editar biblioteca", "rescanLibrary": "Re-escanear biblioteca", "customFetchMetadata": "Obtención personalizada de metadatos", @@ -438,6 +439,49 @@ "addButton": "Agregar libro físico", "fetchMetadataTooltip": "Obtener metadatos por ISBN" }, + "bulkIsbnImport": { + "title": "Importar ISBNs", + "description": "Importar varios libros físicos desde una lista de ISBNs", + "closeTooltip": "Cerrar", + "libraryLabel": "Biblioteca", + "libraryPlaceholder": "Seleccionar una biblioteca", + "tabFile": "Subir archivo", + "tabPaste": "Pegar ISBNs", + "chooseFile": "Elegir archivo", + "fileFormatsHint": "Formatos compatibles: .txt, .csv, .tsv (máx. 1 MB)", + "pastePlaceholder": "Pegue los ISBNs aquí, uno por línea o separados por comas...", + "parseButton": "Analizar", + "errorFileTooLarge": "El archivo supera el límite de 1 MB.", + "errorNoIsbns": "No se encontraron ISBNs en la entrada.", + "errorTooMany": "Solo se importarán los primeros {{ max }} ISBNs. Divida el archivo para el resto.", + "validCount": "{{ count }} ISBN(s) válido(s)", + "skippedCount": "{{ count }} omitido(s)", + "duplicatesRemoved": "{{ count }} duplicado(s) eliminado(s)", + "reason": { + "invalid": "Formato de ISBN no válido", + "alreadyExists": "Ya existe en esta biblioteca" + }, + "previewLabel": "ISBNs a importar", + "clearButton": "Limpiar", + "validationLibraryRequired": "Seleccione una biblioteca", + "validationNoIsbns": "Suba un archivo o pegue ISBNs para comenzar", + "validationReady": "Listo para importar {{ count }} ISBN(s)", + "cancelButton": "Cancelar", + "startImportButton": "Iniciar importación", + "processingLabel": "Procesando {{ current }} de {{ total }}", + "lookingUp": "Buscando metadatos...", + "createdNoMetadata": "Creado (sin metadatos encontrados)", + "unknownError": "Error desconocido", + "processingHint": "Los libros ya creados se conservarán si cancela.", + "cancelImportButton": "Detener importación", + "summaryTitle": "Importación completada", + "summaryCreated": "Creados con metadatos", + "summaryNoMetadata": "Creados (solo ISBN)", + "summaryFailed": "Fallidos", + "summaryCancelled": "Omitidos (cancelados)", + "failedIsbnsLabel": "ISBNs fallidos", + "doneButton": "Listo" + }, "fileUploader": { "title": "Subir archivo adicional", "unknownTitle": "Título desconocido",