/** * src/api/kb.ts * 知识库 HTTP API(暂缓迁入 features/kb,KB redesign 后迁移)。 */ import { getAuthHeaders } from '@/shared/utils/auth'; import { BusinessError, requestJson } from '@/shared/api/client'; 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 KbQueuedJobResponse extends KbJob { accepted?: boolean; queue_result?: string; } export interface KbUploadVersionResponse { accepted?: boolean; message?: string; queue_result?: string; version: KbDocumentVersionItem; clean_job?: KbJob | 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 auth = () => ({ headers: getAuthHeaders() }); const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } }); const kbErrorMessage = (e: unknown, fallback: string) => (e as Error).message || fallback; const getJson = async (path: string, fallback: T): Promise => { try { return await requestJson(path, auth()); } catch { return fallback; } }; const getJsonWithStatus = async (path: string, fallback: T): Promise> => { try { const data = await requestJson(path, auth()); return { ok: true, data }; } catch (e) { const err = e as BusinessError; return { ok: false, data: fallback, error: kbErrorMessage(e, '知识库接口请求失败'), status: err.status, }; } }; 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 group = await requestJson('/api/kb/groups', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload), }); return { ok: true, group }; } catch (e) { return { ok: false, error: kbErrorMessage(e, '创建知识库分组失败') }; } }; 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 settings = await requestJson('/api/kb/dify/settings', { method: 'PATCH', ...jsonAuth(), body: JSON.stringify(payload), }); return { ok: true, settings }; } catch (e) { return { ok: false, error: kbErrorMessage(e, '保存 Dify 设置失败') }; } }; 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 job = await requestJson(`/api/kb/jobs/${jobId}/run`, { method: 'POST', ...auth(), }); return { ok: true, job, run_result: job.run_result }; } catch (e) { return { ok: false, error: kbErrorMessage(e, '执行任务失败') }; } }; export const createKbDocument = async ( groupId: number, payload: { title: string; description?: string } ): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => { try { const document = await requestJson(`/api/kb/groups/${groupId}/files`, { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload), }); return { ok: true, document }; } catch (e) { return { ok: false, error: kbErrorMessage(e, '创建文档失败') }; } }; export const updateKbDocument = async ( documentId: number, payload: { title: string; description?: string; status?: string } ): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => { try { const document = await requestJson(`/api/kb/documents/${documentId}`, { method: 'PATCH', ...jsonAuth(), body: JSON.stringify(payload), }); return { ok: true, document }; } catch (e) { return { ok: false, error: kbErrorMessage(e, '更新文档失败') }; } }; export const deleteKbDocument = async ( documentId: number ): Promise<{ ok: boolean; error?: string }> => { try { await requestJson(`/api/kb/documents/${documentId}`, { method: 'DELETE', ...auth() }); return { ok: true }; } catch (e) { return { ok: false, error: kbErrorMessage(e, '删除文档失败') }; } }; 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) { let message = '读取原始文件失败'; try { const data = await res.json(); if (typeof data?.error === 'string' && data.error.trim()) message = data.error; else if (typeof data?.message === 'string' && data.message.trim()) message = data.message; } catch { // ignore non-json error body } return { ok: false, error: message }; } 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 data = await requestJson(`/api/kb/documents/${documentId}/markdown`, auth()); return { ok: true, data }; } catch (e) { return { ok: false, error: kbErrorMessage(e, '读取清洗后的 Markdown 失败') }; } }; export const updateKbDocumentMarkdown = async ( documentId: number, payload: { content: string } ): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => { try { const data = await requestJson(`/api/kb/documents/${documentId}/markdown`, { method: 'PATCH', ...jsonAuth(), body: JSON.stringify(payload), }); return { ok: true, data }; } catch (e) { return { ok: false, error: kbErrorMessage(e, '保存 Markdown 失败') }; } }; export const uploadKbDocumentVersion = async ( documentId: number, file: File ): Promise<{ ok: boolean; error?: string; version?: KbDocumentVersionItem; clean_job?: KbJob | null; message?: string; status?: number }> => { try { const formData = new FormData(); formData.append('file', file); const payload = await requestJson(`/api/kb/documents/${documentId}/upload`, { method: 'POST', ...auth(), body: formData, }); return { ok: true, version: payload.version, clean_job: payload.clean_job, message: payload.message }; } catch (e) { const err = e as BusinessError; if (err.status === 413) { return { ok: false, error: '文件过大,超过当前上传限制,请联系管理员放宽限制后重试', status: 413, }; } return { ok: false, error: kbErrorMessage(e, '上传文档版本失败'), status: err.status }; } }; export const submitKbDocumentClean = async ( documentId: number ): Promise<{ ok: boolean; error?: string; job?: KbJob | null; message?: string; status?: number }> => { try { const job = await requestJson(`/api/kb/documents/${documentId}/clean`, { method: 'POST', ...auth(), }); return { ok: true, job, message: job.message || undefined }; } catch (e) { const err = e as BusinessError; return { ok: false, error: kbErrorMessage(e, '提交清洗任务失败'), status: err.status }; } }; export const createKbPathUploadJob = async ( groupId: number, payload: { total_files: number; selected_paths: string[]; files?: Array<{ relative_path: string; original_name: string }>; } ): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => { try { const job = await requestJson(`/api/kb/groups/${groupId}/path-upload-jobs`, { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload), }); return { ok: true, job }; } catch (e) { const err = e as BusinessError; return { ok: false, error: kbErrorMessage(e, '创建路径上传任务失败'), status: err.status }; } }; export const uploadKbPathJobFile = async ( jobId: number | string, file: File, relativePath: string, ): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => { try { const formData = new FormData(); formData.append('file', file); formData.append('relative_path', relativePath); const job = await requestJson(`/api/kb/path-upload-jobs/${jobId}/files`, { method: 'POST', ...auth(), body: formData, }); return { ok: true, job }; } catch (e) { const err = e as BusinessError; if (err.status === 413) { return { ok: false, error: '文件过大,超过当前上传限制,请联系管理员放宽限制后重试', status: 413, }; } return { ok: false, error: kbErrorMessage(e, '上传路径文件失败'), status: err.status }; } }; export const markKbPathJobFileFailed = async ( jobId: number | string, payload: { relative_path: string; original_name?: string; error: string } ): Promise<{ ok: boolean; error?: string; job?: KbJob }> => { try { const job = await requestJson(`/api/kb/path-upload-jobs/${jobId}/files/fail`, { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload), }); return { ok: true, job }; } catch (e) { return { ok: false, error: kbErrorMessage(e, '记录路径文件失败状态失败') }; } }; export const finalizeKbPathUploadJob = async ( jobId: number | string, ): Promise<{ ok: boolean; error?: string; job?: KbJob }> => { try { const job = await requestJson(`/api/kb/path-upload-jobs/${jobId}/finalize`, { method: 'POST', ...auth(), }); return { ok: true, job }; } catch (e) { return { ok: false, error: kbErrorMessage(e, '提交路径上传任务失败') }; } }; export const retryFailedKbPathUploadJob = async ( jobId: number | string, payload?: { relative_paths?: string[] }, ): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => { try { const job = await requestJson(`/api/kb/path-upload-jobs/${jobId}/retry-failed`, { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload || {}), }); return { ok: true, job }; } catch (e) { const err = e as BusinessError; return { ok: false, error: kbErrorMessage(e, '重试失败文件失败'), status: err.status }; } }; export const deleteKbPathJobFile = async ( jobId: number | string, relativePath: string, ): Promise<{ ok: boolean; error?: string; job?: KbJob; document_deleted?: boolean }> => { try { const query = new URLSearchParams({ relative_path: relativePath }); const result = await requestJson<{ ok: boolean; job: KbJob; document_deleted?: boolean }>( `/api/kb/path-upload-jobs/${jobId}/files?${query.toString()}`, { method: 'DELETE', ...auth() } ); return { ok: true, job: result.job, document_deleted: result.document_deleted }; } catch (e) { return { ok: false, error: kbErrorMessage(e, '删除路径上传文件失败') }; } }; export const syncKbDocumentToDify = async ( documentId: number ): Promise<{ ok: boolean; error?: string; job?: KbQueuedJobResponse }> => { try { const job = await requestJson(`/api/kb/documents/${documentId}/sync`, { method: 'POST', ...auth(), }); return { ok: true, job }; } catch (e) { return { ok: false, error: kbErrorMessage(e, '同步到 Dify 失败') }; } }; export const updateKbGroup = async ( groupId: number, payload: { name: string; description?: string } ): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => { try { const group = await requestJson(`/api/kb/groups/${groupId}`, { method: 'PATCH', ...jsonAuth(), body: JSON.stringify(payload), }); return { ok: true, group }; } catch (e) { return { ok: false, error: kbErrorMessage(e, '更新知识库分组失败') }; } }; export const deleteKbGroup = async ( groupId: number ): Promise<{ ok: boolean; error?: string }> => { try { await requestJson(`/api/kb/groups/${groupId}`, { method: 'DELETE', ...auth() }); return { ok: true }; } catch (e) { return { ok: false, error: kbErrorMessage(e, '删除知识库分组失败') }; } };