import { getAuthHeaders } from '../utils/auth'; export interface KbGroup { id: number; name: string; description?: string | null; department_id?: number | null; document_count?: number; created_at?: string | null; updated_at?: string | null; } export interface KbDocumentItem { id: number; group_id?: number; title: string; description?: string | null; status?: string; source_type?: string | null; created_at?: string | null; updated_at?: string; version_count?: number; latest_version?: KbDocumentVersionItem | null; } export interface KbDocumentVersionItem { id: number; document_id: number; version_no: number; status: string; is_current: boolean; source_file_name: string; source_file_ext?: string | null; source_file_size?: number | null; sha256?: string | null; cleaned_file_path?: string | null; cleaned_preview_path?: string | null; error_message?: string | null; created_at?: string | null; } export interface KbSyncRecordItem { id: number; group_id?: number | null; document_id?: number | null; document_version_id: number; dataset_id: string; dataset_name?: string | null; remote_document_id: string; remote_document_name?: string | null; status: string; sync_hash?: string | null; error_message?: string | null; synced_at?: string | null; updated_at?: string | null; } export interface KbDocumentMarkdown { document_id: number; title: string; version: KbDocumentVersionItem | null; content: string; kind: 'markdown' | 'preview'; } export interface KbJob { id: number | string; job_type: string; status: string; group_id?: number | null; document_id?: number | null; document_version_id?: number | null; progress?: number; message?: string | null; error_message?: string | null; payload_json?: Record | null; result_json?: Record | null; created_at?: string; started_at?: string | null; finished_at?: string | null; } export interface KbDifySettings { DIFY_API_BASE: string; DIFY_API_KEY: string; KB_DIFY_PERMISSION: string; KB_DIFY_INDEXING_TECHNIQUE: string; KB_DIFY_SEARCH_METHOD: string; KB_DIFY_DOC_FORM: string; dify_api_configured?: boolean; } export interface KbDifyHealth { dify_base_url: string; dify_api_configured: boolean; api: { configured: boolean; reachable: boolean; dataset_count?: number | null; error?: string | null; }; local_sync_health: { dataset_bound_groups: number; sync_records: number; syncing_versions: number; synced_versions: number; failed_sync_records: number; pending_sync_jobs: number; }; } export interface KbListResponse { ok: boolean; data: T; error?: string; status?: number; } const getJson = async (path: string, fallback: T): Promise => { try { const res = await fetch(path, { headers: getAuthHeaders() }); if (!res.ok) return fallback; return (await res.json()) as T; } catch { return fallback; } }; const getJsonWithStatus = async (path: string, fallback: T): Promise> => { try { const res = await fetch(path, { headers: getAuthHeaders() }); if (!res.ok) { const data = await res.json().catch(() => ({})); return { ok: false, data: fallback, error: data?.error || '知识库接口请求失败', status: res.status, }; } return { ok: true, data: (await res.json()) as T, status: res.status }; } catch { return { ok: false, data: fallback, error: '知识库接口暂未就绪,请稍后再试' }; } }; export const getKbGroups = async (): Promise => { return getJson('/api/kb/groups', []); }; export const getKbGroupFiles = async (groupId: number): Promise => { return getJson(`/api/kb/groups/${groupId}/files`, []); }; export const getKbGroupsSafe = async (): Promise> => { return getJsonWithStatus('/api/kb/groups', []); }; export const getKbGroupFilesSafe = async (groupId: number): Promise> => { return getJsonWithStatus(`/api/kb/groups/${groupId}/files`, []); }; export const createKbGroup = async (payload: { name: string; description?: string; }): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => { try { const res = await fetch('/api/kb/groups', { method: 'POST', headers: { 'Content-Type': 'application/json', ...getAuthHeaders(), }, body: JSON.stringify(payload), }); if (!res.ok) { const data = await res.json().catch(() => ({})); return { ok: false, error: data?.error || '创建知识库分组失败' }; } return { ok: true, group: (await res.json()) as KbGroup }; } catch { return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; } }; export const getKbJobs = async (): Promise => { return getJson('/api/kb/jobs', []); }; export const getKbJobsSafe = async (): Promise> => { return getJsonWithStatus('/api/kb/jobs', []); }; export const getKbDifySettings = async (): Promise => { return getJson('/api/kb/dify/settings', null); }; export const updateKbDifySettings = async ( payload: Partial ): Promise<{ ok: boolean; error?: string; settings?: KbDifySettings }> => { try { const res = await fetch('/api/kb/dify/settings', { method: 'PATCH', headers: { 'Content-Type': 'application/json', ...getAuthHeaders(), }, body: JSON.stringify(payload), }); if (!res.ok) { const data = await res.json().catch(() => ({})); return { ok: false, error: data?.error || '保存 Dify 设置失败' }; } return { ok: true, settings: (await res.json()) as KbDifySettings }; } catch { return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; } }; export const getKbDifyHealth = async (): Promise => { return getJson('/api/kb/dify/health', null); }; export const runKbJob = async ( jobId: number | string ): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => { try { const res = await fetch(`/api/kb/jobs/${jobId}/run`, { method: 'POST', headers: getAuthHeaders(), }); if (!res.ok) { const data = await res.json().catch(() => ({})); return { ok: false, error: data?.error || '执行任务失败' }; } const job = (await res.json()) as KbJob & { run_result?: string }; return { ok: true, job, run_result: job.run_result }; } catch { return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; } }; export const createKbDocument = async ( groupId: number, payload: { title: string; description?: string } ): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => { try { const res = await fetch(`/api/kb/groups/${groupId}/files`, { method: 'POST', headers: { 'Content-Type': 'application/json', ...getAuthHeaders(), }, body: JSON.stringify(payload), }); if (!res.ok) { const data = await res.json().catch(() => ({})); return { ok: false, error: data?.error || '创建文档失败' }; } return { ok: true, document: (await res.json()) as KbDocumentItem }; } catch { return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; } }; export const updateKbDocument = async ( documentId: number, payload: { title: string; description?: string; status?: string } ): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => { try { const res = await fetch(`/api/kb/documents/${documentId}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json', ...getAuthHeaders(), }, body: JSON.stringify(payload), }); if (!res.ok) { const data = await res.json().catch(() => ({})); return { ok: false, error: data?.error || '更新文档失败' }; } return { ok: true, document: (await res.json()) as KbDocumentItem }; } catch { return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; } }; export const deleteKbDocument = async ( documentId: number ): Promise<{ ok: boolean; error?: string }> => { try { const res = await fetch(`/api/kb/documents/${documentId}`, { method: 'DELETE', headers: getAuthHeaders(), }); if (!res.ok) { const data = await res.json().catch(() => ({})); return { ok: false, error: data?.error || '删除文档失败' }; } return { ok: true }; } catch { return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; } }; export const getKbDocumentVersions = async ( documentId: number ): Promise => { return getJson(`/api/kb/documents/${documentId}/versions`, []); }; export const getKbDocumentVersionSourceFile = async ( versionId: number ): Promise<{ ok: boolean; error?: string; blob?: Blob; filename?: string; contentType?: string }> => { try { const res = await fetch(`/api/kb/document-versions/${versionId}/source-file`, { headers: getAuthHeaders(), }); if (!res.ok) { const data = await res.json().catch(() => ({})); return { ok: false, error: data?.error || '读取原始文件失败' }; } const disposition = res.headers.get('content-disposition') || ''; const filenameMatch = disposition.match(/filename\*=UTF-8''([^;]+)|filename="?([^"]+)"?/i); const filename = decodeURIComponent(filenameMatch?.[1] || filenameMatch?.[2] || ''); return { ok: true, blob: await res.blob(), filename: filename || undefined, contentType: res.headers.get('content-type') || undefined, }; } catch { return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; } }; export const getKbDocumentSyncRecords = async ( documentId: number ): Promise => { return getJson(`/api/kb/documents/${documentId}/sync-records`, []); }; export const getKbDocumentMarkdown = async ( documentId: number ): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => { try { const res = await fetch(`/api/kb/documents/${documentId}/markdown`, { headers: getAuthHeaders(), }); if (!res.ok) { const data = await res.json().catch(() => ({})); return { ok: false, error: data?.error || '读取清洗后的 Markdown 失败' }; } return { ok: true, data: (await res.json()) as KbDocumentMarkdown }; } catch { return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; } }; export const updateKbDocumentMarkdown = async ( documentId: number, payload: { content: string } ): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => { try { const res = await fetch(`/api/kb/documents/${documentId}/markdown`, { method: 'PATCH', headers: { 'Content-Type': 'application/json', ...getAuthHeaders(), }, body: JSON.stringify(payload), }); if (!res.ok) { const data = await res.json().catch(() => ({})); return { ok: false, error: data?.error || '保存 Markdown 失败' }; } return { ok: true, data: (await res.json()) as KbDocumentMarkdown }; } catch { return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; } }; export const uploadKbDocumentVersion = async ( documentId: number, file: File ): Promise<{ ok: boolean; error?: string; version?: KbDocumentVersionItem; status?: number }> => { try { const formData = new FormData(); formData.append('file', file); const res = await fetch(`/api/kb/documents/${documentId}/upload`, { method: 'POST', headers: getAuthHeaders(), body: formData, }); if (!res.ok) { if (res.status === 413) { return { ok: false, error: '文件过大,超过当前上传限制,请联系管理员放宽限制后重试', status: res.status }; } const data = await res.json().catch(() => ({})); return { ok: false, error: data?.error || '上传文档版本失败', status: res.status }; } return { ok: true, version: (await res.json()) as KbDocumentVersionItem, status: res.status }; } catch { return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; } }; export const createKbPathUploadJob = async ( groupId: number, payload: { total_files: number; selected_paths: string[] } ): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => { try { const res = await fetch(`/api/kb/groups/${groupId}/path-upload-jobs`, { method: 'POST', headers: { 'Content-Type': 'application/json', ...getAuthHeaders(), }, body: JSON.stringify(payload), }); const data = await res.json().catch(() => ({})); if (!res.ok) { return { ok: false, error: data?.error || '创建路径上传任务失败', status: res.status }; } return { ok: true, job: data as KbJob, status: res.status }; } catch { return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; } }; export const uploadKbPathJobFile = async ( jobId: number | string, file: File, relativePath: string, ): Promise<{ ok: boolean; error?: string; job?: KbJob }> => { try { const formData = new FormData(); formData.append('file', file); formData.append('relative_path', relativePath); const res = await fetch(`/api/kb/path-upload-jobs/${jobId}/files`, { method: 'POST', headers: getAuthHeaders(), body: formData, }); const data = await res.json().catch(() => ({})); if (!res.ok) { return { ok: false, error: data?.error || '上传路径文件失败' }; } return { ok: true, job: data as KbJob }; } catch { return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; } }; export const finalizeKbPathUploadJob = async ( jobId: number | string, ): Promise<{ ok: boolean; error?: string; job?: KbJob }> => { try { const res = await fetch(`/api/kb/path-upload-jobs/${jobId}/finalize`, { method: 'POST', headers: getAuthHeaders(), }); const data = await res.json().catch(() => ({})); if (!res.ok) { return { ok: false, error: data?.error || '提交路径上传任务失败' }; } return { ok: true, job: data as KbJob }; } catch { return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; } }; export const retryFailedKbPathUploadJob = async ( jobId: number | string, payload?: { relative_paths?: string[] }, ): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => { try { const res = await fetch(`/api/kb/path-upload-jobs/${jobId}/retry-failed`, { method: 'POST', headers: { 'Content-Type': 'application/json', ...getAuthHeaders(), }, body: JSON.stringify(payload || {}), }); const data = await res.json().catch(() => ({})); if (!res.ok) { return { ok: false, error: data?.error || '重试失败文件失败', status: res.status }; } return { ok: true, job: data as KbJob, status: res.status }; } catch { return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; } }; export const syncKbDocumentToDify = async ( documentId: number ): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => { try { const res = await fetch(`/api/kb/documents/${documentId}/sync`, { method: 'POST', headers: getAuthHeaders(), }); if (!res.ok) { const data = await res.json().catch(() => ({})); return { ok: false, error: data?.error || data?.error_message || data?.run_result || '同步到 Dify 失败' }; } const job = (await res.json()) as KbJob & { run_result?: string }; return { ok: true, job, run_result: job.run_result }; } catch { return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; } }; export const updateKbGroup = async ( groupId: number, payload: { name: string; description?: string } ): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => { try { const res = await fetch(`/api/kb/groups/${groupId}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json', ...getAuthHeaders(), }, body: JSON.stringify(payload), }); if (!res.ok) { const data = await res.json().catch(() => ({})); return { ok: false, error: data?.error || '更新知识库分组失败' }; } return { ok: true, group: (await res.json()) as KbGroup }; } catch { return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; } }; export const deleteKbGroup = async ( groupId: number ): Promise<{ ok: boolean; error?: string }> => { try { const res = await fetch(`/api/kb/groups/${groupId}`, { method: 'DELETE', headers: getAuthHeaders(), }); if (!res.ok) { const data = await res.json().catch(() => ({})); return { ok: false, error: data?.error || '删除知识库分组失败' }; } return { ok: true }; } catch { return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; } };