Feature: live preview of storage path (#7870)

This commit is contained in:
shamoon
2024-10-09 16:35:36 -07:00
committed by GitHub
parent 8dd355f6bf
commit 024b60638a
15 changed files with 426 additions and 54 deletions

View File

@@ -10,7 +10,57 @@
<div class="modal-body">
<pngx-input-text i18n-title title="Name" formControlName="name" [error]="error?.name" autocomplete="off"></pngx-input-text>
<pngx-input-textarea i18n-title title="Path" formControlName="path" [error]="error?.path" [hint]="pathHint" [monospace]="true"></pngx-input-textarea>
<pngx-input-textarea i18n-title title="Path" formControlName="path" [error]="error?.path" hint="See <a target='_blank' href='https://docs.paperless-ngx.com/advanced_usage/#file-name-handling'>the documentation</a>." i18n-hint [monospace]="true"></pngx-input-textarea>
<div ngbAccordion>
<div ngbAccordionItem>
<h2 ngbAccordionHeader>
<button ngbAccordionButton i18n>Preview</button>
</h2>
<div ngbAccordionCollapse>
<div ngbAccordionBody>
<ng-template>
<div class="card mb-2">
<div class="card-body p-2">
@if (testLoading) {
<ng-container [ngTemplateOutlet]="loadingTemplate"></ng-container>
} @else if (testResult) {
<code>{{testResult}}</code>
} @else if (testFailed) {
<div class="text-danger" i18n>Path test failed</div>
} @else {
<div class="text-muted small" i18n>No document selected</div>
}
</div>
</div>
<ng-select name="testDocument"
[items]="foundDocuments$ | async"
placeholder="Search for a document" i18n-placeholder
notFoundText="No documents found" i18n-notFoundText
bindValue="id"
bindLabel="title"
[compareWith]="compareDocuments"
[trackByFn]="trackByFn"
[minTermLength]="2"
[loading]="loading"
[typeahead]="documentsInput$"
(change)="testPath($event)">
<ng-template #loadingTemplate ng-loadingspinner-tmp>
<div class="spinner-border spinner-border-sm fw-normal ms-2 me-auto" role="status"></div>
<div class="visually-hidden" i18n>Loading...</div>
</ng-template>
<ng-template ng-option-tmp let-document="item" let-index="index" let-search="searchTerm">
<div>{{document.title}} <small class="text-muted">({{document.created | customDate:'shortDate'}})</small></div>
</ng-template>
</ng-select>
</ng-template>
</div>
</div>
</div>
</div>
<hr/>
<pngx-input-select i18n-title title="Matching algorithm" [items]="getMatchingAlgorithms()" formControlName="matching_algorithm"></pngx-input-select>
@if (patternRequired) {
<pngx-input-text i18n-title title="Matching pattern" formControlName="match" [error]="error?.match"></pngx-input-text>

View File

@@ -0,0 +1,4 @@
.accordion {
--bs-accordion-btn-padding-x: 0.75rem;
--bs-accordion-btn-padding-y: 0.375rem;
}

View File

@@ -1,7 +1,11 @@
import { provideHttpClientTesting } from '@angular/common/http/testing'
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { NgbActiveModal, NgbModule } from '@ng-bootstrap/ng-bootstrap'
import {
NgbAccordionButton,
NgbActiveModal,
NgbModule,
} from '@ng-bootstrap/ng-bootstrap'
import { NgSelectModule } from '@ng-select/ng-select'
import { IfOwnerDirective } from 'src/app/directives/if-owner.directive'
import { IfPermissionsDirective } from 'src/app/directives/if-permissions.directive'
@@ -14,10 +18,16 @@ import { TextAreaComponent } from '../../input/textarea/textarea.component'
import { EditDialogMode } from '../edit-dialog.component'
import { StoragePathEditDialogComponent } from './storage-path-edit-dialog.component'
import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http'
import { StoragePathService } from 'src/app/services/rest/storage-path.service'
import { DocumentService } from 'src/app/services/rest/document.service'
import { of, throwError } from 'rxjs'
import { FILTER_TITLE } from 'src/app/data/filter-rule-type'
import { By } from '@angular/platform-browser'
describe('StoragePathEditDialogComponent', () => {
let component: StoragePathEditDialogComponent
let settingsService: SettingsService
let documentService: DocumentService
let fixture: ComponentFixture<StoragePathEditDialogComponent>
beforeEach(async () => {
@@ -40,6 +50,7 @@ describe('StoragePathEditDialogComponent', () => {
],
}).compileComponents()
documentService = TestBed.inject(DocumentService)
fixture = TestBed.createComponent(StoragePathEditDialogComponent)
settingsService = TestBed.inject(SettingsService)
settingsService.currentUser = { id: 99, username: 'user99' }
@@ -59,4 +70,87 @@ describe('StoragePathEditDialogComponent', () => {
fixture.detectChanges()
expect(editTitleSpy).toHaveBeenCalled()
})
it('should support test path', () => {
const testSpy = jest.spyOn(
component['service'] as StoragePathService,
'testPath'
)
testSpy.mockReturnValueOnce(of('test/abc123'))
component.objectForm.patchValue({ path: 'test/{{title}}' })
fixture.detectChanges()
component.testPath({ id: 1 })
expect(testSpy).toHaveBeenCalledWith('test/{{title}}', 1)
expect(component.testResult).toBe('test/abc123')
expect(component.testFailed).toBeFalsy()
// test failed
testSpy.mockReturnValueOnce(of(''))
component.testPath({ id: 1 })
expect(component.testResult).toBeNull()
expect(component.testFailed).toBeTruthy()
component.testPath(null)
expect(component.testResult).toBeNull()
})
it('should compare two documents by id', () => {
const doc1 = { id: 1 }
const doc2 = { id: 2 }
expect(component.compareDocuments(doc1, doc1)).toBeTruthy()
expect(component.compareDocuments(doc1, doc2)).toBeFalsy()
})
it('should use id as trackBy', () => {
expect(component.trackByFn({ id: 1 })).toBe(1)
})
it('should search on select text input', () => {
fixture.debugElement
.query(By.directive(NgbAccordionButton))
.triggerEventHandler('click', null)
fixture.detectChanges()
const documents = [
{ id: 1, title: 'foo' },
{ id: 2, title: 'bar' },
]
const listSpy = jest.spyOn(documentService, 'listFiltered')
listSpy.mockReturnValueOnce(
of({
count: 1,
results: documents[0],
all: [1],
} as any)
)
component.documentsInput$.next('bar')
expect(listSpy).toHaveBeenCalledWith(
1,
null,
'created',
true,
[{ rule_type: FILTER_TITLE, value: 'bar' }],
{ truncate_content: true }
)
listSpy.mockReturnValueOnce(
of({
count: 2,
results: [...documents],
all: [1, 2],
} as any)
)
component.documentsInput$.next('ba')
listSpy.mockReturnValueOnce(throwError(() => new Error()))
component.documentsInput$.next('foo')
})
it('should run path test on path change', () => {
const testSpy = jest.spyOn(component, 'testPath')
component['testDocument'] = { id: 1 } as any
component.objectForm.patchValue(
{ path: 'test/{{title}}' },
{ emitEvent: true }
)
fixture.detectChanges()
expect(testSpy).toHaveBeenCalled()
})
})

View File

@@ -1,9 +1,25 @@
import { Component } from '@angular/core'
import { Component, OnDestroy } from '@angular/core'
import { FormControl, FormGroup } from '@angular/forms'
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'
import {
Subject,
Observable,
concat,
of,
distinctUntilChanged,
takeUntil,
tap,
switchMap,
map,
catchError,
filter,
} from 'rxjs'
import { EditDialogComponent } from 'src/app/components/common/edit-dialog/edit-dialog.component'
import { Document } from 'src/app/data/document'
import { FILTER_TITLE } from 'src/app/data/filter-rule-type'
import { DEFAULT_MATCHING_ALGORITHM } from 'src/app/data/matching-model'
import { StoragePath } from 'src/app/data/storage-path'
import { DocumentService } from 'src/app/services/rest/document.service'
import { StoragePathService } from 'src/app/services/rest/storage-path.service'
import { UserService } from 'src/app/services/rest/user.service'
import { SettingsService } from 'src/app/services/settings.service'
@@ -13,24 +29,34 @@ import { SettingsService } from 'src/app/services/settings.service'
templateUrl: './storage-path-edit-dialog.component.html',
styleUrls: ['./storage-path-edit-dialog.component.scss'],
})
export class StoragePathEditDialogComponent extends EditDialogComponent<StoragePath> {
export class StoragePathEditDialogComponent
extends EditDialogComponent<StoragePath>
implements OnDestroy
{
public documentsInput$ = new Subject<string>()
public foundDocuments$: Observable<Document[]>
private testDocument: Document
public testResult: string
public testFailed: boolean = false
public loading = false
public testLoading = false
private unsubscribeNotifier: Subject<any> = new Subject()
constructor(
service: StoragePathService,
activeModal: NgbActiveModal,
userService: UserService,
settingsService: SettingsService
settingsService: SettingsService,
private documentsService: DocumentService
) {
super(service, activeModal, userService, settingsService)
this.initPathObservables()
}
get pathHint() {
return (
$localize`e.g.` +
' <code class="text-nowrap">{{ created_year }}-{{ title }}</code> ' +
$localize`or use slashes to add directories e.g.` +
' <code class="text-nowrap">{{ created_year }}/{{ title }}</code>. ' +
$localize`See <a target="_blank" href="https://docs.paperless-ngx.com/advanced_usage/#file-name-handling">documentation</a> for full list.`
)
ngOnDestroy(): void {
this.unsubscribeNotifier.next(this)
this.unsubscribeNotifier.complete()
}
getCreateTitle() {
@@ -51,4 +77,71 @@ export class StoragePathEditDialogComponent extends EditDialogComponent<StorageP
permissions_form: new FormControl(null),
})
}
public testPath(document: Document) {
if (!document) {
this.testResult = null
return
}
this.testDocument = document
this.testLoading = true
;(this.service as StoragePathService)
.testPath(this.objectForm.get('path').value, document.id)
.subscribe((result) => {
if (result?.length) {
this.testResult = result
this.testFailed = false
} else {
this.testResult = null
this.testFailed = true
}
this.testLoading = false
})
}
compareDocuments(document: Document, selectedDocument: Document) {
return document.id === selectedDocument.id
}
private initPathObservables() {
this.objectForm
.get('path')
.valueChanges.pipe(
takeUntil(this.unsubscribeNotifier),
filter((path) => path && !!this.testDocument)
)
.subscribe(() => {
this.testPath(this.testDocument)
})
this.foundDocuments$ = concat(
of([]), // default items
this.documentsInput$.pipe(
tap(() => console.log('searching')),
distinctUntilChanged(),
takeUntil(this.unsubscribeNotifier),
tap(() => (this.loading = true)),
switchMap((title) =>
this.documentsService
.listFiltered(
1,
null,
'created',
true,
[{ rule_type: FILTER_TITLE, value: title }],
{ truncate_content: true }
)
.pipe(
map((result) => result.results),
catchError(() => of([])), // empty on error
tap(() => (this.loading = false))
)
)
)
)
}
trackByFn(item: Document) {
return item.id
}
}

View File

@@ -3,3 +3,7 @@
color: rgba(var(--bs-danger-rgb), var(--bs-text-opacity)) !important;
}
}
.accordion-button {
font-size: 1rem;
}

View File

@@ -20,7 +20,7 @@
(change)="onChange(value)"
[disabled]="disabled"
[placeholder]="placeholder"
rows="6">
rows="4">
</textarea>
@if (hint) {
<small class="form-text text-muted" [innerHTML]="hint | safeHtml"></small>

View File

@@ -1,7 +1,35 @@
import { StoragePathService } from './storage-path.service'
import { commonAbstractNameFilterPaperlessServiceTests } from './abstract-name-filter-service.spec'
import { Subscription } from 'rxjs'
import { HttpTestingController } from '@angular/common/http/testing'
import { TestBed } from '@angular/core/testing'
import { environment } from 'src/environments/environment'
let httpTestingController: HttpTestingController
let service: StoragePathService
let subscription: Subscription
const endpoint = 'storage_paths'
commonAbstractNameFilterPaperlessServiceTests(
'storage_paths',
StoragePathService
)
describe(`Additional service tests for StoragePathservice`, () => {
beforeEach(() => {
httpTestingController = TestBed.inject(HttpTestingController)
service = TestBed.inject(StoragePathService)
})
afterEach(() => {
subscription?.unsubscribe()
httpTestingController.verify()
})
it('should support testing path', () => {
subscription = service.testPath('path', 11).subscribe()
httpTestingController
.expectOne(`${environment.apiBaseUrl}${endpoint}/test/`)
.flush('ok')
})
})

View File

@@ -2,6 +2,7 @@ import { HttpClient } from '@angular/common/http'
import { Injectable } from '@angular/core'
import { StoragePath } from 'src/app/data/storage-path'
import { AbstractNameFilterService } from './abstract-name-filter-service'
import { Observable } from 'rxjs'
@Injectable({
providedIn: 'root',
@@ -10,4 +11,11 @@ export class StoragePathService extends AbstractNameFilterService<StoragePath> {
constructor(http: HttpClient) {
super(http, 'storage_paths')
}
public testPath(path: string, documentID: number): Observable<any> {
return this.http.post<string>(`${this.getResourceUrl()}test/`, {
path,
document: documentID,
})
}
}