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:
Peyman Honarjoo
2026-10-10 00:20:00 +03:30
parent 0b5a882ecb
commit ff7fcbc4bb
71 changed files with 9148 additions and 780 deletions
+4 -15
View File
@@ -56,6 +56,9 @@
},
"serve": {
"builder": "@angular/build:dev-server",
"options": {
"proxyConfig": "proxy.conf.json"
},
"configurations": {
"production": {
"buildTarget": "faq-chatbot:build:production"
@@ -74,21 +77,7 @@
"options": {
"tsConfig": "tsconfig.spec.json",
"runner": "vitest",
"buildTarget": "faq-chatbot:build:development",
"assets": [
{
"glob": "**/*",
"input": "public"
},
{
"glob": "**/*",
"input": "src/assets",
"output": "assets"
}
],
"styles": [
"src/styles.css"
]
"buildTarget": "faq-chatbot:build:development"
}
}
}
@@ -0,0 +1,445 @@
# راهنمای اتصال UI به backend دستیار اسناد و مکالمهٔ صوتی
تاریخ تهیه: ۲۰۲۶-۱۰-۰۹
این فایل برای توسعه‌دهندهٔ frontend تهیه شده است تا UI موجود را به backend فعلی وصل کند. قرارداد مرورگر برای Gemini Live و OpenAI Realtime یکسان است؛ انتخاب provider و کلیدهای آن فقط سمت backend قرار دارند. فعلاً Gemini پیش‌فرض موقت است.
این راهنما دستور اتصال است و به معنی پذیرش اجراشدهٔ UI، کیفیت گفتار فارسی یا سخت‌افزار مرورگر نیست. نمونه‌های JSON شکل داده را نشان می‌دهند؛ شناسه، digest، revision و مسیر نشست باید از پاسخ واقعی سرور گرفته شوند.
## ۱. اطلاعاتی که تیم backend باید تحویل دهد
پیش از تست مشترک، جدول زیر با اطلاعات محیط واقعی تکمیل شود. جای‌خالی‌ها نباید به تنظیمات اجرایی تبدیل شوند.
| مورد | مقدار مورد توافق |
| ---------------------------------------------- | --------------------------------------------------------------- |
| آدرس backend قابل‌دسترسی از ماشین اجرای پراکسی | `TO_BE_PROVIDED`؛ پیش‌فرض محلی Compose: `http://localhost:8080` |
| آدرس و Origin دقیق UI | `TO_BE_PROVIDED`؛ نمونهٔ محلی: `http://localhost:5173` |
| نسخهٔ مشترک backend و فایل‌های نمونه | commit یا snapshot مورد توافق: `TO_BE_PROVIDED` |
| حساب تست administrator | نام کاربری و رمز از مسیر جداگانه و امن تحویل شوند |
| حساب تست user | نام کاربری و رمز از مسیر جداگانه و امن تحویل شوند |
| فایل نمونه برای آپلود و بازبینی انسانی | `TO_BE_PROVIDED` |
| سند آماده و انتخاب‌شده برای تست مکالمه | شناسهٔ واقعی و سؤال دارای پاسخ در همان سند: `TO_BE_PROVIDED` |
| آمادگی صوت و calibration | تیم backend وضعیت واقعی را اعلام کند؛ UI نیز F01 را بخواند |
| زمان تست مشترک مرورگر، میکروفن و بلندگو | `TO_BE_PROVIDED` |
اگر frontend و backend روی دو ماشین جدا اجرا می‌شوند، `localhost` در target پراکسی به ماشین frontend اشاره می‌کند. آدرس قابل‌دسترسی backend را جایگزین کنید.
کلید provider، رمز دیتابیس و فایل `.env` حاوی اسرار وارد کد، build، تنظیمات عمومی یا storage مرورگر نشوند. UI برای ورود فقط اطلاعات حساب کاربردی دریافت می‌کند.
## ۲. فایل‌های همراه و مرجع قرارداد
این فایل Markdown همراه با فایل‌های زیر تحویل شود. لینک‌ها نسبت به محل این فایل در repository هستند؛ برای تحویل خارج از repository، فایل‌های اشاره‌شده را نیز ارسال کنید.
| فایل | کاربرد |
| --------------------------------------------------------------- | --------------------------------------------------------------- |
| [راهنمای backend فاز ۳](realtime-agent-phase3-handoff.md) | قرارداد اسناد، review، retry، selection و تنظیمات توسعه |
| [راهنمای صوت](frontend-voice-integration-example.md) | جریان صوت، کنترل‌ها، رویدادها و recovery |
| [API catalog](../specifications/RAG-Phase1-API-Catalog.md) | قرارداد مرجع API؛ فقط endpointهای MVP در این تحویل استفاده شوند |
| [document-client.js](../../examples/document-client.js) | helper عملیات اسناد و configuration |
| [voice-client.js](../../examples/voice-client.js) | helper ورود، ساخت نشست، صوت و cleanup |
| [voice-audio-worklet.js](../../examples/voice-audio-worklet.js) | capture و playback و گزارش نمونه‌های واقعاً پخش‌شده |
| [vite-proxy.config.js](../../examples/vite-proxy.config.js) | پراکسی توسعهٔ HTTP و WebSocket |
helperها نمونهٔ توسعه‌اند؛ مدیریت صفحات، وضعیت UI، خطا، درخواست‌های لغوشده و ذخیرهٔ تلاش‌های نامطمئن بر عهدهٔ frontend است. در صورت اختلاف با یک پاسخ واقعی، کد خطا و request ID را به تیم backend بدهید؛ پاسخ یا قرارداد را خودسرانه بازتعریف نکنید.
## ۳. محدودهٔ UI و مسئولیت طرفین
| قابلیت | مسئولیت UI | مسئولیت backend |
| ---------- | ----------------------------------------------------------------- | ------------------------------------------------------- |
| ورود و نقش | فرم ورود، نگهداری وضعیت کاربر، نمایش قابلیت‌های مجاز | cookie، اعتبارسنجی حساب و مجوز هر درخواست |
| اسناد | آپلود، نمایش وضعیت، مرور شواهد، approve/reject، retry و selection | ذخیرهٔ immutable، پردازش worker، کنترل review و انتشار |
| صوت | میکروفن، playback، transcript، منابع، توقف و recovery | اتصال provider، ابزار جست‌وجو، lifecycle و کنترل دسترسی |
| خطا | پیام قابل‌فهم و اقدام مناسب، نگهداری شناسهٔ خطا | error envelope امن و correlation |
`admin` به اسناد، review، retry و selection دسترسی دارد. `admin` و `user` می‌توانند configuration را بخوانند و مکالمهٔ صوتی متعلق به خودشان را بسازند. پنهان‌کردن دکمه در UI جای کنترل مجوز سرور را نمی‌گیرد.
در MVP فعلی UI برای ثبت‌نام عمومی، مدیریت حساب، حذف سند، ویرایش configuration، انتخاب مدل/provider، public text chat یا تاریخچهٔ کامل و پایدار transcript ساخته نشود. routeهای deferred در API catalog به معنی route قابل‌استفاده نیستند.
## ۴. تنظیم اتصال محلی
### پراکسی same-origin
در مثال فعلی UI روی `http://localhost:5173` است و API از میزبان روی `8080` در دسترس خواهد بود. مرورگر تمام HTTPها را به `/api/v1/...` روی Origin خود UI می‌فرستد. پراکسی همان مسیر `/api` را بدون حذف prefix به backend منتقل می‌کند.
نمونهٔ Vite را در configuration موجود ادغام کنید؛ تنظیمات دیگر پروژه را جایگزین نکنید:
```js
export default {
server: {
host: 'localhost',
port: 5173,
strictPort: true,
proxy: {
'/api': {
target: 'http://127.0.0.1:8080',
ws: true,
changeOrigin: false,
},
},
},
};
```
`changeOrigin: false`، Host مرورگر را حفظ می‌کند. تیم backend برای این مثال محلی تنظیم کند:
```dotenv
TRUSTED_HOSTS=["localhost:5173","localhost:8080"]
TRUSTED_ORIGINS=["http://localhost:5173"]
COOKIE_SECURE=false
```
Host دوم برای دسترسی مستقیم محلی به health و schema است؛ اجرای mutation از Origin دیگری نیازمند تنظیم صریح همان Origin است. در محیط HTTPS، cookie باید Secure باشد و اتصال صوت WSS باشد. از wildcard برای CORS همراه credentials استفاده نشود. مرورگر برای میکروفن و AudioWorklet به secure context، مثل HTTPS یا localhost، نیاز دارد.
پیش‌فرض Docker Compose: API داخل container روی `8000` و روی میزبان با `${API_PORT:-8080}` منتشر می‌شود. اگر `API_PORT` عوض شد، target پراکسی را هماهنگ کنید. برای اجرای مستقیم مطابق این مثال، تیم backend از یک API process روی `8080` و worker جداگانه استفاده کند:
```sh
python -m app.server --host 0.0.0.0 --port 8080
python -m app.worker
```
آماده‌سازی دیتابیس، migration، حساب‌ها، storage، credentials و calibration وظیفهٔ تیم backend است. شروع worker می‌تواند provider call ایجاد کند و باید مطابق مجوز محیط انجام شود. frontend چند API worker یا reload برای محیط تست صوت درخواست نکند.
### تشخیص اتصال
با Host مجاز و backend آماده:
- `GET http://localhost:8080/health/live`: پاسخ `200` و `{"status":"ok"}`.
- `GET http://localhost:8080/health/ready`: پاسخ `200` هنگام readiness و `503` هنگام آماده‌نبودن.
- `GET http://localhost:8080/openapi.json`: schema محیط جاری.
- `http://localhost:8080/docs`: نمایش schema؛ اجرای درخواست‌های تعاملی نیز باید الزامات Origin/CSRF را رعایت کند.
پراکسی نمونه فقط `/api` را منتقل می‌کند؛ برای health از آدرس مستقیم مجاز استفاده کنید، یا مسیر health را صریحاً در پراکسی خود اضافه کنید. هیچ‌کدام از healthها گواه کیفیت provider نیستند.
## ۵. احراز هویت و قرارداد HTTP
تمام routeهای جدول‌های بعدی زیر `/api/v1` هستند.
| عملیات | درخواست | نتیجه |
| ---------------------- | --------------------------------------------- | -------------------------------- |
| ورود | `POST /auth/login` با `username` و `password` | `200`، cookie و user/CSRF/expiry |
| خواندن یا refresh هویت | `GET /me` | `200` با همان شکل هویت؛ یا `401` |
| خروج | `POST /auth/logout` بدون body | `204` بدون JSON |
| خواندن قابلیت‌ها | `GET /configuration` | `200` برای هر دو نقش |
نمونهٔ ورود:
```json
{ "username": "<test-account>", "password": "<password-from-login-form>" }
```
شکل پاسخ ورود و `/me`:
```json
{
"user": {
"id": "<server-user-id>",
"username": "<actual-username>",
"role": "admin",
"organization_id": "<server-organization-id>"
},
"csrf_token": "<server-csrf-token>",
"expires_at": "<server-ISO-timestamp>"
}
```
- cookie به نام `rag_session`، HttpOnly است؛ آن را از JavaScript نخوانید و token جایگزین نسازید.
- در معماری same-origin از `credentials: 'same-origin'` استفاده کنید.
- mutationهای authenticated، شامل upload و ساخت نشست، `X-CSRF-Token` می‌خواهند. CSRF از login یا `/me` گرفته شود. login خودش trusted Origin می‌خواهد.
- پس از reload ابتدا `/me` را بخوانید. روی `401` وضعیت authenticated را پاک و ورود مجدد را نمایش دهید.
- برای `FormData`، Content-Type را دستی ننویسید؛ browser باید boundary را بسازد. برای JSON از `application/json` استفاده کنید.
- پاسخ `204` را با `response.json()` نخوانید.
- `organization_id`، actor، reviewer یا مدل را برای تحمیل scope در درخواست‌ها اضافه نکنید.
configuration شامل `revision`، `assistant_name`، `instruction` و `capabilities` است. UI از مقادیر واقعی `text`، `voice`، `captions`، `supported_upload_types`، `max_upload_bytes`، `max_pdf_pages` و مشخصات audio استفاده کند. در صورت `voice=false`، شروع صوت غیرفعال و پیش‌نیاز به تیم backend اعلام شود؛ این flag گواه کیفیت گفتار نیست. `ocr_review_required` در configuration سیاست فعلی deployment است، نه سیاست همهٔ اسناد قبلی.
## ۶. جریان اسناد برای administrator
| عملیات | route | موفقیت و نکته |
| ------------------ | ----------------------------------------------------------- | ------------------------------------------------ |
| آپلود | `POST /documents` | `202`؛ multipart؛ required `Idempotency-Key` |
| فهرست | `GET /documents` | `200`؛ pagination و فیلتر |
| polling جزئیات | `GET /documents/{document_id}` | `200`؛ وضعیت واقعی processing/review/retry |
| شواهد pending | `GET /documents/{document_id}/extraction-review` | `200`؛ paginated |
| preview | مسیر `preview_path` در پاسخ شواهد | تصویر authenticated؛ بدون path ساخته‌شده توسط UI |
| تصمیم انسانی | `POST /documents/{document_id}/extraction-review/decisions` | `200`؛ JSON و required `Idempotency-Key` |
| retry همان job | `POST /documents/{document_id}/retry` | `202`؛ بدون body و required `Idempotency-Key` |
| خواندن selection | `GET /knowledge-selection` | `200` |
| جایگزینی selection | `PATCH /knowledge-selection` | `200`؛ کل مجموعه با expected revision |
### آپلود و وضعیت
body فقط یک `file` و `title` اختیاری دارد. title حداکثر ۲۰۰ کاراکتر است؛ محدودیت فایل را از configuration بخوانید. UI اعتبارسنجی اولیه انجام دهد، ولی format و محتوا را سرور تصمیم می‌گیرد.
```js
const uploadKey = crypto.randomUUID();
const uploaded = await documents.upload(file, title, uploadKey);
// uploaded.document_id و uploaded.job_id را از پاسخ واقعی نگه دارید.
```
هر upload با کلید تازه یک سند مستقل می‌سازد. برای نتیجهٔ نامطمئن همان File، title و کلید را نگه دارید و همان درخواست را replay کنید؛ تولید کلید جدید می‌تواند سند دیگری بسازد. کلید در header `Idempotency-Key` ارسال می‌شود. replay موفق header `Idempotency-Replayed: true` دارد؛ تغییر payload زیر همان کلید، `409 IDEMPOTENCY_CONFLICT` می‌دهد.
تا زمانی که document وضعیت `queued` یا `processing` دارد polling کنید؛ فاصلهٔ پیشنهادی دو ثانیه است، در tab پنهان آهسته‌تر شود. polling با خروج از صفحه لغو شود و پاسخ دیررس نتواند سند جدیدِ انتخاب‌شده در UI را بازنویسی کند. درصد پیشرفت ساختگی نمایش ندهید؛ از `job.stage` و وضعیت واقعی استفاده کنید.
| وضعیت یا فیلد پاسخ | رفتار UI |
| ---------------------------------- | -------------------------------------------- |
| `queued` / `processing` | نمایش انتظار و مرحله، ادامهٔ polling |
| `failed` و `review_required=true` | دریافت و نمایش شواهد pending |
| `failed` و `job.can_retry=true` | امکان retry صریح؛ علت خطا نیز نمایش داده شود |
| `failed` و `review_state=rejected` | نمایش رد؛ retry خودکار انجام نشود |
| `ready` و `is_active=false` | آمادهٔ انتخاب؛ هنوز وارد جست‌وجو نشده است |
| `searchable=true` | سند طبق پاسخ فعلی سرور قابل جست‌وجو است |
`job.error` ممکن است null یا شامل `code`، `message` و `retryable` باشد. امکان retry را از `job.can_retry` بگیرید؛ صرف `retryable=true` مجوز retry خودکار نیست.
فهرست اسناد `limit` پیش‌فرض ۲۰ و حداکثر ۱۰۰ دارد؛ فیلترهای `status` و `is_active` پشتیبانی می‌شوند. پاسخ شامل `items`، `next_cursor` و `knowledge_revision` است. cursor opaque است؛ آن را تغییر ندهید و در query URL encode کنید.
### review و سیاست OCR
شواهد review پیش‌فرض ۱۰ و حداکثر ۲۰ item در هر صفحه دارد. از `next_cursor` برای ادامه استفاده کنید. اگر مجموعه پس از تصمیم‌ها تغییر کرد و cursor نامعتبر شد، pendingها را دوباره از ابتدای مجموعه بخوانید. item شامل digest واقعی، `review_kind`، blocks، `required_checks` و preview احتمالی است.
UI برای انسان، متن دقیق، گروه‌های Q&A و تصویر موجود را نمایش دهد. تصمیم approve/reject و یادداشت از انسان گرفته شود؛ روی دکمهٔ approve تمام چک‌ها به‌طور خودکار تأیید نشوند.
```json
{
"evidence_sha256": "<digest-from-current-review-item>",
"decision": "approve",
"checked": ["<actual-required-check-names-confirmed-by-human>"],
"note": "<nonblank-human-review-note>",
"excluded_group_ids": []
}
```
برای approval، مجموعهٔ `checked` باید دقیقاً با چک‌های موردنیاز item تطبیق کند. note غیرخالی و حداکثر ۲۰۰۰ کاراکتر است. برای rejection نیز note لازم است؛ چک‌های تکمیل‌نشده را تأییدشده وانمود نکنید.
در review استخراج، `excluded_group_ids` باید خالی باشد. در `factual_corpus` فقط گروه‌های کامل موجود را می‌توان exclude کرد؛ دست‌کاری متن اصلی یا حذف نیمهٔ سؤال/پاسخ مجاز نیست. approval باید دست‌کم یک گروه factual واجد شرایط باقی بگذارد و placeholderهای نامعتبر را وارد corpus نکند. `preview_path` برای factual ممکن است null باشد.
سیاست `INGEST_OCR_REVIEW_REQUIRED` فقط تنظیم backend است، default آن true است و در هر job ثابت می‌ماند. UI از فیلدهای همان document استفاده کند:
- `ocr_review_required`: سیاست frozen آن سند.
- `review_required`: وجود تصمیم pending.
- `review_state`: `not_evaluated`، `not_required`، `pending`، `approved` یا `rejected`.
- `extraction_quality_decision`: null، `passed`، `reviewed` یا `partially_reviewed`؛ بدون ساختن ادعای تأیید انسانی.
false بودن سیاست OCR، review factual یا reviewهای دیگر را حذف نمی‌کند. UI toggle برای تغییر این سیاست ندارد. در preview از URL سرور با cookie استفاده کنید؛ path ذخیره‌سازی یا URL provider ساخته نشود.
approve به‌تنهایی retry، انتشار یا activation نمی‌کند. پس از تکمیل pendingها، detail را بخوانید و در صورت `job.can_retry=true`، retry صریح با کلید مستقل ارسال کنید. صفحات بعدی استخراج نیز ممکن است review تازه بخواهند. retry همان سند و همان job را ادامه می‌دهد. retry با body غیرخالی، `422 VALIDATION_ERROR` است.
### selection
برای اضافه یا حذف یک سند، ابتدا K01 را بخوانید، مجموعهٔ کامل جدید را بسازید و K02 را ارسال کنید:
```json
{
"expected_revision": 3,
"document_ids": ["<all-selected-document-ids-in-the-desired-new-set>"]
}
```
`expected_revision` در مثال فرضی است و باید از آخرین K01 بیاید. PATCH یک delta نیست؛ ارسال فقط یک ID می‌تواند بقیهٔ اسناد را حذف کند. شناسه‌ها unique و سندها ready باشند.
بعد از timeout یا `REVISION_CONFLICT` ابتدا K01 را دوباره بخوانید. درخواست قبلی ممکن است commit شده باشد؛ آن را کورکورانه تکرار نکنید. حذف سند فعال می‌تواند epoch را تغییر دهد و نشست‌های صوت قبلی را ببندد. UI منابع قدیمی را معتبر نمایش ندهد و ساخت مکالمهٔ تازه را پیشنهاد کند.
## ۷. ساخت و کنترل نشست صوت
| عملیات | route | کاربرد |
| ------ | ---------------------------------------------------- | ---------------------------------------------- |
| C01 | `POST /conversations` | ساخت owned conversation با `mode=voice`؛ `201` |
| V01 | `POST /voice/sessions` | رزرو session؛ `201` یا replay با `201/202` |
| V02 | `GET /voice/sessions/{session_id}` | وضعیت، diagnostics امن و toolهای اخیر |
| V03 | `GET /voice/sessions/by-request/{client_request_id}` | بازیابی رزرو بدون اتصال provider |
| V04 | `POST /voice/sessions/{session_id}/close` | بستن صریح بدون body؛ `200` |
| media | WebSocket روی `stream_path` دریافتی | یک اتصال فعال؛ cookie و Origin |
ابتدا C01 و سپس V01:
```json
{ "client_request_id": "<conversation-request-uuid>", "mode": "voice" }
```
```json
{ "conversation_id": "<id-from-C01>", "client_request_id": "<session-request-uuid>" }
```
این دو request ID جدا هستند و در JSON می‌آیند؛ با header کلید عملیات سند اشتباه نشوند. پاسخ V01 شامل `session_id`، `conversation_id`، `status`، `stream_path`، `expires_at` و `poll_url` است. مسیر اتصال را از `stream_path` بگیرید؛ route provider یا path ثابت اختراع نکنید.
برای نتیجهٔ نامطمئن، payload و IDهای همان تلاش حفظ و replay شوند. V03 برای reconciliation است و provider جدید باز نمی‌کند. نشست connected یا terminal اتصال media را از نو احیا نمی‌کند؛ recovery به معنی seamless reconnect نیست.
دو WebSocket هم‌زمان برای یک session ساخته نشود. پس از loss، وضعیت را از V02/V03 بگیرید، رزرو قدیمی را ببندید و با اقدام صریح کاربر مکالمه و نشست تازه بسازید. هنگام refresh صفحه، helper فعلی تلاش ایجاد را فقط در حافظهٔ همان instance نگه می‌دارد؛ اگر recovery بین reload لازم است، UI باید IDها و payload همان تلاش را بدون provider secret نگه دارد و ابتدا با سرور reconcile کند.
## ۸. راه‌اندازی helper و فایل صوت
در پروژهٔ UI، دو client module را در مسیر source قرار دهید و worklet را به‌عنوان asset مستقل از همان Origin سرو کنید. برای Vite می‌توان worklet را در `public/voice-audio-worklet.js` گذاشت و URL زیر را به constructor داد. متن worklet باید JavaScript باشد؛ fallback HTML مربوط به SPA برای این URL برنگردد.
```js
import { VoiceClient } from './integrations/voice-client.js';
import { DocumentClient } from './integrations/document-client.js';
// handleVoiceEvent و showFailure توابع UI خودتان هستند.
const voice = new VoiceClient(handleVoiceEvent, '/voice-audio-worklet.js');
const documents = new DocumentClient(voice);
async function signIn(username, password) {
const identity = await voice.login(username, password);
const configuration = await documents.configuration();
return { identity, configuration };
}
async function prepareVoice() {
const configuration = await documents.configuration();
if (!configuration.capabilities.voice) throw new Error('VOICE_UNAVAILABLE');
voice.newCreationAttempt(); // فقط برای یک تلاش واقعاً تازه
return voice.reserve();
}
// ابتدا prepareVoice موفق شود؛ سپس دکمهٔ شروع برای کاربر فعال شود.
// connect مستقیماً از gesture کاربر فراخوانی شود تا AudioContext مجاز باشد.
startButton.addEventListener('click', () => {
void voice.connect().catch(showFailure);
});
stopButton.addEventListener('click', () => {
void voice.close().catch(showFailure);
});
// logoutButton در handler خود voice.logout() را فراخوانی کند.
// route/component هنگام خروج باید voice.close() را await کند و خطا را مدیریت کند.
```
`prepareVoice` را با نشست فعال دوباره اجرا نکنید. پس از timeout ایجاد، به‌جای `newCreationAttempt` از `retryCreation()` همان تلاش استفاده کنید. شروع و cleanup باید برای هر connection مالکیت مشخص داشته باشند؛ جواب دیررس permission یا callback نشست قدیمی نباید نشست جدید را ببندد.
متدهای اصلی نمونه:
| client | متدها |
| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| VoiceClient | `login`، `refreshIdentity`، `newCreationAttempt`، `reserve`، `retryCreation`، `recover`، `poll`، `connect`، `close`، `logout`، `freshSession` |
| DocumentClient | `configuration`، `upload`، `list`، `poll`، `review`، `decide`، `retry`، `selection`، `replace` |
برای recovery صوت، اگر از `freshSession()` استفاده می‌کنید آن را با gesture مناسب کاربر اجرا کنید و روی browser واقعی مجازبودن AudioContext را تست کنید. UI نباید پس از refresh یا قطع شبکه خودکار میکروفن را باز کند.
## ۹. قرارداد صوت و رویدادها
صوت در هر دو جهت raw mono signed PCM16 little-endian با نرخ **۲۴۰۰۰ Hz**، یک channel و بدون WAV header است؛ معادل ۴۸۰۰۰ byte در ثانیه. WebM، Opus یا blob خروجی MediaRecorder را روی این stream نفرستید. capture دستگاه باید به نرخ قرارداد تبدیل شود. helper و worklet این مسیر را پیاده می‌کنند و AudioContext با نرخ نامعتبر را رد می‌کنند.
میکروفن فقط پس از `session_ready` شروع به ارسال کند. سقف هر پیام binary در نمونهٔ فعلی ۹۶۰۰ byte است و طول باید sample-aligned باشد. capture و playback نمونه دارای دو سقف مستقل ۹۶۰۰۰ byte و ۱۰۰ پیام هستند. در adaptation، هر دو کنترل و cleanup آن‌ها حفظ شوند؛ ظرفیت پرشده باید با failure امن پایان یابد، نه با حذف بی‌صدای PCM و ادامهٔ همان context.
| رویداد سرور | رفتار UI |
| --------------------- | -------------------------------------------------------------------------- |
| `session_ready` | session ID و audio format را تطبیق دهید؛ آماده‌شدن واقعی را نمایش دهید |
| `user_speech_started` | turn جدید را با `turn_ref` ثبت کنید |
| `transcript` | برحسب turn و role، partial را به‌روز و completed را نهایی کنید |
| `sources` | منابع را به همان turn/tool call مرتبط کنید؛ منابع turnهای دیگر مخلوط نشوند |
| `audio_started` | `audio_ref` فعلی را برای binaryهای بعدی تعیین کنید |
| `audio_ended` | پایان generation همان audio ref؛ به معنی شنیده‌شدن نیست |
| `turn_interrupted` | صوت صف‌شده را flush و progress نهایی مصرف‌شده را گزارش کنید |
| `error` | خطای turn یا session را با قواعد راهنمای صوت مدیریت کنید |
شکل readiness:
```json
{
"type": "session_ready",
"session_id": "<reserved-session-id>",
"input_audio": { "encoding": "pcm_s16le", "sample_rate": 24000, "channels": 1 },
"output_audio": { "encoding": "pcm_s16le", "sample_rate": 24000, "channels": 1 }
}
```
شکل transcript:
```json
{
"type": "transcript",
"turn_ref": "<server-turn-ref>",
"role": "assistant",
"text": "<actual-transcript>",
"status": "completed"
}
```
تنها کنترل JSON از سمت client:
```json
{ "type": "playback_progress", "audio_ref": "<server-audio-ref>", "played_ms": 120 }
```
`played_ms` مقدار تجمعی واقعی است؛ از sampleهای مصرف‌شدهٔ worklet محاسبه می‌شود، نه elapsed timer، دریافت شبکه یا طول کل فایل. flush یا admission به معنی شنیدن نیست. مقدار را برای هر `audio_ref` جدا نگه دارید و گزارش نهایی interruption را بفرستید. helper این کار را انجام می‌دهد؛ UI کانال progress موازی با شمارش حدسی اضافه نکند.
برای sources از `source_ref`، title و location دریافتی استفاده کنید. location می‌تواند page یا section خالی داشته باشد. منبع، excerpt، لینک دانلود یا مسیر اصل سند را از خودتان نسازید؛ API دانلود اصل سند در این تحویل وجود ندارد. در polling، `available=false` یعنی excerpt قبلی معتبر نیست و نباید همچنان نمایش داده شود.
خطای canonical search برای turn واجد شرایط می‌تواند با توضیح صوتی امن ادامه یابد. خطای setup، transport، overflow، authority یا context sync نشست را متوقف می‌کند. fatal بودن را فقط از `retryable` استنتاج نکنید؛ رفتار helper و قرارداد guide را حفظ کنید. UI ابزار backend را خودش دوباره اجرا نمی‌کند.
### محدودیت‌های فعلی که در UX رعایت شوند
- Gemini فعلاً truncation نمونه‌دقیقِ تأییدشده برای context ندارد؛ interruption می‌تواند نشست را ببندد و نیازمند مکالمهٔ تازه باشد. seamless barge-in وعده داده نشود.
- ورودی commitنشده، شامل سکوت، سقف ده ثانیه دارد. UI ack یا مرز گفتار ساختگی برای دورزدن این محدودیت نفرستد؛ شکست و recovery را مطابق سرور مدیریت کند.
- transcript و منابع متعلق به نشست فعلی‌اند؛ history کامل و ماندگار وعده داده نشود.
- logout، خروج از صفحه و توقف باید trackهای میکروفن، worklet، AudioContext و WebSocket را آزاد کنند. در توقف عمدی، progress نهایی و V04 پیش از بسته‌شدن transport انجام شوند؛ `voice.close()` این ترتیب را اجرا می‌کند.
## ۱۰. خطا و بازیابی
شکل HTTP error:
```json
{
"error": {
"code": "REVISION_CONFLICT",
"message": "Request could not be completed.",
"request_id": "<correlation-uuid>",
"retryable": false
}
}
```
header `X-Request-ID` همان correlation را فراهم می‌کند؛ بعضی خطاها `details` دارند. متن خام error را به‌عنوان تنها UX استفاده نکنید؛ برحسب code پیام فارسی مناسب نمایش دهید. لایهٔ request در UI، status، code و request ID را حفظ کند. DocumentClient این فیلدها را ارائه می‌کند؛ VoiceClient.request نمونه فقط code/status را در exception نگه می‌دارد و برای diagnostics کامل باید metadata امن response را در adaptation حفظ کنید.
| کد یا وضعیت | اقدام |
| ----------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| `401 AUTH_REQUIRED` | cleanup رسانه و ورود مجدد؛ `/me` برای وضعیت هویت |
| `403 CSRF_INVALID` | در صورت باقی‌بودن هویت، refresh از `/me`؛ replay فقط با همان کلید/payload و پس از رفع علت |
| `403 FORBIDDEN` | بررسی نقش یا Host/Origin؛ درخواست تکراری بدون تغییر علت مفید نیست |
| `404 NOT_FOUND` | ID مخفی/حذف‌شده یا رزرو پیدا نشده؛ ابتدا نوع عملیات و تلاش ایجاد را بررسی کنید |
| `409 IDEMPOTENCY_CONFLICT` | payload زیر کلید تغییر کرده؛ تلاش اصلی را reconcile کنید |
| `409 REVISION_CONFLICT` | K01 جدید و اقدام کاربر بر اساس state تازه |
| `409 DOCUMENT_NOT_READY` | موارد rejected در details را نمایش دهید؛ selection ناقص نفرستید |
| `409 EXTRACTION_REVIEW_PENDING` | pendingها را بخوانید و review انسانی را تکمیل کنید |
| `409 DOCUMENT_NOT_RETRYABLE` | detail تازه و شرایط retry؛ دکمه بر اساس can_retry |
| `409 REVIEW_STALE` / `REVIEW_ALREADY_DECIDED` | شواهد و وضعیت تازه؛ approval قدیمی را روی output جدید کپی نکنید |
| `409 LIVE_SESSION_BUSY` | نشست موجود را reconcile کنید؛ اتصال دوم نسازید |
| `CONTEXT_REVOKED` / `CONVERSATION_STALE` | context و خروجی قدیمی را کنار بگذارید؛ نشست تازه، بدون کپی context revoked |
| `413 FILE_TOO_LARGE` / `PAYLOAD_TOO_LARGE` | محدودیت فایل یا envelope درخواست؛ تغییر اندازه به معنی تغییر payload است |
| `415 UNSUPPORTED_FILE_TYPE` | فایل مجاز طبق configuration انتخاب شود |
| `422 INVALID_FILE` / `VALIDATION_ERROR` | مشکل file یا شکل درخواست را اصلاح کنید |
| `429 RATE_LIMITED` | `Retry-After` را رعایت کنید؛ از retry burst جلوگیری کنید |
| `503 DEPENDENCY_UNAVAILABLE` / `CALIBRATION_REQUIRED` | آمادگی backend بررسی شود؛ نتیجهٔ mutation ممکن است نامطمئن باشد |
| قطع WebSocket یا API restart | cleanup، polling/reconciliation و تلاش تازهٔ صریح؛ ادامهٔ context فرضی ممنوع |
انتظار برای دریافت JSON در backend ۱۵ ثانیه و برای body خالی retry پنج ثانیه است؛ محدودیت envelope تصمیم ۶۰٬۱۵۱٬۰۷۲ byte و selection یک MiB است. این‌ها تضمین مدت تکمیل processing نیستند. تایم‌اوت کوتاه client به معنی rollback نیست. helper صوت HTTP deadline پنج ثانیه دارد؛ helper اسناد deadline اختصاصی ندارد و UI باید سیاست timeout و لغو خود را با حفظ semantics عملیات اضافه کند.
هیچ retry خودکار نباید کلید تازهٔ upload/decision/retry بسازد. K02 کلید عملیات سند ندارد و با revision کنترل می‌شود. پس از timeout آن K01 بخوانید. در logout حتی اگر V04 شکست خورد، تلاش برای A02 و پاک‌سازی محلی انجام شود؛ helper فعلی این کار را می‌کند.
در diagnostics فقط زمان، نوع عملیات، status، code، request/session/turn/audio refs لازم ثبت شوند؛ رمز، cookie، CSRF، audio، متن سند و متن خصوصی transcript در log ثبت نشوند.
## ۱۱. معیارهای تست مشترک UI و backend
| سناریو | نتیجهٔ مورد انتظار |
| ------------------------------------- | ------------------------------------------------------------------------- |
| ورود admin و user، reload و `/me` | هویت واقعی و مجوز صحیح؛ CSRF تازه |
| logout هنگام صوت | توقف میکروفن و پخش، revoke حساب session و UI خارج‌شده |
| user روی عملیات اسناد | دسترسی UI محدود و رد واقعی سرور |
| آپلود فایل تازه | document/job واقعی و مستقل، ابتدا inactive |
| timeout یا double-click آپلود | replay با همان کلید؛ سند تکراری ناخواسته ساخته نشود |
| فایل نامعتبر یا بیش‌ازحد | پیام برحسب code و حفظ امکان انتخاب فایل جدید |
| processing و تغییر صفحه | وضعیت واقعی، polling قابل‌لغو و عدم نمایش پاسخ دیررس برای سند دیگر |
| review چندصفحه‌ای و preview | شواهد واقعی، cookie، چک انسانی و تصمیم evidence-bound |
| approve/reject و retry | approve خودکار منتشر نکند؛ rejected ادامه نگیرد؛ retry همان job باشد |
| OCR اختیاری و factual | UI سیاست frozen سند و نیاز مستقل factual را رعایت کند |
| selection و revision conflict | ready-only، کل مجموعه، re-read پس از conflict یا timeout |
| قطع پاسخ C01/V01 | همان تلاش با UUID و payload قبلی replay/reconcile شود |
| شروع صوت با کلیک و permission ردشده | صدای واقعی یا پیام قابل‌فهم، بدون میکروفن یا context رهاشده |
| سؤال فارسی و پیگیری | transcript و sourceها به turn صحیح متصل باشند؛ شنیده‌شدن انسانی بررسی شود |
| پاسخ بی‌مدرک یا خطای جست‌وجو | منبع ساختگی نشان داده نشود؛ خطای turn با fatal session اشتباه نشود |
| interruption هنگام جست‌وجو و playback | صوت قدیمی متوقف، progress واقعی، recovery مطابق provider منتخب |
| قطع provider، شبکه و API restart | cleanup و state سرور روشن؛ اتصال خودکار به همان نشست فرض نشود |
| حذف سند از selection هنگام صوت | نشست قدیمی بی‌اعتبار و excerpt revoked پنهان شود |
| مرورگر یا tab دوم | نشست دیگر مجوز مالکیت ایجاد نکند؛ دو اتصال یک session رد شوند |
برای هر نتیجه، نوع محیط/browser، نسخهٔ مشترک، حساب/نقش بدون رمز، سناریو، زمان و request IDهای امن ثبت شود. provider و hardware واقعی جدا از mock بررسی شوند. هیچ خانهٔ اجرا‌نشده به‌عنوان pass ثبت نشود.
+628
View File
@@ -0,0 +1,628 @@
# RAG Assistant — Frontend MVP API Catalog & Integration Guide
این سند کاتالوگ دقیق و رسمی API برای تیم توسعه رابط کاربری (UI Developer) در فاز **MVP (Phase 1)** است. کلیه اندپوینت‌های غیرمرتبط با MVP (مانند چت متنی، هیستوری قدیمی، ویرایش تنظیمات و حذف فایل) از این کاتالوگ حذف شده‌اند.
---
## ۱. اصول عمومی و استانداردهای ارتباطی (Conventions & Auth)
* **Base URL**: `/api/v1` (روت‌های سلامت خارج از پیشوند هستند: `/health/live` و `/health/ready`).
* **فرمت داده**: تمام درخواست‌ها و پاسخ‌ها به صورت `application/json; charset=utf-8` هستند (به جز اندپوینت آپلود فایل که `multipart/form-data` است).
* **احراز هویت (Authentication)**:
* از کوکی امن HttpOnly به نام `rag_session` استفاده می‌شود که پس از لاگین به صورت خودکار توسط مرورگر ست می‌شود.
* تمام درخواست‌ها باید به همان مبدا (`Same-Origin`) یا مبدا مجاز فرستاده شوند (`credentials: "include"` در `fetch` یا Axios).
* **امنیت CSRF**:
* در کلیه درخواست‌های تغییر وضعیت (`POST` و `PATCH`) پس از لاگین، باید توکن CSRF در هدر فرستاده شود:
`X-CSRF-Token: <token_from_login_or_me>`
* **هدرهای ردیابی و همزمانی (Idempotency)**:
* `X-Request-ID`: شناسه اختیاری کلاینت برای ردیابی لاگ‌ها (در صورت ارسال نشدن، سرور یک مقدار تولید می‌کند).
* `Idempotency-Key`: هدر اجباری (فرمت UUID v4) برای عملیات‌های غیرتکرارپذیر:
* `POST /documents` (آپلود)
* `POST /documents/{id}/retry` (تلاش مجدد)
* `POST /documents/{id}/extraction-review/decisions` (ثبت تصمیم بازبینی)
* **ساختار استاندارد خطا (Error Envelope)**:
در تمامی خطاهای کلاینت/سرور (4xx و 5xx) ساختار پاسخ دقیقاً به این شکل است:
```json
{
"error": {
"code": "REVISION_CONFLICT",
"message": "Selection changed; reload and try again.",
"request_id": "req-98fbc182",
"retryable": false,
"details": {}
}
}
```
---
## ۲. احراز هویت و اطلاعات کاربر (Authentication)
### A01. ورود به سیستم (Login)
* **متد و آدرس**: `POST /api/v1/auth/login`
* **دسترسی**: عمومی (Public)
* **Request Headers**:
* `Content-Type: application/json`
* **Request Body**:
```json
{
"username": "demo.admin",
"password": "SecurePassword123"
}
```
* **Response (200 OK)**:
* مرورگر کوکی `rag_session` را دریافت می‌کند.
```json
{
"user": {
"id": "01000000-0000-4000-8000-000000000001",
"username": "demo.admin",
"role": "admin",
"organization_id": "02000000-0000-4000-8000-000000000001"
},
"csrf_token": "a1b2c3d4e5f6-csrf-token",
"expires_at": "2026-10-08T18:00:00Z"
}
```
* **خطاها**:
* `401 Unauthorized` (`INVALID_CREDENTIALS`): نام کاربری یا رمز عبور اشتباه است.
* `429 Too Many Requests` (`RATE_LIMITED`): تلاش‌های بیش از حد مجاز.
---
### A02. خروج از سیستم (Logout)
* **متد و آدرس**: `POST /api/v1/auth/logout`
* **دسترسی**: لاگین‌شده
* **Request Headers**:
* `X-CSRF-Token: <token>`
* **Response (204 No Content)**: بدون بدنه. کوکی پاک می‌شود و سشن‌های صوتی فعال کاربر بسته می‌شوند.
---
### A03. دریافت وضعیت و هویت کاربر جاری (Current User / Refresh Token)
* **متد و آدرس**: `GET /api/v1/me`
* **دسترسی**: لاگین‌شده
* **Response (200 OK)**:
```json
{
"user": {
"id": "01000000-0000-4000-8000-000000000001",
"username": "demo.admin",
"role": "admin",
"organization_id": "02000000-0000-4000-8000-000000000001"
},
"csrf_token": "a1b2c3d4e5f6-csrf-token",
"expires_at": "2026-10-08T18:00:00Z"
}
```
* **خطاها**:
* `401 Unauthorized` (`AUTH_REQUIRED`): کاربر لاگین نیست یا سشن منقضی شده است.
---
## ۳. تنظیمات و قابلیت‌های سیستم (Configuration - Read-only)
### F01. دریافت قابلیت‌ها و محدودیت‌ها (Capabilities)
UI باید قبل از رندر فرم آپلود یا فضای صوتی این اطلاعات را بخواند تا محدودیت‌های فایل و ویژگی‌های فعال را نمایش دهد.
* **متد و آدرس**: `GET /api/v1/configuration`
* **دسترسی**: لاگین‌شده (Admin یا User)
* **Response (200 OK)**:
```json
{
"revision": 1,
"assistant_name": "سامانه پاسخگوی فنی اسناد",
"instruction": "پاسخ‌ها را دقیق و صرفاً بر اساس مستندات مصوب و به زبان فارسی ارائه دهید.",
"capabilities": {
"text": false,
"voice": true,
"captions": true,
"supported_upload_types": [
"application/pdf",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"image/jpeg",
"image/png",
"text/markdown"
],
"max_upload_bytes": 20971520,
"max_pdf_pages": 50,
"supported_structure_notes": "پشتیبانی از ساختارهای بخشنامه‌ها، جداول، اینفوگرافیک و پرسش‌وپاسخ"
}
}
```
---
## ۴. مدیریت اسناد و پردازش (Admin Documents & Ingestion)
> **نکته دسترسی**: تمامی اندپوینت‌های این بخش نیاز به نقش `role: "admin"` دارند.
### D01. آپلود سند جدید (Upload Document)
* **متد و آدرس**: `POST /api/v1/documents`
* **Request Headers**:
* `Content-Type: multipart/form-data`
* `X-CSRF-Token: <token>`
* `Idempotency-Key: <uuid-v4>` (الزامی)
* **Form Data**:
* `file`: فایل انتخابی (Binary)
* `title`: (اختیاری) عنوان مدرک (حداکثر ۲۰۰ کاراکتر). در صورت عدم ارسال، نام فایل استفاده می‌شود.
* **Response (202 Accepted)**:
```json
{
"document_id": "10000000-0000-4000-8000-000000000001",
"job_id": "40000000-0000-4000-8000-000000000001",
"status": "queued",
"is_active": false,
"searchable": false
}
```
* **خطاها**:
* `413 Payload Too Large` (`FILE_TOO_LARGE`): فایل بزرگتر از `max_upload_bytes` است.
* `415 Unsupported Media Type` (`UNSUPPORTED_FILE_TYPE`): فرمت فایل غیرمجاز است.
* `409 Conflict` (`IDEMPOTENCY_CONFLICT`): ارسال مجدد با همان کلید اما با فایلی متفاوت.
---
### D02. لیست اسناد (List Documents)
* **متد و آدرس**: `GET /api/v1/documents`
* **Query Parameters**:
* `limit`: پیش‌فرض ۲۰، حداکثر ۱۰۰ (اختیاری)
* `cursor`: شناسه مکان‌نما برای صفحه بعد (اختیاری)
* `status`: فیلتر وضعیت: `queued` | `processing` | `ready` | `failed` (اختیاری)
* `is_active`: `true` | `false` (اختیاری)
* **Response (200 OK)**:
```json
{
"items": [
{
"id": "10000000-0000-4000-8000-000000000001",
"title": "دستورالعمل ساعات کاری",
"filename": "working-hours.pdf",
"status": "ready",
"is_active": true,
"searchable": true,
"chunk_count": 8,
"created_at": "2026-10-07T09:00:00Z",
"job": {
"id": "40000000-0000-4000-8000-000000000001",
"status": "succeeded",
"stage": "publish",
"attempt_count": 1,
"retry_generation": 0,
"can_retry": false,
"error": null
}
}
],
"next_cursor": null,
"knowledge_revision": 2
}
```
---
### D03. جزئیات و استعلام وضعیت پردازش سند (Document Detail / Polling)
کلاینت برای اسنادی که در وضعیت `queued` یا `processing` هستند، این اندپوینت را هر ۲ ثانیه Poll می‌کند تا به وضعیت پایانی (`ready` یا `failed`) برسد.
* **متد و آدرس**: `GET /api/v1/documents/{document_id}`
* **Response (200 OK)** (نمونه وضعیت نیازمند بازبینی):
```json
{
"id": "10000000-0000-4000-8000-000000000001",
"title": "ساعات کاری شعب",
"filename": "working-hours.pdf",
"status": "failed",
"is_active": false,
"searchable": false,
"created_at": "2026-10-07T09:00:00Z",
"chunk_count": 0,
"review_required": true,
"job": {
"id": "40000000-0000-4000-8000-000000000001",
"status": "failed",
"stage": "extract",
"attempt_count": 1,
"retry_generation": 0,
"can_retry": false,
"error": {
"code": "EXTRACTION_REVIEW_REQUIRED",
"message": "استخراج تصویر/صفحه نیازمند بازبینی و تایید ادمین است.",
"retryable": true
}
}
}
```
* **توضیح وضعیت `searchable`**:
`searchable = (status == "ready") && (is_active == true)`
---
### D06. دریافت شواهد نیازمند بازبینی (Extraction Review Candidates)
وقتی سندی خطای `review_required: true` خورده باشد، ادمین برای دیدن محتوای استخراج‌شده و مقایسه با تصویر اصلی از این اندپوینت استفاده می‌کند.
* **متد و آدرس**: `GET /api/v1/documents/{document_id}/extraction-review`
* **Response (200 OK)**:
```json
{
"document_id": "10000000-0000-4000-8000-000000000001",
"status": "failed",
"review_required": true,
"items": [
{
"evidence_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"review_kind": "extraction",
"location": {
"page": 1,
"section": "pdf/page/1"
},
"blocks": [
{
"block_id": "pdf/page/1/block/1",
"text": "ساعات کاری کلیه شعب در روزهای پنجشنبه از ساعت ۰۸:۰۰ الی ۱۲:۰۰ می‌باشد.",
"group_id": null
}
],
"required_checks": [
"readability",
"order",
"completeness",
"numbers",
"dates",
"negation",
"exceptions"
],
"decision": null,
"preview_path": "/api/v1/documents/10000000-0000-4000-8000-000000000001/extraction-review/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855/preview"
}
],
"next_cursor": null
}
```
#### پیش‌نمایش تصویر (Preview Subresource):
آدرس داخل فیلد `preview_path` مستقیماً به صورت تگ `<img src="...">` (همراه با کوکی معتبر) قابل نمایش است و تصویر رندرشده صفحه را برمی‌گرداند (`Content-Type: image/jpeg` یا `image/png`).
---
### D07. ثبت تصمیم بازبینی (Submit Review Decision)
برای هر آیتم بازبینی، ادمین باید چک‌باکس‌های الزامی (`required_checks`) را تایید کرده و تصمیم خود را ثبت کند.
* **متد و آدرس**: `POST /api/v1/documents/{document_id}/extraction-review/decisions`
* **Request Headers**:
* `X-CSRF-Token: <token>`
* `Idempotency-Key: <uuid-v4>` (الزامی)
* **Request Body**:
```json
{
"evidence_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"decision": "approve",
"checked": [
"readability",
"order",
"completeness",
"numbers",
"dates",
"negation",
"exceptions"
],
"note": "متن با صفحه اصلی مقایسه و تاریخ و ساعت تایید شد.",
"excluded_group_ids": []
}
```
* **مقادیر فیلد `decision`**: فقط `"approve"` یا `"reject"`.
* **Response (200 OK)**:
```json
{
"document_id": "10000000-0000-4000-8000-000000000001",
"evidence_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"decision": "approve",
"review_required": false
}
```
*(اگر هنوز صفحات دیگری نیاز به بازبینی داشته باشند، `review_required: true` خواهد بود).*
---
### D04. تلاش مجدد برای پردازش سند (Retry Document)
پس از آنکه همه شواهد سندی که نیازمند بازبینی بوده تایید شد (یا اگر سندی به دلیل خطای شبکه در امبدینگ موقتاً fail شده بود)، این اندپوینت فراخوانی می‌شود تا ورکر ادامه پردازش را انجام دهد.
* **متد و آدرس**: `POST /api/v1/documents/{document_id}/retry`
* **Request Headers**:
* `X-CSRF-Token: <token>`
* `Idempotency-Key: <uuid-v4>` (الزامی)
* **Request Body**: ندارد (بدون بدنه).
* **Response (202 Accepted)**:
```json
{
"document_id": "10000000-0000-4000-8000-000000000001",
"job_id": "40000000-0000-4000-8000-000000000001",
"status": "queued",
"retry_generation": 1
}
```
* **خطاها**:
* `409 Conflict` (`EXTRACTION_REVIEW_PENDING`): هنوز آیتم‌های تاییدنشده برای این سند باقی مانده است.
* `409 Conflict` (`DOCUMENT_NOT_RETRYABLE`): سند در حال پردازش یا وضعیت غیرقابل تلاش مجدد است.
---
## ۵. انتخاب دانش فعال برای سرچ صوتی (Knowledge Selection)
این بخش وظیفه فعال یا غیرفعال کردن اسناد آماده (`ready`) را برای ورود به حوزه سرچ مدل صوتی بر عهده دارد.
### K01. دریافت لیست اسناد فعال (Get Selection)
* **متد و آدرس**: `GET /api/v1/knowledge-selection`
* **دسترسی**: فقط Admin
* **Response (200 OK)**:
```json
{
"revision": 2,
"access_epoch": 1,
"document_ids": [
"10000000-0000-4000-8000-000000000001"
]
}
```
---
### K02. تغییر لیست اسناد فعال (Replace Selection)
این عملیات جایگزین‌کننده کل لیست است (نه به صورت اضافه/کم کردن). ابتدا با `K01` لیست فعلی و `revision` را دریافت کنید، سپس تغییرات چک‌باکس‌ها را ارسال نمایید.
* **متد و آدرس**: `PATCH /api/v1/knowledge-selection`
* **دسترسی**: فقط Admin
* **Request Headers**:
* `X-CSRF-Token: <token>`
* **Request Body**:
```json
{
"expected_revision": 2,
"document_ids": [
"10000000-0000-4000-8000-000000000001",
"10000000-0000-4000-8000-000000000002"
]
}
```
* **Response (200 OK)**:
```json
{
"revision": 3,
"access_epoch": 1,
"document_ids": [
"10000000-0000-4000-8000-000000000001",
"10000000-0000-4000-8000-000000000002"
],
"conversations_invalidated": false
}
```
* **خطاها**:
* `409 Conflict` (`DOCUMENT_NOT_READY`): تلاش برای فعال‌سازی سندی که هنوز در وضعیت `ready` نیست.
* `409 Conflict` (`REVISION_CONFLICT`): ادمین دیگری همزمان پایگاه دانش را تغییر داده است (UI باید با `K01` مجدداً صفحه را به‌روز کند).
* **نکته**: اگر سندی غیرفعال (حذف از لیست) شود، فیلد `conversations_invalidated: true` خواهد شد و سشن‌های صوتی فعال گذشته متوقف می‌شوند تا اطلاعات نامعتبر به کاربر داده نشود.
---
## ۶. مکالمه صوتی زنده (Live Voice Conversations & WSS)
این بخش هسته تعامل کاربر و هوش مصنوعی در MVP است.
### C01. ایجاد مکالمه صوتی (Create Conversation)
* **متد و آدرس**: `POST /api/v1/conversations`
* **دسترسی**: لاگین‌شده (Admin یا User)
* **Request Headers**:
* `X-CSRF-Token: <token>`
* **Request Body**:
```json
{
"client_request_id": "50000000-0000-4000-8000-000000000001",
"mode": "voice",
"title": "مکالمه صوتی ساعت کاری"
}
```
*(در فاز MVP فقط مقدار `mode: "voice"` مجاز است).*
* **Response (201 Created)**:
```json
{
"id": "60000000-0000-4000-8000-000000000001",
"mode": "voice",
"title": "مکالمه صوتی ساعت کاری",
"status": "active",
"access_epoch": 1,
"created_at": "2026-10-07T09:05:00Z"
}
```
---
### V01. رزرو و ایجاد سشن صوتی لایو (Start Voice Session)
* **متد و آدرس**: `POST /api/v1/voice/sessions`
* **دسترسی**: مالک مکالمه
* **Request Headers**:
* `X-CSRF-Token: <token>`
* **Request Body**:
```json
{
"conversation_id": "60000000-0000-4000-8000-000000000001",
"client_request_id": "91000000-0000-4000-8000-000000000001"
}
```
* **Response (201 Created)**:
```json
{
"session_id": "a0000000-0000-4000-8000-000000000001",
"conversation_id": "60000000-0000-4000-8000-000000000001",
"status": "connecting",
"stream_path": "/api/v1/voice/sessions/a0000000-0000-4000-8000-000000000001/stream",
"expires_at": "2026-10-07T09:35:00Z",
"poll_url": "/api/v1/voice/sessions/a0000000-0000-4000-8000-000000000001"
}
```
*(آدرس `stream_path` مسیری است که فرانت‌اند بلافاصله به آن WebSocket متصل می‌کند).*
---
### V02. استعلام وضعیت سشن صوتی و شواهد اخیر (Poll Voice Session)
* **متد و آدرس**: `GET /api/v1/voice/sessions/{session_id}`
* **دسترسی**: مالک مکالمه
* **Response (200 OK)**:
```json
{
"session_id": "a0000000-0000-4000-8000-000000000001",
"status": "connected",
"close_reason": null,
"expires_at": "2026-10-07T09:35:00Z",
"recent_tool_results": [
{
"tool_call_id": "b0000000-0000-4000-8000-000000000001",
"status": "succeeded",
"created_at": "2026-10-07T09:08:00Z",
"sources": [
{
"source_ref": "S1",
"document_id": "10000000-0000-4000-8000-000000000001",
"chunk_id": "30000000-0000-4000-8000-000000000001",
"title": "دستورالعمل ساعات کاری",
"excerpt": "ساعات کاری شعب در روزهای پنجشنبه از ساعت ۰۸:۰۰ الی ۱۲:۰۰ می‌باشد.",
"location": {
"page": 1,
"section": "بند ۲ - ساعات اداری"
},
"available": true
}
]
}
]
}
```
---
### V04. پایان مکالمه صوتی (Close Voice Session)
* **متد و آدرس**: `POST /api/v1/voice/sessions/{session_id}/close`
* **دسترسی**: مالک مکالمه
* **Request Headers**:
* `X-CSRF-Token: <token>`
* **Response (200 OK)**:
```json
{
"session_id": "a0000000-0000-4000-8000-000000000001",
"status": "closed",
"close_reason": "user_requested"
}
```
---
### پروتکل وب‌سوکت استریم صوتی (WebSocket Stream Contract)
* **آدرس اتصال**: `wss://<host>/api/v1/voice/sessions/{session_id}/stream`
* **احراز هویت**: به صورت خودکار از طریق کوکی `rag_session` هنگام Handshake برقرار می‌شود.
#### ۱. فرمت صوت باینری (Binary Audio Frames):
* **ارسال از کلاینت به سرور (Microphone Input)**:
* فرمت باینری: `PCM 16-bit Little-Endian`
* نرخ نمونه‌برداری: `16,000 Hz (16 kHz)`
* تعداد کانال: `1 (Mono)`
* **دریافت از سرور به کلاینت (Speaker Output)**:
* فرمت باینری: `PCM 16-bit Little-Endian`
* نرخ نمونه‌برداری: `24,000 Hz (24 kHz)`
* تعداد کانال: `1 (Mono)`
#### ۲. پیام‌های کنترلی متنی (JSON Control Messages):
##### الف) اعلام آماده‌بودن سشن (`session_ready`):
```json
{
"type": "session_ready",
"session_id": "a0000000-0000-4000-8000-000000000001",
"input_audio": {
"encoding": "pcm_s16le",
"sample_rate": 16000,
"channels": 1
},
"output_audio": {
"encoding": "pcm_s16le",
"sample_rate": 24000,
"channels": 1
}
}
```
##### ب) زیرنویس و رونوشت زنده (`transcript`):
```json
{
"type": "transcript",
"turn_ref": "live-turn-1",
"role": "assistant",
"text": "طبق بخشنامه ساعات کاری شعب در پنجشنبه‌ها تا ساعت ۱۲ ظهر است.",
"status": "completed"
}
```
*(مقادیر `status`: `"partial"` برای متن در حال تولید، `"completed"` برای پایان پاسخ، `"interrupted"` در صورت قطع شدن توسط کاربر).*
##### ج) کارت منابع بازیابی‌شده (`sources`):
همزمان با پاسخ صوتی یا قبل از آن به فرانت‌اند فرستاده می‌شود تا در کنار زیرنویس رندر شود:
```json
{
"type": "sources",
"turn_ref": "live-turn-1",
"tool_call_id": "call-1",
"sources": [
{
"source_ref": "S1",
"document_id": "10000000-0000-4000-8000-000000000001",
"chunk_id": "30000000-0000-4000-8000-000000000001",
"title": "دستورالعمل ساعات کاری",
"location": {
"page": 1,
"section": "بند ۲"
}
}
]
}
```
##### د) وقفه توسط کاربر / Barge-in (`turn_interrupted`):
اگر کاربر در میان صحبت مدل شروع به صحبت کند:
```json
{
"type": "turn_interrupted",
"turn_ref": "live-turn-1",
"cancelled_tool_call_ids": ["call-1"]
}
```
*(کلاینت باید فورا صف بافر پخش صدا را خالی کرده و وضعیت رونوشت جاری را به Interrupted تغییر دهد).*
##### ه) خطا در استریم (`error`):
```json
{
"type": "error",
"turn_ref": "live-turn-1",
"error": {
"code": "SEARCH_TIMEOUT",
"message": "مهلت زمان جستجوی اسناد به پایان رسید.",
"request_id": "req-98fbc182",
"retryable": true
}
}
```
---
## ۷. برگه راهنمای کدهای خطا (Error Codes Quick Reference)
| کد HTTP | `error.code` | توضیح و اقدام پیشنهادی برای UI |
| :--- | :--- | :--- |
| `401` | `AUTH_REQUIRED` | ریدایرکت به صفحه لاگین |
| `401` | `INVALID_CREDENTIALS` | نمایش پیام "نام کاربری یا رمز عبور نامعتبر است" |
| `403` | `CSRF_INVALID` | درخواست توکن مجدد از `/api/v1/me` و تکرار درخواست |
| `404` | `NOT_FOUND` | منبع یافت نشد |
| `409` | `REVISION_CONFLICT` | رفرش مجدد وضعیت با `GET /knowledge-selection` |
| `409` | `DOCUMENT_NOT_READY` | فقط اسناد وضعیت `ready` قابلیت فعال‌سازی دارند |
| `409` | `EXTRACTION_REVIEW_PENDING` | قبل از زدن دکمه Retry، باید شواهد تایید شوند |
| `409` | `IDEMPOTENCY_CONFLICT` | اصلاح کلید یا عدم ارسال دیتای متفاوت با کلید قبلی |
| `409` | `LIVE_SESSION_UNUSABLE` | سشن صوتی بسته شده؛ باید سشن جدید با `V01` ساخته شود |
| `413` | `FILE_TOO_LARGE` | نمایش خطای حجم بالای فایل طبق `max_upload_bytes` |
| `415` | `UNSUPPORTED_FILE_TYPE` | نمایش فرمت‌های مجاز اعلام‌شده در `F01` |
| `429` | `RATE_LIMITED` | نمایش پیام صبر و محدودیت نرخ درخواست |
| `503` | `DEPENDENCY_UNAVAILABLE` | خطای موقت سرور/پایگاه داده؛ درخواست بررسی اتصال |
+7
View File
@@ -0,0 +1,7 @@
{
"/api": {
"target": "http://127.0.0.1:8080",
"ws": true,
"changeOrigin": false
}
}
@@ -1,14 +1,15 @@
/**
* Mic capture: downsamples the context rate to `targetRate` (default 16 kHz),
* converts to PCM16 mono and posts fixed-size frames (default 20 ms) to the main thread.
* Mic capture: downsamples the context rate to `targetRate` (default 24 kHz per the
* voice contract), converts to PCM16 mono and posts fixed-size frames (default 20 ms)
* to the main thread. Frames are always sample-aligned PCM16.
* Message: { pcm: ArrayBuffer (Int16), rms: number (0..1) }
*/
class PcmCaptureProcessor extends AudioWorkletProcessor {
constructor(options) {
super();
const o = (options && options.processorOptions) || {};
this.targetRate = o.targetRate || 16000;
this.frameSamples = o.frameSamples || 320;
this.targetRate = o.targetRate || 24000;
this.frameSamples = o.frameSamples || 480;
this.ratio = sampleRate / this.targetRate; // input samples per output sample
this.pos = 0;
this.sum = 0;
+71 -12
View File
@@ -1,14 +1,29 @@
/**
* Streaming PCM playback with a ring buffer.
* Messages in: { type: 'push', pcm: ArrayBuffer (Int16 mono), sampleRate }
* Streaming PCM16 playback (contract: 24 kHz mono PCM16LE output, no WAV header).
*
* Bounded playout queue: at most BOUND_SAMPLES (96,000 bytes) of source audio is admitted.
* When it fills, the processor reports `overflow` and the call must fail safely — PCM is
* never silently dropped to keep the same context alive.
*
* Real playback progress: `played_ms` is computed from the source samples actually
* consumed by `process()` per audio_ref (never an elapsed timer), kept cumulative per ref
* and reported roughly 4×/s, on ref changes, and on clear/flush/idle — so the main thread
* can send the contract's `playback_progress` control message.
*
* Messages in: { type: 'push', pcm: ArrayBuffer (Int16 mono), sampleRate, audioRef }
* { type: 'clear' } barge-in: drop everything immediately
* { type: 'flush' } end of turn: play what is left, then report 'idle'
* Messages out: { type: 'idle' } buffer ran dry after playing
* Messages out: { type: 'progress', audioRef, playedMs }
* { type: 'idle' } buffer ran dry after playing
* { type: 'overflow' } bounded queue filled — caller fails the session safely
*/
const BOUND_BYTES = 96000; // contract cap for the playback queue
const REPORT_INTERVAL_MS = 250;
class PcmPlaybackProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.capacity = Math.floor(sampleRate * 30);
this.capacity = Math.floor(BOUND_BYTES / 2); // source samples (PCM16)
this.buf = new Float32Array(this.capacity);
this.r = 0;
this.w = 0;
@@ -17,10 +32,15 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
this.started = false;
this.prev = 0;
this.pos = 1;
this.ratio = 1; // source samples per output sample, set per push
this.currentRef = null;
this.refPlayedSamples = new Map(); // cumulative consumed source samples per audio_ref
this.unreportedSamples = 0;
this.overflowPosted = false;
this.port.onmessage = (e) => {
const m = e.data;
if (!m) return;
if (m.type === 'push') this.push(new Int16Array(m.pcm), m.sampleRate);
if (m.type === 'push') this.push(new Int16Array(m.pcm), m.sampleRate, m.audioRef || null);
else if (m.type === 'clear') this.clear();
else if (m.type === 'flush') this.flush();
};
@@ -31,21 +51,33 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
this.started = false;
this.prev = 0;
this.pos = 1;
this.reportProgress(true); // final report for the interrupted ref
}
flush() {
if (this.count === 0) {
this.started = false;
this.reportProgress(true);
this.port.postMessage({ type: 'idle' });
} else {
this.started = true; // short tail: do not wait for the prebuffer
}
}
push(int16, srcRate) {
push(int16, srcRate, audioRef) {
const n = int16.length;
if (!n) return;
const ratio = srcRate / sampleRate; // source samples per output sample
// Bounded queue: admitting this chunk past the cap is a safe failure, not a silent drop.
if (this.count + n > this.capacity) {
if (!this.overflowPosted) {
this.overflowPosted = true;
this.port.postMessage({ type: 'overflow' });
}
return;
}
this.ratio = srcRate / sampleRate; // source samples per output sample
const src = new Float32Array(n + 1);
src[0] = this.prev;
for (let i = 0; i < n; i++) src[i + 1] = int16[i] / 32768;
@@ -55,17 +87,19 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
const i = Math.floor(pos);
const frac = pos - i;
this.write(src[i] * (1 - frac) + src[i + 1] * frac);
pos += ratio;
pos += this.ratio;
}
this.prev = src[n];
this.pos = pos - n;
if (audioRef !== this.currentRef) {
this.reportProgress(true); // final report for the ref that just ended
this.currentRef = audioRef;
this.reportProgress(true);
}
}
write(v) {
if (this.count === this.capacity) {
this.r = (this.r + 1) % this.capacity; // overflow: drop the oldest sample
this.count--;
}
this.buf[this.w] = v;
this.w = (this.w + 1) % this.capacity;
this.count++;
@@ -78,17 +112,31 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
if (!this.started && this.count >= this.prebuffer) this.started = true;
if (this.started) {
let played = 0;
for (let i = 0; i < ch0.length; i++) {
if (this.count > 0) {
ch0[i] = this.buf[this.r];
this.r = (this.r + 1) % this.capacity;
this.count--;
played++;
} else {
ch0[i] = 0;
}
}
if (this.currentRef && played > 0) {
// Convert consumed output samples back to contract (source) samples.
const consumed = played * this.ratio;
const ref = this.currentRef;
this.refPlayedSamples.set(ref, (this.refPlayedSamples.get(ref) ?? 0) + consumed);
this.unreportedSamples += consumed;
const srcRate = this.ratio * sampleRate;
if ((this.unreportedSamples / srcRate) * 1000 >= REPORT_INTERVAL_MS) {
this.reportProgress(false);
}
}
if (this.count === 0) {
this.started = false;
this.reportProgress(true);
this.port.postMessage({ type: 'idle' });
}
} else {
@@ -98,6 +146,17 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
for (let c = 1; c < out.length; c++) out[c].set(ch0);
return true;
}
reportProgress(force) {
this.unreportedSamples = 0;
const ref = this.currentRef;
if (!ref) return;
const srcRate = this.ratio * sampleRate;
const playedSamples = this.refPlayedSamples.get(ref) ?? 0;
const playedMs = Math.max(0, Math.round((playedSamples / srcRate) * 1000));
if (playedMs <= 0) return; // nothing has actually been heard for this ref yet
this.port.postMessage({ type: 'progress', audioRef: ref, playedMs });
}
}
registerProcessor('pcm-playback', PcmPlaybackProcessor);
+17 -1
View File
@@ -1,10 +1,20 @@
import { ApplicationConfig, provideBrowserGlobalErrorListeners, provideZonelessChangeDetection } from '@angular/core';
import { ApplicationConfig, provideBrowserGlobalErrorListeners, provideZonelessChangeDetection, APP_INITIALIZER } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { routes } from './app.routes';
import { AuthService } from './services/auth/auth.service';
/**
* On every page load the HttpOnly `rag_session` cookie is validated with `GET /me`
* before the first route activates; a 401 drops the authenticated state so the
* guard sends the user to the login page.
*/
function initializeAuth(auth: AuthService): () => Promise<boolean> {
return () => auth.ensureIdentity().catch(() => false);
}
export const appConfig: ApplicationConfig = {
providers: [
@@ -13,6 +23,12 @@ export const appConfig: ApplicationConfig = {
provideRouter(routes),
provideAnimations(),
provideHttpClient(),
{
provide: APP_INITIALIZER,
useFactory: initializeAuth,
deps: [AuthService],
multi: true,
},
{
provide: TOAST_CONFIG,
useValue: {
+9
View File
@@ -0,0 +1,9 @@
/* `app-root` defaults to `display: inline`, which adds a line-box strut below the
full-height shell and makes the body scroll. Block + fixed viewport height keeps
every page inside the viewport; scrolling happens in the shell's scroll container. */
:host {
display: block;
height: 100vh;
height: 100dvh;
overflow: hidden;
}
+28
View File
@@ -3,6 +3,10 @@ import { HomePage } from './pages/home/home.page';
import { SettingsPage } from './pages/settings/settings.page';
import { LoginPage } from './pages/login/login.page';
import { ReportsPage } from './pages/reports/reports.page';
import { WallboardPage } from './pages/wallboard/wallboard.page';
import { CallCenterPage } from './pages/call-center/call-center.page';
import { CallCenterCallsPage } from './pages/call-center/call-center-calls.page';
import { ChatQuestionsPage } from './pages/chat-questions/chat-questions.page';
import { AuthService } from './services/auth/auth.service';
import { authGuard } from './services/auth/auth.guard';
import { Router } from '@angular/router';
@@ -44,4 +48,28 @@ export const routes: Routes = [
component: ReportsPage,
canActivate: [authGuard],
},
{
path: 'wallboard',
title: 'والبورد',
component: WallboardPage,
canActivate: [authGuard],
},
{
path: 'call-center',
title: 'ارتباط با کال سنتر',
component: CallCenterPage,
canActivate: [authGuard],
},
{
path: 'call-center/calls',
title: 'بازخوانی تماس‌ها از کال سنتر',
component: CallCenterCallsPage,
canActivate: [authGuard],
},
{
path: 'chat-questions',
title: 'سوالات چت سایت و اپلیکیشن',
component: ChatQuestionsPage,
canActivate: [authGuard],
},
];
+11 -1
View File
@@ -1,12 +1,22 @@
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { App } from './app';
describe('App', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [App],
providers: [provideZonelessChangeDetection()]
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
provideAnimations(),
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
],
}).compileComponents();
});
+13
View File
@@ -40,9 +40,20 @@
background: var(--menu-toggle-hover);
}
/* The shell owns the viewport: exactly one screen tall, nothing scrolls at the page
level. Routed pages scroll inside .main-content instead. */
.app-layout {
display: flex;
height: 100vh;
height: 100dvh;
overflow: hidden;
}
.main-content {
flex: 1;
min-height: 0;
overflow-y: auto;
overflow-x: hidden;
background: var(--main-content-bg);
}
@@ -51,6 +62,8 @@
flex-direction: column;
flex: 1;
min-width: 0;
/* Lets .main-content shrink and scroll instead of growing past the viewport. */
min-height: 0;
margin-right: 72px;
transition: margin-right 0.3s ease;
}
+2
View File
@@ -1,6 +1,8 @@
<div class="app-layout">
<app-sidebar
[isOpen]="sidebarOpen()"
[userName]="userName()"
[navItems]="navItems()"
[chatHistory]="chatHistory()"
(close)="sidebarOpen.set(false)"
(navClick)="sidebarOpen.set(true)"
+44 -10
View File
@@ -1,10 +1,34 @@
import { ChangeDetectionStrategy, Component, signal, inject } from '@angular/core';
import { ChangeDetectionStrategy, Component, signal, inject, computed } from '@angular/core';
import { RouterModule } from '@angular/router';
import { RouterOutlet } from '@angular/router';
import { SidebarComponent, ChatHistoryItem } from '../shared/ui/sidebar/sidebar.component';
import { SidebarComponent, ChatHistoryItem, NavItem } from '../shared/ui/sidebar/sidebar.component';
import { AuthService } from '../services/auth/auth.service';
import { VoiceStreamService } from '../services/voice-stream/voice-stream.service';
import { ThemeService } from '../services/theme/theme.service';
/** Navigation outside the assistant: document management is admin-only per the contract. */
const BASE_NAV_ITEMS: NavItem[] = [
{ icon: 'M12 5v14M5 12h14', label: 'چت جدید', route: '/' },
{ icon: 'M4 4v16h16M8 20V11M12.5 20V6M17 20V9', label: 'گزارشات', route: '/reports' },
{ icon: 'M2 4h20v12H2zM8 20h8M12 16v4', label: 'والبورد', route: '/wallboard' },
{
icon: 'M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71',
label: 'ارتباط با کال سنتر',
route: '/call-center',
},
{
icon: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3',
label: 'بازخوانی تماس‌ها از کال سنتر',
route: '/call-center/calls',
},
{ icon: 'M7.9 20A9 9 0 1 0 4 16.1L2 22Z', label: 'سوالات چت سایت و اپلیکیشن', route: '/chat-questions' },
{
icon: 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37.996.608 2.296.07 2.573-1.066zM15 12a3 3 0 11-6 0 0 3 3 0 016 0z',
label: 'تنظیمات',
route: '/settings',
},
];
@Component({
selector: 'app-layout',
standalone: true,
@@ -16,26 +40,36 @@ import { ThemeService } from '../services/theme/theme.service';
export class LayoutComponent {
private readonly authService = inject(AuthService);
private readonly themeService = inject(ThemeService);
private readonly voiceStream = inject(VoiceStreamService);
readonly sidebarOpen = signal(true);
readonly chatHistory = signal<ChatHistoryItem[]>([]);
readonly isDarkMode = this.themeService.isDarkMode;
/** The signed-in identity exactly as the server reported it. */
readonly userName = computed(() => this.authService.currentUserSubject.value?.username ?? '');
/** Hiding a nav entry is only cosmetic: every request is still authorized server-side. */
readonly navItems = computed<NavItem[]>(() => {
const isAdmin = this.authService.currentUserSubject.value?.role === 'admin';
return isAdmin ? BASE_NAV_ITEMS : BASE_NAV_ITEMS.filter((item) => item.route !== '/settings');
});
onProfile(): void {
this.sidebarOpen.set(false);
}
/**
* Logout releases the live voice session first (final playback progress, then V04),
* then A02 — even if V04 fails the logout still completes and local state is dropped.
*/
onLogout(): void {
this.sidebarOpen.set(false);
void this.voiceStream.close().finally(() => {
this.authService.logout().subscribe({
next: () => {
this.sidebarOpen.set(false);
this.navigateToLogin();
},
error: () => {
this.sidebarOpen.set(false);
this.navigateToLogin();
},
next: () => this.navigateToLogin(),
error: () => this.navigateToLogin(),
});
});
}
@@ -0,0 +1,25 @@
/* Page-specific styles for «بازخوانی تماس‌ها از کال سنتر» (shared chrome: shared/styles/demo-page.css) */
.demo-filters {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr)) auto;
gap: 1rem 1.25rem;
align-items: end;
}
@media (max-width: 1024px) {
.demo-filters {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.demo-filters .demo-btn {
grid-column: 1 / -1;
justify-self: start;
}
}
@media (max-width: 640px) {
.demo-filters {
grid-template-columns: minmax(0, 1fr);
}
}
@@ -0,0 +1,148 @@
<div class="demo-page">
<header class="demo-header">
<div class="demo-title-group">
<span class="demo-title-icon">
<svg
width="22"
height="22"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3" />
</svg>
</span>
<div>
<h1 class="demo-title">بازخوانی تماس‌ها از کال سنتر</h1>
<p class="demo-subtitle">دریافت و بازخوانی سابقه تماس‌ها از سامانه کال سنتر</p>
</div>
</div>
<span class="demo-chip">نمایشی</span>
</header>
<section class="demo-card demo-notice">
<span class="demo-notice-icon">
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="9" />
<path d="M12 8v4M12 16h.01" />
</svg>
</span>
<div>
<h2>این بخش هنوز فعال نیست</h2>
<p>
این صفحه مکانیزم بازخوانی سابقه تماس‌ها از کال سنتر را نمایش می‌دهد. رکوردهای زیر داده نمونه
هستند و از سرور واقعی دریافت نشده‌اند؛ پس از اتصال به کال سنتر، بازخوانی بر اساس بازه تاریخ و
وضعیت تماس انجام می‌شود.
</p>
</div>
</section>
<section class="demo-card">
<div class="demo-card-header">
<div>
<h2 class="demo-card-title">فیلتر بازخوانی</h2>
<p class="demo-card-description">
بازه تاریخ و وضعیت مورد نظر را انتخاب کنید تا گزارش تماس‌ها دریافت شود.
</p>
</div>
</div>
<div class="demo-filters">
@for (filter of filters; track filter.label) {
<label class="demo-field">
<span class="demo-field-label">{{ filter.label }}</span>
@if (filter.type === 'select') {
<select class="demo-field-input" disabled>
@for (option of filter.options ?? []; track option) {
<option [value]="option">{{ option }}</option>
}
</select>
} @else {
<input class="demo-field-input" type="text" [value]="filter.value" readonly />
}
<span class="demo-field-hint">{{ filter.hint }}</span>
</label>
}
<button type="button" class="demo-btn demo-btn--primary" disabled>بازخوانی تماس‌ها</button>
</div>
<div class="demo-actions">
<span class="demo-hint">
این کنترل‌ها در فاز جاری فعال نیستند و هیچ درخواستی به کال سنتر ارسال نمی‌شود.
</span>
</div>
</section>
<section class="demo-card">
<div class="demo-card-header">
<div>
<h2 class="demo-card-title">سابقه تماس‌ها</h2>
<p class="demo-card-description">
نمونه‌ای از رکوردهایی که پس از اتصال، از کال سنتر بازخوانی می‌شود.
</p>
</div>
<span class="demo-badge">داده نمونه</span>
</div>
<div class="demo-table-wrapper">
<table class="demo-table">
<thead>
<tr>
<th>شماره تماس</th>
<th>مدت تماس</th>
<th>وضعیت</th>
<th>تاریخ</th>
</tr>
</thead>
<tbody>
@for (call of exampleCalls; track call.phone) {
<tr>
<td>{{ call.phone }}</td>
<td>{{ call.duration }}</td>
<td>
<span class="demo-tag demo-tag--{{ call.statusKind }}">{{ call.status }}</span>
</td>
<td>{{ call.date }}</td>
</tr>
}
</tbody>
</table>
</div>
</section>
<section class="demo-card">
<div class="demo-empty">
<svg
width="40"
height="40"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M3 3v18h18" />
<path d="M7 15l4-6 4 4 4-7" />
</svg>
<h3>هنوز گزارشی بازخوانی نشده است</h3>
<p>
پس از اتصال به سامانه کال سنتر، گزارش‌های تماس بر اساس بازه زمانی انتخاب‌شده در این صفحه
نمایش داده می‌شود.
</p>
</div>
</section>
</div>
@@ -0,0 +1,46 @@
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { CallCenterCallsPage } from './call-center-calls.page';
describe('CallCenterCallsPage', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [CallCenterCallsPage],
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
provideAnimations(),
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
],
}).compileComponents();
});
it('should create the page', () => {
const fixture = TestBed.createComponent(CallCenterCallsPage);
expect(fixture.componentInstance).toBeTruthy();
});
it('renders example call rows and disabled symbolic controls', () => {
const fixture = TestBed.createComponent(CallCenterCallsPage);
fixture.detectChanges();
const element: HTMLElement = fixture.nativeElement;
expect(element.querySelector('.demo-title')?.textContent?.trim()).toBe('بازخوانی تماس‌ها از کال سنتر');
expect(element.textContent).toContain('این بخش هنوز فعال نیست');
expect(element.textContent).toContain('داده نمونه');
const rows = element.querySelectorAll('.demo-table tbody tr');
expect(rows.length).toBe(4);
expect(element.textContent).toContain('۰۹۱۲۱۲۳۴۵۶۷');
expect(element.textContent).toContain('پاسخ‌داده شده');
const buttons = Array.from(element.querySelectorAll('button')) as HTMLButtonElement[];
buttons.forEach((button) => expect(button.disabled).toBe(true));
expect(element.querySelector('select')?.disabled).toBe(true);
});
});
@@ -0,0 +1,85 @@
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { CommonModule } from '@angular/common';
interface ExampleCall {
phone: string;
duration: string;
status: string;
statusKind: 'answered' | 'pending' | 'missed';
date: string;
}
interface CallFilter {
label: string;
value: string;
hint: string;
type: 'text' | 'select';
options?: string[];
}
/**
* Symbolic demonstration page for retrieving call records from the call
* center. The rows are example data and every control is a placeholder.
*/
@Component({
selector: 'app-call-center-calls',
standalone: true,
imports: [CommonModule],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './call-center-calls.page.html',
styleUrls: ['./call-center-calls.page.css', '../../shared/styles/demo-page.css'],
})
export class CallCenterCallsPage {
readonly filters: CallFilter[] = [
{
label: 'از تاریخ',
value: '۱۴۰۴/۰۷/۰۱',
hint: 'نمونه — بازه تاریخ قابل انتخاب است.',
type: 'text',
},
{
label: 'تا تاریخ',
value: '۱۴۰۴/۰۷/۳۰',
hint: 'نمونه — بازه تاریخ قابل انتخاب است.',
type: 'text',
},
{
label: 'وضعیت تماس',
value: 'همه وضعیت‌ها',
hint: 'فیلتر نمونه.',
type: 'select',
options: ['همه وضعیت‌ها', 'پاسخ‌داده شده', 'بدون پاسخ', 'در انتظار بازبینی'],
},
];
readonly exampleCalls: ExampleCall[] = [
{
phone: '۰۹۱۲۱۲۳۴۵۶۷',
duration: '۲:۴۵',
status: 'پاسخ‌داده شده',
statusKind: 'answered',
date: '۱۴ مهر ۱۴۰۴',
},
{
phone: '۰۹۳۵۱۱۲۲۳۳۴۴',
duration: '۰:۳۸',
status: 'بدون پاسخ',
statusKind: 'missed',
date: '۱۴ مهر ۱۴۰۴',
},
{
phone: '۰۹۱۲۹۸۷۶۵۴۳۲',
duration: '۵:۱۲',
status: 'پاسخ‌داده شده',
statusKind: 'answered',
date: '۱۳ مهر ۱۴۰۴',
},
{
phone: '۰۹۱۵۵۵۱۲۳۴۵',
duration: '۱:۰۳',
status: 'در انتظار بازبینی',
statusKind: 'pending',
date: '۱۳ مهر ۱۴۰۴',
},
];
}
@@ -0,0 +1,5 @@
/* Page-specific styles for «ارتباط با کال سنتر» (shared chrome: shared/styles/demo-page.css) */
.demo-field-input--masked {
letter-spacing: 0.2em;
}
@@ -0,0 +1,158 @@
<div class="demo-page">
<header class="demo-header">
<div class="demo-title-group">
<span class="demo-title-icon">
<svg
width="22"
height="22"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path
d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"
/>
</svg>
</span>
<div>
<h1 class="demo-title">ارتباط با کال سنتر</h1>
<p class="demo-subtitle">اتصال برنامه به سامانه کال سنتر و همگام‌سازی تماس‌ها</p>
</div>
</div>
<span class="demo-chip">نمایشی</span>
</header>
<section class="demo-card demo-notice">
<span class="demo-notice-icon">
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="9" />
<path d="M12 8v4M12 16h.01" />
</svg>
</span>
<div>
<h2>این بخش هنوز فعال نیست</h2>
<p>
این صفحه نحوه اتصال برنامه به سامانه کال سنتر را نمایش می‌دهد. در فاز جاری هیچ اتصالی برقرار
نشده است و مقادیر نشان‌داده‌شده صرفاً نمونه هستند؛ پس از راه‌اندازی، اتصال از همین‌جا پیکربندی
و بررسی می‌شود.
</p>
</div>
</section>
<section class="demo-card">
<div class="demo-card-header">
<div>
<h2 class="demo-card-title">وضعیت اتصال</h2>
<p class="demo-card-description">
آخرین وضعیت بررسی اتصال برنامه به سامانه کال سنتر.
</p>
</div>
<div class="demo-status-row">
<span class="demo-status demo-status--off">اتصال برقرار نشده</span>
</div>
</div>
<p class="demo-card-description">
تا زمانی که اتصال برقرار نشده باشد، تماس‌های کال سنتر در والبرد و گزارش‌ها ثبت نمی‌شوند و
انتقال تماس از هوش مصنوعی به کارشناس انجام نمی‌شود.
</p>
</section>
<section class="demo-card">
<div class="demo-card-header">
<div>
<h2 class="demo-card-title">اطلاعات اتصال</h2>
<p class="demo-card-description">
مقادیر زیر از نمونه‌های نمایشی گرفته شده‌اند و قابل ویرایش نیستند.
</p>
</div>
</div>
<div class="demo-form-grid">
@for (field of connectionFields; track field.label) {
<label class="demo-field">
<span class="demo-field-label">{{ field.label }}</span>
<input
class="demo-field-input"
[class.demo-field-input--masked]="field.masked"
type="text"
[value]="field.value"
readonly
/>
<span class="demo-field-hint">{{ field.hint }}</span>
</label>
}
</div>
<div class="demo-actions">
<button type="button" class="demo-btn demo-btn--primary" disabled>بررسی اتصال</button>
<button type="button" class="demo-btn demo-btn--outline" disabled>ذخیره تنظیمات</button>
<span class="demo-hint">این کنترل‌ها در فاز جاری فعال نیستند.</span>
</div>
</section>
<section class="demo-card">
<div class="demo-card-header">
<div>
<h2 class="demo-card-title">قابلیت‌های پس از اتصال</h2>
<p class="demo-card-description">با برقراری اتصال به کال سنتر، این قابلیت‌ها فعال می‌شوند.</p>
</div>
</div>
<div class="demo-features">
@for (feature of features; track feature.id) {
<article class="demo-feature">
<span class="demo-feature-icon">
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path [attr.d]="feature.icon" />
</svg>
</span>
<h3>{{ feature.title }}</h3>
<p>{{ feature.description }}</p>
</article>
}
</div>
</section>
<section class="demo-card">
<div class="demo-empty">
<svg
width="40"
height="40"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M22 12h-4l-3 9L9 3l-3 9H2" />
</svg>
<h3>رخداد اتصالی ثبت نشده است</h3>
<p>
پس از برقراری اتصال، رخدادهای آزمایش اتصال، قطع و راه‌اندازی مجدد در این بخش نمایش داده
می‌شود.
</p>
</div>
</section>
</div>
@@ -0,0 +1,47 @@
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { CallCenterPage } from './call-center.page';
describe('CallCenterPage', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [CallCenterPage],
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
provideAnimations(),
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
],
}).compileComponents();
});
it('should create the page', () => {
const fixture = TestBed.createComponent(CallCenterPage);
expect(fixture.componentInstance).toBeTruthy();
});
it('renders the symbolic call-center connection state', () => {
const fixture = TestBed.createComponent(CallCenterPage);
fixture.detectChanges();
const element: HTMLElement = fixture.nativeElement;
expect(element.querySelector('.demo-title')?.textContent?.trim()).toBe('ارتباط با کال سنتر');
expect(element.textContent).toContain('این بخش هنوز فعال نیست');
expect(element.textContent).toContain('اتصال برقرار نشده');
expect(element.querySelectorAll('.demo-feature').length).toBe(3);
const inputs = Array.from(element.querySelectorAll('input')) as HTMLInputElement[];
expect(inputs.some((input) => input.value.includes('callcenter.raymand.ir'))).toBe(true);
expect(inputs.some((input) => input.readOnly)).toBe(true);
// every control stays a disabled placeholder
const buttons = Array.from(element.querySelectorAll('button')) as HTMLButtonElement[];
expect(buttons.length).toBeGreaterThan(0);
buttons.forEach((button) => expect(button.disabled).toBe(true));
});
});
@@ -0,0 +1,74 @@
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { CommonModule } from '@angular/common';
interface ConnectionField {
label: string;
value: string;
hint: string;
masked?: boolean;
}
interface CenterFeature {
id: string;
icon: string;
title: string;
description: string;
}
/**
* Symbolic demonstration page for the call-center integration. No backend
* connection exists yet: every value shown is illustrative and the controls
* are disabled placeholders.
*/
@Component({
selector: 'app-call-center',
standalone: true,
imports: [CommonModule],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './call-center.page.html',
styleUrls: ['./call-center.page.css', '../../shared/styles/demo-page.css'],
})
export class CallCenterPage {
readonly connectionFields: ConnectionField[] = [
{
label: 'آدرس سرویس کال سنتر',
value: 'https://callcenter.raymandcti.com/api/v1',
hint: 'مقدار نمونه — آدرس واقعی پس از راه‌اندازی ثبت می‌شود.',
},
{
label: 'کلید API',
value: '••••••••••••••••••••',
hint: 'کلید به‌صورت رمزنگاری‌شده نگهداری می‌شود.',
masked: true,
},
{
label: 'صف پیش‌فرض',
value: 'پشتیبانی',
hint: 'تماس‌های ارجاع‌شده به این صف وصل می‌شوند.',
},
];
readonly features: CenterFeature[] = [
{
id: 'live',
icon: 'M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z',
title: 'تماس‌های در جریان',
description:
'فهرست تماس‌های فعال و وضعیت لحظه‌ای هر کارشناس به‌صورت بلادرنگ نمایش داده می‌شود.',
},
{
id: 'transfer',
icon: 'M8 3 4 7l4 4M4 7h16M16 21l4-4-4-4M20 17H4',
title: 'انتقال از هوش مصنوعی به کارشناس',
description:
'تماس‌هایی که هوش مصنوعی نتوانسته پاسخ دهد، به همراه سابقه گفتگو به کارشناس ارجاع می‌شود.',
},
{
id: 'sync',
icon: 'M21 12A9 9 0 0 0 6.6 7.5l-3 3m0 0 3 3-3-3Z',
title: 'همگام‌سازی وضعیت کارشناسان',
description:
'حاضر بودن، مرخصی و خارج‌شدن کارشناسان بین برنامه و سامانه کال سنتر همگام می‌شود.',
},
];
}
@@ -0,0 +1,6 @@
/* Page-specific styles for «سوالات چت سایت و اپلیکیشن» (shared chrome: shared/styles/demo-page.css) */
.demo-list-main {
flex: 1 1 22rem;
min-width: 0;
}
@@ -0,0 +1,106 @@
<div class="demo-page">
<header class="demo-header">
<div class="demo-title-group">
<span class="demo-title-icon">
<svg
width="22"
height="22"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z" />
</svg>
</span>
<div>
<h1 class="demo-title">سوالات چت سایت و اپلیکیشن</h1>
<p class="demo-subtitle">پرسش‌های ثبت‌شده در چت سایت و اپلیکیشن موبایل</p>
</div>
</div>
<span class="demo-chip">نمایشی</span>
</header>
<section class="demo-card demo-notice">
<span class="demo-notice-icon">
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="9" />
<path d="M12 8v4M12 16h.01" />
</svg>
</span>
<div>
<h2>این بخش هنوز فعال نیست</h2>
<p>
این صفحه پرسش‌هایی را که کاربران در چت سایت یا اپلیکیشن موبایل ثبت کرده‌اند نمایش می‌دهد. در
فاز جاری این کانال‌ها به برنامه متصل نیستند و موارد زیر صرفاً نمونه هستند؛ پس از اتصال،
پرسش‌های بی‌پاسخ در این صفحه برای بررسی و افزودن به پایگاه دانش نمایش داده می‌شوند.
</p>
</div>
</section>
<section class="demo-card">
<div class="demo-card-header">
<div>
<h2 class="demo-card-title">نمونه پرسش‌های چت</h2>
<p class="demo-card-description">
پرسش‌های دریافتی به همراه منبع ثبت و وضعیت پاسخ‌گویی.
</p>
</div>
<span class="demo-badge">داده نمونه</span>
</div>
<div class="demo-list">
@for (item of exampleQuestions; track item.id) {
<article class="demo-list-item">
<div class="demo-list-main">
<p class="demo-question">{{ item.question }}</p>
<div class="demo-meta">
<span class="demo-tag" [class.demo-tag--site]="item.sourceKind === 'site'" [class.demo-tag--app]="item.sourceKind === 'app'">
{{ item.source }}
</span>
<span class="demo-tag" [class.demo-tag--answered]="item.statusKind === 'answered'" [class.demo-tag--pending]="item.statusKind === 'pending'">
{{ item.status }}
</span>
<span>{{ item.date }}</span>
</div>
</div>
<button type="button" class="demo-btn demo-btn--outline" disabled>پاسخ به پرسش</button>
</article>
}
</div>
</section>
<section class="demo-card">
<div class="demo-empty">
<svg
width="40"
height="40"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
<path d="M8 10h8M8 14h5" />
</svg>
<h3>پرسشی از چت ثبت نشده است</h3>
<p>
پس از اتصال چت سایت و اپلیکیشن موبایل، پرسش‌های جدید کاربران به‌صورت خودکار در این صفحه نمایش
داده می‌شود تا برای آن‌ها پاسخ ثبت شود.
</p>
</div>
</section>
</div>
@@ -0,0 +1,47 @@
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { ChatQuestionsPage } from './chat-questions.page';
describe('ChatQuestionsPage', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [ChatQuestionsPage],
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
provideAnimations(),
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
],
}).compileComponents();
});
it('should create the page', () => {
const fixture = TestBed.createComponent(ChatQuestionsPage);
expect(fixture.componentInstance).toBeTruthy();
});
it('renders example chat questions with source and status tags', () => {
const fixture = TestBed.createComponent(ChatQuestionsPage);
fixture.detectChanges();
const element: HTMLElement = fixture.nativeElement;
expect(element.querySelector('.demo-title')?.textContent?.trim()).toBe('سوالات چت سایت و اپلیکیشن');
expect(element.textContent).toContain('این بخش هنوز فعال نیست');
expect(element.textContent).toContain('داده نمونه');
const items = element.querySelectorAll('.demo-list-item');
expect(items.length).toBe(3);
expect(element.querySelectorAll('.demo-tag--site').length).toBe(2);
expect(element.querySelectorAll('.demo-tag--app').length).toBe(1);
expect(element.querySelectorAll('.demo-tag--pending').length).toBe(1);
expect(element.textContent).toContain('هزینه ارسال به شهرستان‌ها چگونه محاسبه می‌شود؟');
const buttons = Array.from(element.querySelectorAll('button')) as HTMLButtonElement[];
buttons.forEach((button) => expect(button.disabled).toBe(true));
});
});
@@ -0,0 +1,56 @@
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { CommonModule } from '@angular/common';
interface ExampleQuestion {
id: string;
question: string;
source: string;
sourceKind: 'site' | 'app';
status: string;
statusKind: 'answered' | 'pending';
date: string;
}
/**
* Symbolic demonstration page for questions submitted through the website and
* mobile application chat channels. Example data only; no channel is connected.
*/
@Component({
selector: 'app-chat-questions',
standalone: true,
imports: [CommonModule],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './chat-questions.page.html',
styleUrls: ['./chat-questions.page.css', '../../shared/styles/demo-page.css'],
})
export class ChatQuestionsPage {
readonly exampleQuestions: ExampleQuestion[] = [
{
id: 'q-1',
question: 'برای ایمپورت محصولات جدید چه مراحلی را باید طی کنم؟',
source: 'سایت',
sourceKind: 'site',
status: 'پاسخ داده شده',
statusKind: 'answered',
date: '۱۴ مهر ۱۴۰۴',
},
{
id: 'q-2',
question: 'هزینه ارسال به شهرستان‌ها چگونه محاسبه می‌شود؟',
source: 'اپلیکیشن',
sourceKind: 'app',
status: 'در انتظار پاسخ',
statusKind: 'pending',
date: '۱۴ مهر ۱۴۰۴',
},
{
id: 'q-3',
question: 'آیا امکان لغو سفارش پس از پرداخت وجود دارد؟',
source: 'سایت',
sourceKind: 'site',
status: 'پاسخ داده شده',
statusKind: 'answered',
date: '۱۳ مهر ۱۴۰۴',
},
];
}
+144 -74
View File
@@ -1,16 +1,33 @@
/* --------------------------------------------------------------------------
Home page — Claude-style chat column
Structure:
.home-page
.chat-column
.transcript-list (flex: 1, scroll)
.composer (pinned bottom of column)
Two layouts, CSS-only, driven by [class.has-conversation]:
- empty state column hugs its content and centers (logo + composer as a group)
- conversation column is exactly one viewport tall, transcript scrolls inside it
-------------------------------------------------------------------------- */
/* The host defaults to `display: inline`, which adds a line-box strut under the
full-height column and pushes the page into Y overflow. Block removes it. */
:host {
display: block;
min-height: 0;
}
.home-page {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100dvh;
box-sizing: border-box;
padding: 2rem 1rem;
transition: padding 0.4s ease;
padding: 0;
position: relative;
background:
radial-gradient(ellipse 50% 40% at 50% 45%, rgba(59, 130, 246, 0.1), transparent 70%),
var(--app-bg);
/* Flat page color; every decorative glow lives in ::below so it can fade out as one. */
background: var(--app-bg);
}
.home-page::before {
@@ -18,54 +35,91 @@
position: absolute;
inset: 0;
background:
radial-gradient(ellipse 50% 40% at 50% 45%, rgba(59, 130, 246, 0.1), transparent 70%),
radial-gradient(circle at 50% 40%, rgba(59, 130, 246, 0.07), transparent 55%),
radial-gradient(circle at 35% 55%, rgba(99, 102, 241, 0.05), transparent 50%),
radial-gradient(circle at 65% 50%, rgba(59, 130, 246, 0.04), transparent 45%);
pointer-events: none;
z-index: 0;
transition: opacity 0.35s ease;
}
.home-page > .home-content {
/* Conversation open (messages or voice call): the bluish glow disappears completely. */
.home-page.has-conversation::before {
opacity: 0;
}
/* ---- Chat column (Claude: one continuous column) ---- */
.chat-column {
position: relative;
z-index: 1;
}
.home-page.has-messages {
justify-content: flex-end;
background: var(--app-bg);
}
.home-page.has-messages::before {
opacity: 0;
}
.home-header {
position: absolute;
top: 2rem;
left: 50%;
transform: translateX(-50%);
text-align: center;
transition:
opacity 0.35s ease,
transform 0.35s ease,
margin 0.35s ease;
opacity: 1;
}
.home-page.has-messages .home-header {
opacity: 0;
transform: translateX(-50%) translateY(-8px);
pointer-events: none;
}
.home-page.has-messages .home-title {
opacity: 0;
pointer-events: none;
}
.home-content {
display: flex;
flex-direction: column;
width: 100%;
max-width: 800px;
/* Auto height + viewport floor: grows only if the empty group cannot fit (then the
shell scrolls) instead of clipping. */
height: auto;
min-height: 100dvh;
box-sizing: border-box;
}
/* Conversation: the column is exactly one viewport tall so the composer stays pinned
and only the transcript area scrolls. `overflow` keeps any stray child box from
propagating phantom height to the page. */
.home-page.has-conversation .chat-column {
height: 100dvh;
overflow: hidden;
}
/* Empty state: the column stops stretching, so the empty content and the composer are
centered together in the viewport instead of the composer being pinned to the bottom. */
.home-page:not(.has-conversation) .chat-column {
justify-content: center;
}
.home-page:not(.has-conversation) .transcript-list {
flex: 0 0 auto;
overflow: visible;
}
.home-page:not(.has-conversation) .empty-state {
flex: 0 0 auto;
}
/* ---- Transcript list (scrollable body) ---- */
.transcript-list {
flex: 1 1 auto;
min-height: 0;
overflow-y: auto;
overflow-x: hidden;
/* Hide the scrollbar, keep wheel / trackpad / touch scrolling */
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* legacy Edge */
scroll-behavior: smooth;
display: flex;
flex-direction: column;
/* Space so last message clears the composer */
padding: 1.25rem 1rem 0.5rem;
box-sizing: border-box;
}
.transcript-list::-webkit-scrollbar {
display: none; /* Chrome, Safari, Edge */
width: 0;
height: 0;
}
/* Empty state centered in the transcript area */
.empty-state {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
padding: 2rem 1rem;
min-height: 0;
}
.home-icon-wrapper {
@@ -89,7 +143,7 @@
.home-title {
width: 100%;
margin: 0 0 1rem;
margin: 0;
display: flex;
align-items: center;
@@ -98,7 +152,7 @@
text-align: center;
direction: rtl;
font-size: 1.5rem;
font-size: 1.45rem;
font-weight: 400;
line-height: 1.5;
color: var(--text-primary);
@@ -110,18 +164,12 @@
.cursor {
display: inline-block;
width: 2px;
height: 1.15em;
margin-right: 3px;
background-color: var(--text-primary);
border-radius: 1px;
animation: cursorBlink 0.8s ease-in-out infinite;
flex-shrink: 0;
}
@@ -134,20 +182,56 @@
45% {
opacity: 1;
}
46%,
100% {
opacity: 0;
}
}
/* Voice panel becomes the transcript body — no extra card chrome */
.chat-transcript-body {
display: block;
flex: 1 1 auto;
min-height: 0;
width: 100%;
}
/* ---- Composer (pinned bottom of the chat column) ---- */
.composer {
flex-shrink: 0;
width: 100%;
padding: 0.75rem 1rem 1.25rem;
box-sizing: border-box;
background: transparent;
/* Subtle top fade so messages don't collide with the input */
position: relative;
}
.composer::before {
content: '';
position: absolute;
left: 0;
right: 0;
bottom: 100%;
height: 1.5rem;
pointer-events: none;
background: linear-gradient(to top, var(--app-bg), transparent);
opacity: 0;
transition: opacity 0.25s ease;
}
.home-page.has-conversation .composer::before {
opacity: 1;
}
/* ---- Responsive ---- */
@media (max-width: 640px) {
.home-page {
padding: 1.25rem 0.75rem;
.transcript-list {
padding: 1rem 0.75rem 0.5rem;
}
.home-header {
top: 1.25rem;
.composer {
padding: 0.5rem 0.75rem 1rem;
}
.home-icon-wrapper {
@@ -156,11 +240,6 @@
padding: 0.5rem;
}
.home-logo {
width: 100%;
height: 100%;
}
.home-title {
font-size: 1.375rem;
}
@@ -168,20 +247,11 @@
@media (prefers-reduced-motion: reduce) {
.home-page,
.home-header,
.home-icon-wrapper {
.home-page::before,
.transcript-list,
.composer::before {
transition: none !important;
animation: none !important;
}
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
scroll-behavior: auto !important;
}
}
+29 -13
View File
@@ -1,6 +1,21 @@
<div class="home-page" [class.has-messages]="hasMessages()">
<div class="home-header" [class.header-hidden]="hasMessages()">
<div
class="home-page"
[class.has-conversation]="hasConversation()"
>
<!-- Claude-style chat column: transcript list + composer in one continuous column -->
<div class="chat-column" role="main">
<!-- Transcript list (scrollable). Empty state or live/ended voice transcript. -->
<div
class="transcript-list"
#transcriptScroller
role="log"
aria-label="متن گفتگو"
aria-live="polite"
aria-relevant="additions"
>
@if (!hasConversation()) {
<!-- Empty state: logo + typing title (Claude empty chat feel) -->
<div class="empty-state">
<div class="home-icon-wrapper">
<img
class="home-logo"
@@ -8,29 +23,30 @@
alt="Raymand"
/>
</div>
</div>
<div class="home-content">
<h1 class="home-title">
<span class="home-title-text">
{{ streamedText() }}
</span>
<span class="home-title-text">{{ streamedText() }}</span>
<span
class="cursor"
[class.cursor-hidden]="!isStreaming()"
aria-hidden="true"
></span>
</h1>
</div>
} @else if (voiceHasTranscript()) {
<!-- Voice stream fills the transcript list (no separate card chrome) -->
<app-voice-stream-panel class="chat-transcript-body" />
}
</div>
<!-- Composer: always at the bottom of the same column (Claude pattern) -->
<div class="composer">
<app-ai-chat-input
placeholder="پیام خود را بنویسید..."
[hasMessages]="hasMessages()"
[hasMessages]="hasConversation()"
(messageSent)="onMessageSent($event)"
(fileSelected)="onFileSelected($event)"
(voiceToggled)="onVoiceToggled($event)"
/>
</div>
</div>
</div>
+20 -6
View File
@@ -3,18 +3,21 @@ import {
Component,
inject,
signal,
computed,
OnInit,
OnDestroy,
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { AiChatInputComponent } from '../../shared/ui/ai-chat-input/ai-chat-input.component';
import { VoiceStreamPanelComponent } from '../../shared/ui/voice-stream-panel/voice-stream-panel.component';
import { VoiceStreamService } from '../../services/voice-stream/voice-stream.service';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
import { ThemeService } from '../../services/theme/theme.service';
import { Subscription } from 'rxjs';
const HOME_TITLES = [
'چه چیزی می‌خواهید بدانید؟...',
'چه چیزی می‌خواهید بدانید؟',
'سوالتان را بپرسید، با شما هستم...',
'هر سوالی دارید، از من بپرسید...',
'از هر چیزی که می‌خواهید شروع کنید...',
@@ -29,7 +32,7 @@ const HOME_TITLES = [
@Component({
selector: 'app-home',
standalone: true,
imports: [CommonModule, AiChatInputComponent],
imports: [CommonModule, AiChatInputComponent, VoiceStreamPanelComponent],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './home.page.html',
styleUrl: './home.page.css',
@@ -37,6 +40,7 @@ const HOME_TITLES = [
export class HomePage implements OnInit, OnDestroy {
private readonly themeService = inject(ThemeService);
private readonly router = inject(Router);
private readonly voiceStream = inject(VoiceStreamService);
readonly isDarkMode = this.themeService.isDarkMode;
@@ -45,6 +49,20 @@ export class HomePage implements OnInit, OnDestroy {
readonly hasMessages = signal(false);
/**
* Conversation owns the layout when there is a live voice call,
* leftover voice transcript, or text messages — same idea as Claude's
* chat column switching from empty state to transcript list.
*/
readonly voiceHasTranscript = computed(
() => this.voiceStream.isOpen() || this.voiceStream.messages().length > 0,
);
readonly hasConversation = computed(() => this.hasMessages() || this.voiceHasTranscript());
/** @deprecated use hasConversation — kept for any external bindings */
readonly voicePanelVisible = this.hasConversation;
readonly homeTitle = signal('');
readonly streamedText = signal('');
readonly isStreaming = signal(false);
@@ -97,12 +115,9 @@ export class HomePage implements OnInit, OnDestroy {
}
index++;
this.streamedText.set(text.substring(0, index));
// Slightly random timing makes it feel more natural
const delay = 16 + Math.random() * 8;
this.typingTimer = setTimeout(typeNextCharacter, delay);
};
@@ -114,7 +129,6 @@ export class HomePage implements OnInit, OnDestroy {
clearTimeout(this.typingTimer);
this.typingTimer = null;
}
this.isStreaming.set(false);
}
+7 -6
View File
@@ -127,7 +127,6 @@ export class LoginPage {
}
onSubmit(): void {
this.router.navigate(['/']);
const allErrors = this.validateAllFields();
if (Object.keys(allErrors).length > 0) {
@@ -159,11 +158,13 @@ export class LoginPage {
},
error: (err) => {
this.isLoading.set(false);
const message =
(err as any)?.error?.message ||
(err as any)?.message ||
'خطا در اتصال به سرور. لطفاً دوباره تلاش کنید.';
this.generalError.set(message);
// Errors are mapped by backend code instead of showing the raw server message.
this.generalError.set(
AuthService.messageForError(
err,
'خطا در اتصال به سرور. لطفاً دوباره تلاش کنید.',
),
);
this.triggerShake();
},
});
+146
View File
@@ -0,0 +1,146 @@
import { ChangeDetectionStrategy, Component, computed, inject, signal, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { forkJoin } from 'rxjs';
import { ReportsService } from '../../services/reports/reports.service';
import { ReportsView } from '../../services/reports/reports.types';
import { BarChartComponent, BarChartItem } from '../../shared/ui/charts/bar-chart.component';
import { DoughnutChartComponent, DoughnutSegment } from '../../shared/ui/charts/doughnut-chart.component';
import { LineChartComponent, LinePoint } from '../../shared/ui/charts/line-chart.component';
import { CHART_PALETTE } from '../../shared/utils/chart-palette';
import { formatCount, formatDecimal, formatPercent } from '../../shared/utils/format.util';
type ReportTabId = 'questions' | 'performance';
@Component({
selector: 'app-reports',
standalone: true,
imports: [CommonModule, BarChartComponent, DoughnutChartComponent, LineChartComponent],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './reports.page.html',
styleUrl: './reports.page.css',
})
export class ReportsPage implements OnInit {
private readonly reports = inject(ReportsService);
readonly tabs: { id: ReportTabId; label: string; icon: string }[] = [
{
id: 'questions',
label: 'پرسش‌های کاربران',
icon: 'M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z',
},
{
id: 'performance',
label: 'عملکرد و روند',
icon: 'M22 12h-4l-3 9L9 3l-3 9H2',
},
];
readonly activeTab = signal<ReportTabId>('questions');
readonly loading = signal(true);
readonly loadError = signal(false);
readonly data = signal<ReportsView | null>(null);
readonly summary = computed(() => this.data()?.summary ?? null);
readonly ai = computed(() => this.data()?.aiPerformance ?? null);
readonly topQuestions = computed<BarChartItem[]>(() => {
const questions = this.data()?.topQuestions ?? [];
return questions.map((question, index) => ({
label: question.text,
value: question.count,
color: CHART_PALETTE[index % CHART_PALETTE.length],
hint: `دسته: ${question.category}`,
}));
});
readonly categories = computed<DoughnutSegment[]>(() => {
const shares = this.data()?.categories ?? [];
return shares.map((share, index) => ({
label: share.category,
value: share.count,
color: CHART_PALETTE[index % CHART_PALETTE.length],
}));
});
readonly trend = computed<LinePoint[]>(() => {
const points = this.data()?.trend ?? [];
return points.map((point) => ({ label: point.label, value: point.count }));
});
readonly channels = computed<BarChartItem[]>(() => {
const channels = this.data()?.aiPerformance.channels ?? [];
return channels.map((channel, index) => ({
label: channel.label,
value: channel.count,
color: CHART_PALETTE[index % CHART_PALETTE.length],
}));
});
readonly aiAnswerRate = computed(() => {
const summary = this.summary();
if (!summary || summary.totalQuestions === 0) return 0;
return (summary.aiAnswered / summary.totalQuestions) * 100;
});
readonly faqBasedRate = computed(() => {
const ai = this.ai();
if (!ai || ai.totalResponses === 0) return 0;
return (ai.faqBasedResponses / ai.totalResponses) * 100;
});
readonly trendTotal = computed(() => this.trend().reduce((sum, point) => sum + point.value, 0));
readonly trendPeak = computed(() => {
const points = this.trend();
if (points.length === 0) return null;
return points.reduce((peak, point) => (point.value > peak.value ? point : peak), points[0]);
});
ngOnInit(): void {
this.load();
}
selectTab(id: ReportTabId): void {
this.activeTab.set(id);
}
load(): void {
this.loading.set(true);
this.loadError.set(false);
forkJoin({
topQuestions: this.reports.getTopQuestions(),
summary: this.reports.getQuestionSummary(),
categories: this.reports.getCategoryDistribution(),
trend: this.reports.getUsageTrend(),
aiPerformance: this.reports.getAiPerformance(),
}).subscribe({
next: (data) => {
this.data.set(data);
this.loading.set(false);
},
error: () => {
this.data.set(null);
this.loading.set(false);
this.loadError.set(true);
},
});
}
retry(): void {
this.load();
}
formatCount(value: number): string {
return formatCount(value);
}
formatDecimal(value: number): string {
return formatDecimal(value);
}
formatPercent(value: number): string {
return formatPercent(value);
}
}
+354 -92
View File
@@ -88,12 +88,6 @@
animation: slideInRight 0.3s ease-out;
}
.file-item:nth-child(1) { animation-delay: 0.05s; }
.file-item:nth-child(2) { animation-delay: 0.1s; }
.file-item:nth-child(3) { animation-delay: 0.15s; }
.file-item:nth-child(4) { animation-delay: 0.2s; }
.file-item:nth-child(5) { animation-delay: 0.25s; }
.file-icon-wrapper {
transition: all 0.2s ease;
}
@@ -113,11 +107,6 @@
animation: fadeInUp 0.4s ease-out forwards;
}
.setting-item:nth-child(1) { animation-delay: 0.05s; }
.setting-item:nth-child(2) { animation-delay: 0.1s; }
.setting-item:nth-child(3) { animation-delay: 0.15s; }
.setting-item:nth-child(4) { animation-delay: 0.2s; }
.form-select {
appearance: none;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%2364748b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
@@ -197,9 +186,11 @@
border-color: var(--color-primary);
}
/* `.toggle-active` mirrors the checked state set by the host; keep it solid too
so it never wins over the neutral base with a transparent primary wash. */
.toggle-switch.toggle-active {
background-color: var(--color-primary)/15;
border-color: var(--color-primary)/25;
background-color: var(--color-primary);
border-color: var(--color-primary);
}
.toggle-switch:focus-within {
@@ -207,111 +198,55 @@
box-shadow: 0 0 0 3px var(--color-primary)/30;
}
.toggle-switch:hover {
background-color: var(--color-primary)/10;
/* Unchecked (off) hover: solid neutral, never transparent. */
.toggle-switch:hover:not(:has(input:checked)) {
background-color: color-mix(in srgb, var(--toggle-bg) 60%, #000);
}
.toggle-switch:hover:has(input:checked) {
background-color: var(--color-primary);
}
.toggle-switch:hover.toggle-active {
background-color: var(--color-primary)/20;
/* Checked hover: solid, slightly darker primary. */
.toggle-switch:has(input:checked):hover {
background-color: color-mix(in srgb, var(--color-primary) 78%, #000);
}
@keyframes fadeInDown {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
from { opacity: 0; transform: translateY(-10px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes slideInRight {
from {
opacity: 0;
transform: translateX(20px);
}
to {
opacity: 1;
transform: translateX(0);
}
from { opacity: 0; transform: translateX(20px); }
to { opacity: 1; transform: translateX(0); }
}
@keyframes slideIn {
from {
width: 0;
opacity: 0;
}
to {
width: 1.5rem;
opacity: 1;
}
from { width: 0; opacity: 0; }
to { width: 1.5rem; opacity: 1; }
}
@keyframes bounce {
0%, 20%, 50%, 80%, 100% {
transform: translateY(0);
}
40% {
transform: translateY(-5px);
}
60% {
transform: translateY(-3px);
}
0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
40% { transform: translateY(-5px); }
60% { transform: translateY(-3px); }
}
@keyframes pulse {
0%, 100% {
transform: scale(1);
}
50% {
transform: scale(1.1);
}
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
0%, 100% { transform: scale(1); }
50% { transform: scale(1.1); }
}
@media (max-width: 640px) {
@@ -393,3 +328,330 @@
:host-context([data-bs-theme="dark"]) .setting-item:hover {
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4), 0 2px 8px rgba(0, 0, 0, 0.3);
}
:host-context([data-bs-theme="dark"]) .btn--outline:hover:not(:disabled) {
background: color-mix(in srgb, var(--color-primary) 30%, #171717);
}
:host-context([data-bs-theme="dark"]) .toggle-switch:hover:not(:has(input:checked)) {
background-color: color-mix(in srgb, var(--toggle-bg) 50%, #000);
}
:host-context([data-bs-theme="dark"]) .toggle-switch:has(input:checked):hover {
background-color: color-mix(in srgb, var(--color-primary) 75%, #000);
}
/* ===== Dropzone disabled overlay ===== */
.dropzone-disabled {
opacity: 0.6;
pointer-events: none;
}
/* ===== Upload actions + queue ===== */
.upload-actions {
animation: fadeInUp 0.4s ease-out;
}
.upload-queue {
animation: fadeInUp 0.4s ease-out;
}
.upload-task {
animation: slideInRight 0.3s ease-out;
}
.upload-progress-bar {
background: var(--surface-border);
}
.upload-progress-bar > div {
background: var(--color-primary);
}
/* ===== Buttons ===== */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.4rem;
border-radius: 0.5rem;
padding: 0.5rem 0.9rem;
font-size: 0.85rem;
font-weight: 500;
border: 1px solid transparent;
cursor: pointer;
transition: background-color 0.2s, border-color 0.2s, color 0.2s;
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn--primary {
background: var(--color-primary);
color: #ffffff;
}
.btn--primary:hover:not(:disabled) {
background: color-mix(in srgb, var(--color-primary) 80%, #000);
}
.btn--primary:active:not(:disabled) {
background: color-mix(in srgb, var(--color-primary) 70%, #000);
}
.btn--outline {
background: transparent;
border-color: var(--color-input-border);
color: var(--text-secondary);
}
.btn--outline:hover:not(:disabled) {
background: color-mix(in srgb, var(--color-primary) 22%, #ffffff);
border-color: var(--color-primary);
color: var(--color-primary);
}
/* ===== Documents table ===== */
.documents-section {
animation: fadeInUp 0.5s ease-out;
}
.documents-filters {
animation: fadeInUp 0.4s ease-out;
}
.documents-table-wrapper {
border: 1px solid var(--color-card-border);
}
.documents-table {
border-collapse: separate;
border-spacing: 0;
}
.documents-table th,
.documents-table td {
padding: 0.6rem 0.75rem;
text-align: right;
vertical-align: top;
border-bottom: 1px solid var(--color-card-border);
}
.documents-table thead th {
background: var(--sidebar-hover);
}
.table-row-animate {
animation: fadeInUp 0.3s ease-out;
}
.documents-table tbody tr:last-child td {
border-bottom: none;
}
/* Status badges */
.status-queued {
background: var(--color-warning)/15;
color: var(--color-warning);
}
.status-processing {
background: var(--color-info)/15;
color: var(--color-info);
}
.status-ready {
background: var(--color-success)/15;
color: var(--color-success);
}
.status-failed {
background: var(--color-danger)/15;
color: var(--color-danger);
}
.status-dot,
.dot-queued,
.dot-processing,
.dot-ready,
.dot-failed {
width: 0.4rem;
height: 0.4rem;
border-radius: 9999px;
flex-shrink: 0;
}
.dot-queued { background: var(--color-warning); }
.dot-processing { background: var(--color-info); animation: pulse-dot 1.5s ease-in-out infinite; }
.dot-ready { background: var(--color-success); }
.dot-failed { background: var(--color-danger); }
@keyframes pulse-dot {
0%, 100% { opacity: 1; }
50% { opacity: 0.4; }
}
/* Active toggle button */
.active-toggle {
display: inline-flex;
align-items: center;
gap: 0.35rem;
border-radius: 9999px;
padding: 0.25rem 0.7rem;
font-size: 0.78rem;
font-weight: 600;
border: 1px solid var(--color-input-border);
cursor: pointer;
transition: background-color 0.2s, border-color 0.2s, color 0.2s;
}
.active-toggle--on {
background: var(--color-success)/15;
border-color: var(--color-success);
color: var(--color-success);
}
.active-toggle:not(.active-toggle--on) {
background: var(--color-input-border)/40;
color: var(--text-muted);
}
.active-toggle:hover {
opacity: 0.85;
}
.active-toggle:disabled {
cursor: default;
opacity: 0.6;
}
/* Documents empty / error / pagination */
.documents-loading,
.documents-empty,
.documents-error {
animation: fadeIn 0.3s ease-out;
}
/* ===== Review modal ===== */
.review-backdrop {
position: fixed;
inset: 0;
background: var(--overlay);
display: flex;
align-items: center;
justify-content: center;
z-index: 100;
padding: 1rem;
}
.review-modal {
background: var(--card-bg);
border: 1px solid var(--color-card-border);
border-radius: 1rem;
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
width: 100%;
max-width: 56rem;
max-height: 85dvh;
overflow: hidden;
display: flex;
flex-direction: column;
}
.review-modal-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1rem 1.25rem;
border-bottom: 1px solid var(--color-card-border);
}
.review-modal-body {
padding: 1.25rem;
overflow-y: auto;
flex: 1 1 auto;
min-height: 0;
}
.review-modal-footer {
border-top: 1px solid var(--color-card-border);
}
.review-loading {
animation: fadeIn 0.3s ease-out;
}
.review-items {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
gap: 1rem;
}
.review-item {
animation: fadeInUp 0.3s ease-out;
}
.review-item-header {
animation: fadeInDown 0.3s ease-out;
}
.review-item-body {
animation: fadeIn 0.3s ease-out;
}
.review-preview {
background: var(--sidebar-hover);
border: 1px dashed var(--color-card-border);
}
.review-preview img {
max-width: 100%;
height: auto;
display: block;
}
.review-item-actions {
animation: fadeInDown 0.3s ease-out;
}
/* ===== App settings: AI model cards grid ===== */
.ai-models-grid {
animation: fadeInUp 0.5s ease-out;
}
.ai-models-grid > app-ai-model-config-card {
animation: fadeInUp 0.4s ease-out;
}
/* Shared form utilities (also used by the review modal — page-scoped) */
.form-label {
font-size: 0.8rem;
font-weight: 500;
color: var(--text-secondary);
}
.form-input {
background: var(--color-input-bg);
color: var(--text-secondary);
border: 1px solid var(--color-input-border);
border-radius: 0.5rem;
padding: 0.5rem 0.75rem;
font-size: 0.875rem;
outline: none;
transition: border-color 0.2s, box-shadow 0.2s;
width: 100%;
box-sizing: border-box;
}
.form-input:focus {
border-color: var(--color-primary);
box-shadow: 0 0 0 3px var(--color-primary)/20;
}
.form-input:disabled {
background: var(--surface-bg);
cursor: default;
opacity: 0.7;
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
.dot-processing { animation: none; }
}
@media (max-width: 640px) {
.documents-table {
font-size: 0.75rem;
}
.documents-table th,
.documents-table td {
padding: 0.4rem 0.3rem;
}
.review-modal {
max-width: 100%;
max-height: 90dvh;
border-radius: 0.75rem;
}
.review-item-body {
grid-template-columns: 1fr;
}
.ai-models-grid {
grid-template-columns: 1fr;
}
}
@media (max-width: 480px) {
.documents-filters {
flex-wrap: wrap;
gap: 0.5rem;
}
}
+655 -45
View File
@@ -1,4 +1,5 @@
<div class="settings-page max-w-3xl mx-auto px-4 py-8">
<!-- prettier-ignore -->
<div class="settings-page max-w-6xl mx-auto px-4 py-8">
<header class="settings-header mb-8">
<h1 class="text-3xl font-semibold text-[var(--text-primary)] mb-1">تنظیمات</h1>
<p class="text-sm text-[var(--text-muted)]">مدیریت FAQ و ترجیحات برنامه</p>
@@ -58,7 +59,7 @@
>
<circle cx="12" cy="12" r="3" />
<path
d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"
d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l-.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l-.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"
/>
</svg>
<span>تنظیمات برنامه</span>
@@ -93,13 +94,32 @@
آپلود سند FAQ
</h2>
<p class="text-sm text-[var(--text-muted)]">
فایل‌های PDF، DOCX یا TXT خود را بکشید و رها کنید یا برای آپلود کلیک کنید.
فایل‌های {{ supportedFormatsLabel() }} خود را بکشید و رها کنید یا برای آپلود کلیک کنید.
</p>
@if (!capabilitiesLoaded() && !configLoading()) {
<p class="text-xs text-[var(--color-danger)] mt-1">
محدودیت‌های آپلود از سرور دریافت نشده‌اند؛ آپلود غیرفعال است.
</p>
}
@if (maxUploadBytes()) {
<p class="text-xs text-[var(--text-muted)] mt-1">
حداکثر حجم: {{ formatFileSize(maxUploadBytes()) }}
</p>
}
@if (pdfPageLimitLabel()) {
<p class="text-xs text-[var(--text-muted)] mt-1">
حداکثر تعداد صفحات PDF: {{ pdfPageLimitLabel() }}
</p>
}
@if (configError()) {
<p class="text-xs text-[var(--color-danger)] mt-1">{{ configError() }}</p>
}
</div>
<div
class="dropzone relative flex flex-col items-center justify-center gap-3 p-8 border-2 border-dashed border-[rgba(148,163,184,0.25)] rounded-xl bg-[var(--dropzone-bg)] cursor-pointer transition-all duration-300 hover:border-primary/50 hover:bg-primary/5 hover:shadow-[0_10px_30px_rgba(59,130,246,0.15)]"
[class.dropzone-active]="isDragging()"
[class.dropzone-disabled]="isUploading()"
(dragover)="onDragOver($event)"
(dragleave)="onDragLeave()"
(drop)="onDrop($event)"
@@ -114,8 +134,9 @@
id="faq-file-input"
type="file"
class="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
accept=".pdf,.docx,.doc,.txt"
[accept]="supportedUploadAccept()"
multiple
[disabled]="isUploading()"
(change)="onFileSelected($event)"
/>
@@ -140,11 +161,11 @@
فایل‌ها را اینجا رها کنید
</p>
<p class="text-xs text-[var(--text-muted)] mt-1">یا کلیک کنید برای انتخاب</p>
<p class="text-xs text-[var(--text-muted)] mt-2">پشتیبانی: PDF، DOCX، TXT</p>
<p class="text-xs text-[var(--text-muted)] mt-2">پشتیبانی: {{ supportedFormatsLabel() }}</p>
</div>
</div>
@if (fileCount > 0) {
@if (fileCount > 0 && !isUploading()) {
<div class="file-list mt-6 animate-slide-up">
<div class="flex items-center justify-between mb-4">
<h3 class="text-lg font-medium text-[var(--text-primary)] flex items-center gap-2">
@@ -204,7 +225,7 @@
type="button"
class="file-remove-btn p-2 text-[var(--text-muted)] rounded-lg transition-all duration-200 hover:text-red-400 hover:bg-red-400/10 hover:scale-110 shrink-0"
(click)="removeFile($index)"
aria-label="حذف فایل {{ file.name }}"
[attr.aria-label]="'حذف فایل ' + file.name"
>
<svg
class="w-4 h-4"
@@ -224,6 +245,517 @@
</ul>
</div>
}
@if (fileCount > 0 && !isUploading()) {
<div class="upload-actions mt-4 flex items-center justify-between gap-3">
<button
type="button"
class="btn btn--primary"
(click)="uploadFiles()"
[disabled]="isUploading() || !capabilitiesLoaded() || !isAdmin()"
>
<span>آپلود فایل‌ها</span>
@if (!isAdmin()) {
<span class="text-xs">(مدیریت اسناد فقط برای ادمین‌ها)</span>
}
@if (!capabilitiesLoaded()) {
<span class="text-xs">(تنظیمات سرور بارگذاری نشد)</span>
}
</button>
</div>
}
@if (isUploading()) {
<div class="upload-queue mt-4 space-y-3" aria-live="polite" aria-label="وضعیت آپلود">
<h3 class="text-sm font-medium text-[var(--text-secondary)] mb-2">در حال آپلود...</h3>
@for (task of uploadQueue(); track $index) {
<div class="upload-task flex items-center gap-3">
<div class="flex-1 min-w-0">
<div class="flex items-center justify-between gap-2">
<span class="text-sm text-[var(--text-secondary)] truncate">{{ task.file.name }}</span>
<span class="text-xs text-[var(--text-muted)]">
@if (task.status === 'uploading') {
{{ task.progress }}%
} @else if (task.status === 'done') {
<span class="text-[var(--color-success)]">بارگذاری شد</span>
} @else {
<span class="text-[var(--color-danger)]">خطا</span>
}
</span>
</div>
<div class="upload-progress-bar mt-1 h-1.5 bg-[var(--surface-border)] rounded-full overflow-hidden">
<div
class="h-full bg-primary rounded-full transition-all duration-200"
[style.width]="(task.progress) + '%'"
></div>
</div>
@if (task.error) {
<p class="text-xs text-[var(--color-danger)] mt-1">{{ task.error }}</p>
}
</div>
@if (task.status === 'uploading') {
<button
type="button"
class="file-remove-btn p-1 text-[var(--text-muted)] rounded transition-colors hover:text-red-400"
(click)="cancelUpload($index)"
aria-label="لغو آپلود"
>
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="18" y1="6" x2="6" y2="18" />
<line x1="6" y1="6" x2="18" y2="18" />
</svg>
</button>
}
@if (task.status === 'error') {
<button
type="button"
class="file-remove-btn p-1 text-[var(--text-muted)] rounded transition-colors hover:text-[var(--color-primary)]"
(click)="retryUpload($index)"
aria-label="دوباره‌سعی آپلود"
title="دوباره‌سعی"
>
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round"
stroke-linejoin="round">
<path d="M21 12A9 9 0 0 0 6.6 7.5l-3 3m0 0 3 3-3-3Z" />
</svg>
</button>
}
</div>
}
</div>
}
<!-- اسناد آپلود شده -->
<div class="documents-section mt-8">
@if (!isAdmin()) {
<div class="documents-locked flex flex-col items-center justify-center gap-3 py-10 text-center">
<svg class="w-10 h-10 text-[var(--text-muted)]" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="1.5" stroke-linecap="round"
stroke-linejoin="round">
<path d="M12 1.75v20.5" />
<path d="M4.25 12h15.5" />
</svg>
<p class="text-sm text-[var(--text-secondary)]">مدیریت و لیست اسناد فقط برای ادمین‌ها در دسترس است.</p>
</div>
}
@if (isAdmin()) {
<div class="section-header mb-4">
<h2 class="text-xl font-semibold text-[var(--text-primary)] mb-1 flex items-center gap-2">
<svg
class="w-5 h-5 text-primary"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14 2 14 8 20 8" />
<polyline points="14 8 20 8 20 14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h8z" />
</svg>
اسناد آپلود شده
</h2>
<p class="text-sm text-[var(--text-muted)]">
فهرست اسناد ثبت‌شده و وضعیت پردازش آن‌ها. وضعیت در صف یا پردازش در حال پردازش به‌صورت خودکار به‌روز می‌شود.
</p>
</div>
@if (documentsLoading() && documents().length === 0) {
<div class="documents-loading flex items-center justify-center gap-2 py-10 text-[var(--text-muted)]">
<svg class="w-5 h-5 animate-spin" viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="12" y1="5" x2="12" y2="19" />
<path d="M19 12a7 7 0 1 1-14 0a7 7 0 0 1 14 0z" />
</svg>
<span>در حال بارگذاری اسناد...</span>
</div>
}
@if (documentsError() && documents().length === 0) {
<div class="documents-error flex flex-col items-center justify-center gap-3 py-10 text-center">
<p class="text-sm text-[var(--text-secondary)]">{{ documentsError() }}</p>
<button type="button" class="btn btn--outline" (click)="refreshDocuments()">
تلاش مجدد
</button>
</div>
}
@if (documents().length > 0) {
<div class="documents-filters mb-3 flex items-center justify-between gap-2">
<div class="flex items-center gap-2">
<select
class="form-select bg-[var(--input-bg)] text-[var(--text-secondary)] border border-[var(--input-border)] rounded-lg px-3 py-1.5 text-xs min-w-[130px] cursor-pointer"
[value]="activeFilter()"
(change)="activeFilter.set($any($event.target).value); applyDocumentFilters()"
>
<option value="all">همه وضعیت‌ها</option>
<option value="queued">در صف</option>
<option value="processing">در حال پردازش</option>
<option value="ready">آماده</option>
<option value="failed">ناموفق</option>
</select>
<label class="toggle-switch" [class.toggle-active]="activeOnly()">
<input type="checkbox" [checked]="activeOnly()" (change)="activeOnly.set($any($event.target).checked); applyDocumentFilters()" />
<span class="toggle-slider"></span>
</label>
<span class="text-xs text-[var(--text-muted)]">فقط فعال</span>
</div>
<button type="button" class="btn btn--outline" (click)="refreshDocuments()" [disabled]="documentsLoading()">
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M3 12a9 9 0 0 1 9-9a9 9 0 1 1 0 18a9 9 0 0 1 0-18z" />
<path d="M12 8v4l2 2" />
</svg>
<span>به‌روزرسانی</span>
</button>
</div>
<div class="documents-table-wrapper overflow-x-auto rounded-xl border border-[var(--color-card-border)] bg-[var(--card-bg)]">
<table class="documents-table min-w-full text-sm text-right">
<thead class="bg-[var(--sidebar-hover)]">
<tr>
<th class="px-3 py-2 text-xs font-medium text-[var(--text-muted)]">نام فایل</th>
<th class="px-3 py-2 text-xs font-medium text-[var(--text-muted)]">عنوان سند</th>
<th class="px-3 py-2 text-xs font-medium text-[var(--text-muted)]">وضعیت پردازش</th>
<th class="px-3 py-2 text-xs font-medium text-[var(--text-muted)]">تعداد بخش‌ها</th>
<th class="px-3 py-2 text-xs font-medium text-[var(--text-muted)]">تاریخ آپلود</th>
<th class="px-3 py-2 text-xs font-medium text-[var(--text-muted)]">فعال‌سازی</th>
<th class="px-3 py-2 text-xs font-medium text-[var(--text-muted)]">عملیات</th>
</tr>
</thead>
<tbody class="divide-y divide-[var(--color-card-border)]">
@for (doc of documents(); track doc.id) {
<tr class="table-row-animate">
<td class="px-3 py-2.5 align-top">
<span class="text-sm text-[var(--text-secondary)] truncate block max-w-[14rem]"
>{{ doc.filename }}</span>
</td>
<td class="px-3 py-2.5 align-top">
<span class="text-sm text-[var(--text-secondary)]">{{ doc.title ?? '—' }}</span>
</td>
<td class="px-3 py-2.5 align-top">
<span
class="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium"
[class.status-queued]="doc.status === 'queued'"
[class.status-processing]="doc.status === 'processing'"
[class.status-ready]="doc.status === 'ready'"
[class.status-failed]="doc.status === 'failed'"
>
<span class="status-dot" [class.dot-queued]="doc.status === 'queued'"
[class.dot-processing]="doc.status === 'processing'" [class.dot-ready]="doc.status === 'ready'"
[class.dot-failed]="doc.status === 'failed'"></span>
{{ statusLabel(doc.status) }}
</span>
@if (isReviewNeeded(doc)) {
<span class="block text-xs text-[var(--color-warning)] mt-1 font-medium">
نیازمند بازبینی ادمین
</span>
}
@if (doc.job.error; as jobError) {
<span class="block text-xs text-[var(--color-danger)] mt-1"
title="{{ jobError.message }}">{{ jobError.code }}</span>
}
</td>
<td class="px-3 py-2.5 align-top">
<span class="text-sm text-[var(--text-muted)]">{{ doc.chunk_count }}</span>
</td>
<td class="px-3 py-2.5 align-top">
<span class="text-sm text-[var(--text-muted)]">{{ formatDateTime(doc.created_at) }}</span>
</td>
<td class="px-3 py-2.5 align-top min-w-[11rem]">
@if (doc.status === 'ready' && !isReviewNeeded(doc) && isAdmin()) {
@if (togglingDocId() === doc.id) {
<div class="flex items-center gap-1.5 text-xs text-[var(--text-muted)]">
<svg class="w-3 h-3 animate-spin" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round"
stroke-linejoin="round">
<line x1="12" y1="5" x2="12" y2="19" />
<path d="M19 12a7 7 0 0 1-14 0a7 7 0 0 1 14 0z" />
</svg>
<span>در حال به‌روزرسانی</span>
</div>
} @else {
<button
type="button"
class="active-toggle"
[class.active-toggle--on]="isDocumentActive(doc)"
(click)="toggleDocumentActive(doc)"
>
<span>{{ isDocumentActive(doc) ? 'فعال' : 'غیرفعال' }}</span>
</button>
}
} @else {
<span
class="text-xs"
[class.text-[var(--color-success)]="doc.is_active"
[class.text-[var(--text-muted)]="!doc.is_active"
>{{ doc.is_active ? 'فعال' : 'غیرفعال' }}</span
>
}
</td>
<td class="px-3 py-2.5 align-top">
<div class="flex items-center gap-1.5">
@if (isReviewNeeded(doc) && doc.status === 'failed') {
<button
type="button"
class="btn btn--outline"
[disabled]="reviewingDocId() === doc.id"
(click)="openReview(doc)"
>
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round"
stroke-linejoin="round">
<path d="M2 12s9-7 19-7c2.6 0 4.5 2 4.5 4.5S23.6 19 21 19s-4.5-2.5-4.5-4.5S17.4 7 9 7" />
<path d="M2 12s9 7 19 7c2.6 0 4.5-2 4.5-4.5S23.6 7 21 7s-4.5 2.5-4.5 4.5S16.6 17 21 17" />
<circle cx="12" cy="12" r="3" />
</svg>
<span>بازبینی سند</span>
</button>
}
@if (canRetryDocument(doc)) {
<button
type="button"
class="btn btn--outline"
(click)="retryDocument(doc)"
>
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round"
stroke-linejoin="round">
<path d="M21 12A9 9 0 0 0 6.6 7.5l-3 3m0 0 3 3-3-3Z" />
</svg>
<span>دوباره‌سعی</span>
</button>
}
</div>
</td>
</tr>
}
</tbody>
</table>
</div>
@if (!hasMoreDocuments() && !documentsLoading()) {
<p class="text-xs text-[var(--text-muted)] text-center mt-3">
{{ documents().length }} سند ثبت شده
</p>
}
@if (hasMoreDocuments() && !documentsLoading()) {
<div class="documents-pagination mt-3 text-center">
<button type="button" class="btn btn--outline" (click)="loadMoreDocuments()">
بیشتر بارگذاری
</button>
</div>
}
} @else {
@if (!documentsLoading() && !documentsError()) {
<div class="documents-empty flex flex-col items-center justify-center gap-3 py-10 text-center">
<svg class="w-10 h-10 text-[var(--text-muted)]" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="1.5" stroke-linecap="round"
stroke-linejoin="round">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14 2 14 8 20 8" />
<polyline points="14 8 20 8 20 14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V5a2 a2 0 0 1 2-2h8z" />
</svg>
<p class="text-sm text-[var(--text-muted)]">هنوز سندی آپلود نشده است.</p>
</div>
}
}
}
</div>
<!-- Extraction review modal -->
@if (reviewingDocId()) {
<div class="review-backdrop" (click)="closeReview()">
<div
class="review-modal"
(click)="onReviewModalClick($event)"
role="dialog"
aria-modal="true"
aria-label="بازبینی سند"
>
<header class="review-modal-header">
<h3 class="text-lg font-semibold text-[var(--text-primary)]">بازبینی استخراج سند</h3>
<button type="button" class="file-remove-btn p-1 text-[var(--text-muted)]"
(click)="closeReview()" aria-label="بستن">
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="18" y1="6" x2="6" y2="18" />
<line x1="6" y1="6" x2="18" y2="18" />
</svg>
</button>
</header>
<div class="review-modal-body">
@if (reviewLoading()) {
<div class="review-loading flex items-center justify-center gap-2 py-8 text-[var(--text-muted)]">
<svg class="w-5 h-5 animate-spin" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round"
stroke-linejoin="round">
<line x1="12" y1="5" x2="12" y2="19" />
<path d="M19 12a7 7 0 0 1-14 0a7 7 0 0 1 14 0z" />
</svg>
<span>در حال بارگذاری شواهد...</span>
</div>
}
@if (!reviewLoading() && reviewItems().length === 0) {
<p class="text-sm text-[var(--text-muted)]">شاهده‌ای نیازمند بازبینی یافت نشد.</p>
}
@if (!reviewLoading() && reviewItems().length > 0) {
<div class="review-items space-y-5">
@for (item of reviewItems(); track item.evidence_sha256) {
<div class="review-item border border-[var(--color-card-border)] rounded-xl p-4 bg-[var(--surface-bg)]">
<div class="review-item-header flex items-center justify-between gap-2 mb-3">
<div class="text-xs text-[var(--text-muted)]">
<span>{{ reviewKindLabel(item) }}</span>
@if (item.location; as location) {
<span>
@if (location.page != null) { صفحه {{ location.page }} }
@if (location.section) { — {{ location.section }} }
</span>
}
</div>
@if (decisionFor(item) === 'approve' && isReviewSubmittable(item)) {
<span class="text-xs text-[var(--color-success)] font-medium">تکمیل شد</span>
}
</div>
<div class="review-item-body grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="review-preview min-h-[120px] flex items-center justify-center bg-[var(--sidebar-hover)] rounded-lg overflow-hidden">
@if (previewImageUrl(item); as previewUrl) {
<img
[src]="previewUrl"
[alt]="'پیش‌نمایش صفحه ' + (item.location?.page ?? '')"
class="max-w-full max-h-48 object-contain"
loading="lazy"
/>
} @else {
<span class="text-xs text-[var(--text-muted)]">پیش‌نمایشی موجود نیست</span>
}
</div>
<div class="review-content space-y-3">
<div>
<label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">
متن استخراج‌شده
</label>
<ul class="text-xs text-[var(--text-secondary)] space-y-1 max-h-36 overflow-y-auto pr-2">
@for (block of item.blocks; track block.block_id) {
<li class="leading-relaxed">{{ block.text }}</li>
}
</ul>
</div>
<div>
<label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">
بررسی‌های الزامی
</label>
<ul class="space-y-1 text-xs">
@for (check of item.required_checks; track check) {
<li class="flex items-center gap-2">
<input
type="checkbox"
[id]="item.evidence_sha256 + '-' + check"
[checked]="isCheckChecked(item, check)"
(change)="toggleCheck(item, check, $any($event.target).checked)"
/>
<label [attr.for]="item.evidence_sha256 + '-' + check" class="text-[var(--text-secondary)] cursor-pointer">{{ checkLabel(check) }}</label>
</li>
}
</ul>
</div>
<div>
<label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">
تصمیم
</label>
<div class="flex items-center gap-3 text-xs">
<label class="flex items-center gap-1.5 cursor-pointer">
<input type="radio" name="decision-{{ item.evidence_sha256 }}"
value="approve" [checked]="decisionFor(item) === 'approve'"
(change)="setDecision(item, 'approve')" />
<span class="text-[var(--text-secondary)]">تایید</span>
</label>
<label class="flex items-center gap-1.5 cursor-pointer">
<input type="radio" name="decision-{{ item.evidence_sha256 }}"
value="reject" [checked]="decisionFor(item) === 'reject'"
(change)="setDecision(item, 'reject')" />
<span class="text-[var(--text-secondary)]">رد</span>
</label>
</div>
</div>
<div>
<label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">
یادداشت بازبینی (الزامی)
</label>
<textarea
class="form-input w-full text-xs"
rows="2"
[value]="noteFor(item)"
(input)="setNote(item, $any($event.target).value)"
placeholder="مثال: با صفحه اصلی مقایسه و تاریخ و ساعت تأیید شد."
></textarea>
</div>
@if (item.review_kind !== 'extraction') {
<div>
<label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">
شناسه گروه‌های حذف‌شده (اختیاری)
</label>
<input
type="text"
class="form-input w-full text-xs"
[value]="excludedGroupIdsFor(item)"
(input)="setExcludedGroupIds(item, $any($event.target).value)"
placeholder="با کامای جدا کنید"
/>
</div>
}
</div>
</div>
<div class="review-item-actions flex items-center justify-end gap-2 mt-3">
<button
type="button"
class="btn btn--primary"
[disabled]="!isReviewSubmittable(item)"
(click)="submitReviewDecision(item)"
>
<span>ثبت تصمیم بازبینی</span>
</button>
</div>
</div>
}
</div>
}
</div>
<footer class="review-modal-footer border-t border-[var(--color-card-border)] p-3 flex justify-end gap-2">
@if (canRetryAfterReview()) {
<button type="button" class="btn btn--primary" (click)="finishReviewAndRetry()">
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 12A9 9 0 0 0 6.6 7.5l-3 3m0 0 3 3-3-3Z" />
</svg>
<span>بستن و دوباره‌سعی پردازش</span>
</button>
}
<button type="button" class="btn btn--outline" (click)="closeReview()">
<span>بستن</span>
</button>
</footer>
</div>
</div>
}
</section>
}
@@ -244,7 +776,7 @@
>
<circle cx="12" cy="12" r="3" />
<path
d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"
d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l-.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l-.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l-.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"
/>
</svg>
تنظیمات کلی
@@ -252,43 +784,6 @@
</div>
<div class="settings-grid space-y-3">
<!-- <div
class="setting-item flex items-center justify-between gap-4 p-4 bg-[var(--card-bg)] rounded-xl shadow-[0_2px_8px_rgba(0,0,0,0.04)] transition-all duration-200 hover:shadow-[0_4px_16px_rgba(0,0,0,0.08)] hover:-translate-y-0.5"
>
<div class="setting-info flex flex-col gap-1 min-w-0">
<span class="text-sm font-medium text-[var(--text-secondary)]"
>زبان رابط کاربری</span
>
<span class="text-xs text-[var(--text-muted)]"
>زبان نمایش برنامه را انتخاب کنید</span
>
</div>
<div class="setting-control shrink-0">
<select
class="form-select bg-[var(--input-bg)] text-[var(--text-secondary)] border border-[var(--input-border)] rounded-lg px-3 py-2 text-sm min-w-[140px] cursor-pointer transition-all duration-200 focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20 focus:shadow-[0_0_0_3px_var(--color-primary)/20]"
[(ngModel)]="language"
>
<option value="fa">فارسی</option>
<option value="en">English</option>
</select>
</div>
</div> -->
<!-- <div
class="setting-item flex items-center justify-between gap-4 p-4 bg-[var(--card-bg)] rounded-xl shadow-[0_2px_8px_rgba(0,0,0,0.04)] transition-all duration-200 hover:shadow-[0_4px_16px_rgba(0,0,0,0.08)] hover:-translate-y-0.5"
>
<div class="setting-info flex flex-col gap-1 min-w-0">
<span class="text-sm font-medium text-[var(--text-secondary)]">اعلان‌ها</span>
<span class="text-xs text-[var(--text-muted)]">دریافت اعلان‌های برنامه</span>
</div>
<div class="setting-control shrink-0">
<label class="toggle-switch" [class.toggle-active]="notificationsEnabled()">
<input type="checkbox" [(ngModel)]="notificationsEnabled" />
<span class="toggle-slider"></span>
</label>
</div>
</div> -->
<div
class="setting-item flex items-center justify-between gap-4 p-4 bg-[var(--card-bg)] rounded-xl shadow-[0_2px_8px_rgba(0,0,0,0.04)] transition-all duration-200 hover:shadow-[0_4px_16px_rgba(0,0,0,0.08)] hover:-translate-y-0.5"
>
@@ -304,6 +799,121 @@
</div>
</div>
<div
class="setting-item flex items-center justify-between gap-4 p-4 bg-[var(--card-bg)] rounded-xl shadow-[0_2px_8px_rgba(0,0,0,0.04)] transition-all duration-200 hover:shadow-[0_4px_16px_rgba(0,0,0,0.08)] hover:-translate-y-0.5"
>
<div class="setting-info flex flex-col gap-1 min-w-0">
<label class="text-sm font-medium text-[var(--text-secondary)] cursor-pointer">
نیاز به تأیید ادمین برای اسناد OCR شده
</label>
<span class="text-xs text-[var(--text-muted)] block mt-0.5">
در صورت فعال بودن، محتوای استخراج‌شده از اسناد باید توسط ادمین بازبینی و تأیید شود.
</span>
<span class="text-xs text-[var(--color-warning)] mt-0.5">پیش‌نویس — ذخیره‌سازی در فاز MVP پشتیبانی نمی‌شود</span>
</div>
<div class="setting-control shrink-0">
<label class="toggle-switch" [class.toggle-active]="ocrAdminApproval()">
<input type="checkbox" [checked]="ocrAdminApproval()" (change)="toggleOcrApproval()" />
<span class="toggle-slider"></span>
</label>
</div>
</div>
</div>
<div class="mt-8">
<h3 class="text-lg font-semibold text-[var(--text-primary)] mb-4 flex items-center gap-2">
<svg class="w-5 h-5 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z" />
<path d="M19 10v2a7 7 0 0 1-14 0v-2" />
<line x1="12" x2="12" y1="19" y2="22" />
</svg>
تنظیمات مدل‌های هوش مصنوعی
</h3>
<p class="text-xs text-[var(--text-muted)] mb-4">
هر کارت به‌صورت مستقل پیکربندی می‌شود. در فاز MVP، این تنظیمات در حافظه نگهداری می‌شوند و به سرور ارسال نمی‌شوند.
</p>
<div class="ai-models-grid grid grid-cols-1 lg:grid-cols-2 gap-6">
<app-ai-model-config-card
title="تنظیمات مدل هوش مصنوعی"
task="text"
[config]="textModelConfig()"
(configChange)="textModelConfig.set($event)"
[connected]="textModelConnected()"
(save)="saveModelConfig('text')"
(testConnection)="testModelConnection('text')"
></app-ai-model-config-card>
<app-ai-model-config-card
title="تنظیمات مدل امبدینگ"
task="embedding"
[config]="embeddingModelConfig()"
(configChange)="embeddingModelConfig.set($event)"
[connected]="embeddingModelConnected()"
(save)="saveModelConfig('embedding')"
(testConnection)="testModelConnection('embedding')"
></app-ai-model-config-card>
<app-ai-model-config-card
title="تنظیمات مدل OCR"
task="ocr"
[config]="ocrModelConfig()"
(configChange)="ocrModelConfig.set($event)"
[connected]="ocrModelConnected()"
(save)="saveModelConfig('ocr')"
(testConnection)="testModelConnection('ocr')"
></app-ai-model-config-card>
</div>
</div>
<div class="mt-8">
<h3 class="text-lg font-semibold text-[var(--text-primary)] mb-4 flex items-center gap-2">
<svg class="w-5 h-5 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z" />
<path d="M19 10v2a7 7 0 0 1-14 0v-2" />
<line x1="12" x2="12" y1="19" y2="22" />
</svg>
تنظیمات مدل‌های داخلی
</h3>
<p class="text-xs text-[var(--text-muted)] mb-4">
مدل‌های داخلی مرکز تماس — تبدیل گفتار به نوشتار، تبدیل نوشتار به گفتار و مدل گفتگو —
هر کارت به‌صورت مستقل پیکربندی می‌شود. در فاز MVP، این تنظیمات در حافظه نگهداری می‌شوند و به
سرور ارسال نمی‌شوند.
</p>
<div class="ai-models-grid grid grid-cols-1 lg:grid-cols-2 gap-6">
<app-ai-model-config-card
title="تنظیمات مدل تبدیل گفتار به نوشتار"
task="stt"
[config]="sttModelConfig()"
(configChange)="sttModelConfig.set($event)"
[connected]="sttModelConnected()"
(save)="saveModelConfig('stt')"
(testConnection)="testModelConnection('stt')"
></app-ai-model-config-card>
<app-ai-model-config-card
title="تنظیمات مدل تبدیل نوشتار به گفتار"
task="tts"
[config]="ttsModelConfig()"
(configChange)="ttsModelConfig.set($event)"
[connected]="ttsModelConnected()"
(save)="saveModelConfig('tts')"
(testConnection)="testModelConnection('tts')"
></app-ai-model-config-card>
<app-ai-model-config-card
title="تنظیمات مدل گفتگوی داخلی"
task="dialogue"
[config]="dialogueModelConfig()"
(configChange)="dialogueModelConfig.set($event)"
[connected]="dialogueModelConnected()"
(save)="saveModelConfig('dialogue')"
(testConnection)="testModelConnection('dialogue')"
></app-ai-model-config-card>
</div>
</div>
</section>
}
File diff suppressed because it is too large Load Diff
+398
View File
@@ -0,0 +1,398 @@
.wallboard-page {
min-height: 100%;
padding: 2.25rem 3rem 3.5rem;
display: flex;
flex-direction: column;
gap: 1.5rem;
animation: fadeIn 0.4s ease-out;
}
.wallboard-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
}
.wallboard-title-group {
display: flex;
align-items: center;
gap: 0.875rem;
}
.wallboard-title-icon {
display: flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
border-radius: 0.875rem;
background: var(--color-primary);
color: #ffffff;
flex-shrink: 0;
}
.wallboard-title {
margin: 0;
font-size: 1.5rem;
font-weight: 700;
color: var(--text-primary);
line-height: 1.3;
}
.wallboard-subtitle {
margin: 0.15rem 0 0;
font-size: 0.8125rem;
color: var(--text-muted);
}
.wallboard-header-actions {
display: flex;
align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
}
.period-chip {
padding: 0.45rem 0.9rem;
border: 1px solid var(--card-border);
border-radius: 9999px;
background: var(--card-bg);
font-size: 0.75rem;
color: var(--text-secondary);
white-space: nowrap;
}
.last-updated {
font-size: 0.75rem;
color: var(--text-muted);
white-space: nowrap;
}
.refresh-btn {
display: inline-flex;
align-items: center;
gap: 0.45rem;
padding: 0.45rem 0.9rem;
border: 1px solid var(--card-border);
border-radius: 9999px;
background: var(--card-bg);
color: var(--text-secondary);
font-size: 0.75rem;
font-weight: 500;
cursor: pointer;
transition: color 0.2s ease, border-color 0.2s ease, transform 0.2s ease;
}
.refresh-btn:hover:not(:disabled) {
color: var(--color-primary);
border-color: var(--color-primary);
transform: translateY(-1px);
}
.refresh-btn:disabled {
opacity: 0.6;
cursor: default;
}
.refresh-icon--spinning {
animation: spin 1s linear infinite;
}
/* ---- KPI tiles ---- */
.kpi-grid {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 1.25rem;
}
.kpi-card {
position: relative;
display: flex;
flex-direction: column;
gap: 0.4rem;
padding: 1.1rem 1.25rem 1.15rem;
border: 1px solid var(--card-border);
border-radius: 1.25rem;
background: var(--card-bg);
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.06), 0 2px 10px rgba(0, 0, 0, 0.03);
overflow: hidden;
animation: fadeInUp 0.5s ease-out both;
}
.kpi-card::before {
content: '';
position: absolute;
inset-block-start: 0;
inset-inline: 0;
height: 3px;
background: var(--kpi-color, var(--color-primary));
}
.kpi-card:nth-child(1) { animation-delay: 0.03s; }
.kpi-card:nth-child(2) { animation-delay: 0.06s; }
.kpi-card:nth-child(3) { animation-delay: 0.09s; }
.kpi-card:nth-child(4) { animation-delay: 0.12s; }
.kpi-card:nth-child(5) { animation-delay: 0.15s; }
.kpi-card-top {
display: flex;
align-items: center;
gap: 0.6rem;
}
.kpi-icon {
display: flex;
align-items: center;
justify-content: center;
width: 34px;
height: 34px;
border-radius: 0.7rem;
background: var(--kpi-color, var(--color-primary));
color: #ffffff;
flex-shrink: 0;
}
.kpi-label {
margin: 0;
font-size: 0.8125rem;
font-weight: 500;
color: var(--text-secondary);
line-height: 1.5;
}
.kpi-value {
font-size: 1.75rem;
font-weight: 700;
color: var(--text-primary);
line-height: 1.2;
}
.kpi-progress {
height: 6px;
border-radius: 9999px;
background: var(--stat-progress-bg, rgba(100, 116, 139, 0.16));
overflow: hidden;
}
.kpi-progress-fill {
display: block;
height: 100%;
border-radius: 9999px;
background: var(--kpi-color, var(--color-primary));
transition: width 0.8s cubic-bezier(0.22, 1, 0.36, 1);
}
.kpi-hint {
font-size: 0.6875rem;
color: var(--text-muted);
line-height: 1.6;
}
/* ---- charts ---- */
.charts-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 1.25rem;
}
.report-card {
padding: 1.25rem 1.4rem;
border: 1px solid var(--card-border);
border-radius: 1.25rem;
background: var(--card-bg);
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.06), 0 2px 10px rgba(0, 0, 0, 0.03);
animation: fadeInUp 0.5s ease-out both;
}
.card-header {
margin-bottom: 1.1rem;
}
.card-title {
margin: 0;
font-size: 1.0625rem;
font-weight: 600;
color: var(--text-primary);
}
.card-description {
margin: 0.2rem 0 0;
font-size: 0.75rem;
color: var(--text-muted);
line-height: 1.7;
}
.chart-peak {
display: inline-block;
margin-inline-start: 0.35rem;
color: var(--text-secondary);
}
/* ---- states ---- */
.error-card {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.5rem;
padding: 3rem 1.5rem;
text-align: center;
color: var(--text-muted);
}
.error-card h2 {
margin: 0.5rem 0 0;
font-size: 1.0625rem;
font-weight: 600;
color: var(--text-primary);
}
.error-card p {
margin: 0;
font-size: 0.8125rem;
}
.retry-btn {
margin-top: 0.75rem;
padding: 0.55rem 1.5rem;
border: none;
border-radius: 0.75rem;
background: var(--color-primary);
color: #ffffff;
font-size: 0.8125rem;
font-weight: 500;
cursor: pointer;
transition: opacity 0.2s ease, transform 0.2s ease;
}
.retry-btn:hover {
opacity: 0.9;
transform: translateY(-1px);
}
.skeleton-card {
min-height: 148px;
}
.skeleton {
border-radius: 0.5rem;
background: linear-gradient(
90deg,
var(--stat-progress-bg, rgba(100, 116, 139, 0.12)) 25%,
rgba(100, 116, 139, 0.05) 37%,
var(--stat-progress-bg, rgba(100, 116, 139, 0.12)) 63%
);
background-size: 400% 100%;
animation: skeletonShimmer 1.4s ease infinite;
}
.skeleton-title {
width: 45%;
height: 0.875rem;
}
.skeleton-value {
width: 35%;
height: 2rem;
margin-top: 0.75rem;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(16px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes skeletonShimmer {
from {
background-position: 100% 50%;
}
to {
background-position: 0 50%;
}
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: reduce) {
.kpi-card,
.report-card,
.skeleton,
.refresh-icon--spinning {
animation: none;
}
}
@media (max-width: 1400px) {
.wallboard-page {
padding: 1.75rem 2rem 3rem;
}
.kpi-grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
@media (max-width: 1024px) {
.wallboard-page {
padding: 1.5rem 1.75rem 2.75rem;
}
.kpi-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.charts-grid {
grid-template-columns: minmax(0, 1fr);
}
}
@media (max-width: 640px) {
.wallboard-page {
padding: 1.25rem 1.25rem 2.25rem;
}
.kpi-grid {
grid-template-columns: minmax(0, 1fr);
}
.wallboard-header-actions {
width: 100%;
}
}
:host-context([data-bs-theme='dark']) .report-card,
:host-context([data-bs-theme='dark']) .kpi-card {
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3), 0 2px 10px rgba(0, 0, 0, 0.2);
}
:host-context([data-bs-theme='dark']) .kpi-progress {
background: rgba(148, 163, 184, 0.2);
}
:host-context([data-bs-theme='dark']) .skeleton {
background: linear-gradient(90deg, rgba(148, 163, 184, 0.14) 25%, rgba(148, 163, 184, 0.05) 37%, rgba(148, 163, 184, 0.14) 63%);
background-size: 400% 100%;
}
+159
View File
@@ -0,0 +1,159 @@
<div class="wallboard-page">
<header class="wallboard-header">
<div class="wallboard-title-group">
<span class="wallboard-title-icon">
<svg
width="22"
height="22"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M2 4h20v12H2zM8 20h8M12 16v4" />
</svg>
</span>
<div>
<h1 class="wallboard-title">والبورد</h1>
<p class="wallboard-subtitle">نمای یک‌نگاه فعالیت مرکز تماس مبتنی بر هوش مصنوعی</p>
</div>
</div>
<div class="wallboard-header-actions">
@if (periodLabel()) {
<span class="period-chip">بازه گزارش: {{ periodLabel() }}</span>
}
<span class="last-updated">آخرین به‌روزرسانی: {{ lastUpdated() }}</span>
<button type="button" class="refresh-btn" (click)="refresh()" [disabled]="loading()">
<svg
class="refresh-icon"
[class.refresh-icon--spinning]="loading()"
width="15"
height="15"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21 12A9 9 0 0 0 6.6 7.5l-3 3m0 0 3 3-3-3Z" />
</svg>
<span>به‌روزرسانی</span>
</button>
</div>
</header>
@if (loading()) {
<div class="kpi-grid">
@for (card of [1, 2, 3, 4, 5]; track card) {
<div class="kpi-card skeleton-card">
<div class="skeleton skeleton-title"></div>
<div class="skeleton skeleton-value"></div>
</div>
}
</div>
} @else if (loadError()) {
<div class="report-card error-card" role="alert">
<svg
width="40"
height="40"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="9" />
<path d="M12 8v4M12 16h.01" />
</svg>
<h2>دریافت اطلاعات والبرد ممکن نشد</h2>
<p>ارتباط با سرور برقرار نشد. لطفاً دوباره تلاش کنید.</p>
<button type="button" class="retry-btn" (click)="retry()">تلاش مجدد</button>
</div>
} @else if (data(); as view) {
<section class="kpi-grid" aria-label="شاخص‌های کلیدی والبرد">
@for (kpi of kpis(); track kpi.id) {
<article class="kpi-card" [style.--kpi-color]="kpi.color">
<div class="kpi-card-top">
<span class="kpi-icon" aria-hidden="true">
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path [attr.d]="kpi.icon" />
</svg>
</span>
<h2 class="kpi-label">{{ kpi.label }}</h2>
</div>
<strong class="kpi-value">{{ kpi.value }}</strong>
@if (kpi.progress !== null) {
<div class="kpi-progress" aria-hidden="true">
<span class="kpi-progress-fill" [style.width.%]="kpi.progress"></span>
</div>
}
<span class="kpi-hint">{{ kpi.hint }}</span>
</article>
}
</section>
<div class="charts-grid">
<section class="report-card chart-card">
<div class="card-header">
<h2 class="card-title">هوش مصنوعی در مقابل کارشناس</h2>
<p class="card-description">
سهم هر روش پاسخ‌گویی از کل {{ formatCount(view.kpis.totalCalls) }} تماس در
{{ view.kpis.periodLabel }}
</p>
</div>
<app-doughnut-chart
[segments]="outcomes()"
centerLabel="کل تماس‌ها"
ariaLabel="نمودار دایره‌ای سهم روش‌های پاسخ‌گویی به تماس‌ها"
/>
</section>
<section class="report-card chart-card">
<div class="card-header">
<h2 class="card-title">توزیع تماس‌ها در ساعات روز</h2>
<p class="card-description">
حجم تماس‌ها در بازه‌های دو ساعته
@if (busiestHour(); as peak) {
<span class="chart-peak">پرفشارترین بازه: {{ peak.label }}</span>
}
</p>
</div>
<app-bar-chart
[items]="hourly()"
valueSuffix=" تماس"
ariaLabel="نمودار میله‌ای توزیع تماس‌ها در ساعات روز"
/>
</section>
</div>
<section class="report-card chart-card chart-card--wide">
<div class="card-header">
<h2 class="card-title">روند فعالیت تماس‌ها</h2>
<p class="card-description">
تغییرات حجم کل تماس‌ها در ۱۴ روز گذشته — روی نمودار بر روی هر نقطه بایست تا جزئیات آن روز
را ببینید.
</p>
</div>
<app-line-chart
[points]="activity()"
seriesLabel="تعداد تماس‌ها"
gradientId="wallboardCallActivity"
ariaLabel="نمودار خطی روند فعالیت تماس‌ها در گذر زمان"
/>
</section>
}
</div>
@@ -0,0 +1,74 @@
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { WallboardPage } from './wallboard.page';
describe('WallboardPage', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [WallboardPage],
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
provideAnimations(),
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
],
}).compileComponents();
});
function titles(fixture: { nativeElement: HTMLElement }): (string | undefined)[] {
return Array.from(fixture.nativeElement.querySelectorAll('.card-title')).map((node) =>
node.textContent?.trim(),
);
}
it('should create the page', () => {
const fixture = TestBed.createComponent(WallboardPage);
expect(fixture.componentInstance).toBeTruthy();
});
it('renders the five wallboard KPIs with Persian values', () => {
const fixture = TestBed.createComponent(WallboardPage);
fixture.detectChanges();
const element: HTMLElement = fixture.nativeElement;
expect(element.querySelector('.wallboard-title')?.textContent?.trim()).toBe('والبورد');
const labels = Array.from(element.querySelectorAll('.kpi-label')).map((node) =>
node.textContent?.trim(),
);
expect(labels).toEqual([
'تعداد کل تماس‌ها',
'تعداد تماس با هوش مصنوعی',
'میانگین زمان صحبت با هوش مصنوعی',
'تعداد تماس موفق با هوش مصنوعی',
'تعداد تماس با کارشناس بعد از هوش مصنوعی',
]);
const values = Array.from(element.querySelectorAll('.kpi-value')).map((node) =>
node.textContent?.trim(),
);
expect(values).toEqual(['۱۲,۸۴۶', '۸,۴۱۲', '۲:۲۲', '۷,۱۵۶', '۱,۲۵۶']);
expect(element.querySelectorAll('.kpi-card').length).toBe(5);
expect(element.textContent).toContain('۶۵٪ از کل تماس‌ها');
});
it('renders the wallboard charts', () => {
const fixture = TestBed.createComponent(WallboardPage);
fixture.detectChanges();
const element: HTMLElement = fixture.nativeElement;
expect(titles(fixture)).toEqual([
'هوش مصنوعی در مقابل کارشناس',
'توزیع تماس‌ها در ساعات روز',
'روند فعالیت تماس‌ها',
]);
expect(element.querySelector('app-doughnut-chart')).toBeTruthy();
expect(element.querySelector('app-bar-chart')).toBeTruthy();
expect(element.querySelector('app-line-chart')).toBeTruthy();
});
});
+193
View File
@@ -0,0 +1,193 @@
import { ChangeDetectionStrategy, Component, computed, inject, signal, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { forkJoin } from 'rxjs';
import { WallboardService } from '../../services/wallboard/wallboard.service';
import { WallboardView } from '../../services/wallboard/wallboard.types';
import { BarChartComponent, BarChartItem } from '../../shared/ui/charts/bar-chart.component';
import { DoughnutChartComponent, DoughnutSegment } from '../../shared/ui/charts/doughnut-chart.component';
import { LineChartComponent, LinePoint } from '../../shared/ui/charts/line-chart.component';
import { CHART_COLORS, CHART_PALETTE } from '../../shared/utils/chart-palette';
import { formatCount, formatPercent, toPersianDigits } from '../../shared/utils/format.util';
/** One KPI tile on the wallboard; rendering stays fully data-driven. */
export interface WallboardKpiCard {
id: string;
label: string;
value: string;
hint: string;
icon: string;
color: string;
/** Share of the related total (0–100) rendered as a progress bar; null hides it. */
progress: number | null;
}
@Component({
selector: 'app-wallboard',
standalone: true,
imports: [CommonModule, BarChartComponent, DoughnutChartComponent, LineChartComponent],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './wallboard.page.html',
styleUrl: './wallboard.page.css',
})
export class WallboardPage implements OnInit {
private readonly wallboard = inject(WallboardService);
readonly loading = signal(true);
readonly loadError = signal(false);
readonly data = signal<WallboardView | null>(null);
readonly lastUpdated = signal<string>('—');
readonly kpis = computed<WallboardKpiCard[]>(() => {
const view = this.data();
if (!view) {
return [];
}
return this.buildKpiCards(view);
});
readonly periodLabel = computed(() => this.data()?.kpis.periodLabel ?? '');
readonly outcomes = computed<DoughnutSegment[]>(() => {
const outcomes = this.data()?.outcomes ?? [];
return outcomes.map((outcome, index) => ({
label: outcome.label,
value: outcome.value,
color: CHART_PALETTE[index % CHART_PALETTE.length],
}));
});
readonly activity = computed<LinePoint[]>(() => {
const points = this.data()?.activity ?? [];
return points.map((point) => ({ label: point.label, value: point.count }));
});
readonly hourly = computed<BarChartItem[]>(() => {
const buckets = this.data()?.hourly ?? [];
return buckets.map((bucket) => ({
label: bucket.label,
value: bucket.count,
color: CHART_COLORS.primary,
}));
});
readonly busiestHour = computed(() => {
const buckets = this.data()?.hourly ?? [];
if (buckets.length === 0) {
return null;
}
return buckets.reduce((peak, bucket) => (bucket.count > peak.count ? bucket : peak), buckets[0]);
});
ngOnInit(): void {
this.load();
}
load(): void {
this.loading.set(true);
this.loadError.set(false);
forkJoin({
kpis: this.wallboard.getKpis(),
outcomes: this.wallboard.getOutcomes(),
activity: this.wallboard.getActivity(),
hourly: this.wallboard.getHourlyDistribution(),
}).subscribe({
next: (data) => {
this.data.set(data);
this.loading.set(false);
this.lastUpdated.set(this.formatClock(new Date()));
},
error: () => {
this.data.set(null);
this.loading.set(false);
this.loadError.set(true);
},
});
}
retry(): void {
this.load();
}
refresh(): void {
this.load();
}
/** KPI tiles in display order, each with its own icon, accent colour and share bar. */
private buildKpiCards(view: WallboardView): WallboardKpiCard[] {
const { kpis } = view;
const aiShare = kpis.totalCalls > 0 ? (kpis.aiCalls / kpis.totalCalls) * 100 : 0;
const successRate = kpis.aiCalls > 0 ? (kpis.successfulAiCalls / kpis.aiCalls) * 100 : 0;
const transferRate = kpis.aiCalls > 0 ? (kpis.transferredToAgentCalls / kpis.aiCalls) * 100 : 0;
return [
{
id: 'total-calls',
label: 'تعداد کل تماس‌ها',
value: formatCount(kpis.totalCalls),
hint: `کل تماس‌های دریافتی در ${kpis.periodLabel}`,
icon: 'M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z',
color: CHART_COLORS.primary,
progress: null,
},
{
id: 'ai-calls',
label: 'تعداد تماس با هوش مصنوعی',
value: formatCount(kpis.aiCalls),
hint: `${formatPercent(aiShare)} از کل تماس‌ها`,
icon: 'M12 3l1.9 5.8a2 2 0 0 0 1.3 1.3L21 12l-5.8 1.9a2 2 0 0 0-1.3 1.3L12 21l-1.9-5.8a2 2 0 0 0-1.3-1.3L3 12l5.8-1.9a2 2 0 0 0 1.3-1.3z',
color: CHART_COLORS.ai,
progress: aiShare,
},
{
id: 'avg-ai-talk',
label: 'میانگین زمان صحبت با هوش مصنوعی',
value: this.formatDuration(kpis.avgAiTalkSeconds),
hint: `دقیقه و ثانیه — میانگین روی ${formatCount(kpis.aiCalls)} تماس`,
icon: 'M3.34 19a10 10 0 1 1 17.32 0M12 14l4-4',
color: CHART_COLORS.info,
progress: null,
},
{
id: 'successful-ai-calls',
label: 'تعداد تماس موفق با هوش مصنوعی',
value: formatCount(kpis.successfulAiCalls),
hint: `${formatPercent(successRate)} از تماس‌های هوش مصنوعی`,
icon: 'M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18M8.5 12.5l2.5 2.5 4.5-5',
color: CHART_COLORS.success,
progress: successRate,
},
{
id: 'transferred-to-agent',
label: 'تعداد تماس با کارشناس بعد از هوش مصنوعی',
value: formatCount(kpis.transferredToAgentCalls),
hint: `${formatPercent(transferRate)} از تماس‌های هوش مصنوعی`,
icon: 'M8 3 4 7l4 4M4 7h16M16 21l4-4-4-4M20 17H4',
color: CHART_COLORS.warning,
progress: transferRate,
},
];
}
/** 142 -> «۲:۲۲» (دقیقه:ثانیه) */
formatDuration(totalSeconds: number): string {
const minutes = Math.floor(totalSeconds / 60);
const seconds = Math.round(totalSeconds % 60);
return toPersianDigits(`${minutes}:${String(seconds).padStart(2, '0')}`);
}
formatCount(value: number): string {
return formatCount(value);
}
formatPercent(value: number): string {
return formatPercent(value);
}
private formatClock(date: Date): string {
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return toPersianDigits(`${hours}:${minutes}`);
}
}
+14 -1
View File
@@ -1,4 +1,9 @@
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { AuthService } from './auth.service';
@@ -6,7 +11,15 @@ describe('AuthService', () => {
let service: AuthService;
beforeEach(() => {
TestBed.configureTestingModule({});
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
provideAnimations(),
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
],
});
service = TestBed.inject(AuthService);
});
+83 -27
View File
@@ -1,6 +1,7 @@
import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject, forkJoin, of, throwError } from 'rxjs';
import { tap, map, switchMap, catchError } from 'rxjs/operators';
import { Observable, BehaviorSubject, firstValueFrom, throwError } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
import { HttpErrorResponse } from '@angular/common/http';
import { HttpService } from '../http-request/http.service';
export interface AuthUser {
@@ -16,24 +17,25 @@ export interface LoginResponse {
expires_at: string;
}
export interface CurrentUserResponse {
user: AuthUser;
csrf_token: string;
expires_at: string;
}
export type CurrentUserResponse = LoginResponse;
/** All MVP routes live under `/api/v1` and are reached through the same-origin proxy. */
const API = 'api/v1';
@Injectable({
providedIn: 'root',
})
export class AuthService {
public currentUserSubject = new BehaviorSubject<AuthUser | null>(null);
/** CSRF token is kept in memory only (never persisted): it is re-read from `/me` after every reload. */
private csrfToken: string | null = null;
/** True once `/me` confirmed the identity for this page load (the cookie is the source of truth). */
private identityVerified = false;
constructor(
private httpService: HttpService,
) {
constructor(private httpService: HttpService) {
// Restore the last known user for instant rendering; `ensureIdentity()` re-validates
// it against `/me` at bootstrap (the HttpOnly `rag_session` cookie is the real session).
const savedUser = localStorage.getItem('current_user');
const savedCsrf = localStorage.getItem('csrf_token');
if (savedUser) {
try {
this.currentUserSubject.next(JSON.parse(savedUser));
@@ -41,21 +43,17 @@ export class AuthService {
// ignore corrupt data
}
}
if (savedCsrf) {
this.csrfToken = savedCsrf;
}
}
login(credentials: {
username: string;
password: string;
}): Observable<LoginResponse> {
return this.httpService.postRaw<LoginResponse>('v1/auth/login', credentials).pipe(
return this.httpService.postRaw<LoginResponse>(`${API}/auth/login`, credentials, {
headers: this.correlationHeaders(),
}).pipe(
tap((response) => {
this.currentUserSubject.next(response.user);
this.csrfToken = response.csrf_token;
localStorage.setItem('current_user', JSON.stringify(response.user));
localStorage.setItem('csrf_token', response.csrf_token);
this.applyIdentity(response);
}),
catchError((err) => {
this.clearAuth();
@@ -65,15 +63,17 @@ export class AuthService {
}
logout(): Observable<void> {
const headers: Record<string, string> = {};
const headers: Record<string, string> = this.correlationHeaders();
if (this.csrfToken) {
headers['X-CSRF-Token'] = this.csrfToken;
}
return this.httpService.postRaw<void>('v1/auth/logout', {}, { headers }).pipe(
// A02 has no body and returns 204 without a JSON payload.
return this.httpService.postRaw<void>(`${API}/auth/logout`, null, { headers }).pipe(
tap(() => {
this.clearAuth();
}),
catchError((err) => {
// Even when A02 fails, the local session is dropped so the UI shows the signed-out state.
this.clearAuth();
return throwError(() => err);
}),
@@ -81,16 +81,42 @@ export class AuthService {
}
getCurrentUser(): Observable<CurrentUserResponse> {
return this.httpService.getRaw<CurrentUserResponse>('v1/me').pipe(
return this.httpService.getRaw<CurrentUserResponse>(`${API}/me`, {
headers: this.correlationHeaders(),
}).pipe(
tap((response) => {
this.currentUserSubject.next(response.user);
this.csrfToken = response.csrf_token;
localStorage.setItem('current_user', JSON.stringify(response.user));
localStorage.setItem('csrf_token', response.csrf_token);
this.applyIdentity(response);
}),
);
}
/** Per-request correlation id shared with the server's `X-Request-ID`. */
private correlationHeaders(): Record<string, string> {
return { 'X-Request-ID': crypto.randomUUID() };
}
/**
* Reads `/me` once per page load. After a reload this is the first call the app makes,
* so a restored user is only trusted when the server still accepts the session cookie.
* `401 AUTH_REQUIRED` clears the authenticated state; anything else keeps the cached user.
*/
async ensureIdentity(): Promise<boolean> {
if (this.identityVerified) return this.isAuthenticated();
try {
const response = await firstValueFrom(this.getCurrentUser());
this.identityVerified = true;
return !!response?.user;
} catch (err) {
const res = err as HttpErrorResponse | undefined;
const code = (res?.error as { error?: { code?: string } } | null)?.error?.code;
if (res?.status === 401 || code === 'AUTH_REQUIRED') {
// The cookie session is gone (expired/revoked): drop the authenticated state.
this.clearAuth();
}
return this.isAuthenticated();
}
}
isAuthenticated(): boolean {
return !!this.currentUserSubject.value;
}
@@ -103,10 +129,40 @@ export class AuthService {
return this.csrfToken;
}
private applyIdentity(response: LoginResponse): void {
this.currentUserSubject.next(response.user);
this.csrfToken = response.csrf_token;
this.identityVerified = true;
localStorage.setItem('current_user', JSON.stringify(response.user));
}
private clearAuth(): void {
this.currentUserSubject.next(null);
this.csrfToken = null;
this.identityVerified = false;
localStorage.removeItem('current_user');
localStorage.removeItem('csrf_token');
}
/** Persian message for a backend error envelope code (catalog §7 / handoff §10). */
static messageForError(err: unknown, fallback = 'خطا در ارتباط با سرور. لطفاً دوباره تلاش کنید.'): string {
const res = err as HttpErrorResponse | undefined;
const code = (res?.error as { error?: { code?: string; message?: string } } | null)?.error?.code;
switch (code) {
case 'INVALID_CREDENTIALS':
return 'نام کاربری یا رمز عبور نامعتبر است.';
case 'AUTH_REQUIRED':
return 'نشست شما منقضی شده است. دوباره وارد شوید.';
case 'CSRF_INVALID':
return 'نشست شما نامعتبر است. دوباره وارد شوید.';
case 'FORBIDDEN':
return 'دسترسی به این بخش مجاز نیست.';
case 'RATE_LIMITED':
return 'تلاش‌های بیش از حد مجاز. لطفاً بعداً تلاش کنید.';
case 'DEPENDENCY_UNAVAILABLE':
return 'سرویس موقتاً در دسترس نیست. لطفاً دوباره تلاش کنید.';
default:
if (!code && res && res.status === 0) return 'ارتباط با سرور برقرار نشد.';
return fallback;
}
}
}
@@ -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: 'ناموفق',
};
@@ -1,4 +1,9 @@
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { HttpService } from './http.service';
@@ -6,7 +11,15 @@ describe('HttpService', () => {
let service: HttpService;
beforeEach(() => {
TestBed.configureTestingModule({});
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
provideAnimations(),
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
],
});
service = TestBed.inject(HttpService);
});
+72 -12
View File
@@ -1,7 +1,13 @@
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import {
HttpClient,
HttpErrorResponse,
HttpHeaders,
HttpEvent,
HttpEventType,
} from '@angular/common/http';
import { Router } from '@angular/router';
import { catchError, Observable, throwError, map } from 'rxjs';
import { catchError, Observable, throwError, map, race } from 'rxjs';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrService } from 'ngx-toastr';
@@ -25,6 +31,8 @@ export interface HttpOptions {
cooldownMs?: number;
skipHasErrorCheck?: boolean;
headers?: Record<string, string>;
/** Optional AbortSignal forwarded to the underlying XMLHttpRequest. */
signal?: AbortSignal;
}
export const EVENT_STREAM_HEADERS = {
@@ -37,15 +45,16 @@ export const EVENT_STREAM_HEADERS = {
providedIn: 'root',
})
export class HttpService {
// private readonly baseUrl = `${window.location.protocol}//${window.location.hostname}/api`;
// public readonly backendUrl = `${window.location.protocol}//${window.location.hostname}/api`;
// public readonly apiUrl = `${window.location.protocol}//${window.location.hostname}/api`;
// public readonly imagesUrl = `${window.location.protocol}//${window.location.hostname}`;
private readonly baseUrl = `http://192.168.180.151:1321`;
public readonly backendUrl = `http://192.168.180.151:1321`;
public readonly apiUrl = `http://192.168.180.151:1321`;
public readonly imagesUrl = `http://192.168.180.151:1321`;
/**
* 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,
@@ -197,7 +206,7 @@ export class HttpService {
...headers,
},
signal: controller.signal,
credentials: 'omit',
credentials: 'same-origin',
})
.then((response) => {
if (!response.ok || !response.body) {
@@ -275,6 +284,57 @@ export class HttpService {
});
}
/**
* 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();
+14 -1
View File
@@ -1,4 +1,9 @@
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { ThemeService } from './theme.service';
@@ -6,7 +11,15 @@ describe('ThemeService', () => {
let service: ThemeService;
beforeEach(() => {
TestBed.configureTestingModule({});
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
provideAnimations(),
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
],
});
service = TestBed.inject(ThemeService);
});
+2 -2
View File
@@ -21,7 +21,7 @@ export class ThemeService {
this.applyTheme('light');
}
this.httpService.get('users/get-dark-mode').subscribe({
this.httpService.get('users/get-dark-mode', { skipToast: true }).subscribe({
next: (res: any) => {
const isBackendDark = res.result.dark_mode;
const trueTheme = isBackendDark ? 'dark' : 'light';
@@ -41,7 +41,7 @@ export class ThemeService {
const payload = { dark_mode: isDark };
this.httpService.post('users/update-dark-mode', payload).subscribe({
this.httpService.post('users/update-dark-mode', payload, { skipToast: true }).subscribe({
next: () => {},
error: () => {}
});
@@ -1,9 +1,13 @@
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { firstValueFrom, Observable } from 'rxjs';
import { VOICE_STREAM_CONFIG } from './voice-stream.types';
import { firstValueFrom, race, throwError, Observable } from 'rxjs';
import { delay } from 'rxjs/operators';
import { VOICE_STREAM_CONFIG, VoiceSessionStatus } from './voice-stream.types';
/** Error envelope from the catalog: { error: { code, message, request_id, retryable, details } }. */
/** The voice helper's HTTP deadline: a client timeout never means the server rolled back. */
const REQUEST_DEADLINE_MS = 5000;
/** Error envelope from the contract: { error: { code, message, request_id, retryable, details } }. */
export class VoiceApiError extends Error {
constructor(
readonly status: number,
@@ -24,14 +28,26 @@ export interface MeResponse {
}
export interface ConfigurationResponse {
capabilities: { text: boolean; voice: boolean; captions: boolean };
revision: number;
assistant_name: string;
instruction: string;
capabilities: {
text: boolean;
voice: boolean;
captions: boolean;
supported_upload_types?: string[];
max_upload_bytes?: number;
max_pdf_pages?: number;
};
}
export interface ConversationResponse {
id: string;
mode: 'voice';
title: string;
title?: string;
status: string;
access_epoch?: number;
created_at?: string;
}
export interface VoiceSessionResponse {
@@ -43,10 +59,15 @@ export interface VoiceSessionResponse {
poll_url: string;
}
/** V02: status + safe diagnostics for a reserved/connected session. */
export interface VoiceSessionPollResponse extends VoiceSessionStatus {
recent_tool_results?: unknown[];
}
/**
* Thin client for the endpoints the live voice call needs (A03, F01, C01, V01, V04).
* Uses HttpClient so the app's existing interceptors (401 → login redirect, etc.) still apply.
* Auth is the HttpOnly `rag_session` cookie; state-changing calls also need `X-CSRF-Token`.
* Thin client for the endpoints the live voice call needs (A03, F01, C01, V01, V02, V03, V04).
* Auth is the HttpOnly `rag_session` cookie (same-origin proxy); state-changing calls also need
* `X-CSRF-Token`. C01/V01 are idempotent through their JSON `client_request_id`, never headers.
*/
@Injectable({ providedIn: 'root' })
export class VoiceApiService {
@@ -55,50 +76,78 @@ export class VoiceApiService {
/** A03: identity + a fresh CSRF token. 401 AUTH_REQUIRED when not logged in. */
me(): Promise<MeResponse> {
return this.send(this.http.get<MeResponse>(this.url('/me'), { withCredentials: true }));
return this.send(this.http.get<MeResponse>(this.url('/me'), this.readOptions()));
}
/** F01: capabilities (the UI must check `voice` before offering a call). */
configuration(): Promise<ConfigurationResponse> {
return this.send(
this.http.get<ConfigurationResponse>(this.url('/configuration'), { withCredentials: true }),
);
return this.send(this.http.get<ConfigurationResponse>(this.url('/configuration'), this.readOptions()));
}
/** C01: only `mode: "voice"` exists in the MVP. */
createConversation(csrf: string, title: string): Promise<ConversationResponse> {
/** C01: only `mode: "voice"` exists in the MVP. `clientRequestId` makes replays return the same conversation. */
createConversation(csrf: string, title: string, clientRequestId: string): Promise<ConversationResponse> {
return this.send(
this.http.post<ConversationResponse>(
this.url('/conversations'),
{ client_request_id: crypto.randomUUID(), mode: 'voice', title },
this.options(csrf),
{ client_request_id: clientRequestId, mode: 'voice', title },
this.writeOptions(csrf),
),
);
}
/** V01: reserves a live session; connect the WebSocket to the returned `stream_path`. */
createVoiceSession(csrf: string, conversationId: string): Promise<VoiceSessionResponse> {
createVoiceSession(
csrf: string,
conversationId: string,
clientRequestId: string,
): Promise<VoiceSessionResponse> {
return this.send(
this.http.post<VoiceSessionResponse>(
this.url('/voice/sessions'),
{ conversation_id: conversationId, client_request_id: crypto.randomUUID() },
this.options(csrf),
{ conversation_id: conversationId, client_request_id: clientRequestId },
this.writeOptions(csrf),
),
);
}
/** V04: closes the session (idempotent from the UI's point of view). */
/** V02: status + safe diagnostics (no secrets). */
pollVoiceSession(csrf: string, sessionId: string): Promise<VoiceSessionPollResponse> {
return this.send(
this.http.get<VoiceSessionPollResponse>(
this.url(`/voice/sessions/${encodeURIComponent(sessionId)}`),
this.readOptions(),
),
);
}
/**
* V03: reconcile a reservation by its C01/V01 `client_request_id` — used after an
* ambiguous (timeout / network) reserve, or after a reload. Never opens a new provider
* connection: `null` means the attempt was never reserved.
*/
getVoiceSessionByRequest(csrf: string, clientRequestId: string): Promise<VoiceSessionResponse | null> {
return this.send(
this.http
.get<VoiceSessionResponse>(
this.url(`/voice/sessions/by-request/${encodeURIComponent(clientRequestId)}`),
this.readOptions(),
)
.pipe(this.mapNotFoundToNull()),
);
}
/** V04: closes the session explicitly (no body). */
async closeVoiceSession(csrf: string, sessionId: string): Promise<void> {
await this.send(
this.http.post<unknown>(
this.url(`/voice/sessions/${encodeURIComponent(sessionId)}/close`),
{},
this.options(csrf),
this.writeOptions(csrf),
),
);
}
/** `wss://…` URL for a V01 `stream_path`. */
/** `wss://…` URL for a V01 `stream_path` (same origin as the UI). */
streamUrl(streamPath: string): string {
const base = this.config.apiOrigin || window.location.origin;
const url = new URL(streamPath, base);
@@ -112,22 +161,56 @@ export class VoiceApiService {
return `${this.config.apiOrigin}${this.config.apiBase}${path}`;
}
private options(csrf: string) {
private readOptions() {
return { withCredentials: true, headers: new HttpHeaders({ 'X-Request-ID': crypto.randomUUID() }) };
}
private writeOptions(csrf: string) {
return {
withCredentials: true,
headers: new HttpHeaders({ 'X-CSRF-Token': csrf, 'X-Request-ID': crypto.randomUUID() }),
headers: new HttpHeaders({
'X-CSRF-Token': csrf,
'X-Request-ID': crypto.randomUUID(),
}),
};
}
private mapNotFoundToNull<T>() {
return (source: Observable<T>): Observable<T | null> =>
new Observable<T | null>((observer) => {
const sub = source.subscribe({
next: (value) => observer.next(value),
error: (err: unknown) => {
if (err instanceof HttpErrorResponse && err.status === 404) observer.next(null);
else observer.error(err);
observer.complete();
},
complete: () => observer.complete(),
});
return () => sub.unsubscribe();
});
}
private async send<T>(request: Observable<T>): Promise<T> {
try {
return await firstValueFrom(request);
return await firstValueFrom(this.withDeadline(request));
} catch (err) {
throw this.toApiError(err);
}
}
/** A short deadline keeps the UI responsive; the caller reconciles the uncertain outcome. */
private withDeadline<T>(request: Observable<T>): Observable<T> {
return race(
request,
throwError(() => new VoiceApiError(0, 'TIMEOUT', 'request-deadline')).pipe(
delay(REQUEST_DEADLINE_MS),
),
);
}
private toApiError(err: unknown): VoiceApiError {
if (err instanceof VoiceApiError) return err; // deadline / already-normalized error
if (err instanceof HttpErrorResponse) {
const envelope = (err.error as { error?: Record<string, unknown> } | null)?.error;
return new VoiceApiError(
@@ -9,6 +9,13 @@ export interface VoiceEngineHandlers {
onPlaybackIdle(): void;
/** The microphone track ended unexpectedly. */
onMicEnded(): void;
/**
* Real playback progress for one server `audio_ref`: cumulative milliseconds computed
* from consumed samples (never a timer), reported ~4×/s and finally on interruption/stop.
*/
onPlaybackProgress(audioRef: string, playedMs: number): void;
/** The bounded playback queue filled: the session must fail safely (no silent PCM drop). */
onPlaybackOverflow(): void;
}
export class VoiceEngineError extends Error {
@@ -20,8 +27,8 @@ export class VoiceEngineError extends Error {
/**
* Low-level audio for the call:
* mic → [pcm-capture worklet] → PCM16 frames → (service → transport)
* (transport → service) → PCM16 chunks → [pcm-playback worklet] → speakers
* mic → [pcm-capture worklet] → PCM16 24 kHz frames → (service → transport)
* (transport → service) → PCM16 24 kHz chunks → [pcm-playback worklet] → speakers
* Everything here runs outside Angular's zone; frames arrive ~50×/s and must not trigger change detection.
*/
@Injectable({ providedIn: 'root' })
@@ -106,8 +113,22 @@ export class VoiceAudioEngine {
numberOfOutputs: 1,
outputChannelCount: [1],
});
this.playback.port.onmessage = (event: MessageEvent<{ type: string }>) => {
if (event.data?.type === 'idle') handlers.onPlaybackIdle();
this.playback.port.onmessage = (
event: MessageEvent<{ type: string; audioRef?: string; playedMs?: number }>,
) => {
switch (event.data?.type) {
case 'idle':
handlers.onPlaybackIdle();
break;
case 'progress':
if (event.data.audioRef) {
handlers.onPlaybackProgress(event.data.audioRef, event.data.playedMs ?? 0);
}
break;
case 'overflow':
handlers.onPlaybackOverflow();
break;
}
};
this.analyser = ctx.createAnalyser();
this.analyser.fftSize = 1024;
@@ -119,17 +140,17 @@ export class VoiceAudioEngine {
// ---- playback --------------------------------------------------------------
/** Queues a PCM16 mono chunk at config.outputSampleRate. Ownership of the buffer moves to the worklet. */
enqueuePlayback(chunk: ArrayBuffer): void {
/** Queues a PCM16 mono chunk at config.outputSampleRate under its server `audio_ref`. */
enqueuePlayback(chunk: ArrayBuffer, audioRef: string | null): void {
if (!this.playback) return;
const buffer = chunk.byteLength % 2 === 0 ? chunk : chunk.slice(0, chunk.byteLength - 1);
this.playback.port.postMessage(
{ type: 'push', pcm: buffer, sampleRate: this.config.outputSampleRate },
{ type: 'push', pcm: buffer, sampleRate: this.config.outputSampleRate, audioRef },
[buffer],
);
}
/** Barge-in: drop all queued audio immediately. */
/** Barge-in: drop all queued audio immediately (final progress is reported by the worklet). */
clearPlayback(): void {
this.playback?.port.postMessage({ type: 'clear' });
}
@@ -0,0 +1,304 @@
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { first } from 'rxjs';
import { vi } from 'vitest';
import { VoiceApiError, VoiceApiService } from './voice-api.service';
import { VoiceAudioEngine, VoiceEngineHandlers } from './voice-audio-engine.service';
import { VoiceStreamService } from './voice-stream.service';
import { VOICE_TRANSPORT_FACTORY, VoiceTransport, VoiceTransportHandlers } from './voice-transport';
import { PlaybackProgressMessage, VoiceServerEvent } from './voice-stream.types';
const ME = { user: { id: 'u1', username: 'admin', role: 'admin', organization_id: 'o1' }, csrf_token: 'csrf-1', expires_at: 'later' };
const CONFIG = {
revision: 1,
assistant_name: 'دستیار',
instruction: '',
capabilities: { text: true, voice: true, captions: true },
};
const CONVERSATION = { id: 'conv-1', mode: 'voice' as const, status: 'active' };
const SESSION = {
session_id: 'ses-1',
conversation_id: 'conv-1',
status: 'reserved',
stream_path: '/api/v1/voice/sessions/ses-1/stream',
expires_at: 'later',
poll_url: '/api/v1/voice/sessions/ses-1',
};
const READY_EVENT: VoiceServerEvent = {
type: 'session_ready',
session_id: 'ses-1',
input_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 },
output_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 },
};
/** Flush pending microtasks/timers so the service reaches a stable await point. */
const flush = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 5));
describe('VoiceStreamService (backend handoff contract)', () => {
let service: VoiceStreamService;
let api: {
me: ReturnType<typeof vi.fn>;
configuration: ReturnType<typeof vi.fn>;
createConversation: ReturnType<typeof vi.fn>;
createVoiceSession: ReturnType<typeof vi.fn>;
getVoiceSessionByRequest: ReturnType<typeof vi.fn>;
pollVoiceSession: ReturnType<typeof vi.fn>;
closeVoiceSession: ReturnType<typeof vi.fn>;
streamUrl: ReturnType<typeof vi.fn>;
};
let engineHandlers: VoiceEngineHandlers | null;
let transportHandlers: VoiceTransportHandlers | null;
let controls: PlaybackProgressMessage[];
beforeEach(() => {
sessionStorage.clear();
engineHandlers = null;
transportHandlers = null;
controls = [];
api = {
me: vi.fn().mockResolvedValue(ME),
configuration: vi.fn().mockResolvedValue(CONFIG),
createConversation: vi.fn().mockResolvedValue(CONVERSATION),
createVoiceSession: vi.fn().mockResolvedValue(SESSION),
getVoiceSessionByRequest: vi.fn().mockResolvedValue(null),
pollVoiceSession: vi.fn().mockResolvedValue({ session_id: 'ses-1', status: 'connected' }),
closeVoiceSession: vi.fn().mockResolvedValue(undefined),
streamUrl: vi.fn().mockReturnValue('wss://ui.local/api/v1/voice/sessions/ses-1/stream'),
};
const transportMock: VoiceTransport & { handlers: VoiceTransportHandlers | null } = {
handlers: null,
connect: vi.fn().mockImplementation((handlers: VoiceTransportHandlers) => {
transportHandlers = handlers;
transportMock.handlers = handlers;
return Promise.resolve();
}),
sendAudio: vi.fn(),
sendControl: vi.fn().mockImplementation((message: PlaybackProgressMessage) => controls.push(message)),
close: vi.fn(),
};
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
{ provide: VoiceApiService, useValue: api },
{
provide: VoiceAudioEngine,
useValue: {
isSupported: true,
start: vi.fn().mockImplementation((handlers: VoiceEngineHandlers) => {
engineHandlers = handlers;
return Promise.resolve();
}),
stop: vi.fn(),
setMuted: vi.fn(),
enqueuePlayback: vi.fn(),
clearPlayback: vi.fn(),
flushPlayback: vi.fn(),
inputLevel: () => 0,
outputLevel: () => 0,
},
},
{ provide: VOICE_TRANSPORT_FACTORY, useFactory: () => () => transportMock },
],
});
service = TestBed.inject(VoiceStreamService);
});
/** Drives a full start() up to `connected`, emitting the server `session_ready`. */
async function startConnected(): Promise<void> {
const started = service.start();
await flush();
transportHandlers?.onEvent(READY_EVENT);
await started;
}
function firstEndedError(): Promise<string | undefined> {
return new Promise((resolve) => service.sessionEnded$.pipe(first()).subscribe((end) => resolve(end.error)));
}
it('creates conversation then voice session with two separate client request ids', async () => {
await startConnected();
expect(api.createConversation).toHaveBeenCalledTimes(1);
const [, , conversationRequestId] = api.createConversation.mock.calls[0];
expect(conversationRequestId).toMatch(/^[0-9a-f-]{36}$/);
expect(api.createVoiceSession).toHaveBeenCalledTimes(1);
const [, conversationId, sessionRequestId] = api.createVoiceSession.mock.calls[0];
expect(conversationId).toBe('conv-1');
expect(sessionRequestId).not.toBe(conversationRequestId); // the two ids are independent
expect(service.connection()).toBe('connected');
expect(service.state()).toBe('LISTENING');
});
it('rejects a session_ready whose audio format breaks the 24 kHz mono PCM16LE contract', async () => {
const started = service.start();
await flush();
transportHandlers?.onEvent({
type: 'session_ready',
session_id: 'ses-1',
input_audio: { encoding: 'pcm_s16le', sample_rate: 16000, channels: 1 },
output_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 },
});
const result = await started;
expect(result).toEqual({ ok: false, reason: 'connect', message: 'فرمت صدای سرور با برنامه سازگار نیست.' });
});
it('reconciles an ambiguous V01 through V03 instead of creating a second session', async () => {
api.createVoiceSession
.mockRejectedValueOnce(new VoiceApiError(0, 'TIMEOUT', 'timeout'))
.mockResolvedValue(SESSION);
api.getVoiceSessionByRequest.mockResolvedValue(SESSION);
await startConnected();
expect(api.getVoiceSessionByRequest).toHaveBeenCalledTimes(1);
const requestedId = api.getVoiceSessionByRequest.mock.calls[0][1];
expect(typeof requestedId).toBe('string');
expect(api.createVoiceSession).toHaveBeenCalledTimes(1); // no blind duplicate create
expect(service.connection()).toBe('connected');
});
it('replays V01 with the same client_request_id when reconciliation finds nothing', async () => {
api.createVoiceSession
.mockRejectedValueOnce(new VoiceApiError(0, 'TIMEOUT', 'timeout'))
.mockResolvedValue(SESSION);
api.getVoiceSessionByRequest.mockResolvedValue(null);
await startConnected();
expect(api.createVoiceSession).toHaveBeenCalledTimes(2);
const firstId = api.createVoiceSession.mock.calls[0][2];
const secondId = api.createVoiceSession.mock.calls[1][2];
expect(secondId).toBe(firstId); // same attempt, same payload
});
it('keeps the creation attempt after an ambiguous reserve so the next start() reconciles', async () => {
api.createConversation.mockRejectedValue(new VoiceApiError(0, 'TIMEOUT', 'timeout'));
const first = await service.start();
expect(first.ok).toBe(false);
expect(sessionStorage.getItem('voice_creation_attempt')).toBeTruthy();
// The replay used the same ids, never a fresh uuid.
const firstId = api.createConversation.mock.calls[0][2];
const secondId = api.createConversation.mock.calls[1][2];
expect(secondId).toBe(firstId);
});
it('sends playback_progress with the cumulative played_ms reported by the worklet', async () => {
await startConnected();
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1' });
engineHandlers?.onPlaybackProgress('aud-1', 120);
engineHandlers?.onPlaybackProgress('aud-1', 900);
expect(controls).toEqual([
{ type: 'playback_progress', audio_ref: 'aud-1', played_ms: 120 },
{ type: 'playback_progress', audio_ref: 'aud-1', played_ms: 900 },
]);
});
it('reports the final real played progress when the turn is interrupted', async () => {
await startConnected();
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 'turn-1', role: 'assistant', text: 'پاسخ', status: 'partial' });
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-2' });
engineHandlers?.onPlaybackProgress('aud-2', 300);
controls = [];
transportHandlers?.onEvent({ type: 'turn_interrupted', turn_ref: 'turn-1' });
// The worklet answers `clear` with its final cumulative report for the ref.
engineHandlers?.onPlaybackProgress('aud-2', 780);
expect(controls).toEqual([
{ type: 'playback_progress', audio_ref: 'aud-2', played_ms: 780 },
]);
expect(service.messages().find((m) => m.id === 'turn-1:assistant')?.interrupted).toBe(true);
});
it('ends safely with a failure when the bounded playback queue overflows', async () => {
await startConnected();
const ended = firstEndedError();
engineHandlers?.onPlaybackOverflow();
expect(await ended).toBe('حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو به‌طور ایمن پایان یافت.');
expect(service.connection()).toBe('disconnected');
});
it('requires a fresh conversation after CONTEXT_REVOKED and drops the old attempt', async () => {
await startConnected();
const ended = firstEndedError();
transportHandlers?.onEvent({
type: 'error',
error: { code: 'CONTEXT_REVOKED', message: 'context revoked', retryable: false },
});
expect(await ended).toBe('محتوای دانش تغییر کرده و مکالمهٔ قبلی دیگر معتبر نیست. گفتگوی جدیدی شروع کنید.');
expect(sessionStorage.getItem('voice_creation_attempt')).toBeNull();
expect(service.connection()).toBe('disconnected');
});
it('keeps a retryable server error non-fatal (the session stays usable)', async () => {
await startConnected();
transportHandlers?.onEvent({
type: 'error',
error: { code: 'SEARCH_TIMEOUT', message: 'جست‌وجو دیر شد', retryable: true },
});
expect(service.streamError()).toBe('جست‌وجو دیر شد');
expect(service.connection()).toBe('connected');
});
it('hides excerpts of sources the server marks unavailable', async () => {
await startConnected();
transportHandlers?.onEvent({
type: 'sources',
turn_ref: 'turn-9',
sources: [
{
source_ref: 'src-1',
document_id: 'doc-1',
chunk_id: 'chunk-1',
title: 'سند آزمون',
excerpt: 'متن منقضی‌شده',
available: false,
},
],
});
const assistant = service.messages().find((m) => m.id === 'turn-9:assistant');
expect(assistant?.sources?.[0].available).toBe(false);
expect(assistant?.sources?.[0].excerpt).toBeUndefined();
});
it('marks partial then completed transcripts final', async () => {
await startConnected();
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'سلام', status: 'partial' });
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'سلام و خوب', status: 'partial' });
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'سلام و خوب', status: 'completed' });
const assistant = service.messages().find((m) => m.id === 't1:assistant');
expect(assistant?.text).toBe('سلام و خوب');
expect(assistant?.final).toBe(true);
});
it('closes the reservation (V04) when the call ends on user request', async () => {
await startConnected();
await service.close();
expect(api.closeVoiceSession).toHaveBeenCalledWith('csrf-1', 'ses-1');
expect(sessionStorage.getItem('voice_creation_attempt')).toBeNull();
expect(service.connection()).toBe('disconnected');
});
});
@@ -1,7 +1,7 @@
import { Injectable, NgZone, computed, inject, signal } from '@angular/core';
import { Subject } from 'rxjs';
import { MicrophoneError } from '../microphone/microphone.service';
import { VoiceApiError, VoiceApiService } from './voice-api.service';
import { VoiceApiError, VoiceApiService, VoiceSessionResponse } from './voice-api.service';
import { VoiceAudioEngine, VoiceEngineError } from './voice-audio-engine.service';
import { VOICE_TRANSPORT_FACTORY, VoiceTransport } from './voice-transport';
import {
@@ -21,7 +21,8 @@ export type VoiceStartFailure =
| 'auth'
| 'unavailable'
| 'api'
| 'connect';
| 'connect'
| 'overflow';
export type VoiceStartResult =
| { ok: true }
@@ -45,8 +46,11 @@ const MESSAGES = {
api: 'شروع گفتگوی صوتی ناموفق بود. دوباره تلاش کنید.',
connect: 'اتصال به سرور صوتی برقرار نشد. دوباره تلاش کنید.',
badFormat: 'فرمت صدای سرور با برنامه سازگار نیست.',
overflow: 'حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو به‌طور ایمن پایان یافت.',
disconnected: 'ارتباط با سرور قطع شد و گفتگو پایان یافت.',
server: 'سرور گفتگوی صوتی با خطا مواجه شد.',
contextRevoked: 'محتوای دانش تغییر کرده و مکالمهٔ قبلی دیگر معتبر نیست. گفتگوی جدیدی شروع کنید.',
stale: 'مکالمهٔ قبلی منقضی شده است. گفتگوی جدیدی شروع کنید.',
conversationTitle: 'گفتگوی صوتی',
} as const;
@@ -54,20 +58,29 @@ const MESSAGES = {
const INTERRUPTED_FLASH_MS = 150;
/** How long a retryable server error stays on screen. */
const ERROR_BANNER_MS = 6000;
/** Longest wait for the worklet's final playback report when closing a call. */
const FINAL_PROGRESS_WAIT_MS = 300;
/**
* One live voice call against the MVP API (mvp_ui_api_catalog.md §6):
* One live voice call against the backend handoff contract (§7–§9):
*
* mic ─▶ engine ─▶ PCM16 16 kHz frames ─▶ WSS ─▶ server
* server ─▶ session_ready / transcript / sources / turn_interrupted / error (JSON)
* mic ─▶ engine ─▶ PCM16 24 kHz frames ─▶ WSS ─▶ server
* server ─▶ session_ready / user_speech_started / transcript / sources /
* audio_started / audio_ended / turn_interrupted / error (JSON)
* ─▶ PCM16 24 kHz audio (binary) ─▶ engine playback
* client ─▶ playback_progress (the only JSON control message, cumulative played_ms)
*
* Start: mic permission → GET /me (CSRF) → GET /configuration (voice enabled?)
* → POST /conversations → POST /voice/sessions → WSS stream_path → `session_ready`.
* End: close the socket, stop audio, POST /voice/sessions/{id}/close.
* Start: mic permission → GET /me (CSRF) → POST /conversations → POST /voice/sessions
* → WSS stream_path → `session_ready`.
* End: final playback progress → V04 close → close the socket, stop the audio.
*
* Barge-in is decided by the server: it sends `turn_interrupted` and the client flushes playback.
* (The contract has no client→server interrupt message.)
* Barge-in is decided by the server: it sends `turn_interrupted` and the client flushes
* playback. The contract has no other client→server JSON message.
*
* Ambiguous C01/V01 outcomes (timeout / network) are reconciled with the SAME
* `client_request_id` pair — replayed via V03 or the identical request — never with new
* ids, so a second conversation/session is never created. The attempt is kept in
* sessionStorage (ids and paths only, no secrets) so a reload can reconcile first.
*/
@Injectable({ providedIn: 'root' })
export class VoiceStreamService {
@@ -106,6 +119,24 @@ export class VoiceStreamService {
} | null = null;
private lastConversationId: string | null = null;
/** Creation attempt: stable client request ids + the ids/paths the server returned. */
private attempt: VoiceCreationAttempt | null = null;
/** Latest cumulative played_ms actually consumed by the worklet, per server audio_ref. */
private readonly playedMsByRef = new Map<string, number>();
private currentAudioRef: string | null = null;
private progressWaiters: Array<() => void> = [];
constructor() {
this.attempt = loadPersistedAttempt();
// A reload during a call leaves an un-reconciled reservation: reconcile with the
// server first (V02/V03), close what is still open, and drop the attempt. Media is
// never auto-resumed — the user starts a fresh conversation explicitly.
if (this.attempt) void this.recover();
// Leaving the page releases mic/worklet/AudioContext/WebSocket immediately.
window.addEventListener('pagehide', this.onPageLeave);
}
// ---- public API -----------------------------------------------------------
async start(options: { title?: string } = {}): Promise<VoiceStartResult> {
@@ -120,27 +151,35 @@ export class VoiceStreamService {
this.clearError();
this.resetTurnFlags();
this.lastConversationId = null;
this.currentAudioRef = null;
this.playedMsByRef.clear();
this.state.set('IDLE');
this.connection.set('connecting');
// Reuse a persisted attempt (ambiguous outcome of a previous try); otherwise create one.
if (!this.attempt) this.attempt = newCreationAttempt();
persistAttempt(this.attempt);
// 1) microphone + worklets (needs the user gesture; shows the permission prompt)
try {
await this.engine.start({
onFrame: (pcm) => this.onMicFrame(pcm),
onPlaybackIdle: () => this.ngZone.run(() => this.onPlaybackIdle()),
onMicEnded: () => this.ngZone.run(() => this.failSession(MESSAGES.micLost, session)),
onPlaybackProgress: (audioRef, playedMs) =>
this.ngZone.run(() => this.onPlaybackProgress(audioRef, playedMs)),
onPlaybackOverflow: () => this.ngZone.run(() => this.failSession(MESSAGES.overflow, session)),
});
} catch (err) {
return this.abortStart(session, this.mapEngineError(err));
}
if (stale()) {
// Cancelled while the permission prompt / worklets were loading: release what was just opened.
if (!this.isOpen()) this.engine.stop();
return this.failure('cancelled', '');
}
// 2) REST: identity/CSRF → capabilities → conversation → voice session
let streamPath: string;
let voiceSession: VoiceSessionResponse;
try {
const me = await this.api.me();
if (stale()) return this.failure('cancelled', '');
@@ -151,29 +190,31 @@ export class VoiceStreamService {
return this.abortStart(session, { reason: 'unavailable', message: MESSAGES.voiceDisabled });
}
const conversation = await this.api.createConversation(me.csrf_token, MESSAGES.conversationTitle);
if (stale()) return this.failure('cancelled', '');
const voiceSession = await this.api.createVoiceSession(me.csrf_token, conversation.id);
const remote = {
sessionId: voiceSession.session_id,
conversationId: conversation.id,
csrf: me.csrf_token,
};
voiceSession = await this.reserve(me.csrf_token, options.title ?? MESSAGES.conversationTitle);
if (stale()) {
this.closeRemote(remote); // cancelled after the server already reserved the session
this.closeRemote({ sessionId: voiceSession.session_id, csrf: me.csrf_token });
this.attempt = null;
clearPersistedAttempt();
return this.failure('cancelled', '');
}
this.remote = remote;
this.lastConversationId = conversation.id;
streamPath = voiceSession.stream_path;
} catch (err) {
if (stale()) return this.failure('cancelled', '');
return this.abortStart(session, this.mapApiError(err));
// An ambiguous reserve outcome (timeout / network / 5xx) keeps the attempt: the
// next start reconciles it with the same client_request_ids instead of creating a
// second conversation/session. A definitive failure (4xx) drops it.
const keepAttempt = err instanceof VoiceApiError && this.isAmbiguous(err);
return this.abortStart(session, this.mapApiError(err), keepAttempt);
}
this.remote = {
sessionId: voiceSession.session_id,
conversationId: voiceSession.conversation_id,
csrf: this.lastCsrf,
};
this.lastConversationId = voiceSession.conversation_id;
// 3) WebSocket (created outside the zone so socket events don't trigger change detection)
const transport = this.createTransport(this.api.streamUrl(streamPath));
const transport = this.createTransport(this.api.streamUrl(voiceSession.stream_path));
this.transport = transport;
try {
await this.ngZone.runOutsideAngular(() =>
@@ -181,6 +222,7 @@ export class VoiceStreamService {
onEvent: (event) => this.ngZone.run(() => this.onServerEvent(event, session)),
onAudio: (chunk) => this.onServerAudio(chunk, session),
onClose: () => this.ngZone.run(() => this.failSession(MESSAGES.disconnected, session)),
onOverflow: () => this.ngZone.run(() => this.failSession(MESSAGES.overflow, session)),
}),
);
} catch {
@@ -216,8 +258,92 @@ export class VoiceStreamService {
/** User ends the call. Safe to call at any time. */
end(): void {
if (!this.isOpen()) return;
this.finishSession();
void this.close();
}
/**
* Intentional close: final playback progress for the active audio_ref, then V04, and
* only then the socket/audio teardown — the order required by the contract.
*/
async close(options: { error?: string } = {}): Promise<void> {
if (!this.isOpen()) {
// Idle: nothing to close. A persisted creation attempt from an ambiguous reserve
// outcome is kept so the next start() reconciles it instead of duplicating it.
return;
}
const remote = this.remote;
// 1) final, worklet-computed playback progress for the ref that is still playing
await this.reportFinalProgress();
// 2) V04 before the transport closes
if (remote) {
try {
await this.api.closeVoiceSession(remote.csrf, remote.sessionId);
} catch {
/* the session may already be closed/expired (e.g. 409 LIVE_SESSION_UNUSABLE) */
}
}
// 3) release mic, worklets, AudioContext and the WebSocket
const wasConnected = this.connection() === 'connected';
const conversationId = this.remote?.conversationId ?? this.lastConversationId;
// Invalidate pending async work BEFORE resolving the session_ready waiter, so a
// start() still waiting sees a cancelled session instead of a connect failure.
this.session++;
this.rejectReady();
this.finalizeAll();
const messages = this.messages();
this.teardown();
if (wasConnected) {
this.sessionEnded$.next({ conversationId, messages, error: options.error });
}
}
/**
* After media/context loss the user starts a brand-new conversation: the old
* reservation is closed (V04) and its creation attempt is dropped, so the next
* `start()` mints fresh client request ids. An ambiguous attempt that was never
* connected is still reconciled with the same ids — never duplicated.
*/
async freshSession(title?: string): Promise<VoiceStartResult> {
await this.close();
return this.start({ title });
}
/**
* Reconcile a persisted creation attempt with the server (V02/V03) and close whatever
* reservation is still open. Media is never resumed automatically: recovery is not a
* seamless reconnect. Returns whether an attempt existed.
*/
async recover(): Promise<boolean> {
const attempt = this.attempt;
if (!attempt) return false;
try {
const me = await this.api.me();
// A call may have started while the request was in flight: never close its session.
if (this.isOpen() || this.attempt !== attempt) return true;
let sessionId = attempt.sessionId;
if (!sessionId) {
const existing = await this.api.getVoiceSessionByRequest(me.csrf_token, attempt.sessionRequestId);
sessionId = existing?.session_id ?? null;
}
if (this.isOpen() || this.attempt !== attempt) return true;
if (sessionId) {
await this.api.closeVoiceSession(me.csrf_token, sessionId).catch(() => undefined);
}
} catch {
/* the attempt is stale either way: drop it below */
}
if (!this.isOpen() && this.attempt === attempt) {
this.attempt = null;
clearPersistedAttempt();
}
return true;
}
/** V02: status + safe diagnostics of the current reservation (for the UI, no secrets). */
async poll(): Promise<unknown> {
const remote = this.remote;
if (!remote) return null;
return this.api.pollVoiceSession(remote.csrf, remote.sessionId);
}
toggleMute(): void {
@@ -236,9 +362,10 @@ export class VoiceStreamService {
this.clearError();
}
/** Component teardown: release everything without emitting events. */
/** Component teardown: release a live call without emitting events. */
dispose(): void {
this.rejectReady();
if (!this.isOpen()) return; // keep an ambiguous attempt for reconciliation
this.teardown();
}
@@ -248,11 +375,11 @@ export class VoiceStreamService {
if (this.streaming) this.transport?.sendAudio(pcm);
}
// ---- audio from the server (outside the zone) ------------------------------
// ---- audio from the server (outside the zone) -----------------------------
private onServerAudio(chunk: ArrayBuffer, session: number): void {
if (session !== this.session || !this.streaming) return;
this.engine.enqueuePlayback(chunk);
this.engine.enqueuePlayback(chunk, this.currentAudioRef);
this.clearSettleTimer();
if (this.state() !== 'SPEAKING') {
@@ -266,6 +393,52 @@ export class VoiceStreamService {
}
}
// ---- playback progress ------------------------------------------------------
private onPlaybackProgress(audioRef: string, playedMs: number): void {
if (playedMs <= 0) return;
// Keep the latest cumulative value per ref; the final report is sent from here too.
this.playedMsByRef.set(audioRef, playedMs);
this.sendPlaybackProgress(audioRef, playedMs);
this.resolveProgressWaiters();
}
/**
* The only client→server JSON control message: cumulative REAL played milliseconds
* for a server audio_ref, computed by the worklet from consumed samples.
*/
private sendPlaybackProgress(audioRef: string, playedMs: number): void {
const transport = this.transport;
if (!transport || playedMs <= 0) return;
transport.sendControl({ type: 'playback_progress', audio_ref: audioRef, played_ms: playedMs });
}
/**
* Before closing a call, ask the worklet for the final played report of the active ref
* (barge-in drops the queue, so the last 250 ms cadence may be stale).
*/
private reportFinalProgress(): Promise<void> {
const ref = this.currentAudioRef;
const transport = this.transport;
if (!ref || !transport || this.connection() !== 'connected') return Promise.resolve();
this.engine.clearPlayback(); // worklet answers with its final cumulative report
return new Promise<void>((resolve) => {
const done = (): void => {
clearTimeout(timer);
resolve();
};
const timer = setTimeout(done, FINAL_PROGRESS_WAIT_MS);
this.progressWaiters.push(done);
});
}
private resolveProgressWaiters(): void {
const waiters = this.progressWaiters;
this.progressWaiters = [];
waiters.forEach((waiter) => waiter());
}
// ---- JSON events from the server -------------------------------------------
private onServerEvent(event: VoiceServerEvent, session: number): void {
@@ -286,6 +459,10 @@ export class VoiceStreamService {
break;
}
case 'user_speech_started':
// A new server turn started; the transcript/sources of older turns stay untouched.
break;
case 'transcript':
this.onTranscript(event);
break;
@@ -294,6 +471,15 @@ export class VoiceStreamService {
this.upsertSources(event);
break;
case 'audio_started':
this.currentAudioRef = event.audio_ref;
break;
case 'audio_ended':
// Generation ended; the ref's audio may still be playing — its final progress is
// reported when the queue drains or the turn is interrupted.
break;
case 'turn_interrupted':
this.onTurnInterrupted(event.turn_ref);
break;
@@ -329,7 +515,7 @@ export class VoiceStreamService {
/** Server-side barge-in: the user spoke over the assistant. */
private onTurnInterrupted(turnRef: string): void {
this.engine.clearPlayback(); // empty the playback queue immediately
this.engine.clearPlayback(); // the worklet posts the final progress for the active ref
this.turnEnded = false;
this.clearSettleTimer();
this.markInterrupted(turnRef);
@@ -349,6 +535,17 @@ export class VoiceStreamService {
const { message, retryable, code } = event.error;
console.warn('VoiceStreamService: server error', code, event.error.request_id);
// The old conversation/session is no longer usable: the user must start a fresh one
// (Gemini interruption can also require ending the session entirely).
if (code === 'CONTEXT_REVOKED' || code === 'CONVERSATION_STALE') {
this.failSession(MESSAGES.contextRevoked, session);
return;
}
if (code === 'LIVE_SESSION_UNUSABLE' || code === 'SESSION_CLOSED') {
this.failSession(MESSAGES.sessionUnusable, session);
return;
}
if (!retryable) {
this.failSession(message || MESSAGES.server, session);
return;
@@ -426,12 +623,11 @@ export class VoiceStreamService {
}
/**
* The catalog does not say whether a `partial` carries the full text so far or only the new fragment,
* The contract does not say whether a `partial` carries the full text so far or only the new fragment,
* so both are handled:
* - `completed` with text → the final full text replaces whatever was accumulated
* - text that starts with what we already have → cumulative, replace
* - anything else → a fragment, append as-is (fragments carry their own spacing)
* If the backend turns out to use only one style, this is the single place to simplify.
*/
private mergeTranscriptText(previous: string, event: TranscriptEvent): string {
const next = event.text;
@@ -452,9 +648,14 @@ export class VoiceStreamService {
const sources = [...(current.sources ?? [])];
for (const source of event.sources) {
if (!sources.some((s) => s.source_ref === source.source_ref && s.chunk_id === source.chunk_id)) {
sources.push(source);
}
// `available: false` means the excerpt is no longer valid: keep the reference for
// the turn but hide its excerpt instead of showing revoked text.
const normalized = source.available === false ? { ...source, excerpt: undefined } : source;
const existing = sources.findIndex(
(s) => s.source_ref === normalized.source_ref && s.chunk_id === normalized.chunk_id,
);
if (existing === -1) sources.push(normalized);
else sources[existing] = normalized;
}
const next = { ...current, sources };
@@ -494,34 +695,29 @@ export class VoiceStreamService {
private failSession(message: string, session: number): void {
if (session !== this.session || !this.isOpen()) return;
this.finishSession(message);
}
private finishSession(error?: string): void {
const wasConnected = this.connection() === 'connected';
const conversationId = this.remote?.conversationId ?? this.lastConversationId;
this.rejectReady();
this.finalizeAll();
const messages = this.messages();
this.teardown();
if (wasConnected) this.sessionEnded$.next({ conversationId, messages, error });
// `close()` performs the ordered teardown (final progress → V04 → transport) and
// emits sessionEnded$ exactly once, carrying the failure message.
void this.close({ error: message });
}
private abortStart(
session: number,
failure: { reason: VoiceStartFailure; message: string },
keepAttempt = false,
): VoiceStartResult {
if (session === this.session) this.teardown();
if (session === this.session) this.teardown({ keepAttempt });
return this.failure(failure.reason, failure.message);
}
/** Releases every resource; idempotent. Invalidates all pending async work via `session`. */
private teardown(): void {
private teardown(options: { keepAttempt?: boolean } = {}): void {
this.session++;
this.streaming = false;
this.resetTurnFlags();
this.clearSettleTimer();
this.clearError();
this.resolveProgressWaiters();
this.currentAudioRef = null;
if (this.interruptTimer) {
clearTimeout(this.interruptTimer);
this.interruptTimer = null;
@@ -532,9 +728,14 @@ export class VoiceStreamService {
transport?.close();
this.engine.stop();
// V04: tell the server the session is over (best effort).
// The reservation is over: drop the attempt so the next start() mints fresh request ids —
// unless an ambiguous reserve failure still needs the same ids replayed/reconciled.
const remote = this.remote;
this.remote = null;
if (!options.keepAttempt) {
this.attempt = null;
clearPersistedAttempt();
}
if (remote) this.closeRemote(remote);
this.connection.set('disconnected');
@@ -548,6 +749,23 @@ export class VoiceStreamService {
});
}
private onPageLeave = (): void => {
if (!this.isOpen()) return;
const transport = this.transport;
const remote = this.remote;
this.session++;
this.streaming = false;
this.transport = null;
transport?.close();
this.engine.stop();
this.remote = null;
if (remote) this.closeRemote(remote);
// The attempt id/path stay in sessionStorage on purpose: the next page load reconciles
// it with V02/V03 (V04 may not complete while unloading) before anything else.
this.connection.set('disconnected');
this.state.set('IDLE');
};
private resetTurnFlags(): void {
this.turnEnded = false;
}
@@ -589,6 +807,114 @@ export class VoiceStreamService {
waiter.reject(error);
}
// ---- creation attempt / reservation -----------------------------------------
/** CSRF of the most recent `/me`; refreshed per attempt. */
private lastCsrf = '';
/**
* C01 then V01 with the attempt's stable client request ids. Ambiguous outcomes
* (timeout / network) are reconciled with the SAME ids: V03 first, then an identical
* replay — never new ids, never a blind retry of an unknown state.
*/
private async reserve(csrf: string, title: string): Promise<VoiceSessionResponse> {
const attempt = this.attempt ?? newCreationAttempt();
this.attempt = attempt;
let activeCsrf = csrf;
if (!attempt.conversationId) {
try {
const conversation = await this.api.createConversation(
activeCsrf,
title,
attempt.conversationRequestId,
);
attempt.conversationId = conversation.id;
} catch (err) {
const refreshed = await this.refreshAfterCsrfFailure(err);
activeCsrf = refreshed ?? activeCsrf;
if (!this.isAmbiguous(err) && !refreshed) throw err;
// Replay the identical request: C01 is idempotent on client_request_id.
const conversation = await this.api.createConversation(
activeCsrf,
title,
attempt.conversationRequestId,
);
attempt.conversationId = conversation.id;
}
persistAttempt(attempt);
}
if (!attempt.sessionId || !attempt.streamPath) {
let voiceSession: VoiceSessionResponse | null = null;
try {
voiceSession = await this.api.createVoiceSession(
activeCsrf,
attempt.conversationId!,
attempt.sessionRequestId,
);
} catch (err) {
const refreshed = await this.refreshAfterCsrfFailure(err);
activeCsrf = refreshed ?? activeCsrf;
if (this.isAmbiguous(err) || refreshed) {
// Did the ambiguous V01 create a reservation? Reconcile before replaying.
const existing = await this.api
.getVoiceSessionByRequest(activeCsrf, attempt.sessionRequestId)
.catch(() => null);
if (existing?.stream_path) {
voiceSession = existing;
} else {
voiceSession = await this.api.createVoiceSession(
activeCsrf,
attempt.conversationId!,
attempt.sessionRequestId,
);
}
} else if (err instanceof VoiceApiError && err.code === 'LIVE_SESSION_BUSY') {
// A session already exists for this request: reconcile instead of a second one.
const existing = await this.api
.getVoiceSessionByRequest(activeCsrf, attempt.sessionRequestId)
.catch(() => null);
if (existing?.stream_path) voiceSession = existing;
else throw err;
} else {
throw err;
}
}
attempt.sessionId = voiceSession!.session_id;
attempt.streamPath = voiceSession!.stream_path;
persistAttempt(attempt);
}
this.lastCsrf = activeCsrf;
this.lastConversationId = attempt.conversationId;
return {
session_id: attempt.sessionId!,
conversation_id: attempt.conversationId!,
status: 'connecting',
stream_path: attempt.streamPath!,
expires_at: '',
poll_url: '',
};
}
/** 403 CSRF_INVALID → read a fresh token from `/me` and allow one identical replay. */
private async refreshAfterCsrfFailure(err: unknown): Promise<string | null> {
if (!(err instanceof VoiceApiError) || err.code !== 'CSRF_INVALID') return null;
try {
const me = await this.api.me();
return me.csrf_token;
} catch {
return null;
}
}
/** Timeout / network / 5xx: the outcome is unknown, so reconcile instead of assuming. */
private isAmbiguous(err: unknown): boolean {
if (!(err instanceof VoiceApiError)) return true;
return err.status === 0 || err.status === 408 || err.status >= 500;
}
// ---- error mapping ---------------------------------------------------------
private mapEngineError(err: unknown): { reason: VoiceStartFailure; message: string } {
@@ -605,19 +931,24 @@ export class VoiceStreamService {
return { reason: 'engine', message: MESSAGES.engine };
}
/** Maps the catalog's error codes (§7) to a user-facing Persian message. */
/** Maps the contract's error codes (handoff §10) to a user-facing Persian message. */
private mapApiError(err: unknown): { reason: VoiceStartFailure; message: string } {
if (!(err instanceof VoiceApiError)) return { reason: 'api', message: MESSAGES.api };
switch (err.code) {
case 'AUTH_REQUIRED':
return { reason: 'auth', message: MESSAGES.auth };
case 'CSRF_INVALID':
return { reason: 'auth', message: MESSAGES.auth };
case 'RATE_LIMITED':
return { reason: 'api', message: MESSAGES.rateLimited };
case 'CALIBRATION_REQUIRED':
case 'DEPENDENCY_UNAVAILABLE':
return { reason: 'unavailable', message: MESSAGES.unavailable };
case 'LIVE_SESSION_UNUSABLE':
return { reason: 'api', message: MESSAGES.sessionUnusable };
case 'CONTEXT_REVOKED':
case 'CONVERSATION_STALE':
return { reason: 'api', message: MESSAGES.stale };
case 'NETWORK':
return { reason: 'connect', message: MESSAGES.connect };
default:
@@ -629,3 +960,55 @@ export class VoiceStreamService {
return { ok: false, reason, message };
}
}
// ---------------------------------------------------------------------------
// Creation-attempt persistence (ids and paths only — never cookies, CSRF or audio)
// ---------------------------------------------------------------------------
interface VoiceCreationAttempt {
conversationRequestId: string;
sessionRequestId: string;
conversationId: string | null;
sessionId: string | null;
streamPath: string | null;
}
const ATTEMPT_STORAGE_KEY = 'voice_creation_attempt';
function newCreationAttempt(): VoiceCreationAttempt {
return {
conversationRequestId: crypto.randomUUID(),
sessionRequestId: crypto.randomUUID(),
conversationId: null,
sessionId: null,
streamPath: null,
};
}
function loadPersistedAttempt(): VoiceCreationAttempt | null {
try {
const raw = sessionStorage.getItem(ATTEMPT_STORAGE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw) as VoiceCreationAttempt;
if (!parsed?.conversationRequestId || !parsed?.sessionRequestId) return null;
return parsed;
} catch {
return null;
}
}
function persistAttempt(attempt: VoiceCreationAttempt): void {
try {
sessionStorage.setItem(ATTEMPT_STORAGE_KEY, JSON.stringify(attempt));
} catch {
/* storage unavailable (private mode): the attempt lives in memory only */
}
}
function clearPersistedAttempt(): void {
try {
sessionStorage.removeItem(ATTEMPT_STORAGE_KEY);
} catch {
/* storage unavailable: nothing to clear */
}
}
@@ -12,7 +12,9 @@ export type VoiceStreamState = 'IDLE' | 'LISTENING' | 'PROCESSING' | 'SPEAKING'
export type VoiceConnection = 'disconnected' | 'connecting' | 'connected';
// ---------------------------------------------------------------------------
// Backend contract: mvp_ui_api_catalog.md (§6, "Live Voice Conversations & WSS")
// Backend contract: docs/backend-api-docs/frontend-backend-connection-handoff.md (§7–§9)
// Audio is raw mono signed PCM16 little-endian at 24000 Hz in BOTH directions
// (no WAV header). The session id, stream path and refs always come from the server.
// ---------------------------------------------------------------------------
export interface VoiceSource {
@@ -21,7 +23,8 @@ export interface VoiceSource {
chunk_id: string;
title: string;
excerpt?: string;
location?: { page?: number; section?: string };
location?: { page?: number; section?: string } | null;
/** `false` = the excerpt is no longer valid and must be hidden, not kept on screen. */
available?: boolean;
}
@@ -40,25 +43,44 @@ export type VoiceServerEvent =
input_audio: VoiceAudioFormat;
output_audio: VoiceAudioFormat;
}
| {
type: 'user_speech_started';
turn_ref: string;
}
| {
type: 'transcript';
turn_ref: string;
role: 'user' | 'assistant';
/**
* Full text so far OR a new fragment: the catalog does not say which, so
* Full text so far OR a new fragment: the contract does not say which, so
* `VoiceStreamService.mergeTranscriptText` accepts both (`completed` always carries the final text).
*/
text: string;
status: TranscriptStatus;
}
| { type: 'sources'; turn_ref: string; tool_call_id: string; sources: VoiceSource[] }
| { type: 'turn_interrupted'; turn_ref: string; cancelled_tool_call_ids: string[] }
| { type: 'sources'; turn_ref: string; tool_call_id?: string; sources: VoiceSource[] }
| { type: 'audio_started'; audio_ref: string; turn_ref?: string }
| { type: 'audio_ended'; audio_ref: string; turn_ref?: string }
| { type: 'turn_interrupted'; turn_ref: string; cancelled_tool_call_ids?: string[] }
| {
type: 'error';
turn_ref?: string;
audio_ref?: string;
error: { code: string; message: string; request_id?: string; retryable: boolean };
};
/**
* The only client→server JSON control message. `played_ms` is the cumulative real
* playback time of `audio_ref` (computed from samples actually consumed by the
* playback worklet — never an elapsed timer), and is sent again as the final
* interruption/stop report.
*/
export interface PlaybackProgressMessage {
type: 'playback_progress';
audio_ref: string;
played_ms: number;
}
export interface VoiceMessage {
/** `${turn_ref}:${role}` */
id: string;
@@ -80,26 +102,34 @@ export interface VoiceSessionEnd {
error?: string;
}
/** V02/V03 polling shape (safe diagnostics only). */
export interface VoiceSessionStatus {
session_id: string;
status: string;
close_reason?: string | null;
expires_at?: string;
}
export interface VoiceStreamConfig {
/** API prefix. */
apiBase: string;
/** Origin of the API; '' = same origin as the app (required for the `rag_session` cookie handshake). */
apiOrigin: string;
/** Fixed by the contract: 16 kHz up, 24 kHz down, mono PCM16. */
/** Fixed by the contract: 24 kHz up and 24 kHz down, mono PCM16LE. */
inputSampleRate: number;
outputSampleRate: number;
frameMs: number;
connectTimeoutMs: number;
/** After playback drains without a `completed` assistant transcript, wait this long, then return to LISTENING. */
settleMs: number;
/** Folder (relative to <base href>) holding the two *.worklet.js files. */
/** Folder (relative to <base href>) holding the two *.worklet.js files, served from the UI origin. */
workletBasePath: string;
}
export const DEFAULT_VOICE_STREAM_CONFIG: VoiceStreamConfig = {
apiBase: '/api/v1',
apiOrigin: 'http://192.168.180.151:1322',
inputSampleRate: 16000,
apiOrigin: 'http://10.0.8.51:1322',
inputSampleRate: 24000,
outputSampleRate: 24000,
frameMs: 20,
connectTimeoutMs: 8000,
@@ -1,31 +1,46 @@
import { InjectionToken, inject } from '@angular/core';
import { VOICE_STREAM_CONFIG, VoiceServerEvent } from './voice-stream.types';
import { PlaybackProgressMessage, VOICE_STREAM_CONFIG, VoiceServerEvent } from './voice-stream.types';
export interface VoiceTransportHandlers {
onEvent(event: VoiceServerEvent): void;
onAudio(chunk: ArrayBuffer): void;
/** Only called for closes the client did not ask for. */
onClose(info: { clean: boolean; code: number; reason: string }): void;
/**
* A bounded queue filled up (capture send queue or socket backpressure). The call must
* end safely with a failure — silently dropping PCM and continuing is not allowed.
*/
onOverflow(which: 'send'): void;
}
export interface VoiceTransport {
connect(handlers: VoiceTransportHandlers): Promise<void>;
/** PCM16 mono 16 kHz frame. */
/** PCM16 mono 24 kHz frame, sample-aligned, at most MAX_MESSAGE_BYTES. */
sendAudio(frame: ArrayBuffer): void;
/** The only client→server JSON message (`playback_progress`). */
sendControl(message: PlaybackProgressMessage): void;
close(): void;
}
/** Drop mic frames instead of queueing when the socket is this far behind (~0.5 MB ≈ 16 s of audio). */
const MAX_BUFFERED_BYTES = 512 * 1024;
/** Maximum size of one binary frame on the wire (contract: 9600 bytes, sample-aligned). */
export const MAX_MESSAGE_BYTES = 9600;
/** Bounded capture queue: 96000 bytes / 100 messages. Filled capacity fails the call. */
const MAX_QUEUE_BYTES = 96000;
const MAX_QUEUE_MESSAGES = 100;
/**
* Plain WebSocket. Authentication is the `rag_session` cookie sent automatically on the handshake,
* so the page must be served from the same site as the API. The contract has no client→server
* JSON messages: the client only sends binary audio frames.
* Plain WebSocket. Authentication is the `rag_session` cookie sent automatically on the
* handshake, so the page is served from the same origin as the API (same-origin `/api`
* proxy). The contract has exactly one client→server JSON message: `playback_progress`.
*/
export class WebSocketVoiceTransport implements VoiceTransport {
private ws: WebSocket | null = null;
private handlers: VoiceTransportHandlers | null = null;
private closedByClient = false;
/** Frames produced before the socket opens (or while backpressured). */
private sendQueue: ArrayBuffer[] = [];
private sendQueuedBytes = 0;
private sendQueuedMessages = 0;
constructor(
private readonly url: string,
@@ -37,6 +52,8 @@ export class WebSocketVoiceTransport implements VoiceTransport {
const ws = new WebSocket(this.url);
ws.binaryType = 'arraybuffer';
this.ws = ws;
this.handlers = handlers;
this.closedByClient = false;
let opened = false;
const timer = setTimeout(() => {
@@ -47,6 +64,7 @@ export class WebSocketVoiceTransport implements VoiceTransport {
ws.onopen = () => {
opened = true;
clearTimeout(timer);
this.flushSendQueue();
resolve();
};
@@ -75,6 +93,7 @@ export class WebSocketVoiceTransport implements VoiceTransport {
reject(new Error('connect-failed'));
return;
}
this.dropSendQueue();
if (!this.closedByClient) {
handlers.onClose({ clean: event.wasClean, code: event.code, reason: event.reason });
}
@@ -84,13 +103,41 @@ export class WebSocketVoiceTransport implements VoiceTransport {
sendAudio(frame: ArrayBuffer): void {
const ws = this.ws;
if (ws?.readyState === WebSocket.OPEN && ws.bufferedAmount < MAX_BUFFERED_BYTES) {
if (!ws || this.closedByClient) return;
// Contract guards: every binary message is sample-aligned and bounded.
if (frame.byteLength === 0 || frame.byteLength % 2 !== 0 || frame.byteLength > MAX_MESSAGE_BYTES) {
return; // never emit an out-of-contract frame; the capture worklet guarantees this shape
}
if (ws.readyState === WebSocket.OPEN) {
ws.send(frame);
return;
}
if (ws.readyState !== WebSocket.CONNECTING) return;
this.sendQueuedBytes += frame.byteLength;
this.sendQueuedMessages += 1;
if (this.sendQueuedBytes > MAX_QUEUE_BYTES || this.sendQueuedMessages > MAX_QUEUE_MESSAGES) {
// Filled capacity is a safe failure, not a silent drop.
this.dropSendQueue();
const handlers = this.handlers;
this.close();
handlers?.onOverflow('send');
}
this.sendQueue.push(frame);
}
sendControl(message: PlaybackProgressMessage): void {
const ws = this.ws;
if (ws?.readyState === WebSocket.OPEN && !this.closedByClient) {
ws.send(JSON.stringify(message));
}
}
close(): void {
this.closedByClient = true;
this.dropSendQueue();
const ws = this.ws;
this.ws = null;
if (!ws) return;
@@ -102,6 +149,25 @@ export class WebSocketVoiceTransport implements VoiceTransport {
/* already closed */
}
}
private flushSendQueue(): void {
const ws = this.ws;
const queue = this.sendQueue;
this.sendQueue = [];
this.sendQueuedBytes = 0;
this.sendQueuedMessages = 0;
if (!ws) return; // the onclose handler already runs for this socket
for (const frame of queue) {
if (ws.readyState !== WebSocket.OPEN) break;
ws.send(frame);
}
}
private dropSendQueue(): void {
this.sendQueue = [];
this.sendQueuedBytes = 0;
this.sendQueuedMessages = 0;
}
}
/** Replace in tests, or to plug a different transport. */
@@ -0,0 +1,87 @@
import {
CallActivityPoint,
CallOutcomeShare,
HourlyCallPoint,
WallboardKpis,
} from './wallboard.types';
const ACTIVITY_DAYS = 14;
const HOUR_BUCKETS: { hour: number; span: number }[] = [
{ hour: 8, span: 2 },
{ hour: 10, span: 2 },
{ hour: 12, span: 2 },
{ hour: 14, span: 2 },
{ hour: 16, span: 2 },
{ hour: 18, span: 2 },
{ hour: 20, span: 2 },
];
/** Deterministic pseudo-random source so mock data stays stable across reloads and tests. */
function seededNoise(seed: number): number {
const value = Math.sin(seed * 12.9898) * 43758.5453;
return Math.abs(value - Math.floor(value));
}
function buildActivity(): CallActivityPoint[] {
const points: CallActivityPoint[] = [];
const today = new Date();
for (let offset = ACTIVITY_DAYS - 1; offset >= 0; offset--) {
const date = new Date(today);
date.setDate(today.getDate() - offset);
const weekday = date.getDay();
const isWeekend = weekday === 4 || weekday === 5;
const noise = seededNoise(offset + 3);
// Lower weekend volume with a mild upward drift toward today.
const base = isWeekend ? 620 : 980;
const drift = (ACTIVITY_DAYS - offset) * 6;
points.push({
label: date.toLocaleDateString('fa-IR', { day: 'numeric', month: 'long' }),
count: Math.round(base + noise * 180 + drift),
});
}
return points;
}
function buildHourly(): HourlyCallPoint[] {
return HOUR_BUCKETS.map((bucket, index) => {
const noise = seededNoise(index + 11);
// Mid-day and late-afternoon peaks, quiet early morning.
const peak = bucket.hour <= 12 ? 1.35 : bucket.hour >= 18 ? 1.5 : 1.15;
return {
label: `${toPersianHour(bucket.hour)}–${toPersianHour(bucket.hour + bucket.span)}`,
count: Math.round((520 + noise * 260) * peak),
};
});
}
function toPersianHour(hour: number): string {
const persianDigits = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
return String(hour)
.padStart(2, '0')
.replace(/\d/g, (digit) => persianDigits[Number(digit)]);
}
export const MOCK_WALLBOARD_KPIS: WallboardKpis = {
totalCalls: 12846,
aiCalls: 8412,
avgAiTalkSeconds: 142,
successfulAiCalls: 7156,
transferredToAgentCalls: 1256,
periodLabel: 'امروز',
};
export const MOCK_CALL_OUTCOMES: CallOutcomeShare[] = [
{ id: 'ai', label: 'پاسخ‌گویی هوش مصنوعی', value: 7156 },
{ id: 'transfer', label: 'انتقال به کارشناس پس از هوش مصنوعی', value: 1256 },
{ id: 'direct-agent', label: 'تماس مستقیم با کارشناس', value: 4434 },
];
export const MOCK_CALL_ACTIVITY: CallActivityPoint[] = buildActivity();
export const MOCK_HOURLY_CALLS: HourlyCallPoint[] = buildHourly();
@@ -0,0 +1,77 @@
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { firstValueFrom } from 'rxjs';
import { WallboardService } from './wallboard.service';
describe('WallboardService', () => {
let service: WallboardService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
provideAnimations(),
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
],
});
service = TestBed.inject(WallboardService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('returns KPIs with a consistent AI breakdown', async () => {
const kpis = await firstValueFrom(service.getKpis());
expect(kpis.totalCalls).toBeGreaterThan(0);
expect(kpis.aiCalls).toBeGreaterThan(0);
expect(kpis.aiCalls).toBeLessThanOrEqual(kpis.totalCalls);
expect(kpis.successfulAiCalls + kpis.transferredToAgentCalls).toBe(kpis.aiCalls);
expect(kpis.avgAiTalkSeconds).toBeGreaterThan(0);
});
it('returns outcome shares summing up to the total call count', async () => {
const outcomes = await firstValueFrom(service.getOutcomes());
const kpis = await firstValueFrom(service.getKpis());
const total = outcomes.reduce((sum, outcome) => sum + outcome.value, 0);
expect(outcomes.length).toBeGreaterThan(0);
expect(total).toBe(kpis.totalCalls);
});
it('returns a 14 point activity trend with valid labels', async () => {
const activity = await firstValueFrom(service.getActivity());
expect(activity).toHaveLength(14);
activity.forEach((point) => {
expect(point.label).toBeTruthy();
expect(point.count).toBeGreaterThan(0);
});
});
it('returns hourly buckets covering the whole working day', async () => {
const hourly = await firstValueFrom(service.getHourlyDistribution());
expect(hourly.length).toBeGreaterThan(0);
hourly.forEach((bucket) => {
expect(bucket.label).toMatch(/–/);
expect(bucket.count).toBeGreaterThan(0);
});
});
it('returns a complete overview combining every wallboard dataset', async () => {
const overview = await firstValueFrom(service.getOverview());
expect(overview.kpis.totalCalls).toBeGreaterThan(0);
expect(overview.outcomes.length).toBeGreaterThan(0);
expect(overview.activity).toHaveLength(14);
expect(overview.hourly.length).toBeGreaterThan(0);
});
});
@@ -0,0 +1,77 @@
import { Injectable, inject } from '@angular/core';
import { map, Observable, of } from 'rxjs';
import { HttpService } from '../http-request/http.service';
import {
CallActivityPoint,
CallOutcomeShare,
HourlyCallPoint,
WallboardKpis,
WallboardView,
} from './wallboard.types';
import {
MOCK_CALL_ACTIVITY,
MOCK_CALL_OUTCOMES,
MOCK_HOURLY_CALLS,
MOCK_WALLBOARD_KPIS,
} from './wallboard.mock';
/**
* Call center wallboard data source. The dashboard is read-only, so every
* endpoint is a plain GET that returns a ready-to-render view. While no
* wallboard endpoints exist on the backend, deterministic mock data keeps the
* dashboard fully explorable; flip `useMockData` to false (and align the
* endpoint paths) to consume the real API without touching the page.
*/
@Injectable({
providedIn: 'root',
})
export class WallboardService {
private readonly http = inject(HttpService);
/** Flip to false once the backend wallboard endpoints are deployed. */
private readonly useMockData = true;
getKpis(): Observable<WallboardKpis> {
return this.request<WallboardKpis>('wallboard/kpis', {}, MOCK_WALLBOARD_KPIS);
}
/** سهم روش‌های پاسخ‌گویی: هوش مصنوعی در مقابل کارشناس. */
getOutcomes(): Observable<CallOutcomeShare[]> {
return this.request<CallOutcomeShare[]>('wallboard/call-outcomes', {}, MOCK_CALL_OUTCOMES);
}
getActivity(days = 14): Observable<CallActivityPoint[]> {
return this.request<CallActivityPoint[]>(
'wallboard/call-activity',
{ days },
MOCK_CALL_ACTIVITY,
);
}
getHourlyDistribution(): Observable<HourlyCallPoint[]> {
return this.request<HourlyCallPoint[]>(
'wallboard/hourly-distribution',
{},
MOCK_HOURLY_CALLS,
);
}
getOverview(): Observable<WallboardView> {
return this.request<WallboardView>('wallboard/overview', {}, {
kpis: MOCK_WALLBOARD_KPIS,
outcomes: MOCK_CALL_OUTCOMES,
activity: MOCK_CALL_ACTIVITY,
hourly: MOCK_HOURLY_CALLS,
});
}
private request<T>(endpoint: string, params: Record<string, unknown>, fallback: T): Observable<T> {
if (this.useMockData) {
return of(fallback);
}
return this.http
.get<T>(endpoint, { params, skipToast: true, skipHasErrorCheck: true })
.pipe(map((response) => response.result));
}
}
@@ -0,0 +1,41 @@
/** KPI snapshot for the wallboard («والبورد») dashboard. */
export interface WallboardKpis {
/** کل تماس‌های دریافتی */
totalCalls: number;
/** تماس‌هایی که با هوش مصنوعی گفتگو شده‌اند */
aiCalls: number;
/** میانگین زمان صحبت کاربر با هوش مصنوعی (ثانیه) */
avgAiTalkSeconds: number;
/** تماس‌هایی که هوش مصنوعی با موفقیت به پایان رسانده است */
successfulAiCalls: number;
/** تماس‌هایی که پس از هوش مصنوعی به کارشناس transfer شده‌اند */
transferredToAgentCalls: number;
/** برچسب بازه زمانی گزارش */
periodLabel: string;
}
/** سهم هر روش پاسخ‌گویی از کل تماس‌ها (نمودار دایره‌ای هوش مصنوعی/کارشناس) */
export interface CallOutcomeShare {
id: string;
label: string;
value: number;
}
/** نقطه از روند فعالیت تماس‌ها در گذر زمان (نمودار خطی) */
export interface CallActivityPoint {
label: string;
count: number;
}
/** حجم تماس‌ها در هر بازه ساعتی (نمودار میله‌ای) */
export interface HourlyCallPoint {
label: string;
count: number;
}
export interface WallboardView {
kpis: WallboardKpis;
outcomes: CallOutcomeShare[];
activity: CallActivityPoint[];
hourly: HourlyCallPoint[];
}
+529
View File
@@ -0,0 +1,529 @@
/* Shared chrome for the symbolic demonstration pages:
«ارتباط با کال سنتر»، «بازخوانی تماس‌ها از کال سنتر» and «سوالات چت سایت و اپلیکیشن».
Each page component includes this file through styleUrls, so keep every selector
page-agnostic (prefix: demo-). Visual language mirrors the reports/wallboard pages. */
.demo-page {
min-height: 100%;
padding: 2.25rem 3rem 3.5rem;
display: flex;
flex-direction: column;
gap: 1.5rem;
animation: demoFadeIn 0.4s ease-out;
}
/* ---------- header ---------- */
.demo-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
}
.demo-title-group {
display: flex;
align-items: center;
gap: 0.875rem;
}
.demo-title-icon {
display: flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
border-radius: 0.875rem;
background: var(--color-primary);
color: #ffffff;
flex-shrink: 0;
}
.demo-title {
margin: 0;
font-size: 1.5rem;
font-weight: 700;
color: var(--text-primary);
line-height: 1.3;
}
.demo-subtitle {
margin: 0.15rem 0 0;
font-size: 0.8125rem;
color: var(--text-muted);
}
.demo-chip {
display: inline-flex;
align-items: center;
gap: 0.35rem;
padding: 0.45rem 0.9rem;
border-radius: 9999px;
border: 1px solid color-mix(in srgb, var(--color-warning) 45%, transparent);
background: color-mix(in srgb, var(--color-warning) 10%, transparent);
color: var(--color-warning);
font-size: 0.75rem;
font-weight: 500;
white-space: nowrap;
}
/* ---------- cards ---------- */
.demo-card {
padding: 1.25rem 1.4rem;
border: 1px solid var(--card-border);
border-radius: 1.25rem;
background: var(--card-bg);
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.06), 0 2px 10px rgba(0, 0, 0, 0.03);
animation: demoFadeInUp 0.5s ease-out both;
}
.demo-card-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
flex-wrap: wrap;
margin-bottom: 1.1rem;
}
.demo-card-title {
margin: 0;
font-size: 1.0625rem;
font-weight: 600;
color: var(--text-primary);
}
.demo-card-description {
margin: 0.2rem 0 0;
font-size: 0.75rem;
color: var(--text-muted);
line-height: 1.7;
}
.demo-badge {
display: inline-flex;
align-items: center;
padding: 0.25rem 0.7rem;
border-radius: 9999px;
border: 1px solid color-mix(in srgb, var(--color-info) 40%, transparent);
background: color-mix(in srgb, var(--color-info) 10%, transparent);
color: var(--color-info);
font-size: 0.6875rem;
font-weight: 500;
white-space: nowrap;
}
/* ---------- notice (page intent) ---------- */
.demo-notice {
display: flex;
align-items: flex-start;
gap: 0.875rem;
border-color: color-mix(in srgb, var(--color-primary) 30%, var(--card-border));
}
.demo-notice-icon {
display: flex;
align-items: center;
justify-content: center;
width: 38px;
height: 38px;
border-radius: 0.75rem;
background: color-mix(in srgb, var(--color-primary) 12%, transparent);
color: var(--color-primary);
flex-shrink: 0;
}
.demo-notice h2 {
margin: 0 0 0.3rem;
font-size: 0.9375rem;
font-weight: 600;
color: var(--text-primary);
}
.demo-notice p {
margin: 0;
font-size: 0.8125rem;
color: var(--text-muted);
line-height: 1.8;
}
/* ---------- feature cards ---------- */
.demo-features {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 1rem;
}
.demo-feature {
display: flex;
flex-direction: column;
gap: 0.45rem;
padding: 1rem 1.1rem;
border: 1px solid var(--card-border);
border-radius: 1rem;
background: color-mix(in srgb, var(--sidebar-hover) 60%, transparent);
}
.demo-feature-icon {
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
border-radius: 0.65rem;
background: color-mix(in srgb, var(--color-primary) 12%, transparent);
color: var(--color-primary);
}
.demo-feature h3 {
margin: 0;
font-size: 0.8125rem;
font-weight: 600;
color: var(--text-primary);
}
.demo-feature p {
margin: 0;
font-size: 0.75rem;
color: var(--text-muted);
line-height: 1.7;
}
/* ---------- status pill ---------- */
.demo-status {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.3rem 0.75rem;
border-radius: 9999px;
font-size: 0.75rem;
font-weight: 500;
}
.demo-status::before {
content: '';
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
}
.demo-status--off {
background: color-mix(in srgb, var(--color-warning) 14%, transparent);
color: var(--color-warning);
}
.demo-status--on {
background: color-mix(in srgb, var(--color-success) 14%, transparent);
color: var(--color-success);
}
.demo-status-row {
display: flex;
align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
}
/* ---------- symbolic form ---------- */
.demo-form-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 1rem 1.25rem;
}
.demo-field {
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.demo-field-label {
font-size: 0.8rem;
font-weight: 500;
color: var(--text-secondary);
}
.demo-field-input {
background: var(--color-input-bg);
color: var(--text-secondary);
border: 1px solid var(--color-input-border);
border-radius: 0.5rem;
padding: 0.5rem 0.75rem;
font-size: 0.875rem;
outline: none;
width: 100%;
box-sizing: border-box;
}
.demo-field-input[readonly] {
background: var(--surface-bg);
cursor: default;
opacity: 0.85;
}
.demo-field-hint {
font-size: 0.75rem;
color: var(--text-muted);
line-height: 1.6;
}
.demo-actions {
display: flex;
align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
margin-top: 1.1rem;
}
.demo-hint {
font-size: 0.75rem;
color: var(--text-muted);
}
.demo-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.4rem;
border-radius: 0.5rem;
padding: 0.5rem 0.9rem;
font-size: 0.85rem;
font-weight: 500;
border: 1px solid transparent;
cursor: pointer;
transition: background-color 0.2s, border-color 0.2s, color 0.2s;
}
.demo-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.demo-btn--primary {
background: var(--color-primary);
color: #ffffff;
}
.demo-btn--primary:hover:not(:disabled) {
background: color-mix(in srgb, var(--color-primary) 80%, #000);
}
.demo-btn--outline {
background: transparent;
border-color: var(--color-input-border);
color: var(--text-secondary);
}
.demo-btn--outline:hover:not(:disabled) {
background: color-mix(in srgb, var(--color-primary) 22%, #ffffff);
border-color: var(--color-primary);
color: var(--color-primary);
}
/* ---------- table (example data) ---------- */
.demo-table-wrapper {
overflow-x: auto;
border: 1px solid var(--card-border);
border-radius: 1rem;
}
.demo-table {
width: 100%;
border-collapse: separate;
border-spacing: 0;
font-size: 0.8125rem;
text-align: right;
}
.demo-table thead th {
padding: 0.7rem 1rem;
background: var(--sidebar-hover);
color: var(--text-secondary);
font-size: 0.75rem;
font-weight: 500;
white-space: nowrap;
border-bottom: 1px solid var(--card-border);
}
.demo-table tbody td {
padding: 0.7rem 1rem;
color: var(--text-secondary);
border-bottom: 1px solid var(--card-border);
white-space: nowrap;
}
.demo-table tbody tr:last-child td {
border-bottom: none;
}
.demo-table tbody tr:hover td {
background: color-mix(in srgb, var(--sidebar-hover) 45%, transparent);
}
/* ---------- question list (example data) ---------- */
.demo-list {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.demo-list-item {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
padding: 0.9rem 1.1rem;
border: 1px solid var(--card-border);
border-radius: 1rem;
background: color-mix(in srgb, var(--sidebar-hover) 45%, transparent);
}
.demo-question {
margin: 0 0 0.4rem;
font-size: 0.875rem;
font-weight: 500;
color: var(--text-primary);
line-height: 1.7;
}
.demo-meta {
display: flex;
align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
font-size: 0.6875rem;
color: var(--text-muted);
}
.demo-tag {
display: inline-flex;
align-items: center;
padding: 0.15rem 0.6rem;
border-radius: 9999px;
font-size: 0.6875rem;
font-weight: 500;
}
.demo-tag--site {
background: color-mix(in srgb, var(--color-info) 12%, transparent);
color: var(--color-info);
}
.demo-tag--app {
background: color-mix(in srgb, var(--color-primary) 12%, transparent);
color: var(--color-primary);
}
.demo-tag--answered {
background: color-mix(in srgb, var(--color-success) 14%, transparent);
color: var(--color-success);
}
.demo-tag--pending {
background: color-mix(in srgb, var(--color-warning) 14%, transparent);
color: var(--color-warning);
}
.demo-tag--missed {
background: color-mix(in srgb, var(--color-danger) 14%, transparent);
color: var(--color-danger);
}
/* ---------- empty state ---------- */
.demo-empty {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.4rem;
padding: 2.5rem 1.5rem;
text-align: center;
color: var(--text-muted);
}
.demo-empty h3 {
margin: 0.4rem 0 0;
font-size: 0.9375rem;
font-weight: 600;
color: var(--text-primary);
}
.demo-empty p {
margin: 0;
font-size: 0.8125rem;
line-height: 1.8;
max-width: 42rem;
}
/* ---------- animations ---------- */
@keyframes demoFadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes demoFadeInUp {
from {
opacity: 0;
transform: translateY(16px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@media (prefers-reduced-motion: reduce) {
.demo-page,
.demo-card {
animation: none;
}
}
@media (max-width: 1400px) {
.demo-page {
padding: 1.75rem 2rem 3rem;
}
}
@media (max-width: 1024px) {
.demo-page {
padding: 1.5rem 1.75rem 2.75rem;
}
.demo-features {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.demo-form-grid {
grid-template-columns: minmax(0, 1fr);
}
}
@media (max-width: 640px) {
.demo-page {
padding: 1.25rem 1.25rem 2.25rem;
}
.demo-features {
grid-template-columns: minmax(0, 1fr);
}
}
:host-context([data-bs-theme='dark']) .demo-card {
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3), 0 2px 10px rgba(0, 0, 0, 0.2);
}
@@ -11,8 +11,8 @@
transition: min-height 0.4s cubic-bezier(0.22, 1, 0.36, 1);
}
/* Height of the voice view; the wrapper animates to it so the page never jumps. */
.ai-chat-input-wrapper.voice-active {
/* Height of the dictation view; the wrapper animates to it so the page never jumps. */
.ai-chat-input-wrapper.dictation-active {
min-height: 460px;
}
@@ -33,10 +33,20 @@
inset: 0;
opacity: 0;
transform: translateY(10px) scale(0.98);
/* Never blocks the transcript underneath; the dictation view re-enables it. */
pointer-events: none;
/* The layer is inset:0 of a collapsed wrapper while dictation is not running, so the
dictation view inside it would overflow its box and add phantom height to the page
(visible as a gap under the composer + a Y scroll). Clipping keeps it out of layout.
It stays in the DOM (display is untouched) so the viewChild refs stay valid. */
overflow: hidden;
}
.ai-chat-input-wrapper.voice-active .composer-layer {
/* Out of the flow so the voice view takes the full height while it runs. */
position: absolute;
inset-inline: 0;
bottom: 0;
opacity: 0;
transform: translateY(10px);
pointer-events: none;
@@ -45,8 +55,8 @@
.ai-chat-input-wrapper.voice-active .voice-layer {
opacity: 1;
transform: translateY(0) scale(1);
pointer-events: auto;
}
:host-context(.has-messages) {
position: fixed;
bottom: 0;
@@ -118,6 +128,7 @@
}
.composer-textarea::-webkit-scrollbar-thumb {
background: var(--muted);
border: none;
border-radius: 9999px;
}
@@ -307,6 +318,8 @@
border: 1px solid var(--surface-border);
border-radius: 1.5rem;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.03);
/* Re-enabled on the view itself; the layer stays click-through for the transcript. */
pointer-events: auto;
}
.orb-container {
@@ -509,7 +522,7 @@
max-width: 100%;
}
.ai-chat-input-wrapper.voice-active {
.ai-chat-input-wrapper.dictation-active {
min-height: 410px;
}
@@ -554,11 +567,7 @@
}
}
/* ---------- Live voice call (taller view for the running transcript) ---------- */
.ai-chat-input-wrapper.stream-active {
min-height: min(580px, 78vh);
}
/* ---------- Send icon ---------- */
.send-btn svg {
animation: sendIconIn 0.18s ease;
}
@@ -579,9 +588,3 @@
animation: none !important;
}
}
@media (max-width: 640px) {
.ai-chat-input-wrapper.stream-active {
min-height: min(540px, 80vh);
}
}
@@ -1,7 +1,7 @@
<div
class="ai-chat-input-wrapper"
[class.voice-active]="anyVoiceActive()"
[class.stream-active]="streamOpen()"
[class.dictation-active]="isVoiceMode()"
[attr.data-voice-state]="voiceState()"
(keydown.escape)="onEscape()"
>
@@ -153,9 +153,7 @@
[attr.inert]="anyVoiceActive() ? null : ''"
[attr.aria-hidden]="anyVoiceActive() ? null : 'true'"
>
@if (layerMode() === 'stream') {
<app-voice-stream-panel />
} @else {
@if (!streamOpen()) {
<div class="voice-mode" role="region" aria-label="حالت صوتی">
<div class="orb-container" #orbContainer aria-hidden="true">
@if (!orbAvailable()) {
@@ -24,7 +24,6 @@ import {
import { VoiceOrbService } from '../../../services/voice-orb/voice-orb.service';
import { VoiceStreamService } from '../../../services/voice-stream/voice-stream.service';
import { VoiceMessage } from '../../../services/voice-stream/voice-stream.types';
import { VoiceStreamPanelComponent } from '../voice-stream-panel/voice-stream-panel.component';
export type VoiceState =
| 'idle'
@@ -53,8 +52,6 @@ export const DEFAULT_ATTACHMENT_ACTIONS: readonly AttachmentAction[] = [
];
const NOTICE_TIMEOUT_MS = 7000;
/** Keeps the previous voice view mounted while the layer fades out (matches the 0.35 s CSS fade). */
const LAYER_SWAP_MS = 400;
const MIC_ERRORS: Record<string, string> = {
unsupported: 'مرورگر شما از دسترسی به میکروفون پشتیبانی نمی‌کند (اتصال امن HTTPS لازم است).',
@@ -76,7 +73,6 @@ const SPEECH_ERRORS: Record<SpeechErrorKind, string> = {
@Component({
selector: 'app-ai-chat-input',
standalone: true,
imports: [VoiceStreamPanelComponent],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './ai-chat-input.component.html',
styleUrl: './ai-chat-input.component.css',
@@ -114,8 +110,6 @@ export class AiChatInputComponent implements OnDestroy {
// Live voice call (voice-to-voice stream)
readonly streamOpen = this.voiceStream.isOpen;
/** Which view the voice layer shows; swapped after the fade so nothing flashes. */
readonly layerMode = signal<'dictation' | 'stream'>('dictation');
readonly canSend = computed(() => !!this.message().trim());
readonly anyVoiceActive = computed(() => this.isVoiceMode() || this.streamOpen());
readonly actionLabel = computed(() => (this.canSend() ? 'ارسال پیام' : 'شروع گفتگوی صوتی'));
@@ -173,7 +167,6 @@ export class AiChatInputComponent implements OnDestroy {
/** Textarea content when recording started; dictated text is appended to it. */
private baseText = '';
private noticeTimer: ReturnType<typeof setTimeout> | null = null;
private layerTimer: ReturnType<typeof setTimeout> | null = null;
constructor() {
// The outside-click listener only exists while the menu is open.
@@ -193,7 +186,6 @@ export class AiChatInputComponent implements OnDestroy {
this.voiceToggled.emit(false);
this.voiceSessionEnded.emit(messages);
if (error) this.showNotice({ kind: 'error', text: error });
this.scheduleLayerReset();
this.focusTextarea();
});
}
@@ -204,7 +196,6 @@ export class AiChatInputComponent implements OnDestroy {
this.mic.release();
this.voiceStream.dispose();
this.voiceOrb.dispose();
if (this.layerTimer) clearTimeout(this.layerTimer);
this.clearNoticeTimer();
}
@@ -351,36 +342,18 @@ export class AiChatInputComponent implements OnDestroy {
this.dismissNotice();
this.closeAttachmentMenu();
this.cancelLayerReset();
this.layerMode.set('stream');
this.voiceToggled.emit(true);
const result = await this.voiceStream.start();
if (!result.ok) {
// The call never connected, so no sessionEnded event is emitted for it.
this.voiceToggled.emit(false);
this.scheduleLayerReset();
if (result.reason !== 'cancelled') {
this.showNotice({ kind: 'error', text: result.message });
}
}
}
private scheduleLayerReset(): void {
this.cancelLayerReset();
this.layerTimer = setTimeout(() => {
this.layerTimer = null;
if (!this.streamOpen()) this.layerMode.set('dictation');
}, LAYER_SWAP_MS);
}
private cancelLayerReset(): void {
if (this.layerTimer) {
clearTimeout(this.layerTimer);
this.layerTimer = null;
}
}
// ---- voice: start ---------------------------------------------------------
async toggleVoiceMode(): Promise<void> {
@@ -403,8 +376,6 @@ export class AiChatInputComponent implements OnDestroy {
private async startVoice(): Promise<void> {
if (this.disabled() || this.streamOpen()) return;
this.cancelLayerReset();
this.layerMode.set('dictation');
this.dismissNotice();
this.closeAttachmentMenu();
@@ -0,0 +1,175 @@
.ai-model-card {
animation: fadeInUp 0.4s ease-out;
}
.ai-model-card-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
padding: 1rem 1.25rem 0.75rem;
border-bottom: 1px solid var(--surface-border);
}
.ai-model-badge {
font-size: 0.7rem;
font-weight: 600;
padding: 0.15rem 0.55rem;
border-radius: 9999px;
background: var(--color-warning)/15;
color: var(--color-warning);
}
.ai-model-badge.ai-model-badge--connected {
background: var(--color-success)/15;
color: var(--color-success);
}
.ai-model-body {
padding: 1rem 1.25rem;
}
.form-field {
display: flex;
flex-direction: column;
gap: 0.3rem;
}
.form-label {
font-size: 0.8rem;
font-weight: 500;
color: var(--text-secondary);
}
.form-required {
color: var(--color-danger);
}
.form-hint {
margin-top: 0.25rem;
font-size: 0.75rem;
}
.form-select {
appearance: none;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%2364748b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 0.75rem center;
padding-right: 2.5rem;
padding-left: 0.75rem;
background-color: var(--color-input-bg);
color: var(--text-secondary);
border: 1px solid var(--color-input-border);
border-radius: 0.5rem;
font-size: 0.875rem;
outline: none;
transition: border-color 0.2s, box-shadow 0.2s;
}
.form-select:focus {
box-shadow: 0 0 0 3px var(--color-primary)/20;
}
.form-input {
background: var(--color-input-bg);
color: var(--text-secondary);
border: 1px solid var(--color-input-border);
border-radius: 0.5rem;
padding: 0.5rem 0.75rem;
font-size: 0.875rem;
outline: none;
transition: border-color 0.2s, box-shadow 0.2s;
width: 100%;
box-sizing: border-box;
}
.form-input:focus {
border-color: var(--color-primary);
box-shadow: 0 0 0 3px var(--color-primary)/20;
}
.form-input:disabled {
background: var(--surface-bg);
cursor: default;
opacity: 0.7;
}
.form-visibility-toggle {
position: absolute;
inset-inline-start: 0.5rem;
top: 50%;
translate: 0 -50%;
display: flex;
align-items: center;
justify-content: center;
width: 1.5rem;
height: 1.5rem;
border: none;
background: transparent;
color: var(--text-muted);
cursor: pointer;
border-radius: 0.375rem;
transition: color 0.2s;
}
.form-visibility-toggle:hover {
color: var(--text-primary);
}
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.4rem;
border-radius: 0.5rem;
padding: 0.5rem 0.9rem;
font-size: 0.85rem;
font-weight: 500;
border: 1px solid transparent;
cursor: pointer;
transition: background-color 0.2s, border-color 0.2s, color 0.2s;
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn--primary {
background: var(--color-primary);
color: #fff;
}
.btn--primary:hover:not(:disabled) {
background: color-mix(in srgb, var(--color-primary) 80%, #000);
}
.btn--primary:active:not(:disabled) {
background: color-mix(in srgb, var(--color-primary) 70%, #000);
}
.btn--outline {
background: transparent;
border-color: var(--color-input-border);
color: var(--text-secondary);
}
.btn--outline:hover:not(:disabled) {
background: color-mix(in srgb, var(--color-primary) 22%, #ffffff);
border-color: var(--color-primary);
color: var(--color-primary);
}
:host-context([data-bs-theme="dark"]) .btn--outline:hover:not(:disabled) {
background: color-mix(in srgb, var(--color-primary) 30%, #171717);
}
.ai-model-actions {
direction: ltr;
}
@media (prefers-reduced-motion: reduce) {
.ai-model-card,
.ai-model-card-header {
animation-duration: 0.01ms !important;
}
}
@@ -0,0 +1,304 @@
import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
import { CommonModule } from '@angular/common';
export type AiProvider = 'openai' | 'gemini' | 'local';
export type AiTask = 'text' | 'embedding' | 'ocr' | 'stt' | 'tts' | 'dialogue';
export interface AiModelConfig {
provider: AiProvider;
model: string;
apiKey: string;
apiKeyVisible: boolean;
serviceUrl: string;
}
interface ProviderOption {
value: AiProvider;
label: string;
needsApiKey: boolean;
}
interface ModelOption {
value: string;
label: string;
}
/**
* Reusable, self-contained configuration card for one AI model class (text /
* embedding / OCR). All state lives in the parent (passed in as a signal-backed
* config object + `@Output`); this component is intentionally "dumb": it emits
* every user change so three instances stay fully independent, and it never
* pretends to persist anything — there is no documented backend for model
* configuration, so the Save / Test buttons surface a clear "not connected"
* status instead of simulating success.
*/
@Component({
selector: 'app-ai-model-config-card',
standalone: true,
imports: [CommonModule],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="ai-model-card settings-card">
<header class="ai-model-card-header">
<h3 class="text-base font-medium text-[var(--text-primary)]">{{ title() }}</h3>
<span class="ai-model-badge" [class.ai-model-badge--connected]="connected()"
>{{ connected() ? 'متصل' : 'متصل نشده' }}</span>
</header>
<div class="ai-model-body space-y-4">
<!-- Provider -->
<div class="form-field">
<label class="form-label">ارائه‌دهنده</label>
<select
class="form-select w-full"
[value]="config().provider"
(change)="onProviderChange($any($event.target).value)"
>
@for (provider of providers(); track provider.value) {
<option [value]="provider.value">{{ provider.label }}</option>
}
</select>
</div>
<!-- Model -->
<div class="form-field">
<label class="form-label">مدل</label>
<select
class="form-select w-full"
[value]="config().model"
(change)="onModelChange($any($event.target).value)"
>
@for (model of modelsForProvider(); track model.value) {
<option [value]="model.value">{{ model.label }}</option>
}
</select>
</div>
<!-- API key -->
<div class="form-field">
<label class="form-label">
کلید API
@if (apiKeyRequired()) { <span class="form-required" aria-hidden="true">*</span> }
</label>
<div class="relative">
<input
[type]="config().apiKeyVisible ? 'text' : 'password'"
class="form-input w-full pe-10"
[placeholder]="apiKeyPlaceholder()"
[value]="config().apiKey"
(input)="onApiKeyChange($any($event.target).value)"
autocomplete="off"
[attr.aria-label]="apiKeyAriaLabel()"
/>
<button
type="button"
class="form-visibility-toggle"
[attr.aria-label]="config().apiKeyVisible ? 'پنهان کن' : 'نمایش بده'"
(click)="toggleApiKeyVisibility()"
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
@if (config().apiKeyVisible) {
<path d="M1 1l22 22M10.5 10.5A2.5 2.5 0 0 0 13.5 13.5M9.9 9.9L4.15 18.5A9.92 9.92 0 0 1 1 12 11.5 11.5 0 0 1 9.9 9.9Zm10.2 10.2A11.5 11.5 0 0 0 23 12a11.5 11.5 0 0 1-3.35-7.75l2.1-2.1A11.33 11.33 0 0 1 23 12a11.5 11.5 0 0 0-3.35 7.75Z" />
<circle cx="12" cy="12" r="1" />
<line x1="1" y1="1" x2="23" y2="23" />
} @else {
<path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7-11-7-11-7z" />
<circle cx="12" cy="12" r="3" />
<line x1="12" y1="1" x2="12" y2="12.01" />
}
</svg>
</button>
</div>
<div class="form-hint">
@if (connected() && config().apiKey) {
<span class="text-[var(--text-muted)]">تنظیم شده — مقدار فعلی نمایش داده نمی‌شود</span>
} @else {
<span class="text-[var(--text-muted)]">کلید در حافظه نگهداری می‌شود و ذخیره نمی‌شود</span>
}
</div>
</div>
<!-- Service URL -->
<div class="form-field">
<label class="form-label">آدرس سرویس</label>
<input
type="url"
class="form-input w-full"
[value]="config().serviceUrl"
(input)="onServiceUrlChange($any($event.target).value)"
[disabled]="!serviceUrlEditable()"
[attr.aria-label]="'آدرس سرویس ' + title()"
/>
@if (!serviceUrlEditable()) {
<span class="text-[var(--text-muted)] mt-1 text-xs">آدرس استاندارد {{ config().provider === 'local' ? 'سرویس محلی' : 'سرویس' }} به‌صورت پیش‌فرض به کار می‌رود</span>
}
</div>
<!-- Actions -->
<div class="ai-model-actions flex gap-2 pt-2">
<button type="button" class="btn btn--primary flex-1" (click)="save.emit()">ذخیره تنظیمات</button>
<button type="button" class="btn btn--outline flex-1" (click)="testConnection.emit()">بررسی اتصال</button>
</div>
</div>
</div>
`,
styleUrl: './ai-model-config-card.component.css',
})
export class AiModelConfigCardComponent {
readonly title = input.required<string>();
readonly task = input.required<AiTask>();
readonly config = input.required<AiModelConfig>();
/** True when a provider API key has genuinely been persisted by the backend. */
readonly connected = input<boolean>(false);
readonly configChange = output<AiModelConfig>();
readonly save = output<void>();
readonly testConnection = output<void>();
readonly providers = computed(() => PROVIDERS_BY_TASK[this.task()]);
readonly modelsForProvider = computed(() => {
const models = MODELS_BY_TASK[this.task()]?.[this.config().provider];
return models ?? [{ value: '', label: 'مدلی یافت نشد' }];
});
readonly apiKeyRequired = computed(() => PROVIDERS[this.config().provider]?.needsApiKey ?? false);
readonly serviceUrlEditable = computed(() => this.config().provider === 'local');
private emitChange(patch: Partial<AiModelConfig>): void {
this.configChange.emit({ ...this.config(), ...patch });
}
onProviderChange(value: string): void {
const next = value as AiProvider;
const defaults = DEFAULT_CONFIG_FOR[next];
this.emitChange({
provider: next,
model: defaults.model,
serviceUrl: defaults.serviceUrl,
});
}
onModelChange(value: string): void {
this.emitChange({ model: value });
}
onApiKeyChange(value: string): void {
this.emitChange({ apiKey: value, apiKeyVisible: this.config().apiKeyVisible });
}
toggleApiKeyVisibility(): void {
this.emitChange({ apiKeyVisible: !this.config().apiKeyVisible });
}
onServiceUrlChange(value: string): void {
this.emitChange({ serviceUrl: value });
}
apiKeyPlaceholder(): string {
return this.apiKeyRequired() ? 'کلید API خود را وارد کنید' : 'اختیاری';
}
apiKeyAriaLabel(): string {
return this.config().apiKeyVisible ? 'کلید API (قابل رؤیت)' : 'کلید API (مخفی)';
}
}
const PROVIDERS: Record<AiProvider, ProviderOption> = {
openai: { value: 'openai', label: 'OpenAI', needsApiKey: true },
gemini: { value: 'gemini', label: 'Gemini', needsApiKey: true },
local: { value: 'local', label: 'Local', needsApiKey: false },
};
/** Provider option shown for the self-hosted «مدل‌های داخلی». */
const INTERNAL_PROVIDER: ProviderOption = {
value: 'local',
label: 'سرویس داخلی',
needsApiKey: false,
};
const PROVIDCERS_BY_TASK_FALLBACK: Record<AiTask, ProviderOption[]> = {
text: [PROVIDERS.openai, PROVIDERS.gemini, PROVIDERS.local],
embedding: [PROVIDERS.openai, PROVIDERS.gemini, PROVIDERS.local],
ocr: [PROVIDERS.openai, PROVIDERS.gemini, PROVIDERS.local],
// «مدل‌های داخلی» run on the organization's own infrastructure, so the only
// provider option is the internal service endpoint.
stt: [INTERNAL_PROVIDER],
tts: [INTERNAL_PROVIDER],
dialogue: [INTERNAL_PROVIDER],
};
const PROVIDERS_BY_TASK: Record<AiTask, ProviderOption[]> = PROVIDCERS_BY_TASK_FALLBACK;
const DEFAULT_CONFIG_FOR: Record<AiProvider, { model: string; serviceUrl: string }> = {
openai: { model: '', serviceUrl: 'https://api.openai.com/v1' },
gemini: { model: '', serviceUrl: 'https://generativelanguage.googleapis.com/v1' },
local: { model: '', serviceUrl: 'http://localhost:8000' },
};
const MODEL_OPTION = (value: string, label: string): ModelOption => ({ value, label });
const MODELS_BY_TASK: Record<
AiTask,
Partial<Record<AiProvider, ModelOption[]>>
> = {
text: {
openai: [
MODEL_OPTION('gpt-4o', 'GPT-4o'),
MODEL_OPTION('gpt-4o-mini', 'GPT-4o mini'),
MODEL_OPTION('gpt-4-turbo', 'GPT-4 Turbo'),
MODEL_OPTION('gpt-3.5-turbo', 'GPT-3.5 Turbo'),
],
gemini: [
MODEL_OPTION('gemini-2.0-flash', 'Gemini 2.0 Flash'),
MODEL_OPTION('gemini-2.5-pro', 'Gemini 2.5 Pro'),
MODEL_OPTION('gemini-1.5-flash', 'Gemini 1.5 Flash'),
MODEL_OPTION('gemini-1.5-pro', 'Gemini 1.5 Pro'),
],
local: [MODEL_OPTION('', 'سفارشی')],
},
embedding: {
openai: [
MODEL_OPTION('text-embedding-3-small', 'text-embedding-3-small'),
MODEL_OPTION('text-embedding-3-large', 'text-embedding-3-large'),
MODEL_OPTION('text-embedding-ada-002', 'text-embedding-ada-002'),
],
gemini: [MODEL_OPTION('text-embedding-004', 'text-embedding-004')],
local: [MODEL_OPTION('', 'سفارشی')],
},
ocr: {
openai: [
MODEL_OPTION('gpt-4o', 'GPT-4o (چشم‌پوشی)'),
MODEL_OPTION('gpt-4o-mini', 'GPT-4o mini (چشم‌پوشی)'),
],
gemini: [
MODEL_OPTION('gemini-1.5-pro', 'Gemini 1.5 Pro (چشم‌پوشی)'),
MODEL_OPTION('gemini-2.0-flash', 'Gemini 2.0 Flash (چشم‌پوشی)'),
],
local: [MODEL_OPTION('', 'سفارشی')],
},
// «مدل‌های داخلی» — self-hosted speech and dialogue models of the call center.
stt: {
local: [
MODEL_OPTION('whisper-large-v3', 'Whisper Large v3'),
MODEL_OPTION('parrotnet-v2', 'ParrotNet v2 (فارسی)'),
MODEL_OPTION('fastconformer-fa', 'FastConformer فارسی'),
],
},
tts: {
local: [
MODEL_OPTION('xtts-v2', 'Coqui XTTS v2'),
MODEL_OPTION('vits-fa', 'VITS فارسی'),
MODEL_OPTION('piper-fa', 'Piper فارسی'),
],
},
dialogue: {
local: [
MODEL_OPTION('llama-3.1-70b', 'Llama 3.1 70B'),
MODEL_OPTION('dorna-8b', 'Dorna 8B (پارسی)'),
MODEL_OPTION('qwen2.5-72b', 'Qwen2.5 72B'),
],
},
};
@@ -34,6 +34,31 @@ export class SidebarComponent {
label: 'چت جدید',
route: '/',
},
{
icon: 'M4 4v16h16M8 20V11M12.5 20V6M17 20V9',
label: 'گزارشات',
route: '/reports',
},
{
icon: 'M2 4h20v12H2zM8 20h8M12 16v4',
label: 'والبورد',
route: '/wallboard',
},
{
icon: 'M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71',
label: 'ارتباط با کال سنتر',
route: '/call-center',
},
{
icon: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3',
label: 'بازخوانی تماس‌ها از کال سنتر',
route: '/call-center/calls',
},
{
icon: 'M7.9 20A9 9 0 1 0 4 16.1L2 22Z',
label: 'سوالات چت سایت و اپلیکیشن',
route: '/chat-questions',
},
{
icon: 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.573-1.066zM15 12a3 3 0 11-6 0 3 3 0 016 0z',
label: 'تنظیمات',
@@ -1,27 +1,46 @@
:host {
display: block;
min-height: 0;
height: 100%;
}
.stream-panel {
direction: rtl;
--footer-h: 3.5rem;
--orb-zone: 7.25rem;
--orb-gap: 0.75rem;
--reserve: calc(var(--footer-h) + var(--orb-gap) + var(--orb-zone) + var(--orb-gap));
position: relative;
display: flex;
flex-direction: column;
box-sizing: border-box;
min-height: 0;
height: 100%;
direction: rtl;
background: transparent; /* was surface card */
border: none; /* removed card border */
border-radius: 0;
box-shadow: none; /* removed card shadow */
overflow: hidden;
}
/* ---------- Orb layer (behind the transcript) ---------- */
.stream-orb-layer {
position: absolute;
bottom: calc(var(--footer-h) + var(--orb-gap));
left: 50%;
transform: translateX(-50%);
z-index: 1;
display: flex;
flex-direction: column;
align-items: center;
gap: 0.75rem;
padding: 1rem 1.25rem 1.25rem;
background: var(--surface-bg);
border: 1px solid var(--surface-border);
border-radius: 1.5rem;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.03);
gap: 0.5rem;
transition: opacity 0.45s ease, transform 0.45s ease;
}
/* ---------- Orb ---------- */
.orb-container {
width: 170px;
height: 170px;
width: 88px;
height: 88px;
max-width: 100%;
flex-shrink: 0;
display: flex;
@@ -35,6 +54,7 @@
height: 100% !important;
}
/* Shown only when WebGL is unavailable */
.orb-fallback {
width: 70%;
height: 70%;
@@ -59,12 +79,11 @@
display: flex;
align-items: center;
gap: 0.5rem;
flex-shrink: 0;
}
.status-text {
margin: 0;
font-size: 0.9375rem;
font-size: 0.8125rem;
color: var(--text-secondary);
text-align: center;
}
@@ -109,126 +128,41 @@
}
}
/* ---------- Transcript ---------- */
/* ---------- Transcript (overlaid on top of the orb) ---------- */
.stream-transcript {
position: relative;
z-index: 2;
flex: 1;
min-height: 0;
width: 100%;
max-width: 640px;
max-width: 680px;
margin: 0 auto;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 0.5rem;
padding: 0.25rem 0.25rem;
/* Hide the scrollbar, keep wheel / trackpad / touch scrolling */
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* legacy Edge */
padding: 1rem 0.75rem var(--reserve);
scroll-behavior: smooth;
transition: padding-bottom 0.45s ease;
}
.stream-transcript::-webkit-scrollbar {
width: 4px;
}
.stream-transcript::-webkit-scrollbar-thumb {
background: var(--muted);
border-radius: 9999px;
}
.transcript-empty {
margin: auto;
font-size: 0.875rem;
color: var(--muted);
text-align: center;
}
/* RTL: user bubbles sit on the right (start), assistant bubbles on the left (end). */
.bubble-row {
display: flex;
justify-content: flex-end;
}
.bubble-row.is-user {
justify-content: flex-start;
}
.bubble {
max-width: 85%;
padding: 0.5rem 0.875rem;
border-radius: 1.125rem;
background: var(--sidebar-hover);
color: var(--text-primary);
font-size: 0.9375rem;
line-height: 1.7;
text-align: right;
white-space: pre-wrap;
overflow-wrap: anywhere;
border-end-end-radius: 0.375rem;
transition: opacity 0.2s ease;
}
.bubble.is-user {
background: var(--color-primary);
color: #ffffff;
border-end-end-radius: 1.125rem;
border-end-start-radius: 0.375rem;
}
.bubble.is-partial {
opacity: 0.7;
}
.bubble.is-interrupted .bubble-text {
opacity: 0.8;
}
.bubble-tag {
margin-inline-start: 0.375rem;
font-size: 0.75rem;
opacity: 0.7;
}
/* ---------- Sources (retrieved documents) ---------- */
.source-list {
list-style: none;
margin: 0.375rem 0 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.source-chip {
display: flex;
align-items: baseline;
gap: 0.375rem;
padding: 0.25rem 0.5rem;
border: 1px solid var(--surface-border);
border-radius: 0.625rem;
background: var(--surface-bg);
color: var(--text-secondary);
font-size: 0.75rem;
line-height: 1.5;
}
.source-chip.is-unavailable {
opacity: 0.55;
text-decoration: line-through;
}
.source-ref {
flex-shrink: 0;
padding: 0 0.375rem;
border-radius: 9999px;
background: var(--color-primary);
color: #ffffff;
font-size: 0.6875rem;
font-weight: 600;
display: none; /* Chrome, Safari, Edge */
width: 0;
height: 0;
}
/* ---------- Retryable server error ---------- */
.stream-error {
position: absolute;
bottom: calc(var(--footer-h) + 0.5rem);
left: 50%;
transform: translateX(-50%);
z-index: 3;
display: flex;
align-items: center;
gap: 0.5rem;
width: 100%;
max-width: 640px;
width: min(100% - 1.5rem, 640px);
box-sizing: border-box;
padding: 0.5rem 0.75rem;
border: 1px solid rgba(239, 68, 68, 0.45);
@@ -236,7 +170,6 @@
color: #dc2626;
font-size: 0.8125rem;
line-height: 1.6;
flex-shrink: 0;
}
.stream-error span {
@@ -263,14 +196,26 @@
outline-offset: 1px;
}
/* ---------- Actions ---------- */
/* ---------- Controls ---------- */
.stream-footer {
position: absolute;
bottom: 0;
left: 0;
right: 0;
z-index: 3;
display: flex;
align-items: center;
justify-content: center;
padding-bottom: 0.25rem;
transition: opacity 0.45s ease, transform 0.45s ease;
}
.stream-actions {
display: flex;
align-items: center;
justify-content: center;
gap: 0.625rem;
flex-wrap: wrap;
flex-shrink: 0;
}
.stream-btn {
@@ -328,6 +273,32 @@
color: #ffffff;
}
/* ---------- Ended: orb + controls fade out, transcript stays ---------- */
/* The orb + footer reserve only exists while the call is live; collapsing it stops the
bottom padding from forcing the panel (and the chat column) taller than the viewport. */
.stream-panel.is-ended {
--reserve: 0rem;
}
.stream-panel.is-ended .stream-orb-layer {
opacity: 0;
transform: translateX(-50%) translateY(14px) scale(0.9);
pointer-events: none;
}
.stream-panel.is-ended .stream-footer {
opacity: 0;
transform: translateY(10px);
pointer-events: none;
}
/* The transcript keeps the full height of the chat column: no max-height, so it never
collapses into a short nested scroll box — scrolling stays on the full-height area. */
.stream-panel.is-ended .stream-transcript {
padding: 1rem 0.75rem;
}
.sr-only {
position: absolute;
width: 1px;
@@ -344,7 +315,8 @@
.status-dot,
.orb-fallback,
.stream-btn,
.bubble,
.stream-orb-layer,
.stream-footer,
.stream-transcript {
animation: none !important;
transition: none !important;
@@ -354,18 +326,14 @@
@media (max-width: 640px) {
.stream-panel {
gap: 0.5rem;
padding: 0.75rem 0.75rem 1rem;
--footer-h: 3.25rem;
--orb-zone: 6rem;
--orb-gap: 0.5rem;
}
.orb-container {
width: 130px;
height: 130px;
}
.bubble {
max-width: 92%;
font-size: 0.875rem;
width: 68px;
height: 68px;
}
.stream-btn {
@@ -1,16 +1,36 @@
<div class="stream-panel" role="region" aria-label="گفتگوی صوتی" [attr.data-state]="state()">
<div
class="stream-panel"
role="region"
aria-label="گفتگوی صوتی"
[class.is-ended]="ended()"
[attr.data-state]="state()"
>
<div class="sr-only" role="status" aria-live="polite">{{ statusText() }}</div>
<div class="orb-container" #orbContainer aria-hidden="true">
<!-- Orb layer: behind the transcript, anchored just above the controls -->
<div class="stream-orb-layer" aria-hidden="true">
<div class="orb-container" #orbContainer>
@if (!orbAvailable()) {
<div class="orb-fallback"></div>
}
</div>
<div class="stream-status" [attr.data-state]="state()">
<span class="status-dot" aria-hidden="true"></span>
<p class="status-text">{{ statusText() }}</p>
</div>
</div>
<!-- Transcript: overlaid on top of the orb, keeps streaming while the call runs -->
<div
class="stream-transcript"
#scroller
role="log"
aria-label="متن گفتگو"
aria-live="polite"
aria-relevant="additions"
>
<app-voice-transcript [messages]="messages()" />
</div>
@if (streamError(); as errorText) {
<div class="stream-error" role="alert">
@@ -24,43 +44,8 @@
</div>
}
<div class="stream-transcript" #scroller role="log" aria-label="متن گفتگو" aria-live="polite" aria-relevant="additions">
@for (message of messages(); track message.role + message.id) {
<div class="bubble-row" [class.is-user]="message.role === 'user'">
<div
class="bubble"
[class.is-user]="message.role === 'user'"
[class.is-partial]="!message.final"
[class.is-interrupted]="message.interrupted"
dir="rtl"
>
@if (message.text) {
<span class="bubble-text">{{ message.text }}</span>
}
@if (message.interrupted) {
<span class="bubble-tag">(قطع شد)</span>
}
@if (message.sources?.length) {
<ul class="source-list" aria-label="منابع پاسخ">
@for (source of message.sources ?? []; track source.source_ref + source.chunk_id) {
<li
class="source-chip"
[class.is-unavailable]="source.available === false"
[attr.title]="source.excerpt ?? null"
>
<span class="source-ref">{{ source.source_ref }}</span>
<span class="source-label">{{ sourceLabel(source) }}</span>
</li>
}
</ul>
}
</div>
</div>
} @empty {
<p class="transcript-empty">صحبت کنید؛ گفتگو اینجا نمایش داده می‌شود</p>
}
</div>
<!-- Controls: fade out together with the orb when the call ends -->
<div class="stream-footer">
<div class="stream-actions">
<button
type="button"
@@ -99,4 +84,5 @@
<span>پایان گفتگو</span>
</button>
</div>
</div>
</div>
@@ -12,7 +12,8 @@ import {
} from '@angular/core';
import { OrbMode, VoiceOrbService } from '../../../services/voice-orb/voice-orb.service';
import { VoiceStreamService } from '../../../services/voice-stream/voice-stream.service';
import { VoiceSource, VoiceStreamState } from '../../../services/voice-stream/voice-stream.types';
import { VoiceStreamState } from '../../../services/voice-stream/voice-stream.types';
import { VoiceTranscriptComponent } from '../voice-transcript/voice-transcript.component';
const ORB_MODE: Record<VoiceStreamState, OrbMode> = {
IDLE: 'listening',
@@ -22,10 +23,11 @@ const ORB_MODE: Record<VoiceStreamState, OrbMode> = {
SPEAKING: 'speaking',
};
/** Live call view: orb, status, running two-sided transcript, mute / end controls. */
/** Live call view: orb behind an overlaid running transcript, mute / end controls. */
@Component({
selector: 'app-voice-stream-panel',
standalone: true,
imports: [VoiceTranscriptComponent],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './voice-stream-panel.component.html',
styleUrl: './voice-stream-panel.component.css',
@@ -40,9 +42,12 @@ export class VoiceStreamPanelComponent implements AfterViewInit, OnDestroy {
readonly muted = this.voice.muted;
readonly streamError = this.voice.streamError;
readonly orbAvailable = signal(true);
/** The call is over: the orb and controls fade out, the transcript stays. */
readonly ended = computed(() => this.connection() === 'disconnected');
private readonly orbContainer = viewChild.required<ElementRef<HTMLDivElement>>('orbContainer');
private readonly scroller = viewChild<ElementRef<HTMLDivElement>>('scroller');
private orbRunning = false;
readonly statusText = computed(() => {
if (this.connection() === 'connecting') return 'در حال اتصال...';
@@ -76,6 +81,15 @@ export class VoiceStreamPanelComponent implements AfterViewInit, OnDestroy {
if (el) el.scrollTop = el.scrollHeight;
});
});
// The orb animates only while a call is live; it fades out (and stops) when the call ends.
effect(() => {
if (this.ended()) {
this.orb.stopAnimation();
} else if (this.orbRunning) {
this.orb.startAnimation();
}
});
}
ngAfterViewInit(): void {
@@ -83,9 +97,10 @@ export class VoiceStreamPanelComponent implements AfterViewInit, OnDestroy {
this.orbAvailable.set(ready);
if (!ready) return;
this.orbRunning = true;
this.orb.resetOrbGeometry();
this.orb.setLevelProvider(() => this.voice.orbLevel());
this.orb.startAnimation();
if (!this.ended()) this.orb.startAnimation();
}
ngOnDestroy(): void {
@@ -94,14 +109,6 @@ export class VoiceStreamPanelComponent implements AfterViewInit, OnDestroy {
this.orb.setMode('listening');
}
/** "عنوان — صفحه ۱، بند ۲" */
sourceLabel(source: VoiceSource): string {
const parts: string[] = [];
if (source.location?.page != null) parts.push(`صفحه ${source.location.page}`);
if (source.location?.section) parts.push(source.location.section);
return parts.length ? `${source.title} — ${parts.join('، ')}` : source.title;
}
dismissError(): void {
this.voice.dismissError();
}
@@ -0,0 +1,132 @@
:host {
display: flex;
flex-direction: column;
gap: 0.5rem;
min-height: 0;
flex: 1;
}
/* RTL: user bubbles sit on the right (start), assistant text on the left (end). */
.bubble-row {
display: flex;
justify-content: flex-end;
animation: bubbleIn 0.3s ease;
}
.bubble-row.is-user {
justify-content: flex-start;
}
/* Assistant: plain text on the page background (chat-style, no bubble). */
.bubble {
max-width: 88%;
padding: 0.125rem 0;
color: var(--text-primary);
font-size: 0.9375rem;
line-height: 1.8;
text-align: right;
white-space: pre-wrap;
overflow-wrap: anywhere;
transition: opacity 0.2s ease;
}
.bubble.is-user {
max-width: 85%;
padding: 0.5rem 0.875rem;
border-radius: 1.125rem;
background: var(--color-primary);
color: #ffffff;
border-end-end-radius: 1.125rem;
border-end-start-radius: 0.375rem;
}
.bubble.is-partial {
opacity: 0.7;
}
.bubble.is-interrupted .bubble-text {
opacity: 0.8;
}
.bubble-tag {
margin-inline-start: 0.375rem;
font-size: 0.75rem;
opacity: 0.7;
}
@keyframes bubbleIn {
from {
opacity: 0;
transform: translateY(8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* ---------- Sources (retrieved documents) ---------- */
.source-list {
list-style: none;
margin: 0.375rem 0 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.source-chip {
display: flex;
align-items: baseline;
gap: 0.375rem;
padding: 0.25rem 0.5rem;
border: 1px solid var(--surface-border);
border-radius: 0.625rem;
background: var(--surface-bg);
color: var(--text-secondary);
font-size: 0.75rem;
line-height: 1.5;
}
.source-chip.is-unavailable {
opacity: 0.55;
text-decoration: line-through;
}
.source-ref {
flex-shrink: 0;
padding: 0 0.375rem;
border-radius: 9999px;
background: var(--color-primary);
color: #ffffff;
font-size: 0.6875rem;
font-weight: 600;
}
.transcript-empty {
margin: auto;
font-size: 0.875rem;
color: var(--muted);
text-align: center;
}
@media (prefers-reduced-motion: reduce) {
.bubble-row {
animation: none !important;
}
.bubble {
transition: none !important;
}
}
@media (max-width: 640px) {
.bubble {
max-width: 94%;
font-size: 0.875rem;
}
.bubble.is-user {
max-width: 92%;
}
}
@@ -0,0 +1,34 @@
@for (message of messages(); track message.role + message.id) {
<div class="bubble-row" [class.is-user]="message.role === 'user'">
<div
class="bubble"
[class.is-user]="message.role === 'user'"
[class.is-partial]="!message.final"
[class.is-interrupted]="message.interrupted"
dir="rtl"
>
@if (message.text) {
<span class="bubble-text">{{ message.text }}</span>
}
@if (message.interrupted) {
<span class="bubble-tag">(قطع شد)</span>
}
@if (message.sources?.length) {
<ul class="source-list" aria-label="منابع پاسخ">
@for (source of message.sources ?? []; track source.source_ref + source.chunk_id) {
<li
class="source-chip"
[class.is-unavailable]="source.available === false"
[attr.title]="source.excerpt ?? null"
>
<span class="source-ref">{{ source.source_ref }}</span>
<span class="source-label">{{ sourceLabel(source) }}</span>
</li>
}
</ul>
}
</div>
</div>
} @empty {
<p class="transcript-empty">صحبت کنید؛ گفتگو اینجا نمایش داده می‌شود</p>
}
@@ -0,0 +1,22 @@
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
import { VoiceMessage, VoiceSource } from '../../../services/voice-stream/voice-stream.types';
/** Read-only transcript bubbles (user / assistant), shared by the live call view and the ended-call chat box. */
@Component({
selector: 'app-voice-transcript',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './voice-transcript.component.html',
styleUrl: './voice-transcript.component.css',
})
export class VoiceTranscriptComponent {
readonly messages = input.required<VoiceMessage[]>();
/** "عنوان — صفحه ۱، بند ۲" */
sourceLabel(source: VoiceSource): string {
const parts: string[] = [];
if (source.location?.page != null) parts.push(`صفحه ${source.location.page}`);
if (source.location?.section) parts.push(source.location.section);
return parts.length ? `${source.title} — ${parts.join('، ')}` : source.title;
}
}
+21
View File
@@ -0,0 +1,21 @@
/** Shared categorical chart palette, aligned with the app theme tokens. */
export const CHART_PALETTE = [
'#3b82f6', // blue — primary
'#22c55e', // green — success
'#f59e0b', // amber — warning
'#06b6d4', // cyan — info
'#8b5cf6', // violet — ai
'#ef4444', // red — danger
'#14b8a6', // teal
'#64748b', // slate — neutral
] as const;
export const CHART_COLORS = {
primary: CHART_PALETTE[0],
success: CHART_PALETTE[1],
warning: CHART_PALETTE[2],
info: CHART_PALETTE[3],
ai: CHART_PALETTE[4],
danger: CHART_PALETTE[5],
neutral: CHART_PALETTE[7],
} as const;
+115 -2
View File
@@ -2,6 +2,7 @@
@import "@angular/cdk/overlay-prebuilt.css";
@theme {
--font-sans: "Lahze", "Vazir", sans-serif;
--color-primary: #3b82f6;
--color-secondary: #64748b;
--color-success: #22c55e;
@@ -39,6 +40,15 @@
--text-primary: var(--color-text-primary);
--text-secondary: var(--color-text-secondary);
--text-muted: var(--color-text-muted);
/* App scrollbars — light defaults, overridden in the dark theme below */
--scrollbar-thumb: #cbd5e1;
--scrollbar-thumb-hover: #94a3b8;
--scrollbar-track: #f1f5f9;
/* Short aliases for the card surface tokens (pages/charts use the short names) */
--card-bg: var(--surface-bg);
--card-border: var(--surface-border);
}
[data-bs-theme="dark"] {
@@ -69,21 +79,124 @@
--color-dropzone-bg: rgba(23, 23, 23, 0.6);
--color-dropzone-border: #3e3e3e;
/* App scrollbars — dark theme */
--scrollbar-thumb: #3f3f46;
--scrollbar-thumb-hover: #52525b;
--scrollbar-track: #171717;
/* Short aliases for the card surface tokens (pages/charts use the short names) */
--card-bg: var(--surface-bg);
--card-border: var(--surface-border);
--text-primary: var(--color-text-primary);
--text-secondary: var(--color-text-secondary);
--text-muted: var(--color-text-muted);
}
* {
font-family: "Vazir", sans-serif;
font-family: "Lahze", sans-serif;
}
/* ---------- Scrollbars: themed with the app, dark under [data-bs-theme="dark"] ----------
Applies to every scroll container (main content, sidebar, panels, textareas).
Component rules that hide or slim a specific scrollbar still win on specificity. */
* {
scrollbar-width: thin;
scrollbar-color: var(--scrollbar-thumb) var(--scrollbar-track);
}
*::-webkit-scrollbar {
width: 10px;
height: 10px;
}
*::-webkit-scrollbar-track {
background: var(--scrollbar-track);
}
*::-webkit-scrollbar-thumb {
background-color: var(--scrollbar-thumb);
border-radius: 9999px;
border: 2px solid var(--scrollbar-track);
}
*::-webkit-scrollbar-thumb:hover {
background-color: var(--scrollbar-thumb-hover);
}
*::-webkit-scrollbar-corner {
background-color: var(--scrollbar-track);
}
body {
direction: rtl;
font-family: "Vazir", sans-serif;
font-family: "Lahze", sans-serif;
text-align: right;
background: var(--app-bg);
color: var(--app-text);
margin: 0;
padding: 0;
}
@font-face {
font-family: "Lahze";
src: url("/assets/images/fonts/LAHZEH-FANUM-THIN.TTF") format("truetype");
font-weight: 100;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "Lahze";
src: url("/assets/images/fonts/LAHZEH-FANUM-EXTRALIGHT.TTF") format("truetype");
font-weight: 200;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "Lahze";
src: url("/assets/images/fonts/LAHZEH-FANUM-LIGHT.TTF") format("truetype");
font-weight: 300;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "Lahze";
src: url("/assets/images/fonts/LAHZEH-FANUM-REGULAR.TTF") format("truetype");
font-weight: 400;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "Lahze";
src: url("/assets/images/fonts/LAHZEH-FANUM-MEDIUM.TTF") format("truetype");
font-weight: 500;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "Lahze";
src: url("/assets/images/fonts/LAHZEH-FANUM-SEMIBOLD.TTF") format("truetype");
font-weight: 600;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "Lahze";
src: url("/assets/images/fonts/LAHZEH-FANUM-BOLD.TTF") format("truetype");
font-weight: 700;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "Lahze";
src: url("/assets/images/fonts/LAHZEH-FANUM-EXTRABOLD.TTF") format("truetype");
font-weight: 800;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "Lahze";
src: url("/assets/images/fonts/LAHZEH-FANUM-BLACK.TTF") format("truetype");
font-weight: 900;
font-style: normal;
font-display: swap;
}