build(ui): expand application shell and implement administrative dashboard pages
This commit significantly expands the application's routing, navigation, and administrative capabilities. It introduces several new functional modules and refines the core layout for a more professional, dashboard-oriented experience. - **Routing & Navigation**: - Added routes for `wallboard`, `call-center`, `call-center/calls`, and `chat-questions`. - Updated `SidebarComponent` to include all new navigation items. - Enhanced `LayoutComponent` with dynamic navigation based on user roles (admin vs. user). - **New Administrative Pages**: - `WallboardPage`: Implements a real-time KPI dashboard with call activity trends and outcome distributions. - `CallCenterPage`: Provides a symbolic interface for managing call center connectivity and synchronization. - `CallCenterCallsPage`: Implements a call history retrieval interface with filtering capabilities. - `ChatQuestionsPage`: Adds a module for reviewing user questions from web and mobile channels. - **Core Infrastructure & Refinement**: - Updated `AppConfig` to include an `APP_INITIALIZER` for validating user identity via `AuthService` on startup. - Refined `HomeComponent` layout to a "Claude-style" continuous chat column. - Implemented global themed scrollbars and integrated the 'Lahze' font family. - Added `proxy.conf.json` and updated `angular.json` to support local backend development. - **Documentation**: - Added comprehensive API handoff guides for frontend-backend connection and MVP API catalog.
This commit is contained in:
@@ -0,0 +1,166 @@
|
||||
import { provideZonelessChangeDetection } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient, HttpEventType } from '@angular/common/http';
|
||||
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { provideAnimations } from '@angular/platform-browser/animations';
|
||||
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
|
||||
import { DocumentsService } from './documents.service';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
|
||||
describe('DocumentsService (backend handoff contract)', () => {
|
||||
let service: DocumentsService;
|
||||
let httpMock: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideZonelessChangeDetection(),
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
provideRouter([]),
|
||||
provideAnimations(),
|
||||
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
|
||||
{ provide: AuthService, useValue: { getCsrfToken: () => 'csrf-abc' } },
|
||||
],
|
||||
});
|
||||
service = TestBed.inject(DocumentsService);
|
||||
httpMock = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpMock.verify();
|
||||
});
|
||||
|
||||
it('uses same-origin /api/v1 paths for every MVP endpoint', () => {
|
||||
service.getConfiguration().subscribe();
|
||||
const req = httpMock.expectOne('/api/v1/configuration');
|
||||
expect(req.request.method).toBe('GET');
|
||||
req.flush({});
|
||||
|
||||
service.getDocuments({ status: 'ready', is_active: true }).subscribe();
|
||||
const list = httpMock.expectOne('/api/v1/documents?status=ready&is_active=true');
|
||||
list.flush({ items: [], next_cursor: null, knowledge_revision: 1 });
|
||||
|
||||
service.getKnowledgeSelection().subscribe();
|
||||
const selection = httpMock.expectOne('/api/v1/knowledge-selection');
|
||||
selection.flush({ active_document_ids: [], revision: 1 });
|
||||
});
|
||||
|
||||
it('sends the caller idempotency key for uploads and reuses FormData without manual Content-Type', () => {
|
||||
const file = new File([new Uint8Array([1, 2, 3])], 'faq.pdf', { type: 'application/pdf' });
|
||||
const progress: number[] = [];
|
||||
|
||||
service.uploadDocument(file, 'عنوان', (percent) => progress.push(percent), undefined, 'key-upload-1').subscribe();
|
||||
|
||||
const req = httpMock.expectOne('/api/v1/documents');
|
||||
expect(req.request.method).toBe('POST');
|
||||
expect(req.request.headers.get('Idempotency-Key')).toBe('key-upload-1');
|
||||
expect(req.request.headers.get('X-CSRF-Token')).toBe('csrf-abc');
|
||||
// The browser must own the multipart boundary.
|
||||
expect(req.request.headers.get('Content-Type')).toBeNull();
|
||||
expect((req.request.body as FormData).get('title')).toBe('عنوان');
|
||||
req.event({ type: HttpEventType.UploadProgress, loaded: 3, total: 3 });
|
||||
req.flush(
|
||||
{ document_id: 'doc-1', job_id: 'job-1' },
|
||||
{ status: 202, statusText: 'Accepted' },
|
||||
);
|
||||
expect(progress).toEqual([100]);
|
||||
});
|
||||
|
||||
it('sends the same decision key on replay and forbids an empty note payload shape', () => {
|
||||
service
|
||||
.submitReviewDecision('doc-1', {
|
||||
evidence_sha256: 'sha-1',
|
||||
decision: 'approve',
|
||||
checked: ['check-a'],
|
||||
note: 'تأیید شد',
|
||||
excluded_group_ids: [],
|
||||
}, 'key-decision-1')
|
||||
.subscribe();
|
||||
|
||||
const req = httpMock.expectOne('/api/v1/documents/doc-1/extraction-review/decisions');
|
||||
expect(req.request.method).toBe('POST');
|
||||
expect(req.request.headers.get('Idempotency-Key')).toBe('key-decision-1');
|
||||
expect(req.request.body).toEqual({
|
||||
evidence_sha256: 'sha-1',
|
||||
decision: 'approve',
|
||||
checked: ['check-a'],
|
||||
note: 'تأیید شد',
|
||||
excluded_group_ids: [],
|
||||
});
|
||||
req.flush({ decision_id: 'dec-1', review_state: 'pending' });
|
||||
|
||||
// Replaying the SAME key must hit the same URL with the same payload — the server
|
||||
// deduplicates it (Idempotency-Replayed: true) instead of creating a second decision.
|
||||
service
|
||||
.submitReviewDecision(
|
||||
'doc-1',
|
||||
{
|
||||
evidence_sha256: 'sha-1',
|
||||
decision: 'approve',
|
||||
checked: ['check-a'],
|
||||
note: 'تأیید شد',
|
||||
excluded_group_ids: [],
|
||||
},
|
||||
'key-decision-1',
|
||||
)
|
||||
.subscribe();
|
||||
const replay = httpMock.expectOne('/api/v1/documents/doc-1/extraction-review/decisions');
|
||||
expect(replay.request.headers.get('Idempotency-Key')).toBe('key-decision-1');
|
||||
replay.flush({ decision_id: 'dec-1', review_state: 'pending' }, {
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
headers: { 'Idempotency-Replayed': 'true' },
|
||||
} as never);
|
||||
});
|
||||
|
||||
it('retries the same job through D04 with an explicit idempotency key', () => {
|
||||
service.retryDocument('doc-1', 'key-retry-1').subscribe();
|
||||
|
||||
const req = httpMock.expectOne('/api/v1/documents/doc-1/retry');
|
||||
expect(req.request.method).toBe('POST');
|
||||
expect(req.request.headers.get('Idempotency-Key')).toBe('key-retry-1');
|
||||
req.flush({ job_id: 'job-1', status: 'queued' }, { status: 202, statusText: 'Accepted' });
|
||||
});
|
||||
|
||||
it('replaces the whole selection with a revision guard and no idempotency key (K02)', () => {
|
||||
service.updateKnowledgeSelection({ expected_revision: 3, document_ids: ['doc-1', 'doc-2'] }).subscribe();
|
||||
|
||||
const req = httpMock.expectOne('/api/v1/knowledge-selection');
|
||||
expect(req.request.method).toBe('PATCH');
|
||||
expect(req.request.body).toEqual({ expected_revision: 3, document_ids: ['doc-1', 'doc-2'] });
|
||||
// K02 is revision-controlled: no Idempotency-Key header.
|
||||
expect(req.request.headers.get('Idempotency-Key')).toBeNull();
|
||||
expect(req.request.headers.get('X-CSRF-Token')).toBe('csrf-abc');
|
||||
req.flush({ revision: 4, active_document_ids: ['doc-1', 'doc-2'], conversations_invalidated: true });
|
||||
});
|
||||
|
||||
it('surfaces the error envelope code and request id for correlation', () => {
|
||||
let captured: { code: string; message: string; requestId?: string } = { code: '', message: '' };
|
||||
service.updateKnowledgeSelection({ expected_revision: 9, document_ids: [] }).subscribe({
|
||||
error: (err) => {
|
||||
captured = DocumentsService.getErrorInfo(err);
|
||||
},
|
||||
});
|
||||
|
||||
httpMock.expectOne('/api/v1/knowledge-selection').flush(
|
||||
{ error: { code: 'REVISION_CONFLICT', message: 'Request could not be completed.', request_id: 'corr-1', retryable: false } },
|
||||
{ status: 409, statusText: 'Conflict', headers: { 'X-Request-ID': 'corr-1' } },
|
||||
);
|
||||
|
||||
expect(captured.code).toBe('REVISION_CONFLICT');
|
||||
expect(captured.requestId).toBe('corr-1');
|
||||
expect(DocumentsService.statusForError(captured.code, captured.message)).toContain('همزمان');
|
||||
});
|
||||
|
||||
it('maps contract error codes to Persian guidance', () => {
|
||||
expect(DocumentsService.statusForError('DOCUMENT_NOT_READY', '')).toContain('آماده');
|
||||
expect(DocumentsService.statusForError('EXTRACTION_REVIEW_PENDING', '')).toContain('بازبینی');
|
||||
expect(DocumentsService.statusForError('REVIEW_STALE', '')).toContain('شواهد');
|
||||
expect(DocumentsService.statusForError('CONTEXT_REVOKED', '')).toContain('باطل');
|
||||
expect(DocumentsService.statusForError('RATE_LIMITED', '')).toContain('حد مجاز');
|
||||
expect(DocumentsService.isPolling('processing')).toBe(true);
|
||||
expect(DocumentsService.isPolling('ready')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,244 @@
|
||||
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 {
|
||||
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': crypto.randomUUID() };
|
||||
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 = crypto.randomUUID(),
|
||||
): 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 = crypto.randomUUID(),
|
||||
): 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 = crypto.randomUUID(),
|
||||
): Observable<RetryResult> {
|
||||
return this.http.postRaw<RetryResult>(
|
||||
`${API}/documents/${encodeURIComponent(documentId)}/retry`,
|
||||
{},
|
||||
{ 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
/**
|
||||
* Type definitions for the MVP document / knowledge-selection / extraction-review API.
|
||||
* Source of truth: docs/backend-api-docs/mvp_ui_api_catalog.md
|
||||
*
|
||||
* These endpoints return *raw* JSON (not the ApiResult envelope used by the legacy
|
||||
* HttpService envelope methods), so they are consumed through `getRaw`/`postRaw`/
|
||||
* `patchRaw`/`uploadWithProgress` and errors are inspected via the standard
|
||||
* `{ error: { code, message, request_id, retryable, details } }` envelope.
|
||||
*/
|
||||
|
||||
/** Document processing lifecycle. */
|
||||
export type DocumentStatus = 'queued' | 'processing' | 'ready' | 'failed';
|
||||
|
||||
/** Frozen-per-document OCR review policy state (D03). */
|
||||
export type ReviewState = 'not_evaluated' | 'not_required' | 'pending' | 'approved' | 'rejected';
|
||||
|
||||
/** Extraction quality decision; never fabricate a human-approval claim from it. */
|
||||
export type ExtractionQualityDecision = null | 'passed' | 'reviewed' | 'partially_reviewed';
|
||||
|
||||
export interface DocumentLocation {
|
||||
page?: number | null;
|
||||
section?: string | null;
|
||||
}
|
||||
|
||||
export interface DocumentJobError {
|
||||
code: string;
|
||||
message: string;
|
||||
request_id?: string;
|
||||
retryable?: boolean;
|
||||
details?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface DocumentJob {
|
||||
id: string;
|
||||
status: string;
|
||||
stage: string | null;
|
||||
attempt_count: number;
|
||||
retry_generation: number;
|
||||
can_retry: boolean;
|
||||
error: DocumentJobError | null;
|
||||
}
|
||||
|
||||
/** A single document row as returned by `GET /documents` (D02). */
|
||||
export interface DocumentListItem {
|
||||
id: string;
|
||||
title: string | null;
|
||||
filename: string;
|
||||
status: DocumentStatus;
|
||||
is_active: boolean;
|
||||
searchable: boolean;
|
||||
chunk_count: number;
|
||||
created_at: string;
|
||||
job: DocumentJob;
|
||||
/** Present on the detail/polling response (D03); absent from the base list. */
|
||||
review_required?: boolean;
|
||||
/** Frozen OCR policy of this document (D03); the UI has no toggle for it. */
|
||||
ocr_review_required?: boolean;
|
||||
review_state?: ReviewState;
|
||||
extraction_quality_decision?: ExtractionQualityDecision;
|
||||
}
|
||||
|
||||
/** `GET /documents` (D02) paginated result. */
|
||||
export interface DocumentListResponse {
|
||||
items: DocumentListItem[];
|
||||
next_cursor: string | null;
|
||||
knowledge_revision: number;
|
||||
}
|
||||
|
||||
/** Query parameters accepted by `GET /documents`. */
|
||||
export interface DocumentListParams {
|
||||
limit?: number;
|
||||
cursor?: string;
|
||||
status?: DocumentStatus;
|
||||
is_active?: boolean;
|
||||
}
|
||||
|
||||
/** `GET /documents/{id}` (D03) — same as a list item plus the review flag. */
|
||||
export interface DocumentDetail extends DocumentListItem {
|
||||
review_required: boolean;
|
||||
}
|
||||
|
||||
/** `POST /documents` (D01) accepted payload. */
|
||||
export interface DocumentUploadResult {
|
||||
document_id: string;
|
||||
job_id: string;
|
||||
status: DocumentStatus;
|
||||
is_active: boolean;
|
||||
searchable: boolean;
|
||||
}
|
||||
|
||||
/** `POST /documents/{id}/retry` (D04) accepted payload. */
|
||||
export interface RetryResult {
|
||||
document_id: string;
|
||||
job_id: string;
|
||||
status: DocumentStatus;
|
||||
retry_generation: number;
|
||||
}
|
||||
|
||||
/** A single extraction block from `GET /documents/{id}/extraction-review` (D06). */
|
||||
export interface ExtractionBlock {
|
||||
block_id: string;
|
||||
text: string;
|
||||
group_id: string | null;
|
||||
}
|
||||
|
||||
/** One reviewable evidence item from D06 (extraction or factual_corpus). */
|
||||
export interface ExtractionItem {
|
||||
evidence_sha256: string;
|
||||
review_kind: string;
|
||||
location?: DocumentLocation | null;
|
||||
blocks: ExtractionBlock[];
|
||||
required_checks: string[];
|
||||
decision: 'approve' | 'reject' | null;
|
||||
/** Authenticated preview URL from the server (may be null, e.g. factual evidence). */
|
||||
preview_path: string | null;
|
||||
}
|
||||
|
||||
/** `GET /documents/{id}/extraction-review` (D06). */
|
||||
export interface ExtractionReviewResponse {
|
||||
document_id: string;
|
||||
status: DocumentStatus;
|
||||
review_required: boolean;
|
||||
items: ExtractionItem[];
|
||||
next_cursor: string | null;
|
||||
}
|
||||
|
||||
/** `POST /documents/{id}/extraction-review/decisions` (D07). */
|
||||
export interface ReviewDecisionRequest {
|
||||
evidence_sha256: string;
|
||||
decision: 'approve' | 'reject';
|
||||
checked: string[];
|
||||
note?: string;
|
||||
excluded_group_ids?: string[];
|
||||
}
|
||||
|
||||
export interface ReviewDecisionResponse {
|
||||
document_id: string;
|
||||
evidence_sha256: string;
|
||||
decision: 'approve' | 'reject';
|
||||
review_required: boolean;
|
||||
}
|
||||
|
||||
/** System configuration / capabilities from `GET /configuration` (F01). */
|
||||
export interface SystemConfiguration {
|
||||
revision: number;
|
||||
assistant_name: string;
|
||||
instruction: string;
|
||||
capabilities: SystemCapabilities;
|
||||
}
|
||||
|
||||
export interface SystemCapabilities {
|
||||
text: boolean;
|
||||
voice: boolean;
|
||||
captions: boolean;
|
||||
supported_upload_types: string[];
|
||||
max_upload_bytes: number;
|
||||
max_pdf_pages: number;
|
||||
supported_structure_notes: string;
|
||||
}
|
||||
|
||||
/** `GET /knowledge-selection` (K01). */
|
||||
export interface KnowledgeSelection {
|
||||
revision: number;
|
||||
access_epoch: number;
|
||||
document_ids: string[];
|
||||
}
|
||||
|
||||
/** `PATCH /knowledge-selection` (K02) request / response. */
|
||||
export interface KnowledgeSelectionPatch {
|
||||
expected_revision: number;
|
||||
document_ids: string[];
|
||||
}
|
||||
|
||||
export interface KnowledgeSelectionResponse extends KnowledgeSelection {
|
||||
conversations_invalidated: boolean;
|
||||
}
|
||||
|
||||
/** Standard error envelope carried on a non-2xx response body. */
|
||||
export interface ErrorEnvelope {
|
||||
error: {
|
||||
code: string;
|
||||
message: string;
|
||||
request_id?: string;
|
||||
retryable?: boolean;
|
||||
details?: Record<string, unknown>;
|
||||
};
|
||||
}
|
||||
|
||||
/** Persian labels for document processing status. */
|
||||
export const DOCUMENT_STATUS_LABEL: Record<DocumentStatus, string> = {
|
||||
queued: 'در صف پردازش',
|
||||
processing: 'در حال پردازش',
|
||||
ready: 'آماده',
|
||||
failed: 'ناموفق',
|
||||
};
|
||||
Reference in New Issue
Block a user