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

@@ -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>