refactor(frontend): 重构前端第二版

This commit is contained in:
sophie committed 2026-06-11 13:47:06 +08:00
1 parent 2631f78b00
commit 4b562cfa82
205 files changed
+15399 -12015

No files matched your search

+140 -9
View File
@@ -1,12 +1,143 @@
/**
* shared/api/client.ts
* 转发至现有 api/client,后续迁移实现到此文件。
* 跨域 HTTP 客户端:envelope 解析、BusinessError、requestJson。
* 所有 feature API 层应通过此模块发起 JSON 请求。
*/
export {
BusinessError,
isEnvelope,
requestJson,
type ApiSuccessEnvelope,
type ApiErrorBody,
type ApiErrorEnvelope,
} from '@/api/client';
import { getAuthHeaders } from '@/shared/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}` : '';
const fallback = String(fallbackMessage || '').trim();
const isGenericFallback = (msg: string) => {
const v = msg.trim().toLowerCase();
if (!v) return true;
if (v === 'invalid request parameters' || v === 'invalid request parameters.') return true;
if (v === 'request failed' || v === 'request failed.') return true;
if (v.startsWith('http ')) return true;
return false;
};
if (key && i18n.global.te(key)) {
const localized = String(i18n.global.t(key));
if (normalizedCode === 'VALIDATION_INVALID_PARAM' && fallback && !isGenericFallback(fallback) && fallback !== localized) {
return `${localized} ${fallback}`;
}
if (
normalizedCode === 'AUTH_FORBIDDEN'
&& fallback
&& !isGenericFallback(fallback)
&& fallback.toLowerCase() !== 'forbidden'
&& fallback !== localized
) {
return fallback;
}
return localized;
}
if (fallback) return fallback;
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;
}
@@ -0,0 +1,133 @@
<script setup lang="ts">
/**
* shared/components/DeleteConfirmDialog.vue
* 通用删除确认弹窗。
*/
import { computed, onBeforeUnmount, watch } from 'vue';
import { useI18n } from 'vue-i18n';
interface Props {
modelValue: boolean;
title?: string;
message?: string;
confirmText?: string;
cancelText?: string;
confirmLoading?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
title: '',
message: '',
confirmText: '',
cancelText: '',
confirmLoading: false,
});
const emit = defineEmits<{
(e: 'update:modelValue', value: boolean): void;
(e: 'confirm'): void;
(e: 'cancel'): void;
}>();
const { t } = useI18n();
const resolvedTitle = computed(() => props.title || t('common.deleteDialog.defaultTitle'));
const resolvedMessage = computed(() => props.message || t('common.deleteDialog.defaultMessage'));
const resolvedCancelText = computed(() => props.cancelText || t('common.deleteDialog.cancel'));
const resolvedConfirmText = computed(() => props.confirmText || t('common.deleteDialog.confirm'));
const closeDialog = () => {
emit('update:modelValue', false);
};
const handleCancel = () => {
emit('cancel');
closeDialog();
};
const handleConfirm = () => {
emit('confirm');
};
const handleEscKey = (event: KeyboardEvent) => {
if (event.key === 'Escape' && props.modelValue) {
handleCancel();
}
};
watch(
() => props.modelValue,
(visible) => {
if (visible) {
document.addEventListener('keydown', handleEscKey);
return;
}
document.removeEventListener('keydown', handleEscKey);
},
{ immediate: true }
);
onBeforeUnmount(() => {
document.removeEventListener('keydown', handleEscKey);
});
</script>
<template>
<Teleport to="body">
<Transition name="delete-dialog-fade">
<div
v-if="modelValue"
class="dialog-overlay items-center"
@click.self="handleCancel"
>
<div class="dialog-panel max-w-[416px] rounded-lg px-6 pt-7 pb-5">
<div class="flex items-start gap-3">
<span class="dialog-icon-warning" aria-hidden="true">!</span>
<div class="min-w-0">
<h3 class="text-base font-semibold leading-6 text-primary">
{{ resolvedTitle }}
</h3>
<p class="section-desc mt-3 whitespace-pre-line">
{{ resolvedMessage }}
</p>
</div>
</div>
<div class="mt-6 flex justify-end gap-2">
<button type="button" class="btn-secondary btn-sm" @click="handleCancel">
{{ resolvedCancelText }}
</button>
<button
type="button"
class="btn-danger btn-sm"
:disabled="confirmLoading"
@click="handleConfirm"
>
{{ resolvedConfirmText }}
</button>
</div>
</div>
</div>
</Transition>
</Teleport>
</template>
<style scoped>
.delete-dialog-fade-enter-active,
.delete-dialog-fade-leave-active {
transition: opacity 0.18s ease;
}
.delete-dialog-fade-enter-from,
.delete-dialog-fade-leave-to {
opacity: 0;
}
@media (max-width: 768px) {
.dialog-panel {
max-width: 94vw;
padding: 20px 16px 16px;
}
}
</style>
@@ -0,0 +1,583 @@
<script setup lang="ts">
/**
* shared/components/FilePreviewModal.vue
* 文件预览弹窗(图片/PDF 等)。
*/
/**
* FilePreviewModal.vue
* 文件用途:文件预览弹窗,用于在聊天页预览来源文件内容
* 引用文件:vue, marked
* 逻辑关系:
* - 接收 ChatView 传入的 file(name/url)与弹窗显隐状态
* - 根据扩展名选择预览模式(markdown/image/iframe)
* - 对 Office 文档在可公网 HTTPS 访问时走 Office 在线预览,否则降级为打开/下载
*/
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { marked } from 'marked';
import * as XLSX from 'xlsx';
import VueOfficeDocx from '@vue-office/docx';
import VueOfficeExcel from '@vue-office/excel';
import VueOfficePdf from '@vue-office/pdf';
import '@vue-office/docx/lib/index.css';
import '@vue-office/excel/lib/index.css';
interface PreviewFile {
name: string;
url: string;
actualExt?: string;
}
interface ExcelPreviewData {
sheet_name: string;
sheets: string[];
columns: string[];
rows: Array<Array<string | number | boolean>>;
limit: number;
truncated: boolean;
}
type OfficeKind = 'docx' | 'excel' | 'pdf' | null;
type PreviewMode = 'markdown' | 'image' | 'iframe' | 'sheet' | 'office';
const props = defineProps<{
modelValue: boolean;
file: PreviewFile | null;
agentId?: number | null;
authHeaders?: Record<string, string>;
}>();
const emit = defineEmits<{
(e: 'update:modelValue', value: boolean): void;
}>();
const { t } = useI18n();
const isLoading = ref(false);
const error = ref('');
const markdownHtml = ref('');
const excelPreview = ref<ExcelPreviewData | null>(null);
const officeSrc = ref<string | ArrayBuffer | Blob>('');
const officeKind = ref<OfficeKind>(null);
const officeObjectUrl = ref<string>('');
const officeRenderKey = ref(0);
/**
* 从 URL 或文件名中提取扩展名。
* - 会先去掉 query 参数(兼容签名链接)。
* - 返回小写扩展名(不含点号)。
*/
const getExt = (raw: string) => {
const clean = (raw.split('?')[0] ?? '').toLowerCase();
const parts = clean.split('/');
const lastPart = parts[parts.length - 1] ?? '';
const i = lastPart.lastIndexOf('.');
return i >= 0 ? lastPart.slice(i + 1) : '';
};
const ext = computed(() => {
const actual = getExt(props.file?.actualExt || '');
if (actual) return actual;
// Display name extension has higher priority than URL.
const byName = getExt(props.file?.name || '');
if (byName) return byName;
return getExt(props.file?.url || '');
});
const preferredMode = computed<PreviewMode>(() => {
if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp'].includes(ext.value)) return 'image';
if (['md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'].includes(ext.value)) return 'markdown';
if (['xlsx', 'xls'].includes(ext.value)) return 'sheet';
if (['docx'].includes(ext.value)) return 'office';
if (['doc', 'ppt', 'pptx', 'pdf'].includes(ext.value)) return 'iframe';
return 'iframe';
});
const resolvedMode = ref<PreviewMode>('iframe');
const needsOfficeFallback = computed(() => {
// We no longer need fallback for doc/ppt/pptx because they are converted to PDF by the backend
return false;
});
/**
* 计算 iframe 预览地址。
* - pdf/doc/docx 优先走后端同源代理地址;
* - Office 文档且满足公网 HTTPS 时,走微软在线预览;
* - 其余返回原始 URL,由浏览器自行处理。
*/
const iframeSrc = computed(() => {
if (!props.file?.url) return '';
if (officeObjectUrl.value) return officeObjectUrl.value;
if (!props.agentId) return '';
if (['pdf', 'doc', 'ppt', 'pptx'].includes(ext.value)) {
// These formats must use the authenticated fetch -> blob flow only.
// Never fallback to a protected iframe URL, otherwise it returns Unauthorized.
return officeObjectUrl.value;
}
return props.file.url;
});
const imageSrc = computed(() => officeObjectUrl.value || props.file?.url || '');
const officePreviewExts = new Set(['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx']);
const close = () => emit('update:modelValue', false);
const previewTooLarge = computed(() => /file too large for online preview/i.test(error.value));
const clearOfficeObjectUrl = () => {
if (officeObjectUrl.value) {
URL.revokeObjectURL(officeObjectUrl.value);
officeObjectUrl.value = '';
}
officeSrc.value = '';
officeKind.value = null;
};
const extractErrorMessage = (payload: any, fallback: string) => {
if (!payload) return fallback;
if (typeof payload === 'string' && payload.trim()) return payload.trim();
if (typeof payload?.message === 'string' && payload.message.trim()) return payload.message.trim();
if (typeof payload?.error === 'string' && payload.error.trim()) return payload.error.trim();
if (typeof payload?.error?.message === 'string' && payload.error.message.trim()) return payload.error.message.trim();
if (typeof payload?.detail === 'string' && payload.detail.trim()) return payload.detail.trim();
return fallback;
};
const readErrorMessage = async (res: Response) => {
const fallback = `HTTP ${res.status}`;
const contentType = (res.headers.get('content-type') || '').toLowerCase();
if (contentType.includes('application/json')) {
const payload = await res.json().catch(() => null);
return extractErrorMessage(payload, fallback);
}
const text = await res.text().catch(() => '');
return extractErrorMessage(text, fallback);
};
const applyExcelPreview = (buffer: ArrayBuffer) => {
const workbook = XLSX.read(buffer, { type: 'array' });
if (!workbook.SheetNames.length) {
throw new Error('workbook has no sheets');
}
const sheetName = workbook.SheetNames[0] || 'Sheet1';
const worksheet = workbook.Sheets[sheetName];
if (!worksheet) {
throw new Error(`worksheet not found: ${sheetName}`);
}
const matrix = XLSX.utils.sheet_to_json<(string | number | boolean)[]>(worksheet, {
header: 1,
raw: false,
defval: '',
});
const limit = 100;
const rows = matrix.slice(0, limit).map((row) => row.map((cell) => cell ?? ''));
const maxCols = rows.reduce((max, row) => Math.max(max, row.length), 0);
const normalizedRows = rows.map((row) =>
row.length < maxCols ? [...row, ...Array(maxCols - row.length).fill('')] : row
);
excelPreview.value = {
sheet_name: sheetName,
sheets: workbook.SheetNames,
columns: Array.from({ length: maxCols }, (_, i) => `COL_${i + 1}`),
rows: normalizedRows,
limit,
truncated: matrix.length > limit,
};
};
const tryApplyExcelPreview = (buffer: ArrayBuffer) => {
try {
applyExcelPreview(buffer);
return true;
} catch {
return false;
}
};
const loadSheetPreview = async () => {
if (!props.file?.url) return;
if (!props.agentId) throw new Error('agent_id is required for excel preview');
const params = new URLSearchParams({
agent_id: String(props.agentId),
url: props.file.url,
name: props.file.name || '',
});
const res = await fetch(`/api/chat/preview-excel?${params.toString()}`, {
headers: props.authHeaders || {},
});
if (!res.ok) {
throw new Error(await readErrorMessage(res));
}
excelPreview.value = await res.json();
};
const loadOfficeContent = async () => {
if (!props.file?.url) return;
if (!props.agentId) throw new Error('agent_id is required for office preview');
const params = new URLSearchParams({
agent_id: String(props.agentId),
url: props.file.url,
name: props.file.name || '',
});
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
headers: props.authHeaders || {},
});
if (!res.ok) {
throw new Error(await readErrorMessage(res));
}
const buffer = await res.arrayBuffer();
clearOfficeObjectUrl();
officeSrc.value = buffer;
officeRenderKey.value += 1;
if (ext.value === 'docx' || ext.value === 'doc') officeKind.value = 'docx';
else if (ext.value === 'xlsx' || ext.value === 'xls') officeKind.value = 'excel';
else officeKind.value = null;
};
const loadPdfContent = async (): Promise<'iframe' | 'office' | 'sheet'> => {
if (!props.file?.url) return 'iframe';
if (!props.agentId) throw new Error('agent_id is required for pdf preview');
if (ext.value === 'doc') {
try {
await loadSheetPreview();
return 'sheet';
} catch {
// Not an excel-disguised-as-doc file, continue with the normal document preview flow.
}
}
const params = new URLSearchParams({
agent_id: String(props.agentId),
url: props.file.url,
name: props.file.name || '',
});
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
headers: props.authHeaders || {},
});
if (!res.ok) {
throw new Error(await readErrorMessage(res));
}
const blob = await res.blob();
clearOfficeObjectUrl();
const buffer = await blob.arrayBuffer();
const actualExt = (res.headers.get('X-Preview-Actual-Ext') || '').toLowerCase();
const blobType = (blob.type || '').toLowerCase();
const effectiveExt = actualExt || ext.value;
const isDocxPayload = actualExt === 'docx' || blobType.includes('wordprocessingml.document');
const isExcelPayload = ['xlsx', 'xls'].includes(actualExt) || blobType.includes('spreadsheetml.sheet') || blobType.includes('application/vnd.ms-excel');
if (isExcelPayload) {
if (tryApplyExcelPreview(buffer)) {
return 'sheet';
}
await loadSheetPreview();
return 'sheet';
}
if (!blobType.includes('pdf') && tryApplyExcelPreview(buffer)) {
return 'sheet';
}
if (isDocxPayload) {
officeSrc.value = buffer;
officeRenderKey.value += 1;
officeKind.value = 'docx';
return 'office';
}
if (!blobType.includes('pdf') && officePreviewExts.has(effectiveExt)) {
throw new Error('当前原始文件暂不支持直接预览,已阻止浏览器自动下载');
}
let fallbackType = 'application/octet-stream';
if (ext.value === 'pdf' || ['doc', 'ppt', 'pptx'].includes(ext.value)) fallbackType = 'application/pdf';
else if (ext.value === 'docx') fallbackType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
const effectiveBlob = blob.type ? blob : new Blob([blob], { type: fallbackType });
if (
['doc', 'ppt', 'pptx'].includes(ext.value)
&& effectiveBlob.type.toLowerCase().includes('pdf')
) {
officeSrc.value = effectiveBlob;
officeRenderKey.value += 1;
officeKind.value = 'pdf';
return 'office';
}
officeObjectUrl.value = URL.createObjectURL(effectiveBlob);
return 'iframe';
};
const loadBinaryContent = async () => {
if (!props.file?.url) return;
if (!props.agentId) throw new Error('agent_id is required for binary preview');
const params = new URLSearchParams({
agent_id: String(props.agentId),
url: props.file.url,
name: props.file.name || '',
});
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
headers: props.authHeaders || {},
});
if (!res.ok) {
throw new Error(await readErrorMessage(res));
}
const blob = await res.blob();
clearOfficeObjectUrl();
officeObjectUrl.value = URL.createObjectURL(blob);
};
/**
* 在弹窗/文件变化时加载预览内容。
* 流程:
* 1) 重置状态并按扩展名确定优先模式;
* 2) Excel 走后端 /preview-excel 返回表格数据;
* 3) 文本类走后端 /preview-text 返回文本并渲染 Markdown;
* 4) 其他格式交由 iframe 或降级策略处理;
* 5) 失败写入 error,前端展示可读错误信息。
*/
const loadContent = async () => {
error.value = '';
markdownHtml.value = '';
excelPreview.value = null;
clearOfficeObjectUrl();
if (!props.modelValue || !props.file) return;
if (!props.file?.url) return;
resolvedMode.value = preferredMode.value;
if (['pdf', 'doc', 'docx', 'ppt', 'pptx'].includes(ext.value) && preferredMode.value === 'iframe') {
if (needsOfficeFallback.value) {
resolvedMode.value = 'iframe';
return;
}
isLoading.value = true;
try {
resolvedMode.value = await loadPdfContent();
} catch (e: any) {
error.value = e?.message || `Failed to preview ${ext.value}`;
resolvedMode.value = 'iframe';
} finally {
isLoading.value = false;
}
return;
}
if (preferredMode.value === 'office' && !needsOfficeFallback.value) {
isLoading.value = true;
try {
await loadOfficeContent();
if (!officeKind.value) {
throw new Error(`Unsupported office preview extension: ${ext.value}`);
}
resolvedMode.value = 'office';
} catch (e: any) {
error.value = e?.message || 'Failed to preview office file';
resolvedMode.value = 'iframe';
} finally {
isLoading.value = false;
}
return;
}
if (preferredMode.value === 'sheet') {
isLoading.value = true;
try {
await loadSheetPreview();
resolvedMode.value = 'sheet';
} catch (e: any) {
error.value = e?.message || 'Failed to preview excel';
resolvedMode.value = 'iframe';
} finally {
isLoading.value = false;
}
return;
}
if (preferredMode.value === 'image' || (preferredMode.value === 'iframe' && !/^https?:\/\//i.test(props.file.url || ''))) {
isLoading.value = true;
try {
await loadBinaryContent();
resolvedMode.value = preferredMode.value === 'image' ? 'image' : 'iframe';
} catch (e: any) {
error.value = e?.message || 'Failed to load file preview';
resolvedMode.value = preferredMode.value === 'image' ? 'image' : 'iframe';
} finally {
isLoading.value = false;
}
return;
}
if (preferredMode.value !== 'markdown') return;
isLoading.value = true;
try {
if (!props.agentId) {
throw new Error('agent_id is required for text preview');
}
const params = new URLSearchParams({
agent_id: String(props.agentId),
url: props.file.url,
name: props.file.name || '',
ext: ext.value || '',
});
const res = await fetch(`/api/chat/preview-text?${params.toString()}`, {
headers: props.authHeaders || {},
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err?.error || `HTTP ${res.status}`);
}
const payload = await res.json();
const text = String(payload?.content || '');
markdownHtml.value = marked.parse(text) as string;
} catch (e: any) {
error.value = e?.message || 'Failed to load file';
} finally {
isLoading.value = false;
}
};
/**
* 响应式重载:
* - 弹窗显隐变化;
* - 文件 URL 变化;
* - 文件名变化。
*/
watch(
() => [props.modelValue, props.file?.url, props.file?.name],
() => {
loadContent();
},
{ immediate: true }
);
watch(
() => props.modelValue,
(v) => {
if (!v) {
clearOfficeObjectUrl();
}
}
);
</script>
<template>
<div v-if="modelValue && file" class="dialog-overlay dialog-overlay--z80 items-center">
<div class="dialog-panel max-w-5xl h-[85vh] overflow-hidden">
<div class="dialog-header dialog-header--compact items-start">
<div class="min-w-0">
<div class="text-sm font-medium text-slate-500 dark:text-slate-400 tracking-wide">{{ t('filePreview.title') }}</div>
<div class="mt-1 font-semibold text-slate-900 dark:text-slate-100 break-words">{{ file.name }}</div>
</div>
<button type="button" class="btn-secondary shrink-0" @click="close">{{ t('common.close') }}</button>
</div>
<div class="dialog-preview-body">
<div v-if="isLoading" class="text-sm text-muted">{{ t('common.loading') }}</div>
<div v-else-if="error" class="alert-ds alert-error text-sm">
<template v-if="previewTooLarge">
{{ t('filePreview.tooLarge') }}
</template>
<template v-else>
{{ t('filePreview.previewFailed') }}{{ error }}
</template>
</div>
<div
v-else-if="resolvedMode === 'markdown'"
class="prose prose-sm max-w-none dialog-preview-frame p-5"
v-html="markdownHtml"
></div>
<div
v-else-if="resolvedMode === 'sheet' && excelPreview"
class="dialog-preview-frame h-full p-4 overflow-auto"
>
<div class="mb-3 text-xs text-muted">
Sheet: {{ excelPreview.sheet_name }} | Rows: {{ excelPreview.rows.length }}
<span v-if="excelPreview.truncated"> (truncated)</span>
</div>
<table class="min-w-full text-xs border-collapse">
<thead>
<tr>
<th
v-for="(col, i) in excelPreview.columns"
:key="`h-${i}`"
class="sticky top-0 bg-surface-soft border border-default px-2 py-1 text-left font-semibold text-secondary"
>
{{ col }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, ri) in excelPreview.rows" :key="`r-${ri}`">
<td
v-for="(cell, ci) in row"
:key="`c-${ri}-${ci}`"
class="border border-default px-2 py-1 align-top whitespace-pre-wrap break-words text-secondary"
>
{{ cell }}
</td>
</tr>
</tbody>
</table>
</div>
<div
v-else-if="resolvedMode === 'office' && officeKind"
class="dialog-preview-frame h-full p-2 overflow-auto"
>
<VueOfficeDocx
v-if="officeKind === 'docx'"
:key="`docx-${officeRenderKey}`"
:src="officeSrc"
@rendered="error = ''"
@error="error = 'DOCX render failed'"
style="height: 100%; width: 100%;"
/>
<VueOfficeExcel
v-else-if="officeKind === 'excel'"
:key="`excel-${officeRenderKey}`"
:src="officeSrc"
style="height: 100%; width: 100%;"
/>
<VueOfficePdf
v-else-if="officeKind === 'pdf'"
:key="`pdf-${officeRenderKey}`"
:src="officeSrc"
style="height: 100%; width: 100%;"
/>
</div>
<div v-else-if="resolvedMode === 'image'" class="dialog-preview-frame h-full flex items-center justify-center p-2">
<img :src="imageSrc" :alt="file.name" class="max-w-full max-h-full object-contain" />
</div>
<div
v-else-if="['pdf', 'doc', 'ppt', 'pptx'].includes(ext) && officeObjectUrl"
class="dialog-preview-frame h-full overflow-hidden"
>
<iframe
:src="officeObjectUrl"
class="w-full h-full min-h-[480px] border-0"
allow="clipboard-read; clipboard-write"
></iframe>
</div>
<div
v-else-if="needsOfficeFallback"
class="dialog-preview-frame h-full p-6"
>
<!-- Graceful fallback for private/non-HTTPS Office links:
show actions instead of an empty iframe. -->
<div class="text-sm font-semibold text-secondary">Preview not available for this file URL</div>
<div class="mt-2 text-sm text-muted">
This Office file uses a private or non-HTTPS link, so online preview cannot render it.
</div>
</div>
<iframe
v-else
:src="iframeSrc"
class="dialog-preview-frame w-full h-full min-h-[480px]"
allow="clipboard-read; clipboard-write"
></iframe>
</div>
</div>
</div>
</template>
@@ -0,0 +1,207 @@
<script setup lang="ts">
/**
* shared/components/GeneralFeedbackDialog.vue
* 通用意见反馈提交弹窗。
*/
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { MessageSquareText, X } from 'lucide-vue-next';
interface Props {
modelValue: boolean;
authHeaders?: Record<string, string>;
sourcePage?: string;
chatLogId?: number | null;
}
const props = withDefaults(defineProps<Props>(), {
authHeaders: () => ({}),
sourcePage: 'unknown',
chatLogId: null,
});
const emit = defineEmits<{
(e: 'update:modelValue', value: boolean): void;
(e: 'submitted'): void;
}>();
const { t, locale } = useI18n({ useScope: 'global' });
const typeOptions = computed(() => [
t('feedback.type.featureSuggestion'),
t('feedback.type.issueReport'),
t('feedback.type.experienceOptimization'),
]);
const moduleOptions = computed(() => [
t('feedback.module.knowledgeBase'),
t('feedback.module.general'),
t('feedback.module.workflow'),
t('feedback.module.accountPermission'),
]);
const selectedType = ref<string>(t('feedback.type.featureSuggestion'));
const selectedModule = ref<string>(t('feedback.module.knowledgeBase'));
const content = ref('');
const submitting = ref(false);
const error = ref('');
const canSubmit = computed(() => content.value.trim().length > 0 && !submitting.value);
const closeDialog = () => {
emit('update:modelValue', false);
};
const resetForm = () => {
selectedType.value = t('feedback.type.featureSuggestion');
selectedModule.value = t('feedback.module.knowledgeBase');
content.value = '';
error.value = '';
submitting.value = false;
};
watch(
() => props.modelValue,
(visible) => {
if (visible) resetForm();
},
);
watch(locale, () => {
if (props.modelValue) {
resetForm();
}
});
const submitFeedback = async () => {
if (!canSubmit.value) {
error.value = t('feedback.msg.fillContent');
return;
}
submitting.value = true;
error.value = '';
try {
const payload: Record<string, unknown> = {
feedback_type: selectedType.value,
feedback_module: selectedModule.value,
content: content.value.trim(),
source_page: props.sourcePage,
};
if (props.chatLogId !== null && props.chatLogId !== undefined) {
payload.chat_log_id = props.chatLogId;
}
const res = await fetch('/api/user/feedback', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...props.authHeaders,
},
body: JSON.stringify(payload),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
error.value = data?.error || t('feedback.msg.submitFailed');
return;
}
emit('submitted');
closeDialog();
} catch {
error.value = t('feedback.msg.submitFailed');
} finally {
submitting.value = false;
}
};
</script>
<template>
<div
v-if="modelValue"
class="dialog-overlay dialog-overlay--z80"
>
<div class="dialog-panel max-w-2xl max-h-[92vh]">
<div class="dialog-header">
<h3 class="section-title text-2xl">{{ t('feedback.title') }}</h3>
<button
type="button"
class="btn-icon-ds"
aria-label="Close"
@click="closeDialog"
>
<X class="h-5 w-5" />
</button>
</div>
<div class="dialog-body space-y-5">
<div class="space-y-1.5">
<label class="label-field block">{{ t('feedback.labels.type') }}</label>
<div class="segment-control segment-control--cols-3 segment-control--md" role="radiogroup" :aria-label="t('feedback.labels.type')">
<button
v-for="item in typeOptions"
:key="item"
type="button"
role="radio"
:aria-checked="selectedType === item"
class="segment-item"
:class="selectedType === item ? 'segment-item--active' : ''"
@click="selectedType = item"
>
{{ item }}
</button>
</div>
</div>
<div class="space-y-1.5">
<label class="label-field block">{{ t('feedback.labels.module') }}</label>
<select v-model="selectedModule" class="input-field text-base">
<option v-for="item in moduleOptions" :key="item" :value="item">{{ item }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field block">
{{ t('feedback.labels.content') }}<span class="ml-0.5 text-red-500">*</span>
</label>
<textarea
v-model="content"
rows="5"
maxlength="2000"
class="input-field resize-none text-base"
:placeholder="t('feedback.placeholder.content')"
/>
<div class="mt-2 flex items-center justify-between">
<div v-if="error" class="text-base text-red-600">{{ error }}</div>
<div v-else class="text-base text-muted"> </div>
<div class="text-base text-muted">{{ content.length }}/2000</div>
</div>
</div>
</div>
<div class="dialog-footer">
<button
type="button"
class="btn-ghost"
:disabled="submitting"
@click="closeDialog"
>
{{ t('feedback.cancel') }}
</button>
<button
type="button"
class="btn-primary"
:disabled="!canSubmit"
@click="submitFeedback"
>
<MessageSquareText class="h-5 w-5" />
{{ submitting ? t('feedback.submitting') : t('feedback.submit') }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,41 @@
<script setup lang="ts">
import { ref } from 'vue'
defineProps<{ msg: string }>()
const count = ref(0)
</script>
<template>
<h1>{{ msg }}</h1>
<div class="card">
<button type="button" @click="count++">count is {{ count }}</button>
<p>
Edit
<code>components/HelloWorld.vue</code> to test HMR
</p>
</div>
<p>
Check out
<a href="https://vuejs.org/guide/quick-start.html#local" target="_blank"
>create-vue</a
>, the official Vue + Vite starter
</p>
<p>
Learn more about IDE Support for Vue in the
<a
href="https://vuejs.org/guide/scaling-up/tooling.html#ide-support"
target="_blank"
>Vue Docs Scaling up Guide</a
>.
</p>
<p class="read-the-docs">Click on the Vite and Vue logos to learn more</p>
</template>
<style scoped>
.read-the-docs {
color: #888;
}
</style>
@@ -0,0 +1,186 @@
<script setup lang="ts">
/**
* shared/components/LevelMessageDialog.vue
* 全局分级消息弹窗(info/success/warning/error)。
*/
import { computed, onBeforeUnmount, watch } from 'vue';
import { Check, Info, AlertTriangle, XCircle, X } from 'lucide-vue-next';
type MessageLevel = 'success' | 'info' | 'warning' | 'error';
interface Props {
modelValue: boolean;
level?: MessageLevel;
title?: string;
message?: string;
closeOnMask?: boolean;
closeOnEsc?: boolean;
autoCloseMs?: number;
}
const props = withDefaults(defineProps<Props>(), {
level: 'info',
title: '',
message: '',
closeOnMask: true,
closeOnEsc: true,
autoCloseMs: 5000,
});
const emit = defineEmits<{
(e: 'update:modelValue', value: boolean): void;
(e: 'close'): void;
}>();
const ALERT_CLASS: Record<MessageLevel, string> = {
success: 'alert-ds alert-success',
info: 'alert-ds alert-info',
warning: 'alert-ds alert-warning',
error: 'alert-ds alert-error',
};
const ICON_MAP: Record<MessageLevel, typeof Check> = {
success: Check,
info: Info,
warning: AlertTriangle,
error: XCircle,
};
const DEFAULT_TITLE_MAP: Record<MessageLevel, string> = {
success: 'Success',
info: 'Info',
warning: 'Warning',
error: 'Error',
};
const panelClass = computed(() => ALERT_CLASS[props.level]);
const resolvedIcon = computed(() => ICON_MAP[props.level]);
const resolvedTitle = computed(() => props.title || DEFAULT_TITLE_MAP[props.level]);
const resolvedMessage = computed(() => props.message || '');
let autoCloseTimer: ReturnType<typeof setTimeout> | null = null;
const clearAutoCloseTimer = () => {
if (!autoCloseTimer) return;
clearTimeout(autoCloseTimer);
autoCloseTimer = null;
};
const closeDialog = () => {
clearAutoCloseTimer();
emit('update:modelValue', false);
emit('close');
};
const handleMaskClose = () => {
if (!props.closeOnMask) return;
closeDialog();
};
const handleEscKey = (event: KeyboardEvent) => {
if (!props.closeOnEsc) return;
if (event.key === 'Escape' && props.modelValue) {
closeDialog();
}
};
watch(
() => [props.modelValue, props.level, props.title, props.message, props.autoCloseMs],
([visible]) => {
clearAutoCloseTimer();
if (!visible) {
document.removeEventListener('keydown', handleEscKey);
return;
}
document.addEventListener('keydown', handleEscKey);
if (props.autoCloseMs > 0) {
autoCloseTimer = setTimeout(() => {
closeDialog();
}, props.autoCloseMs);
}
},
{ immediate: true }
);
onBeforeUnmount(() => {
clearAutoCloseTimer();
document.removeEventListener('keydown', handleEscKey);
});
</script>
<template>
<Transition name="level-dialog-fade">
<div
v-if="modelValue"
class="dialog-overlay dialog-overlay--z110 items-center"
@click.self="handleMaskClose"
>
<div
class="level-dialog-panel w-full max-w-[430px] rounded-2xl border shadow-elevated px-9 py-8 relative"
:class="panelClass"
>
<button
type="button"
class="btn-icon-ds absolute top-4 right-4"
@click="closeDialog"
aria-label="close dialog"
>
<X class="w-4 h-4" />
</button>
<div class="flex items-start gap-4 pr-8 min-h-0">
<span class="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full border-2 border-current mt-0.5">
<component :is="resolvedIcon" class="h-4 w-4" />
</span>
<div class="min-w-0 w-full">
<h3 class="text-base font-semibold leading-6">
{{ resolvedTitle }}
</h3>
<p class="level-dialog-message mt-3 text-sm leading-7 whitespace-pre-line break-words opacity-90">
{{ resolvedMessage }}
</p>
</div>
</div>
</div>
</div>
</Transition>
</template>
<style scoped>
.level-dialog-fade-enter-active,
.level-dialog-fade-leave-active {
transition: opacity 0.2s ease;
}
.level-dialog-fade-enter-from,
.level-dialog-fade-leave-to {
opacity: 0;
}
.level-dialog-panel {
max-height: min(80vh, 640px);
display: flex;
flex-direction: column;
}
.level-dialog-message {
max-height: min(48vh, 320px);
overflow: auto;
padding-right: 0.25rem;
}
@media (max-width: 768px) {
.level-dialog-panel {
max-width: 94vw;
max-height: 82vh;
padding: 20px 18px;
}
.level-dialog-message {
max-height: 52vh;
}
}
</style>
@@ -0,0 +1,120 @@
<script setup lang="ts">
/**
* shared/components/LocaleToggleButton.vue
* 语言切换按钮。
*/
import { computed, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { Check, Languages } from 'lucide-vue-next';
const props = withDefaults(
defineProps<{
floating?: boolean;
/** header:登录顶栏;sidebar:Chat 侧栏底栏图标行 */
variant?: 'header' | 'sidebar';
/** sidebar 折叠栏用 md 图标 */
iconSize?: 'sm' | 'md';
}>(),
{
floating: false,
variant: 'header',
iconSize: 'sm',
},
);
const { locale, t } = useI18n();
const open = ref(false);
const rootRef = ref<HTMLElement | null>(null);
/** 语言菜单文案固定,不随当前 locale 翻译(与产品约定一致) */
const LOCALE_PICKER_OPTIONS = [
{ value: 'zh-CN', label: '简体中文' },
{ value: 'zh-TW', label: '繁體中文' },
{ value: 'en', label: 'English' },
{ value: 'th', label: 'ไทย' },
] as const;
const buttonClass = computed(() => {
if (props.variant === 'sidebar') {
return [
'flex items-center justify-center transition-colors hover:text-secondary',
open.value ? 'text-brand-600' : 'text-muted',
];
}
if (props.floating) return 'header-locale-btn header-locale-btn--floating';
return 'header-locale-btn';
});
const iconClass = computed(() => {
if (props.variant === 'header') return 'h-4 w-4 md:h-5 md:w-5';
return props.iconSize === 'md' ? 'h-5 w-5' : 'h-4 w-4';
});
const menuClass = computed(() =>
props.variant === 'sidebar'
? 'header-locale-menu header-locale-menu--sidebar'
: 'header-locale-menu',
);
const selectLocale = (code: string) => {
locale.value = code;
open.value = false;
};
const onDocumentClick = (event: MouseEvent) => {
if (!rootRef.value?.contains(event.target as Node)) {
open.value = false;
}
};
watch(open, (isOpen) => {
if (isOpen) {
document.addEventListener('click', onDocumentClick);
return;
}
document.removeEventListener('click', onDocumentClick);
});
onBeforeUnmount(() => {
document.removeEventListener('click', onDocumentClick);
});
</script>
<template>
<div ref="rootRef" class="relative shrink-0">
<button
type="button"
:class="buttonClass"
:title="t('workspace.languageLabel')"
:aria-label="t('workspace.languageLabel')"
:aria-expanded="open"
aria-haspopup="listbox"
@click.stop="open = !open"
>
<Languages :class="iconClass" />
</button>
<div
v-if="open"
:class="menuClass"
role="listbox"
:aria-label="t('workspace.languageLabel')"
@click.stop
>
<button
v-for="item in LOCALE_PICKER_OPTIONS"
:key="item.value"
type="button"
role="option"
:aria-selected="locale === item.value"
class="header-locale-menu__item"
:class="{ 'header-locale-menu__item--active': locale === item.value }"
@click="selectLocale(item.value)"
>
<span>{{ item.label }}</span>
<Check v-if="locale === item.value" class="h-4 w-4 shrink-0 text-brand-600" aria-hidden="true" />
</button>
</div>
</div>
</template>
@@ -0,0 +1,78 @@
<script setup lang="ts">
/**
* shared/components/ScheduleRunsPanel.vue
* 排程执行记录列表面板(workspace 嵌入用)。
*/
import { onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { listWorkspaceScheduleRuns, workspaceRunExcelUrl, type ScheduleRun } from '@/features/workspace/api/schedule.api';
const { t } = useI18n();
const isLoading = ref(false);
const error = ref('');
const runs = ref<ScheduleRun[]>([]);
const loadRuns = async () => {
isLoading.value = true;
error.value = '';
try {
runs.value = await listWorkspaceScheduleRuns();
} catch (e: any) {
error.value = e?.message || t('scheduleRuns.msg.loadFailed');
} finally {
isLoading.value = false;
}
};
onMounted(() => {
void loadRuns();
});
</script>
<template>
<div class="admin-table-section mt-6 p-5">
<div class="mb-4 flex items-center justify-between">
<h3 class="section-title">{{ t('scheduleRuns.title') }}</h3>
<button type="button" class="btn-secondary btn-sm" @click="loadRuns">
{{ t('scheduleRuns.refresh') }}
</button>
</div>
<p class="section-desc mb-3">{{ t('scheduleRuns.tip') }}</p>
<div v-if="isLoading" class="py-6 text-sm text-muted">{{ t('scheduleRuns.loading') }}</div>
<div v-else-if="error" class="py-6 text-sm text-rose-500">{{ error }}</div>
<div v-else-if="runs.length === 0" class="py-6 text-sm text-muted">{{ t('scheduleRuns.empty') }}</div>
<div v-else class="admin-table-wrap">
<table class="admin-table min-w-[920px] text-sm">
<thead>
<tr>
<th class="px-2 py-2">{{ t('scheduleRuns.columns.runNo') }}</th>
<th class="px-2 py-2">{{ t('scheduleRuns.columns.schedule') }}</th>
<th class="px-2 py-2">{{ t('scheduleRuns.columns.start') }}</th>
<th class="px-2 py-2">{{ t('scheduleRuns.columns.end') }}</th>
<th class="px-2 py-2">{{ t('scheduleRuns.columns.status') }}</th>
<th class="px-2 py-2">{{ t('scheduleRuns.columns.total') }}</th>
<th class="px-2 py-2">{{ t('scheduleRuns.columns.success') }}</th>
<th class="px-2 py-2">{{ t('scheduleRuns.columns.failed') }}</th>
<th class="px-2 py-2">Excel</th>
</tr>
</thead>
<tbody>
<tr v-for="run in runs" :key="run.id">
<td class="px-2 py-2 text-secondary">{{ run.run_no }}</td>
<td class="px-2 py-2 text-secondary">{{ run.schedule_name || '-' }}</td>
<td class="px-2 py-2 text-secondary">{{ run.started_at || '-' }}</td>
<td class="px-2 py-2 text-secondary">{{ run.finished_at || '-' }}</td>
<td class="px-2 py-2 text-secondary">{{ run.status }}</td>
<td class="px-2 py-2 text-secondary">{{ run.total_count }}</td>
<td class="px-2 py-2 text-secondary">{{ run.success_count }}</td>
<td class="px-2 py-2 text-secondary">{{ run.failed_count }}</td>
<td class="px-2 py-2">
<a class="text-brand-600 hover:underline" :href="workspaceRunExcelUrl(run.id)" target="_blank">{{ t('scheduleRuns.viewExcel') }}</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
@@ -0,0 +1,38 @@
<script setup lang="ts">
/**
* shared/components/ThemeToggleButton.vue
* 明暗主题切换按钮。
*/
import { computed } from 'vue';
import { Sun, Moon } from 'lucide-vue-next';
import { useTheme } from '@/shared/composables/useTheme';
import { useI18n } from 'vue-i18n';
const props = withDefaults(defineProps<{ floating?: boolean }>(), {
floating: false,
});
const { t } = useI18n();
const { appliedTheme, toggleLightDark } = useTheme();
const isDarkTheme = computed(() => appliedTheme.value === 'dark');
const buttonClass = computed(() =>
props.floating
? 'theme-toggle-btn theme-toggle-btn--floating'
: 'theme-toggle-btn theme-toggle-btn--inline'
);
</script>
<template>
<button
type="button"
:class="buttonClass"
:title="isDarkTheme ? (t('theme.switchToLight') || 'Switch to light mode') : (t('theme.switchToDark') || 'Switch to dark mode')"
:aria-label="isDarkTheme ? (t('theme.switchToLight') || 'Switch to light mode') : (t('theme.switchToDark') || 'Switch to dark mode')"
@click="toggleLightDark"
>
<Sun v-if="isDarkTheme" class="w-4 h-4 md:w-5 md:h-5" />
<Moon v-else class="w-4 h-4 md:w-5 md:h-5" />
</button>
</template>
@@ -0,0 +1,83 @@
<script setup lang="ts">
/**
* shared/components/kb/DifyHealthDialog.vue
* 知识库 Dify 健康检查弹窗(KB 暂缓 redesign)。
*/
import { ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { getKbDifyHealth, type KbDifyHealth } from '@/api/kb';
const props = defineProps<{ open: boolean }>();
const emit = defineEmits<{ close: []; error: [message: string] }>();
const { t } = useI18n();
const loading = ref(false);
const payload = ref<KbDifyHealth | null>(null);
const close = () => emit('close');
const loadHealth = async () => {
loading.value = true;
payload.value = await getKbDifyHealth();
loading.value = false;
if (!payload.value) emit('error', t('kbDifyHealth.msg.loadFailed'));
};
watch(() => props.open, (open) => {
if (open) void loadHealth();
});
</script>
<template>
<div v-if="open" class="dialog-overlay" @click="close">
<div class="dialog-panel max-w-4xl p-6" @click.stop>
<div class="flex items-center justify-between gap-4">
<div>
<h3 class="section-title text-xl">{{ t('kbDifyHealth.title') }}</h3>
<p class="section-desc mt-1">{{ t('kbDifyHealth.subtitle') }}</p>
</div>
<div class="flex items-center gap-3">
<button type="button" class="btn-secondary btn-sm" @click="loadHealth">
{{ t('common.refresh') }}
</button>
<button type="button" class="btn-secondary btn-sm" @click="close">
{{ t('common.close') }}
</button>
</div>
</div>
<div v-if="loading" class="py-16 text-center text-sm text-muted">{{ t('kbDifyHealth.loading') }}</div>
<div v-else-if="payload" class="mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3">
<div class="dialog-stat-card">
<div class="label-field">Dify API</div>
<div class="mt-3 text-2xl font-semibold text-primary">{{ payload.api.reachable ? t('kbDifyHealth.reachable') : t('kbDifyHealth.unreachable') }}</div>
<div class="mt-2 break-all text-xs text-muted">{{ payload.dify_base_url || t('kbDifyHealth.notConfigured') }}</div>
</div>
<div class="dialog-stat-card">
<div class="label-field">{{ t('kbDifyHealth.datasetCount') }}</div>
<div class="mt-3 text-2xl font-semibold text-primary">{{ payload.api.dataset_count ?? '--' }}</div>
<div class="mt-2 text-xs text-muted">{{ t('kbDifyHealth.configured') }}{{ payload.dify_api_configured ? t('common.yes') : t('common.no') }}</div>
</div>
<div class="dialog-stat-card">
<div class="label-field">{{ t('kbDifyHealth.boundGroups') }}</div>
<div class="mt-3 text-2xl font-semibold text-primary">{{ payload.local_sync_health.dataset_bound_groups }}</div>
<div class="mt-2 text-xs text-muted">{{ t('kbDifyHealth.localSyncRecords') }}{{ payload.local_sync_health.sync_records }}</div>
</div>
<div class="dialog-stat-card">
<div class="label-field">{{ t('kbDifyHealth.syncingVersions') }}</div>
<div class="mt-3 text-2xl font-semibold text-primary">{{ payload.local_sync_health.syncing_versions }}</div>
</div>
<div class="dialog-stat-card">
<div class="label-field">{{ t('kbDifyHealth.syncedVersions') }}</div>
<div class="mt-3 text-2xl font-semibold text-primary">{{ payload.local_sync_health.synced_versions }}</div>
</div>
<div class="dialog-stat-card">
<div class="label-field">{{ t('kbDifyHealth.pendingSyncJobs') }}</div>
<div class="mt-3 text-2xl font-semibold text-primary">{{ payload.local_sync_health.pending_sync_jobs }}</div>
<div v-if="payload.api.error" class="mt-2 text-xs text-rose-500">{{ payload.api.error }}</div>
</div>
</div>
</div>
</div>
</template>
@@ -0,0 +1,119 @@
<script setup lang="ts">
/**
* shared/components/kb/DifySettingsDialog.vue
* 知识库 Dify 配置弹窗(KB 暂缓 redesign)。
*/
import { reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { getKbDifySettings, updateKbDifySettings } from '@/api/kb';
const props = defineProps<{ open: boolean }>();
const emit = defineEmits<{ close: []; saved: [message: string]; error: [message: string] }>();
const { t } = useI18n();
const loading = ref(false);
const saving = ref(false);
const form = reactive({
DIFY_API_BASE: '',
DIFY_API_KEY: '',
KB_DIFY_PERMISSION: 'only_me',
KB_DIFY_INDEXING_TECHNIQUE: 'high_quality',
KB_DIFY_SEARCH_METHOD: 'semantic_search',
KB_DIFY_DOC_FORM: 'text_model',
});
const close = () => emit('close');
const loadSettings = async () => {
loading.value = true;
const settings = await getKbDifySettings();
loading.value = false;
if (!settings) {
emit('error', t('kbDifySettings.msg.loadFailed'));
return;
}
Object.assign(form, settings);
};
const save = async () => {
saving.value = true;
const result = await updateKbDifySettings(form);
saving.value = false;
if (!result.ok) {
emit('error', result.error || t('kbDifySettings.msg.saveFailed'));
return;
}
emit('saved', t('kbDifySettings.msg.saved'));
emit('close');
};
watch(() => props.open, (open) => {
if (open) void loadSettings();
});
</script>
<template>
<div v-if="open" class="dialog-overlay" @click="close">
<div class="dialog-panel max-w-3xl p-6" @click.stop>
<div class="flex items-center justify-between gap-4">
<div>
<h3 class="section-title text-xl">{{ t('kbDifySettings.title') }}</h3>
<p class="section-desc mt-1">{{ t('kbDifySettings.subtitle') }}</p>
</div>
<button type="button" class="btn-secondary btn-sm" @click="close">
{{ t('common.close') }}
</button>
</div>
<div v-if="loading" class="py-16 text-center text-sm text-muted">{{ t('kbDifySettings.loading') }}</div>
<div v-else class="mt-6 grid gap-4 md:grid-cols-2 form-stack">
<label class="space-y-2 md:col-span-2">
<span class="label-field block">Dify Base URL</span>
<input v-model="form.DIFY_API_BASE" class="input-field" placeholder="https://api.dify.ai/v1" />
</label>
<label class="space-y-2 md:col-span-2">
<span class="label-field block">Dify API Key</span>
<input v-model="form.DIFY_API_KEY" class="input-field" placeholder="app-..." />
</label>
<label class="space-y-2">
<span class="label-field block">Permission</span>
<select v-model="form.KB_DIFY_PERMISSION" class="input-field">
<option value="only_me">only_me</option>
<option value="all_team_members">all_team_members</option>
</select>
</label>
<label class="space-y-2">
<span class="label-field block">Indexing Technique</span>
<select v-model="form.KB_DIFY_INDEXING_TECHNIQUE" class="input-field">
<option value="high_quality">high_quality</option>
<option value="economy">economy</option>
</select>
</label>
<label class="space-y-2">
<span class="label-field block">Search Method</span>
<select v-model="form.KB_DIFY_SEARCH_METHOD" class="input-field">
<option value="semantic_search">semantic_search</option>
<option value="hybrid_search">hybrid_search</option>
<option value="full_text_search">full_text_search</option>
</select>
</label>
<label class="space-y-2">
<span class="label-field block">Doc Form</span>
<select v-model="form.KB_DIFY_DOC_FORM" class="input-field">
<option value="text_model">text_model</option>
</select>
</label>
</div>
<div class="mt-6 flex justify-end gap-3">
<button type="button" class="btn-secondary" @click="close">
{{ t('common.cancel') }}
</button>
<button type="button" class="btn-primary" :disabled="saving" @click="save">
{{ saving ? t('kbDifySettings.saving') : t('kbDifySettings.save') }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,379 @@
<script setup lang="ts">
/**
* shared/components/kb/KbAdminPanel.vue
* 知识库管理面板(KB 暂缓 redesign)。
*/
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { Activity, FolderPlus, Pencil, Play, Settings, Trash2, Wrench, X } from 'lucide-vue-next';
import DifyHealthDialog from './DifyHealthDialog.vue';
import DifySettingsDialog from './DifySettingsDialog.vue';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import {
createKbGroup,
deleteKbGroup,
getKbGroupsSafe,
getKbJobsSafe,
runKbJob,
updateKbGroup,
type KbGroup,
type KbJob,
} from '@/api/kb';
const router = useRouter();
const { t } = useI18n();
const groups = ref<KbGroup[]>([]);
const jobs = ref<KbJob[]>([]);
const isSubmitting = ref(false);
const isRefreshing = ref(false);
const editingGroupId = ref<number | null>(null);
const form = ref({
name: '',
description: '',
});
const feedback = ref('');
const feedbackType = ref<'success' | 'error' | ''>('');
const runningJobId = ref<number | string | null>(null);
const settingsDialogOpen = ref(false);
const healthDialogOpen = ref(false);
const deleteDialogOpen = ref(false);
const deletingGroup = ref<KbGroup | null>(null);
const formTitle = computed(() => editingGroupId.value ? t('kbAdmin.form.editTitle') : t('kbAdmin.form.createTitle'));
const formDescription = computed(() => editingGroupId.value
? t('kbAdmin.form.editDesc')
: t('kbAdmin.form.createDesc'));
const submitText = computed(() => {
if (isSubmitting.value) return editingGroupId.value ? t('kbAdmin.form.saving') : t('kbAdmin.form.submitting');
return editingGroupId.value ? t('kbAdmin.form.saveChanges') : t('kbAdmin.form.create');
});
const loadData = async () => {
isRefreshing.value = true;
const [groupsResult, jobsResult] = await Promise.all([getKbGroupsSafe(), getKbJobsSafe()]);
if (groupsResult.ok) {
groups.value = groupsResult.data;
} else {
feedback.value = groupsResult.error || t('kbAdmin.msg.loadGroupsFailed');
feedbackType.value = 'error';
}
if (jobsResult.ok) {
jobs.value = jobsResult.data;
} else {
feedback.value = jobsResult.error || t('kbAdmin.msg.loadJobsFailed');
feedbackType.value = 'error';
}
isRefreshing.value = false;
};
const resetForm = () => {
editingGroupId.value = null;
form.value = { name: '', description: '' };
};
const handleCreateGroup = async () => {
if (!form.value.name.trim()) {
feedback.value = t('kbAdmin.msg.nameRequired');
feedbackType.value = 'error';
return;
}
isSubmitting.value = true;
const payload = {
name: form.value.name.trim(),
description: form.value.description.trim(),
};
const result = editingGroupId.value
? await updateKbGroup(editingGroupId.value, payload)
: await createKbGroup(payload);
isSubmitting.value = false;
if (!result.ok) {
feedback.value = result.error || t('kbAdmin.msg.createFailed');
feedbackType.value = 'error';
return;
}
feedback.value = editingGroupId.value ? t('kbAdmin.msg.updated') : t('kbAdmin.msg.created');
feedbackType.value = 'success';
resetForm();
await loadData();
};
const handleEditGroup = (group: KbGroup) => {
editingGroupId.value = group.id;
form.value = {
name: group.name,
description: group.description || '',
};
feedback.value = '';
feedbackType.value = '';
};
const handleDeleteGroup = async (group: KbGroup) => {
deletingGroup.value = group;
deleteDialogOpen.value = true;
};
const handleDeleteGroupConfirm = async () => {
if (!deletingGroup.value) return;
const result = await deleteKbGroup(deletingGroup.value.id);
if (!result.ok) {
feedback.value = result.error || t('kbAdmin.msg.deleteFailed');
feedbackType.value = 'error';
return;
}
if (editingGroupId.value === deletingGroup.value.id) {
resetForm();
}
feedback.value = t('kbAdmin.msg.deleted');
feedbackType.value = 'success';
deleteDialogOpen.value = false;
deletingGroup.value = null;
await loadData();
};
const handleRunJob = async (job: KbJob) => {
runningJobId.value = job.id;
const result = await runKbJob(job.id);
runningJobId.value = null;
if (!result.ok) {
feedback.value = result.error || t('kbAdmin.msg.runFailed');
feedbackType.value = 'error';
return;
}
feedback.value = result.run_result || t('kbAdmin.msg.runDone');
feedbackType.value = 'success';
await loadData();
};
onMounted(async () => {
await loadData();
});
defineExpose({ loadData });
</script>
<template>
<div class="animate-fade-in-up">
<div class="kb-admin-header">
<div class="min-w-0 flex-1">
<h2 class="text-xl font-bold text-primary">{{ t('kbAdmin.title') }}</h2>
<p class="section-desc mt-1">
{{ t('kbAdmin.subtitle') }}
</p>
</div>
<div class="flex w-full shrink-0 flex-col gap-2 sm:w-auto sm:flex-row sm:items-center sm:justify-end">
<div
class="kb-admin-toolbar"
role="toolbar"
:aria-label="t('kbAdmin.toolbar')"
>
<button
type="button"
class="kb-admin-toolbar-btn"
@click="settingsDialogOpen = true"
:title="t('kbAdmin.difySettings')"
>
<Settings class="h-4 w-4 shrink-0" />
<span class="whitespace-nowrap">{{ t('kbAdmin.difySettings') }}</span>
</button>
<button
type="button"
class="kb-admin-toolbar-btn"
@click="healthDialogOpen = true"
:title="t('kbAdmin.healthCheck')"
>
<Activity class="h-4 w-4 shrink-0" />
<span class="whitespace-nowrap">{{ t('kbAdmin.healthCheck') }}</span>
</button>
</div>
<button
type="button"
class="btn-primary inline-flex w-full items-center justify-center gap-2 px-5 py-2.5 text-sm sm:w-auto"
@click="router.push('/kb/workspace')"
>
<Wrench class="h-4 w-4 shrink-0" />
<span class="whitespace-nowrap">{{ t('kbAdmin.goWorkspace') }}</span>
</button>
</div>
</div>
<div class="kb-admin-body">
<section class="kb-admin-section">
<div class="mb-5 flex items-center gap-3">
<div class="flex h-10 w-10 items-center justify-center rounded-2xl bg-brand-50 text-brand-600">
<FolderPlus class="h-5 w-5" />
</div>
<div>
<h3 class="section-title">{{ formTitle }}</h3>
<p class="section-desc">{{ formDescription }}</p>
</div>
</div>
<div class="space-y-4">
<div>
<label class="label-field mb-2 block">{{ t('kbAdmin.form.groupName') }}</label>
<input v-model="form.name" class="input-field" :placeholder="t('kbAdmin.form.groupNamePlaceholder')" />
</div>
<div>
<label class="label-field mb-2 block">{{ t('kbAdmin.form.groupDesc') }}</label>
<textarea
v-model="form.description"
rows="4"
class="input-field"
:placeholder="t('kbAdmin.form.groupDescPlaceholder')"
/>
</div>
<div class="flex flex-wrap items-center justify-end gap-2 border-t border-subtle pt-4">
<button
type="button"
class="btn-primary inline-flex items-center gap-1.5 px-5 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-60"
@click="handleCreateGroup"
:disabled="isSubmitting"
>
<FolderPlus v-if="!isSubmitting" class="h-4 w-4 shrink-0" />
{{ submitText }}
</button>
<button
v-if="editingGroupId"
type="button"
class="btn-secondary inline-flex items-center gap-1.5 px-4 py-2 text-sm"
@click="resetForm"
>
<X class="h-4 w-4 shrink-0" />
{{ t('kbAdmin.form.cancelEdit') }}
</button>
</div>
<p
v-if="feedback"
class="text-sm"
:class="feedbackType === 'error' ? 'text-rose-500' : 'text-emerald-600'"
>
{{ feedback }}
</p>
</div>
</section>
<div class="space-y-6">
<section class="kb-admin-section">
<div class="mb-4 flex items-center justify-between">
<h3 class="section-title">{{ t('kbAdmin.groupsTitle') }}</h3>
<span class="text-xs text-muted">{{ isRefreshing ? t('common.loading') : '/api/kb/groups' }}</span>
</div>
<div v-if="groups.length === 0" class="kb-admin-empty">
{{ t('kbAdmin.groupsEmpty') }}
</div>
<div v-else class="grid grid-cols-1 gap-3 md:grid-cols-2">
<div
v-for="group in groups"
:key="group.id"
class="kb-admin-card"
>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="font-semibold text-primary">{{ group.name }}</div>
<div class="mt-1 text-sm text-muted">{{ group.description || t('kbAdmin.noDescription') }}</div>
</div>
<div class="kb-admin-badge">
{{ t('kbAdmin.documentCount', { count: group.document_count ?? 0 }) }}
</div>
</div>
<div class="mt-4 flex flex-wrap items-center justify-between gap-3">
<div class="text-xs text-muted">
{{ t('kbAdmin.updatedAt') }}{{ group.updated_at || '--' }}
</div>
<div class="flex items-center gap-2">
<button
type="button"
class="btn-secondary inline-flex items-center gap-1 px-3 py-2 text-xs"
@click="handleEditGroup(group)"
>
<Pencil class="h-3.5 w-3.5" />
{{ t('common.edit') }}
</button>
<button
type="button"
class="inline-flex items-center gap-1 rounded-xl border border-rose-200 px-3 py-2 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50"
@click="handleDeleteGroup(group)"
>
<Trash2 class="h-3.5 w-3.5" />
{{ t('common.delete') }}
</button>
</div>
</div>
</div>
</div>
</section>
<section class="kb-admin-section">
<div class="mb-4 flex items-center justify-between">
<h3 class="section-title">{{ t('kbAdmin.jobsTitle') }}</h3>
<span class="text-xs text-muted">/api/kb/jobs</span>
</div>
<div v-if="jobs.length === 0" class="kb-admin-empty">
{{ t('kbAdmin.jobsEmpty') }}
</div>
<div v-else class="space-y-3">
<div
v-for="job in jobs"
:key="job.id"
class="kb-admin-card"
>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="font-semibold text-primary">{{ job.job_type }}</div>
<div class="mt-1 text-sm text-muted">{{ job.created_at || '--' }}</div>
<div class="mt-2 text-sm text-muted">
{{ job.message || t('kbAdmin.noJobMessage') }}
</div>
<div class="mt-2 text-xs text-muted">
{{ t('kbAdmin.jobMeta', { docId: job.document_id ?? '--', versionId: job.document_version_id ?? '--', progress: job.progress ?? 0 }) }}
</div>
</div>
<span class="kb-admin-badge">
{{ job.status }}
</span>
</div>
<div v-if="['clean', 'sync_dify'].includes(job.job_type) && job.status !== 'success'" class="mt-3 flex justify-end">
<button
type="button"
class="inline-flex items-center gap-1 rounded-xl border border-brand-200 px-3 py-2 text-xs font-medium text-brand-700 transition-colors hover:bg-brand-50 disabled:cursor-not-allowed disabled:opacity-60"
@click="handleRunJob(job)"
:disabled="runningJobId === job.id"
>
<Play class="h-3.5 w-3.5" />
{{ runningJobId === job.id ? t('kbAdmin.running') : t('kbAdmin.runJob') }}
</button>
</div>
</div>
</div>
</section>
</div>
</div>
</div>
<DifySettingsDialog
:open="settingsDialogOpen"
@close="settingsDialogOpen = false"
@saved="(message) => { feedback = message; feedbackType = 'success'; void loadData(); }"
@error="(message) => { feedback = message; feedbackType = 'error'; }"
/>
<DifyHealthDialog
:open="healthDialogOpen"
@close="healthDialogOpen = false"
@error="(message) => { feedback = message; feedbackType = 'error'; }"
/>
<DeleteConfirmDialog
v-model="deleteDialogOpen"
:title="t('kbAdmin.deleteDialog.title')"
:message="t('kbAdmin.deleteDialog.message', { name: deletingGroup?.name || '' })"
@confirm="handleDeleteGroupConfirm"
@cancel="() => { deleteDialogOpen = false; deletingGroup = null; }"
/>
</template>
@@ -0,0 +1,208 @@
/**
* shared/composables/useAudioTranscription.ts
* 语音录制与转写,供聊天输入栏使用。
*/
import { ref, computed, onBeforeUnmount } from 'vue';
import { getAuthHeaders } from '@/shared/utils/auth';
export type AudioTranscriptionErrorKey =
| 'chat.voiceRequiresHttps'
| 'chat.voiceNotSupported'
| 'chat.voicePermissionDenied'
| 'chat.voiceRecordTooShort'
| 'chat.voiceTranscriptionFailed';
const isSecureContextForMic = (): boolean => {
if (typeof window === 'undefined') return false;
if (window.isSecureContext) return true;
const host = window.location.hostname;
return host === 'localhost' || host === '127.0.0.1';
};
const canUseMediaRecorder = (): boolean => {
if (typeof window === 'undefined') return false;
return Boolean(window.MediaRecorder && navigator.mediaDevices?.getUserMedia);
};
export const getVoiceUnavailableErrorKey = (): AudioTranscriptionErrorKey | null => {
if (!isSecureContextForMic()) return 'chat.voiceRequiresHttps';
if (!canUseMediaRecorder()) return 'chat.voiceNotSupported';
return null;
};
const pickMimeType = (): string => {
const candidates = [
'audio/webm;codecs=opus',
'audio/webm',
'audio/mp4',
'audio/ogg;codecs=opus',
];
for (const type of candidates) {
if (MediaRecorder.isTypeSupported(type)) return type;
}
return '';
};
export function useAudioTranscription(options: {
onResult: (text: string) => void;
onError: (key: AudioTranscriptionErrorKey) => void;
}) {
const isRecording = ref(false);
const isTranscribing = ref(false);
const isSupported = computed(() => getVoiceUnavailableErrorKey() === null);
const isBusy = computed(() => isRecording.value || isTranscribing.value);
let mediaStream: MediaStream | null = null;
let mediaRecorder: MediaRecorder | null = null;
let chunks: Blob[] = [];
let baseText = '';
let skipTranscription = false;
const cleanupStream = () => {
if (mediaStream) {
mediaStream.getTracks().forEach((track) => track.stop());
mediaStream = null;
}
mediaRecorder = null;
chunks = [];
};
const stopRecording = () => {
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
mediaRecorder.stop();
return;
}
isRecording.value = false;
cleanupStream();
};
const transcribeBlob = async (blob: Blob, mimeType: string) => {
if (blob.size < 800) {
options.onError('chat.voiceRecordTooShort');
return;
}
isTranscribing.value = true;
try {
const ext = mimeType.includes('mp4') ? 'm4a' : 'webm';
const formData = new FormData();
formData.append('audio', blob, `recording.${ext}`);
const response = await fetch('/api/speech/transcribe', {
method: 'POST',
headers: { ...getAuthHeaders() },
body: formData,
});
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
const errMsg = payload?.error?.message || payload?.message || `Request failed (${response.status})`;
throw new Error(errMsg);
}
const text = String(payload.text || '').trim();
if (!text) {
options.onError('chat.voiceRecordTooShort');
return;
}
const prefix = baseText.trim();
options.onResult(prefix ? `${prefix} ${text}` : text);
} catch {
options.onError('chat.voiceTranscriptionFailed');
} finally {
isTranscribing.value = false;
}
};
const startRecording = async (existingText = '') => {
if (isBusy.value) return;
const unavailable = getVoiceUnavailableErrorKey();
if (unavailable) {
options.onError(unavailable);
return;
}
baseText = existingText;
try {
mediaStream = await navigator.mediaDevices.getUserMedia({ audio: true });
} catch (err) {
const denied = err instanceof DOMException && (
err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError'
);
options.onError(denied ? 'chat.voicePermissionDenied' : 'chat.voiceTranscriptionFailed');
return;
}
chunks = [];
const mimeType = pickMimeType();
try {
mediaRecorder = mimeType
? new MediaRecorder(mediaStream, { mimeType })
: new MediaRecorder(mediaStream);
} catch {
cleanupStream();
options.onError('chat.voiceNotSupported');
return;
}
mediaRecorder.ondataavailable = (event) => {
if (event.data.size > 0) chunks.push(event.data);
};
mediaRecorder.onstop = async () => {
isRecording.value = false;
const type = mediaRecorder?.mimeType || mimeType || 'audio/webm';
const blob = new Blob(chunks, { type });
const shouldSkip = skipTranscription;
skipTranscription = false;
cleanupStream();
if (shouldSkip) return;
await transcribeBlob(blob, type);
};
mediaRecorder.onerror = () => {
isRecording.value = false;
cleanupStream();
options.onError('chat.voiceTranscriptionFailed');
};
mediaRecorder.start();
isRecording.value = true;
};
const toggle = (existingText = '') => {
if (isTranscribing.value) return;
if (isRecording.value) {
stopRecording();
return;
}
void startRecording(existingText);
};
const cancel = () => {
skipTranscription = true;
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
mediaRecorder.stop();
} else {
cleanupStream();
}
isRecording.value = false;
isTranscribing.value = false;
};
onBeforeUnmount(cancel);
return {
isRecording,
isTranscribing,
isSupported,
isBusy,
startRecording,
stopRecording,
toggle,
cancel,
};
}
@@ -0,0 +1,8 @@
/**
* shared/composables/useChat.ts
* 兼容转发至 chat feature 的 useChat。
*/
/**
* @deprecated 请使用 @/features/chat/composables/useChat
*/
export { useChat } from '@/features/chat/composables/useChat';
@@ -0,0 +1,62 @@
/**
* shared/composables/useGlobalMessageDialog.ts
* 全局消息弹窗单例状态与展示控制。
*/
import { readonly, ref } from 'vue';
export type MessageLevel = 'success' | 'info' | 'warning' | 'error';
// 全局单例状态:整个应用共享一套消息弹框。
const visible = ref(false);
const level = ref<MessageLevel>('info');
const title = ref('');
const message = ref('');
const MAX_DIALOG_MESSAGE_LENGTH = 240;
const normalizeMessage = (raw: string) => {
if (!raw) return '';
return raw
.replace(/\s+/g, ' ')
.replace(/<[^>]*>/g, '')
.trim();
};
const formatMessageForDialog = (level: MessageLevel, raw: string) => {
const normalized = normalizeMessage(raw);
if (!normalized) return '';
// Error messages often include long backend stack/driver details.
if (level === 'error' && normalized.length > MAX_DIALOG_MESSAGE_LENGTH) {
return `${normalized.slice(0, MAX_DIALOG_MESSAGE_LENGTH)}...`;
}
return normalized;
};
export const useGlobalMessageDialog = () => {
const showMessageDialog = (
nextLevel: MessageLevel,
nextMessage: string,
nextTitle = ''
) => {
level.value = nextLevel;
title.value = nextTitle;
message.value = formatMessageForDialog(nextLevel, nextMessage);
visible.value = true;
};
const closeMessageDialog = () => {
visible.value = false;
title.value = '';
message.value = '';
};
return {
messageDialogVisible: visible,
messageDialogLevel: readonly(level),
messageDialogTitle: readonly(title),
messageDialogContent: readonly(message),
showMessageDialog,
closeMessageDialog,
};
};
@@ -0,0 +1,36 @@
/**
* shared/composables/useIsMobile.ts
* 检测竖屏/横屏,供移动端布局切换。
*/
import { ref, onMounted, onBeforeUnmount, readonly } from 'vue';
const isMobile = ref(false);
let listeners = 0;
const update = () => {
isMobile.value = window.innerHeight > window.innerWidth;
};
const startListening = () => {
if (listeners === 0) {
update();
window.addEventListener('resize', update);
}
listeners++;
};
const stopListening = () => {
listeners--;
if (listeners <= 0) {
listeners = 0;
window.removeEventListener('resize', update);
}
};
export function useIsMobile() {
onMounted(() => startListening());
onBeforeUnmount(() => stopListening());
return { isMobile: readonly(isMobile) };
}
@@ -0,0 +1,39 @@
/**
* shared/composables/useMessage.ts
* 业务层消息助手,封装全局 LevelMessageDialog 调用。
*/
import { useGlobalMessageDialog } from './useGlobalMessageDialog';
type MessageTitle = string | undefined;
/**
* 业务层消息助手:
* - 统一复用全局 LevelMessageDialog
* - 提供更短的方法名,减少重复传 level 字符串
*/
export const useMessage = () => {
const { showMessageDialog } = useGlobalMessageDialog();
const info = (message: string, title?: MessageTitle) =>
showMessageDialog('info', message, title);
const success = (message: string, title?: MessageTitle) =>
showMessageDialog('success', message, title);
const warning = (message: string, title?: MessageTitle) =>
showMessageDialog('warning', message, title);
// 兼容常见缩写调用:msg.warn(...)
const warn = warning;
const error = (message: string, title?: MessageTitle) =>
showMessageDialog('error', message, title);
return {
info,
success,
warning,
warn,
error,
};
};
@@ -0,0 +1,48 @@
/**
* shared/composables/useReportLayoutStorage.ts
* 报表页面布局偏好 localStorage 持久化。
*/
/**
* useReportLayoutStorage.ts
* 用途:为报表页面提供统一的布局偏好持久化能力(按用户 + 表名隔离)
*/
const getCurrentAuthUser = () => {
let stored = localStorage.getItem('hxops_user');
if (!stored) stored = sessionStorage.getItem('hxops_user');
if (!stored) return null;
try {
const data = JSON.parse(stored);
return data.user || data;
} catch {
return null;
}
};
const getCurrentIdentity = () => {
const user = getCurrentAuthUser();
return user?.id ? `id_${user.id}` : `u_${user?.username || 'guest'}`;
};
const getReportLayoutStorageKey = (table: string) => {
return `hxops_report_layout_v2_${getCurrentIdentity()}_${table}`;
};
export const loadReportLayoutPref = <T = any>(table: string): T | null => {
try {
const raw = localStorage.getItem(getReportLayoutStorageKey(table));
if (!raw) return null;
return JSON.parse(raw) as T;
} catch {
return null;
}
};
export const saveReportLayoutPref = (table: string, payload: unknown) => {
try {
localStorage.setItem(getReportLayoutStorageKey(table), JSON.stringify(payload));
} catch {
// Ignore storage write failure to avoid blocking core report flow.
}
};
@@ -0,0 +1,93 @@
/**
* shared/composables/useTheme.ts
* 主题 preference 与 dark/light 切换(全局单例)。
*/
import { computed, ref } from 'vue';
export type ThemePreference = 'light' | 'dark' | 'system';
export type AppliedTheme = 'light' | 'dark';
const THEME_KEY = 'hxops_theme_preference';
const validThemePrefs: ThemePreference[] = ['light', 'dark', 'system'];
const themePreference = ref<ThemePreference>('system');
const systemPrefersDark = ref(false);
let initialized = false;
let mediaListenerCleanup: (() => void) | null = null;
const appliedTheme = computed<AppliedTheme>(() => {
if (themePreference.value === 'system') {
return systemPrefersDark.value ? 'dark' : 'light';
}
return themePreference.value;
});
const applyTheme = () => {
const root = document.documentElement;
const isDark = appliedTheme.value === 'dark';
root.classList.toggle('dark', isDark);
root.setAttribute('data-theme', appliedTheme.value);
};
const parseTheme = (value: string | null | undefined): ThemePreference | null => {
if (!value) return null;
return validThemePrefs.includes(value as ThemePreference) ? (value as ThemePreference) : null;
};
const setThemePreference = (value: ThemePreference, persist = true) => {
themePreference.value = value;
if (persist) {
localStorage.setItem(THEME_KEY, value);
}
applyTheme();
};
const toggleLightDark = () => {
setThemePreference(appliedTheme.value === 'dark' ? 'light' : 'dark');
};
const initTheme = () => {
if (initialized) {
applyTheme();
return;
}
initialized = true;
const media = window.matchMedia('(prefers-color-scheme: dark)');
systemPrefersDark.value = media.matches;
const onMediaChange = (event: MediaQueryListEvent) => {
systemPrefersDark.value = event.matches;
if (themePreference.value === 'system') {
applyTheme();
}
};
media.addEventListener('change', onMediaChange);
mediaListenerCleanup = () => media.removeEventListener('change', onMediaChange);
const stored = parseTheme(localStorage.getItem(THEME_KEY));
if (stored) {
themePreference.value = stored;
}
applyTheme();
};
const cleanupTheme = () => {
mediaListenerCleanup?.();
mediaListenerCleanup = null;
initialized = false;
};
export function useTheme() {
return {
themePreference,
appliedTheme,
initTheme,
cleanupTheme,
setThemePreference,
toggleLightDark,
};
}
+4
View File
@@ -1,3 +1,7 @@
/**
* shared/constants/routes.ts
* 全局路由 path 常量与公开路径判定。
*/
/** 无需登录即可访问的路由 path */
export const PUBLIC_PATHS = ['/', '/login', '/casdoor-callback', '/reset-password'] as const;
+14
View File
@@ -0,0 +1,14 @@
/**
* shared/index.ts
* 跨域共享层统一导出入口(composables / utils / constants)。
*/
export * from './composables/useTheme';
export * from './composables/useMessage';
export * from './composables/useIsMobile';
export * from './composables/useGlobalMessageDialog';
export * from './composables/useReportLayoutStorage';
export * from './composables/useAudioTranscription';
export * from './api/client';
export * from './constants/routes';
export type * from './types/auth.types';
export type * from './types/schedule.types';
@@ -0,0 +1,16 @@
<script setup lang="ts">
/**
* shared/layouts/AppHeaderTools.vue
* 顶栏工具区:主题与语言切换。
*/
import ThemeToggleButton from '@/shared/components/ThemeToggleButton.vue';
import LocaleToggleButton from '@/shared/components/LocaleToggleButton.vue';
</script>
<template>
<div class="flex items-center gap-2">
<ThemeToggleButton />
<LocaleToggleButton />
</div>
</template>
+68
View File
@@ -0,0 +1,68 @@
<script setup lang="ts">
/**
* shared/layouts/AppShell.vue
* 通用应用壳层布局。
*/
import { ref } from 'vue';
import { PanelLeftClose, PanelLeftOpen } from 'lucide-vue-next';
import AppHeaderTools from './AppHeaderTools.vue';
withDefaults(
defineProps<{
title?: string;
subtitle?: string;
collapsibleSidebar?: boolean;
}>(),
{
title: '',
subtitle: '',
collapsibleSidebar: true,
}
);
const sidebarCollapsed = ref(false);
</script>
<template>
<div class="page-shell flex min-h-screen flex-col">
<header class="app-header">
<div class="flex min-w-0 items-center gap-3">
<button
v-if="collapsibleSidebar"
type="button"
class="btn-icon-ds hidden md:inline-flex"
:aria-label="sidebarCollapsed ? 'Expand sidebar' : 'Collapse sidebar'"
@click="sidebarCollapsed = !sidebarCollapsed"
>
<PanelLeftOpen v-if="sidebarCollapsed" class="h-5 w-5" />
<PanelLeftClose v-else class="h-5 w-5" />
</button>
<div class="min-w-0">
<slot name="header-brand">
<div v-if="title" class="truncate text-sm font-bold text-primary">{{ title }}</div>
<div v-if="subtitle" class="truncate text-xs text-muted">{{ subtitle }}</div>
</slot>
</div>
</div>
<div class="flex items-center gap-3">
<slot name="header-actions" />
<AppHeaderTools />
</div>
</header>
<div class="flex min-h-0 flex-1">
<aside
v-if="$slots.sidebar"
class="app-sidebar hidden md:block transition-[width] duration-200"
:class="sidebarCollapsed ? 'app-sidebar--collapsed' : ''"
>
<slot name="sidebar" :collapsed="sidebarCollapsed" />
</aside>
<main class="min-w-0 flex-1 overflow-y-auto page-shell-mobile py-6">
<slot />
</main>
</div>
</div>
</template>
+16
View File
@@ -0,0 +1,16 @@
<script setup lang="ts">
/**
* shared/layouts/ChatShell.vue
* 对话页壳层:侧栏 + 主区,颜色走 L1 设计令牌。
*/
</script>
<template>
<div class="relative flex h-screen overflow-hidden bg-page text-secondary">
<slot name="overlay" />
<slot name="sidebar" />
<div class="relative z-10 flex h-full w-full flex-1 flex-col overflow-hidden bg-surface">
<slot />
</div>
</div>
</template>
@@ -0,0 +1,19 @@
<script setup lang="ts">
/**
* shared/layouts/MarketingShell.vue
* 营销/登录页壳层。
*/
/** L3 — 登录 / 营销页布局 */
</script>
<template>
<div class="page-shell min-h-screen">
<div v-if="$slots.tools" class="fixed top-4 right-4 z-50 flex items-center gap-2">
<slot name="tools" />
</div>
<main class="mx-auto max-w-7xl page-shell-mobile pb-12">
<slot />
</main>
</div>
</template>
@@ -0,0 +1,22 @@
<script setup lang="ts">
/**
* shared/layouts/MinimalShell.vue
* 极简壳层(重置密码等)。
*/
/** L3 — 单卡居中页(重置密码等) */
withDefaults(
defineProps<{
maxWidth?: string;
}>(),
{ maxWidth: '28rem' }
);
</script>
<template>
<div class="page-shell flex min-h-screen items-center justify-center p-4">
<div class="card w-full shadow-elevated p-8 md:p-10" :style="{ maxWidth }">
<slot />
</div>
</div>
</template>
@@ -0,0 +1,923 @@
/**
* shared/styles/components-ds.css
* 设计系统组件样式(按钮、表格、表单等)。
*/
/**
* L2 Design System components — token-driven, no dark: color pairs.
*/
@layer components {
.page-shell {
min-height: 100vh;
background-color: var(--bg-page);
color: var(--text-secondary);
}
.page-title {
font-size: 1.5rem;
line-height: 2rem;
font-weight: 700;
color: var(--text-primary);
}
.section-title {
font-size: 1.125rem;
line-height: 1.75rem;
font-weight: 600;
color: var(--text-primary);
}
.section-desc {
font-size: 0.875rem;
line-height: 1.25rem;
color: var(--text-muted);
}
.input-field-ds { @apply input-field; }
.select-field-ds { @apply select-field; }
/* 顶栏语言图标 — 无圆圈,与 theme-toggle-btn--inline 同占位对齐 */
.header-locale-btn {
@apply flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border-0 bg-transparent p-0 text-muted shadow-none transition-colors hover:text-primary;
}
.header-locale-btn:focus-visible {
outline: none;
box-shadow: 0 0 0 2px var(--focus-ring);
border-radius: 0.5rem;
}
@media (min-width: 768px) {
.header-locale-btn {
@apply h-9 w-9;
}
}
.header-locale-btn--floating {
@apply fixed bottom-5 right-5 z-[70] h-11 w-11 rounded-full;
}
/* 顶栏语言图标 — 下拉菜单 */
.header-locale-menu {
@apply absolute right-0 top-full z-[60] mt-1.5 min-w-[9.5rem] overflow-hidden rounded-xl border border-default py-1 shadow-elevated;
background-color: var(--bg-surface);
}
.header-locale-menu--sidebar {
@apply bottom-full top-auto right-0 left-auto mb-1.5 mt-0;
}
.header-locale-menu__item {
@apply flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm font-medium text-secondary transition-colors;
}
.header-locale-menu__item:hover {
@apply bg-surface-soft text-primary;
}
.header-locale-menu__item--active {
@apply bg-brand-50 text-brand-700;
}
html.dark .header-locale-menu__item--active {
@apply bg-brand-950/40 text-brand-300;
}
.card-ds { @apply card; }
.card-ds-interactive {
@apply card;
}
.card-ds-interactive:hover {
box-shadow: var(--shadow-elevated);
border-color: rgba(14, 165, 233, 0.35);
}
.card-padding {
padding: 1rem;
}
@media (min-width: 640px) {
.card-padding {
padding: 1.5rem;
}
}
.surface-panel {
background-color: var(--bg-surface);
border: 1px solid var(--border-default);
border-radius: 1rem;
}
/* Aliases — prefer .btn-secondary / .btn-ghost in style.css */
.btn-secondary-ds { @apply btn-secondary; }
.btn-ghost-ds { @apply btn-ghost; }
.btn-icon-ds {
display: inline-flex;
align-items: center;
justify-content: center;
width: 2.25rem;
height: 2.25rem;
border-radius: 0.75rem;
color: var(--text-muted);
transition: background-color 0.2s, color 0.2s;
}
.btn-icon-ds:hover {
background-color: var(--bg-surface-strong);
color: var(--text-primary);
}
.alert-ds {
display: flex;
gap: 0.75rem;
padding: 1rem 1.25rem;
border-radius: 0.75rem;
border: 1px solid;
font-size: 0.875rem;
}
.alert-success {
background-color: var(--status-success-bg);
border-color: var(--status-success-border);
color: var(--status-success-fg);
}
.alert-info {
background-color: var(--status-info-bg);
border-color: var(--status-info-border);
color: var(--status-info-fg);
}
.alert-warning {
background-color: var(--status-warning-bg);
border-color: var(--status-warning-border);
color: var(--status-warning-fg);
}
.alert-error {
background-color: var(--status-error-bg);
border-color: var(--status-error-border);
color: var(--status-error-fg);
}
.app-header {
display: flex;
align-items: center;
justify-content: space-between;
height: var(--header-height);
padding-left: 1rem;
padding-right: 1rem;
border-bottom: 1px solid var(--border-default);
background-color: color-mix(in srgb, var(--bg-surface) 88%, transparent);
backdrop-filter: blur(12px);
position: sticky;
top: 0;
z-index: 30;
}
.app-sidebar {
width: var(--sidebar-width);
flex-shrink: 0;
border-right: 1px solid var(--border-default);
background-color: var(--bg-surface);
overflow-y: auto;
}
.app-sidebar--collapsed {
width: var(--sidebar-collapsed-width);
}
.sidebar-nav-item {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.625rem 1rem;
margin: 0 0.5rem;
border-radius: 0.75rem;
font-size: 0.875rem;
font-weight: 500;
color: var(--text-muted);
transition: background-color 0.15s, color 0.15s;
}
.sidebar-nav-item:hover {
background-color: var(--bg-surface-soft);
color: var(--text-secondary);
}
.sidebar-nav-item--active {
background-color: color-mix(in srgb, #0ea5e9 12%, var(--bg-surface-soft));
color: #0284c7;
}
html.dark .sidebar-nav-item--active {
color: #7dd3fc;
}
.token-swatch {
border-radius: 0.75rem;
border: 1px solid var(--border-default);
overflow: hidden;
}
.token-swatch__color {
height: 3.5rem;
}
.token-swatch__meta {
padding: 0.5rem 0.75rem;
background-color: var(--bg-surface);
border-top: 1px solid var(--border-subtle);
}
.shell-preview {
border: 1px dashed var(--border-default);
border-radius: 1rem;
overflow: hidden;
background-color: var(--bg-page);
}
.shell-preview__chrome {
height: 2rem;
background-color: var(--bg-surface-strong);
border-bottom: 1px solid var(--border-default);
display: flex;
align-items: center;
padding: 0 0.5rem;
gap: 0.25rem;
}
.shell-preview__dot {
width: 0.5rem;
height: 0.5rem;
border-radius: 9999px;
background-color: var(--border-default);
}
/* Admin — data tables (token-driven, no dark: pairs) */
.admin-table-section {
background-color: var(--bg-surface);
border: 1px solid var(--border-default);
@apply rounded-2xl shadow-sm overflow-hidden animate-fade-in;
}
.admin-table-wrap {
@apply overflow-x-auto;
}
.admin-table-header {
@apply px-8 py-6 border-b border-default flex justify-between items-center;
background-color: var(--bg-surface);
}
.admin-table-header--stacked {
@apply flex-col md:flex-row items-start md:items-center gap-4;
}
.admin-table-filters {
@apply px-8 py-4 border-b border-subtle gap-4;
background-color: var(--bg-surface-soft);
}
.admin-table-filters--inline {
@apply flex flex-wrap p-4 rounded-xl border border-default shadow-sm;
background-color: var(--bg-surface);
}
.admin-table {
@apply w-full text-left;
}
.admin-table thead {
background-color: var(--bg-surface-soft);
border-bottom: 1px solid var(--border-subtle);
}
.admin-table thead th {
@apply font-semibold text-muted uppercase tracking-wider;
}
.admin-table tbody tr {
border-top: 1px solid var(--border-subtle);
transition: background-color 0.15s ease;
}
.admin-table tbody tr:hover {
background-color: var(--bg-surface-soft);
}
.admin-table-empty {
@apply py-12 text-center text-sm text-muted;
}
.admin-table-filter-input {
@apply px-3 py-2 rounded-lg border text-sm outline-none transition;
border-color: var(--border-default);
background-color: var(--bg-surface);
color: var(--text-primary);
}
.admin-table-filter-input:focus {
border-color: #0ea5e9;
box-shadow: 0 0 0 2px var(--focus-ring);
}
.admin-table-sticky-head {
background-color: var(--bg-surface-soft);
}
.admin-table-sticky-cell {
background-color: var(--bg-surface);
}
.admin-report-table-wrap {
@apply overflow-x-auto rounded-2xl border border-default shadow-elevated;
background-color: var(--bg-surface);
}
.admin-report-table thead {
@apply sticky top-0 text-xs uppercase tracking-wider;
background: linear-gradient(
to right,
var(--bg-surface-strong),
color-mix(in srgb, var(--bg-surface-soft) 75%, #0ea5e9 25%)
);
color: var(--text-secondary);
}
.admin-report-table thead th {
@apply font-semibold border-b border-default align-top;
}
.admin-report-table tbody tr {
border-top: 1px solid var(--border-subtle);
transition: background-color 0.15s ease;
}
.admin-report-table tbody tr:nth-child(odd) {
background-color: var(--bg-surface);
}
.admin-report-table tbody tr:nth-child(even) {
background-color: color-mix(in srgb, var(--bg-surface-soft) 65%, transparent);
}
.admin-report-table tbody tr:hover {
background-color: color-mix(in srgb, #0ea5e9 8%, var(--bg-surface-soft));
}
.admin-report-table tbody td {
@apply text-sm border-b border-subtle align-top;
color: var(--text-secondary);
}
.admin-report-filter-input {
@apply w-full px-2 py-1 text-xs border rounded outline-none font-normal normal-case;
border-color: var(--border-default);
background-color: var(--bg-surface);
color: var(--text-primary);
}
.admin-report-filter-input:focus {
border-color: #0ea5e9;
box-shadow: 0 0 0 1px var(--focus-ring);
}
/* Admin — reports module shell */
.admin-report-section {
@apply relative rounded-3xl border border-default shadow-elevated overflow-hidden animate-fade-in;
background-color: var(--bg-surface);
background-image: linear-gradient(
145deg,
var(--bg-surface) 0%,
var(--bg-surface-soft) 55%,
color-mix(in srgb, var(--bg-surface-soft) 88%, #0ea5e9 12%) 100%
);
}
.admin-report-toolbar {
@apply px-6 md:px-8 py-5 border-b border-default flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between sticky top-0 z-10;
background-color: color-mix(in srgb, var(--bg-surface) 92%, transparent);
backdrop-filter: blur(12px);
}
.admin-report-badge {
@apply inline-flex items-center rounded-full border border-default px-3 py-1 text-xs font-medium;
background-color: var(--bg-surface-soft);
color: var(--text-secondary);
}
.admin-report-badge--info {
border-color: color-mix(in srgb, #0ea5e9 30%, var(--border-default));
background-color: color-mix(in srgb, #0ea5e9 10%, var(--bg-surface-soft));
color: var(--text-secondary);
}
.admin-report-badge--indigo {
border-color: color-mix(in srgb, #6366f1 30%, var(--border-default));
background-color: color-mix(in srgb, #6366f1 10%, var(--bg-surface-soft));
color: var(--text-secondary);
}
.admin-report-panel {
@apply p-4 md:p-5 rounded-2xl border border-default shadow-sm;
background-color: var(--bg-surface);
}
.admin-report-setting-chip {
@apply flex items-center gap-2 px-3 py-2 rounded-lg border border-default text-xs;
background-color: var(--bg-surface-soft);
color: var(--text-secondary);
}
.admin-report-sort-row {
@apply grid grid-cols-12 items-center gap-2 text-xs p-2 border border-default rounded-lg;
background-color: var(--bg-surface);
}
.admin-report-col-chip {
@apply flex items-center justify-between gap-2 px-2 py-1.5 rounded-lg border border-default;
background-color: var(--bg-surface-soft);
}
.admin-report-header-btn {
@apply text-left transition-colors text-secondary hover:text-brand-600;
}
.admin-report-page-btn {
@apply rounded-lg border border-default px-2.5 py-1.5 text-xs text-secondary transition-colors;
}
.admin-report-page-btn:hover:not(:disabled) {
background-color: var(--bg-surface-soft);
}
.admin-report-page-btn--active {
@apply border-brand-600 bg-brand-600 text-white;
}
.admin-report-page-btn--active:hover {
background-color: #0284c7;
}
.admin-report-page-btn:disabled {
@apply opacity-40 cursor-not-allowed;
}
.admin-nav-btn {
@apply px-4 py-3 text-left text-sm font-medium rounded-xl transition-all flex items-center gap-3 relative overflow-hidden whitespace-nowrap flex-shrink-0;
color: var(--text-muted);
}
.admin-nav-btn:hover:not(.admin-nav-btn--active) {
background-color: var(--bg-surface-soft);
color: var(--text-primary);
}
.admin-nav-btn--active {
background-color: color-mix(in srgb, #0ea5e9 12%, var(--bg-surface-soft));
color: #0284c7;
box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
}
html.dark .admin-nav-btn--active {
color: #7dd3fc;
box-shadow: none;
outline: 1px solid color-mix(in srgb, #0ea5e9 25%, transparent);
outline-offset: -1px;
}
.admin-nav-subitem {
@apply w-full text-left px-4 py-2 text-xs font-medium rounded-lg transition-colors flex items-center gap-2;
color: var(--text-muted);
}
.admin-nav-subitem:hover:not(.admin-nav-subitem--active) {
background-color: var(--bg-surface-soft);
color: var(--text-secondary);
}
.admin-nav-subitem--active {
background-color: color-mix(in srgb, #0ea5e9 12%, var(--bg-surface-soft));
color: #0284c7;
}
html.dark .admin-nav-subitem--active {
color: #7dd3fc;
}
.admin-form-panel {
@apply px-8 py-8 border-b border-default bg-surface;
}
.admin-side-card {
@apply card p-6 h-fit;
}
.admin-panel {
@apply rounded-2xl border border-default bg-surface shadow-sm;
}
.admin-panel-lg {
@apply rounded-3xl border border-default bg-surface shadow-sm;
}
.admin-panel-padding {
@apply p-6;
}
.admin-stat-tile {
@apply rounded-2xl bg-surface-soft px-4 py-3;
}
.admin-modal-overlay {
@apply fixed inset-0 z-50 flex items-start sm:items-center justify-center p-3 sm:p-4 overflow-y-auto bg-overlay backdrop-blur-sm;
}
.admin-modal-panel {
@apply card w-full shadow-elevated flex flex-col;
}
.admin-modal-header {
@apply px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-default flex justify-between items-start shrink-0;
}
.admin-modal-body {
@apply px-5 sm:px-8 py-5 space-y-5 overflow-y-auto flex-1;
}
.admin-modal-footer {
@apply px-5 sm:px-8 py-4 border-t border-default flex justify-end gap-3 bg-surface rounded-b-2xl shrink-0;
}
.admin-modal-footer--muted {
background-color: var(--bg-surface-soft);
}
.admin-dropdown {
@apply absolute z-20 mt-2 max-h-64 overflow-auto rounded-xl border border-default bg-surface shadow-elevated;
}
.admin-code-block {
@apply p-3 rounded-lg border border-default text-sm font-mono break-all;
background-color: var(--bg-surface-soft);
color: var(--text-secondary);
}
.admin-pre-block {
@apply mt-1 max-h-[200px] overflow-auto whitespace-pre-wrap rounded-lg border border-default p-2 font-mono text-[10px];
background-color: var(--bg-surface-strong);
color: var(--text-secondary);
}
.admin-pre-block--sql {
@apply mt-1 max-h-none overflow-auto whitespace-pre-wrap rounded-lg border border-default p-3 font-mono text-xs text-emerald-600;
background-color: var(--bg-surface-strong);
}
html.dark .admin-pre-block--sql {
color: #6ee7b7;
}
.admin-checkbox {
@apply w-4 h-4 cursor-pointer rounded border-default text-brand-600 focus:ring-brand-500;
}
.admin-checkbox-lg {
@apply w-5 h-5 cursor-pointer rounded border-default text-blue-600 focus:ring-blue-500;
}
/* Segment control — 与个人中心「主题」切换同款(细边框 + brand 选中态) */
.segment-control {
@apply grid w-full gap-2;
}
.segment-control--cols-2 {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.segment-control--cols-3 {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.segment-control--cols-4 {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
@media (min-width: 640px) {
.segment-control--cols-4 {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
}
/* 工具栏内 2 个短标签(如 数据库直联 | 外部 API) */
.segment-control--fit {
@apply inline-grid w-auto;
grid-template-columns: repeat(2, max-content);
}
.segment-control--fit .segment-item {
@apply w-auto;
}
.segment-item {
@apply w-full cursor-pointer whitespace-nowrap rounded-xl border border-default bg-surface px-3 py-3 text-center text-sm font-medium text-secondary transition-colors;
}
.segment-item:hover:not(:disabled):not(.segment-item--active) {
@apply bg-surface-soft text-primary;
}
.segment-item--active {
@apply border-brand-500 bg-brand-50 text-brand-700;
}
html.dark .segment-item--active {
@apply border-brand-400 bg-brand-950/50 text-brand-300;
}
.segment-item:disabled {
@apply cursor-not-allowed opacity-60;
}
.segment-control--sm .segment-item {
@apply px-3 py-2 text-xs;
}
.segment-control--md .segment-item {
@apply px-3 py-3 text-sm;
}
/* @deprecated — use .segment-control + .segment-item */
.btn-segment-group {
@apply segment-control segment-control--cols-2 segment-control--sm;
}
.btn-segment-group .btn-segment {
@apply segment-item;
border: none;
border-radius: 0.5rem;
box-shadow: none;
}
.btn-segment-group .btn-segment.btn-segment--active {
@apply segment-item--active;
}
/* KB admin panel (embedded in AdminView) */
.kb-admin-header {
@apply flex flex-col gap-4 border-b border-default bg-surface px-8 py-6 lg:flex-row lg:items-start lg:justify-between;
}
.kb-admin-toolbar {
@apply inline-flex w-full items-stretch divide-x divide-subtle overflow-hidden rounded-xl border border-default sm:w-auto;
background-color: var(--bg-surface-soft);
}
.kb-admin-toolbar-btn {
@apply inline-flex flex-1 items-center justify-center gap-1.5 px-3 py-2.5 text-sm font-medium transition-colors sm:flex-none sm:px-4;
color: var(--text-secondary);
}
.kb-admin-toolbar-btn:hover {
background-color: var(--bg-surface);
color: var(--text-primary);
}
.kb-admin-body {
@apply grid grid-cols-1 gap-6 bg-surface p-8 xl:grid-cols-[420px_minmax(0,1fr)];
}
.kb-admin-section {
@apply admin-panel p-6;
}
.kb-admin-card {
@apply admin-panel px-4 py-4;
}
.kb-admin-empty {
@apply rounded-2xl border border-dashed px-4 py-10 text-center text-sm text-muted;
border-color: var(--border-default);
background-color: var(--bg-surface-soft);
}
.kb-admin-badge {
@apply rounded-full bg-surface-soft px-2.5 py-1 text-xs font-medium text-secondary shrink-0;
}
/* Chat — L2 */
.chat-sidebar-btn {
@apply flex w-full items-center justify-center gap-2 rounded-xl border border-default bg-surface-soft py-3 text-sm font-medium text-secondary shadow-sm transition-colors hover-surface-strong;
}
.chat-sidebar-btn-icon {
@apply flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-surface-soft text-secondary shadow-sm transition-colors hover-surface-strong;
}
.chat-history-item {
@apply relative flex w-full items-center justify-between rounded-lg transition-colors hover-surface-soft;
}
.chat-history-item--active {
background-color: color-mix(in srgb, #0ea5e9 12%, var(--bg-surface-soft));
}
.chat-history-link {
@apply flex-1 truncate px-3 py-2.5 text-left text-sm pr-8 text-secondary;
}
.chat-history-link--active {
@apply font-medium text-brand-700;
}
html.dark .chat-history-link--active {
color: #7dd3fc;
}
.chat-dropdown {
@apply absolute z-50 rounded-xl border border-default bg-surface py-1 shadow-elevated;
}
.chat-msg-assistant {
@apply w-full rounded-2xl border border-default bg-surface px-6 py-4 text-[15px] leading-relaxed text-primary shadow-sm;
}
.chat-agent-panel {
@apply mb-4 rounded-2xl border border-default p-3;
background-color: color-mix(in srgb, var(--bg-surface-soft) 85%, transparent);
}
.chat-icon-muted {
@apply text-muted transition-colors hover:text-secondary;
}
/* Workspace logged-in — L3 main + L2 nav (reuse admin-nav rhythm) */
.ws-main {
@apply min-w-0 section-gap bg-page page-shell-mobile md:py-8 lg:px-8;
}
.ws-nav-btn {
@apply flex w-full items-center gap-3 rounded-2xl px-4 py-3 text-left text-[15px] font-medium transition-all;
color: var(--text-secondary);
}
.ws-nav-btn:hover:not(.ws-nav-btn--active) {
background-color: var(--bg-surface-soft);
color: var(--text-primary);
}
.ws-nav-btn--active {
background-color: color-mix(in srgb, #0ea5e9 12%, var(--bg-surface-soft));
color: #0284c7;
box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
}
html.dark .ws-nav-btn--active {
color: #7dd3fc;
outline: 1px solid color-mix(in srgb, #0ea5e9 25%, transparent);
outline-offset: -1px;
}
.ws-nav-btn--danger {
@apply text-red-500 hover:bg-red-50 hover:text-red-600;
}
html.dark .ws-nav-btn--danger {
@apply text-red-400 hover:bg-red-950/40 hover:text-red-300;
}
.ws-card {
@apply admin-panel-lg px-6 py-6 shadow-sm md:px-8;
}
.ws-history-card {
@apply w-full admin-panel p-3 text-left transition-colors hover:border-brand-300;
background-color: var(--bg-surface);
}
.ws-history-card:hover {
background-color: color-mix(in srgb, #0ea5e9 8%, var(--bg-surface));
}
/* Shared dialogs — app-wide (Dify, delete confirm, feedback, file preview) */
.dialog-overlay {
@apply fixed inset-0 flex items-start sm:items-center justify-center p-3 sm:p-4 overflow-y-auto bg-overlay backdrop-blur-sm;
z-index: 100;
}
.dialog-overlay--z80 {
z-index: 80;
}
.dialog-overlay--z110 {
z-index: 110;
}
.dialog-panel {
@apply card w-full shadow-elevated flex flex-col;
}
.dialog-header {
@apply flex items-center justify-between gap-4 border-b border-default shrink-0 px-5 py-4 sm:px-8 sm:pt-7 sm:pb-4;
}
.dialog-header--compact {
@apply px-6 py-4;
}
.dialog-body {
@apply overflow-y-auto flex-1 px-5 py-5 sm:px-8 form-stack;
}
.dialog-body--flush {
@apply px-0 py-0;
}
.dialog-footer {
@apply flex justify-end gap-3 border-t border-default shrink-0 px-5 py-4 sm:px-8 rounded-b-2xl;
background-color: var(--bg-surface);
}
.dialog-stat-card {
@apply admin-panel px-4 py-4;
}
.dialog-preview-body {
@apply flex-1 overflow-auto p-4 bg-page;
}
.dialog-preview-frame {
@apply bg-surface border border-default rounded-lg;
}
.dialog-icon-warning {
@apply inline-flex h-[22px] w-[22px] shrink-0 items-center justify-center rounded-full text-sm font-semibold leading-none mt-0.5;
background-color: var(--status-warning-bg);
color: var(--status-warning-fg);
border: 1px solid var(--status-warning-border);
}
.theme-toggle-btn {
@apply flex items-center justify-center rounded-full border border-default backdrop-blur-md transition-all text-muted hover:text-primary hover:shadow-md;
background-color: color-mix(in srgb, var(--bg-surface) 88%, transparent);
}
.theme-toggle-btn--inline {
@apply h-8 w-8 md:h-9 md:w-9 shadow-sm;
}
.theme-toggle-btn--floating {
@apply fixed bottom-5 right-5 z-[70] h-11 w-11 shadow-lg hover:shadow-xl;
}
/* KB Workspace */
.kb-ws-section {
@apply admin-panel-lg p-6;
}
.kb-ws-card {
@apply admin-panel p-4 transition-colors h-full min-h-[260px] flex flex-col;
}
.kb-ws-card--interactive {
@apply kb-ws-card cursor-pointer hover:border-brand-300;
}
.kb-ws-stat-grid {
@apply mb-6 grid grid-cols-2 gap-3 admin-panel-lg p-4 md:grid-cols-4 xl:grid-cols-7;
}
.kb-ws-stat-tile {
@apply admin-stat-tile text-center transition-colors;
}
.kb-ws-group-list-btn {
@apply w-full admin-panel px-4 py-4 text-left transition-all;
}
.kb-ws-group-list-btn--active {
border-color: color-mix(in srgb, #0ea5e9 40%, var(--border-default));
background-color: color-mix(in srgb, #0ea5e9 10%, var(--bg-surface-soft));
color: #0284c7;
}
html.dark .kb-ws-group-list-btn--active {
color: #7dd3fc;
}
.kb-ws-badge-count {
@apply kb-admin-badge;
}
.kb-ws-icon-btn {
@apply btn-icon-ds rounded-2xl border border-default;
}
.kb-ws-tooltip {
@apply pointer-events-none absolute left-0 top-8 z-10 hidden w-80 admin-panel px-4 py-3 text-sm text-muted shadow-elevated group-hover:block;
}
}
+103
View File
@@ -0,0 +1,103 @@
/**
* shared/styles/tokens.css
* Design tokens:颜色、间距、圆角等 CSS 变量。
*/
/**
* L1 Design Tokens — single source for light/dark colors.
* Toggle theme via html.dark (useTheme); do not duplicate values in components.
*/
:root {
/* Surfaces */
--bg-page: #f8fafc;
--bg-surface: #ffffff;
--bg-surface-soft: #f8fafc;
--bg-surface-strong: #f1f5f9;
/* Text */
--text-primary: #0f172a;
--text-secondary: #334155;
--text-muted: #64748b;
/* Borders & effects */
--border-default: #e2e8f0;
--border-subtle: #f1f5f9;
--overlay-soft: rgba(15, 23, 42, 0.4);
--shadow-elevated: 0 8px 30px -12px rgba(15, 23, 42, 0.2);
--glow-accent: 0 0 0 1px rgba(14, 165, 233, 0.18), 0 16px 40px -22px rgba(14, 165, 233, 0.45);
--focus-ring: rgba(14, 165, 233, 0.35);
/* Status — backgrounds & foregrounds */
--status-success-bg: #eef8e8;
--status-success-border: #b7e2a7;
--status-success-fg: #389e0d;
--status-info-bg: #eaf4ff;
--status-info-border: #9fcbff;
--status-info-fg: #1677ff;
--status-warning-bg: #fff8e8;
--status-warning-border: #ffd88a;
--status-warning-fg: #d48806;
--status-error-bg: #fff1f0;
--status-error-border: #ffb3b0;
--status-error-fg: #cf1322;
/* L3 layout constants */
--header-height: 3.5rem;
--sidebar-width: 16rem;
--sidebar-collapsed-width: 4rem;
--content-max-width: 80rem;
/* Spacing rhythm (L2/L3 reference — prefer semantic classes over raw gap-*) */
--space-page-x: 1rem;
--space-page-x-md: 2rem;
--space-section: 1.5rem;
--space-section-lg: 2rem;
--space-card: 1.5rem;
--space-form: 1rem;
--radius-control: 0.75rem;
--radius-surface: 1rem;
--glass-panel-bg: rgba(255, 255, 255, 0.68);
--glass-panel-border: rgba(148, 163, 184, 0.26);
--chat-composer-gradient: linear-gradient(180deg, rgba(255, 255, 255, 0.97) 0%, rgba(248, 250, 252, 0.97) 100%);
--chat-composer-shadow: 0 14px 28px -20px rgba(15, 23, 42, 0.38);
--chat-composer-shadow-focus: 0 16px 34px -22px rgba(14, 165, 233, 0.45);
}
html.dark {
color-scheme: dark;
--bg-page: #020617;
--bg-surface: #0b1220;
--bg-surface-soft: #0f172a;
--bg-surface-strong: #1e293b;
--text-primary: #f8fafc;
--text-secondary: #cbd5e1;
--text-muted: #94a3b8;
--border-default: #334155;
--border-subtle: #1e293b;
--overlay-soft: rgba(2, 6, 23, 0.72);
--shadow-elevated: 0 12px 30px -16px rgba(2, 6, 23, 0.85);
--glow-accent: 0 0 0 1px rgba(56, 189, 248, 0.28), 0 20px 44px -24px rgba(56, 189, 248, 0.5);
--focus-ring: rgba(56, 189, 248, 0.4);
--status-success-bg: rgba(34, 197, 94, 0.12);
--status-success-border: rgba(34, 197, 94, 0.35);
--status-success-fg: #86efac;
--status-info-bg: rgba(56, 189, 248, 0.12);
--status-info-border: rgba(56, 189, 248, 0.35);
--status-info-fg: #7dd3fc;
--status-warning-bg: rgba(250, 204, 21, 0.12);
--status-warning-border: rgba(250, 204, 21, 0.35);
--status-warning-fg: #fde047;
--status-error-bg: rgba(239, 68, 68, 0.12);
--status-error-border: rgba(239, 68, 68, 0.35);
--status-error-fg: #fca5a5;
--glass-panel-bg: rgba(2, 6, 23, 0.66);
--glass-panel-border: rgba(71, 85, 105, 0.5);
--chat-composer-gradient: linear-gradient(180deg, rgba(15, 23, 42, 0.92) 0%, rgba(10, 16, 30, 0.92) 100%);
--chat-composer-shadow: 0 18px 36px -28px rgba(2, 6, 23, 0.96);
--chat-composer-shadow-focus: 0 16px 34px -22px rgba(56, 189, 248, 0.45);
}
+31
View File
@@ -0,0 +1,31 @@
/**
* shared/styles/utilities.css
* 全局 Tailwind 辅助类扩展(L1 semantic utilities)。
*/
/**
* L1 semantic utilities — use these instead of bg-white dark:bg-slate-900 pairs.
*/
@layer utilities {
.bg-page { background-color: var(--bg-page); }
.bg-surface { background-color: var(--bg-surface); }
.bg-surface-soft { background-color: var(--bg-surface-soft); }
.bg-surface-strong { background-color: var(--bg-surface-strong); }
.text-primary { color: var(--text-primary); }
.text-secondary { color: var(--text-secondary); }
.text-muted { color: var(--text-muted); }
.border-default { border-color: var(--border-default); }
.border-subtle { border-color: var(--border-subtle); }
.shadow-elevated { box-shadow: var(--shadow-elevated); }
.bg-overlay { background-color: var(--overlay-soft); }
.hover-surface-soft:hover { background-color: var(--bg-surface-soft); }
.hover-surface-strong:hover { background-color: var(--bg-surface-strong); }
.divide-subtle > :not([hidden]) ~ :not([hidden]) {
border-color: var(--border-subtle);
}
}
+1 -1
View File
@@ -1 +1 @@
export type { AuthUser } from '@/utils/auth';
export type { AuthUser } from '@/shared/utils/auth';
+107
View File
@@ -0,0 +1,107 @@
/**
* shared/types/schedule.types.ts
* 定时任务 / 排程执行记录类型,admin 与 workspace 共用。
*/
export interface ScheduleTask {
id: number;
schedule_no: string;
name: string;
schedule_type: string;
owner_user_id: number;
owner_username?: string | null;
cron_expr: string;
wait_seconds: number;
dify_agent_id?: number | null;
platform_api_path?: string | null;
data_source_type?: string;
kb_sync_enabled?: boolean;
kb_group_id?: number | null;
notify_user_ids_json: number[];
notify_enabled: boolean;
enabled: boolean;
next_run_at?: string | null;
last_run_at?: string | null;
last_status?: string | null;
created_at?: string | null;
updated_at?: string | null;
}
export interface ScheduleRun {
id: number;
run_no: string;
schedule_task_id: number;
schedule_name?: string | null;
trigger_type: string;
started_at?: string | null;
finished_at?: string | null;
duration_ms: number;
status: string;
total_count: number;
success_count: number;
failed_count: number;
api_request_json?: Record<string, any> | null;
api_response_json?: Record<string, any> | null;
response_summary_json?: Record<string, any> | null;
step_logs?: StepLog[] | null;
dify_execution_snapshot?: DifyExecutionSnapshot | null;
error_message?: string | null;
excel_file_name?: string | null;
excel_file_size?: number | null;
kb_sync_status?: string | null;
kb_group_id?: number | null;
kb_document_id?: number | null;
kb_document_version_id?: number | null;
kb_sync_job_id?: number | null;
kb_sync_error?: string | null;
wecom_notified: boolean;
wecom_notified_at?: string | null;
wecom_notify_error?: string | null;
created_at?: string | null;
}
export interface StepLog {
step: string;
status: string;
started_at?: string;
finished_at?: string;
duration_ms?: number;
row_id?: string;
detail?: Record<string, any>;
}
export interface DifyExecutionSnapshot {
dify_enabled?: boolean;
dify_agent_id?: number | null;
dify_agent_name?: string | null;
dify_app_id?: string | null;
dify_system_prompt?: string;
captured_at?: string;
}
export interface TestScheduleSqlResult {
total: number;
showing: number;
limit: number;
sql: string;
columns: string[];
rows: Record<string, any>[];
}
export interface TestScheduleRunResult {
run_no: string;
run_id: number;
sql: string;
limit: number;
total_count: number;
success_count: number;
failed_count: number;
skipped_count: number;
details: Record<string, any>[];
errors: string[];
step_logs: StepLog[];
dify_agent_id: number | null;
dify_execution_snapshot?: DifyExecutionSnapshot | null;
kb_sync_status?: string | null;
kb_sync_error?: string | null;
kb_document_id?: number | null;
}
+57
View File
@@ -0,0 +1,57 @@
/**
* shared/utils/agentTabs.ts
* 多标签页 Agent 会话协调(避免重复打开)。
*/
const agentWindowName = (agentId: number): string => `hxops_agent_${agentId}`;
const isBlankWindow = (win: Window): boolean => {
try {
const href = win.location.href;
return href === 'about:blank' || href.endsWith('about:blank');
} catch {
return true;
}
};
/** Mark this browser tab as the chat window for an agent (used by window.open target name). */
export const registerOpenAgentId = (agentId: number | null): void => {
if (agentId && Number.isFinite(agentId) && agentId > 0) {
window.name = agentWindowName(agentId);
return;
}
if (window.name.startsWith('hxops_agent_')) {
window.name = '';
}
};
/** App startup hook (kept for compatibility). */
export const initAgentTabSync = (): void => {
// Named-window focus does not require background listeners.
};
/**
* Focus an existing same-agent tab without reload, or open a new one.
*
* Per HTML: window.open('', target) focuses an existing named window and
* ignores the URL, so the page is not refreshed.
*/
export const openAgentChatTab = (url: string, agentId: number): void => {
const target = agentWindowName(agentId);
const existing = window.open('', target);
if (!existing || existing.closed) {
const opened = window.open(url, target);
opened?.focus();
return;
}
existing.focus();
if (isBlankWindow(existing)) {
try {
existing.location.href = url;
} catch {
window.open(url, target);
}
}
};
+174
View File
@@ -0,0 +1,174 @@
/**
* shared/utils/auth.ts
* 认证 token / 用户读写、logout、跨标签同步。
*/
export interface AuthUser {
id?: number;
username?: string;
real_name?: string;
employee_id?: string;
role?: string;
token?: string;
access_token?: string;
refresh_token?: string;
expires_in?: number;
token_expires_at?: number;
}
export const getStoredAuthUser = (): AuthUser | null => {
const candidates = [
sessionStorage.getItem('hxops_user'),
localStorage.getItem('hxops_user'),
];
for (const stored of candidates) {
if (!stored) continue;
try {
const data = JSON.parse(stored);
return (data.user || data) as AuthUser;
} catch {
continue;
}
}
return null;
};
export const getAuthToken = (): string => {
const user = getStoredAuthUser();
const token = user?.access_token || user?.token;
return token ? String(token) : '';
};
export const getAuthHeaders = (): Record<string, string> => {
const token = getAuthToken();
if (!token) return {};
return { Authorization: `Bearer ${token}` };
};
export const saveAuthUser = (user: AuthUser, remember = false): void => {
const next = { ...user };
if (next.expires_in && !next.token_expires_at) {
// Pre-compute an absolute expiry timestamp for later proactive checks.
next.token_expires_at = Date.now() + Number(next.expires_in) * 1000;
}
const payload = remember
? { user: next, expiry: Date.now() + 30 * 24 * 60 * 60 * 1000 }
: { user: next };
if (remember) {
localStorage.setItem('hxops_user', JSON.stringify(payload));
sessionStorage.removeItem('hxops_user');
} else {
sessionStorage.setItem('hxops_user', JSON.stringify(payload));
localStorage.removeItem('hxops_user');
}
};
const AUTH_LOGOUT_KEY = 'hxops_auth_logout';
const AUTH_BC_NAME = 'hxops_auth';
let _authBroadcast: BroadcastChannel | null = null;
let _authSyncInitialized = false;
const clearAuthStorage = (): void => {
localStorage.removeItem('hxops_user');
sessionStorage.removeItem('hxops_user');
sessionStorage.removeItem('hxops_wecom_state');
sessionStorage.removeItem('hxops_casdoor_state');
};
const broadcastLogout = (): void => {
try {
localStorage.setItem(AUTH_LOGOUT_KEY, String(Date.now()));
localStorage.removeItem(AUTH_LOGOUT_KEY);
} catch {
// ignore quota / private mode errors
}
try {
if (!_authBroadcast) {
_authBroadcast = new BroadcastChannel(AUTH_BC_NAME);
}
_authBroadcast.postMessage({ type: 'logout', ts: Date.now() });
} catch {
// BroadcastChannel may be unavailable
}
};
const dispatchLogout = (detail: Record<string, unknown> = {}): void => {
window.dispatchEvent(new CustomEvent('hxops:logout', { detail }));
};
const handleRemoteLogout = (): void => {
if (!getStoredAuthUser()) return;
clearAuthStorage();
dispatchLogout({ remote: true });
};
/** Clear credentials and notify other tabs in the same browser. */
export const logoutAuth = (): void => {
clearAuthStorage();
broadcastLogout();
dispatchLogout({ source: 'local' });
};
export const clearAuthUser = (): void => {
logoutAuth();
};
/** Listen for logout in other tabs (storage + BroadcastChannel). */
export const initAuthSync = (): void => {
if (_authSyncInitialized) return;
_authSyncInitialized = true;
window.addEventListener('storage', (event: StorageEvent) => {
if (event.key === 'hxops_user' && event.newValue === null && event.oldValue != null) {
handleRemoteLogout();
return;
}
if (event.key === AUTH_LOGOUT_KEY && event.newValue != null) {
handleRemoteLogout();
}
});
try {
if (!_authBroadcast) {
_authBroadcast = new BroadcastChannel(AUTH_BC_NAME);
}
_authBroadcast.onmessage = (event: MessageEvent) => {
if (event.data?.type === 'logout') {
handleRemoteLogout();
}
};
} catch {
// ignore
}
};
let _refreshing: Promise<string | null> | null = null;
export const refreshAccessToken = async (): Promise<string | null> => {
// Single-flight guard: concurrent 401s share one refresh request.
const current = getStoredAuthUser();
const refreshToken = current?.refresh_token;
if (!refreshToken) return null;
if (_refreshing) return _refreshing;
_refreshing = (async () => {
try {
// Backend endpoint wraps Casdoor refresh flow.
const res = await fetch('/api/user/casdoor/refresh', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refresh_token: refreshToken }),
});
if (!res.ok) return null;
const data = await res.json();
if (!data?.access_token) return null;
// Preserve existing profile fields while replacing rotated token material.
saveAuthUser({ ...(current || {}), ...data }, Boolean(localStorage.getItem('hxops_user')));
return String(data.access_token);
} catch {
return null;
} finally {
_refreshing = null;
}
})();
return _refreshing;
};
+51
View File
@@ -0,0 +1,51 @@
/**
* shared/utils/casdoor.ts
* Casdoor OAuth 错误文案解析。
*/
import type { BusinessError } from '@/shared/api/client';
type TranslateFn = (key: string, params?: Record<string, unknown>) => string;
function cleanText(value: unknown): string {
return typeof value === 'string' ? value.trim() : String(value ?? '').trim();
}
export function pickCasdoorErrorCode(err: BusinessError): string {
const code = cleanText(err.code);
if (code.startsWith('CASDOOR_') || code === 'ACCOUNT_DISABLED' || code === 'AUTH.INCORRECT_CURRENT_PASSWORD') {
return code;
}
const detailsCode = cleanText(err.details?.error_code);
if (detailsCode) return detailsCode;
const raw = cleanText(err.message).toLowerCase();
if (raw.includes('invalid or expired casdoor state')) return 'CASDOOR_STATE_EXPIRED';
if (raw.includes('invalid_grant')) return 'CASDOOR_INVALID_CREDENTIALS';
if (raw.includes("doesn't exist") || raw.includes('does not exist')) return 'CASDOOR_USER_NOT_IN_IDP';
return code;
}
export function resolveCasdoorErrorMessage(err: BusinessError, t: TranslateFn): string {
const errorCode = pickCasdoorErrorCode(err);
const keyMap: Record<string, string> = {
CASDOOR_INVALID_CREDENTIALS: 'login.casdoorErrors.invalidCredentials',
CASDOOR_CODE_EXPIRED: 'login.casdoorErrors.codeExpired',
CASDOOR_STATE_EXPIRED: 'login.casdoorErrors.stateExpired',
CASDOOR_USER_NOT_FOUND: 'workspace.msg.casdoorNotMatchedContactAdmin',
ACCOUNT_DISABLED: 'login.accountDisabled',
CASDOOR_ACCESS_DENIED: 'login.casdoorErrors.accessDenied',
CASDOOR_CONFIG_ERROR: 'login.casdoorErrors.configError',
CASDOOR_AUTH_FAILED: 'login.casdoorErrors.authFailed',
CASDOOR_PASSWORD_POLICY: 'login.casdoorErrors.passwordPolicy',
CASDOOR_SET_PASSWORD_FAILED: 'login.casdoorErrors.setPasswordFailed',
CASDOOR_USER_NOT_IN_IDP: 'login.casdoorErrors.userNotInIdp',
'AUTH.INCORRECT_CURRENT_PASSWORD': 'login.casdoorErrors.incorrectCurrentPassword',
'VALIDATION.INVALID_PARAM': 'login.casdoorErrors.stateExpired',
};
const key = keyMap[errorCode];
if (key) return t(key);
const raw = cleanText(err.message);
if (raw === 'Incorrect username or password') return t('login.casdoorErrors.invalidCredentials');
if (raw === 'Incorrect current password') return t('login.casdoorErrors.incorrectCurrentPassword');
if (raw === 'Invalid or expired Casdoor state') return t('login.casdoorErrors.stateExpired');
return raw || t('login.casdoorErrors.authFailed');
}
+40
View File
@@ -0,0 +1,40 @@
/**
* shared/utils/clipboard.ts
* 剪贴板写入兼容封装。
*/
/**
* Copy plain text to the clipboard with fallbacks for restricted browsers
* (e.g. WeCom embedded WebView, HTTP deployments).
*/
export async function copyTextToClipboard(text: string): Promise<boolean> {
const value = String(text ?? '');
if (!value.trim()) return false;
if (navigator.clipboard?.writeText) {
try {
await navigator.clipboard.writeText(value);
return true;
} catch {
// Fall through to legacy copy.
}
}
try {
const textarea = document.createElement('textarea');
textarea.value = value;
textarea.setAttribute('readonly', 'true');
textarea.style.position = 'fixed';
textarea.style.left = '-9999px';
textarea.style.top = '0';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
textarea.setSelectionRange(0, value.length);
const ok = document.execCommand('copy');
document.body.removeChild(textarea);
return ok;
} catch {
return false;
}
}
@@ -0,0 +1,24 @@
/**
* shared/utils/lastChatAgent.ts
* 最近访问的聊天 Agent ID 持久化。
*/
const STORAGE_KEY = 'hxops_last_chat_agent_id';
export function getLastChatAgentId(fallback = 16): number {
try {
const raw = sessionStorage.getItem(STORAGE_KEY);
const id = Number(raw);
return Number.isFinite(id) && id > 0 ? id : fallback;
} catch {
return fallback;
}
}
export function setLastChatAgentId(agentId: number): void {
if (!Number.isFinite(agentId) || agentId <= 0) return;
try {
sessionStorage.setItem(STORAGE_KEY, String(agentId));
} catch {
// ignore storage failures
}
}
+335
View File
@@ -0,0 +1,335 @@
/**
* shared/utils/wecom.ts
* 企业微信登录/绑定相关工具与文案格式化。
*/
export type WecomMatchField = 'employee_id' | 'mobile' | 'email';
export interface WecomNormalizedMatchRules {
operator: 'AND' | 'OR';
fields: WecomMatchField[];
}
export interface WecomLoginErrorPayload {
error?: string | null;
error_code?: string | null;
reason?: string | null;
missing_field?: string | null;
candidate_count?: number | null;
match_rules?: unknown;
}
export interface WecomLoginDialogContent {
title: string;
summary: string;
details: string[];
technical?: string;
}
export interface WecomAuditRowLike {
status?: string | null;
reason?: string | null;
error_code?: string | null;
match_rules?: string | null;
match_operator?: string | null;
match_result?: string | null;
}
type TranslateFn = (key: string, params?: Record<string, unknown>) => string;
const KNOWN_MATCH_FIELDS: WecomMatchField[] = ['employee_id', 'mobile', 'email'];
function cleanText(value: unknown): string {
return typeof value === 'string' ? value.trim() : String(value ?? '').trim();
}
function normalizeMatchField(value: unknown): WecomMatchField | null {
const normalized = cleanText(value).toLowerCase();
return KNOWN_MATCH_FIELDS.includes(normalized as WecomMatchField)
? (normalized as WecomMatchField)
: null;
}
function getFieldGuide(field: WecomMatchField | null, t: TranslateFn): string {
if (field === 'mobile') return t('login.wecomFieldGuides.mobile');
if (field === 'email') return t('login.wecomFieldGuides.email');
if (field === 'employee_id') return t('login.wecomFieldGuides.employee_id');
return t('login.wecomFieldGuides.default');
}
function extractMissingField(reason: string): WecomMatchField | null {
if (!reason.startsWith('missing_attr:')) return null;
return normalizeMatchField(reason.split(':', 2)[1]);
}
function formatRuleList(fields: WecomMatchField[], operator: 'AND' | 'OR', t: TranslateFn): string {
if (fields.length === 0) return t('login.wecomFieldLabels.match_rules');
const labels = fields.map((field) => formatWecomFieldLabel(field, t));
if (labels.length === 1) return labels[0] || t('login.wecomFieldLabels.match_rules');
const joiner = operator === 'OR' ? ` ${t('login.wecomRuleJoin.or')} ` : ` ${t('login.wecomRuleJoin.and')} `;
return labels.join(joiner);
}
function buildTechnicalInfo(errorCode: string, rawError: string): string | undefined {
const parts: string[] = [];
if (errorCode) parts.push(`code=${errorCode}`);
if (rawError) parts.push(rawError);
return parts.length ? parts.join(' | ') : undefined;
}
export function normalizeWecomMatchRules(
input: unknown,
fallbackOperator: unknown = 'AND',
): WecomNormalizedMatchRules {
let fieldsSource: unknown[] = [];
let operator: 'AND' | 'OR' = cleanText(fallbackOperator).toUpperCase() === 'OR' ? 'OR' : 'AND';
if (Array.isArray(input)) {
fieldsSource = input;
} else if (typeof input === 'string') {
fieldsSource = input.split(',');
} else if (input && typeof input === 'object') {
const maybeRules = input as Record<string, unknown>;
fieldsSource = Array.isArray(maybeRules.fields) ? maybeRules.fields : [];
operator = cleanText(maybeRules.operator).toUpperCase() === 'OR' ? 'OR' : operator;
}
const fields = fieldsSource
.map((value) => normalizeMatchField(value))
.filter((value): value is WecomMatchField => Boolean(value));
return { operator, fields };
}
export function formatWecomFieldLabel(field: unknown, t: TranslateFn): string {
const normalized = normalizeMatchField(field);
if (normalized === 'employee_id') return t('login.wecomFieldLabels.employee_id');
if (normalized === 'mobile') return t('login.wecomFieldLabels.mobile');
if (normalized === 'email') return t('login.wecomFieldLabels.email');
return t('login.wecomFieldLabels.match_rules');
}
export function formatWecomRuleText(
input: unknown,
t: TranslateFn,
fallbackOperator: unknown = 'AND',
): string {
const rules = normalizeWecomMatchRules(input, fallbackOperator);
return formatRuleList(rules.fields, rules.operator, t);
}
export function buildWecomLoginDialogContent(
payload: WecomLoginErrorPayload,
t: TranslateFn,
): WecomLoginDialogContent {
const rawError = cleanText(payload.error);
const errorCode = cleanText(payload.error_code);
const reason = cleanText(payload.reason);
const rulesText = formatWecomRuleText(payload.match_rules, t);
const technical = buildTechnicalInfo(errorCode, rawError);
if (errorCode === 'WECOM_MATCH_ATTR_MISSING') {
const missingField = normalizeMatchField(payload.missing_field) || extractMissingField(reason);
return {
title: t('login.wecomDialogTitles.matchAttrMissing'),
summary: t('login.wecomDialogSummaries.matchAttrMissing', {
field: formatWecomFieldLabel(missingField, t),
}),
details: [
t('login.wecomDialogDetails.currentRules', { rules: rulesText }),
getFieldGuide(missingField, t),
t('login.wecomDialogDetails.bindFallback'),
],
technical,
};
}
if (errorCode === 'WECOM_MATCH_AMBIGUOUS') {
const candidateCount = Number(payload.candidate_count || 0);
return {
title: t('login.wecomDialogTitles.matchAmbiguous'),
summary: candidateCount > 1
? t('login.wecomDialogSummaries.matchAmbiguousWithCount', { count: candidateCount })
: t('login.wecomDialogSummaries.matchAmbiguous'),
details: [
t('login.wecomDialogDetails.currentRules', { rules: rulesText }),
t('login.wecomDialogDetails.ambiguousAction'),
],
technical,
};
}
if (errorCode === 'WECOM_BIND_REQUIRED') {
return {
title: t('login.wecomDialogTitles.bindRequired'),
summary: t('login.wecomDialogSummaries.bindRequired'),
details: [
t('login.wecomDialogDetails.currentRules', { rules: rulesText }),
t('login.wecomDialogDetails.bindRequiredAction'),
],
technical,
};
}
if (errorCode === 'WECOM_BIND_INPUT_REQUIRED') {
return {
title: t('login.wecomDialogTitles.bindInputRequired'),
summary: t('login.wecomDialogSummaries.bindInputRequired'),
details: [
t('login.wecomDialogDetails.bindInputRequiredAction'),
],
technical,
};
}
if (errorCode === 'WECOM_BIND_CONFLICT') {
return {
title: t('login.wecomDialogTitles.bindConflict'),
summary: t('login.wecomDialogSummaries.bindConflict'),
details: [
rawError || t('login.wecomDialogDetails.bindConflictAction'),
t('login.wecomDialogDetails.bindConflictAction'),
],
technical,
};
}
if (errorCode === 'WECOM_NOT_IN_AGENT_SCOPE') {
return {
title: t('login.wecomDialogTitles.notInScope'),
summary: t('login.wecomDialogSummaries.notInScope'),
details: [
rawError || t('login.wecomDialogDetails.notInScopeAction'),
],
technical,
};
}
if (rawError.includes('Invalid or expired WeCom state')) {
return {
title: t('login.wecomDialogTitles.stateExpired'),
summary: t('login.wecomStateExpired'),
details: [t('login.wecomDialogDetails.retryLogin')],
technical,
};
}
if (rawError.includes('Account is disabled')) {
return {
title: t('login.wecomDialogTitles.accountDisabled'),
summary: t('login.wecomAccountDisabled'),
details: [t('login.wecomDialogDetails.contactAdmin')],
technical,
};
}
if (rawError.includes('bind WeCom account') || rawError.includes('No linked account found')) {
return {
title: t('login.wecomDialogTitles.bindRequired'),
summary: t('login.wecomDialogSummaries.bindRequired'),
details: [
t('login.wecomDialogDetails.currentRules', { rules: rulesText }),
t('login.wecomDialogDetails.bindRequiredAction'),
],
technical,
};
}
return {
title: t('login.wecomDialogTitles.loginFailed'),
summary: rawError || t('login.wecomLoginFailed'),
details: [t('login.wecomDialogDetails.retryLogin')],
technical,
};
}
function formatWecomMatchResult(result: string, t: TranslateFn): string {
if (result === 'already_bound') return t('admin.wecom.auditResults.already_bound');
if (result === 'matched_and_bound') return t('admin.wecom.auditResults.matched_and_bound');
if (result === 'auto_created') return t('admin.wecom.auditResults.auto_created');
if (result === 'input_verified_and_bound') return t('admin.wecom.auditResults.input_verified_and_bound');
return result || '-';
}
export function formatWecomAuditReason(row: WecomAuditRowLike, t: TranslateFn): string {
const reason = cleanText(row.reason);
const errorCode = cleanText(row.error_code);
if (cleanText(row.status) === 'success') {
const result = cleanText(row.match_result);
return result ? formatWecomMatchResult(result, t) : t('admin.wecom.auditMessages.loginSuccess');
}
if (errorCode === 'WECOM_MATCH_ATTR_MISSING') {
const field = extractMissingField(reason);
return t('admin.wecom.auditMessages.matchAttrMissing', {
field: formatWecomFieldLabel(field, t),
});
}
if (errorCode === 'WECOM_MATCH_AMBIGUOUS') {
return t('admin.wecom.auditMessages.matchAmbiguous');
}
if (errorCode === 'WECOM_BIND_REQUIRED') {
return t('admin.wecom.auditMessages.bindRequired');
}
if (errorCode === 'WECOM_BIND_CONFLICT') {
return t('admin.wecom.auditMessages.bindConflict');
}
if (errorCode === 'WECOM_BIND_INPUT_REQUIRED') {
return t('admin.wecom.auditMessages.bindInputRequired');
}
if (errorCode === 'WECOM_BIND_INPUT_NOT_FOUND') {
return t('admin.wecom.auditMessages.bindInputNotFound');
}
if (errorCode === 'WECOM_BIND_INPUT_AMBIGUOUS') {
return t('admin.wecom.auditMessages.bindInputAmbiguous');
}
if (errorCode === 'WECOM_NOT_IN_AGENT_SCOPE') {
return t('admin.wecom.auditMessages.notInScope');
}
if (reason === 'invalid_state') return t('admin.wecom.auditMessages.invalidState');
if (reason === 'missing_code') return t('admin.wecom.auditMessages.missingCode');
if (reason === 'account_disabled') return t('admin.wecom.auditMessages.accountDisabled');
if (reason.startsWith('auth_failed:')) {
return t('admin.wecom.auditMessages.authFailed', {
detail: reason.split(':', 2)[1] || '-',
});
}
if (reason.startsWith('user_fetch_failed:')) {
return t('admin.wecom.auditMessages.userFetchFailed', {
detail: reason.split(':', 2)[1] || '-',
});
}
if (reason.startsWith('not_in_agent_scope:')) return t('admin.wecom.auditMessages.notInScope');
if (reason.startsWith('exception:')) {
return t('admin.wecom.auditMessages.exception', {
detail: reason.split(':', 2)[1] || '-',
});
}
return reason || '-';
}
export function buildWecomAuditMeta(row: WecomAuditRowLike, t: TranslateFn): string[] {
const items: string[] = [];
const rulesText = formatWecomRuleText(row.match_rules, t, row.match_operator);
if (cleanText(row.match_rules)) {
items.push(t('admin.wecom.auditMeta.rules', { rules: rulesText }));
}
if (cleanText(row.match_result)) {
items.push(t('admin.wecom.auditMeta.result', {
result: formatWecomMatchResult(cleanText(row.match_result), t),
}));
}
if (cleanText(row.error_code)) {
items.push(t('admin.wecom.auditMeta.errorCode', { code: cleanText(row.error_code) }));
}
return items;
}