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 { const headers: Record = { '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 { return { ...this.csrfHeaders(), 'Idempotency-Key': key }; } private onlyDefined(params: DocumentListParams): Record { const out: Record = {}; 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 { return this.http.getRaw(`${API}/configuration`, { skipToast: true }); } /** D02 — paginated document list. */ getDocuments(params: DocumentListParams = {}): Observable { const query = new HttpParams({ fromObject: this.onlyDefined(params) }); return this.http.getRaw(`${API}/documents`, { params: query, skipToast: true, }); } /** D03 — single document detail (used for 2-second status polling). */ getDocument(id: string): Observable { return this.http.getRaw(`${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 { const form = new FormData(); form.append('file', file); if (title) { form.append('title', title); } return this.http .uploadWithProgress(`${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) .body as DocumentUploadResult, ), ); } /** D07 — submit an extraction-review decision (approve/reject). */ submitReviewDecision( documentId: string, request: ReviewDecisionRequest, idempotencyKey: string = uuid(), ): Observable { return this.http.postRaw( `${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 { const params: Record = {}; if (cursor) { params['cursor'] = cursor; } return this.http.getRaw( `${API}/documents/${encodeURIComponent(documentId)}/extraction-review`, { params, skipToast: true }, ); } /** D04 — retry processing of a document. */ retryDocument( documentId: string, idempotencyKey: string = uuid(), ): Observable { return this.http.postRaw( `${API}/documents/${encodeURIComponent(documentId)}/retry`, null, { headers: this.idempotencyHeaders(idempotencyKey), skipToast: true }, ); } /** K01 — current active-knowledge selection (revision + active document ids). */ getKnowledgeSelection(): Observable { return this.http.getRaw(`${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 { return this.http.patchRaw(`${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); } }