Files
faq_chatbot_frontend/src/app/services/documents/documents.service.ts
T

246 lines
9.7 KiB
TypeScript

import { Injectable, inject } from '@angular/core';
import { HttpErrorResponse, HttpEventType, HttpHeaders, HttpParams } from '@angular/common/http';
import { map, filter, Observable, tap } from 'rxjs';
import { HttpService } from '../http-request/http.service';
import { AuthService } from '../auth/auth.service';
import { uuid } from '../../shared/utils/uuid';
import {
DocumentDetail,
DocumentListParams,
DocumentListResponse,
DocumentStatus,
DocumentUploadResult,
ErrorEnvelope,
ExtractionItem,
ExtractionReviewResponse,
KnowledgeSelection,
KnowledgeSelectionPatch,
KnowledgeSelectionResponse,
RetryResult,
ReviewDecisionRequest,
ReviewDecisionResponse,
SystemConfiguration,
} from './documents.types';
/** Base path for the documented MVP endpoints (`/api/v1/...`), served same-origin. */
const API = 'api/v1';
@Injectable({ providedIn: 'root' })
export class DocumentsService {
private readonly http = inject(HttpService);
private readonly auth = inject(AuthService);
/**
* Headers required for every state-changing MVP call: a fresh CSRF token
* (from the login/`/me` flow) and a per-request correlation id.
*/
private csrfHeaders(): Record<string, string> {
const headers: Record<string, string> = { 'X-Request-ID': uuid() };
const token = this.auth.getCsrfToken();
if (token) {
headers['X-CSRF-Token'] = token;
}
return headers;
}
/**
* Idempotent operations (D01 upload, D07 decisions, D04 retry) take the caller's key:
* an ambiguous failure (timeout / dropped connection) must replay the SAME key with the
* SAME payload — minting a new key would create a second document/decision/retry.
* `Idempotency-Replayed: true` on a successful replay confirms the server deduplicated it.
*/
private idempotencyHeaders(key: string): Record<string, string> {
return { ...this.csrfHeaders(), 'Idempotency-Key': key };
}
private onlyDefined(params: DocumentListParams): Record<string, string> {
const out: Record<string, string> = {};
if (params.limit != null) out['limit'] = String(params.limit);
if (params.cursor) out['cursor'] = params.cursor;
if (params.status) out['status'] = params.status;
if (params.is_active != null) out['is_active'] = String(params.is_active);
return out;
}
/** F01 — read-only capabilities used to configure upload validation. */
getConfiguration(): Observable<SystemConfiguration> {
return this.http.getRaw<SystemConfiguration>(`${API}/configuration`, { skipToast: true });
}
/** D02 — paginated document list. */
getDocuments(params: DocumentListParams = {}): Observable<DocumentListResponse> {
const query = new HttpParams({ fromObject: this.onlyDefined(params) });
return this.http.getRaw<DocumentListResponse>(`${API}/documents`, {
params: query,
skipToast: true,
});
}
/** D03 — single document detail (used for 2-second status polling). */
getDocument(id: string): Observable<DocumentDetail> {
return this.http.getRaw<DocumentDetail>(`${API}/documents/${encodeURIComponent(id)}`, {
skipToast: true,
});
}
/**
* D01 — upload a single document with live progress.
* @param idempotencyKey caller-owned key; replay the SAME key for an uncertain outcome.
*/
uploadDocument(
file: File,
title: string | undefined,
onProgress: (percent: number) => void,
signal?: AbortSignal,
idempotencyKey: string = uuid(),
): Observable<DocumentUploadResult> {
const form = new FormData();
form.append('file', file);
if (title) {
form.append('title', title);
}
return this.http
.uploadWithProgress<DocumentUploadResult>(`${API}/documents`, form, {
headers: this.idempotencyHeaders(idempotencyKey),
skipToast: true,
signal,
})
.pipe(
tap((event) => {
if (event.type === HttpEventType.UploadProgress && event.total) {
onProgress(Math.round((100 * event.loaded) / event.total));
}
}),
filter((event) => event.type === HttpEventType.Response),
map(
(event) =>
(event as import('@angular/common/http').HttpResponse<DocumentUploadResult>)
.body as DocumentUploadResult,
),
);
}
/** D07 — submit an extraction-review decision (approve/reject). */
submitReviewDecision(
documentId: string,
request: ReviewDecisionRequest,
idempotencyKey: string = uuid(),
): Observable<ReviewDecisionResponse> {
return this.http.postRaw<ReviewDecisionResponse>(
`${API}/documents/${encodeURIComponent(documentId)}/extraction-review/decisions`,
request,
{ headers: this.idempotencyHeaders(idempotencyKey), skipToast: true },
);
}
/** D06 — extraction-review evidence items. */
getExtractionReview(documentId: string, cursor?: string): Observable<ExtractionReviewResponse> {
const params: Record<string, string> = {};
if (cursor) {
params['cursor'] = cursor;
}
return this.http.getRaw<ExtractionReviewResponse>(
`${API}/documents/${encodeURIComponent(documentId)}/extraction-review`,
{ params, skipToast: true },
);
}
/** D04 — retry processing of a document. */
retryDocument(
documentId: string,
idempotencyKey: string = uuid(),
): Observable<RetryResult> {
return this.http.postRaw<RetryResult>(
`${API}/documents/${encodeURIComponent(documentId)}/retry`,
null,
{ headers: this.idempotencyHeaders(idempotencyKey), skipToast: true },
);
}
/** K01 — current active-knowledge selection (revision + active document ids). */
getKnowledgeSelection(): Observable<KnowledgeSelection> {
return this.http.getRaw<KnowledgeSelection>(`${API}/knowledge-selection`, { skipToast: true });
}
/**
* K02 — replace the whole active-knowledge selection. The full set is keyed by
* `expected_revision` (no Idempotency-Key): after a timeout or REVISION_CONFLICT the UI
* re-reads K01 first instead of blindly repeating the request.
*/
updateKnowledgeSelection(patch: KnowledgeSelectionPatch): Observable<KnowledgeSelectionResponse> {
return this.http.patchRaw<KnowledgeSelectionResponse>(`${API}/knowledge-selection`, patch, {
headers: this.csrfHeaders(),
skipToast: true,
});
}
/** Extract the standard error envelope from an HttpErrorResponse, if present. */
static getErrorInfo(error: unknown): { code: string; message: string; requestId?: string } {
const res = error as HttpErrorResponse | undefined;
const envelope = res?.error as ErrorEnvelope | undefined;
const code = envelope?.error?.code ?? (res?.status === 0 ? 'NETWORK' : 'UNKNOWN');
const message = envelope?.error?.message ?? res?.message ?? 'خطای ناشناخته سرور';
const requestId =
envelope?.error?.request_id ??
(res?.headers?.get?.('X-Request-ID') as string | undefined) ??
undefined;
return { code, message, requestId };
}
/** Map a backend error code to a user-facing Persian message (handoff §10 / catalog §7). */
static statusForError(code: string, fallback: string): string {
switch (code) {
case 'DOCUMENT_NOT_READY':
return 'فقط اسناد وضعیت آماده قابل فعال‌سازی هستند.';
case 'EXTRACTION_REVIEW_PENDING':
return 'قبل از تلاش مجدد، شواهد نیازمند بازبینی را تکمیل کنید.';
case 'REVISION_CONFLICT':
return 'لیست دانش همزمان توسط کاربر دیگری به‌روز شده است. صفحه را تازه‌سازی کنید.';
case 'IDEMPOTENCY_CONFLICT':
return 'این عملیات قبلاً با محتوای دیگری ثبت شده است.';
case 'REVIEW_STALE':
case 'REVIEW_ALREADY_DECIDED':
return 'شواهد بازبینی تغییر کرده است؛ موارد را دوباره خوانده و تصمیم بگیرید.';
case 'FILE_TOO_LARGE':
case 'PAYLOAD_TOO_LARGE':
return 'حجم فایل یا درخواست بیش از حد مجاز است.';
case 'UNSUPPORTED_FILE_TYPE':
return 'نوع فایل پشتیبانی نمی‌شود.';
case 'INVALID_FILE':
return 'فایل قابل پردازش نیست.';
case 'VALIDATION_ERROR':
return 'شکل درخواست نامعتبر است.';
case 'CONTEXT_REVOKED':
case 'CONVERSATION_STALE':
return 'مکالمه‌های صوتی قبلی به‌دلیل تغییر محتوای دانش باطل شده‌اند. گفتگوی جدیدی شروع کنید.';
case 'LIVE_SESSION_UNUSABLE':
return 'نشست صوتی بسته شده است. گفتگوی جدیدی شروع کنید.';
case 'RATE_LIMITED':
return 'تلاش‌های بیش از حد مجاز. لطفاً بعداً تلاش کنید.';
case 'CALIBRATION_REQUIRED':
case 'DEPENDENCY_UNAVAILABLE':
return 'سرویس موقتاً در دسترس نیست. لطفاً دوباره تلاش کنید.';
case 'AUTH_REQUIRED':
return 'ابتدا وارد سیستم شوید.';
case 'CSRF_INVALID':
return 'نشست شما نامعتبر است. دوباره وارد شوید.';
case 'FORBIDDEN':
return 'دسترسی به این عملیات مجاز نیست.';
case 'NETWORK':
return 'ارتباط با سرور برقرار نشد.';
default:
return fallback;
}
}
/** True if the backend status is a terminal state (no more polling). */
static isTerminal(status: DocumentStatus): boolean {
return status === 'ready' || status === 'failed';
}
/** Whether a status row still needs to be polled per D03. */
static isPolling(status: DocumentStatus): boolean {
return !DocumentsService.isTerminal(status);
}
}