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,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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user