import { ChangeDetectionStrategy, Component, OnDestroy, OnInit, computed, inject, signal, } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { ToastrService } from 'ngx-toastr'; import { ThemeService } from '../../services/theme/theme.service'; import { DocumentsService } from '../../services/documents/documents.service'; import { AuthService } from '../../services/auth/auth.service'; import { HttpService } from '../../services/http-request/http.service'; import { AiModelConfigCardComponent, AiModelConfig, AiTask, } from '../../shared/ui/ai-model-config-card/ai-model-config-card.component'; import { formatJalaliDateTime, toPersianDigits } from '../../shared/utils/format.util'; import { DocumentDetail, DocumentListItem, DocumentListParams, DocumentListResponse, DocumentStatus, ExtractionItem, ExtractionReviewResponse, KnowledgeSelection, KnowledgeSelectionResponse, RetryResult, SystemConfiguration, DOCUMENT_STATUS_LABEL, } from '../../services/documents/documents.types'; type TabId = 'faq' | 'app' | 'models'; type UploadStatus = 'uploading' | 'done' | 'error'; interface UploadTask { file: File; progress: number; status: UploadStatus; error: string | null; /** Stable Idempotency-Key: an uncertain outcome replays the SAME key for this File. */ idempotencyKey: string; } interface ReviewDecisionForm { decision: 'approve' | 'reject'; checked: string[]; note: string; excludedGroupIds: string[]; /** Stable Idempotency-Key for this human decision; kept for an uncertain replay. */ idempotencyKey: string; } const MIME_LABEL: Record = { 'application/pdf': 'PDF', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'DOCX', 'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'PPTX', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'XLSX', 'application/msword': 'DOC', 'image/jpeg': 'JPEG', 'image/png': 'PNG', 'image/gif': 'GIF', 'text/markdown': 'Markdown', 'text/plain': 'TXT', }; const OPENAI_BASE_CONFIG: AiModelConfig = { provider: 'openai', model: 'gpt-4o', apiKey: '', apiKeyVisible: false, serviceUrl: 'https://api.openai.com/v1', }; const DEFAULT_MODEL_CONFIG: Record = { text: OPENAI_BASE_CONFIG, embedding: { ...OPENAI_BASE_CONFIG, model: 'text-embedding-3-small', }, ocr: OPENAI_BASE_CONFIG, stt: OPENAI_BASE_CONFIG, tts: OPENAI_BASE_CONFIG, dialogue: OPENAI_BASE_CONFIG, }; /** «مدل‌های داخلی» — self-hosted models of the call center, one card each. */ const DEFAULT_INTERNAL_MODEL_CONFIG: Record<'stt' | 'tts' | 'dialogue', AiModelConfig> = { stt: { provider: 'local', model: 'whisper-large-v3', apiKey: '', apiKeyVisible: false, serviceUrl: 'http://localhost:8001', }, tts: { provider: 'local', model: 'xtts-v2', apiKey: '', apiKeyVisible: false, serviceUrl: 'http://localhost:8002', }, dialogue: { provider: 'local', model: 'llama-3.1-70b', apiKey: '', apiKeyVisible: false, serviceUrl: 'http://localhost:8003', }, }; const POLL_INTERVAL_MS = 2000; /** Hidden tabs poll slower (D03); the same interval is re-read on every tick. */ const HIDDEN_POLL_INTERVAL_MS = 4000; /** A human review note is mandatory for both decisions and bounded by the contract. */ const REVIEW_NOTE_MAX = 2000; /** Persian display labels for extraction-review `required_checks` identifiers (D06/D07). */ const CHECK_LABEL: Record = { readability: 'خوانایی متن', order: 'ترتیب صفحات', completeness: 'کامل بودن محتوا', numbers: 'درستی اعداد', dates: 'درستی تاریخ‌ها', negation: 'منفی‌سازی‌ها', exceptions: 'استثناها', layout: 'چینش صفحه', table: 'جدول‌ها', figure: 'شکل‌ها', }; @Component({ selector: 'app-settings', standalone: true, imports: [CommonModule, FormsModule, AiModelConfigCardComponent], changeDetection: ChangeDetectionStrategy.OnPush, templateUrl: './settings.page.html', styleUrl: './settings.page.css', }) export class SettingsPage implements OnInit, OnDestroy { private readonly themeService = inject(ThemeService); private readonly documentsService = inject(DocumentsService); private readonly auth = inject(AuthService); private readonly http = inject(HttpService); private readonly toastr = inject(ToastrService); readonly tabs: { id: TabId; label: string }[] = [ { id: 'faq', label: 'آپلود FAQ' }, { id: 'app', label: 'تنظیمات برنامه' }, { id: 'models', label: 'تنظیمات مدل‌های هوش مصنوعی' }, ]; readonly activeTab = signal('faq'); // ---- existing local file state (kept as-is) ---- readonly uploadedFiles = signal([]); readonly isDragging = signal(false); readonly uploadQueue = signal([]); readonly isUploading = signal(false); // ---- system configuration (F01) ---- readonly configuration = signal(null); readonly configLoading = signal(false); readonly configError = signal(null); readonly supportedUploadTypes = computed( () => this.configuration()?.capabilities?.supported_upload_types ?? [], ); readonly supportedUploadAccept = computed(() => { const types = this.supportedUploadTypes(); return types.length > 0 ? types.join(',') : ''; }); readonly supportedFormatsLabel = computed(() => { const types = this.supportedUploadTypes(); if (types.length === 0) { return 'در دسترس نیست'; } return types .map((t) => MIME_LABEL[t] ?? t) .filter(Boolean) .join('، '); }); readonly maxUploadBytes = computed( () => this.configuration()?.capabilities?.max_upload_bytes ?? 0, ); readonly maxPdfPages = computed( () => this.configuration()?.capabilities?.max_pdf_pages ?? 0, ); // ---- uploaded documents table (D02) ---- readonly documents = signal([]); readonly documentsLoading = signal(false); readonly documentsError = signal(null); readonly documentsNextCursor = signal(null); readonly hasMoreDocuments = computed(() => !!this.documentsNextCursor()); readonly activeFilter = signal('all'); readonly activeOnly = signal(false); /** * True when a document filter (status other than "all", or active-only) is applied. Keeps * the filter controls + table shell visible even when the filter matches zero rows, so the * user can change/reset the filter instead of the whole panel vanishing. */ readonly hasActiveFilters = computed(() => this.activeFilter() !== 'all' || this.activeOnly()); readonly hasActiveDocuments = computed(() => this.documents().some((d) => d.is_active)); readonly currentUserRole = computed<'admin' | 'user' | null>(() => { const user = this.auth.getCurrentUserValue(); return user ? (user.role as 'admin' | 'user') : null; }); readonly isAdmin = computed(() => this.currentUserRole() === 'admin'); readonly documentManagementReady = computed( () => !!this.configuration() && this.isAdmin(), ); /** True only when the F01 capabilities block was actually returned by the backend. */ readonly capabilitiesLoaded = computed(() => { const caps = this.configuration()?.capabilities; return ( !!caps && Array.isArray(caps.supported_upload_types) && typeof caps.max_upload_bytes === 'number' && typeof caps.max_pdf_pages === 'number' ); }); /** Human-readable PDF page limit, or empty when unavailable. */ readonly pdfPageLimitLabel = computed(() => { const max = this.maxPdfPages(); return max > 0 ? toPersianDigits(String(max)) : ''; }); // ---- knowledge selection (K01/K02) ---- readonly knowledgeSelection = signal(null); readonly togglingDocId = signal(null); // ---- extraction review modal (D06/D07) ---- readonly reviewingDocId = signal(null); readonly reviewDoc = signal(null); readonly reviewItems = signal([]); readonly reviewLoading = signal(false); readonly reviewNextCursor = signal(null); readonly reviewHasMore = computed(() => !!this.reviewNextCursor()); readonly reviewDecisions = signal>({}); // ---- app settings ---- readonly language = signal('fa'); readonly notificationsEnabled = signal(true); readonly isDarkMode = this.themeService.isDarkMode; readonly ocrAdminApproval = signal(false); readonly textModelConfig = signal(DEFAULT_MODEL_CONFIG.text); readonly embeddingModelConfig = signal(DEFAULT_MODEL_CONFIG.embedding); readonly ocrModelConfig = signal(DEFAULT_MODEL_CONFIG.ocr); // ---- app settings: internal (self-hosted) models ---- readonly sttModelConfig = signal(DEFAULT_INTERNAL_MODEL_CONFIG.stt); readonly ttsModelConfig = signal(DEFAULT_INTERNAL_MODEL_CONFIG.tts); readonly dialogueModelConfig = signal(DEFAULT_INTERNAL_MODEL_CONFIG.dialogue); // nothing is persisted in the MVP; all model configurations report as unconnected readonly textModelConnected = computed(() => false); readonly embeddingModelConnected = computed(() => false); readonly ocrModelConnected = computed(() => false); readonly sttModelConnected = computed(() => false); readonly ttsModelConnected = computed(() => false); readonly dialogueModelConnected = computed(() => false); private readonly pollingTimers = new Map>(); /** * Stable Idempotency-Keys for document retries (D04). A retry key lives from the click * until the retry succeeded, so an uncertain outcome replays the SAME key; the next * explicit retry of the same document mints a fresh one. */ private readonly retryKeys = new Map(); // Abort controllers for in-flight uploads, keyed by queue index. private readonly uploadControllers = new Map(); private uploadPending = 0; private uploadSuccess = 0; private uploadFailed = 0; private uploadCancelled = 0; ngOnInit(): void { this.loadConfiguration(); this.loadDocuments(); } ngOnDestroy(): void { this.stopAllPolling(); } selectTab(id: TabId): void { this.activeTab.set(id); if (id === 'faq') { this.loadDocuments(true); } } // --------------------------------------------------------------------------- // File selection (preserved behaviour) // --------------------------------------------------------------------------- onFileSelected(event: Event): void { const input = event.target as HTMLInputElement; const files = input.files ? Array.from(input.files) : []; this.uploadedFiles.set(files); input.value = ''; } onDragOver(event: DragEvent): void { event.preventDefault(); if (!this.isUploading()) { this.isDragging.set(true); } } onDragLeave(): void { this.isDragging.set(false); } onDrop(event: DragEvent): void { event.preventDefault(); this.isDragging.set(false); if (this.isUploading()) { return; } const files = event.dataTransfer?.files ? Array.from(event.dataTransfer.files) : []; this.uploadedFiles.set(files); } removeFile(index: number): void { this.uploadedFiles.update((files) => files.filter((_, i) => i !== index)); } clearAllFiles(): void { this.uploadedFiles.set([]); this.uploadQueue.set([]); } formatFileSize(bytes: number): string { if (bytes === 0) return '0 بایت'; const k = 1024; const sizes = ['بایت', 'کیلوبایت', 'مگابایت', 'گیگابایت']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; } /** تاریخ آپلود به صورت تاریخ و ساعت جلالی */ formatDateTime(iso: string): string { return formatJalaliDateTime(iso); } get fileCount(): number { return this.uploadedFiles().length; } // --------------------------------------------------------------------------- // Configuration (F01) // --------------------------------------------------------------------------- loadConfiguration(): void { this.configLoading.set(true); this.configError.set(null); this.documentsService.getConfiguration().subscribe({ next: (config) => { this.configuration.set(config); this.configLoading.set(false); }, error: (err) => { const info = DocumentsService.getErrorInfo(err); this.configError.set(DocumentsService.statusForError(info.code, info.message)); this.configLoading.set(false); this.toastr.error('خطا در دریافت تنظیمات سرور.'); }, }); } // --------------------------------------------------------------------------- // Uploads (D01) // --------------------------------------------------------------------------- async uploadFiles(): Promise { if (!this.isAdmin()) { this.toastr.warning('مدیریت اسناد فقط برای ادمین‌ها در دسترس است.'); return; } if (!this.capabilitiesLoaded()) { this.toastr.warning('تنظیمات سرور بارگذاری نشده است. لطفاً دوباره تلاش کنید.'); return; } const files = this.uploadedFiles(); if (files.length === 0 || this.isUploading()) { return; } const types = this.supportedUploadTypes(); const maxSize = this.maxUploadBytes(); const maxPages = this.maxPdfPages(); const tasks: UploadTask[] = []; const invalid: string[] = []; for (const file of files) { const typeOk = types.length === 0 || this.isFileTypeSupported(file, types); const sizeOk = maxSize === 0 || file.size <= maxSize; let pageOk = true; if (typeOk && sizeOk && this.isPdf(file) && maxPages > 0) { const pages = await this.countPdfPages(file); if (pages !== null && pages > maxPages) { pageOk = false; invalid.push(`${file.name} — بیش از ${toPersianDigits(String(maxPages))} صفحه`); } } if (!typeOk) { invalid.push(`${file.name} — نوع فایل پشتیبانی نمی‌شود`); } else if (!sizeOk) { invalid.push(`${file.name} — بیش از ${this.formatFileSize(maxSize)}`); } else if (pageOk) { tasks.push({ file, progress: 0, status: 'uploading', error: null, idempotencyKey: crypto.randomUUID(), }); } } if (invalid.length > 0) { invalid.forEach((msg) => this.toastr.warning(msg)); } if (tasks.length === 0) { return; } this.uploadControllers.clear(); this.uploadSuccess = 0; this.uploadFailed = 0; this.uploadCancelled = 0; this.uploadPending = tasks.length; this.isUploading.set(true); this.uploadQueue.set(tasks); tasks.forEach((task, index) => this.runUploadTask(task, index)); } private runUploadTask(task: UploadTask, index: number): void { const controller = new AbortController(); this.uploadControllers.set(index, controller); this.documentsService .uploadDocument( task.file, task.file.name, (percent) => { this.uploadQueue.update((q) => q.map((t, i) => (i === index ? { ...t, progress: percent } : t)), ); }, controller.signal, task.idempotencyKey, ) .subscribe({ next: () => { this.uploadQueue.update((q) => q.map((t, i) => (i === index ? { ...t, status: 'done', progress: 100, error: null } : t)), ); this.uploadSuccess++; this.finalizeUpload(); }, error: (err) => { if (controller.signal.aborted) { this.uploadQueue.update((q) => q.map((t, i) => (i === index ? { ...t, status: 'error', progress: 100, error: 'لغو شد' } : t)), ); this.uploadCancelled++; this.finalizeUpload(); return; } const info = DocumentsService.getErrorInfo(err); const message = DocumentsService.statusForError(info.code, info.message); this.uploadQueue.update((q) => q.map((t, i) => (i === index ? { ...t, status: 'error', error: message } : t)), ); this.uploadFailed++; this.toastr.error(`آپلود ${task.file.name} ناموفق بود: ${message}`); this.finalizeUpload(); }, }); } private finalizeUpload(): void { this.uploadPending--; if (this.uploadPending <= 0) { this.isUploading.set(false); this.uploadControllers.clear(); const failedTasks = this.uploadQueue().filter((t) => t.status === 'error'); if (this.uploadFailed === 0 && this.uploadCancelled === 0) { this.uploadedFiles.set([]); this.uploadQueue.set([]); this.toastr.success('آپلود فایل‌ها با موفقیت پذیرفته شد.'); } else if (this.uploadFailed > 0) { // Preserve failed files in the selection so the admin can retry them, // and keep their tasks visible (with an error state + retry action). this.uploadedFiles.set(failedTasks.map((t) => t.file)); this.toastr.error( `${this.uploadFailed} فایل آپلود ناموفق مانده‌اند؛ برای retry آن‌ها در لیست زیر اقدام کنید.`, ); } else { this.uploadedFiles.set(failedTasks.map((t) => t.file)); this.toastr.info('آپلود برخی فایل‌ها توسط کاربر لغو شد.'); } this.uploadSuccess = 0; this.uploadFailed = 0; this.uploadCancelled = 0; this.refreshDocuments(); } } /** Retry a single failed/cancelled upload task, preserving its File. */ retryUpload(index: number): void { const task = this.uploadQueue()[index]; if (!task || task.status !== 'error' || this.isUploading()) { return; } this.uploadControllers.clear(); this.uploadSuccess = 0; this.uploadFailed = 0; this.uploadCancelled = 0; this.uploadPending = 1; this.isUploading.set(true); this.uploadQueue.update((q) => q.map((t, i) => (i === index ? { ...t, status: 'uploading', progress: 0, error: null } : t)), ); this.runUploadTask(this.uploadQueue()[index], index); } cancelUpload(index: number): void { const controller = this.uploadControllers.get(index); if (controller) { controller.abort(); } else { this.uploadQueue.update((q) => q.map((t, i) => (i === index ? { ...t, status: 'error', progress: 100, error: 'لغو شد' } : t)), ); } } private isPdf(file: File): boolean { return file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf'); } private async countPdfPages(file: File): Promise { try { const text = await file.text(); // Best-effort page count: each page is a `/Type/Page` object (not `/Pages`). const matches = text.match(/\/Type\s*\/Page(?!s)/gi); return matches ? matches.length : null; } catch { return null; } } private isFileTypeSupported(file: File, types: string[]): boolean { if (types.includes(file.type)) { return true; } const ext = file.name.split('.').pop()?.toLowerCase() ?? ''; return types.some((mime) => { const label = MIME_LABEL[mime]?.toLowerCase() ?? ''; return ext === this.extensionForMime(mime); }); } private extensionForMime(mime: string): string { switch (mime) { case 'application/pdf': return 'pdf'; case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': return 'docx'; case 'image/jpeg': return 'jpg'; case 'image/png': return 'png'; case 'text/markdown': return 'md'; case 'text/plain': return 'txt'; default: return ''; } } statusLabel(status: DocumentStatus): string { return DOCUMENT_STATUS_LABEL[status] ?? status; } // --------------------------------------------------------------------------- // Documents list (D02) + polling (D03) // --------------------------------------------------------------------------- loadDocuments(reset = false): void { if (!this.isAdmin()) { this.documents.set([]); this.documentsNextCursor.set(null); this.documentsLoading.set(false); this.documentsError.set('دسترسی مدیریت اسناد فقط برای ادمین‌ها است.'); return; } if (reset) { this.documentsNextCursor.set(null); } this.documentsLoading.set(true); this.documentsError.set(null); const params: DocumentListParams = { limit: 20 }; const cursor = this.documentsNextCursor(); if (cursor) { params.cursor = cursor; } const filter = this.activeFilter(); if (filter !== 'all') { params.status = filter; } if (this.activeOnly()) { params.is_active = true; } this.documentsService.getDocuments(params).subscribe({ next: (res: DocumentListResponse) => { if (reset) { this.documents.set(res.items); } else { this.documents.update((prev) => [...prev, ...res.items]); } this.documentsNextCursor.set(res.next_cursor); this.documentsLoading.set(false); this.schedulePolling(res.items); }, error: (err) => { const info = DocumentsService.getErrorInfo(err); this.documentsError.set(DocumentsService.statusForError(info.code, info.message)); this.documentsLoading.set(false); if (info.code === 'AUTH_REQUIRED') { this.toastr.error('لطفاً ابتدا وارد سیستم شوید.'); } else { this.toastr.error(DocumentsService.statusForError(info.code, info.message)); } }, }); } refreshDocuments(): void { this.stopAllPolling(); this.loadDocuments(true); } applyDocumentFilters(): void { this.stopAllPolling(); this.loadDocuments(true); } loadMoreDocuments(): void { if (this.hasMoreDocuments() && !this.documentsLoading()) { this.loadDocuments(false); } } private schedulePolling(items: DocumentListItem[]): void { // NOTE: do NOT stop existing timers here. Pagination loads additional pages // that are concatenated to the existing list, so documents loaded on earlier // pages must keep being polled (see D03). `startPolling` is idempotent per // document id, and `applyPolledDetail` clears timers for terminal states. for (const item of items) { if (DocumentsService.isPolling(item.status)) { this.startPolling(item.id); } } } private startPolling(documentId: string): void { if (this.pollingTimers.has(documentId)) { return; } const tick = () => { this.documentsService.getDocument(documentId).subscribe({ next: (detail: DocumentDetail) => { this.applyPolledDetail(detail); if (DocumentsService.isPolling(detail.status)) { const interval = typeof document !== 'undefined' && document.hidden ? HIDDEN_POLL_INTERVAL_MS : POLL_INTERVAL_MS; this.pollingTimers.set(documentId, setTimeout(tick, interval)); } }, error: () => { // Stop polling a failing document but keep it in the list. this.pollingTimers.delete(documentId); }, }); }; this.pollingTimers.set(documentId, setTimeout(tick, POLL_INTERVAL_MS)); } private applyPolledDetail(detail: DocumentDetail): void { this.documents.update((list) => list.map((item) => (item.id === detail.id ? this.mergeDetail(item, detail) : item)), ); if (detail.status === 'ready' || detail.status === 'failed') { this.pollingTimers.delete(detail.id); if (detail.status === 'failed' && detail.review_required) { this.toastr.warning(`سند «${detail.title ?? detail.filename}» نیازمند بازبینی ادمین است.`); } } } private mergeDetail(item: DocumentListItem, detail: DocumentDetail): DocumentListItem { return { ...item, ...detail } as DocumentListItem; } private stopAllPolling(): void { for (const timer of this.pollingTimers.values()) { clearTimeout(timer); } this.pollingTimers.clear(); } // --------------------------------------------------------------------------- // Knowledge selection / activation (K01/K02) // --------------------------------------------------------------------------- ensureKnowledgeSelection(): Promise { const current = this.knowledgeSelection(); if (current) { return Promise.resolve(current); } return new Promise((resolve) => { this.documentsService.getKnowledgeSelection().subscribe({ next: (sel) => { this.knowledgeSelection.set(sel); resolve(sel); }, error: () => resolve(null), }); }); } async toggleDocumentActive(doc: DocumentListItem): Promise { if (!this.isAdmin()) { this.toastr.warning('مدیریت اسناد فقط برای ادمین‌ها در دسترس است.'); return; } if (this.togglingDocId() === doc.id) { return; } if (doc.status !== 'ready') { this.toastr.info('فقط اسناد آماده قابل فعال‌سازی یا غیرفعال‌سازی هستند.'); return; } if (doc.review_required) { this.toastr.warning('سند دارای بازبینی معلق است و قابل فعال‌سازی نیست.'); return; } this.togglingDocId.set(doc.id); try { const selection = await this.ensureKnowledgeSelection(); if (!selection) { this.toastr.error('خطا در دریافت لیست انتخاب دانش.'); return; } const currentlyActive = selection.document_ids.includes(doc.id); const nextIds = currentlyActive ? selection.document_ids.filter((id) => id !== doc.id) : [doc.id, ...selection.document_ids]; this.documentsService .updateKnowledgeSelection({ expected_revision: selection.revision, document_ids: nextIds, }) .subscribe({ next: (res: KnowledgeSelectionResponse) => { this.knowledgeSelection.set(res); this.documents.update((list) => list.map((d) => d.id === doc.id ? { ...d, is_active: res.document_ids.includes(d.id), searchable: res.document_ids.includes(d.id) && d.status === 'ready', } : d, ), ); this.togglingDocId.set(null); if (res.conversations_invalidated) { // Active voice sessions were closed by the server: old excerpts are revoked. this.toastr.warning( 'با حذف سند از دانش فعال، نشست‌های صوتی در حال اجرا باطل شدند؛ گفتگوی جدیدی شروع کنید.', ); } this.toastr.success( `سند «${doc.title ?? doc.filename}» ${currentlyActive ? 'غیرفعال' : 'فعال'} شد.`, ); }, error: (err) => { const info = DocumentsService.getErrorInfo(err); this.togglingDocId.set(null); if (info.code === 'REVISION_CONFLICT') { this.knowledgeSelection.set(null); this.toastr.warning('لیست دانش به‌روز شد. لطفاً دوباره تلاش کنید.'); this.refreshDocuments(); } else if (info.code === 'DOCUMENT_NOT_READY') { this.toastr.error('فقط اسناد وضعیت آماده قابل فعال‌سازی هستند.'); } else { this.toastr.error( `فعال‌سازی ناموفق: ${DocumentsService.statusForError(info.code, info.message)}`, ); } }, }); } catch { this.togglingDocId.set(null); this.toastr.error('خطا در فعال‌سازی سند.'); } } isDocumentActive(doc: DocumentListItem): boolean { const selection = this.knowledgeSelection(); if (selection) { return selection.document_ids.includes(doc.id); } return doc.is_active; } // --------------------------------------------------------------------------- // Extraction review (D06/D07) + retry (D04) // --------------------------------------------------------------------------- openReview(doc: DocumentListItem): void { if (!this.isAdmin()) { this.toastr.warning('بازبینی اسناد فقط برای ادمین‌ها در دسترس است.'); return; } this.reviewingDocId.set(doc.id); this.reviewDoc.set(doc); this.reviewItems.set([]); this.reviewNextCursor.set(null); this.reviewDecisions.set({}); this.loadAllReviewItems(); } closeReview(): void { this.reviewingDocId.set(null); this.reviewDoc.set(null); this.reviewItems.set([]); this.reviewDecisions.set({}); this.reviewNextCursor.set(null); } onReviewModalClick(event: MouseEvent): void { event.stopPropagation(); } /** Load every review page (following `next_cursor`) for the current document. */ loadAllReviewItems(): void { const docId = this.reviewingDocId(); if (!docId) { return; } this.reviewLoading.set(true); this.reviewItems.set([]); this.reviewNextCursor.set(null); this.reviewDecisions.set({}); const collect = (cursor: string | null, restarted = false): void => { this.documentsService.getExtractionReview(docId, cursor ?? undefined).subscribe({ next: (res: ExtractionReviewResponse) => { this.reviewItems.update((items) => [...items, ...res.items]); if (res.next_cursor) { collect(res.next_cursor); } else { this.reviewLoading.set(false); this.initReviewDecisions(this.reviewItems()); } }, error: (err) => { // An invalidated cursor (the evidence set changed under us) means the pendings // must be re-read from the beginning — never continue from a stale page. const info = DocumentsService.getErrorInfo(err); if (!restarted && (info.code === 'VALIDATION_ERROR' || info.code === 'NOT_FOUND')) { collect(null, true); return; } this.reviewLoading.set(false); this.toastr.error('خطا در دریافت شواهد بازبینی.'); }, }); }; collect(null); } private initReviewDecisions(items: ExtractionItem[]): void { const forms = this.reviewDecisions(); for (const item of items) { if (!forms[item.evidence_sha256]) { // Do NOT pre-check required_checks; the admin must explicitly review and // check each item. Only restore a decision the backend has already // recorded (legitimate persisted review state). forms[item.evidence_sha256] = { decision: item.decision ?? 'approve', checked: [], note: '', excludedGroupIds: [], idempotencyKey: crypto.randomUUID(), }; } } this.reviewDecisions.set({ ...forms }); } isCheckComplete(item: ExtractionItem): boolean { const form = this.reviewDecisions()[item.evidence_sha256]; return ( form?.checked.length === item.required_checks.length && item.required_checks.every((c) => form?.checked.includes(c)) ); } /** * A human note is mandatory for BOTH approve and reject (non-blank, bounded length), * and approve additionally needs every required check confirmed by the human. */ isReviewNoteValid(item: ExtractionItem): boolean { const form = this.reviewForm(item.evidence_sha256); const note = form.note.trim(); return note.length > 0 && note.length <= REVIEW_NOTE_MAX; } /** True when this item's decision can be submitted (approve: all checks + note). */ isReviewSubmittable(item: ExtractionItem): boolean { const form = this.reviewForm(item.evidence_sha256); if (!this.isReviewNoteValid(item)) return false; if (form.decision === 'approve') return this.isReviewCheckComplete(item); return true; } submitReviewDecision(item: ExtractionItem): void { const form = this.reviewForm(item.evidence_sha256); if (!this.isReviewSubmittable(item)) { if (form.decision === 'approve' && !this.isReviewCheckComplete(item)) { this.toastr.warning('برای تایید، تمام بررسی‌های الزامی باید انتخاب شود.'); } else { this.toastr.warning('یادداشت بازبینی (غیرخالی، حداکثر ۲۰۰۰ کاراکتر) الزامی است.'); } return; } // `excluded_group_ids` is only meaningful for factual_corpus evidence; extraction // review must send an empty list. const excludedGroupIds = item.review_kind === 'extraction' ? [] : form.excludedGroupIds; this.documentsService .submitReviewDecision( this.reviewingDocId()!, { evidence_sha256: item.evidence_sha256, decision: form.decision, checked: form.checked, note: form.note.trim(), excluded_group_ids: excludedGroupIds, }, form.idempotencyKey, ) .subscribe({ next: () => { this.toastr.success('تصمیم بازبینی ثبت شد.'); this.loadAllReviewItems(); }, error: (err) => { const info = DocumentsService.getErrorInfo(err); if (info.code === 'REVIEW_STALE' || info.code === 'REVIEW_ALREADY_DECIDED') { // The evidence set changed: re-read from the start, never copy an old approval. this.loadAllReviewItems(); } this.toastr.error(DocumentsService.statusForError(info.code, info.message)); }, }); } finishReviewAndRetry(): void { if (!this.isAdmin()) { this.toastr.warning('مدیریت اسناد فقط برای ادمین‌ها در دسترس است.'); return; } const doc = this.reviewDoc(); if (!doc) { return; } if (!doc.job?.can_retry) { this.toastr.warning('سند در حال حاضر قابل تلاش مجدد نیست.'); return; } if (!this.allReviewsDecided()) { this.toastr.warning('هنوز شواهد بازبینی تکمیل نشده‌اند.'); return; } const key = this.retryKeys.get(doc.id) ?? crypto.randomUUID(); this.retryKeys.set(doc.id, key); this.documentsService.retryDocument(doc.id, key).subscribe({ next: () => { this.retryKeys.delete(doc.id); this.toastr.success('سعی مجدد در صف پردازش قرار گرفت.'); this.closeReview(); this.refreshDocuments(); }, error: (err) => { const info = DocumentsService.getErrorInfo(err); if (info.code === 'EXTRACTION_REVIEW_PENDING') { this.toastr.warning('شواهد بازبینی هنوز تکمیل نشده‌اند؛ ابتدا همه موارد را بررسی کنید.'); } else { this.toastr.error(DocumentsService.statusForError(info.code, info.message)); } }, }); } private reviewForm(sha: string): ReviewDecisionForm { const forms = this.reviewDecisions(); return ( forms[sha] ?? { decision: 'approve' as const, checked: [], note: '', excludedGroupIds: [], idempotencyKey: crypto.randomUUID(), } ); } private setReviewForm(sha: string, form: ReviewDecisionForm): void { this.reviewDecisions.update((forms) => ({ ...forms, [sha]: form })); } isCheckChecked(item: ExtractionItem, check: string): boolean { return this.reviewForm(item.evidence_sha256).checked.includes(check); } toggleCheck(item: ExtractionItem, check: string, checked: boolean): void { const form = this.reviewForm(item.evidence_sha256); const checkedList = checked ? Array.from(new Set([...form.checked, check])) : form.checked.filter((c) => c !== check); this.setReviewForm(item.evidence_sha256, { ...form, checked: checkedList }); } decisionFor(item: ExtractionItem): 'approve' | 'reject' { return this.reviewForm(item.evidence_sha256).decision; } setDecision(item: ExtractionItem, decision: 'approve' | 'reject'): void { const form = this.reviewForm(item.evidence_sha256); this.setReviewForm(item.evidence_sha256, { ...form, decision }); } noteFor(item: ExtractionItem): string { return this.reviewForm(item.evidence_sha256).note; } setNote(item: ExtractionItem, value: string): void { const form = this.reviewForm(item.evidence_sha256); this.setReviewForm(item.evidence_sha256, { ...form, note: value }); } excludedGroupIdsFor(item: ExtractionItem): string { return this.reviewForm(item.evidence_sha256).excludedGroupIds.join(', '); } setExcludedGroupIds(item: ExtractionItem, value: string): void { const form = this.reviewForm(item.evidence_sha256); const ids = value .split(',') .map((s) => s.trim()) .filter(Boolean); this.setReviewForm(item.evidence_sha256, { ...form, excludedGroupIds: ids }); } isReviewCheckComplete(item: ExtractionItem): boolean { const form = this.reviewForm(item.evidence_sha256); return ( form.checked.length === item.required_checks.length && item.required_checks.every((c) => form.checked.includes(c)) ); } /** Persian label for a backend `required_checks` identifier (D06/D07). */ checkLabel(check: string): string { return CHECK_LABEL[check] ?? check; } /** True when every review item has a valid decision (approve: checks + note; reject: note). */ allReviewsDecided(): boolean { const items = this.reviewItems(); if (items.length === 0) { return false; } const forms = this.reviewDecisions(); return items.every((item) => { const form = forms[item.evidence_sha256]; if (!form || form.decision === null) { return false; } if (!this.isReviewNoteValid(item)) { return false; } if (form.decision === 'approve') { return item.required_checks.every((c) => form.checked.includes(c)); } return true; }); } /** Whether the in-review document is ready to be retried (review resolved + backend retryable). */ canRetryAfterReview(): boolean { const doc = this.reviewDoc(); return ( !!doc && !!doc.job?.can_retry && this.allReviewsDecided() && !this.reviewLoading() ); } canRetryDocument(doc: DocumentListItem): boolean { if (!doc) { return false; } if (!this.isAdmin()) { return false; } const error = doc.job?.error; return (!!doc.job?.can_retry && error?.code !== 'EXTRACTION_REVIEW_REQUIRED') ?? false; } retryDocument(doc: DocumentListItem): void { if (!this.isAdmin()) { this.toastr.warning('مدیریت اسناد فقط برای ادمین‌ها در دسترس است.'); return; } if (!doc.job?.can_retry) { this.toastr.warning('سند در حال حاضر قابل تلاش مجدد نیست.'); return; } const key = this.retryKeys.get(doc.id) ?? crypto.randomUUID(); this.retryKeys.set(doc.id, key); this.documentsService.retryDocument(doc.id, key).subscribe({ next: (res: RetryResult) => { this.retryKeys.delete(doc.id); this.toastr.success('سعی مجدد در صف پردازش قرار گرفت.'); this.refreshDocuments(); }, error: (err) => { const info = DocumentsService.getErrorInfo(err); if (info.code === 'EXTRACTION_REVIEW_PENDING') { // Backend confirms review requirements are unresolved: do NOT show // success, surface the pending condition instead. this.toastr.warning('ابتدا شواهد بازبینی را تکمیل و تأیید کنید.'); } else { this.toastr.error(DocumentsService.statusForError(info.code, info.message)); } }, }); } /** Server-provided preview URL (authenticated via the session cookie); null = no preview. */ previewImageUrl(item: ExtractionItem): string | null { const path = item.preview_path; if (!path) return null; if (path.startsWith('http://') || path.startsWith('https://')) { return path; } return `${this.http.apiUrl}${path.startsWith('/') ? '' : '/'}${path}`; } /** Persian label for the evidence kind (extraction vs factual_corpus). */ reviewKindLabel(item: ExtractionItem): string { return item.review_kind === 'factual_corpus' ? 'پرسش و پاسخ' : 'استخراج تصویر'; } isReviewNeeded(doc: DocumentListItem): boolean { return doc.review_required === true || doc.job.error?.code === 'EXTRACTION_REVIEW_REQUIRED'; } // --------------------------------------------------------------------------- // App settings: model configuration cards (prototype — no backend) // --------------------------------------------------------------------------- saveModelConfig(task: AiTask): void { const label = MODEL_CARD_LABEL[task]; this.toastr.info( `ذخیره تنظیمات ${label} در فاز MVP پشتیبانی نمی‌شود. تنظیمات در حافظه نگهداری می‌شوند.`, ); } testModelConnection(task: AiTask): void { const label = MODEL_CARD_LABEL[task]; this.toastr.info(`بررسی اتصال ${label}: هیچ API پیکربندی مدلی یافت نشد.`); } toggleOcrApproval(): void { this.ocrAdminApproval.set(!this.ocrAdminApproval()); this.toastr.info('ذخیره‌سازی سیاست بازبینی OCR در فاز MVP پشتیبانی نمی‌شود.'); } toggleDarkMode(): void { this.themeService.toggleDarkMode(); } } const MODEL_CARD_LABEL: Record = { text: 'هوش مصنوعی', embedding: 'امبدینگ', ocr: 'OCR', stt: 'تبدیل گفتار به نوشتار', tts: 'تبدیل نوشتار به گفتار', dialogue: 'مدل گفتگوی داخلی', };