Files
faq_chatbot_frontend/src/app/services/http-request/http.service.ts
T
Peyman Honarjoo ff7fcbc4bb 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.
2026-10-10 00:20:00 +03:30

395 lines
13 KiB
TypeScript

import { Injectable } from '@angular/core';
import {
HttpClient,
HttpErrorResponse,
HttpHeaders,
HttpEvent,
HttpEventType,
} from '@angular/common/http';
import { Router } from '@angular/router';
import { catchError, Observable, throwError, map, race } from 'rxjs';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrService } from 'ngx-toastr';
export interface ApiResult<T> {
hasError: boolean;
messages: string[];
result: T;
}
export interface ApiResultArray<T> {
hasError: boolean;
messages: string[];
result: {
data: T[];
};
}
export interface HttpOptions {
params?: any;
skipToast?: boolean;
cooldownMs?: number;
skipHasErrorCheck?: boolean;
headers?: Record<string, string>;
/** Optional AbortSignal forwarded to the underlying XMLHttpRequest. */
signal?: AbortSignal;
}
export const EVENT_STREAM_HEADERS = {
Accept: 'text/event-stream',
'Cache-Control': 'no-cache',
'X-Requested-With': 'XMLHttpRequest',
};
@Injectable({
providedIn: 'root',
})
export class HttpService {
/**
* Same-origin deployment: the browser talks to `/api/v1/...` on the UI origin and
* the dev-server proxy (proxy.conf.json) forwards `/api` — including WebSocket
* upgrades — to the backend. The `rag_session` cookie therefore stays same-origin
* and is sent automatically; no bearer token is used for the MVP endpoints.
*/
private readonly baseUrl = 'http://10.0.8.51:1321';
public readonly backendUrl = 'http://10.0.8.51:1321';
public readonly apiUrl = 'http://10.0.8.51:1321';
public readonly imagesUrl = 'http://10.0.8.51:1321';
constructor(
private readonly http: HttpClient,
private readonly router: Router,
private readonly toast: ToastrService,
private readonly modal: NgbModal,
) {
this.messageCooldowns = new Map();
this.DEFAULT_COOLDOWN_MS = 30000;
}
private readonly messageCooldowns: Map<string, number>;
private readonly DEFAULT_COOLDOWN_MS: number;
private getToken(): string | null {
return localStorage.getItem('access_token');
}
private getHeaders(): HttpHeaders {
const token = this.getToken();
let headers = new HttpHeaders();
if (token) {
headers = headers.set('Authorization', `Bearer ${token}`);
}
return headers;
}
private shouldDisplayMessage(message: string, customCooldown?: number): boolean {
const cooldown = customCooldown ?? this.DEFAULT_COOLDOWN_MS;
const now = Date.now();
const lastShown = this.messageCooldowns.get(message);
if (lastShown !== undefined && now - lastShown < cooldown) {
return false;
}
this.messageCooldowns.set(message, now);
return true;
}
private handleUnauthorized(): void {
this.toast.clear();
localStorage.removeItem('access_token');
this.modal.dismissAll();
this.toast.error('جلسه منقضی شده است. لطفاً دوباره وارد شوید.');
this.router.navigate(['/login']);
}
private handleError(error: HttpErrorResponse, skipToast = false): Observable<never> {
if (error.status === 401) {
this.handleUnauthorized();
return throwError(() => new Error('Unauthorized'));
}
if (error.status === 429 && !skipToast) {
if (this.shouldDisplayMessage('تلاش‌های بیش از حد مجاز. لطفاً بعداً تلاش کنید.')) {
this.toast.warning('تلاش‌های بیش از حد مجاز. لطفاً بعداً تلاش کنید.');
}
return throwError(() => new Error('RATE_LIMITED'));
}
if (error.status === 422 && error.error && !skipToast) {
try {
const apiError = error.error as ApiResult<any>;
if (apiError?.hasError && Array.isArray(apiError.messages)) {
apiError.messages.forEach((msg) => {
if (this.shouldDisplayMessage(msg)) {
this.toast.error(msg);
}
});
return throwError(() => new Error(apiError.messages.join('; ')));
}
} catch (e) {
if (this.shouldDisplayMessage('خطای نامشخص در پردازش پاسخ سرور.')) {
this.toast.error('خطای نامشخص در پردازش پاسخ سرور.');
}
return throwError(() => new Error('Invalid server response'));
}
}
return throwError(() => error);
}
private processResponse<T>(response: ApiResult<T>, options?: HttpOptions): ApiResult<T> {
if (!response || !Array.isArray(response.messages)) {
if (
!options?.skipToast &&
this.shouldDisplayMessage('پاسخ سرور نامعتبر است.', options?.cooldownMs)
) {
this.toast.error('پاسخ سرور نامعتبر است.');
}
throw new Error('Invalid server response');
}
if (!options?.skipToast) {
response.messages.forEach((message) => {
if (!this.shouldDisplayMessage(message, options?.cooldownMs)) {
return;
}
response.hasError ? this.toast.error(message) : this.toast.success(message);
});
}
if (response.hasError && !options?.skipHasErrorCheck) {
throw new Error(response.messages.join('; '));
}
return response;
}
get<T>(endpoint: string, options: HttpOptions = {}): Observable<ApiResult<T>> {
const url = `${this.baseUrl}/${endpoint}`;
const headers = this.mergeHeaders(options.headers);
return this.http
.get<ApiResult<T>>(url, {
headers,
params: options.params,
})
.pipe(
map((response) => this.processResponse(response, options)),
catchError((err) => this.handleError(err, options.skipToast)),
);
}
private getAuthHeaderObject(): Record<string, string> {
const token = this.getToken();
return token ? { Authorization: `Bearer ${token}` } : {};
}
private mergeHeaders(extra?: Record<string, string>): HttpHeaders {
let headers = this.getHeaders();
if (extra) {
Object.entries(extra).forEach(([key, value]) => {
headers = headers.set(key, value as string);
});
}
return headers;
}
getStream<T = any>(endpoint: string, headers: Record<string, string> = {}): Observable<T> {
const url = `${this.baseUrl}/${endpoint}`;
return new Observable<T>((observer) => {
const controller = new AbortController();
fetch(url, {
method: 'GET',
headers: {
...EVENT_STREAM_HEADERS,
...this.getAuthHeaderObject(),
...headers,
},
signal: controller.signal,
credentials: 'same-origin',
})
.then((response) => {
if (!response.ok || !response.body) {
throw new Error(`Stream request failed: ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
const pump = (): void => {
reader
.read()
.then(({ done, value }) => {
if (done) {
observer.complete();
return;
}
buffer += decoder.decode(value, { stream: true });
const frames = buffer.split('\n\n');
buffer = frames.pop() ?? '';
for (const frame of frames) {
const dataLines = frame
.split('\n')
.filter((line) => line.startsWith('data:'))
.map((line) => line.slice(5).trim());
if (dataLines.length === 0) continue;
const payload = dataLines.join('\n');
try {
observer.next(JSON.parse(payload) as T);
} catch {
observer.next(payload as unknown as T);
}
}
pump();
})
.catch((err) => {
if (!controller.signal.aborted) observer.error(err);
});
};
pump();
})
.catch((err) => observer.error(err));
return () => controller.abort();
});
}
post<T>(endpoint: string, data: any, options: HttpOptions = {}): Observable<ApiResult<T>> {
const url = `${this.baseUrl}/${endpoint}`;
return this.http
.post<ApiResult<T>>(url, data, {
headers: this.mergeHeaders(options.headers),
params: options.params,
})
.pipe(
map((response) => this.processResponse(response, options)),
catchError((err) => this.handleError(err, options.skipToast)),
);
}
postRaw<T>(endpoint: string, data: any, options: HttpOptions = {}): Observable<T> {
const url = `${this.baseUrl}/${endpoint}`;
const headers = options.headers ? new HttpHeaders(options.headers) : new HttpHeaders();
return this.http.post<T>(url, data, {
headers,
params: options.params,
});
}
/**
* Raw PATCH (no envelope processing, no bearer token): used by MVP endpoints
* such as `PATCH /knowledge-selection` whose auth is the `rag_session` cookie.
*/
patchRaw<T>(endpoint: string, data: any, options: HttpOptions = {}): Observable<T> {
const url = `${this.baseUrl}/${endpoint}`;
const headers = options.headers ? new HttpHeaders(options.headers) : new HttpHeaders();
return this.http
.patch<T>(url, data, { headers, params: options.params })
.pipe(catchError((err) => this.handleError(err, options.skipToast)));
}
/**
* Multipart upload that reports byte-level progress as `HttpEvent`s.
* Auth is the session cookie (same origin), so — like `postRaw`/`getRaw` — the
* bearer token is not injected; pass `X-CSRF-Token` / `Idempotency-Key` via `options.headers`.
* Cancellation is driven by racing the request against an `AbortSignal`-derived error;
* the race's teardown unsubscribes and aborts the in-flight XHR.
*/
uploadWithProgress<T>(
endpoint: string,
data: FormData,
options: HttpOptions = {},
): Observable<HttpEvent<T>> {
const url = `${this.baseUrl}/${endpoint}`;
const headers = options.headers ? new HttpHeaders(options.headers) : new HttpHeaders();
const http$ = this.http.post<T>(url, data, {
headers,
params: options.params,
reportProgress: true,
observe: 'events',
});
if (!options.signal) {
return http$.pipe(catchError((err) => this.handleError(err, options.skipToast)));
}
const abort$ = new Observable<never>((subscriber) => {
if (options.signal!.aborted) {
subscriber.error(new HttpErrorResponse({ status: 0, statusText: 'Aborted', url }));
return;
}
const onAbort = () =>
subscriber.error(new HttpErrorResponse({ status: 0, statusText: 'Aborted', url }));
options.signal!.addEventListener('abort', onAbort);
return () => options.signal!.removeEventListener('abort', onAbort);
});
return race(http$, abort$).pipe(catchError((err) => this.handleError(err, options.skipToast)));
}
getRaw<T>(endpoint: string, options: HttpOptions = {}): Observable<T> {
const url = `${this.baseUrl}/${endpoint}`;
const headers = options.headers ? new HttpHeaders(options.headers) : new HttpHeaders();
return this.http.get<T>(url, {
headers,
params: options.params,
});
}
put<T>(endpoint: string, data: any, options: HttpOptions = {}): Observable<ApiResult<T>> {
const url = `${this.baseUrl}/${endpoint}`;
return this.http
.put<ApiResult<T>>(url, data, {
headers: this.mergeHeaders(options.headers),
params: options.params,
})
.pipe(
map((response) => this.processResponse(response, options)),
catchError((err) => this.handleError(err, options.skipToast)),
);
}
patch<T>(endpoint: string, data: any, options: HttpOptions = {}): Observable<ApiResult<T>> {
const url = `${this.baseUrl}/${endpoint}`;
return this.http
.patch<ApiResult<T>>(url, data, {
headers: this.mergeHeaders(options.headers),
params: options.params,
})
.pipe(
map((response) => this.processResponse(response, options)),
catchError((err) => this.handleError(err, options.skipToast)),
);
}
delete<T>(endpoint: string, options: HttpOptions = {}): Observable<ApiResult<T>> {
const url = `${this.baseUrl}/${endpoint}`;
return this.http
.delete<ApiResult<T>>(url, {
headers: this.mergeHeaders(options.headers),
params: options.params,
})
.pipe(
map((response) => this.processResponse(response, options)),
catchError((err) => this.handleError(err, options.skipToast)),
);
}
downloadFile(endpoint: string): Observable<Blob> {
const url = `${this.baseUrl}/${endpoint}`;
return this.http
.get(url, {
headers: this.getHeaders(),
responseType: 'blob',
})
.pipe(catchError((err) => this.handleError(err, false)));
}
}