import { HttpClient } from '@angular/common/http' import { Injectable, inject, signal } from '@angular/core' import { EMPTY, Observable, Subject } from 'rxjs' import { catchError, finalize, first, map, switchMap, takeUntil, tap, } from 'rxjs/operators' import { PaperlessTask, PaperlessTaskStatus, PaperlessTaskStatusCounts, PaperlessTaskType, } from 'src/app/data/paperless-task' import { Results } from 'src/app/data/results' import { environment } from 'src/environments/environment' @Injectable({ providedIn: 'root', }) export class TasksService { private http = inject(HttpClient) private baseUrl: string = environment.apiBaseUrl private endpoint: string = 'tasks' private readonly defaultReloadPageSize = 1000 public loading: boolean = false private readonly tasks = signal([]) private readonly reloadNotifier = new Subject() private unsubscribeNotifer: Subject = new Subject() constructor() { this.reloadNotifier .pipe( switchMap(() => { this.loading = true return this.http .get>(`${this.baseUrl}${this.endpoint}/`, { params: { acknowledged: 'false', page_size: this.defaultReloadPageSize, }, }) .pipe( map((response) => response.results), takeUntil(this.unsubscribeNotifer), catchError(() => EMPTY), finalize(() => { this.loading = false }) ) }) ) .subscribe((tasks) => { this.tasks.set(tasks) }) } public get needsAttentionTasks(): PaperlessTask[] { return this.tasks().filter((t) => [PaperlessTaskStatus.Failure, PaperlessTaskStatus.Revoked].includes( t.status ) ) } public reload() { this.reloadNotifier.next() } public list( page: number, pageSize: number, extraParams?: Record ): Observable> { return this.http.get>( `${this.baseUrl}${this.endpoint}/`, { params: { page, page_size: pageSize, ...extraParams, }, } ) } public statusCounts( extraParams?: Record ): Observable { return this.http.get( `${this.baseUrl}${this.endpoint}/status_counts/`, { params: extraParams, } ) } public dismissTasks(task_ids: Set): Observable { return this.http .post(`${this.baseUrl}tasks/acknowledge/`, { tasks: [...task_ids], }) .pipe( first(), takeUntil(this.unsubscribeNotifer), tap(() => { this.reload() }) ) } public dismissAllTasks(): Observable { return this.http .post(`${this.baseUrl}tasks/acknowledge/`, { all: true, }) .pipe( first(), takeUntil(this.unsubscribeNotifer), tap(() => { this.reload() }) ) } public cancelPending(): void { this.unsubscribeNotifer.next(true) } public run(taskType: PaperlessTaskType): Observable<{ task_id: string }> { return this.http.post<{ task_id: string }>( `${environment.apiBaseUrl}${this.endpoint}/run/`, { task_type: taskType } ) } }