fix: 统一异常处理

This commit is contained in:
sophie committed 2026-05-30 17:06:32 +08:00
1 parent 4daf8dfcaa
commit 0c5cfcaa4a
21 files changed
+2124 -4218

No files matched your search

+134
View File
@@ -0,0 +1,134 @@
import { getAuthHeaders } from '../utils/auth';
import { requestJson } from './client';
const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
// Users
export const listAdminUsers = () => requestJson<any[]>('/api/admin/users', auth());
export const createAdminUser = (payload: Record<string, unknown>) =>
requestJson('/api/admin/users', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
export const updateAdminUser = (id: number, payload: Record<string, unknown>) =>
requestJson(`/api/admin/users/${id}`, { method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload) });
export const approveAdminUser = (id: number) =>
requestJson(`/api/admin/users/${id}/approve`, { method: 'POST', ...auth() });
export const rejectAdminUser = (id: number) =>
requestJson(`/api/admin/users/${id}/reject`, { method: 'POST', ...auth() });
export const cleanupRejectedAdminUsers = () =>
requestJson<{ deleted_count: number }>('/api/admin/users/cleanup-rejected', { method: 'POST', ...auth() });
export const batchDeleteAdminUsers = (userIds: number[]) =>
requestJson<{ deleted_count: number }>('/api/admin/users/batch-delete', {
method: 'POST',
...jsonAuth(),
body: JSON.stringify({ user_ids: userIds }),
});
export const batchUpdateAdminUsers = (userIds: number[], data: Record<string, unknown>) =>
requestJson('/api/admin/users/batch', {
method: 'PUT',
...jsonAuth(),
body: JSON.stringify({ user_ids: userIds, data }),
});
export const updateAdminUserPermissions = (userId: number, agentIds: number[]) =>
requestJson(`/api/admin/users/${userId}/permissions`, {
method: 'POST',
...jsonAuth(),
body: JSON.stringify({ agent_ids: agentIds }),
});
// Departments
export const listAdminDepartments = () => requestJson<any[]>('/api/admin/departments', auth());
export const createAdminDepartment = (payload: Record<string, unknown>) =>
requestJson('/api/admin/departments', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
export const updateAdminDepartment = (id: number, payload: Record<string, unknown>) =>
requestJson(`/api/admin/departments/${id}`, { method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload) });
export const deleteAdminDepartment = (id: number) =>
requestJson(`/api/admin/departments/${id}`, { method: 'DELETE', ...auth() });
// Agents
export const listAdminAgents = () => requestJson<any[]>('/api/admin/agents', auth());
export const createAdminAgent = (payload: Record<string, unknown>) =>
requestJson('/api/admin/agents', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
export const updateAdminAgent = (id: number, payload: Record<string, unknown>) =>
requestJson(`/api/admin/agents/${id}`, { method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload) });
export const deleteAdminAgent = (id: number) =>
requestJson(`/api/admin/agents/${id}`, { method: 'DELETE', ...auth() });
export const testAdminAgent = (id: number) =>
requestJson<any>(`/api/admin/agents/${id}/test`, { method: 'POST', ...auth() });
export const saveAdminAgentPermissions = (agentId: number, userIds: number[]) =>
requestJson(`/api/admin/agents/${agentId}/permissions`, {
method: 'POST',
...jsonAuth(),
body: JSON.stringify({ user_ids: userIds }),
});
// Permission requests
export const listAdminPermissionRequests = () =>
requestJson<any[]>('/api/admin/permission-requests', auth());
export const approveAdminPermissionRequest = (id: number) =>
requestJson(`/api/admin/permission-requests/${id}/approve`, { method: 'POST', ...auth() });
export const rejectAdminPermissionRequest = (id: number) =>
requestJson(`/api/admin/permission-requests/${id}/reject`, { method: 'POST', ...auth() });
export const batchUpdateAdminPermissions = (payload: Record<string, unknown>) =>
requestJson('/api/admin/permissions/batch', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
export const importAdminPermissions = (formData: FormData) =>
requestJson('/api/admin/permissions/import', { method: 'POST', ...auth(), body: formData });
// Reports
export const getAdminUsageReport = () => requestJson<any>('/api/admin/reports/usage', auth());
export const getAdminFeedbackReport = () => requestJson<any>('/api/admin/reports/feedback', auth());
export const getAdminReportTable = (url: string) => requestJson<any[]>(url, auth());
export const getAdminReportTableCount = (url: string) => requestJson<{ total: number }>(url, auth());
export const batchDeleteAdminChatLogs = (ids: number[]) =>
requestJson<{ deleted_count: number }>('/api/admin/database/chat_logs/batch-delete', {
method: 'POST',
...jsonAuth(),
body: JSON.stringify({ ids }),
});
// WeCom admin
export const listAdminWecomBindings = (boundOnly: boolean) =>
requestJson<any[]>(`/api/admin/wecom/bindings?bound_only=${boundOnly ? 'true' : 'false'}`, auth());
export const listAdminWecomLoginAudits = (query: string) =>
requestJson<any[]>(`/api/admin/wecom/login-audits?${query}`, auth());
export const getAdminWecomSystemSettings = () =>
requestJson<any>('/api/admin/wecom/system-settings', auth());
export const getAdminWecomIntegrationManifest = () =>
requestJson<any>('/api/admin/wecom/integration-manifest', auth());
export const saveAdminWecomSystemSettings = (payload: Record<string, unknown>) =>
requestJson<any>('/api/admin/wecom/system-settings', {
method: 'PUT',
...jsonAuth(),
body: JSON.stringify(payload),
});
export const getAdminWecomNotifySettings = () =>
requestJson<any>('/api/admin/wecom/notify-settings', auth());
export const saveAdminWecomNotifySettings = (payload: Record<string, unknown>) =>
requestJson<any>('/api/admin/wecom/notify-settings', {
method: 'PUT',
...jsonAuth(),
body: JSON.stringify(payload),
});
export const getAdminWecomNotifyMetrics = () =>
requestJson<any>('/api/admin/wecom/notify-metrics', auth());
export const bindAdminWecomUser = (payload: Record<string, unknown>) =>
requestJson('/api/admin/wecom/bind', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
export const unbindAdminWecomUser = (userId: number) =>
requestJson('/api/admin/wecom/unbind', {
method: 'POST',
...jsonAuth(),
body: JSON.stringify({ user_id: userId }),
});
// Announcements (admin module uses user endpoints)
export const listAnnouncements = () => requestJson<any[]>('/api/user/announcements', auth());
export const createAnnouncement = (payload: Record<string, unknown>) =>
requestJson('/api/user/announcements', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
export const deleteAnnouncement = (id: number) =>
requestJson(`/api/user/announcements/${id}`, { method: 'DELETE', ...auth() });
// Quick questions
export const listAdminQuickQuestions = () => requestJson<any[]>('/api/admin/quick-questions', auth());
export const saveAdminQuickQuestion = (url: string, method: string, payload: Record<string, unknown>) =>
requestJson(url, { method, ...jsonAuth(), body: JSON.stringify(payload) });
export const deleteAdminQuickQuestion = (id: number) =>
requestJson(`/api/admin/quick-questions/${id}`, { method: 'DELETE', ...auth() });
+125
View File
@@ -0,0 +1,125 @@
/**
* frontend/src/api/client.ts
* 用途:封装前端统一 API 访问与响应解析逻辑。
* 说明:
* 1. 支持两种返回格式:旧格式(直接返回数据)与新格式({ success, data/error })。
* 2. requestJson 统一处理成功/失败分支,并在失败时抛出 BusinessError。
* 3. BusinessError 提供 code/details/requestId,方便页面层做多语言与精细化提示。
*/
import { getAuthHeaders } from '../utils/auth';
import i18n from '../i18n';
export interface ApiSuccessEnvelope<T> {
success: true;
data: T;
request_id?: string;
timestamp?: string;
}
export interface ApiErrorBody {
code?: string;
message?: string;
details?: Record<string, any>;
retryable?: boolean;
}
export interface ApiErrorEnvelope {
success: false;
error?: ApiErrorBody;
request_id?: string;
timestamp?: string;
}
export class BusinessError extends Error {
code: string;
details: Record<string, any>;
requestId?: string;
status?: number;
constructor(args: { message: string; code?: string; details?: Record<string, any>; requestId?: string; status?: number }) {
super(args.message);
this.name = 'BusinessError';
this.code = args.code || 'SYSTEM.UNKNOWN';
this.details = args.details || {};
this.requestId = args.requestId;
this.status = args.status;
}
}
function resolveLocalizedErrorMessage(code?: string, fallbackMessage?: string): string {
const normalizedCode = code ? code.replace(/\./g, '_') : '';
const key = normalizedCode ? `errors.codes.${normalizedCode}` : '';
if (key && i18n.global.te(key)) {
return String(i18n.global.t(key));
}
if (fallbackMessage) return fallbackMessage;
if (i18n.global.te('errors.generic')) {
return String(i18n.global.t('errors.generic'));
}
return code || 'Request failed';
}
export const isEnvelope = (payload: any): payload is ApiSuccessEnvelope<any> | ApiErrorEnvelope => {
return !!payload && typeof payload === 'object' && typeof payload.success === 'boolean';
};
function pickLegacyErrorMessage(payload: any): string | undefined {
if (!payload) return undefined;
if (typeof payload.error === 'string' && payload.error.trim()) return payload.error;
if (typeof payload.message === 'string' && payload.message.trim()) return payload.message;
return undefined;
}
export async function requestJson<T>(url: string, init?: RequestInit): Promise<T> {
const headers = new Headers(init?.headers || {});
const authHeaders = getAuthHeaders();
Object.entries(authHeaders).forEach(([k, v]) => headers.set(k, v as string));
const res = await fetch(url, { ...init, headers });
let data: any = null;
try {
data = await res.json();
} catch {
if (!res.ok) {
throw new BusinessError({
message: `HTTP ${res.status}`,
code: 'SYSTEM.HTTP_ERROR',
status: res.status,
});
}
return null as T;
}
if (!res.ok) {
if (isEnvelope(data) && data.success === false) {
throw new BusinessError({
message: resolveLocalizedErrorMessage(data.error?.code, data.error?.message || `HTTP ${res.status}`),
code: data.error?.code,
details: data.error?.details,
requestId: data.request_id,
status: res.status,
});
}
throw new BusinessError({
message: resolveLocalizedErrorMessage(data?.code, pickLegacyErrorMessage(data) || `HTTP ${res.status}`),
code: data?.code || data?.error_code || 'SYSTEM.HTTP_ERROR',
details: data?.details || {},
requestId: data?.request_id,
status: res.status,
});
}
if (isEnvelope(data)) {
if (data.success === true) return data.data as T;
throw new BusinessError({
message: resolveLocalizedErrorMessage(data.error?.code, data.error?.message || 'Request failed'),
code: data.error?.code,
details: data.error?.details,
requestId: data.request_id,
status: res.status,
});
}
return data as T;
}
+108 -193
View File
@@ -1,4 +1,5 @@
import { getAuthHeaders } from '../utils/auth';
import { BusinessError, requestJson } from './client';
export interface KbGroup {
id: number;
@@ -116,11 +117,14 @@ export interface KbListResponse<T> {
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 <T>(path: string, fallback: T): Promise<T> => {
try {
const res = await fetch(path, { headers: getAuthHeaders() });
if (!res.ok) return fallback;
return (await res.json()) as T;
return await requestJson<T>(path, auth());
} catch {
return fallback;
}
@@ -128,19 +132,16 @@ const getJson = async <T>(path: string, fallback: T): Promise<T> => {
const getJsonWithStatus = async <T>(path: string, fallback: T): Promise<KbListResponse<T>> => {
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: '知识库接口暂未就绪,请稍后再试' };
const data = await requestJson<T>(path, auth());
return { ok: true, data };
} catch (e) {
const err = e as BusinessError;
return {
ok: false,
data: fallback,
error: kbErrorMessage(e, '知识库接口请求失败'),
status: err.status,
};
}
};
@@ -165,21 +166,14 @@ export const createKbGroup = async (payload: {
description?: string;
}): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => {
try {
const res = await fetch('/api/kb/groups', {
const group = await requestJson<KbGroup>('/api/kb/groups', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
...jsonAuth(),
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: '知识库接口暂未就绪,请稍后再试' };
return { ok: true, group };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '创建知识库分组失败') };
}
};
@@ -199,21 +193,14 @@ export const updateKbDifySettings = async (
payload: Partial<KbDifySettings>
): Promise<{ ok: boolean; error?: string; settings?: KbDifySettings }> => {
try {
const res = await fetch('/api/kb/dify/settings', {
const settings = await requestJson<KbDifySettings>('/api/kb/dify/settings', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
...jsonAuth(),
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: '知识库接口暂未就绪,请稍后再试' };
return { ok: true, settings };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '保存 Dify 设置失败') };
}
};
@@ -225,18 +212,13 @@ 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`, {
const job = await requestJson<KbJob & { run_result?: string }>(`/api/kb/jobs/${jobId}/run`, {
method: 'POST',
headers: getAuthHeaders(),
...auth(),
});
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: '知识库接口暂未就绪,请稍后再试' };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '执行任务失败') };
}
};
@@ -245,21 +227,14 @@ export const createKbDocument = async (
payload: { title: string; description?: string }
): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => {
try {
const res = await fetch(`/api/kb/groups/${groupId}/files`, {
const document = await requestJson<KbDocumentItem>(`/api/kb/groups/${groupId}/files`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
...jsonAuth(),
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: '知识库接口暂未就绪,请稍后再试' };
return { ok: true, document };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '创建文档失败') };
}
};
@@ -268,21 +243,14 @@ export const updateKbDocument = async (
payload: { title: string; description?: string; status?: string }
): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => {
try {
const res = await fetch(`/api/kb/documents/${documentId}`, {
const document = await requestJson<KbDocumentItem>(`/api/kb/documents/${documentId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
...jsonAuth(),
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: '知识库接口暂未就绪,请稍后再试' };
return { ok: true, document };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '更新文档失败') };
}
};
@@ -290,17 +258,10 @@ 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 || '删除文档失败' };
}
await requestJson(`/api/kb/documents/${documentId}`, { method: 'DELETE', ...auth() });
return { ok: true };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '删除文档失败') };
}
};
@@ -318,8 +279,15 @@ export const getKbDocumentVersionSourceFile = async (
headers: getAuthHeaders(),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '读取原始文件失败' };
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);
@@ -345,16 +313,10 @@ 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: '知识库接口暂未就绪,请稍后再试' };
const data = await requestJson<KbDocumentMarkdown>(`/api/kb/documents/${documentId}/markdown`, auth());
return { ok: true, data };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '读取清洗后的 Markdown 失败') };
}
};
@@ -363,21 +325,14 @@ export const updateKbDocumentMarkdown = async (
payload: { content: string }
): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => {
try {
const res = await fetch(`/api/kb/documents/${documentId}/markdown`, {
const data = await requestJson<KbDocumentMarkdown>(`/api/kb/documents/${documentId}/markdown`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
...jsonAuth(),
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: '知识库接口暂未就绪,请稍后再试' };
return { ok: true, data };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '保存 Markdown 失败') };
}
};
@@ -388,22 +343,22 @@ export const uploadKbDocumentVersion = async (
try {
const formData = new FormData();
formData.append('file', file);
const res = await fetch(`/api/kb/documents/${documentId}/upload`, {
const version = await requestJson<KbDocumentVersionItem>(`/api/kb/documents/${documentId}/upload`, {
method: 'POST',
headers: getAuthHeaders(),
...auth(),
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 };
} catch (e) {
const err = e as BusinessError;
if (err.status === 413) {
return {
ok: false,
error: '文件过大,超过当前上传限制,请联系管理员放宽限制后重试',
status: 413,
};
}
return { ok: true, version: (await res.json()) as KbDocumentVersionItem, status: res.status };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
return { ok: false, error: kbErrorMessage(e, '上传文档版本失败'), status: err.status };
}
};
@@ -412,21 +367,15 @@ export const createKbPathUploadJob = async (
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`, {
const job = await requestJson<KbJob>(`/api/kb/groups/${groupId}/path-upload-jobs`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
...jsonAuth(),
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: '知识库接口暂未就绪,请稍后再试' };
return { ok: true, job };
} catch (e) {
const err = e as BusinessError;
return { ok: false, error: kbErrorMessage(e, '创建路径上传任务失败'), status: err.status };
}
};
@@ -439,19 +388,14 @@ export const uploadKbPathJobFile = async (
const formData = new FormData();
formData.append('file', file);
formData.append('relative_path', relativePath);
const res = await fetch(`/api/kb/path-upload-jobs/${jobId}/files`, {
const job = await requestJson<KbJob>(`/api/kb/path-upload-jobs/${jobId}/files`, {
method: 'POST',
headers: getAuthHeaders(),
...auth(),
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: '知识库接口暂未就绪,请稍后再试' };
return { ok: true, job };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '上传路径文件失败') };
}
};
@@ -459,17 +403,13 @@ 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`, {
const job = await requestJson<KbJob>(`/api/kb/path-upload-jobs/${jobId}/finalize`, {
method: 'POST',
headers: getAuthHeaders(),
...auth(),
});
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: '知识库接口暂未就绪,请稍后再试' };
return { ok: true, job };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '提交路径上传任务失败') };
}
};
@@ -478,21 +418,15 @@ export const retryFailedKbPathUploadJob = async (
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`, {
const job = await requestJson<KbJob>(`/api/kb/path-upload-jobs/${jobId}/retry-failed`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
...jsonAuth(),
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: '知识库接口暂未就绪,请稍后再试' };
return { ok: true, job };
} catch (e) {
const err = e as BusinessError;
return { ok: false, error: kbErrorMessage(e, '重试失败文件失败'), status: err.status };
}
};
@@ -500,18 +434,13 @@ 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`, {
const job = await requestJson<KbJob & { run_result?: string }>(`/api/kb/documents/${documentId}/sync`, {
method: 'POST',
headers: getAuthHeaders(),
...auth(),
});
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: '知识库接口暂未就绪,请稍后再试' };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '同步到 Dify 失败') };
}
};
@@ -520,21 +449,14 @@ export const updateKbGroup = async (
payload: { name: string; description?: string }
): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => {
try {
const res = await fetch(`/api/kb/groups/${groupId}`, {
const group = await requestJson<KbGroup>(`/api/kb/groups/${groupId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
...jsonAuth(),
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: '知识库接口暂未就绪,请稍后再试' };
return { ok: true, group };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '更新知识库分组失败') };
}
};
@@ -542,16 +464,9 @@ 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 || '删除知识库分组失败' };
}
await requestJson(`/api/kb/groups/${groupId}`, { method: 'DELETE', ...auth() });
return { ok: true };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '删除知识库分组失败') };
}
};
+20 -26
View File
@@ -1,4 +1,5 @@
import { getAuthHeaders } from '../utils/auth';
import { requestJson } from './client';
export interface ScheduleTask {
id: number;
@@ -70,9 +71,7 @@ export interface DifyExecutionSnapshot {
}
async function getJson<T>(url: string): Promise<T> {
const res = await fetch(url, { headers: getAuthHeaders() });
if (!res.ok) throw new Error((await res.json().catch(() => ({})))?.error || 'Request failed');
return (await res.json()) as T;
return requestJson<T>(url, { headers: getAuthHeaders() });
}
export const listAdminSchedules = () =>
@@ -81,39 +80,37 @@ export const listAdminSchedules = () =>
export const exportAdminScheduleUrl = (taskId: number) => `/api/admin/schedules/${taskId}/export`;
export const importAdminSchedules = async (payload: any) => {
const res = await fetch('/api/admin/schedules/import', {
return requestJson('/api/admin/schedules/import', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(payload),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data.error || 'Import failed');
}
return res.json();
};
export const getAdminScheduleTaskConfig = (taskId: number) =>
getJson<{ data_source_type: string; config: Record<string, any> | null }>(`/api/admin/schedule-config/${taskId}`);
export const updateAdminScheduleTaskConfig = (taskId: number, payload: Record<string, any>) =>
fetch(`/api/admin/schedule-config/${taskId}`, {
requestJson(`/api/admin/schedule-config/${taskId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(payload),
}).then(r => {
if (!r.ok) throw new Error('Update config failed');
return r.json();
});
export interface TestScheduleSqlResult {
total: number;
showing: number;
limit: number;
sql: string;
columns: string[];
rows: Record<string, any>[];
}
export const testAdminScheduleSql = (taskId: number, payload: { fetch_where_conditions?: string; fetch_order_by?: string; limit?: number }) =>
fetch(`/api/admin/schedule-config/${taskId}/test-sql`, {
requestJson<TestScheduleSqlResult>(`/api/admin/schedule-config/${taskId}/test-sql`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(payload),
}).then(r => {
if (!r.ok) return r.json().then(e => { throw new Error(e.error || 'Test failed'); });
return r.json();
});
export interface TestScheduleRunResult {
@@ -133,38 +130,35 @@ export interface TestScheduleRunResult {
}
export const testAdminScheduleRun = (taskId: number, payload: { fetch_where_conditions?: string; fetch_order_by?: string; limit?: number }) =>
fetch(`/api/admin/schedule-config/${taskId}/test-run`, {
requestJson<TestScheduleRunResult>(`/api/admin/schedule-config/${taskId}/test-run`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(payload),
}).then(r => {
if (!r.ok) return r.json().then(e => { throw new Error(e.error || 'Test run failed'); });
return r.json() as Promise<TestScheduleRunResult>;
});
export const createAdminSchedule = (payload: Partial<ScheduleTask> & { config?: Record<string, any> }) =>
fetch('/api/admin/schedules', {
requestJson('/api/admin/schedules', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(payload),
});
export const updateAdminSchedule = (id: number, payload: Partial<ScheduleTask> & { config?: Record<string, any> }) =>
fetch(`/api/admin/schedules/${id}`, {
requestJson(`/api/admin/schedules/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(payload),
});
export const deleteAdminSchedule = (id: number) =>
fetch(`/api/admin/schedules/${id}`, {
requestJson(`/api/admin/schedules/${id}`, {
method: 'DELETE',
headers: getAuthHeaders(),
});
export const runAdminSchedule = (id: number) =>
fetch(`/api/admin/schedules/${id}/run`, { method: 'POST', headers: getAuthHeaders() });
requestJson(`/api/admin/schedules/${id}/run`, { method: 'POST', headers: getAuthHeaders() });
export const toggleAdminSchedule = (id: number, enabled: boolean) =>
fetch(`/api/admin/schedules/${id}/${enabled ? 'enable' : 'disable'}`, { method: 'POST', headers: getAuthHeaders() });
requestJson(`/api/admin/schedules/${id}/${enabled ? 'enable' : 'disable'}`, { method: 'POST', headers: getAuthHeaders() });
export const listAdminScheduleRuns = (taskId: number, params?: { status?: string; started_after?: string; started_before?: string }) => {
const sp = new URLSearchParams();
if (params?.status) sp.set('status', params.status);
+77 -1
View File
@@ -1,4 +1,4 @@
import { createI18n } from 'vue-i18n';
import { createI18n } from 'vue-i18n';
const messages = {
'en': {
@@ -152,6 +152,25 @@ const messages = {
confirm: 'OK'
}
},
errors: {
generic: 'Request failed.',
codes: {
AUTH_UNAUTHORIZED: 'Please log in first.',
AUTH_FORBIDDEN: 'You do not have permission to perform this action.',
RESOURCE_NOT_FOUND: 'The requested resource was not found.',
RESOURCE_CONFLICT: 'Request conflict. Please refresh and try again.',
VALIDATION_INVALID_PARAM: 'Invalid request parameters.',
USER_USERNAME_REQUIRED: 'Username is required.',
USER_USERNAME_EXISTS: 'Username already exists.',
USER_EMAIL_INVALID: 'Invalid email format.',
USER_EMAIL_EXISTS: 'Email already exists.',
USER_EMPLOYEE_ID_EXISTS: 'Employee ID already exists.',
USER_PHONE_EXISTS: 'Phone number already exists.',
USER_UNIQUENESS_CONFLICT: 'Data uniqueness conflict.',
SYSTEM_INTERNAL_ERROR: 'Internal server error. Please try again later.',
SYSTEM_HTTP_ERROR: 'Request failed.',
}
},
scheduleRuns: {
title: 'Schedule Runs',
refresh: 'Refresh',
@@ -1606,6 +1625,25 @@ const messages = {
confirm: '确定'
}
},
errors: {
generic: '请求失败。',
codes: {
AUTH_UNAUTHORIZED: '请先登录。',
AUTH_FORBIDDEN: '你没有权限执行该操作。',
RESOURCE_NOT_FOUND: '请求的资源不存在。',
RESOURCE_CONFLICT: '请求冲突,请刷新后重试。',
VALIDATION_INVALID_PARAM: '请求参数不合法。',
USER_USERNAME_REQUIRED: '用户名必填。',
USER_USERNAME_EXISTS: '用户名已存在。',
USER_EMAIL_INVALID: '邮箱格式不正确。',
USER_EMAIL_EXISTS: '邮箱已存在。',
USER_EMPLOYEE_ID_EXISTS: '工号已存在。',
USER_PHONE_EXISTS: '手机号已存在。',
USER_UNIQUENESS_CONFLICT: '数据唯一性冲突。',
SYSTEM_INTERNAL_ERROR: '服务器内部错误,请稍后重试。',
SYSTEM_HTTP_ERROR: '请求失败。',
}
},
scheduleRuns: {
title: '排程记录',
refresh: '刷新',
@@ -3024,6 +3062,25 @@ const messages = {
confirm: '確定'
}
},
errors: {
generic: '請求失敗。',
codes: {
AUTH_UNAUTHORIZED: '請先登入。',
AUTH_FORBIDDEN: '你沒有權限執行此操作。',
RESOURCE_NOT_FOUND: '請求的資源不存在。',
RESOURCE_CONFLICT: '請求衝突,請刷新後重試。',
VALIDATION_INVALID_PARAM: '請求參數不合法。',
USER_USERNAME_REQUIRED: '用戶名必填。',
USER_USERNAME_EXISTS: '用戶名已存在。',
USER_EMAIL_INVALID: '郵箱格式不正確。',
USER_EMAIL_EXISTS: '郵箱已存在。',
USER_EMPLOYEE_ID_EXISTS: '工號已存在。',
USER_PHONE_EXISTS: '手機號已存在。',
USER_UNIQUENESS_CONFLICT: '數據唯一性衝突。',
SYSTEM_INTERNAL_ERROR: '伺服器內部錯誤,請稍後重試。',
SYSTEM_HTTP_ERROR: '請求失敗。',
}
},
scheduleRuns: {
title: '排程記錄',
refresh: '刷新',
@@ -4317,6 +4374,25 @@ const messages = {
confirm: 'ตกลง'
}
},
errors: {
generic: 'คำขอล้มเหลว',
codes: {
AUTH_UNAUTHORIZED: 'กรุณาเข้าสู่ระบบก่อน',
AUTH_FORBIDDEN: 'คุณไม่มีสิทธิ์ดำเนินการนี้',
RESOURCE_NOT_FOUND: 'ไม่พบทรัพยากรที่ร้องขอ',
RESOURCE_CONFLICT: 'คำขอขัดแย้ง โปรดรีเฟรชแล้วลองใหม่',
VALIDATION_INVALID_PARAM: 'พารามิเตอร์คำขอไม่ถูกต้อง',
USER_USERNAME_REQUIRED: 'กรุณากรอกชื่อผู้ใช้',
USER_USERNAME_EXISTS: 'ชื่อผู้ใช้นี้มีอยู่แล้ว',
USER_EMAIL_INVALID: 'รูปแบบอีเมลไม่ถูกต้อง',
USER_EMAIL_EXISTS: 'อีเมลนี้มีอยู่แล้ว',
USER_EMPLOYEE_ID_EXISTS: 'รหัสพนักงานนี้มีอยู่แล้ว',
USER_PHONE_EXISTS: 'หมายเลขโทรศัพท์นี้มีอยู่แล้ว',
USER_UNIQUENESS_CONFLICT: 'ข้อมูลซ้ำกัน',
SYSTEM_INTERNAL_ERROR: 'เซิร์ฟเวอร์ขัดข้อง กรุณาลองใหม่ภายหลัง',
SYSTEM_HTTP_ERROR: 'คำขอล้มเหลว',
}
},
scheduleRuns: {
title: 'บันทึกการตั้งเวลา',
refresh: 'รีเฟรช',
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,4 +1,4 @@


<script setup lang="ts">
/**
+147 -203
View File
@@ -57,6 +57,7 @@ import {
import KbWorkspaceView from './KbWorkspaceView.vue';
import { listWorkspaceScheduleRuns, workspaceRunExcelUrl, type ScheduleRun } from '../api/schedule';
import { BusinessError, requestJson } from '../api/client';
import { Clock, Download, Search, RefreshCw } from 'lucide-vue-next';
const { t, locale } = useI18n();
@@ -202,23 +203,17 @@ const handleForgotPassword = async () => {
}
try {
const res = await fetch('/api/user/reset-password-by-email', {
await requestJson('/api/user/reset-password-by-email', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(forgotPasswordForm.value)
});
const data = await res.json();
if (res.ok) {
msg.success(t('login.passwordResetEmailSent'));
showForgotPasswordModal.value = false;
forgotPasswordForm.value = { email: '' };
} else {
msg.error(data.error || t('login.passwordResetRequestFailed'));
}
msg.success(t('login.passwordResetEmailSent'));
showForgotPasswordModal.value = false;
forgotPasswordForm.value = { email: '' };
} catch (e) {
console.error('Password reset error', e);
msg.error(t('common.errorOccurred'));
msg.error((e as Error)?.message || t('login.passwordResetRequestFailed'));
}
};
@@ -279,13 +274,10 @@ const getSectionTitleKey = (sectionId: string) => {
// Methods
const fetchHome = async () => {
try {
const res = await fetch('/api/user/home', { headers: getAuthHeaders() });
if (res.status === 401) {
msg.error(t('login.loginRequired'));
handleLogout();
return;
const data = await requestJson<any>('/api/user/home', { headers: getAuthHeaders() });
if (!data) {
throw new Error('Missing /api/user/home payload');
}
const data = await res.json();
currentUser.value = {
id: data.user.id,
username: data.user.username,
@@ -357,6 +349,11 @@ return;
});
}
} catch (e) {
if ((e as BusinessError)?.status === 401) {
msg.error(t('login.loginRequired'));
handleLogout();
return;
}
console.error('Failed to load user home', e);
} finally {
isLoading.value = false;
@@ -365,12 +362,7 @@ return;
const fetchPublicAgents = async () => {
try {
const res = await fetch('/api/agents/public');
if (res.ok) {
publicAgents.value = await res.json();
} else {
publicAgents.value = [];
}
publicAgents.value = await requestJson<Agent[]>('/api/agents/public');
} catch (e) {
publicAgents.value = [];
}
@@ -378,10 +370,7 @@ const fetchPublicAgents = async () => {
const fetchAnnouncements = async () => {
try {
const res = await fetch('/api/user/announcements');
if (res.ok) {
announcements.value = await res.json();
}
announcements.value = await requestJson<Announcement[]>('/api/user/announcements');
} catch (e) {
console.error('Failed to load announcements', e);
}
@@ -448,7 +437,7 @@ const handleLogin = async (event?: Event) => {
const loginApi = isCasdoorMode
? (config.auth?.casdoor?.passwordLoginApi || '/api/user/casdoor/password-login')
: '/api/user/login';
const res = await fetch(loginApi, {
const user = await requestJson<any>(loginApi, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -457,31 +446,6 @@ const handleLogin = async (event?: Event) => {
})
});
if (!res.ok) {
const err = await res.json();
// Handle specific error messages if needed, or just alert
let msg = err.error || t('login.failed');
if (isCasdoorMode) {
if (err.error_code === 'CASDOOR_USER_NOT_FOUND') {
msg = t('workspace.msg.casdoorNotMatchedContactAdmin');
} else if (err.error_code === 'ACCOUNT_DISABLED') {
msg = t('login.accountDisabled');
} else if (String(err.error || '').includes('invalid_grant')) {
msg = t('login.incorrectPassword');
}
}
if (err.error === 'User not found') msg = t('login.userNotFound');
if (err.error === 'Incorrect password') msg = t('login.incorrectPassword');
if (err.error === 'Account is disabled') msg = t('login.accountDisabled');
if (err.error === 'Database connection failed') msg = t('login.dbConnectionFailed');
if (err.error === 'Internal server error') msg = t('login.internalError');
msg.error(msg);
return;
}
const user = await res.json();
persistLoginUser(user);
await fetchHome();
@@ -489,8 +453,27 @@ const handleLogin = async (event?: Event) => {
pendingAgentId.value = null;
await router.replace(`/chat/${DEFAULT_POST_LOGIN_AGENT_ID}`);
} catch (e) {
const err = e as BusinessError;
const rawError = String(err.message || '');
const errorCode = String(err.code || '');
let errorText = rawError || t('login.failed');
const loginMode = String(config.auth?.loginMode || 'casdoor').toLowerCase();
if (loginMode === 'casdoor') {
if (errorCode === 'CASDOOR_USER_NOT_FOUND') {
errorText = t('workspace.msg.casdoorNotMatchedContactAdmin');
} else if (errorCode === 'ACCOUNT_DISABLED') {
errorText = t('login.accountDisabled');
} else if (rawError.includes('invalid_grant')) {
errorText = t('login.incorrectPassword');
}
}
if (rawError === 'User not found') errorText = t('login.userNotFound');
if (rawError === 'Incorrect password') errorText = t('login.incorrectPassword');
if (rawError === 'Account is disabled') errorText = t('login.accountDisabled');
if (rawError === 'Database connection failed') errorText = t('login.dbConnectionFailed');
if (rawError === 'Internal server error') errorText = t('login.internalError');
console.error(e);
msg.error(t('login.requestFailed'));
msg.error(errorText || t('login.requestFailed'));
}
};
@@ -519,24 +502,11 @@ const tryCasdoorCallbackLogin = async () => {
}
try {
const api = config.auth.casdoor.loginApi || '/api/user/casdoor/login';
const res = await fetch(api, {
const data = await requestJson<any>(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, state }),
});
const data = await res.json();
if (!res.ok) {
const code = String(data.error_code || '');
let msg = data.error || 'Casdoor login failed';
if (code === 'CASDOOR_USER_NOT_FOUND') {
msg = t('workspace.msg.casdoorNotMatchedNeedLocalUser');
} else if (code === 'ACCOUNT_DISABLED') {
msg = t('workspace.msg.localAccountDisabled');
}
msg.error(msg);
clearWecomCallbackQuery();
return true;
}
// Persist access+refresh tokens for API auth and silent refresh.
persistLoginUser(data);
sessionStorage.removeItem('hxops_casdoor_state');
@@ -544,8 +514,15 @@ const tryCasdoorCallbackLogin = async () => {
await fetchHome();
return true;
} catch (e) {
const err = e as BusinessError;
if (err.code === 'CASDOOR_USER_NOT_FOUND') {
msg.error(t('workspace.msg.casdoorNotMatchedNeedLocalUser'));
} else if (err.code === 'ACCOUNT_DISABLED') {
msg.error(t('workspace.msg.localAccountDisabled'));
} else {
msg.error(err.message || 'Casdoor login failed');
}
console.error(e);
msg.error('Casdoor login failed');
clearWecomCallbackQuery();
return true;
}
@@ -572,10 +549,9 @@ const handleWecomLogin = async () => {
if (hint) {
qs.set('provider_hint', hint);
}
const res = await fetch(`${api}?${qs.toString()}`);
const data = await res.json();
if (!res.ok || !data.url) {
msg.error(data.error || t('login.wecomStartFailed'));
const data = await requestJson<any>(`${api}?${qs.toString()}`);
if (!data?.url) {
msg.error(t('login.wecomStartFailed'));
return;
}
if (data.state) {
@@ -587,10 +563,9 @@ const handleWecomLogin = async () => {
const redirectUri = `${window.location.origin}${wecomCfg.callbackPath || '/workspace'}`;
const api = wecomCfg.authorizeApi || '/api/user/wecom/authorize-url';
const res = await fetch(`${api}?redirect_uri=${encodeURIComponent(redirectUri)}`);
const data = await res.json();
if (!res.ok || !data.url) {
msg.error(data.error || t('login.wecomStartFailed'));
const data = await requestJson<any>(`${api}?redirect_uri=${encodeURIComponent(redirectUri)}`);
if (!data?.url) {
msg.error(t('login.wecomStartFailed'));
return;
}
if (data.state) {
@@ -599,7 +574,7 @@ const handleWecomLogin = async () => {
window.location.href = data.url;
} catch (e) {
console.error(e);
msg.error(t('login.wecomStartFailed'));
msg.error((e as Error)?.message || t('login.wecomStartFailed'));
}
};
@@ -645,7 +620,7 @@ const submitWecomCompleteBind = async () => {
wecomBindPrompt.value.error = '';
try {
const api = config.auth.wecom.completeBindApi || '/api/user/wecom/complete-bind';
const res = await fetch(api, {
const data = await requestJson<any>(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -654,15 +629,6 @@ const submitWecomCompleteBind = async () => {
value: wecomBindPrompt.value.value.trim(),
}),
});
const data = await res.json();
if (!res.ok) {
wecomBindPrompt.value.error = formatWecomBindPromptError(data);
if (String(data.error_code || '') === 'WECOM_BIND_SESSION_EXPIRED') {
openWecomLoginDialog(data);
wecomBindPrompt.value = null;
}
return;
}
wecomLoginDialog.value = null;
persistLoginUser(data);
@@ -671,10 +637,19 @@ const submitWecomCompleteBind = async () => {
window.history.replaceState({}, '', '/workspace');
await fetchHome();
} catch (e) {
console.error(e);
const err = e as BusinessError;
if (wecomBindPrompt.value) {
wecomBindPrompt.value.error = t('login.wecomLoginFailed');
const errorPayload = {
error: err.message,
error_code: err.code,
};
wecomBindPrompt.value.error = formatWecomBindPromptError(errorPayload);
if (String(err.code || '') === 'WECOM_BIND_SESSION_EXPIRED') {
openWecomLoginDialog(errorPayload);
wecomBindPrompt.value = null;
}
}
console.error(e);
} finally {
if (wecomBindPrompt.value) {
wecomBindPrompt.value.submitting = false;
@@ -706,33 +681,11 @@ const tryWecomCallbackLogin = async () => {
isWecomLoggingIn.value = true;
try {
const api = config.auth.wecom.loginApi || '/api/user/wecom/login';
const res = await fetch(api, {
const data = await requestJson<any>(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, state }),
});
const data = await res.json();
if (!res.ok) {
const rawError = String(data.error || '');
let friendly = rawError || t('login.wecomLoginFailed');
if (rawError.includes('Invalid or expired WeCom state')) {
friendly = t('login.wecomStateExpired');
} else if (rawError.includes('bind WeCom account') || rawError.includes('No linked account found')) {
friendly = t('login.wecomBindRequired');
} else if (rawError.includes('Account is disabled')) {
friendly = t('login.wecomAccountDisabled');
}
msg.error(friendly);
sessionStorage.removeItem('hxops_wecom_state');
if (String(data.error_code || '') === 'WECOM_BIND_INPUT_REQUIRED') {
openWecomBindPrompt(data);
clearWecomCallbackQuery();
return true;
}
openWecomLoginDialog(data);
clearWecomCallbackQuery();
return true;
}
wecomLoginDialog.value = null;
persistLoginUser(data);
@@ -741,10 +694,25 @@ const tryWecomCallbackLogin = async () => {
await fetchHome();
return true;
} catch (e) {
const err = e as BusinessError;
const rawError = String(err.message || '');
const errorCode = String(err.code || '');
let friendly = rawError || t('login.wecomLoginFailed');
if (rawError.includes('Invalid or expired WeCom state')) {
friendly = t('login.wecomStateExpired');
} else if (rawError.includes('bind WeCom account') || rawError.includes('No linked account found')) {
friendly = t('login.wecomBindRequired');
} else if (rawError.includes('Account is disabled')) {
friendly = t('login.wecomAccountDisabled');
}
console.error(e);
msg.error(t('login.wecomLoginFailed'));
msg.error(friendly);
sessionStorage.removeItem('hxops_wecom_state');
openWecomLoginDialog({ error: t('login.wecomLoginFailed') });
if (errorCode === 'WECOM_BIND_INPUT_REQUIRED') {
openWecomBindPrompt({ error: rawError, error_code: errorCode });
} else {
openWecomLoginDialog({ error: rawError || t('login.wecomLoginFailed'), error_code: errorCode });
}
clearWecomCallbackQuery();
return true;
} finally {
@@ -759,23 +727,17 @@ const handleRegister = async () => {
}
try {
const res = await fetch('/api/user/register', {
await requestJson('/api/user/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(registerForm.value)
});
if (res.ok) {
msg.success(t('register.success'));
showRegisterModal.value = false;
registerForm.value = { username: '', password: '', email: '', real_name: '', employee_id: '', phone_number: '' };
} else {
const err = await res.json();
msg.error(err.error || t('register.failed'));
}
msg.success(t('register.success'));
showRegisterModal.value = false;
registerForm.value = { username: '', password: '', email: '', real_name: '', employee_id: '', phone_number: '' };
} catch (e) {
console.error('Register error:', e);
msg.error(t('register.requestFailed'));
msg.error((e as Error)?.message || t('register.requestFailed'));
}
};
@@ -872,28 +834,14 @@ const captureOriginalProfile = () => {
originalProfile.value = { ...profileUser.value };
};
const parseErrorMessage = async (res: Response) => {
try {
const data = await res.json();
return data?.error || data?.message || '';
} catch {
try {
return await res.text();
} catch {
return '';
}
}
};
const fetchProfile = async () => {
isProfileLoading.value = true;
try {
const res = await fetch('/api/user/profile', { headers: getAuthHeaders() });
if (!res.ok) {
const data = await requestJson<any>('/api/user/profile', { headers: getAuthHeaders() });
if (!data) {
msg.error(t('workspace.profile.msg.loadFailed'));
return;
}
const data = await res.json();
profileUser.value = { ...profileUser.value, ...data };
if (data.language) locale.value = data.language;
if (data.theme_preference) {
@@ -952,24 +900,17 @@ const saveProfile = async () => {
try {
isProfileSaving.value = true;
const res = await fetch('/api/user/profile', {
await requestJson('/api/user/profile', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(payload),
});
if (!res.ok) {
const message = await parseErrorMessage(res);
msg.error(message || t('workspace.profile.msg.saveFailed'));
return;
}
msg.success(t('workspace.profile.msg.saved'));
captureOriginalProfile();
isProfileEditing.value = false;
} catch (e) {
console.error(e);
msg.error(t('workspace.profile.msg.saveFailed'));
msg.error((e as Error)?.message || t('workspace.profile.msg.saveFailed'));
} finally {
isProfileSaving.value = false;
}
@@ -982,7 +923,7 @@ const handleChangePassword = async () => {
}
try {
const res = await fetch('/api/user/change-password', {
await requestJson('/api/user/change-password', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
@@ -990,19 +931,12 @@ const handleChangePassword = async () => {
new_password: passwordForm.value.new,
}),
});
const data = await res.json();
if (!res.ok) {
msg.error(data.error || t('workspace.profile.msg.changePasswordFailed'));
return;
}
msg.success(t('profile.passwordChanged') || 'Password changed successfully');
passwordForm.value = { current: '', new: '', confirm: '' };
showPasswordModal.value = false;
} catch (e) {
console.error(e);
msg.error(t('workspace.profile.msg.changePasswordFailed'));
msg.error((e as Error)?.message || t('workspace.profile.msg.changePasswordFailed'));
}
};
@@ -1147,19 +1081,14 @@ const isLoadingHistories = ref(false);
const loadChatHistories = async () => {
isLoadingHistories.value = true;
try {
const res = await fetch('/api/agents', { headers: getAuthHeaders() });
if (!res.ok) { isLoadingHistories.value = false; return; }
const agentList = await res.json();
const agentList = await requestJson<any[]>('/api/agents', { headers: getAuthHeaders() });
const allHistories: ChatHistoryItem[] = [];
await Promise.all(
(Array.isArray(agentList) ? agentList : []).map(async (agent: any) => {
try {
const hRes = await fetch(`/api/chat/sessions?agent_id=${agent.id}`, { headers: getAuthHeaders() });
if (hRes.ok) {
const sessions = await hRes.json();
for (const s of sessions) {
allHistories.push({ ...s, agent_id: agent.id, agent_name: agent.name });
}
const sessions = await requestJson<any[]>(`/api/chat/sessions?agent_id=${agent.id}`, { headers: getAuthHeaders() });
for (const s of (Array.isArray(sessions) ? sessions : [])) {
allHistories.push({ ...s, agent_id: agent.id, agent_name: agent.name });
}
} catch {}
})
@@ -1214,7 +1143,7 @@ const handleWecomDeeplinkContext = async () => {
if (traceId && isLoggedIn.value) {
try {
const api = config.auth?.wecom?.deeplinkTraceApi || '/api/user/wecom/deeplink-opened';
await fetch(api, {
await requestJson(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ trace_id: traceId }),
@@ -1242,14 +1171,18 @@ const handleWecomDeeplinkContext = async () => {
// Favorites
const toggleFavorite = async (agentId: number) => {
if (favoriteAgentIds.value.includes(agentId)) {
// Remove
await fetch(`/api/user/favorites/${agentId}`, { method: 'DELETE', headers: getAuthHeaders() });
favoriteAgentIds.value = favoriteAgentIds.value.filter(id => id !== agentId);
} else {
// Add
await fetch(`/api/user/favorites/${agentId}`, { method: 'POST', headers: getAuthHeaders() });
favoriteAgentIds.value.push(agentId);
try {
if (favoriteAgentIds.value.includes(agentId)) {
// Remove
await requestJson(`/api/user/favorites/${agentId}`, { method: 'DELETE', headers: getAuthHeaders() });
favoriteAgentIds.value = favoriteAgentIds.value.filter(id => id !== agentId);
} else {
// Add
await requestJson(`/api/user/favorites/${agentId}`, { method: 'POST', headers: getAuthHeaders() });
favoriteAgentIds.value.push(agentId);
}
} catch (e) {
msg.error((e as Error)?.message || t('common.errorOccurred'));
}
};
@@ -1293,18 +1226,17 @@ const saveQuickQuestion = async () => {
const method = editingQuestionId.value ? 'PUT' : 'POST';
const res = await fetch(url, {
method: method,
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(newQuestion.value),
});
if (res.ok) {
try {
await requestJson(url, {
method: method,
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(newQuestion.value),
});
await fetchHome();
isAddingQuestion.value = false;
editingQuestionId.value = null;
} else {
msg.error(t('workspace.quickQuestions.msg.saveFailed'));
} catch (e) {
msg.error((e as Error)?.message || t('workspace.quickQuestions.msg.saveFailed'));
}
};
@@ -1316,10 +1248,14 @@ const removeQuickQuestion = async (id: number) => {
const confirmRemoveQuickQuestion = async () => {
if (pendingDeleteQuickQuestionId.value === null) return;
await fetch(`/api/user/quick-questions/${pendingDeleteQuickQuestionId.value}`, { method: 'DELETE', headers: getAuthHeaders() });
await fetchHome();
pendingDeleteQuickQuestionId.value = null;
showDeleteQuickQuestionDialog.value = false;
try {
await requestJson(`/api/user/quick-questions/${pendingDeleteQuickQuestionId.value}`, { method: 'DELETE', headers: getAuthHeaders() });
await fetchHome();
pendingDeleteQuickQuestionId.value = null;
showDeleteQuickQuestionDialog.value = false;
} catch (e) {
msg.error((e as Error)?.message || t('workspace.quickQuestions.msg.saveFailed'));
}
};
const cancelRemoveQuickQuestion = () => {
@@ -1330,13 +1266,17 @@ const cancelRemoveQuickQuestion = () => {
// Drag & Drop
const toggleSectionCollapse = async (section: LayoutSection) => {
section.collapsed = !section.collapsed;
// Save layout state
await fetch('/api/user/homepage-layout', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ layout: { sections: layoutSections.value } })
});
try {
await requestJson('/api/user/homepage-layout', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ layout: { sections: layoutSections.value } })
});
} catch (e) {
msg.error((e as Error)?.message || t('common.errorOccurred'));
}
};
const onDragStart = (index: number) => {
@@ -1354,13 +1294,17 @@ const onDrop = async (index: number) => {
layoutSections.value.splice(draggedSectionIndex.value, 1);
layoutSections.value.splice(index, 0, draggedItem);
draggedSectionIndex.value = null;
// Save layout
await fetch('/api/user/homepage-layout', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ layout: { sections: layoutSections.value } })
});
try {
await requestJson('/api/user/homepage-layout', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ layout: { sections: layoutSections.value } })
});
} catch (e) {
msg.error((e as Error)?.message || t('common.errorOccurred'));
}
};
const openAnnouncement = (ann: Announcement) => {