refactor(frontend): rename booklore-ui to frontend
- Frontend path: - rename the tracked Angular app tree from `booklore-ui/` to `frontend/` - preserve file contents during the move so this commit stays focused on the path change itself - Frontend docs: - update the moved frontend README and contribution guide where they refer to the renamed folder - keep those edits limited to path references introduced by the directory rename
This commit is contained in:
@@ -0,0 +1,227 @@
|
||||
<ng-container *transloco="let t; prefix: 'magicShelf'">
|
||||
<div class="magic-shelf-container">
|
||||
<div class="panel-header">
|
||||
<div class="header-icon-wrapper">
|
||||
<i class="pi pi-sparkles header-icon"></i>
|
||||
</div>
|
||||
<div class="header-text">
|
||||
<h2 class="panel-title">
|
||||
{{ editMode ? t('header.titleEdit') : t('header.titleCreate') }}
|
||||
</h2>
|
||||
<p class="panel-description">{{ t('header.description') }}</p>
|
||||
</div>
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
[text]="true"
|
||||
[rounded]="true"
|
||||
severity="secondary"
|
||||
(onClick)="cancel()"
|
||||
class="close-button">
|
||||
</p-button>
|
||||
</div>
|
||||
|
||||
<div class="magic-shelf-content" [formGroup]="form">
|
||||
<fieldset [disabled]="form.get('isPublic')?.value && !isAdmin">
|
||||
<div class="form-header">
|
||||
<div class="form-field">
|
||||
<label for="shelfName">{{ t('form.shelfName') }}</label>
|
||||
<input pInputText id="shelfName" type="text" formControlName="name" [placeholder]="t('form.namePlaceholder')"/>
|
||||
</div>
|
||||
<div class="icon-picker-section">
|
||||
<div class="icon-picker-wrapper">
|
||||
<span>{{ t('form.shelfIcon') }}</span>
|
||||
@if (selectedIcon) {
|
||||
<div class="selected-icon-display">
|
||||
<div class="icon-display-container" (click)="openIconPicker()" (keydown.enter)="openIconPicker()" tabindex="0" role="button">
|
||||
<app-icon-display
|
||||
[icon]="selectedIcon"
|
||||
[size]="'16px'"
|
||||
iconClass="selected-icon"
|
||||
alt="Selected shelf icon">
|
||||
</app-icon-display>
|
||||
<span class="icon-label">{{ t('form.clickToChange') }}</span>
|
||||
</div>
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
severity="danger"
|
||||
[outlined]="true"
|
||||
[rounded]="true"
|
||||
size="small"
|
||||
(onClick)="clearSelectedIcon()"
|
||||
[pTooltip]="t('form.removeIcon')"
|
||||
tooltipPosition="left"
|
||||
/>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="icon-display-container" (click)="openIconPicker()" (keydown.enter)="openIconPicker()" tabindex="0" role="button">
|
||||
<div class="icon-placeholder">
|
||||
<i class="pi pi-plus"></i>
|
||||
<span>{{ t('form.selectIcon') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
@if (isAdmin) {
|
||||
<div class="public-checkbox-section">
|
||||
<div class="checkbox-wrapper">
|
||||
<p-checkbox formControlName="isPublic" [binary]="true" inputId="isPublic" (onChange)="onIsPublicChange($event)"></p-checkbox>
|
||||
<label for="isPublic">{{ t('form.public') }}</label>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (showImportPanel) {
|
||||
<div class="import-panel">
|
||||
<textarea pTextarea [(ngModel)]="importJson" [ngModelOptions]="{standalone: true}" rows="10" [placeholder]="t('importJson.placeholder')" class="import-textarea"></textarea>
|
||||
<div class="import-actions">
|
||||
<p-button [label]="t('actions.cancel')" severity="secondary" [outlined]="true" (onClick)="toggleImportPanel()" size="small"/>
|
||||
<p-button [label]="t('importJson.apply')" icon="pi pi-check" severity="success" (onClick)="applyImportedJson()" size="small"/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="rules-container">
|
||||
<ng-container *ngTemplateOutlet="groupTemplate; context: { group: form.get('group') }"></ng-container>
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
|
||||
<div class="dialog-footer">
|
||||
@if (!editMode) {
|
||||
<p-button
|
||||
icon="pi pi-file-import"
|
||||
[label]="t('importJson.buttonLabel')"
|
||||
[outlined]="true"
|
||||
severity="info"
|
||||
size="small"
|
||||
(onClick)="toggleImportPanel()"
|
||||
/>
|
||||
}
|
||||
<div class="footer-actions">
|
||||
<p-button
|
||||
[label]="t('actions.cancel')"
|
||||
severity="secondary"
|
||||
[outlined]="true"
|
||||
(onClick)="cancel()"
|
||||
/>
|
||||
<p-button
|
||||
[label]="t('actions.saveFilter')"
|
||||
icon="pi pi-save"
|
||||
severity="success"
|
||||
(onClick)="submit()"
|
||||
[disabled]="form.invalid"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ng-template #groupTemplate let-group="group">
|
||||
<div class="group-container" [formGroup]="group">
|
||||
<div class="group-header">
|
||||
<label [for]="getControlId(group.get('join'), 'magic-shelf-group-join')">{{ t('group.condition') }}</label>
|
||||
<p-select [inputId]="getControlId(group.get('join'), 'magic-shelf-group-join')" [options]="conditionOptions" formControlName="join" class="condition-select" appendTo="body" [showClear]="false"/>
|
||||
<p-button icon="pi pi-plus" size="small" text (click)="addRule(group)" [label]="t('actions.addRule')" outlined></p-button>
|
||||
<p-button icon="pi pi-folder-open" size="small" text (click)="addGroup(group)" [label]="t('actions.addGroup')" outlined></p-button>
|
||||
@if (group.parent) {
|
||||
<p-button icon="pi pi-trash" text (click)="deleteGroup(group)" severity="danger"></p-button>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div formArrayName="rules">
|
||||
@for (ruleCtrl of group.get('rules')['controls']; let i = $index; track trackByFn(ruleCtrl, i)) {
|
||||
<div [formGroupName]="i" class="rule-item">
|
||||
@if (isGroup(ruleCtrl)) {
|
||||
<ng-container>
|
||||
<ng-container *ngTemplateOutlet="groupTemplate; context: { group: ruleCtrl }"></ng-container>
|
||||
</ng-container>
|
||||
} @else {
|
||||
<p-select [options]="fieldOptions" [group]="true" optionGroupLabel="label" optionGroupChildren="items" [filter]="true" filterBy="label" formControlName="field" (onChange)="onFieldChange(ruleCtrl)" [placeholder]="t('placeholders.field')" appendTo="body" class="field-select"/>
|
||||
<p-select [options]="getOperatorOptionsForField(ruleCtrl.get('field')?.value)" appendTo="body" formControlName="operator" [placeholder]="t('placeholders.operator')" class="operator-select" (onChange)="onOperatorChange(ruleCtrl)"/>
|
||||
|
||||
@if (!['is_empty', 'is_not_empty'].includes(ruleCtrl.get('operator')?.value)) {
|
||||
@if (['within_last', 'older_than'].includes(ruleCtrl.get('operator')?.value)) {
|
||||
<p-inputNumber formControlName="value" class="value-input" [min]="1" [placeholder]="t('placeholders.amount')" [showButtons]="true"></p-inputNumber>
|
||||
<p-select [options]="dateUnitOptions" formControlName="valueEnd" [placeholder]="t('placeholders.selectUnit')" appendTo="body" class="value-input"></p-select>
|
||||
} @else if (ruleCtrl.get('operator')?.value === 'this_period') {
|
||||
<p-select [options]="datePeriodOptions" formControlName="value" [placeholder]="t('placeholders.selectPeriod')" appendTo="body" class="value-input"></p-select>
|
||||
} @else if (ruleCtrl.get('operator')?.value === 'in_between') {
|
||||
@if (ruleCtrl.get('field')?.value === 'publishedDate') {
|
||||
<p-datepicker [formControl]="ruleCtrl.get('valueStart')" dateFormat="dd-M-yy" [placeholder]="t('placeholders.startYear')" appendTo="body" fluid class="value-input"></p-datepicker>
|
||||
<p-datepicker [formControl]="ruleCtrl.get('valueEnd')" dateFormat="dd-M-yy" [placeholder]="t('placeholders.endYear')" appendTo="body" fluid class="value-input"></p-datepicker>
|
||||
} @else if (['dateFinished', 'addedOn', 'lastReadTime'].includes(ruleCtrl.get('field')?.value)) {
|
||||
<p-datepicker [formControl]="ruleCtrl.get('valueStart')" dateFormat="dd-M-yy" [placeholder]="t('placeholders.startDate')" appendTo="body" fluid class="value-input"></p-datepicker>
|
||||
<p-datepicker [formControl]="ruleCtrl.get('valueEnd')" dateFormat="dd-M-yy" [placeholder]="t('placeholders.endDate')" appendTo="body" fluid class="value-input"></p-datepicker>
|
||||
} @else if (numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.type === 'number') {
|
||||
<p-inputNumber [formControl]="ruleCtrl.get('valueStart')" [min]="0" class="value-input" [placeholder]="t('placeholders.startValue')" [showButtons]="true"></p-inputNumber>
|
||||
<p-inputNumber [formControl]="ruleCtrl.get('valueEnd')" [min]="0" class="value-input" [placeholder]="t('placeholders.endValue')" [showButtons]="true"></p-inputNumber>
|
||||
} @else if (numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.type === 'decimal') {
|
||||
<p-inputNumber [formControl]="ruleCtrl.get('valueStart')" mode="decimal" [minFractionDigits]="1" [maxFractionDigits]="1" [min]="0" [max]="numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.max || 10" class="value-input" [placeholder]="t('placeholders.startValue')" [showButtons]="true"></p-inputNumber>
|
||||
<p-inputNumber [formControl]="ruleCtrl.get('valueEnd')" mode="decimal" [minFractionDigits]="1" [maxFractionDigits]="1" [min]="0" [max]="numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.max || 10" class="value-input" [placeholder]="t('placeholders.endValue')" [showButtons]="true"></p-inputNumber>
|
||||
} @else {
|
||||
<input pInputText [formControl]="ruleCtrl.get('valueStart')" class="value-input" [placeholder]="t('placeholders.startValue')"/>
|
||||
<input pInputText [formControl]="ruleCtrl.get('valueEnd')" class="value-input" [placeholder]="t('placeholders.endValue')"/>
|
||||
}
|
||||
} @else {
|
||||
@if (ruleCtrl.get('field')?.value === 'publishedDate') {
|
||||
<p-datepicker formControlName="value" dateFormat="dd-M-yy" appendTo="body" fluid class="value-input"></p-datepicker>
|
||||
} @else if (['dateFinished', 'addedOn', 'lastReadTime'].includes(ruleCtrl.get('field')?.value)) {
|
||||
<p-datepicker formControlName="value" dateFormat="dd-M-yy" appendTo="body" fluid class="value-input"></p-datepicker>
|
||||
} @else if (numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.type === 'boolean') {
|
||||
<p-select [options]="booleanOptions" formControlName="value" [placeholder]="t('placeholders.selectValue')" appendTo="body" class="value-input"></p-select>
|
||||
} @else if (numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.type === 'number') {
|
||||
<p-inputNumber formControlName="value" class="value-input" mode="decimal" [placeholder]="t('placeholders.value')" [showButtons]="true"></p-inputNumber>
|
||||
} @else if (numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.type === 'decimal') {
|
||||
<p-inputNumber formControlName="value" mode="decimal" [minFractionDigits]="1" [maxFractionDigits]="1" [min]="0" [max]="numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.max || 10" class="value-input" [placeholder]="t('placeholders.value')"></p-inputNumber>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'seriesStatus') {
|
||||
<p-select [options]="seriesStatusOptions" formControlName="value" [placeholder]="t('placeholders.selectSeriesStatus')" appendTo="body" class="value-input"></p-select>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'seriesGaps') {
|
||||
<p-select [options]="seriesGapsOptions" formControlName="value" [placeholder]="t('placeholders.selectSeriesGap')" appendTo="body" class="value-input"></p-select>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'seriesPosition') {
|
||||
<p-select [options]="seriesPositionOptions" formControlName="value" [placeholder]="t('placeholders.selectSeriesPosition')" appendTo="body" class="value-input"></p-select>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'metadataPresence') {
|
||||
<p-select [options]="metadataPresenceOptions" [group]="true" optionGroupLabel="label" optionGroupChildren="items" [filter]="true" filterBy="label" formControlName="value" [placeholder]="t('placeholders.selectMetadataField')" appendTo="body" class="value-input"></p-select>
|
||||
} @else if (['includes_any', 'includes_all', 'excludes_all'].includes(ruleCtrl.get('operator')?.value)) {
|
||||
@if (ruleCtrl.get('field')?.value === 'readStatus') {
|
||||
<p-multiSelect [options]="readStatusOptions" formControlName="value" display="chip" class="value-input" appendTo="body" [placeholder]="t('placeholders.selectStatuses')"></p-multiSelect>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'fileType') {
|
||||
<p-multiSelect [options]="fileType" formControlName="value" display="chip" class="value-input" appendTo="body" [placeholder]="t('placeholders.selectFileTypes')"></p-multiSelect>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'library') {
|
||||
<p-multiSelect [options]="libraryOptions()" formControlName="value" display="chip" class="value-input" appendTo="body" [placeholder]="t('placeholders.selectLibraries')"></p-multiSelect>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'shelf') {
|
||||
<p-multiSelect [options]="shelfOptions()" formControlName="value" display="chip" class="value-input" appendTo="body" [placeholder]="t('placeholders.selectShelves')"></p-multiSelect>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'categories') {
|
||||
<p-multiSelect [options]="categoryOptions()" formControlName="value" display="chip" class="value-input" appendTo="body" [placeholder]="t('placeholders.selectGenres')"></p-multiSelect>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'contentRating') {
|
||||
<p-multiSelect [options]="contentRatingOptions" formControlName="value" display="chip" class="value-input" appendTo="body" [placeholder]="t('placeholders.selectContentRatings')"></p-multiSelect>
|
||||
} @else {
|
||||
<div class="autocomplete-wrapper">
|
||||
<p-autoComplete [formControl]="ruleCtrl.get('value')" [multiple]="true" [typeahead]="false" [dropdown]="false" [forceSelection]="false" [placeholder]="t('placeholders.enterValues')" (onBlur)="onAutoCompleteBlur(ruleCtrl.get('value'), $event)"></p-autoComplete>
|
||||
</div>
|
||||
}
|
||||
} @else if (ruleCtrl.get('field')?.value === 'readStatus') {
|
||||
<p-select [options]="readStatusOptions" formControlName="value" [placeholder]="t('placeholders.selectStatus')" appendTo="body" class="value-input"></p-select>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'fileType') {
|
||||
<p-select [options]="fileType" formControlName="value" [placeholder]="t('placeholders.selectFileType')" appendTo="body" class="value-input"></p-select>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'library') {
|
||||
<p-select [options]="libraryOptions()" formControlName="value" [placeholder]="t('placeholders.selectLibrary')" appendTo="body" class="value-input"></p-select>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'shelf') {
|
||||
<p-select [options]="shelfOptions()" formControlName="value" [placeholder]="t('placeholders.selectShelf')" appendTo="body" class="value-input"></p-select>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'categories') {
|
||||
<p-select [options]="categoryOptions()" formControlName="value" [placeholder]="t('placeholders.selectGenre')" appendTo="body" class="value-input"></p-select>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'contentRating') {
|
||||
<p-select [options]="contentRatingOptions" formControlName="value" [placeholder]="t('placeholders.selectContentRating')" appendTo="body" class="value-input"></p-select>
|
||||
} @else {
|
||||
<input pInputText formControlName="value" class="value-input" [placeholder]="t('placeholders.value')"/>
|
||||
}
|
||||
}
|
||||
}
|
||||
<p-button icon="pi pi-trash" text severity="danger" (click)="removeRule(group, i)"></p-button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</ng-template>
|
||||
</div>
|
||||
</ng-container>
|
||||
@@ -0,0 +1,321 @@
|
||||
@use '../../../shared/styles/panel-shared' as panel;
|
||||
|
||||
.magic-shelf-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
@media (max-width: 1280px) {
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.panel-header {
|
||||
@include panel.panel-header;
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.import-panel {
|
||||
margin-bottom: 0.75rem;
|
||||
padding: 1rem;
|
||||
background: var(--overlay-background);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 8px;
|
||||
|
||||
.import-textarea {
|
||||
width: 100%;
|
||||
font-family: monospace;
|
||||
font-size: 0.85rem;
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.import-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 0.5rem;
|
||||
margin-top: 0.75rem;
|
||||
}
|
||||
}
|
||||
|
||||
.magic-shelf-content {
|
||||
padding: 2rem;
|
||||
background: var(--card-background);
|
||||
border: 1px solid var(--border-color);
|
||||
border-bottom: none;
|
||||
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
|
||||
min-height: 450px;
|
||||
|
||||
@media (max-width: 480px) {
|
||||
padding: 1rem;
|
||||
min-height: 350px;
|
||||
}
|
||||
}
|
||||
|
||||
.form-header {
|
||||
margin-bottom: 0.75rem;
|
||||
display: flex;
|
||||
width: 100%;
|
||||
gap: 1rem;
|
||||
padding: 1rem;
|
||||
background: var(--overlay-background);
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border-color);
|
||||
|
||||
@media (max-width: 768px) {
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
}
|
||||
|
||||
.form-field {
|
||||
flex: 1;
|
||||
|
||||
label {
|
||||
display: block;
|
||||
margin-bottom: 0.5rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-color);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
input {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.icon-picker-section {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
|
||||
.icon-picker-wrapper {
|
||||
label {
|
||||
display: block;
|
||||
margin-bottom: 0.5rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-color);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.selected-icon-display {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.icon-display-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.625rem 1rem;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
background: var(--card-background);
|
||||
|
||||
&:hover {
|
||||
border-color: var(--primary-color);
|
||||
}
|
||||
|
||||
&:focus {
|
||||
outline: 2px solid var(--primary-color);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.selected-icon {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.icon-label {
|
||||
font-size: 0.95rem;
|
||||
color: var(--text-secondary-color);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.icon-placeholder {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
color: var(--text-secondary-color);
|
||||
|
||||
i {
|
||||
font-size: 1.125rem;
|
||||
color: var(--primary-color)
|
||||
}
|
||||
|
||||
span {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
align-items: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
.public-checkbox-section {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
|
||||
.checkbox-wrapper {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 0.625rem 0;
|
||||
|
||||
label {
|
||||
margin-left: 0.5rem;
|
||||
font-weight: 500;
|
||||
color: var(--text-color);
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
align-items: flex-start;
|
||||
|
||||
.checkbox-wrapper {
|
||||
padding: 0.5rem 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.rules-container {
|
||||
overflow: auto;
|
||||
max-height: 40rem;
|
||||
padding: 0.5rem;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
max-height: 35rem;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: var(--overlay-background);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: var(--border-color);
|
||||
border-radius: 3px;
|
||||
transition: background 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
background: var(--primary-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.dialog-footer {
|
||||
@include panel.dialog-footer-end;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.save-button-section {
|
||||
margin: 1.5rem 0 0 0;
|
||||
padding: 1rem;
|
||||
background: var(--overlay-background);
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border-color);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.group-container {
|
||||
padding: 1rem;
|
||||
border-left: 4px solid var(--primary-color);
|
||||
margin-top: 0.75rem;
|
||||
width: 100%;
|
||||
border-radius: 8px;
|
||||
border-top: 1px solid var(--border-color);
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
border-right: 1px solid var(--border-color);
|
||||
transition: all 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 0.75rem;
|
||||
}
|
||||
}
|
||||
|
||||
.group-header {
|
||||
margin-bottom: 0.75rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
|
||||
label {
|
||||
font-weight: 600;
|
||||
color: var(--text-color);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.condition-select {
|
||||
width: 9rem;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
gap: 0.5rem;
|
||||
|
||||
.condition-select {
|
||||
width: 100%;
|
||||
max-width: 9rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.rule-item {
|
||||
margin-left: 1rem;
|
||||
margin-top: 0.75rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 0.125rem;
|
||||
gap: 0.75rem;
|
||||
background: var(--overlay-background);
|
||||
transition: all 0.2s ease;
|
||||
|
||||
.field-select,
|
||||
.operator-select {
|
||||
min-width: 14rem;
|
||||
}
|
||||
|
||||
.value-input,
|
||||
.autocomplete-wrapper {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
flex-wrap: wrap;
|
||||
margin-left: 0.5rem;
|
||||
gap: 0.5rem;
|
||||
|
||||
.field-select,
|
||||
.operator-select {
|
||||
min-width: 12rem;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.value-input,
|
||||
.autocomplete-wrapper {
|
||||
flex: 1;
|
||||
min-width: 200px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
margin-left: 0;
|
||||
padding: 0.5rem;
|
||||
|
||||
.field-select,
|
||||
.operator-select {
|
||||
min-width: 100%;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,675 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {MagicShelfComponent, Rule} from './magic-shelf-component';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {LibraryService} from '../../book/service/library.service';
|
||||
import {ShelfService} from '../../book/service/shelf.service';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {MagicShelfService} from '../service/magic-shelf.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {UserService} from '../../settings/user-management/user.service';
|
||||
import {IconPickerService} from '../../../shared/service/icon-picker.service';
|
||||
import {of} from 'rxjs';
|
||||
|
||||
describe('MagicShelfComponent (Part 3)', () => {
|
||||
let component: MagicShelfComponent;
|
||||
|
||||
const mockTransloco = {
|
||||
translate: vi.fn((key: string) => key),
|
||||
selectTranslation: vi.fn(() => of({})),
|
||||
langChanges$: of('en'),
|
||||
getActiveLang: vi.fn(() => 'en'),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: TranslocoService, useValue: mockTransloco},
|
||||
{provide: LibraryService, useValue: {getLibrariesFromState: vi.fn(() => [])}},
|
||||
{provide: ShelfService, useValue: {shelves$: of([])}},
|
||||
{provide: BookService, useValue: {bookState$: of({loaded: false, books: []})}},
|
||||
{provide: MagicShelfService, useValue: {}},
|
||||
{provide: MessageService, useValue: {add: vi.fn()}},
|
||||
{provide: DynamicDialogRef, useValue: {close: vi.fn()}},
|
||||
{provide: DynamicDialogConfig, useValue: {data: null}},
|
||||
{provide: UserService, useValue: {getCurrentUser: vi.fn(() => ({permissions: {admin: false}}))}},
|
||||
{provide: IconPickerService, useValue: {open: vi.fn(() => of(null))}},
|
||||
]
|
||||
});
|
||||
|
||||
const fixture = TestBed.createComponent(MagicShelfComponent);
|
||||
component = fixture.componentInstance;
|
||||
});
|
||||
|
||||
describe('getOperatorOptionsForField', () => {
|
||||
it('should return is/isNot operators for seriesStatus', () => {
|
||||
const operators = component.getOperatorOptionsForField('seriesStatus');
|
||||
expect(operators).toHaveLength(2);
|
||||
expect(operators.map(o => o.value)).toEqual(['equals', 'not_equals']);
|
||||
expect(operators[0].label).toContain('is');
|
||||
});
|
||||
|
||||
it('should return is/isNot operators for seriesPosition', () => {
|
||||
const operators = component.getOperatorOptionsForField('seriesPosition');
|
||||
expect(operators).toHaveLength(2);
|
||||
expect(operators.map(o => o.value)).toEqual(['equals', 'not_equals']);
|
||||
});
|
||||
|
||||
it('should return has/hasNot operators for seriesGaps', () => {
|
||||
const operators = component.getOperatorOptionsForField('seriesGaps');
|
||||
expect(operators).toHaveLength(2);
|
||||
expect(operators.map(o => o.value)).toEqual(['equals', 'not_equals']);
|
||||
expect(operators[0].label).toContain('has');
|
||||
});
|
||||
|
||||
it('should return has/hasNot operators for metadataPresence', () => {
|
||||
const operators = component.getOperatorOptionsForField('metadataPresence');
|
||||
expect(operators).toHaveLength(2);
|
||||
expect(operators.map(o => o.value)).toEqual(['equals', 'not_equals']);
|
||||
expect(operators[0].label).toContain('has');
|
||||
expect(operators[1].label).toContain('hasNot');
|
||||
});
|
||||
|
||||
it('should include relative date operators for date fields', () => {
|
||||
const operators = component.getOperatorOptionsForField('dateFinished');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('within_last');
|
||||
expect(values).toContain('older_than');
|
||||
expect(values).toContain('this_period');
|
||||
});
|
||||
|
||||
it('should include relative date operators for addedOn', () => {
|
||||
const operators = component.getOperatorOptionsForField('addedOn');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('within_last');
|
||||
expect(values).toContain('older_than');
|
||||
expect(values).toContain('this_period');
|
||||
});
|
||||
|
||||
it('should include relative date operators for publishedDate', () => {
|
||||
const operators = component.getOperatorOptionsForField('publishedDate');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('within_last');
|
||||
expect(values).toContain('older_than');
|
||||
expect(values).toContain('this_period');
|
||||
});
|
||||
|
||||
it('should NOT include relative date operators for number fields', () => {
|
||||
const operators = component.getOperatorOptionsForField('pageCount');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).not.toContain('within_last');
|
||||
expect(values).not.toContain('older_than');
|
||||
expect(values).not.toContain('this_period');
|
||||
});
|
||||
|
||||
it('should include comparison operators for readingProgress', () => {
|
||||
const operators = component.getOperatorOptionsForField('readingProgress');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('greater_than');
|
||||
expect(values).toContain('less_than');
|
||||
expect(values).toContain('in_between');
|
||||
});
|
||||
|
||||
it('should NOT include relative date operators for readingProgress', () => {
|
||||
const operators = component.getOperatorOptionsForField('readingProgress');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).not.toContain('within_last');
|
||||
});
|
||||
|
||||
it('should return only base operators for boolean fields', () => {
|
||||
const operators = component.getOperatorOptionsForField('abridged');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('equals');
|
||||
expect(values).toContain('not_equals');
|
||||
expect(values).toContain('is_empty');
|
||||
expect(values).toContain('is_not_empty');
|
||||
expect(values).not.toContain('contains');
|
||||
expect(values).not.toContain('greater_than');
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildRuleFromData', () => {
|
||||
it('should parse within_last value as number, not date', () => {
|
||||
const rule: Rule = {field: 'dateFinished', operator: 'within_last', value: 30, valueEnd: 'days'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toBe(30);
|
||||
expect(formGroup.get('valueEnd')?.value).toBe('days');
|
||||
});
|
||||
|
||||
it('should preserve this_period value as string', () => {
|
||||
const rule: Rule = {field: 'addedOn', operator: 'this_period', value: 'month'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toBe('month');
|
||||
expect(formGroup.get('valueEnd')?.value).toBeNull();
|
||||
});
|
||||
|
||||
it('should parse older_than value as number', () => {
|
||||
const rule: Rule = {field: 'lastReadTime', operator: 'older_than', value: 6, valueEnd: 'months'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toBe(6);
|
||||
expect(formGroup.get('valueEnd')?.value).toBe('months');
|
||||
});
|
||||
|
||||
it('should still parse regular date values as Date objects', () => {
|
||||
const rule: Rule = {field: 'dateFinished', operator: 'equals', value: '2024-06-15'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it('should parse composite field values as strings', () => {
|
||||
const rule: Rule = {field: 'seriesStatus', operator: 'equals', value: 'reading'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toBe('reading');
|
||||
});
|
||||
|
||||
it('should parse readingProgress values as numbers', () => {
|
||||
const rule: Rule = {field: 'readingProgress', operator: 'greater_than', value: 50};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toBe(50);
|
||||
});
|
||||
});
|
||||
|
||||
describe('onOperatorChange', () => {
|
||||
it('should set valueEnd to days for within_last operator', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('operator')?.setValue('within_last');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('valueEnd')?.value).toBe('days');
|
||||
expect(ruleCtrl.get('value')?.value).toBeNull();
|
||||
});
|
||||
|
||||
it('should set valueEnd to days for older_than operator', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('operator')?.setValue('older_than');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('valueEnd')?.value).toBe('days');
|
||||
expect(ruleCtrl.get('value')?.value).toBeNull();
|
||||
});
|
||||
|
||||
it('should set valueEnd to null for this_period operator', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('operator')?.setValue('this_period');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('valueEnd')?.value).toBeNull();
|
||||
expect(ruleCtrl.get('value')?.value).toBeNull();
|
||||
});
|
||||
|
||||
it('should set value to empty array for includes_any operator', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('operator')?.setValue('includes_any');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('value')?.value).toEqual([]);
|
||||
});
|
||||
|
||||
it('should clear all values for is_empty operator', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('value')?.setValue('something');
|
||||
ruleCtrl.get('operator')?.setValue('is_empty');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('value')?.value).toBeNull();
|
||||
expect(ruleCtrl.get('valueStart')?.value).toBeNull();
|
||||
expect(ruleCtrl.get('valueEnd')?.value).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('option getters', () => {
|
||||
it('should return 5 series status options', () => {
|
||||
const options = component.seriesStatusOptions;
|
||||
expect(options).toHaveLength(5);
|
||||
expect(options.map(o => o.value)).toEqual(['reading', 'completed', 'ongoing', 'not_started', 'fully_read']);
|
||||
});
|
||||
|
||||
it('should return 4 series gaps options', () => {
|
||||
const options = component.seriesGapsOptions;
|
||||
expect(options).toHaveLength(4);
|
||||
expect(options.map(o => o.value)).toEqual(['any_gap', 'missing_first', 'missing_latest', 'duplicate_number']);
|
||||
});
|
||||
|
||||
it('should return 3 series position options', () => {
|
||||
const options = component.seriesPositionOptions;
|
||||
expect(options).toHaveLength(3);
|
||||
expect(options.map(o => o.value)).toEqual(['next_unread', 'first_in_series', 'last_in_series']);
|
||||
});
|
||||
|
||||
it('should return 4 date unit options', () => {
|
||||
const options = component.dateUnitOptions;
|
||||
expect(options).toHaveLength(4);
|
||||
expect(options.map(o => o.value)).toEqual(['days', 'weeks', 'months', 'years']);
|
||||
});
|
||||
|
||||
it('should return 3 date period options', () => {
|
||||
const options = component.datePeriodOptions;
|
||||
expect(options).toHaveLength(3);
|
||||
expect(options.map(o => o.value)).toEqual(['week', 'month', 'year']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fieldOptions grouping', () => {
|
||||
it('should include readingProgress in organization group', () => {
|
||||
const groups = component.fieldOptions;
|
||||
const orgGroup = groups.find(g => g.label.includes('organization'));
|
||||
const fieldValues = orgGroup?.items.map(i => i.value) ?? [];
|
||||
expect(fieldValues).toContain('readingProgress');
|
||||
});
|
||||
|
||||
it('should include seriesStatus, seriesGaps, seriesPosition in series group', () => {
|
||||
const groups = component.fieldOptions;
|
||||
const seriesGroup = groups.find(g => g.label.includes('series'));
|
||||
const fieldValues = seriesGroup?.items.map(i => i.value) ?? [];
|
||||
expect(fieldValues).toContain('seriesStatus');
|
||||
expect(fieldValues).toContain('seriesGaps');
|
||||
expect(fieldValues).toContain('seriesPosition');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getOperatorOptionsForField edge cases', () => {
|
||||
it('should return baseOperators + multiValueOperators for null field', () => {
|
||||
const operators = component.getOperatorOptionsForField(null);
|
||||
const values = operators.map(o => o.value);
|
||||
expect(operators).toHaveLength(7);
|
||||
expect(values).toContain('equals');
|
||||
expect(values).toContain('not_equals');
|
||||
expect(values).toContain('is_empty');
|
||||
expect(values).toContain('is_not_empty');
|
||||
expect(values).toContain('includes_any');
|
||||
expect(values).toContain('excludes_all');
|
||||
expect(values).toContain('includes_all');
|
||||
});
|
||||
|
||||
it('should return baseOperators + multiValueOperators for undefined field', () => {
|
||||
const operators = component.getOperatorOptionsForField(undefined);
|
||||
const values = operators.map(o => o.value);
|
||||
expect(operators).toHaveLength(7);
|
||||
expect(values).toContain('equals');
|
||||
expect(values).toContain('not_equals');
|
||||
expect(values).toContain('is_empty');
|
||||
expect(values).toContain('is_not_empty');
|
||||
expect(values).toContain('includes_any');
|
||||
expect(values).toContain('excludes_all');
|
||||
expect(values).toContain('includes_all');
|
||||
});
|
||||
|
||||
it('should include text operators for title field', () => {
|
||||
const operators = component.getOperatorOptionsForField('title');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('contains');
|
||||
expect(values).toContain('does_not_contain');
|
||||
expect(values).toContain('starts_with');
|
||||
expect(values).toContain('ends_with');
|
||||
expect(values).toContain('includes_any');
|
||||
expect(values).toContain('excludes_all');
|
||||
expect(values).toContain('includes_all');
|
||||
});
|
||||
|
||||
it('should NOT include text operators for library field', () => {
|
||||
const operators = component.getOperatorOptionsForField('library');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('includes_any');
|
||||
expect(values).not.toContain('contains');
|
||||
expect(values).not.toContain('does_not_contain');
|
||||
expect(values).not.toContain('starts_with');
|
||||
expect(values).not.toContain('ends_with');
|
||||
});
|
||||
|
||||
it('should NOT include text operators for readStatus field', () => {
|
||||
const operators = component.getOperatorOptionsForField('readStatus');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('includes_any');
|
||||
expect(values).not.toContain('contains');
|
||||
expect(values).not.toContain('does_not_contain');
|
||||
expect(values).not.toContain('starts_with');
|
||||
expect(values).not.toContain('ends_with');
|
||||
});
|
||||
|
||||
it('should include comparison operators for metadataScore', () => {
|
||||
const operators = component.getOperatorOptionsForField('metadataScore');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('greater_than');
|
||||
expect(values).toContain('greater_than_equal_to');
|
||||
expect(values).toContain('less_than');
|
||||
expect(values).toContain('less_than_equal_to');
|
||||
expect(values).toContain('in_between');
|
||||
});
|
||||
|
||||
it('should include relative date operators for lastReadTime', () => {
|
||||
const operators = component.getOperatorOptionsForField('lastReadTime');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('within_last');
|
||||
expect(values).toContain('older_than');
|
||||
expect(values).toContain('this_period');
|
||||
});
|
||||
|
||||
it('should NOT include comparison operators for string fields', () => {
|
||||
const operators = component.getOperatorOptionsForField('title');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).not.toContain('greater_than');
|
||||
expect(values).not.toContain('greater_than_equal_to');
|
||||
expect(values).not.toContain('less_than');
|
||||
expect(values).not.toContain('less_than_equal_to');
|
||||
expect(values).not.toContain('in_between');
|
||||
});
|
||||
|
||||
it('should include both text and multi-value operators for authors', () => {
|
||||
const operators = component.getOperatorOptionsForField('authors');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('contains');
|
||||
expect(values).toContain('does_not_contain');
|
||||
expect(values).toContain('starts_with');
|
||||
expect(values).toContain('ends_with');
|
||||
expect(values).toContain('includes_any');
|
||||
expect(values).toContain('excludes_all');
|
||||
expect(values).toContain('includes_all');
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildRuleFromData edge cases', () => {
|
||||
it('should handle in_between for date fields', () => {
|
||||
const rule: Rule = {field: 'publishedDate', operator: 'in_between' as any, value: null, valueStart: '2024-01-01', valueEnd: '2024-12-31'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('valueStart')?.value).toBeInstanceOf(Date);
|
||||
expect(formGroup.get('valueEnd')?.value).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it('should handle in_between for number fields', () => {
|
||||
const rule: Rule = {field: 'pageCount', operator: 'in_between' as any, value: null, valueStart: 100, valueEnd: 500};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('valueStart')?.value).toBe(100);
|
||||
expect(formGroup.get('valueEnd')?.value).toBe(500);
|
||||
});
|
||||
|
||||
it('should preserve array values for includes_any', () => {
|
||||
const rule: Rule = {field: 'readStatus', operator: 'includes_any' as any, value: ['READ', 'READING']};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toEqual(['READ', 'READING']);
|
||||
});
|
||||
|
||||
it('should handle is_empty operator with no value', () => {
|
||||
const rule: Rule = {field: 'title', operator: 'is_empty' as any, value: null};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toBeNull();
|
||||
});
|
||||
|
||||
it('should handle boolean field values', () => {
|
||||
const rule: Rule = {field: 'abridged', operator: 'equals', value: 'true'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toBe('true');
|
||||
});
|
||||
|
||||
it('should handle string values for text fields', () => {
|
||||
const rule: Rule = {field: 'title', operator: 'contains' as any, value: 'Harry Potter'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toBe('Harry Potter');
|
||||
});
|
||||
|
||||
it('should handle within_last with string number value', () => {
|
||||
const rule: Rule = {field: 'dateFinished', operator: 'within_last', value: '30', valueEnd: 'days'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toBe(30);
|
||||
});
|
||||
|
||||
it('should handle this_period with null valueEnd', () => {
|
||||
const rule: Rule = {field: 'addedOn', operator: 'this_period', value: 'week', valueEnd: 'something'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('valueEnd')?.value).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('onOperatorChange edge cases', () => {
|
||||
it('should set value to empty array for excludes_all operator', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('operator')?.setValue('excludes_all');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('value')?.value).toEqual([]);
|
||||
});
|
||||
|
||||
it('should set value to empty array for includes_all operator', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('operator')?.setValue('includes_all');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('value')?.value).toEqual([]);
|
||||
});
|
||||
|
||||
it('should clear all values for is_not_empty operator', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('value')?.setValue('something');
|
||||
ruleCtrl.get('valueStart')?.setValue('start');
|
||||
ruleCtrl.get('valueEnd')?.setValue('end');
|
||||
ruleCtrl.get('operator')?.setValue('is_not_empty');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('value')?.value).toBeNull();
|
||||
expect(ruleCtrl.get('valueStart')?.value).toBeNull();
|
||||
expect(ruleCtrl.get('valueEnd')?.value).toBeNull();
|
||||
});
|
||||
|
||||
it('should set value to empty string for regular operators', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('operator')?.setValue('equals');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('value')?.value).toBe('');
|
||||
expect(ruleCtrl.get('valueStart')?.value).toBeNull();
|
||||
expect(ruleCtrl.get('valueEnd')?.value).toBeNull();
|
||||
});
|
||||
|
||||
it('should set value to empty string for in_between operator', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('operator')?.setValue('in_between');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('value')?.value).toBe('');
|
||||
});
|
||||
|
||||
it('should not affect form when called with already-set within_last', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('operator')?.setValue('within_last');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
ruleCtrl.get('value')?.setValue('15');
|
||||
ruleCtrl.get('operator')?.setValue('within_last');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('value')?.value).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('onFieldChange', () => {
|
||||
it('should reset operator and all values', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('field')?.setValue('title');
|
||||
ruleCtrl.get('operator')?.setValue('contains');
|
||||
ruleCtrl.get('value')?.setValue('some value');
|
||||
ruleCtrl.get('valueStart')?.setValue('start');
|
||||
ruleCtrl.get('valueEnd')?.setValue('end');
|
||||
component.onFieldChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('operator')?.value).toBe('');
|
||||
expect(ruleCtrl.get('value')?.value).toBeNull();
|
||||
expect(ruleCtrl.get('valueStart')?.value).toBeNull();
|
||||
expect(ruleCtrl.get('valueEnd')?.value).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('createRule and createGroup', () => {
|
||||
it('should create rule with empty defaults', () => {
|
||||
const rule = component.createRule();
|
||||
expect(rule.get('field')?.value).toBe('');
|
||||
expect(rule.get('operator')?.value).toBe('');
|
||||
expect(rule.get('value')?.value).toBeNull();
|
||||
expect(rule.get('valueStart')?.value).toBeNull();
|
||||
expect(rule.get('valueEnd')?.value).toBeNull();
|
||||
});
|
||||
|
||||
it('should create group with and join and empty rules', () => {
|
||||
const group = component.createGroup();
|
||||
expect(group.get('type')?.value).toBe('group');
|
||||
expect(group.get('join')?.value).toBe('and');
|
||||
expect((group.get('rules') as any).length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fieldOptions completeness', () => {
|
||||
it('should have 9 groups total', () => {
|
||||
expect(component.fieldOptions.length).toBe(9);
|
||||
});
|
||||
|
||||
it('should map categories field to genre translation key', () => {
|
||||
const groups = component.fieldOptions;
|
||||
const bookInfoGroup = groups.find(g => g.label.includes('bookInfo'));
|
||||
const categoriesItem = bookInfoGroup?.items.find(i => i.value === 'categories');
|
||||
expect(categoriesItem).toBeDefined();
|
||||
expect(categoriesItem!.label).toContain('genre');
|
||||
});
|
||||
|
||||
it('should include all audiobook fields in audiobook group', () => {
|
||||
const groups = component.fieldOptions;
|
||||
const audiobookGroup = groups.find(g => g.label.includes('audiobook'));
|
||||
const fieldValues = audiobookGroup?.items.map(i => i.value) ?? [];
|
||||
expect(fieldValues).toContain('narrator');
|
||||
expect(fieldValues).toContain('abridged');
|
||||
expect(fieldValues).toContain('audiobookDuration');
|
||||
});
|
||||
|
||||
it('should include all date fields in dates group', () => {
|
||||
const groups = component.fieldOptions;
|
||||
const datesGroup = groups.find(g => g.label.includes('dates'));
|
||||
const fieldValues = datesGroup?.items.map(i => i.value) ?? [];
|
||||
expect(fieldValues).toContain('publishedDate');
|
||||
expect(fieldValues).toContain('dateFinished');
|
||||
expect(fieldValues).toContain('lastReadTime');
|
||||
expect(fieldValues).toContain('addedOn');
|
||||
});
|
||||
|
||||
it('should include metadataScore and metadataPresence in qualityMetadata group', () => {
|
||||
const groups = component.fieldOptions;
|
||||
const qualityGroup = groups.find(g => g.label.includes('qualityMetadata'));
|
||||
const fieldValues = qualityGroup?.items.map(i => i.value) ?? [];
|
||||
expect(fieldValues).toContain('metadataScore');
|
||||
expect(fieldValues).toContain('metadataPresence');
|
||||
});
|
||||
|
||||
it('should NOT include metadataScore in ratingsReviews group', () => {
|
||||
const groups = component.fieldOptions;
|
||||
const ratingsGroup = groups.find(g => g.label.includes('ratingsReviews'));
|
||||
const fieldValues = ratingsGroup?.items.map(i => i.value) ?? [];
|
||||
expect(fieldValues).not.toContain('metadataScore');
|
||||
});
|
||||
});
|
||||
|
||||
describe('metadataPresenceOptions', () => {
|
||||
it('should return 10 groups', () => {
|
||||
const options = component.metadataPresenceOptions;
|
||||
expect(options).toHaveLength(10);
|
||||
});
|
||||
|
||||
it('should have grouped structure with label and items', () => {
|
||||
const options = component.metadataPresenceOptions;
|
||||
options.forEach(group => {
|
||||
expect(group.label).toBeDefined();
|
||||
expect(group.items).toBeDefined();
|
||||
expect(group.items.length).toBeGreaterThan(0);
|
||||
group.items.forEach(item => {
|
||||
expect(item.label).toBeDefined();
|
||||
expect(item.value).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should include key metadata fields', () => {
|
||||
const options = component.metadataPresenceOptions;
|
||||
const allValues = options.flatMap(g => g.items.map(i => i.value));
|
||||
expect(allValues).toContain('title');
|
||||
expect(allValues).toContain('thumbnailUrl');
|
||||
expect(allValues).toContain('authors');
|
||||
expect(allValues).toContain('isbn13');
|
||||
expect(allValues).toContain('goodreadsId');
|
||||
expect(allValues).toContain('audiobookDuration');
|
||||
expect(allValues).toContain('comicCharacters');
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildRuleFromData for metadataPresence', () => {
|
||||
it('should parse metadataPresence rule with string value', () => {
|
||||
const rule: Rule = {field: 'metadataPresence', operator: 'equals', value: 'thumbnailUrl'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('field')?.value).toBe('metadataPresence');
|
||||
expect(formGroup.get('operator')?.value).toBe('equals');
|
||||
expect(formGroup.get('value')?.value).toBe('thumbnailUrl');
|
||||
});
|
||||
|
||||
it('should parse metadataPresence rule with not_equals', () => {
|
||||
const rule: Rule = {field: 'metadataPresence', operator: 'not_equals', value: 'description'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('operator')?.value).toBe('not_equals');
|
||||
expect(formGroup.get('value')?.value).toBe('description');
|
||||
});
|
||||
});
|
||||
|
||||
describe('numericFieldConfigMap', () => {
|
||||
it('should contain readingProgress with max 100', () => {
|
||||
const config = component.numericFieldConfigMap.get('readingProgress');
|
||||
expect(config).toBeDefined();
|
||||
expect(config!.type).toBe('decimal');
|
||||
expect(config!.max).toBe(100);
|
||||
});
|
||||
|
||||
it('should contain personalRating with max 10', () => {
|
||||
const config = component.numericFieldConfigMap.get('personalRating');
|
||||
expect(config).toBeDefined();
|
||||
expect(config!.type).toBe('decimal');
|
||||
expect(config!.max).toBe(10);
|
||||
});
|
||||
|
||||
it('should contain pageCount with type number and no max', () => {
|
||||
const config = component.numericFieldConfigMap.get('pageCount');
|
||||
expect(config).toBeDefined();
|
||||
expect(config!.type).toBe('number');
|
||||
expect(config!.max).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should not contain title', () => {
|
||||
const config = component.numericFieldConfigMap.get('title' as any);
|
||||
expect(config).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should contain abridged with type boolean', () => {
|
||||
const config = component.numericFieldConfigMap.get('abridged');
|
||||
expect(config).toBeDefined();
|
||||
expect(config!.type).toBe('boolean');
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildGroupFromData', () => {
|
||||
it('should build group with mixed rules and nested groups', () => {
|
||||
const groupData = {
|
||||
name: '',
|
||||
type: 'group' as const,
|
||||
join: 'or' as const,
|
||||
rules: [
|
||||
{field: 'title', operator: 'contains', value: 'test'} as Rule,
|
||||
{
|
||||
type: 'group' as const,
|
||||
join: 'and' as const,
|
||||
rules: [
|
||||
{field: 'pageCount', operator: 'greater_than', value: 100} as Rule
|
||||
],
|
||||
name: ''
|
||||
}
|
||||
]
|
||||
};
|
||||
const result = component.buildGroupFromData(groupData);
|
||||
expect(result.get('join')?.value).toBe('or');
|
||||
const rulesArray = result.get('rules') as any;
|
||||
expect(rulesArray.length).toBe(2);
|
||||
const nestedGroup = rulesArray.at(1);
|
||||
expect(nestedGroup.get('rules')).toBeDefined();
|
||||
expect(nestedGroup.get('rules').length).toBe(1);
|
||||
});
|
||||
|
||||
it('should preserve join type', () => {
|
||||
const groupData = {
|
||||
name: '',
|
||||
type: 'group' as const,
|
||||
join: 'or' as const,
|
||||
rules: []
|
||||
};
|
||||
const result = component.buildGroupFromData(groupData);
|
||||
expect(result.get('join')?.value).toBe('or');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,890 @@
|
||||
import {Component, computed, effect, inject, OnInit} from '@angular/core';
|
||||
import {AbstractControl, FormArray, FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators} from '@angular/forms';
|
||||
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 {MagicShelf, MagicShelfService} from '../service/magic-shelf.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {MultiSelect} from 'primeng/multiselect';
|
||||
import {AutoComplete} from 'primeng/autocomplete';
|
||||
import {EMPTY_CHECK_OPERATORS, MULTI_VALUE_OPERATORS, RELATIVE_DATE_OPERATORS, parseValue, removeNulls, serializeDateRules} from '../service/magic-shelf-utils';
|
||||
import {IconPickerService, IconSelection} from '../../../shared/service/icon-picker.service';
|
||||
import {CheckboxChangeEvent, CheckboxModule} from "primeng/checkbox";
|
||||
import {UserService} from "../../settings/user-management/user.service";
|
||||
import {IconDisplayComponent} from '../../../shared/components/icon-display/icon-display.component';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {ShelfService} from '../../book/service/shelf.service';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
import {TextareaModule} from 'primeng/textarea';
|
||||
|
||||
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'
|
||||
| 'within_last'
|
||||
| 'older_than'
|
||||
| 'this_period'
|
||||
|
||||
export type RuleField =
|
||||
| 'library'
|
||||
| 'shelf'
|
||||
| 'title'
|
||||
| 'subtitle'
|
||||
| 'authors'
|
||||
| 'categories'
|
||||
| 'publisher'
|
||||
| 'publishedDate'
|
||||
| 'seriesName'
|
||||
| 'seriesNumber'
|
||||
| 'seriesTotal'
|
||||
| 'pageCount'
|
||||
| 'language'
|
||||
| 'isbn13'
|
||||
| 'isbn10'
|
||||
| 'amazonRating'
|
||||
| 'amazonReviewCount'
|
||||
| 'goodreadsRating'
|
||||
| 'goodreadsReviewCount'
|
||||
| 'hardcoverRating'
|
||||
| 'hardcoverReviewCount'
|
||||
| 'ranobedbRating'
|
||||
| 'personalRating'
|
||||
| 'fileType'
|
||||
| 'fileSize'
|
||||
| 'readStatus'
|
||||
| 'dateFinished'
|
||||
| 'lastReadTime'
|
||||
| 'metadataScore'
|
||||
| 'moods'
|
||||
| 'tags'
|
||||
| 'addedOn'
|
||||
| 'lubimyczytacRating'
|
||||
| 'description'
|
||||
| 'narrator'
|
||||
| 'ageRating'
|
||||
| 'contentRating'
|
||||
| 'audibleRating'
|
||||
| 'audibleReviewCount'
|
||||
| 'abridged'
|
||||
| 'audiobookDuration'
|
||||
| 'audiobookCodec'
|
||||
| 'audiobookChapterCount'
|
||||
| 'audiobookBitrate'
|
||||
| 'isPhysical'
|
||||
| 'seriesStatus'
|
||||
| 'seriesGaps'
|
||||
| 'seriesPosition'
|
||||
| 'readingProgress'
|
||||
| 'metadataPresence';
|
||||
|
||||
|
||||
interface FullFieldConfig {
|
||||
label: string;
|
||||
type?: FieldType;
|
||||
max?: number;
|
||||
}
|
||||
|
||||
type FieldType = 'number' | 'decimal' | 'date' | 'boolean' | undefined;
|
||||
|
||||
export interface Rule {
|
||||
field: RuleField;
|
||||
operator: RuleOperator;
|
||||
value: unknown;
|
||||
valueStart?: unknown;
|
||||
valueEnd?: unknown;
|
||||
}
|
||||
|
||||
export interface FieldConfig {
|
||||
type: FieldType;
|
||||
max?: number;
|
||||
}
|
||||
|
||||
export interface GroupRule {
|
||||
name: string;
|
||||
type: 'group';
|
||||
join: 'and' | 'or';
|
||||
rules: (Rule | GroupRule)[];
|
||||
}
|
||||
|
||||
export type RuleFormGroup = FormGroup<{
|
||||
field: FormControl<"" | RuleField | null>;
|
||||
operator: FormControl<"" | RuleOperator | null>;
|
||||
value: FormControl<string | null>;
|
||||
valueStart: FormControl<string | null>;
|
||||
valueEnd: FormControl<string | null>;
|
||||
}>;
|
||||
|
||||
export type GroupFormGroup = FormGroup<{
|
||||
type: FormControl<'group'>;
|
||||
join: FormControl<'and' | 'or'>;
|
||||
rules: FormArray<GroupFormGroup | RuleFormGroup>;
|
||||
}>;
|
||||
|
||||
const FIELD_CONFIGS: Record<RuleField, FullFieldConfig> = {
|
||||
library: {label: 'library'},
|
||||
shelf: {label: 'shelf'},
|
||||
readStatus: {label: 'readStatus'},
|
||||
dateFinished: {label: 'dateFinished', type: 'date'},
|
||||
lastReadTime: {label: 'lastReadTime', type: 'date'},
|
||||
metadataScore: {label: 'metadataScore', type: 'decimal', max: 100},
|
||||
title: {label: 'title'},
|
||||
authors: {label: 'authors'},
|
||||
categories: {label: 'categories'},
|
||||
moods: {label: 'moods'},
|
||||
tags: {label: 'tags'},
|
||||
publisher: {label: 'publisher'},
|
||||
publishedDate: {label: 'publishedDate', type: 'date'},
|
||||
personalRating: {label: 'personalRating', type: 'decimal', max: 10},
|
||||
pageCount: {label: 'pageCount', type: 'number'},
|
||||
language: {label: 'language'},
|
||||
isbn13: {label: 'isbn13'},
|
||||
isbn10: {label: 'isbn10'},
|
||||
seriesName: {label: 'seriesName'},
|
||||
seriesNumber: {label: 'seriesNumber', type: 'number'},
|
||||
seriesTotal: {label: 'seriesTotal', type: 'number'},
|
||||
fileSize: {label: 'fileSize', type: 'number'},
|
||||
fileType: {label: 'fileType'},
|
||||
subtitle: {label: 'subtitle'},
|
||||
amazonRating: {label: 'amazonRating', type: 'decimal', max: 5},
|
||||
amazonReviewCount: {label: 'amazonReviewCount', type: 'number'},
|
||||
goodreadsRating: {label: 'goodreadsRating', type: 'decimal', max: 5},
|
||||
goodreadsReviewCount: {label: 'goodreadsReviewCount', type: 'number'},
|
||||
hardcoverRating: {label: 'hardcoverRating', type: 'decimal', max: 5},
|
||||
hardcoverReviewCount: {label: 'hardcoverReviewCount', type: 'number'},
|
||||
ranobedbRating: {label: 'ranobedbRating', type: 'decimal', max: 5},
|
||||
addedOn: {label: 'addedOn', type: 'date'},
|
||||
lubimyczytacRating: {label: 'lubimyczytacRating', type: 'decimal', max: 5},
|
||||
description: {label: 'description'},
|
||||
narrator: {label: 'narrator'},
|
||||
ageRating: {label: 'ageRating', type: 'number'},
|
||||
contentRating: {label: 'contentRating'},
|
||||
audibleRating: {label: 'audibleRating', type: 'decimal', max: 5},
|
||||
audibleReviewCount: {label: 'audibleReviewCount', type: 'number'},
|
||||
abridged: {label: 'abridged', type: 'boolean'},
|
||||
audiobookDuration: {label: 'audiobookDuration', type: 'number'},
|
||||
audiobookCodec: {label: 'audiobookCodec'},
|
||||
audiobookChapterCount: {label: 'audiobookChapterCount', type: 'number'},
|
||||
audiobookBitrate: {label: 'audiobookBitrate', type: 'number'},
|
||||
isPhysical: {label: 'isPhysical', type: 'boolean'},
|
||||
seriesStatus: {label: 'seriesStatus'},
|
||||
seriesGaps: {label: 'seriesGaps'},
|
||||
seriesPosition: {label: 'seriesPosition'},
|
||||
readingProgress: {label: 'readingProgress', type: 'decimal', max: 100},
|
||||
metadataPresence: {label: 'metadataPresence'}
|
||||
};
|
||||
|
||||
interface FieldGroup {
|
||||
translationKey: string;
|
||||
fields: RuleField[];
|
||||
}
|
||||
|
||||
const FIELD_GROUPS: FieldGroup[] = [
|
||||
{ translationKey: 'organization', fields: ['library', 'shelf', 'readStatus', 'readingProgress'] },
|
||||
{ translationKey: 'bookInfo', fields: ['title', 'subtitle', 'description', 'authors', 'categories', 'publisher', 'language', 'pageCount', 'ageRating', 'contentRating'] },
|
||||
{ translationKey: 'series', fields: ['seriesName', 'seriesNumber', 'seriesTotal', 'seriesStatus', 'seriesGaps', 'seriesPosition'] },
|
||||
{ translationKey: 'dates', fields: ['publishedDate', 'dateFinished', 'lastReadTime', 'addedOn'] },
|
||||
{ translationKey: 'ratingsReviews', fields: ['personalRating', 'amazonRating', 'amazonReviewCount', 'goodreadsRating', 'goodreadsReviewCount', 'hardcoverRating', 'hardcoverReviewCount', 'ranobedbRating', 'lubimyczytacRating', 'audibleRating', 'audibleReviewCount'] },
|
||||
{ translationKey: 'qualityMetadata', fields: ['metadataScore', 'metadataPresence'] },
|
||||
{ translationKey: 'tagsMoods', fields: ['moods', 'tags'] },
|
||||
{ translationKey: 'audiobook', fields: ['narrator', 'abridged', 'audiobookDuration', 'audiobookCodec', 'audiobookChapterCount', 'audiobookBitrate'] },
|
||||
{ translationKey: 'fileIdentifiers', fields: ['fileType', 'fileSize', 'isbn13', 'isbn10', 'isPhysical'] }
|
||||
];
|
||||
|
||||
const READ_STATUS_KEYS: Record<string, string> = {
|
||||
UNREAD: 'unread',
|
||||
READING: 'reading',
|
||||
RE_READING: 'reReading',
|
||||
READ: 'read',
|
||||
PARTIALLY_READ: 'partiallyRead',
|
||||
PAUSED: 'paused',
|
||||
WONT_READ: 'wontRead',
|
||||
ABANDONED: 'abandoned',
|
||||
UNSET: 'unset'
|
||||
};
|
||||
|
||||
@Component({
|
||||
selector: 'app-magic-shelf',
|
||||
templateUrl: './magic-shelf-component.html',
|
||||
styleUrl: './magic-shelf-component.scss',
|
||||
standalone: true,
|
||||
imports: [
|
||||
ReactiveFormsModule,
|
||||
FormsModule,
|
||||
NgTemplateOutlet,
|
||||
InputText,
|
||||
Select,
|
||||
Button,
|
||||
DatePicker,
|
||||
InputNumber,
|
||||
MultiSelect,
|
||||
AutoComplete,
|
||||
CheckboxModule,
|
||||
IconDisplayComponent,
|
||||
Tooltip,
|
||||
TranslocoDirective,
|
||||
TextareaModule
|
||||
]
|
||||
})
|
||||
export class MagicShelfComponent implements OnInit {
|
||||
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly controlIds = new WeakMap<AbstractControl, string>();
|
||||
private controlIdCounter = 0;
|
||||
|
||||
numericFieldConfigMap = new Map<RuleField, FieldConfig>(
|
||||
Object.entries(FIELD_CONFIGS)
|
||||
.filter(([, config]) => config.type)
|
||||
.map(([key, config]) => [key as RuleField, {type: config.type!, max: config.max}])
|
||||
);
|
||||
|
||||
get conditionOptions(): { label: string; value: 'and' | 'or' }[] {
|
||||
return [
|
||||
{label: this.t.translate('magicShelf.conditions.and'), value: 'and'},
|
||||
{label: this.t.translate('magicShelf.conditions.or'), value: 'or'},
|
||||
];
|
||||
}
|
||||
|
||||
get fieldOptions() {
|
||||
return FIELD_GROUPS
|
||||
.map(group => ({
|
||||
label: this.t.translate(`magicShelf.fieldGroups.${group.translationKey}`),
|
||||
items: group.fields.map(field => {
|
||||
const config = FIELD_CONFIGS[field];
|
||||
const translationKey = field === 'categories' ? 'genre' : config.label;
|
||||
return {
|
||||
label: this.t.translate(`magicShelf.fields.${translationKey}`),
|
||||
value: field
|
||||
};
|
||||
})
|
||||
}))
|
||||
.filter(group => group.items.length > 0);
|
||||
}
|
||||
|
||||
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'},
|
||||
{label: 'FB2', value: 'fb2'},
|
||||
{label: 'MOBI', value: 'mobi'},
|
||||
{label: 'AZW3', value: 'azw3'},
|
||||
{label: 'M4B', value: 'm4b'},
|
||||
{label: 'M4A', value: 'm4a'},
|
||||
{label: 'MP3', value: 'mp3'},
|
||||
{label: 'OPUS', value: 'opus'}
|
||||
];
|
||||
|
||||
get readStatusOptions() {
|
||||
return Object.entries(ReadStatus).map(([key, value]) => ({
|
||||
label: this.t.translate(`magicShelf.readStatuses.${READ_STATUS_KEYS[key]}`),
|
||||
value
|
||||
}));
|
||||
}
|
||||
|
||||
get booleanOptions() {
|
||||
return [
|
||||
{label: this.t.translate('magicShelf.booleanValues.yes'), value: 'true'},
|
||||
{label: this.t.translate('magicShelf.booleanValues.no'), value: 'false'},
|
||||
];
|
||||
}
|
||||
|
||||
get contentRatingOptions() {
|
||||
return [
|
||||
{label: this.t.translate('magicShelf.contentRatings.everyone'), value: 'EVERYONE'},
|
||||
{label: this.t.translate('magicShelf.contentRatings.teen'), value: 'TEEN'},
|
||||
{label: this.t.translate('magicShelf.contentRatings.mature'), value: 'MATURE'},
|
||||
{label: this.t.translate('magicShelf.contentRatings.adult'), value: 'ADULT'},
|
||||
{label: this.t.translate('magicShelf.contentRatings.explicit'), value: 'EXPLICIT'},
|
||||
];
|
||||
}
|
||||
|
||||
get seriesStatusOptions() {
|
||||
return [
|
||||
{label: this.t.translate('magicShelf.seriesStatuses.reading'), value: 'reading'},
|
||||
{label: this.t.translate('magicShelf.seriesStatuses.completed'), value: 'completed'},
|
||||
{label: this.t.translate('magicShelf.seriesStatuses.ongoing'), value: 'ongoing'},
|
||||
{label: this.t.translate('magicShelf.seriesStatuses.notStarted'), value: 'not_started'},
|
||||
{label: this.t.translate('magicShelf.seriesStatuses.fullyRead'), value: 'fully_read'},
|
||||
];
|
||||
}
|
||||
|
||||
get seriesGapsOptions() {
|
||||
return [
|
||||
{label: this.t.translate('magicShelf.seriesGaps.anyGap'), value: 'any_gap'},
|
||||
{label: this.t.translate('magicShelf.seriesGaps.missingFirst'), value: 'missing_first'},
|
||||
{label: this.t.translate('magicShelf.seriesGaps.missingLatest'), value: 'missing_latest'},
|
||||
{label: this.t.translate('magicShelf.seriesGaps.duplicateNumber'), value: 'duplicate_number'},
|
||||
];
|
||||
}
|
||||
|
||||
get seriesPositionOptions() {
|
||||
return [
|
||||
{label: this.t.translate('magicShelf.seriesPositions.nextUnread'), value: 'next_unread'},
|
||||
{label: this.t.translate('magicShelf.seriesPositions.firstInSeries'), value: 'first_in_series'},
|
||||
{label: this.t.translate('magicShelf.seriesPositions.lastInSeries'), value: 'last_in_series'},
|
||||
];
|
||||
}
|
||||
|
||||
get metadataPresenceOptions() {
|
||||
return [
|
||||
{ label: this.t.translate('magicShelf.metadataFieldGroups.bookInfo'), items: [
|
||||
{label: this.t.translate('magicShelf.metadataFields.title'), value: 'title'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.subtitle'), value: 'subtitle'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.description'), value: 'description'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.thumbnailUrl'), value: 'thumbnailUrl'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.publisher'), value: 'publisher'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.publishedDate'), value: 'publishedDate'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.language'), value: 'language'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.pageCount'), value: 'pageCount'},
|
||||
]},
|
||||
{ label: this.t.translate('magicShelf.metadataFieldGroups.authorsCategories'), items: [
|
||||
{label: this.t.translate('magicShelf.metadataFields.authors'), value: 'authors'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.categories'), value: 'categories'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.moods'), value: 'moods'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.tags'), value: 'tags'},
|
||||
]},
|
||||
{ label: this.t.translate('magicShelf.metadataFieldGroups.series'), items: [
|
||||
{label: this.t.translate('magicShelf.metadataFields.seriesName'), value: 'seriesName'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.seriesNumber'), value: 'seriesNumber'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.seriesTotal'), value: 'seriesTotal'},
|
||||
]},
|
||||
{ label: this.t.translate('magicShelf.metadataFieldGroups.identifiers'), items: [
|
||||
{label: this.t.translate('magicShelf.metadataFields.isbn13'), value: 'isbn13'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.isbn10'), value: 'isbn10'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.asin'), value: 'asin'},
|
||||
]},
|
||||
{ label: this.t.translate('magicShelf.metadataFieldGroups.contentClassification'), items: [
|
||||
{label: this.t.translate('magicShelf.metadataFields.ageRating'), value: 'ageRating'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.contentRating'), value: 'contentRating'},
|
||||
]},
|
||||
{ label: this.t.translate('magicShelf.metadataFieldGroups.ratings'), items: [
|
||||
{label: this.t.translate('magicShelf.metadataFields.personalRating'), value: 'personalRating'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.amazonRating'), value: 'amazonRating'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.goodreadsRating'), value: 'goodreadsRating'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.hardcoverRating'), value: 'hardcoverRating'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.ranobedbRating'), value: 'ranobedbRating'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.lubimyczytacRating'), value: 'lubimyczytacRating'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.audibleRating'), value: 'audibleRating'},
|
||||
]},
|
||||
{ label: this.t.translate('magicShelf.metadataFieldGroups.reviewCounts'), items: [
|
||||
{label: this.t.translate('magicShelf.metadataFields.amazonReviewCount'), value: 'amazonReviewCount'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.goodreadsReviewCount'), value: 'goodreadsReviewCount'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.hardcoverReviewCount'), value: 'hardcoverReviewCount'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.audibleReviewCount'), value: 'audibleReviewCount'},
|
||||
]},
|
||||
{ label: this.t.translate('magicShelf.metadataFieldGroups.externalIds'), items: [
|
||||
{label: this.t.translate('magicShelf.metadataFields.goodreadsId'), value: 'goodreadsId'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.hardcoverId'), value: 'hardcoverId'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.googleId'), value: 'googleId'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.audibleId'), value: 'audibleId'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.lubimyczytacId'), value: 'lubimyczytacId'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.ranobedbId'), value: 'ranobedbId'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.comicvineId'), value: 'comicvineId'},
|
||||
]},
|
||||
{ label: this.t.translate('magicShelf.metadataFieldGroups.audiobook'), items: [
|
||||
{label: this.t.translate('magicShelf.metadataFields.narrator'), value: 'narrator'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.abridged'), value: 'abridged'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.audiobookDuration'), value: 'audiobookDuration'},
|
||||
]},
|
||||
{ label: this.t.translate('magicShelf.metadataFieldGroups.comic'), items: [
|
||||
{label: this.t.translate('magicShelf.metadataFields.comicCharacters'), value: 'comicCharacters'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.comicTeams'), value: 'comicTeams'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.comicLocations'), value: 'comicLocations'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.comicPencillers'), value: 'comicPencillers'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.comicInkers'), value: 'comicInkers'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.comicColorists'), value: 'comicColorists'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.comicLetterers'), value: 'comicLetterers'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.comicCoverArtists'), value: 'comicCoverArtists'},
|
||||
{label: this.t.translate('magicShelf.metadataFields.comicEditors'), value: 'comicEditors'},
|
||||
]},
|
||||
];
|
||||
}
|
||||
|
||||
get dateUnitOptions() {
|
||||
return [
|
||||
{label: this.t.translate('magicShelf.dateUnits.days'), value: 'days'},
|
||||
{label: this.t.translate('magicShelf.dateUnits.weeks'), value: 'weeks'},
|
||||
{label: this.t.translate('magicShelf.dateUnits.months'), value: 'months'},
|
||||
{label: this.t.translate('magicShelf.dateUnits.years'), value: 'years'},
|
||||
];
|
||||
}
|
||||
|
||||
get datePeriodOptions() {
|
||||
return [
|
||||
{label: this.t.translate('magicShelf.datePeriods.week'), value: 'week'},
|
||||
{label: this.t.translate('magicShelf.datePeriods.month'), value: 'month'},
|
||||
{label: this.t.translate('magicShelf.datePeriods.year'), value: 'year'},
|
||||
];
|
||||
}
|
||||
|
||||
libraryOptions = computed(() =>
|
||||
this.libraryService.libraries().map(library => ({
|
||||
label: library.name,
|
||||
value: library.id!
|
||||
}))
|
||||
);
|
||||
shelfOptions = computed(() =>
|
||||
this.shelfService.shelves().map(shelf => ({
|
||||
label: shelf.name,
|
||||
value: shelf.id!
|
||||
}))
|
||||
);
|
||||
categoryOptions = computed(() => {
|
||||
const categoriesSet = new Set<string>();
|
||||
this.bookService.books().forEach(book => {
|
||||
book.metadata?.categories?.forEach(category => categoriesSet.add(category));
|
||||
});
|
||||
|
||||
return Array.from(categoriesSet).map(category => ({
|
||||
label: category,
|
||||
value: category
|
||||
})).sort((a, b) => a.label.localeCompare(b.label));
|
||||
});
|
||||
|
||||
form = new FormGroup({
|
||||
name: new FormControl<string | null>(null),
|
||||
icon: new FormControl<string | null>(null),
|
||||
isPublic: new FormControl<boolean>(false),
|
||||
group: this.createGroup()
|
||||
});
|
||||
|
||||
shelfId: number | null = null;
|
||||
isAdmin: boolean = false;
|
||||
editMode!: boolean;
|
||||
showImportPanel = false;
|
||||
importJson = '';
|
||||
|
||||
libraryService = inject(LibraryService);
|
||||
shelfService = inject(ShelfService);
|
||||
bookService = inject(BookService);
|
||||
magicShelfService = inject(MagicShelfService);
|
||||
ref = inject(DynamicDialogRef);
|
||||
messageService = inject(MessageService);
|
||||
config = inject(DynamicDialogConfig);
|
||||
userService = inject(UserService);
|
||||
private iconPicker = inject(IconPickerService);
|
||||
|
||||
selectedIcon: IconSelection | null = null;
|
||||
private formInitializedFromShelf = false;
|
||||
|
||||
trackByFn(ruleCtrl: AbstractControl, index: number): unknown {
|
||||
return ruleCtrl ?? index;
|
||||
}
|
||||
|
||||
getControlId(control: AbstractControl | null, prefix: string): string {
|
||||
if (!control) {
|
||||
return `${prefix}-missing`;
|
||||
}
|
||||
|
||||
const existingId = this.controlIds.get(control);
|
||||
if (existingId) {
|
||||
return existingId;
|
||||
}
|
||||
|
||||
const newId = `${prefix}-${this.controlIdCounter++}`;
|
||||
this.controlIds.set(control, newId);
|
||||
return newId;
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.isAdmin = this.userService.getCurrentUser()?.permissions.admin ?? false;
|
||||
const id = this.config?.data?.id;
|
||||
this.editMode = !!this.config?.data?.editMode;
|
||||
|
||||
if (id) {
|
||||
this.shelfId = id;
|
||||
effect(() => {
|
||||
const shelf = this.magicShelfService.findShelfById(id);
|
||||
if (!shelf || this.formInitializedFromShelf) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.initializeForm(shelf);
|
||||
this.formInitializedFromShelf = true;
|
||||
});
|
||||
} else {
|
||||
this.initializeForm();
|
||||
this.formInitializedFromShelf = true;
|
||||
}
|
||||
}
|
||||
|
||||
private initializeForm(shelf?: MagicShelf): void {
|
||||
const iconValue = shelf?.icon ?? null;
|
||||
|
||||
this.form = new FormGroup({
|
||||
name: new FormControl<string | null>(shelf?.name ?? null, {nonNullable: true, validators: [Validators.required]}),
|
||||
icon: new FormControl<string | null>(iconValue),
|
||||
isPublic: new FormControl<boolean>(shelf?.isPublic ?? false),
|
||||
group: shelf?.filterJson ? this.buildGroupFromData(JSON.parse(shelf.filterJson)) : this.createGroup()
|
||||
});
|
||||
|
||||
if (iconValue) {
|
||||
this.selectedIcon = iconValue.startsWith('pi ')
|
||||
? {type: 'PRIME_NG', value: iconValue}
|
||||
: {type: 'CUSTOM_SVG', value: iconValue};
|
||||
} else {
|
||||
this.selectedIcon = null;
|
||||
}
|
||||
}
|
||||
|
||||
buildGroupFromData(data: GroupRule): GroupFormGroup {
|
||||
const rulesArray = new FormArray<FormGroup>([]);
|
||||
|
||||
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<GroupFormGroup | RuleFormGroup>
|
||||
}) as GroupFormGroup;
|
||||
}
|
||||
|
||||
buildRuleFromData(data: Rule): RuleFormGroup {
|
||||
const config = FIELD_CONFIGS[data.field];
|
||||
const type = config?.type;
|
||||
const isRelativeDate = RELATIVE_DATE_OPERATORS.includes(data.operator);
|
||||
|
||||
let value, valueStart, valueEnd;
|
||||
if (isRelativeDate) {
|
||||
value = data.operator === 'this_period' ? data.value : parseValue(data.value, 'number');
|
||||
valueStart = null;
|
||||
valueEnd = data.operator !== 'this_period' ? data.valueEnd : null;
|
||||
} else {
|
||||
value = parseValue(data.value, type);
|
||||
valueStart = parseValue(data.valueStart, type);
|
||||
valueEnd = parseValue(data.valueEnd, type);
|
||||
}
|
||||
|
||||
return new FormGroup({
|
||||
field: new FormControl<RuleField>(data.field),
|
||||
operator: new FormControl<RuleOperator>(data.operator),
|
||||
value: new FormControl(value),
|
||||
valueStart: new FormControl(valueStart),
|
||||
valueEnd: new FormControl(valueEnd),
|
||||
}) as RuleFormGroup;
|
||||
}
|
||||
|
||||
get group(): GroupFormGroup {
|
||||
return this.form.get('group') as GroupFormGroup;
|
||||
}
|
||||
|
||||
getOperatorOptionsForField(field: RuleField | null | undefined) {
|
||||
const baseOperators = [
|
||||
{label: this.t.translate('magicShelf.operators.equals'), value: 'equals'},
|
||||
{label: this.t.translate('magicShelf.operators.notEqual'), value: 'not_equals'},
|
||||
{label: this.t.translate('magicShelf.operators.empty'), value: 'is_empty'},
|
||||
{label: this.t.translate('magicShelf.operators.notEmpty'), value: 'is_not_empty'},
|
||||
];
|
||||
|
||||
const multiValueOperators = [
|
||||
{label: this.t.translate('magicShelf.operators.includesAny'), value: 'includes_any'},
|
||||
{label: this.t.translate('magicShelf.operators.excludesAll'), value: 'excludes_all'},
|
||||
{label: this.t.translate('magicShelf.operators.includesAll'), value: 'includes_all'},
|
||||
];
|
||||
|
||||
const textOperators = [
|
||||
{label: this.t.translate('magicShelf.operators.contains'), value: 'contains'},
|
||||
{label: this.t.translate('magicShelf.operators.doesNotContain'), value: 'does_not_contain'},
|
||||
{label: this.t.translate('magicShelf.operators.startsWith'), value: 'starts_with'},
|
||||
{label: this.t.translate('magicShelf.operators.endsWith'), value: 'ends_with'},
|
||||
];
|
||||
|
||||
const comparisonOperators = [
|
||||
{label: this.t.translate('magicShelf.operators.greaterThan'), value: 'greater_than'},
|
||||
{label: this.t.translate('magicShelf.operators.greaterOrEqual'), value: 'greater_than_equal_to'},
|
||||
{label: this.t.translate('magicShelf.operators.lessThan'), value: 'less_than'},
|
||||
{label: this.t.translate('magicShelf.operators.lessOrEqual'), value: 'less_than_equal_to'},
|
||||
{label: this.t.translate('magicShelf.operators.between'), value: 'in_between'},
|
||||
];
|
||||
|
||||
const relativeDateOperators = [
|
||||
{label: this.t.translate('magicShelf.operators.withinLast'), value: 'within_last'},
|
||||
{label: this.t.translate('magicShelf.operators.olderThan'), value: 'older_than'},
|
||||
{label: this.t.translate('magicShelf.operators.thisPeriod'), value: 'this_period'},
|
||||
];
|
||||
|
||||
if (!field) return [...baseOperators, ...multiValueOperators];
|
||||
|
||||
const config = FIELD_CONFIGS[field];
|
||||
|
||||
if (config.type === 'boolean') {
|
||||
return baseOperators;
|
||||
}
|
||||
|
||||
// Composite fields: only is/isNot or has/hasNot
|
||||
if (field === 'seriesStatus' || field === 'seriesPosition') {
|
||||
return [
|
||||
{label: this.t.translate('magicShelf.operators.is'), value: 'equals'},
|
||||
{label: this.t.translate('magicShelf.operators.isNot'), value: 'not_equals'},
|
||||
];
|
||||
}
|
||||
if (field === 'seriesGaps' || field === 'metadataPresence') {
|
||||
return [
|
||||
{label: this.t.translate('magicShelf.operators.has'), value: 'equals'},
|
||||
{label: this.t.translate('magicShelf.operators.hasNot'), value: 'not_equals'},
|
||||
];
|
||||
}
|
||||
|
||||
const isMultiValueField = ['library', 'shelf', 'authors', 'categories', 'moods', 'tags', 'readStatus', 'fileType', 'language', 'title', 'subtitle', 'publisher', 'seriesName', 'isbn13', 'isbn10', 'contentRating', 'narrator', 'description'].includes(field);
|
||||
const operators = [...baseOperators];
|
||||
|
||||
if (isMultiValueField) {
|
||||
operators.push(...multiValueOperators);
|
||||
}
|
||||
|
||||
const isTextEligible = !['library', 'shelf', 'readStatus', 'fileType', 'contentRating'].includes(field);
|
||||
|
||||
if (config.type === 'date') {
|
||||
operators.push(...comparisonOperators, ...relativeDateOperators);
|
||||
} else if (config.type === 'number' || config.type === 'decimal') {
|
||||
operators.push(...comparisonOperators);
|
||||
} else if (isTextEligible) {
|
||||
operators.push(...textOperators);
|
||||
}
|
||||
|
||||
return operators;
|
||||
}
|
||||
|
||||
createRule(): RuleFormGroup {
|
||||
return new FormGroup({
|
||||
field: new FormControl<RuleField | ''>(''),
|
||||
operator: new FormControl<RuleOperator | ''>(''),
|
||||
value: new FormControl<string | null>(null),
|
||||
valueStart: new FormControl<string | null>(null),
|
||||
valueEnd: new FormControl<string | null>(null),
|
||||
}) as RuleFormGroup;
|
||||
}
|
||||
|
||||
createGroup(): GroupFormGroup {
|
||||
return new FormGroup({
|
||||
type: new FormControl<'group'>('group' as const),
|
||||
join: new FormControl<'and' | 'or'>('and' as 'and' | 'or'),
|
||||
rules: new FormArray([] as (GroupFormGroup | RuleFormGroup)[]),
|
||||
}) 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 (operator === 'within_last' || operator === 'older_than') {
|
||||
valueCtrl?.setValue(null);
|
||||
valueStartCtrl?.setValue(null);
|
||||
valueEndCtrl?.setValue('days');
|
||||
} else if (operator === 'this_period') {
|
||||
valueCtrl?.setValue(null);
|
||||
valueStartCtrl?.setValue(null);
|
||||
valueEndCtrl?.setValue(null);
|
||||
} else 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() {
|
||||
this.iconPicker.open().subscribe(icon => {
|
||||
if (icon) {
|
||||
this.selectedIcon = icon;
|
||||
const iconValue = icon.type === 'CUSTOM_SVG'
|
||||
? icon.value
|
||||
: icon.value;
|
||||
this.form.get('icon')?.setValue(iconValue);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
clearSelectedIcon(): void {
|
||||
this.selectedIcon = null;
|
||||
this.form.get('icon')?.setValue(null);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onAutoCompleteBlur(formControl: { value: unknown; setValue: (value: unknown[]) => void }, event: Event) {
|
||||
const target = event.target as HTMLInputElement | null;
|
||||
const inputValue = target?.value?.trim();
|
||||
if (inputValue) {
|
||||
const currentValue = formControl.value || [];
|
||||
const values = Array.isArray(currentValue) ? currentValue :
|
||||
typeof currentValue === 'string' && currentValue ? currentValue.split(',').map((v: string) => v.trim()) : [];
|
||||
|
||||
if (!values.includes(inputValue)) {
|
||||
values.push(inputValue);
|
||||
formControl.setValue(values);
|
||||
}
|
||||
if (target) {
|
||||
target.value = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onIsPublicChange(event: CheckboxChangeEvent): void {
|
||||
const checked = event.checked ?? false;
|
||||
this.form.get('isPublic')?.setValue(checked);
|
||||
}
|
||||
|
||||
toggleImportPanel() {
|
||||
this.showImportPanel = !this.showImportPanel;
|
||||
if (this.showImportPanel) {
|
||||
this.importJson = '';
|
||||
}
|
||||
}
|
||||
|
||||
applyImportedJson() {
|
||||
const trimmed = this.importJson.trim();
|
||||
if (!trimmed) {
|
||||
this.messageService.add({severity: 'warn', summary: this.t.translate('magicShelf.toast.validationErrorSummary'), detail: this.t.translate('magicShelf.importJson.emptyError')});
|
||||
return;
|
||||
}
|
||||
|
||||
let parsed: GroupRule;
|
||||
try {
|
||||
parsed = JSON.parse(trimmed);
|
||||
} catch {
|
||||
this.messageService.add({severity: 'error', summary: this.t.translate('magicShelf.toast.errorSummary'), detail: this.t.translate('magicShelf.importJson.parseError')});
|
||||
return;
|
||||
}
|
||||
|
||||
if (parsed.type !== 'group' || !Array.isArray(parsed.rules)) {
|
||||
this.messageService.add({severity: 'error', summary: this.t.translate('magicShelf.toast.errorSummary'), detail: this.t.translate('magicShelf.importJson.structureError')});
|
||||
return;
|
||||
}
|
||||
|
||||
const builtGroup = this.buildGroupFromData(parsed);
|
||||
this.form.setControl('group', builtGroup);
|
||||
this.showImportPanel = false;
|
||||
this.importJson = '';
|
||||
this.messageService.add({severity: 'success', summary: this.t.translate('magicShelf.toast.successSummary'), detail: this.t.translate('magicShelf.importJson.successDetail')});
|
||||
}
|
||||
|
||||
submit() {
|
||||
if (!this.hasAtLeastOneValidRule(this.group)) {
|
||||
this.messageService.add({severity: 'warn', summary: this.t.translate('magicShelf.toast.validationErrorSummary'), detail: this.t.translate('magicShelf.toast.validationErrorDetail')});
|
||||
return;
|
||||
}
|
||||
|
||||
const value = this.form.value as { name: string | null; icon: string | null; group: GroupRule, isPublic: boolean | null };
|
||||
const cleanedGroup = removeNulls(serializeDateRules(value.group));
|
||||
|
||||
this.magicShelfService.saveShelf({
|
||||
id: this.shelfId ?? undefined,
|
||||
name: value.name,
|
||||
icon: value.icon,
|
||||
iconType: this.selectedIcon?.type,
|
||||
isPublic: !!value.isPublic,
|
||||
group: cleanedGroup
|
||||
}).subscribe({
|
||||
next: (savedShelf) => {
|
||||
this.messageService.add({severity: 'success', summary: this.t.translate('magicShelf.toast.successSummary'), detail: this.t.translate('magicShelf.toast.successDetail')});
|
||||
if (savedShelf?.id) {
|
||||
this.shelfId = savedShelf.id;
|
||||
this.form.patchValue({
|
||||
name: savedShelf.name,
|
||||
icon: savedShelf.icon,
|
||||
isPublic: savedShelf.isPublic
|
||||
});
|
||||
}
|
||||
},
|
||||
error: (err) => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('magicShelf.toast.errorSummary'),
|
||||
detail: err?.error?.message || this.t.translate('magicShelf.toast.errorDetailDefault')
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
cancel() {
|
||||
this.ref.close();
|
||||
}
|
||||
}
|
||||
+533
@@ -0,0 +1,533 @@
|
||||
import {beforeEach, describe, expect, it} from 'vitest';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {BookRuleEvaluatorService} from './book-rule-evaluator.service';
|
||||
import {Book, ReadStatus} from '../../book/model/book.model';
|
||||
import {GroupRule} from '../component/magic-shelf-component';
|
||||
|
||||
describe('BookRuleEvaluatorService - metadataPresence', () => {
|
||||
let service: BookRuleEvaluatorService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
service = TestBed.inject(BookRuleEvaluatorService);
|
||||
});
|
||||
|
||||
const createBook = (overrides: Partial<Book> = {}): Book => ({
|
||||
id: 1,
|
||||
bookType: 'EPUB',
|
||||
libraryId: 1,
|
||||
libraryName: 'Test Library',
|
||||
fileName: 'test.epub',
|
||||
filePath: '/path/to/test.epub',
|
||||
readStatus: ReadStatus.UNREAD,
|
||||
shelves: [],
|
||||
metadata: {
|
||||
bookId: 1,
|
||||
title: 'Test Book',
|
||||
authors: ['Test Author'],
|
||||
categories: ['Fiction'],
|
||||
language: 'en'
|
||||
},
|
||||
...overrides
|
||||
});
|
||||
|
||||
const rule = (operator: string, value: string): GroupRule => ({
|
||||
name: 'test', type: 'group', join: 'and',
|
||||
rules: [{field: 'metadataPresence', operator, value} as never]
|
||||
});
|
||||
|
||||
describe('string fields', () => {
|
||||
it('should detect present title', () => {
|
||||
const book = createBook({metadata: {bookId: 1, title: 'A Book'}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'title'))).toBe(true);
|
||||
expect(service.evaluateGroup(book, rule('not_equals', 'title'))).toBe(false);
|
||||
});
|
||||
|
||||
it('should detect missing title', () => {
|
||||
const book = createBook({metadata: {bookId: 1, title: undefined}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'title'))).toBe(false);
|
||||
expect(service.evaluateGroup(book, rule('not_equals', 'title'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should treat empty string as absent', () => {
|
||||
const book = createBook({metadata: {bookId: 1, title: ''}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'title'))).toBe(false);
|
||||
});
|
||||
|
||||
it('should treat whitespace-only string as absent', () => {
|
||||
const book = createBook({metadata: {bookId: 1, title: ' '}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'title'))).toBe(false);
|
||||
});
|
||||
|
||||
it('should detect present subtitle', () => {
|
||||
const book = createBook({metadata: {bookId: 1, subtitle: 'A Novel'}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'subtitle'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect missing subtitle', () => {
|
||||
const book = createBook({metadata: {bookId: 1}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'subtitle'))).toBe(false);
|
||||
});
|
||||
|
||||
it('should detect present description', () => {
|
||||
const book = createBook({metadata: {bookId: 1, description: 'A tale of adventure'}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'description'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect missing description', () => {
|
||||
const book = createBook({metadata: {bookId: 1}});
|
||||
expect(service.evaluateGroup(book, rule('not_equals', 'description'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present publisher', () => {
|
||||
const book = createBook({metadata: {bookId: 1, publisher: 'Tor Books'}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'publisher'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present publishedDate', () => {
|
||||
const book = createBook({metadata: {bookId: 1, publishedDate: '2024-01-01'}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'publishedDate'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect missing publishedDate', () => {
|
||||
const book = createBook({metadata: {bookId: 1}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'publishedDate'))).toBe(false);
|
||||
});
|
||||
|
||||
it('should detect present language', () => {
|
||||
const book = createBook({metadata: {bookId: 1, language: 'en'}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'language'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present thumbnailUrl', () => {
|
||||
const book = createBook({metadata: {bookId: 1, thumbnailUrl: 'https://example.com/cover.jpg'}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'thumbnailUrl'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect missing thumbnailUrl', () => {
|
||||
const book = createBook({metadata: {bookId: 1}});
|
||||
expect(service.evaluateGroup(book, rule('not_equals', 'thumbnailUrl'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present narrator', () => {
|
||||
const book = createBook({metadata: {bookId: 1, narrator: 'Stephen Fry'}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'narrator'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present contentRating', () => {
|
||||
const book = createBook({metadata: {bookId: 1, contentRating: 'MATURE'}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'contentRating'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present seriesName', () => {
|
||||
const book = createBook({metadata: {bookId: 1, seriesName: 'Dune'}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'seriesName'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect missing seriesName', () => {
|
||||
const book = createBook({metadata: {bookId: 1}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'seriesName'))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('identifier fields', () => {
|
||||
it('should detect present isbn13', () => {
|
||||
const book = createBook({metadata: {bookId: 1, isbn13: '9780123456789'}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'isbn13'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect missing isbn13', () => {
|
||||
const book = createBook({metadata: {bookId: 1}});
|
||||
expect(service.evaluateGroup(book, rule('not_equals', 'isbn13'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present isbn10', () => {
|
||||
const book = createBook({metadata: {bookId: 1, isbn10: '0123456789'}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'isbn10'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present asin', () => {
|
||||
const book = createBook({metadata: {bookId: 1, asin: 'B08N5WRWNW'}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'asin'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect missing asin', () => {
|
||||
const book = createBook({metadata: {bookId: 1}});
|
||||
expect(service.evaluateGroup(book, rule('not_equals', 'asin'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('numeric fields', () => {
|
||||
it('should detect present pageCount', () => {
|
||||
const book = createBook({metadata: {bookId: 1, pageCount: 350}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'pageCount'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect missing pageCount', () => {
|
||||
const book = createBook({metadata: {bookId: 1}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'pageCount'))).toBe(false);
|
||||
});
|
||||
|
||||
it('should treat zero pageCount as present', () => {
|
||||
const book = createBook({metadata: {bookId: 1, pageCount: 0}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'pageCount'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present seriesNumber', () => {
|
||||
const book = createBook({metadata: {bookId: 1, seriesNumber: 3}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'seriesNumber'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present seriesTotal', () => {
|
||||
const book = createBook({metadata: {bookId: 1, seriesTotal: 10}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'seriesTotal'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present ageRating', () => {
|
||||
const book = createBook({metadata: {bookId: 1, ageRating: 16}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'ageRating'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('array fields', () => {
|
||||
it('should detect present authors', () => {
|
||||
const book = createBook({metadata: {bookId: 1, authors: ['Author One']}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'authors'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect empty authors as absent', () => {
|
||||
const book = createBook({metadata: {bookId: 1, authors: []}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'authors'))).toBe(false);
|
||||
expect(service.evaluateGroup(book, rule('not_equals', 'authors'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect missing authors (undefined) as absent', () => {
|
||||
const book = createBook({metadata: {bookId: 1, authors: undefined}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'authors'))).toBe(false);
|
||||
});
|
||||
|
||||
it('should detect present categories', () => {
|
||||
const book = createBook({metadata: {bookId: 1, categories: ['Fantasy']}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'categories'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect empty categories as absent', () => {
|
||||
const book = createBook({metadata: {bookId: 1, categories: []}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'categories'))).toBe(false);
|
||||
});
|
||||
|
||||
it('should detect present moods', () => {
|
||||
const book = createBook({metadata: {bookId: 1, moods: ['Dark', 'Atmospheric']}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'moods'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect missing moods as absent', () => {
|
||||
const book = createBook({metadata: {bookId: 1}});
|
||||
expect(service.evaluateGroup(book, rule('not_equals', 'moods'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present tags', () => {
|
||||
const book = createBook({metadata: {bookId: 1, tags: ['favorite']}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'tags'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect missing tags as absent', () => {
|
||||
const book = createBook({metadata: {bookId: 1}});
|
||||
expect(service.evaluateGroup(book, rule('not_equals', 'tags'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('rating fields', () => {
|
||||
it('should detect present personalRating', () => {
|
||||
const book = createBook({personalRating: 8});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'personalRating'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect missing personalRating', () => {
|
||||
const book = createBook({personalRating: undefined});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'personalRating'))).toBe(false);
|
||||
expect(service.evaluateGroup(book, rule('not_equals', 'personalRating'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present amazonRating', () => {
|
||||
const book = createBook({metadata: {bookId: 1, amazonRating: 4.5}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'amazonRating'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect missing amazonRating', () => {
|
||||
const book = createBook({metadata: {bookId: 1}});
|
||||
expect(service.evaluateGroup(book, rule('not_equals', 'amazonRating'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present goodreadsRating', () => {
|
||||
const book = createBook({metadata: {bookId: 1, goodreadsRating: 4.1}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'goodreadsRating'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present hardcoverRating', () => {
|
||||
const book = createBook({metadata: {bookId: 1, hardcoverRating: 3.9}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'hardcoverRating'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present ranobedbRating', () => {
|
||||
const book = createBook({metadata: {bookId: 1, ranobedbRating: 4.0}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'ranobedbRating'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present lubimyczytacRating', () => {
|
||||
const book = createBook({metadata: {bookId: 1, lubimyczytacRating: 4.2}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'lubimyczytacRating'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present audibleRating', () => {
|
||||
const book = createBook({metadata: {bookId: 1, audibleRating: 4.7}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'audibleRating'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('review count fields', () => {
|
||||
it('should detect present amazonReviewCount', () => {
|
||||
const book = createBook({metadata: {bookId: 1, amazonReviewCount: 1200}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'amazonReviewCount'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect missing amazonReviewCount', () => {
|
||||
const book = createBook({metadata: {bookId: 1}});
|
||||
expect(service.evaluateGroup(book, rule('not_equals', 'amazonReviewCount'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present goodreadsReviewCount', () => {
|
||||
const book = createBook({metadata: {bookId: 1, goodreadsReviewCount: 5000}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'goodreadsReviewCount'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present hardcoverReviewCount', () => {
|
||||
const book = createBook({metadata: {bookId: 1, hardcoverReviewCount: 300}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'hardcoverReviewCount'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present audibleReviewCount', () => {
|
||||
const book = createBook({metadata: {bookId: 1, audibleReviewCount: 500}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'audibleReviewCount'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('external ID fields', () => {
|
||||
it('should detect present goodreadsId', () => {
|
||||
const book = createBook({metadata: {bookId: 1, goodreadsId: '12345'}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'goodreadsId'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect missing goodreadsId', () => {
|
||||
const book = createBook({metadata: {bookId: 1}});
|
||||
expect(service.evaluateGroup(book, rule('not_equals', 'goodreadsId'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present hardcoverId', () => {
|
||||
const book = createBook({metadata: {bookId: 1, hardcoverId: 'hc-123'}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'hardcoverId'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present googleId', () => {
|
||||
const book = createBook({metadata: {bookId: 1, googleId: 'gid-456'}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'googleId'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present audibleId', () => {
|
||||
const book = createBook({metadata: {bookId: 1, audibleId: 'aud-789'}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'audibleId'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present lubimyczytacId', () => {
|
||||
const book = createBook({metadata: {bookId: 1, lubimyczytacId: 'lub-321'}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'lubimyczytacId'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present ranobedbId', () => {
|
||||
const book = createBook({metadata: {bookId: 1, ranobedbId: 'ran-654'}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'ranobedbId'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present comicvineId', () => {
|
||||
const book = createBook({metadata: {bookId: 1, comicvineId: 'cv-987'}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'comicvineId'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect missing comicvineId', () => {
|
||||
const book = createBook({metadata: {bookId: 1}});
|
||||
expect(service.evaluateGroup(book, rule('not_equals', 'comicvineId'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('boolean fields', () => {
|
||||
it('should detect present abridged (true)', () => {
|
||||
const book = createBook({metadata: {bookId: 1, abridged: true}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'abridged'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present abridged (false)', () => {
|
||||
const book = createBook({metadata: {bookId: 1, abridged: false}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'abridged'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect missing abridged', () => {
|
||||
const book = createBook({metadata: {bookId: 1}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'abridged'))).toBe(false);
|
||||
expect(service.evaluateGroup(book, rule('not_equals', 'abridged'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('audiobook fields', () => {
|
||||
it('should detect present audiobookDuration', () => {
|
||||
const book = createBook({metadata: {bookId: 1, audiobookMetadata: {durationSeconds: 36000}}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'audiobookDuration'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect missing audiobookDuration (no audiobookMetadata)', () => {
|
||||
const book = createBook({metadata: {bookId: 1}});
|
||||
expect(service.evaluateGroup(book, rule('not_equals', 'audiobookDuration'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect zero audiobookDuration as present', () => {
|
||||
const book = createBook({metadata: {bookId: 1, audiobookMetadata: {durationSeconds: 0}}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'audiobookDuration'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('comic metadata fields', () => {
|
||||
it('should detect present comicCharacters', () => {
|
||||
const book = createBook({metadata: {bookId: 1, comicMetadata: {characters: ['Batman', 'Joker']}}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'comicCharacters'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect empty comicCharacters as absent', () => {
|
||||
const book = createBook({metadata: {bookId: 1, comicMetadata: {characters: []}}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'comicCharacters'))).toBe(false);
|
||||
});
|
||||
|
||||
it('should detect missing comicCharacters (no comicMetadata)', () => {
|
||||
const book = createBook({metadata: {bookId: 1}});
|
||||
expect(service.evaluateGroup(book, rule('not_equals', 'comicCharacters'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present comicTeams', () => {
|
||||
const book = createBook({metadata: {bookId: 1, comicMetadata: {teams: ['Justice League']}}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'comicTeams'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present comicLocations', () => {
|
||||
const book = createBook({metadata: {bookId: 1, comicMetadata: {locations: ['Gotham City']}}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'comicLocations'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present comicPencillers', () => {
|
||||
const book = createBook({metadata: {bookId: 1, comicMetadata: {pencillers: ['Jim Lee']}}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'comicPencillers'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present comicInkers', () => {
|
||||
const book = createBook({metadata: {bookId: 1, comicMetadata: {inkers: ['Scott Williams']}}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'comicInkers'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present comicColorists', () => {
|
||||
const book = createBook({metadata: {bookId: 1, comicMetadata: {colorists: ['Alex Sinclair']}}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'comicColorists'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present comicLetterers', () => {
|
||||
const book = createBook({metadata: {bookId: 1, comicMetadata: {letterers: ['Todd Klein']}}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'comicLetterers'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present comicCoverArtists', () => {
|
||||
const book = createBook({metadata: {bookId: 1, comicMetadata: {coverArtists: ['Alex Ross']}}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'comicCoverArtists'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect present comicEditors', () => {
|
||||
const book = createBook({metadata: {bookId: 1, comicMetadata: {editors: ['Mark Doyle']}}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'comicEditors'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('should return false for unknown metadata field', () => {
|
||||
const book = createBook();
|
||||
expect(service.evaluateGroup(book, rule('equals', 'nonExistentField'))).toBe(false);
|
||||
});
|
||||
|
||||
it('should handle book with no metadata', () => {
|
||||
const book = createBook({metadata: undefined});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'title'))).toBe(false);
|
||||
expect(service.evaluateGroup(book, rule('not_equals', 'title'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle non-string rule value gracefully', () => {
|
||||
const book = createBook({metadata: {bookId: 1, title: 'Test'}});
|
||||
const g: GroupRule = {
|
||||
name: 'test', type: 'group', join: 'and',
|
||||
rules: [{field: 'metadataPresence', operator: 'equals', value: null} as never]
|
||||
};
|
||||
expect(service.evaluateGroup(book, g)).toBe(false);
|
||||
});
|
||||
|
||||
it('should not require allBooks parameter', () => {
|
||||
const book = createBook({metadata: {bookId: 1, title: 'Test'}});
|
||||
expect(service.evaluateGroup(book, rule('equals', 'title'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('combined rules', () => {
|
||||
it('should match books missing cover OR description', () => {
|
||||
const bookNoCover = createBook({metadata: {bookId: 1, title: 'Test', description: 'Has desc'}});
|
||||
const bookNoDesc = createBook({metadata: {bookId: 2, title: 'Test', thumbnailUrl: 'http://cover.jpg'}});
|
||||
const bookHasBoth = createBook({metadata: {bookId: 3, title: 'Test', description: 'Has desc', thumbnailUrl: 'http://cover.jpg'}});
|
||||
|
||||
const group: GroupRule = {
|
||||
name: 'test', type: 'group', join: 'or',
|
||||
rules: [
|
||||
{field: 'metadataPresence', operator: 'not_equals', value: 'thumbnailUrl'},
|
||||
{field: 'metadataPresence', operator: 'not_equals', value: 'description'}
|
||||
]
|
||||
};
|
||||
|
||||
expect(service.evaluateGroup(bookNoCover, group)).toBe(true);
|
||||
expect(service.evaluateGroup(bookNoDesc, group)).toBe(true);
|
||||
expect(service.evaluateGroup(bookHasBoth, group)).toBe(false);
|
||||
});
|
||||
|
||||
it('should match books with complete identifiers', () => {
|
||||
const bookComplete = createBook({metadata: {bookId: 1, isbn13: '9780123456789', goodreadsId: '12345'}});
|
||||
const bookPartial = createBook({metadata: {bookId: 2, isbn13: '9780123456789'}});
|
||||
|
||||
const group: GroupRule = {
|
||||
name: 'test', type: 'group', join: 'and',
|
||||
rules: [
|
||||
{field: 'metadataPresence', operator: 'equals', value: 'isbn13'},
|
||||
{field: 'metadataPresence', operator: 'equals', value: 'goodreadsId'}
|
||||
]
|
||||
};
|
||||
|
||||
expect(service.evaluateGroup(bookComplete, group)).toBe(true);
|
||||
expect(service.evaluateGroup(bookPartial, group)).toBe(false);
|
||||
});
|
||||
|
||||
it('should work with non-metadataPresence rules in same group', () => {
|
||||
const book = createBook({
|
||||
readStatus: ReadStatus.UNREAD,
|
||||
metadata: {bookId: 1, title: 'Test'}
|
||||
});
|
||||
|
||||
const group: GroupRule = {
|
||||
name: 'test', type: 'group', join: 'and',
|
||||
rules: [
|
||||
{field: 'readStatus', operator: 'equals', value: 'UNREAD'},
|
||||
{field: 'metadataPresence', operator: 'not_equals', value: 'thumbnailUrl'}
|
||||
]
|
||||
};
|
||||
|
||||
expect(service.evaluateGroup(book, group)).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,591 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {Book} from '../../book/model/book.model';
|
||||
import {GroupRule, Rule, RuleField} from '../component/magic-shelf-component';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class BookRuleEvaluatorService {
|
||||
|
||||
evaluateGroup(book: Book, group: GroupRule, allBooks: Book[] = []): boolean {
|
||||
const results = group.rules.map(rule => {
|
||||
if ('type' in rule && rule.type === 'group') {
|
||||
return this.evaluateGroup(book, rule as GroupRule, allBooks);
|
||||
} else {
|
||||
return this.evaluateRule(book, rule as Rule, allBooks);
|
||||
}
|
||||
});
|
||||
return group.join === 'and' ? results.every(Boolean) : results.some(Boolean);
|
||||
}
|
||||
|
||||
private evaluateRule(book: Book, rule: Rule, allBooks: Book[]): boolean {
|
||||
if (rule.field === 'metadataPresence') {
|
||||
return this.evaluateMetadataPresence(book, rule);
|
||||
}
|
||||
|
||||
if (rule.field === 'seriesStatus' || rule.field === 'seriesGaps' || rule.field === 'seriesPosition') {
|
||||
return this.evaluateCompositeField(book, rule, allBooks);
|
||||
}
|
||||
|
||||
const rawValue = this.extractBookValue(book, rule.field);
|
||||
|
||||
const normalize = (val: unknown): unknown => {
|
||||
if (val === null || val === undefined) return val;
|
||||
if (val instanceof Date) return val;
|
||||
if (typeof val === 'boolean') return String(val);
|
||||
if (typeof val === 'string') {
|
||||
const date = new Date(val);
|
||||
if (!isNaN(date.getTime())) return date;
|
||||
return val.toLowerCase();
|
||||
}
|
||||
return val;
|
||||
};
|
||||
|
||||
const value = normalize(rawValue);
|
||||
const ruleVal = normalize(rule.value);
|
||||
const ruleStart = normalize(rule.valueStart);
|
||||
const ruleEnd = normalize(rule.valueEnd);
|
||||
|
||||
const mapFileTypeValue = (uiValue: string): string => {
|
||||
const lowerValue = uiValue.toLowerCase();
|
||||
switch (lowerValue) {
|
||||
case 'cbr':
|
||||
case 'cbz':
|
||||
case 'cb7':
|
||||
return 'cbx';
|
||||
case 'azw':
|
||||
return 'azw3';
|
||||
default:
|
||||
return lowerValue;
|
||||
}
|
||||
};
|
||||
|
||||
const getArrayField = (field: RuleField): string[] => {
|
||||
switch (field) {
|
||||
case 'authors':
|
||||
return (book.metadata?.authors ?? []).map(a => a.toLowerCase());
|
||||
case 'categories':
|
||||
return (book.metadata?.categories ?? []).map(c => c.toLowerCase());
|
||||
case 'moods':
|
||||
return (book.metadata?.moods ?? []).map(m => m.toLowerCase());
|
||||
case 'tags':
|
||||
return (book.metadata?.tags ?? []).map(t => t.toLowerCase());
|
||||
case 'readStatus':
|
||||
return [String(book.readStatus ?? 'UNSET').toLowerCase()];
|
||||
case 'fileType':
|
||||
return [String(book['bookType'] ?? '').toLowerCase()];
|
||||
case 'library':
|
||||
return [String(book.libraryId)];
|
||||
case 'shelf':
|
||||
return (book.shelves ?? []).map(s => String(s.id));
|
||||
case 'language':
|
||||
return [String(book.metadata?.language ?? '').toLowerCase()];
|
||||
case 'title':
|
||||
return [String(book.metadata?.title ?? '').toLowerCase()];
|
||||
case 'subtitle':
|
||||
return [String(book.metadata?.subtitle ?? '').toLowerCase()];
|
||||
case 'publisher':
|
||||
return [String(book.metadata?.publisher ?? '').toLowerCase()];
|
||||
case 'seriesName':
|
||||
return [String(book.metadata?.seriesName ?? '').toLowerCase()];
|
||||
case 'isbn13':
|
||||
return [String(book.metadata?.isbn13 ?? '').toLowerCase()];
|
||||
case 'isbn10':
|
||||
return [String(book.metadata?.isbn10 ?? '').toLowerCase()];
|
||||
case 'narrator':
|
||||
return [String(book.metadata?.narrator ?? '').toLowerCase()];
|
||||
case 'description':
|
||||
return [String(book.metadata?.description ?? '').toLowerCase()];
|
||||
case 'contentRating':
|
||||
return [String(book.metadata?.contentRating ?? '').toLowerCase()];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
const isNumericIdField = rule.field === 'library' || rule.field === 'shelf';
|
||||
const isFileTypeField = rule.field === 'fileType';
|
||||
|
||||
const ruleList = Array.isArray(rule.value)
|
||||
? rule.value.map(v => {
|
||||
if (isNumericIdField) return String(v);
|
||||
const lowerValue = String(v).toLowerCase();
|
||||
return isFileTypeField ? mapFileTypeValue(lowerValue) : lowerValue;
|
||||
})
|
||||
: (rule.value ? [
|
||||
isNumericIdField
|
||||
? String(rule.value)
|
||||
: isFileTypeField
|
||||
? mapFileTypeValue(String(rule.value).toLowerCase())
|
||||
: String(rule.value).toLowerCase()
|
||||
] : []);
|
||||
|
||||
switch (rule.operator) {
|
||||
case 'equals':
|
||||
if (Array.isArray(value)) {
|
||||
return value.some(v => ruleList.includes(isNumericIdField ? String(v) : String(v).toLowerCase()));
|
||||
}
|
||||
if (value instanceof Date && ruleVal instanceof Date) {
|
||||
return value.getTime() === ruleVal.getTime();
|
||||
}
|
||||
if (isFileTypeField && typeof ruleVal === 'string') {
|
||||
const mappedRuleVal = mapFileTypeValue(ruleVal.toLowerCase());
|
||||
return value === mappedRuleVal;
|
||||
}
|
||||
return value === ruleVal;
|
||||
|
||||
case 'not_equals':
|
||||
if (Array.isArray(value)) {
|
||||
return value.every(v => !ruleList.includes(isNumericIdField ? String(v) : String(v).toLowerCase()));
|
||||
}
|
||||
if (value instanceof Date && ruleVal instanceof Date) {
|
||||
return value.getTime() !== ruleVal.getTime();
|
||||
}
|
||||
if (isFileTypeField && typeof ruleVal === 'string') {
|
||||
const mappedRuleVal = mapFileTypeValue(ruleVal.toLowerCase());
|
||||
return value !== mappedRuleVal;
|
||||
}
|
||||
return value !== ruleVal;
|
||||
|
||||
case 'contains':
|
||||
if (Array.isArray(value)) {
|
||||
if (typeof ruleVal !== 'string') return false;
|
||||
return value.some(v => String(v).includes(ruleVal));
|
||||
}
|
||||
if (typeof value !== 'string') return false;
|
||||
if (typeof ruleVal !== 'string') return false;
|
||||
return value.includes(ruleVal);
|
||||
|
||||
case 'does_not_contain':
|
||||
if (Array.isArray(value)) {
|
||||
if (typeof ruleVal !== 'string') return true;
|
||||
return value.every(v => !String(v).includes(ruleVal));
|
||||
}
|
||||
if (typeof value !== 'string') return true;
|
||||
if (typeof ruleVal !== 'string') return true;
|
||||
return !value.includes(ruleVal);
|
||||
|
||||
case 'starts_with':
|
||||
if (Array.isArray(value)) {
|
||||
if (typeof ruleVal !== 'string') return false;
|
||||
return value.some(v => String(v).startsWith(ruleVal));
|
||||
}
|
||||
if (typeof value !== 'string') return false;
|
||||
if (typeof ruleVal !== 'string') return false;
|
||||
return value.startsWith(ruleVal);
|
||||
|
||||
case 'ends_with':
|
||||
if (Array.isArray(value)) {
|
||||
if (typeof ruleVal !== 'string') return false;
|
||||
return value.some(v => String(v).endsWith(ruleVal));
|
||||
}
|
||||
if (typeof value !== 'string') return false;
|
||||
if (typeof ruleVal !== 'string') return false;
|
||||
return value.endsWith(ruleVal);
|
||||
|
||||
case 'greater_than':
|
||||
if (value instanceof Date && ruleVal instanceof Date) {
|
||||
return value > ruleVal;
|
||||
}
|
||||
return Number(value) > Number(ruleVal);
|
||||
|
||||
case 'greater_than_equal_to':
|
||||
if (value instanceof Date && ruleVal instanceof Date) {
|
||||
return value >= ruleVal;
|
||||
}
|
||||
return Number(value) >= Number(ruleVal);
|
||||
|
||||
case 'less_than':
|
||||
if (value instanceof Date && ruleVal instanceof Date) {
|
||||
return value < ruleVal;
|
||||
}
|
||||
return Number(value) < Number(ruleVal);
|
||||
|
||||
case 'less_than_equal_to':
|
||||
if (value instanceof Date && ruleVal instanceof Date) {
|
||||
return value <= ruleVal;
|
||||
}
|
||||
return Number(value) <= Number(ruleVal);
|
||||
|
||||
case 'in_between':
|
||||
if (value == null || ruleStart == null || ruleEnd == null) return false;
|
||||
if (value instanceof Date && ruleStart instanceof Date && ruleEnd instanceof Date) {
|
||||
return value >= ruleStart && value <= ruleEnd;
|
||||
}
|
||||
return Number(value) >= Number(ruleStart) && Number(value) <= Number(ruleEnd);
|
||||
|
||||
case 'is_empty': {
|
||||
const emptyVal = rule.field === 'readStatus' ? book.readStatus : value;
|
||||
if (emptyVal == null) return true;
|
||||
if (typeof emptyVal === 'string') return emptyVal.trim() === '';
|
||||
if (Array.isArray(emptyVal)) return emptyVal.length === 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
case 'is_not_empty': {
|
||||
const notEmptyVal = rule.field === 'readStatus' ? book.readStatus : value;
|
||||
if (notEmptyVal == null) return false;
|
||||
if (typeof notEmptyVal === 'string') return notEmptyVal.trim() !== '';
|
||||
if (Array.isArray(notEmptyVal)) return notEmptyVal.length > 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
case 'includes_all': {
|
||||
const bookList = getArrayField(rule.field);
|
||||
return ruleList.every(v => bookList.includes(v));
|
||||
}
|
||||
|
||||
case 'excludes_all': {
|
||||
const bookList = getArrayField(rule.field);
|
||||
return ruleList.every(v => !bookList.includes(v));
|
||||
}
|
||||
|
||||
case 'includes_any': {
|
||||
const bookList = getArrayField(rule.field);
|
||||
return ruleList.some(v => bookList.includes(v));
|
||||
}
|
||||
|
||||
case 'within_last': {
|
||||
if (!(value instanceof Date)) return false;
|
||||
const threshold = this.computeDateThreshold(Number(rule.value), String(rule.valueEnd ?? 'days'));
|
||||
return value >= threshold;
|
||||
}
|
||||
|
||||
case 'older_than': {
|
||||
if (!(value instanceof Date)) return false;
|
||||
const threshold = this.computeDateThreshold(Number(rule.value), String(rule.valueEnd ?? 'days'));
|
||||
return value < threshold;
|
||||
}
|
||||
|
||||
case 'this_period': {
|
||||
if (!(value instanceof Date)) return false;
|
||||
const start = this.getStartOfPeriod(String(rule.value ?? 'year'));
|
||||
return value >= start;
|
||||
}
|
||||
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private extractBookValue(book: Book, field: RuleField): unknown {
|
||||
switch (field) {
|
||||
case 'library':
|
||||
return book.libraryId;
|
||||
case 'shelf':
|
||||
return (book.shelves ?? []).map(s => s.id);
|
||||
case 'readStatus':
|
||||
return book.readStatus ?? 'UNSET';
|
||||
case 'fileType':
|
||||
return (book['bookType'] as string)?.toLowerCase() ?? null;
|
||||
case 'fileSize':
|
||||
return book.fileSizeKb;
|
||||
case 'metadataScore':
|
||||
return book.metadataMatchScore;
|
||||
case 'personalRating':
|
||||
return book.personalRating;
|
||||
case 'title':
|
||||
return book.metadata?.title?.toLowerCase() ?? null;
|
||||
case 'subtitle':
|
||||
return book.metadata?.subtitle?.toLowerCase() ?? null;
|
||||
case 'authors':
|
||||
return (book.metadata?.authors ?? []).map(a => a.toLowerCase());
|
||||
case 'categories':
|
||||
return (book.metadata?.categories ?? []).map(c => c.toLowerCase());
|
||||
case 'moods':
|
||||
return (book.metadata?.moods ?? []).map(m => m.toLowerCase());
|
||||
case 'tags':
|
||||
return (book.metadata?.tags ?? []).map(t => t.toLowerCase());
|
||||
case 'publisher':
|
||||
return book.metadata?.publisher?.toLowerCase() ?? null;
|
||||
case 'publishedDate':
|
||||
return book.metadata?.publishedDate ? new Date(book.metadata.publishedDate) : null;
|
||||
case 'dateFinished':
|
||||
return book.dateFinished ? new Date(book.dateFinished) : null;
|
||||
case 'lastReadTime':
|
||||
return book.lastReadTime ? new Date(book.lastReadTime) : null;
|
||||
case 'seriesName':
|
||||
return book.metadata?.seriesName?.toLowerCase() ?? null;
|
||||
case 'seriesNumber':
|
||||
return book.metadata?.seriesNumber;
|
||||
case 'seriesTotal':
|
||||
return book.metadata?.seriesTotal;
|
||||
case 'pageCount':
|
||||
return book.metadata?.pageCount;
|
||||
case 'language':
|
||||
return book.metadata?.language?.toLowerCase() ?? null;
|
||||
case 'isbn13':
|
||||
return book.metadata?.isbn13?.toLowerCase() ?? null;
|
||||
case 'isbn10':
|
||||
return book.metadata?.isbn10?.toLowerCase() ?? null;
|
||||
case 'amazonRating':
|
||||
return book.metadata?.amazonRating;
|
||||
case 'amazonReviewCount':
|
||||
return book.metadata?.amazonReviewCount;
|
||||
case 'goodreadsRating':
|
||||
return book.metadata?.goodreadsRating;
|
||||
case 'goodreadsReviewCount':
|
||||
return book.metadata?.goodreadsReviewCount;
|
||||
case 'hardcoverRating':
|
||||
return book.metadata?.hardcoverRating;
|
||||
case 'hardcoverReviewCount':
|
||||
return book.metadata?.hardcoverReviewCount;
|
||||
case 'ranobedbRating':
|
||||
return book.metadata?.ranobedbRating;
|
||||
case 'addedOn':
|
||||
return book.addedOn ? new Date(book.addedOn) : null;
|
||||
case 'description':
|
||||
return book.metadata?.description?.toLowerCase() ?? null;
|
||||
case 'narrator':
|
||||
return book.metadata?.narrator?.toLowerCase() ?? null;
|
||||
case 'ageRating':
|
||||
return book.metadata?.ageRating;
|
||||
case 'contentRating':
|
||||
return book.metadata?.contentRating?.toLowerCase() ?? null;
|
||||
case 'audibleRating':
|
||||
return book.metadata?.audibleRating;
|
||||
case 'audibleReviewCount':
|
||||
return book.metadata?.audibleReviewCount;
|
||||
case 'abridged':
|
||||
return book.metadata?.abridged;
|
||||
case 'audiobookDuration':
|
||||
return book.metadata?.audiobookMetadata?.durationSeconds ?? null;
|
||||
case 'audiobookCodec':
|
||||
return book.metadata?.audiobookMetadata?.codec?.toLowerCase() ?? null;
|
||||
case 'audiobookChapterCount':
|
||||
return book.metadata?.audiobookMetadata?.chapterCount ?? null;
|
||||
case 'audiobookBitrate':
|
||||
return book.metadata?.audiobookMetadata?.bitrate ?? null;
|
||||
case 'isPhysical':
|
||||
return book.isPhysical;
|
||||
case 'lubimyczytacRating':
|
||||
return book.metadata?.lubimyczytacRating;
|
||||
case 'readingProgress': {
|
||||
const prg = [
|
||||
book.koreaderProgress?.percentage ?? 0,
|
||||
book.koboProgress?.percentage ?? 0,
|
||||
book.pdfProgress?.percentage ?? 0,
|
||||
book.epubProgress?.percentage ?? 0,
|
||||
book.cbxProgress?.percentage ?? 0,
|
||||
book.audiobookProgress?.percentage ?? 0,
|
||||
];
|
||||
return Math.max(...prg);
|
||||
}
|
||||
default:
|
||||
return (book as Record<string, unknown>)[field];
|
||||
}
|
||||
}
|
||||
|
||||
private evaluateCompositeField(book: Book, rule: Rule, allBooks: Book[]): boolean {
|
||||
const seriesName = book.metadata?.seriesName;
|
||||
if (!seriesName) return false;
|
||||
|
||||
const seriesBooks = allBooks.filter(b => b.metadata?.seriesName === seriesName);
|
||||
const value = typeof rule.value === 'string' ? rule.value.toLowerCase() : '';
|
||||
const negate = rule.operator === 'not_equals';
|
||||
|
||||
let result: boolean;
|
||||
switch (rule.field) {
|
||||
case 'seriesStatus':
|
||||
result = this.evaluateSeriesStatus(seriesBooks, value);
|
||||
break;
|
||||
case 'seriesGaps':
|
||||
result = this.evaluateSeriesGaps(seriesBooks, value);
|
||||
break;
|
||||
case 'seriesPosition':
|
||||
result = this.evaluateSeriesPosition(book, seriesBooks, value);
|
||||
break;
|
||||
default:
|
||||
result = false;
|
||||
}
|
||||
|
||||
return negate ? !result : result;
|
||||
}
|
||||
|
||||
private evaluateSeriesStatus(seriesBooks: Book[], value: string): boolean {
|
||||
switch (value) {
|
||||
case 'reading':
|
||||
return seriesBooks.some(b => b.readStatus === 'READING' || b.readStatus === 'RE_READING');
|
||||
case 'not_started':
|
||||
return !seriesBooks.some(b =>
|
||||
b.readStatus === 'READ' || b.readStatus === 'READING' ||
|
||||
b.readStatus === 'RE_READING' || b.readStatus === 'PARTIALLY_READ'
|
||||
);
|
||||
case 'fully_read':
|
||||
return seriesBooks.length > 0 && seriesBooks.every(b => b.readStatus === 'READ');
|
||||
case 'completed': {
|
||||
const totals = seriesBooks.map(b => b.metadata?.seriesTotal).filter((t): t is number => t != null);
|
||||
if (totals.length === 0) return false;
|
||||
const maxTotal = Math.max(...totals);
|
||||
return seriesBooks.some(b => b.metadata?.seriesNumber != null && Math.floor(b.metadata.seriesNumber) === maxTotal);
|
||||
}
|
||||
case 'ongoing': {
|
||||
const totals = seriesBooks.map(b => b.metadata?.seriesTotal).filter((t): t is number => t != null);
|
||||
if (totals.length === 0) return false;
|
||||
const maxTotal = Math.max(...totals);
|
||||
return !seriesBooks.some(b => b.metadata?.seriesNumber != null && Math.floor(b.metadata.seriesNumber) === maxTotal);
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private evaluateSeriesGaps(seriesBooks: Book[], value: string): boolean {
|
||||
const numberedBooks = seriesBooks
|
||||
.filter(b => b.metadata?.seriesNumber != null)
|
||||
.map(b => b.metadata!.seriesNumber!);
|
||||
|
||||
if (numberedBooks.length === 0) return false;
|
||||
|
||||
switch (value) {
|
||||
case 'any_gap': {
|
||||
const uniqueFloors = new Set(numberedBooks.map(n => Math.floor(n)));
|
||||
const maxFloor = Math.max(...numberedBooks.map(n => Math.floor(n)));
|
||||
return uniqueFloors.size < maxFloor;
|
||||
}
|
||||
case 'missing_first':
|
||||
return !numberedBooks.some(n => Math.floor(n) === 1);
|
||||
case 'missing_latest': {
|
||||
const totals = seriesBooks.map(b => b.metadata?.seriesTotal).filter((t): t is number => t != null);
|
||||
if (totals.length === 0) return false;
|
||||
const maxTotal = Math.max(...totals);
|
||||
return !numberedBooks.some(n => Math.floor(n) === maxTotal);
|
||||
}
|
||||
case 'duplicate_number':
|
||||
return numberedBooks.length > new Set(numberedBooks).size;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private evaluateSeriesPosition(book: Book, seriesBooks: Book[], value: string): boolean {
|
||||
if (book.metadata?.seriesNumber == null) return false;
|
||||
|
||||
const numberedBooks = seriesBooks.filter(b => b.metadata?.seriesNumber != null);
|
||||
|
||||
switch (value) {
|
||||
case 'first_in_series': {
|
||||
const minNumber = Math.min(...numberedBooks.map(b => b.metadata!.seriesNumber!));
|
||||
return book.metadata.seriesNumber === minNumber;
|
||||
}
|
||||
case 'last_in_series': {
|
||||
const maxNumber = Math.max(...numberedBooks.map(b => b.metadata!.seriesNumber!));
|
||||
return book.metadata.seriesNumber === maxNumber;
|
||||
}
|
||||
case 'next_unread': {
|
||||
if (book.readStatus === 'READ') return false;
|
||||
const hasLowerUnread = numberedBooks.some(b =>
|
||||
b.metadata!.seriesNumber! < book.metadata!.seriesNumber! &&
|
||||
b.readStatus !== 'READ'
|
||||
);
|
||||
if (hasLowerUnread) return false;
|
||||
return numberedBooks.some(b =>
|
||||
b.metadata!.seriesNumber! < book.metadata!.seriesNumber! &&
|
||||
b.readStatus === 'READ'
|
||||
);
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private evaluateMetadataPresence(book: Book, rule: Rule): boolean {
|
||||
const metadataField = typeof rule.value === 'string' ? rule.value : '';
|
||||
const isPresent = this.isMetadataFieldPresent(book, metadataField);
|
||||
return rule.operator === 'equals' ? isPresent : !isPresent;
|
||||
}
|
||||
|
||||
private isMetadataFieldPresent(book: Book, field: string): boolean {
|
||||
const val = this.getMetadataFieldValue(book, field);
|
||||
if (val == null) return false;
|
||||
if (typeof val === 'string') return val.trim() !== '';
|
||||
if (Array.isArray(val)) return val.length > 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
private getMetadataFieldValue(book: Book, field: string): unknown {
|
||||
switch (field) {
|
||||
case 'title': return book.metadata?.title;
|
||||
case 'subtitle': return book.metadata?.subtitle;
|
||||
case 'description': return book.metadata?.description;
|
||||
case 'publisher': return book.metadata?.publisher;
|
||||
case 'publishedDate': return book.metadata?.publishedDate;
|
||||
case 'language': return book.metadata?.language;
|
||||
case 'thumbnailUrl': return book.metadata?.thumbnailUrl;
|
||||
case 'narrator': return book.metadata?.narrator;
|
||||
case 'contentRating': return book.metadata?.contentRating;
|
||||
case 'pageCount': return book.metadata?.pageCount;
|
||||
case 'seriesNumber': return book.metadata?.seriesNumber;
|
||||
case 'seriesTotal': return book.metadata?.seriesTotal;
|
||||
case 'ageRating': return book.metadata?.ageRating;
|
||||
case 'seriesName': return book.metadata?.seriesName;
|
||||
case 'isbn13': return book.metadata?.isbn13;
|
||||
case 'isbn10': return book.metadata?.isbn10;
|
||||
case 'asin': return book.metadata?.asin;
|
||||
case 'authors': return book.metadata?.authors;
|
||||
case 'categories': return book.metadata?.categories;
|
||||
case 'moods': return book.metadata?.moods;
|
||||
case 'tags': return book.metadata?.tags;
|
||||
case 'personalRating': return book.personalRating;
|
||||
case 'amazonRating': return book.metadata?.amazonRating;
|
||||
case 'goodreadsRating': return book.metadata?.goodreadsRating;
|
||||
case 'hardcoverRating': return book.metadata?.hardcoverRating;
|
||||
case 'ranobedbRating': return book.metadata?.ranobedbRating;
|
||||
case 'lubimyczytacRating': return book.metadata?.lubimyczytacRating;
|
||||
case 'audibleRating': return book.metadata?.audibleRating;
|
||||
case 'amazonReviewCount': return book.metadata?.amazonReviewCount;
|
||||
case 'goodreadsReviewCount': return book.metadata?.goodreadsReviewCount;
|
||||
case 'hardcoverReviewCount': return book.metadata?.hardcoverReviewCount;
|
||||
case 'audibleReviewCount': return book.metadata?.audibleReviewCount;
|
||||
case 'goodreadsId': return book.metadata?.goodreadsId;
|
||||
case 'hardcoverId': return book.metadata?.hardcoverId;
|
||||
case 'googleId': return book.metadata?.googleId;
|
||||
case 'audibleId': return book.metadata?.audibleId;
|
||||
case 'lubimyczytacId': return book.metadata?.lubimyczytacId;
|
||||
case 'ranobedbId': return book.metadata?.ranobedbId;
|
||||
case 'comicvineId': return book.metadata?.comicvineId;
|
||||
case 'abridged': return book.metadata?.abridged;
|
||||
case 'audiobookDuration': return book.metadata?.audiobookMetadata?.durationSeconds;
|
||||
case 'audiobookCodec': return book.metadata?.audiobookMetadata?.codec;
|
||||
case 'audiobookChapterCount': return book.metadata?.audiobookMetadata?.chapterCount;
|
||||
case 'audiobookBitrate': return book.metadata?.audiobookMetadata?.bitrate;
|
||||
case 'comicCharacters': return book.metadata?.comicMetadata?.characters;
|
||||
case 'comicTeams': return book.metadata?.comicMetadata?.teams;
|
||||
case 'comicLocations': return book.metadata?.comicMetadata?.locations;
|
||||
case 'comicPencillers': return book.metadata?.comicMetadata?.pencillers;
|
||||
case 'comicInkers': return book.metadata?.comicMetadata?.inkers;
|
||||
case 'comicColorists': return book.metadata?.comicMetadata?.colorists;
|
||||
case 'comicLetterers': return book.metadata?.comicMetadata?.letterers;
|
||||
case 'comicCoverArtists': return book.metadata?.comicMetadata?.coverArtists;
|
||||
case 'comicEditors': return book.metadata?.comicMetadata?.editors;
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
private computeDateThreshold(amount: number, unit: string): Date {
|
||||
const now = new Date();
|
||||
switch (unit.toLowerCase()) {
|
||||
case 'weeks':
|
||||
return new Date(now.getTime() - amount * 7 * 24 * 60 * 60 * 1000);
|
||||
case 'months':
|
||||
return new Date(now.getFullYear(), now.getMonth() - amount, now.getDate());
|
||||
case 'years':
|
||||
return new Date(now.getFullYear() - amount, now.getMonth(), now.getDate());
|
||||
default:
|
||||
return new Date(now.getTime() - amount * 24 * 60 * 60 * 1000);
|
||||
}
|
||||
}
|
||||
|
||||
private getStartOfPeriod(period: string): Date {
|
||||
const now = new Date();
|
||||
switch (period.toLowerCase()) {
|
||||
case 'week': {
|
||||
const day = now.getDay();
|
||||
const diff = day === 0 ? 6 : day - 1;
|
||||
return new Date(now.getFullYear(), now.getMonth(), now.getDate() - diff);
|
||||
}
|
||||
case 'month':
|
||||
return new Date(now.getFullYear(), now.getMonth(), 1);
|
||||
default:
|
||||
return new Date(now.getFullYear(), 0, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
import {RELATIVE_DATE_OPERATORS, MULTI_VALUE_OPERATORS, EMPTY_CHECK_OPERATORS, parseValue, serializeDateRules, removeNulls} from './magic-shelf-utils';
|
||||
|
||||
describe('magic-shelf-utils', () => {
|
||||
|
||||
describe('RELATIVE_DATE_OPERATORS', () => {
|
||||
it('should contain within_last, older_than, this_period', () => {
|
||||
expect(RELATIVE_DATE_OPERATORS).toEqual(['within_last', 'older_than', 'this_period']);
|
||||
});
|
||||
|
||||
it('should not overlap with MULTI_VALUE_OPERATORS', () => {
|
||||
RELATIVE_DATE_OPERATORS.forEach(op => {
|
||||
expect(MULTI_VALUE_OPERATORS).not.toContain(op);
|
||||
});
|
||||
});
|
||||
|
||||
it('should not overlap with EMPTY_CHECK_OPERATORS', () => {
|
||||
RELATIVE_DATE_OPERATORS.forEach(op => {
|
||||
expect(EMPTY_CHECK_OPERATORS).not.toContain(op);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('serializeDateRules', () => {
|
||||
it('should serialize Date values for regular date operators', () => {
|
||||
const rule = {
|
||||
field: 'dateFinished',
|
||||
operator: 'equals',
|
||||
value: new Date('2024-06-15T00:00:00Z'),
|
||||
valueStart: null,
|
||||
valueEnd: null
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBe('2024-06-15');
|
||||
});
|
||||
|
||||
it('should serialize Date values for in_between operator on date fields', () => {
|
||||
const rule = {
|
||||
field: 'addedOn',
|
||||
operator: 'in_between',
|
||||
value: null,
|
||||
valueStart: new Date('2024-01-01T00:00:00Z'),
|
||||
valueEnd: new Date('2024-12-31T00:00:00Z')
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['valueStart']).toBe('2024-01-01');
|
||||
expect(result['valueEnd']).toBe('2024-12-31');
|
||||
});
|
||||
|
||||
it('should NOT serialize values for within_last operator on date fields', () => {
|
||||
const rule = {
|
||||
field: 'dateFinished',
|
||||
operator: 'within_last',
|
||||
value: 30,
|
||||
valueStart: null,
|
||||
valueEnd: 'days'
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBe(30);
|
||||
expect(result['valueEnd']).toBe('days');
|
||||
});
|
||||
|
||||
it('should NOT serialize values for older_than operator on date fields', () => {
|
||||
const rule = {
|
||||
field: 'lastReadTime',
|
||||
operator: 'older_than',
|
||||
value: 6,
|
||||
valueStart: null,
|
||||
valueEnd: 'months'
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBe(6);
|
||||
expect(result['valueEnd']).toBe('months');
|
||||
});
|
||||
|
||||
it('should NOT serialize values for this_period operator on date fields', () => {
|
||||
const rule = {
|
||||
field: 'addedOn',
|
||||
operator: 'this_period',
|
||||
value: 'year',
|
||||
valueStart: null,
|
||||
valueEnd: null
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBe('year');
|
||||
});
|
||||
|
||||
it('should NOT serialize values for publishedDate with within_last', () => {
|
||||
const rule = {
|
||||
field: 'publishedDate',
|
||||
operator: 'within_last',
|
||||
value: 2,
|
||||
valueStart: null,
|
||||
valueEnd: 'years'
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBe(2);
|
||||
expect(result['valueEnd']).toBe('years');
|
||||
});
|
||||
|
||||
it('should recurse through group rules', () => {
|
||||
const group = {
|
||||
type: 'group',
|
||||
join: 'and',
|
||||
rules: [
|
||||
{
|
||||
field: 'dateFinished',
|
||||
operator: 'within_last',
|
||||
value: 7,
|
||||
valueStart: null,
|
||||
valueEnd: 'days'
|
||||
},
|
||||
{
|
||||
field: 'addedOn',
|
||||
operator: 'equals',
|
||||
value: new Date('2024-03-15T00:00:00Z'),
|
||||
valueStart: null,
|
||||
valueEnd: null
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const result = serializeDateRules(group) as { rules: Record<string, unknown>[] };
|
||||
expect(result.rules[0]['value']).toBe(7);
|
||||
expect(result.rules[0]['valueEnd']).toBe('days');
|
||||
expect(result.rules[1]['value']).toBe('2024-03-15');
|
||||
});
|
||||
|
||||
it('should not affect non-date fields', () => {
|
||||
const rule = {
|
||||
field: 'title',
|
||||
operator: 'contains',
|
||||
value: 'Harry Potter',
|
||||
valueStart: null,
|
||||
valueEnd: null
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBe('Harry Potter');
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseValue', () => {
|
||||
it('should parse number values correctly', () => {
|
||||
expect(parseValue(42, 'number')).toBe(42);
|
||||
expect(parseValue('42', 'number')).toBe(42);
|
||||
expect(parseValue(3.5, 'decimal')).toBe(3.5);
|
||||
});
|
||||
|
||||
it('should return null for NaN number values', () => {
|
||||
expect(parseValue('not a number', 'number')).toBeNull();
|
||||
});
|
||||
|
||||
it('should parse date values correctly', () => {
|
||||
const result = parseValue('2024-06-15', 'date');
|
||||
expect(result).toBeInstanceOf(Date);
|
||||
expect((result as Date).getFullYear()).toBe(2024);
|
||||
});
|
||||
|
||||
it('should return null for invalid date values', () => {
|
||||
expect(parseValue('not a date', 'date')).toBeNull();
|
||||
});
|
||||
|
||||
it('should return null for null input', () => {
|
||||
expect(parseValue(null, 'number')).toBeNull();
|
||||
expect(parseValue(null, 'date')).toBeNull();
|
||||
expect(parseValue(null, undefined)).toBeNull();
|
||||
});
|
||||
|
||||
it('should return value as-is for undefined type', () => {
|
||||
expect(parseValue('hello', undefined)).toBe('hello');
|
||||
expect(parseValue('true', 'boolean' as any)).toBe('true');
|
||||
});
|
||||
|
||||
it('should return arrays as-is for undefined type', () => {
|
||||
const arr = ['a', 'b'];
|
||||
expect(parseValue(arr, undefined)).toBe(arr);
|
||||
});
|
||||
});
|
||||
|
||||
describe('removeNulls', () => {
|
||||
it('should remove null values from flat object', () => {
|
||||
expect(removeNulls({a: 1, b: null, c: 'hello'})).toEqual({a: 1, c: 'hello'});
|
||||
});
|
||||
|
||||
it('should remove undefined values from flat object', () => {
|
||||
expect(removeNulls({a: 1, b: undefined})).toEqual({a: 1});
|
||||
});
|
||||
|
||||
it('should keep falsy non-null values', () => {
|
||||
expect(removeNulls({a: 0, b: '', c: false})).toEqual({a: 0, b: '', c: false});
|
||||
});
|
||||
|
||||
it('should recurse into nested objects', () => {
|
||||
expect(removeNulls({a: {b: null, c: 1}, d: 2})).toEqual({a: {c: 1}, d: 2});
|
||||
});
|
||||
|
||||
it('should recurse into arrays', () => {
|
||||
expect(removeNulls([{a: null, b: 1}, {c: null}])).toEqual([{b: 1}, {}]);
|
||||
});
|
||||
|
||||
it('should handle empty objects', () => {
|
||||
expect(removeNulls({})).toEqual({});
|
||||
});
|
||||
|
||||
it('should handle empty arrays', () => {
|
||||
expect(removeNulls([])).toEqual([]);
|
||||
});
|
||||
|
||||
it('should pass through primitive values', () => {
|
||||
expect(removeNulls('hello')).toBe('hello');
|
||||
expect(removeNulls(42)).toBe(42);
|
||||
});
|
||||
|
||||
it('should handle deeply nested structures', () => {
|
||||
expect(removeNulls({a: {b: {c: null, d: {e: null, f: 1}}}})).toEqual({a: {b: {d: {f: 1}}}});
|
||||
});
|
||||
});
|
||||
|
||||
describe('serializeDateRules edge cases', () => {
|
||||
it('should handle lastReadTime date field serialization', () => {
|
||||
const rule = {
|
||||
field: 'lastReadTime',
|
||||
operator: 'equals',
|
||||
value: new Date('2024-08-20T00:00:00Z'),
|
||||
valueStart: null,
|
||||
valueEnd: null
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBe('2024-08-20');
|
||||
});
|
||||
|
||||
it('should preserve string values on date fields', () => {
|
||||
const rule = {
|
||||
field: 'dateFinished',
|
||||
operator: 'equals',
|
||||
value: '2024-06-15',
|
||||
valueStart: null,
|
||||
valueEnd: null
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBe('2024-06-15');
|
||||
});
|
||||
|
||||
it('should handle null value on date field', () => {
|
||||
const rule = {
|
||||
field: 'dateFinished',
|
||||
operator: 'is_empty',
|
||||
value: null,
|
||||
valueStart: null,
|
||||
valueEnd: null
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBeNull();
|
||||
});
|
||||
|
||||
it('should handle undefined value on date field', () => {
|
||||
const rule = {
|
||||
field: 'addedOn',
|
||||
operator: 'is_empty',
|
||||
value: undefined,
|
||||
valueStart: null,
|
||||
valueEnd: null
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should handle deeply nested groups', () => {
|
||||
const nested = {
|
||||
type: 'group',
|
||||
join: 'and',
|
||||
rules: [
|
||||
{
|
||||
type: 'group',
|
||||
join: 'or',
|
||||
rules: [
|
||||
{
|
||||
field: 'addedOn',
|
||||
operator: 'equals',
|
||||
value: new Date('2024-11-01T00:00:00Z'),
|
||||
valueStart: null,
|
||||
valueEnd: null
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const result = serializeDateRules(nested) as { rules: { rules: Record<string, unknown>[] }[] };
|
||||
expect(result.rules[0].rules[0]['value']).toBe('2024-11-01');
|
||||
});
|
||||
|
||||
it('should handle rule with no field property', () => {
|
||||
const rule = {
|
||||
operator: 'equals',
|
||||
value: 'test'
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBe('test');
|
||||
});
|
||||
|
||||
it('should handle empty rules array in group', () => {
|
||||
const group = {
|
||||
type: 'group',
|
||||
rules: []
|
||||
};
|
||||
|
||||
const result = serializeDateRules(group) as { rules: unknown[] };
|
||||
expect(result.rules).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseValue edge cases', () => {
|
||||
it('should parse 0 as valid number', () => {
|
||||
expect(parseValue(0, 'number')).toBe(0);
|
||||
});
|
||||
|
||||
it('should parse empty string as 0 for number', () => {
|
||||
expect(parseValue('', 'number')).toBe(0);
|
||||
});
|
||||
|
||||
it('should handle undefined input', () => {
|
||||
expect(parseValue(undefined, 'number')).toBeNull();
|
||||
});
|
||||
|
||||
it('should handle Date object input for date type', () => {
|
||||
const result = parseValue(new Date('2024-01-01'), 'date');
|
||||
expect(result).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it('should handle numeric timestamp for date type', () => {
|
||||
const result = parseValue(1718409600000, 'date');
|
||||
expect(result).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it('should parse negative numbers', () => {
|
||||
expect(parseValue(-5, 'number')).toBe(-5);
|
||||
});
|
||||
|
||||
it('should parse decimal string as number', () => {
|
||||
expect(parseValue('3.14', 'decimal')).toBe(3.14);
|
||||
});
|
||||
|
||||
it('should return string type value as-is', () => {
|
||||
expect(parseValue('hello', 'string')).toBe('hello');
|
||||
});
|
||||
});
|
||||
|
||||
describe('MULTI_VALUE_OPERATORS', () => {
|
||||
it('should contain exactly includes_any, includes_all, excludes_all', () => {
|
||||
expect(MULTI_VALUE_OPERATORS).toEqual(['includes_any', 'includes_all', 'excludes_all']);
|
||||
});
|
||||
|
||||
it('should have length 3', () => {
|
||||
expect(MULTI_VALUE_OPERATORS.length).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('EMPTY_CHECK_OPERATORS', () => {
|
||||
it('should contain exactly is_empty, is_not_empty', () => {
|
||||
expect(EMPTY_CHECK_OPERATORS).toEqual(['is_empty', 'is_not_empty']);
|
||||
});
|
||||
|
||||
it('should have length 2', () => {
|
||||
expect(EMPTY_CHECK_OPERATORS.length).toBe(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import {RuleOperator} from '../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 const RELATIVE_DATE_OPERATORS: RuleOperator[] = [
|
||||
'within_last',
|
||||
'older_than',
|
||||
'this_period'
|
||||
];
|
||||
|
||||
export function parseValue(val: unknown, type: 'string' | 'number' | 'decimal' | 'date' | 'boolean' | undefined): unknown {
|
||||
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 as string | number | Date);
|
||||
return isNaN(d.getTime()) ? null : d;
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
export function removeNulls(obj: unknown): unknown {
|
||||
if (Array.isArray(obj)) {
|
||||
return obj.map(removeNulls);
|
||||
} else if (typeof obj === 'object' && obj !== null) {
|
||||
return Object.entries(obj).reduce((acc: Record<string, unknown>, [key, value]) => {
|
||||
const cleanedValue = removeNulls(value);
|
||||
if (cleanedValue !== null && cleanedValue !== undefined) {
|
||||
acc[key] = cleanedValue;
|
||||
}
|
||||
return acc;
|
||||
}, {});
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
export function serializeDateRules(ruleOrGroup: unknown): unknown {
|
||||
if (ruleOrGroup !== null && typeof ruleOrGroup === 'object' && 'rules' in ruleOrGroup) {
|
||||
const group = ruleOrGroup as { rules: unknown[] };
|
||||
return {
|
||||
...(ruleOrGroup as Record<string, unknown>),
|
||||
rules: group.rules.map(serializeDateRules)
|
||||
};
|
||||
}
|
||||
|
||||
const rule = ruleOrGroup as { field?: string; operator?: string; value?: unknown; valueStart?: unknown; valueEnd?: unknown; [key: string]: unknown };
|
||||
const isRelativeDateOp = RELATIVE_DATE_OPERATORS.includes(rule.operator as RuleOperator);
|
||||
const isDateField = !isRelativeDateOp && (rule.field === 'publishedDate' || rule.field === 'dateFinished' || rule.field === 'addedOn' || rule.field === 'lastReadTime');
|
||||
const serialize = (val: unknown) => (val instanceof Date ? val.toISOString().split('T')[0] : val);
|
||||
|
||||
return {
|
||||
...(ruleOrGroup as Record<string, unknown>),
|
||||
value: isDateField ? serialize(rule.value) : rule.value,
|
||||
valueStart: isDateField ? serialize(rule.valueStart) : rule.valueStart,
|
||||
valueEnd: isDateField ? serialize(rule.valueEnd) : rule.valueEnd
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import {computed, effect, inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {lastValueFrom, Observable} from 'rxjs';
|
||||
import {tap} from 'rxjs/operators';
|
||||
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
|
||||
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {BookRuleEvaluatorService} from './book-rule-evaluator.service';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {GroupRule} from '../component/magic-shelf-component';
|
||||
|
||||
export interface MagicShelf {
|
||||
id?: number | null;
|
||||
name: string;
|
||||
icon?: string | null;
|
||||
iconType?: 'PRIME_NG' | 'CUSTOM_SVG' | null;
|
||||
filterJson: string;
|
||||
isPublic?: boolean;
|
||||
}
|
||||
|
||||
const MAGIC_SHELVES_QUERY_KEY = ['magicShelves'] as const;
|
||||
|
||||
@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 authService = inject(AuthService);
|
||||
private readonly queryClient = inject(QueryClient);
|
||||
private readonly token = this.authService.token;
|
||||
|
||||
private readonly shelvesQuery = injectQuery(() => ({
|
||||
...this.getShelvesQueryOptions(),
|
||||
enabled: !!this.token(),
|
||||
}));
|
||||
|
||||
readonly shelves = computed(() => this.shelvesQuery.data() ?? []);
|
||||
|
||||
readonly shelvesError = computed<string | null>(() => {
|
||||
if (!this.token() || !this.shelvesQuery.isError()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const error = this.shelvesQuery.error();
|
||||
return error instanceof Error ? error.message : 'Failed to load magic shelves';
|
||||
});
|
||||
|
||||
readonly isShelvesLoading = computed(() => !!this.token() && this.shelvesQuery.isPending());
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const token = this.token();
|
||||
if (token === null) {
|
||||
this.queryClient.removeQueries({queryKey: MAGIC_SHELVES_QUERY_KEY});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private getShelvesQueryOptions() {
|
||||
return queryOptions({
|
||||
queryKey: MAGIC_SHELVES_QUERY_KEY,
|
||||
queryFn: () => lastValueFrom(this.http.get<MagicShelf[]>(this.url))
|
||||
});
|
||||
}
|
||||
|
||||
saveShelf(data: {
|
||||
id?: number;
|
||||
name: string | null;
|
||||
icon: string | null;
|
||||
iconType?: 'PRIME_NG' | 'CUSTOM_SVG';
|
||||
group: unknown;
|
||||
isPublic?: boolean | null;
|
||||
}): Observable<MagicShelf> {
|
||||
const payload: MagicShelf = {
|
||||
id: data.id,
|
||||
name: data.name ?? '',
|
||||
icon: data.icon,
|
||||
iconType: data.iconType,
|
||||
filterJson: JSON.stringify(data.group),
|
||||
isPublic: data.isPublic ?? false
|
||||
};
|
||||
|
||||
return this.http.post<MagicShelf>(this.url, payload).pipe(
|
||||
tap(() => {
|
||||
void this.queryClient.invalidateQueries({queryKey: MAGIC_SHELVES_QUERY_KEY, exact: true});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
findShelfById(id: number): MagicShelf | undefined {
|
||||
return this.shelves().find(shelf => shelf.id === id);
|
||||
}
|
||||
|
||||
getBookCountValue(shelfId: number): number {
|
||||
const shelf = this.findShelfById(shelfId);
|
||||
if (!shelf) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let group: GroupRule;
|
||||
try {
|
||||
group = JSON.parse(shelf.filterJson);
|
||||
} catch (error) {
|
||||
console.error('Invalid filter JSON', error);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const allBooks = this.bookService.books();
|
||||
return allBooks.filter(book =>
|
||||
this.ruleEvaluatorService.evaluateGroup(book, group, allBooks)
|
||||
).length;
|
||||
}
|
||||
|
||||
deleteShelf(id: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/${id}`).pipe(
|
||||
tap(() => {
|
||||
void this.queryClient.invalidateQueries({queryKey: MAGIC_SHELVES_QUERY_KEY, exact: true});
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user