fix(admin): 管理控制台界面使用element plus

This commit is contained in:
sophie committed 2026-10-20 17:01:24 +08:00
1 parent 6c47d0639c
commit cdc8610ec1
45 files changed
+6258 -4639

No files matched your search

@@ -0,0 +1,62 @@
/**
* features/admin/components/AdminListPage.vue
* 用途:管理端列表页的唯一卡片骨架。标题、操作、页签、筛选、表格、分页按固定顺序和 32px 内边距排列。
* 依赖:element-plus 的加载指令、components-ds.css 的 admin-table-section / admin-table-header、element-trial.css 的分页条。
* 逻辑:AdminLayout 提供菜单和内容区外边距;各业务页把文案和控件填进插槽。本组件不请求数据。
* 用户管理、部门管理、常用问题等列表调用本组件。页签用 AdminListTabs。页签、筛选、分页没有内容时不占一行。
*/
<script setup lang="ts">
import { ElLoading } from 'element-plus';
import '@/features/admin/styles/element-trial.css';
defineProps<{
/** 首屏整卡加载。为 true 时先盖住卡片,数据回来再画出标题和表格。 */
loading?: boolean;
}>();
const vLoading = ElLoading.directive;
</script>
<template>
<section v-loading="loading" class="admin-table-section admin-list-page min-h-64">
<template v-if="!loading">
<div class="admin-table-header admin-table-header--stacked">
<div class="min-w-0">
<slot name="title" />
</div>
<slot name="actions" />
</div>
<div v-if="$slots.tabs" class="admin-list-page__tabs">
<slot name="tabs" />
</div>
<div v-if="$slots.filters" class="admin-list-page__filters">
<slot name="filters" />
</div>
<slot />
<div v-if="$slots.pagination" class="hx-admin-pager">
<slot name="pagination" />
</div>
</template>
</section>
</template>
<style scoped>
.admin-list-page__tabs {
padding: 0 32px;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.admin-list-page__filters {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
padding: 16px 32px;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.admin-list-page__filters :deep(.el-input),
.admin-list-page__filters :deep(.el-select) {
flex: none;
}
</style>
@@ -0,0 +1,89 @@
/**
* features/admin/components/AdminListTabs.vue
* 用途:管理端列表卡片里的页签条。只负责切换,不放表格和筛选。
* 依赖:element-plus 的 ElTabs、ElTabPane、ElTag。
* 逻辑:放进 AdminListPage 的 tabs 插槽。当前页签用 v-model 交给页面,页面再决定筛选和表格。
*/
<script setup lang="ts">
import { ElTabPane, ElTabs, ElTag } from 'element-plus';
/** 一个页签。badge 为 0 或空时不显示数字。 */
export interface AdminListTabItem {
name: string;
label: string;
badge?: number | string;
}
defineProps<{
/** 当前页签名,对应 items 里的 name。 */
modelValue: string;
items: AdminListTabItem[];
}>();
const emit = defineEmits<{
'update:modelValue': [value: string];
}>();
/**
* 把 Element 页签切换写回 v-model。
* @param name - 被点中的页签名
*/
function onTabChange(name: string | number): void {
emit('update:modelValue', String(name));
}
/**
* 数字为 0 或空时不画角标。
* @param badge - 页签上的数量
* @returns 是否显示角标
*/
function showBadge(badge: number | string | undefined): boolean {
return badge != null && badge !== '' && badge !== 0;
}
</script>
<template>
<ElTabs :model-value="modelValue" class="admin-list-tabs" @tab-change="onTabChange">
<ElTabPane v-for="item in items" :key="item.name" :name="item.name">
<template #label>
<span class="admin-list-tabs__label">
{{ item.label }}
<ElTag v-if="showBadge(item.badge)" type="warning" effect="light" size="small">
{{ item.badge }}
</ElTag>
</span>
</template>
</ElTabPane>
</ElTabs>
</template>
<style scoped>
.admin-list-tabs :deep(.el-tabs__header) {
margin-bottom: 0;
}
.admin-list-tabs :deep(.el-tabs__nav-wrap::after) {
display: none;
}
.admin-list-tabs :deep(.el-tabs__content) {
display: none;
}
.admin-list-tabs :deep(.el-tabs__item) {
height: 40px;
padding: 0 16px;
font-size: var(--el-font-size-base);
line-height: 40px;
}
.admin-list-tabs :deep(.el-tabs__active-bar + .el-tabs__item) {
padding-left: 0;
}
.admin-list-tabs__label {
display: inline-flex;
align-items: center;
gap: 6px;
}
</style>
@@ -4,6 +4,7 @@
* 用途:管理控制台的应用管理页,提供应用列表、创建/编辑弹窗、测试与授权入口。
* 依赖:useAgentsAdmin 业务编排、Element Plus 表格与按钮、AgentFormModal/AgentTestModal/AgentPermissionModal 弹窗。
* 逻辑:页面加载后先展示应用列表;目录、用户和排程在后台补齐。权限组启用后隐藏按人授权按钮。
* 列表使用 Element stripe 斑马纹。选中行浅底画在单元格上,盖过斑马纹。
*/
<script setup lang="ts">
import { ref, onMounted } from 'vue';
@@ -201,6 +202,7 @@ onMounted(() => {
:data="agents"
row-key="id"
class="agents-element-table hx-admin-table"
stripe
:row-class-name="agentRowClass"
@row-click="onRowClick"
>
@@ -300,8 +302,8 @@ onMounted(() => {
</template>
<style scoped>
.agents-element-table :deep(.agents-row-selected) {
--el-table-tr-bg-color: color-mix(in srgb, #0284c7 8%, transparent);
.agents-element-table :deep(.agents-row-selected td.el-table__cell) {
background: color-mix(in srgb, #0284c7 8%, var(--el-bg-color, #fff));
}
.agents-element-table :deep(.el-table__row) {
@@ -2,12 +2,13 @@
* features/admin/modules/agents/components/AgentCapabilitiesConfig.vue
*
* 用途:应用管理表单中的 capabilities 能力开关面板。
* 依赖:agent.types AgentFormState、useAgentsAdminRegistry catalog 辅助函数、vue-i18n。
* 逻辑:AgentFormModal 挂载本组件;Catalog forced_capabilities 对应项只读展示。
* 依赖:element-plus 复选框、agent.types AgentFormState、useAgentsAdminRegistry catalog 辅助函数、vue-i18n。
* 逻辑:AgentFormModal 挂载本组件;Catalog forced_capabilities 对应项只读展示。内部字段已换 Element。
*/
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElCheckbox, ElTag } from 'element-plus';
import type { AgentCapabilities, AgentFormState } from '@/features/admin/types/agent.types';
import {
catalogForcesCapability,
@@ -41,51 +42,92 @@ const capabilityItems = computed(() => (
));
/**
* 切换 task_progress 时同步 tool_run_progress_enabled,供进度配置面板联动。
* 切换能力开关,并在任务进度上同步 tool_run_progress_enabled。
* 核心逻辑:Catalog 强制项由复选框 disabled 拦住;这里只写用户可改的布尔值。
* @param key - capabilities 字段
* @param checked - Element 复选框回传的新值
*/
const handleCapabilityChange = (key: keyof AgentCapabilities, checked: boolean) => {
props.form.capabilities[key] = checked;
const handleCapabilityChange = (key: keyof AgentCapabilities, checked: string | number | boolean) => {
const enabled = checked === true;
props.form.capabilities[key] = enabled;
if (key === 'task_progress') {
props.form.tool_run_progress_enabled = checked;
props.form.tool_run_progress_enabled = enabled;
}
};
</script>
<template>
<div class="col-span-1 md:col-span-2 rounded-2xl border border-default bg-surface-soft/40 p-4">
<div class="mb-4">
<div class="text-xs font-bold uppercase tracking-wider text-muted">
{{ t('admin.agent.capabilities.title') }}
</div>
<p class="mt-1 text-sm leading-6 text-secondary">
{{ t('admin.agent.capabilities.subtitle') }}
</p>
<div class="agent-form-span agent-form-panel">
<div class="agent-panel-head">
<div class="agent-panel-title">{{ t('admin.agent.capabilities.title') }}</div>
<p class="hx-element-hint">{{ t('admin.agent.capabilities.subtitle') }}</p>
</div>
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
<label
<div class="agent-cap-grid">
<ElCheckbox
v-for="item in capabilityItems"
:key="item.key"
class="inline-flex items-start gap-2 rounded-xl border border-default bg-white px-3 py-2 text-sm text-secondary"
:class="{ 'opacity-80': item.forced }"
:model-value="form.capabilities[item.key]"
:disabled="item.forced"
@change="handleCapabilityChange(item.key, $event)"
>
<input
v-model="form.capabilities[item.key]"
type="checkbox"
class="mt-0.5 accent-brand-600"
:disabled="item.forced"
@change="item.key === 'task_progress'
? handleCapabilityChange('task_progress', ($event.target as HTMLInputElement).checked)
: undefined"
/>
<span>
<span class="font-medium text-primary">{{ item.label }}</span>
<span class="mt-1 block text-xs leading-5 text-muted">{{ item.hint }}</span>
<span v-if="item.forced" class="mt-1 block text-xs leading-5 text-amber-600">
{{ t('admin.agent.capabilities.forcedByCatalog') }}
</span>
</span>
</label>
<span>{{ item.label }}</span>
<span class="hx-element-hint">{{ item.hint }}</span>
<ElTag v-if="item.forced" type="warning" effect="light">
{{ t('admin.agent.capabilities.forcedByCatalog') }}
</ElTag>
</ElCheckbox>
</div>
</div>
</template>
<style scoped>
.agent-form-span {
grid-column: 1 / -1;
}
.agent-form-panel {
margin-bottom: 14px;
padding: 16px;
border: 1px solid var(--el-border-color);
border-radius: var(--el-border-radius-base);
background: var(--el-fill-color-light);
}
.agent-panel-head {
margin-bottom: 12px;
}
.agent-panel-title {
color: var(--el-text-color-primary);
font-size: var(--el-font-size-base);
}
.agent-cap-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.agent-cap-grid :deep(.el-checkbox) {
width: 100%;
height: auto;
align-items: flex-start;
margin-right: 0;
white-space: normal;
}
.agent-cap-grid :deep(.el-checkbox__label) {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 4px;
white-space: normal;
}
@media (max-width: 640px) {
.agent-cap-grid {
grid-template-columns: 1fr;
}
}
</style>
File diff suppressed because it is too large. Load diff
@@ -1,71 +1,138 @@
/**␍
* features/admin/modules/agents/components/AgentToolRunProgressConfig.vue␍
* 用途:应用管理表单中的任务进度关联配置(排程绑定、轮询间隔、运行期锁输入)。␍
* 依赖:agent.types AgentFormState、schedule.types ScheduleTask、vue-i18n。␍
* 逻辑:task_progress 能力开关由 AgentCapabilitiesConfig 维护;本组件只写 bound_schedule_task_id 与 handler_config 轮询参数。␍
*/␍
<script setup lang="ts">␍
import type { AgentFormState } from '@/features/admin/types/agent.types';␍
import type { ScheduleTask } from '@/shared/types/schedule.types';␍
␍
defineProps<{␍
form: AgentFormState;␍
scheduleTasks: ScheduleTask[];␍
/** file_check 等类型需绑定排程任务时才展示关联字段。 */␍
requiresScheduleTask?: boolean;␍
}>();␍
</script>␍
␍
<template>␍
<div class="col-span-1 md:col-span-2 rounded-2xl border border-default bg-surface-soft/40 p-5 space-y-4">␍
<div>␍
<h4 class="text-sm font-semibold text-primary">{{ $t('admin.agent.toolRunProgress.title') }}</h4>␍
<p class="mt-1 text-xs text-muted">{{ $t('admin.agent.toolRunProgress.subtitle') }}</p>␍
</div>␍
␍
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">␍
<div v-if="requiresScheduleTask" class="space-y-2">␍
<label class="text-xs font-bold text-muted uppercase tracking-wider">␍
{{ $t('admin.agent.toolRunProgress.scheduleTaskId') }}␍
</label>␍
<select␍
v-model="form.bound_schedule_task_id"␍
class="w-full input-field text-sm"␍
:disabled="scheduleTasks.length === 0"␍
@change="form.schedule_task_id = form.bound_schedule_task_id"␍
>␍
<option :value="null">␍
{{ scheduleTasks.length === 0␍
? $t('admin.agent.toolRunProgress.noScheduleTasks')␍
: $t('admin.agent.toolRunProgress.selectScheduleTask') }}␍
</option>␍
<option v-for="task in scheduleTasks" :key="task.id" :value="task.id">␍
{{ task.name }}␍
</option>␍
</select>␍
<p class="text-xs text-muted">{{ $t('admin.agent.toolRunProgress.scheduleTaskHint') }}</p>␍
</div>␍
␍
<div v-if="requiresScheduleTask" class="space-y-2">␍
<label class="text-xs font-bold text-muted uppercase tracking-wider">␍
{{ $t('admin.agent.toolRunProgress.pollInterval') }}␍
</label>␍
<input␍
v-model.number="form.poll_interval_seconds"␍
type="number"␍
min="1"␍
max="30"␍
class="w-full input-field text-sm"␍
/>␍
</div>␍
␍
<div v-if="requiresScheduleTask" class="md:col-span-2">␍
<label class="inline-flex items-center gap-2 text-sm text-secondary">␍
<input v-model="form.lock_input_when_running" type="checkbox" class="admin-checkbox" />␍
<span>{{ $t('admin.agent.toolRunProgress.lockInput') }}</span>␍
</label>␍
</div>␍
</div>␍
</div>␍
</template>␍
␍
/**
* features/admin/modules/agents/components/AgentToolRunProgressConfig.vue
* 用途:应用管理表单中的任务进度关联配置(排程绑定、轮询间隔、运行期锁输入)。
* 依赖:element-plus 表单控件、agent.types AgentFormState、schedule.types ScheduleTask、vue-i18n。
* 逻辑:task_progress 能力开关由 AgentCapabilitiesConfig 维护;本组件只写 bound_schedule_task_id 与 handler_config 轮询参数。内部字段已换 Element。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import {
ElCheckbox,
ElFormItem,
ElInputNumber,
ElOption,
ElSelect,
} from 'element-plus';
import type { AgentFormState } from '@/features/admin/types/agent.types';
import type { ScheduleTask } from '@/shared/types/schedule.types';
const props = defineProps<{
form: AgentFormState;
scheduleTasks: ScheduleTask[];
/** file_check 等类型需绑定排程任务时才展示关联字段。 */
requiresScheduleTask?: boolean;
}>();
const { t } = useI18n();
/**
* 选择关联排程。清空写回 null,并同步 schedule_task_id。
* @param value - 选中的排程 id;清空为 undefined
*/
function onScheduleTaskChange(value: number | null | undefined): void {
const taskId = typeof value === 'number' ? value : null;
props.form.bound_schedule_task_id = taskId;
props.form.schedule_task_id = taskId;
}
/**
* 轮询间隔限制在 1 到 30 秒。清空时回落到 1,避免写成空值。
* @param value - 数字输入框的新值
*/
function onPollIntervalChange(value: number | null | undefined): void {
const next = Number(value);
props.form.poll_interval_seconds = Number.isFinite(next) ? Math.min(30, Math.max(1, next)) : 1;
}
</script>
<template>
<div class="agent-form-span agent-form-panel">
<div class="agent-panel-head">
<div class="agent-panel-title">{{ t('admin.agent.toolRunProgress.title') }}</div>
<p class="hx-element-hint">{{ t('admin.agent.toolRunProgress.subtitle') }}</p>
</div>
<div v-if="requiresScheduleTask" class="agent-inner-grid">
<ElFormItem :label="t('admin.agent.toolRunProgress.scheduleTaskId')">
<ElSelect
:model-value="form.bound_schedule_task_id ?? undefined"
clearable
:disabled="scheduleTasks.length === 0"
:placeholder="scheduleTasks.length === 0
? t('admin.agent.toolRunProgress.noScheduleTasks')
: t('admin.agent.toolRunProgress.selectScheduleTask')"
@update:model-value="onScheduleTaskChange"
>
<ElOption
v-for="task in scheduleTasks"
:key="task.id"
:label="task.name"
:value="task.id"
/>
</ElSelect>
<p class="hx-element-hint">{{ t('admin.agent.toolRunProgress.scheduleTaskHint') }}</p>
</ElFormItem>
<ElFormItem :label="t('admin.agent.toolRunProgress.pollInterval')">
<ElInputNumber
:model-value="form.poll_interval_seconds"
:min="1"
:max="30"
:step="1"
controls-position="right"
@update:model-value="onPollIntervalChange"
/>
</ElFormItem>
<ElFormItem class="agent-inner-span">
<ElCheckbox v-model="form.lock_input_when_running">
{{ t('admin.agent.toolRunProgress.lockInput') }}
</ElCheckbox>
</ElFormItem>
</div>
</div>
</template>
<style scoped>
.agent-form-span {
grid-column: 1 / -1;
}
.agent-form-panel {
margin-bottom: 14px;
padding: 16px;
border: 1px solid var(--el-border-color);
border-radius: var(--el-border-radius-base);
background: var(--el-fill-color-light);
}
.agent-panel-head {
margin-bottom: 12px;
}
.agent-panel-title {
color: var(--el-text-color-primary);
font-size: var(--el-font-size-base);
}
.agent-inner-grid {
display: grid;
grid-template-columns: 1fr 1fr;
column-gap: 16px;
}
.agent-inner-grid :deep(.el-select),
.agent-inner-grid :deep(.el-input-number) {
width: 100%;
}
.agent-inner-span {
grid-column: 1 / -1;
}
@media (max-width: 640px) {
.agent-inner-grid {
grid-template-columns: 1fr;
}
}
</style>
@@ -1,19 +1,26 @@
/**
* features/admin/modules/announcements/AnnouncementsPage.vue
* 公告管理独立页面:全宽表格列表 + 发布/编辑/详情居中弹窗。
* 依赖:useAnnouncementsAdmin、AnnouncementFormModal、AnnouncementDetailModal、DeleteConfirmDialog。
* 逻辑:路由 /admin/announcements 挂载本页;列表摘要截断,完整内容在详情弹窗查看。
* 用途:公告管理列表。一张卡片里放标题、发布按钮和表格。
* 依赖:AdminListPage、useAnnouncementsAdmin、useElementProvider、element-plus、公告表单和详情对话框。
* 逻辑:路由 /admin/announcements。骨架用 AdminListPage。发布、编辑、查看仍由本页的两个对话框完成。删除用 Element 确认框。
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Edit, Eye, Plus, Trash2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import { Plus } from '@element-plus/icons-vue';
import { ElButton, ElConfigProvider, ElTable, ElTableColumn } from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/features/admin/styles/element-trial.css';
import AdminListPage from '@/features/admin/components/AdminListPage.vue';
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
import type { AdminAnnouncementRow } from '@/features/admin/types/admin.types';
import AnnouncementDetailModal from './components/AnnouncementDetailModal.vue';
import AnnouncementFormModal from './components/AnnouncementFormModal.vue';
import { useAnnouncementsAdmin } from './composables/useAnnouncementsAdmin';
const { t } = useI18n();
const { elementLocale } = useElementProvider();
const {
announcements,
@@ -23,8 +30,6 @@ const {
isSaving,
showFormModal,
showDetailModal,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
openCreateModal,
openEditModal,
@@ -34,98 +39,66 @@ const {
editFromDetail,
saveAnnouncement,
deleteAnnouncementItem,
closeDeleteConfirm,
confirmDelete,
truncateAnnouncementPreview,
formatPublishedAt,
} = useAnnouncementsAdmin();
/**
* 打开编辑对话框。表格行类型较宽,这里收成公告行。
* @param row - 当前表格行
*/
function editAnnouncement(row: AdminAnnouncementRow): void {
openEditModal(row);
}
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="admin-table-section animate-fade-in-up">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<ElConfigProvider :locale="elementLocale">
<AdminListPage :loading="isLoading">
<template #title>
<h2 class="section-title">{{ t('admin.announcement.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.announcement.subtitle') }}</p>
</template>
<template #actions>
<ElButton type="primary" :icon="Plus" @click="openCreateModal">
{{ t('admin.announcement.add') }}
</ElButton>
</template>
<template v-else>
<div class="admin-table-header admin-table-header--stacked">
<div>
<h2 class="section-title">{{ t('admin.announcement.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.announcement.subtitle') }}</p>
</div>
<button
type="button"
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-all shadow-lg shadow-brand-200 active:scale-95 text-sm font-medium"
@click="openCreateModal"
>
<Plus class="w-4 h-4" />
<span>{{ t('admin.announcement.add') }}</span>
</button>
</div>
<div class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.announcement.headers.title') }}</th>
<th class="px-6 py-4 text-left text-xs w-44">{{ t('admin.announcement.headers.publishedAt') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.announcement.headers.preview') }}</th>
<th class="px-6 py-4 text-right text-xs w-36">{{ t('admin.announcement.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="announcements.length === 0">
<td colspan="4" class="px-6 admin-table-empty">{{ t('admin.announcement.noData') }}</td>
</tr>
<tr v-for="ann in announcements" :key="ann.id" class="group">
<td class="px-6 py-4">
<div class="font-medium text-primary text-sm">{{ ann.title }}</div>
</td>
<td class="px-6 py-4 text-sm text-muted whitespace-nowrap">
{{ formatPublishedAt(ann.created_at) }}
</td>
<td class="px-6 py-4">
<p class="text-sm text-secondary truncate max-w-md" :title="ann.content">
{{ truncateAnnouncementPreview(ann.content) }}
</p>
</td>
<td class="px-6 py-4">
<div class="flex justify-end gap-1">
<button
type="button"
class="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
:title="t('admin.announcement.actions.view')"
@click="openDetailModal(ann)"
>
<Eye class="w-4 h-4" />
</button>
<button
type="button"
class="p-1.5 text-indigo-600 hover:bg-indigo-50 rounded-lg transition-colors"
:title="t('admin.announcement.actions.edit')"
@click="openEditModal(ann)"
>
<Edit class="w-4 h-4" />
</button>
<button
type="button"
class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
:title="t('admin.announcement.actions.delete')"
@click="deleteAnnouncementItem(ann.id)"
>
<Trash2 class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<ElTable
class="hx-admin-table"
:data="announcements"
row-key="id"
:empty-text="t('admin.announcement.noData')"
>
<ElTableColumn prop="title" :label="t('admin.announcement.headers.title')" min-width="180" />
<ElTableColumn :label="t('admin.announcement.headers.publishedAt')" min-width="180">
<template #default="{ row }">{{ formatPublishedAt(row.created_at) }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.announcement.headers.preview')" min-width="240">
<template #default="{ row }">
<p class="announcement-preview" :title="row.content">{{ truncateAnnouncementPreview(row.content) }}</p>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.announcement.headers.actions')" width="200" align="right">
<template #default="{ row }">
<ElButton link type="primary" @click="openDetailModal(row as AdminAnnouncementRow)">
{{ t('admin.announcement.actions.view') }}
</ElButton>
<ElButton link type="primary" @click="editAnnouncement(row as AdminAnnouncementRow)">
{{ t('admin.announcement.actions.edit') }}
</ElButton>
<ElButton link type="danger" @click="deleteAnnouncementItem((row as AdminAnnouncementRow).id)">
{{ t('admin.announcement.actions.delete') }}
</ElButton>
</template>
</ElTableColumn>
</ElTable>
</AdminListPage>
<AnnouncementFormModal
:visible="showFormModal"
@@ -134,19 +107,19 @@ onMounted(() => {
@close="closeFormModal"
@save="saveAnnouncement"
/>
<AnnouncementDetailModal
:visible="showDetailModal"
:announcement="viewingAnnouncement"
@close="closeDetailModal"
@edit="editFromDetail"
/>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@cancel="closeDeleteConfirm"
@confirm="confirmDelete"
/>
</section>
</ElConfigProvider>
</template>
<style scoped>
.announcement-preview {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>
@@ -1,11 +1,12 @@
/**
* features/admin/modules/announcements/components/AnnouncementDetailModal.vue
* 公告详情居中弹窗,展示完整标题、时间与正文。
* 依赖:AdminAnnouncementRow、admin 通用 modal 样式。
* 逻辑:AnnouncementsPage 列表「查看」打开;可跳转编辑或关闭。
* 用途:只读展示公告标题、发布时间和正文。
* 依赖:element-plus 对话框和描述列表、AdminAnnouncementRow。
* 逻辑:AnnouncementsPage 点「查看」后传入。可关闭,或 emit edit 交给页面打开编辑框。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { ElButton, ElDescriptions, ElDescriptionsItem, ElDialog } from 'element-plus';
import type { AdminAnnouncementRow } from '@/features/admin/types/admin.types';
defineProps<{
@@ -25,34 +26,55 @@ const { t } = useI18n();
* @param iso - 后端返回的 created_at
* @returns 本地化日期时间字符串
*/
const formatDateTime = (iso: string): string => new Date(iso).toLocaleString();
function formatDateTime(iso: string): string {
return new Date(iso).toLocaleString();
}
/**
* 对话框关闭时通知页面收起。
* @param open - Element 对话框的打开状态
*/
function onVisibleChange(open: boolean): void {
if (!open) emit('close');
}
</script>
<template>
<div v-if="visible && announcement" class="admin-modal-overlay animate-fade-in items-center">
<div class="admin-modal-panel max-w-3xl max-h-[92vh] scale-100">
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
<h3 class="section-title">{{ t('admin.announcement.viewDetail') }}</h3>
<p class="text-xs text-muted mt-2">{{ formatDateTime(announcement.created_at) }}</p>
</div>
<div class="px-5 sm:px-8 py-5 overflow-y-auto space-y-4">
<div>
<p class="text-xs font-semibold text-muted uppercase tracking-wider mb-1.5">
{{ t('admin.announcement.fields.title') }}
</p>
<p class="text-base font-semibold text-primary">{{ announcement.title }}</p>
</div>
<div>
<p class="text-xs font-semibold text-muted uppercase tracking-wider mb-1.5">
{{ t('admin.announcement.fields.content') }}
</p>
<p class="text-sm text-secondary whitespace-pre-wrap leading-relaxed">{{ announcement.content }}</p>
</div>
</div>
<div class="admin-modal-footer">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.close') }}</button>
<button type="button" class="btn-primary" @click="emit('edit')">{{ t('admin.edit') }}</button>
</div>
</div>
</div>
<ElDialog
:model-value="visible && !!announcement"
:title="t('admin.announcement.viewDetail')"
width="680px"
align-center
append-to-body
:close-on-click-modal="false"
@update:model-value="onVisibleChange"
>
<template v-if="announcement">
<p class="section-desc">{{ formatDateTime(announcement.created_at) }}</p>
<ElDescriptions class="announcement-detail" :column="1" border>
<ElDescriptionsItem :label="t('admin.announcement.fields.title')">
{{ announcement.title }}
</ElDescriptionsItem>
<ElDescriptionsItem :label="t('admin.announcement.fields.content')">
<p class="announcement-detail__content">{{ announcement.content }}</p>
</ElDescriptionsItem>
</ElDescriptions>
</template>
<template #footer>
<ElButton @click="emit('close')">{{ t('admin.close') }}</ElButton>
<ElButton type="primary" @click="emit('edit')">{{ t('admin.edit') }}</ElButton>
</template>
</ElDialog>
</template>
<style scoped>
.announcement-detail {
margin-top: 16px;
}
.announcement-detail__content {
white-space: pre-wrap;
max-height: 50vh;
overflow: auto;
}
</style>
@@ -1,11 +1,12 @@
/**
* features/admin/modules/announcements/components/AnnouncementFormModal.vue
* 公告创建/编辑居中弹窗。
* 依赖:AnnouncementFormState、admin 通用 modal 样式。
* 逻辑:AnnouncementsPage 打开本组件;提交时 emit save,由 composable 调 API。
* 用途:公告发布和编辑对话框。标题一行,正文多行。
* 依赖:element-plus 对话框和表单、AnnouncementFormState。
* 逻辑:AnnouncementsPage 打开本组件。提交时 emit save,由 composable 调接口。样式跟页面已引入的 Element 皮肤走。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { ElButton, ElDialog, ElForm, ElFormItem, ElInput } from 'element-plus';
import type { AnnouncementFormState } from '@/features/admin/types/announcement.types';
defineProps<{
@@ -20,38 +21,41 @@ const emit = defineEmits<{
}>();
const { t } = useI18n();
/**
* 对话框关闭时通知页面收起。
* @param open - Element 对话框的打开状态
*/
function onVisibleChange(open: boolean): void {
if (!open) emit('close');
}
</script>
<template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
<div class="admin-modal-panel max-w-2xl max-h-[92vh] scale-100">
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
<h3 class="section-title">
{{ form.id ? t('admin.announcement.edit') : t('admin.announcement.add') }}
</h3>
</div>
<div class="px-5 sm:px-8 py-5 space-y-5 overflow-y-auto">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.announcement.fields.title') }}</label>
<input v-model="form.title" type="text" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.announcement.fields.content') }}</label>
<textarea v-model="form.content" rows="10" class="input-field text-sm resize-y min-h-[200px]" />
</div>
</div>
<div class="admin-modal-footer">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button type="button" class="btn-primary disabled:opacity-70" :disabled="isSaving" @click="emit('save')">
{{
isSaving
? t('admin.save') + '...'
: form.id
? t('admin.update')
: t('admin.announcement.publish')
}}
</button>
</div>
</div>
</div>
<ElDialog
:model-value="visible"
:title="form.id ? t('admin.announcement.edit') : t('admin.announcement.add')"
width="680px"
align-center
append-to-body
:close-on-click-modal="false"
:close-on-press-escape="!isSaving"
:show-close="!isSaving"
@update:model-value="onVisibleChange"
>
<ElForm label-position="top" :model="form" @submit.prevent="emit('save')">
<ElFormItem :label="t('admin.announcement.fields.title')" required>
<ElInput v-model="form.title" />
</ElFormItem>
<ElFormItem :label="t('admin.announcement.fields.content')" required>
<ElInput v-model="form.content" type="textarea" :rows="8" />
</ElFormItem>
</ElForm>
<template #footer>
<ElButton :disabled="isSaving" @click="emit('close')">{{ t('admin.cancel') }}</ElButton>
<ElButton type="primary" :loading="isSaving" @click="emit('save')">
{{ form.id ? t('admin.update') : t('admin.announcement.publish') }}
</ElButton>
</template>
</ElDialog>
</template>
@@ -1,11 +1,12 @@
/**
* features/admin/modules/announcements/composables/useAnnouncementsAdmin.ts
* 公告管理:列表、发布/编辑弹窗、详情弹窗、删除。
* 依赖:admin.api、announcement.types、useMessage。
* 逻辑:AnnouncementsPage 调用本 composable 驱动表格与两个居中弹窗。
* 依赖:admin.api、announcement.types、useMessage、element-plus 确认框。
* 逻辑:AnnouncementsPage 调用本 composable 驱动表格与两个对话框。删除用 ElMessageBox。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessageBox } from 'element-plus';
import {
createAnnouncement,
deleteAnnouncement,
@@ -33,10 +34,6 @@ export function useAnnouncementsAdmin() {
const showFormModal = ref(false);
const showDetailModal = ref(false);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
/**
* 拉取公告列表并写入 announcements。
* @returns Promise<void>
@@ -60,36 +57,6 @@ export function useAnnouncementsAdmin() {
isLoading.value = false;
};
/**
* 打开删除确认对话框并绑定确认后的删除动作。
* @param message - 确认文案
* @param action - 用户确认后执行的异步删除逻辑
*/
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
deleteConfirmMessage.value = message;
deleteConfirmAction = action;
showDeleteConfirmDialog.value = true;
};
/** 关闭删除确认对话框并清空待执行动作。 */
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmAction = null;
};
/**
* 执行删除确认对话框中绑定的删除动作。
* @returns Promise<void>
*/
const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
}
};
/** 打开「发布公告」弹窗并重置表单。 */
const openCreateModal = (): void => {
form.value = createEmptyAnnouncementForm();
@@ -168,22 +135,30 @@ export function useAnnouncementsAdmin() {
};
/**
* 删除指定公告,删除前弹出确认框。
* 删除指定公告。先用 Element 确认框询问,取消则不请求。
* 核心逻辑:MessageBox 取消时 reject,这里吞掉;确定后删除并刷新列表。
* @param id - 公告主键
*/
const deleteAnnouncementItem = (id: number): void => {
openDeleteConfirm(t('admin.announcement.confirmDelete'), async () => {
try {
await deleteAnnouncement(id);
if (viewingAnnouncement.value?.id === id) {
closeDetailModal();
}
await loadAnnouncements();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
const deleteAnnouncementItem = async (id: number): Promise<void> => {
try {
await ElMessageBox.confirm(t('admin.announcement.confirmDelete'), t('common.deleteDialog.defaultTitle'), {
type: 'warning',
confirmButtonText: t('common.deleteDialog.confirm'),
cancelButtonText: t('common.deleteDialog.cancel'),
});
} catch {
return;
}
try {
await deleteAnnouncement(id);
if (viewingAnnouncement.value?.id === id) {
closeDetailModal();
}
});
await loadAnnouncements();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
};
/**
@@ -201,8 +176,6 @@ export function useAnnouncementsAdmin() {
isSaving,
showFormModal,
showDetailModal,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
openCreateModal,
openEditModal,
@@ -212,8 +185,6 @@ export function useAnnouncementsAdmin() {
editFromDetail,
saveAnnouncement,
deleteAnnouncementItem,
closeDeleteConfirm,
confirmDelete,
truncateAnnouncementPreview,
formatPublishedAt,
};
@@ -1,16 +1,25 @@
/**
* features/admin/modules/dashboard/DashboardPage.vue
* 管理后台仪表盘。路由:/admin/dashboard
* 用途:管理后台仪表盘,四张可点击的统计卡。
* 依赖:useDashboardAdmin、useElementProvider、element-plus。
* 逻辑:路由 /admin/dashboard。统计来自 useDashboardAdmin。点击分别进入应用配置、应用权限和数据报表。本页不是列表,不用 AdminListPage。
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { BarChart2, Bot, MessageSquare, Users } from 'lucide-vue-next';
import { ChatDotRound, DataAnalysis, Monitor, User } from '@element-plus/icons-vue';
import { ElCard, ElConfigProvider, ElIcon, ElLoading, ElStatistic, ElTag } from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/features/admin/styles/element-trial.css';
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
import { useDashboardAdmin } from './composables/useDashboardAdmin';
const vLoading = ElLoading.directive;
const { t } = useI18n();
const router = useRouter();
const { elementLocale } = useElementProvider();
const {
agentCount,
@@ -21,74 +30,89 @@ const {
loadAll,
} = useDashboardAdmin();
/**
* 进入指定管理页。
* @param name - 路由名
* @param table - 数据报表表名;其它页面不传
*/
function openAdmin(name: string, table?: string): void {
if (table) {
void router.push({ name, params: { table } });
return;
}
void router.push({ name });
}
onMounted(() => {
void loadAll();
});
</script>
<template>
<section>
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<div v-else class="grid grid-cols-1 sm:grid-cols-2 gap-6 animate-fade-in">
<div
class="card card-ds-interactive p-6 group cursor-pointer"
@click="router.push({ name: 'AdminAgents' })"
>
<div class="flex justify-between items-start mb-4">
<div class="p-3 bg-brand-50 rounded-xl group-hover:bg-brand-100 transition-colors">
<Bot class="w-6 h-6 text-brand-600" />
<ElConfigProvider :locale="elementLocale">
<section v-loading="isLoading" class="admin-dash">
<h2 class="section-title">{{ t('admin.nav.dashboard') }}</h2>
<div v-if="!isLoading" class="admin-dash__grid">
<ElCard shadow="hover" class="admin-dash__card" @click="openAdmin('AdminAgents')">
<div class="admin-dash__row">
<ElIcon :size="22"><Monitor /></ElIcon>
<ElTag type="success" effect="light">+2 {{ t('admin.dash.new') }}</ElTag>
</div>
<span class="text-xs font-medium text-green-600 bg-green-50 px-2 py-1 rounded-full">
+2 {{ t('admin.dash.new') }}
</span>
</div>
<div class="text-3xl font-bold text-primary mb-1">{{ agentCount }}</div>
<div class="text-sm text-muted font-medium">{{ t('admin.dash.activeAgents') }}</div>
</div>
<ElStatistic :title="t('admin.dash.activeAgents')" :value="agentCount" />
</ElCard>
<div
class="card card-ds-interactive p-6 group cursor-pointer"
@click="router.push({ name: 'AdminPermissions' })"
>
<div class="flex justify-between items-start mb-4">
<div class="p-3 bg-purple-50 rounded-xl group-hover:bg-purple-100 transition-colors">
<Users class="w-6 h-6 text-purple-600" />
<ElCard shadow="hover" class="admin-dash__card" @click="openAdmin('AdminPermissions')">
<div class="admin-dash__row">
<ElIcon :size="22"><User /></ElIcon>
</div>
</div>
<div class="text-3xl font-bold text-primary mb-1">{{ userCount }}</div>
<div class="text-sm text-muted font-medium">{{ t('admin.dash.totalUsers') }}</div>
</div>
<ElStatistic :title="t('admin.dash.totalUsers')" :value="userCount" />
</ElCard>
<div
class="card card-ds-interactive p-6 group cursor-pointer"
@click="router.push({ name: 'AdminReports', params: { table: 'chat_logs' } })"
>
<div class="flex justify-between items-start mb-4">
<div class="p-3 bg-indigo-50 rounded-xl group-hover:bg-indigo-100 transition-colors">
<MessageSquare class="w-6 h-6 text-indigo-600" />
<ElCard shadow="hover" class="admin-dash__card" @click="openAdmin('AdminReports', 'chat_logs')">
<div class="admin-dash__row">
<ElIcon :size="22"><ChatDotRound /></ElIcon>
</div>
</div>
<div class="text-3xl font-bold text-primary mb-1">{{ totalConversations }}</div>
<div class="text-sm text-muted font-medium">{{ t('admin.dash.totalConversations') }}</div>
</div>
<ElStatistic :title="t('admin.dash.totalConversations')" :value="totalConversations" />
</ElCard>
<div
class="card card-ds-interactive p-6 group cursor-pointer"
@click="router.push({ name: 'AdminReports', params: { table: 'feedbacks' } })"
>
<div class="flex justify-between items-start mb-4">
<div class="p-3 bg-orange-50 rounded-xl group-hover:bg-orange-100 transition-colors">
<BarChart2 class="w-6 h-6 text-orange-600" />
<ElCard shadow="hover" class="admin-dash__card" @click="openAdmin('AdminReports', 'feedbacks')">
<div class="admin-dash__row">
<ElIcon :size="22"><DataAnalysis /></ElIcon>
</div>
</div>
<div class="text-3xl font-bold text-primary mb-1">
{{ avgScore.toFixed(1) }}
</div>
<div class="text-sm text-muted font-medium">{{ t('admin.dash.avgRating') }}</div>
<ElStatistic :title="t('admin.dash.avgRating')" :value="avgScore" :precision="1" />
</ElCard>
</div>
</div>
</section>
</section>
</ElConfigProvider>
</template>
<style scoped>
.admin-dash {
min-height: 16rem;
}
.admin-dash__grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px;
margin-top: 16px;
}
.admin-dash__card {
cursor: pointer;
}
.admin-dash__row {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
color: var(--el-color-primary);
}
@media (max-width: 640px) {
.admin-dash__grid {
grid-template-columns: 1fr;
}
}
</style>
@@ -1,24 +1,41 @@
/**
* features/admin/modules/departments/DepartmentsPage.vue
* 用途:部门管理独立页面——全宽表格列表 + 列排序 + 创建/编辑居中弹窗。
* 依赖:useDepartmentsAdmin、SortableTableHeader、DepartmentFormModal、DeleteConfirmDialog。
* 逻辑:路由 /admin/departments;表头排序复用 shared SortableTableHeader + useTableSort。
* 用途:部门管理列表。一张卡片里放标题、添加按钮、搜索、表格。
* 依赖:AdminListPage、useDepartmentsAdmin、useElementProvider、element-plus、lucide-vue-next、部门表单和员工名单弹窗。
* 逻辑:路由 /admin/departments。骨架用 AdminListPage。筛选、列和两个弹窗留在本页。
* 名称、编码、公司用表头排序,排的是当前过滤结果。删除用 Element 确认框。
* 表格用 Element stripe 斑马纹。员工、编辑、删除保持图标按钮,悬停文案走 i18n title。
*/
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { computed, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Edit, Plus, Search, Trash2, Users } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import SortableTableHeader from '@/shared/components/SortableTableHeader.vue';
import { Plus } from '@element-plus/icons-vue';
import { Edit, Trash2, Users } from 'lucide-vue-next';
import {
ElButton,
ElConfigProvider,
ElInput,
ElLoading,
ElTable,
ElTableColumn,
} from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/features/admin/styles/element-trial.css';
import AdminListPage from '@/features/admin/components/AdminListPage.vue';
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
import type { AdminDepartmentMembersResponse, AdminDepartmentRow } from '@/features/admin/types/admin.types';
import DepartmentFormModal from './components/DepartmentFormModal.vue';
import DepartmentMembersModal from './components/DepartmentMembersModal.vue';
import { useDepartmentsAdmin } from './composables/useDepartmentsAdmin';
import { useDepartmentsAdmin, type DeptSortKey } from './composables/useDepartmentsAdmin';
import { listAdminDepartmentMembers } from '@/features/admin/api/admin.api';
import type { AdminDepartmentMembersResponse } from '@/features/admin/types/admin.types';
import { useMessage } from '@/shared/composables/useMessage';
const vLoading = ElLoading.directive;
const { t } = useI18n();
const msg = useMessage();
const { elementLocale } = useElementProvider();
const showMembersModal = ref(false);
const departmentMembers = ref<AdminDepartmentMembersResponse | null>(null);
@@ -29,169 +46,152 @@ const {
sortKey,
sortDir,
isLoading,
isListLoading,
isSaving,
showFormModal,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
toggleSort,
applySort,
openCreateModal,
openEditModal,
closeFormModal,
saveDepartment,
deleteDepartment,
closeDeleteConfirm,
confirmDelete,
} = useDepartmentsAdmin();
onMounted(() => {
void loadAll();
});
const defaultSort = computed(() => ({
prop: sortKey.value || 'name',
order: sortDir.value === 'desc' ? 'descending' as const : 'ascending' as const,
}));
/** 加载并展示指定部门的员工名单。 */
const openDepartmentMembers = async (departmentId: number): Promise<void> => {
const emptyText = computed(() => (
searchQuery.value.trim() ? t('admin.dept.noSearchResults') : t('admin.dept.noDepts')
));
/**
* 把 Element 表头排序交给本地列表。
* 核心逻辑:只接受名称、编码、公司;第三次点击 order 为空时清空排序。
* @param payload.prop - 列字段
* @param payload.order - ascending、descending 或空
*/
function onSortChange(payload: { prop: string | null; order: string | null }): void {
const field = payload.prop;
const sortable = field === 'name' || field === 'code' || field === 'company';
if (sortable && payload.order) {
applySort(field as DeptSortKey, payload.order === 'descending' ? 'desc' : 'asc');
return;
}
applySort('', '');
}
/**
* 打开编辑弹窗。表格插槽行类型较宽,这里收成部门行。
* @param row - 当前表格行
*/
function editDepartment(row: AdminDepartmentRow): void {
openEditModal(row);
}
/**
* 加载并展示指定部门的员工名单。
* 核心逻辑:请求成功才打开弹窗;失败只提示,不打开空名单。
* @param departmentId - 部门主键
*/
async function openDepartmentMembers(departmentId: number): Promise<void> {
try {
departmentMembers.value = await listAdminDepartmentMembers(departmentId) as AdminDepartmentMembersResponse;
showMembersModal.value = true;
} catch (error) {
msg.error((error as Error).message || t('admin.msg.requestFailed'));
}
};
}
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="admin-table-section animate-fade-in-up">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<ElConfigProvider :locale="elementLocale">
<AdminListPage :loading="isLoading">
<template #title>
<h2 class="section-title">{{ t('admin.dept.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.dept.subtitle') }}</p>
</template>
<template #actions>
<ElButton type="primary" :icon="Plus" @click="openCreateModal">
{{ t('admin.dept.add') }}
</ElButton>
</template>
<template #filters>
<ElInput
v-model="searchQuery"
clearable
class="dept-filter-search"
:placeholder="t('admin.dept.searchPlaceholder')"
/>
</template>
<template v-else>
<div class="admin-table-header admin-table-header--stacked">
<div>
<h2 class="section-title">{{ t('admin.dept.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.dept.subtitle') }}</p>
</div>
<button
type="button"
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-all shadow-lg shadow-brand-200 active:scale-95 text-sm font-medium"
@click="openCreateModal"
>
<Plus class="w-4 h-4" />
<span>{{ t('admin.dept.add') }}</span>
</button>
</div>
<div class="admin-table-filters--inline gap-3">
<div class="relative flex-1 min-w-[200px] max-w-sm">
<Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted pointer-events-none" />
<input
v-model="searchQuery"
type="search"
class="admin-table-filter-input w-full pl-9"
:placeholder="t('admin.dept.searchPlaceholder')"
/>
</div>
</div>
<div class="admin-table-wrap">
<!-- 列宽:名称 / 编码 / 公司 / 员工 / 操作 -->
<table class="admin-table table-fixed">
<colgroup>
<col class="w-[25%]" />
<col class="w-[20%]" />
<col class="w-[30%]" />
<col class="w-[12%]" />
<col class="w-[13%]" />
</colgroup>
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">
<SortableTableHeader
column-key="name"
:label="t('admin.dept.headers.name')"
:active-key="sortKey"
:direction="sortDir"
@sort="toggleSort"
/>
</th>
<th class="px-6 py-4 text-left text-xs">
<SortableTableHeader
column-key="code"
:label="t('admin.dept.headers.code')"
:active-key="sortKey"
:direction="sortDir"
@sort="toggleSort"
/>
</th>
<th class="px-6 py-4 text-left text-xs">
<SortableTableHeader
column-key="company"
:label="t('admin.dept.headers.company')"
:active-key="sortKey"
:direction="sortDir"
@sort="toggleSort"
/>
</th>
<th class="px-6 py-4 text-center text-xs">{{ t('admin.dept.headers.members') }}</th>
<th class="px-6 py-4 text-right text-xs">{{ t('admin.dept.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="filteredDepartments.length === 0">
<td colspan="5" class="px-6 admin-table-empty">
{{ searchQuery.trim() ? t('admin.dept.noSearchResults') : t('admin.dept.noDepts') }}
</td>
</tr>
<tr v-for="d in filteredDepartments" :key="d.id" class="group">
<td class="px-6 py-4">
<div class="font-medium text-primary text-sm truncate" :title="d.name">{{ d.name }}</div>
<div
v-if="d.description"
class="text-xs text-muted truncate mt-0.5"
:title="d.description"
>
{{ d.description }}
</div>
</td>
<td class="px-6 py-4 text-sm text-muted font-mono whitespace-nowrap truncate" :title="d.code || '-'">
{{ d.code || '-' }}
</td>
<td class="px-6 py-4 text-sm text-muted truncate" :title="d.company || '-'">
{{ d.company || '-' }}
</td>
<td class="px-6 py-4 text-center">
<button
type="button"
class="inline-flex items-center justify-center rounded-lg bg-blue-50 p-2 text-blue-600 hover:bg-blue-100"
:title="t('admin.dept.actions.viewMembers')"
@click="openDepartmentMembers(d.id)"
><Users class="w-5 h-5" /><span class="ml-1 text-xs">{{ d.member_count || 0 }}</span></button>
</td>
<td class="px-6 py-4">
<div class="flex justify-end gap-1">
<button
type="button"
class="p-1.5 text-indigo-600 hover:bg-indigo-50 rounded-lg transition-colors"
:title="t('admin.dept.actions.edit')"
@click="openEditModal(d)"
>
<Edit class="w-4 h-4" />
</button>
<button
type="button"
class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
:title="t('admin.dept.actions.delete')"
@click="deleteDepartment(d.id)"
>
<Trash2 class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<ElTable
v-loading="isListLoading"
class="hx-admin-table"
:data="filteredDepartments"
row-key="id"
stripe
:default-sort="defaultSort"
:empty-text="emptyText"
@sort-change="onSortChange"
>
<ElTableColumn prop="name" :label="t('admin.dept.headers.name')" sortable="custom" min-width="200">
<template #default="{ row }">
<div :title="row.name">{{ row.name }}</div>
<p v-if="row.description" class="hx-element-hint dept-desc" :title="row.description">
{{ row.description }}
</p>
</template>
</ElTableColumn>
<ElTableColumn prop="code" :label="t('admin.dept.headers.code')" sortable="custom" min-width="140">
<template #default="{ row }">{{ row.code || '-' }}</template>
</ElTableColumn>
<ElTableColumn prop="company" :label="t('admin.dept.headers.company')" sortable="custom" min-width="180">
<template #default="{ row }">{{ row.company || '-' }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.dept.headers.members')" width="120" align="center">
<template #default="{ row }">
<button
type="button"
class="dept-member-btn"
:title="t('admin.dept.actions.viewMembers')"
@click="openDepartmentMembers((row as AdminDepartmentRow).id)"
>
<Users class="dept-member-icon" />
<span>{{ row.member_count || 0 }}</span>
</button>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.dept.headers.actions')" width="120" align="right">
<template #default="{ row }">
<div class="dept-row-actions">
<button
type="button"
class="dept-icon-btn dept-icon-btn--edit"
:title="t('admin.dept.actions.edit')"
@click="editDepartment(row as AdminDepartmentRow)"
>
<Edit class="dept-action-icon" />
</button>
<button
type="button"
class="dept-icon-btn dept-icon-btn--delete"
:title="t('admin.dept.actions.delete')"
@click="deleteDepartment((row as AdminDepartmentRow).id)"
>
<Trash2 class="dept-action-icon" />
</button>
</div>
</template>
</ElTableColumn>
</ElTable>
</AdminListPage>
<DepartmentFormModal
:visible="showFormModal"
@@ -205,12 +205,83 @@ const openDepartmentMembers = async (departmentId: number): Promise<void> => {
:data="departmentMembers"
@close="showMembersModal = false"
/>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@cancel="closeDeleteConfirm"
@confirm="confirmDelete"
/>
</section>
</ElConfigProvider>
</template>
<style scoped>
:deep(.dept-filter-search) {
width: 16rem;
}
.dept-desc {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.dept-member-btn,
.dept-icon-btn {
border: 0;
cursor: pointer;
line-height: 0;
}
.dept-member-btn {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 8px;
border-radius: 8px;
background: #eff6ff;
color: #2563eb;
}
.dept-member-btn:hover {
background: #dbeafe;
}
.dept-member-icon {
width: 20px;
height: 20px;
}
.dept-member-btn span {
margin-left: 4px;
font-size: 12px;
line-height: 1;
}
.dept-row-actions {
display: inline-flex;
justify-content: flex-end;
gap: 4px;
}
.dept-icon-btn {
padding: 6px;
border-radius: 8px;
background: transparent;
transition: background-color 0.15s ease;
}
.dept-action-icon {
width: 16px;
height: 16px;
}
.dept-icon-btn--edit {
color: #4f46e5;
}
.dept-icon-btn--edit:hover {
background: #eef2ff;
}
.dept-icon-btn--delete {
color: #dc2626;
}
.dept-icon-btn--delete:hover {
background: #fef2f2;
}
</style>
@@ -1,11 +1,12 @@
/**
* features/admin/modules/departments/components/DepartmentFormModal.vue
* 用途:部门创建/编辑居中弹窗。
* 依赖:DepartmentFormState、admin 通用 modal 样式。
* 逻辑:DepartmentsPage 打开本组件;提交时 emit save,由 useDepartmentsAdmin 调 API。
* 用途:部门创建和编辑对话框。四个字段,单列。
* 依赖:element-plus 对话框和表单、DepartmentFormState。
* 逻辑:DepartmentsPage 打开本组件。提交时 emit save,由 useDepartmentsAdmin 调接口。样式跟页面已引入的 Element 皮肤走。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { ElButton, ElDialog, ElForm, ElFormItem, ElInput } from 'element-plus';
import type { DepartmentFormState } from '@/features/admin/types/department.types';
defineProps<{
@@ -20,75 +21,52 @@ const emit = defineEmits<{
}>();
const { t } = useI18n();
/**
* 对话框关闭时通知页面收起并重置表单。
* @param open - Element 对话框的打开状态
*/
function onVisibleChange(open: boolean): void {
if (!open) emit('close');
}
</script>
<template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
<div class="admin-modal-panel max-w-lg max-h-[92vh] scale-100">
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
<h3 class="section-title">
{{ form.id ? t('admin.dept.edit') : t('admin.dept.add') }}
</h3>
</div>
<div class="px-5 sm:px-8 py-5 space-y-4 overflow-y-auto">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.name') }}</label>
<input
v-model="form.name"
type="text"
class="input-field text-sm"
:placeholder="t('admin.dept.fields.namePlaceholder')"
/>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.code') }}</label>
<input
v-model="form.code"
type="text"
class="input-field text-sm"
:placeholder="t('admin.dept.fields.codePlaceholder')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.company') }}</label>
<input
v-model="form.company"
type="text"
class="input-field text-sm"
:placeholder="t('admin.dept.fields.companyPlaceholder')"
/>
</div>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.description') }}</label>
<textarea
v-model="form.description"
rows="3"
class="input-field text-sm resize-y"
:placeholder="t('admin.dept.fields.descriptionPlaceholder')"
/>
</div>
</div>
<div class="admin-modal-footer">
<button type="button" class="btn-ghost" @click="emit('close')">
{{ t('admin.cancel') }}
</button>
<button
type="button"
class="btn-primary disabled:opacity-70"
:disabled="isSaving"
@click="emit('save')"
>
{{
isSaving
? t('admin.save') + '...'
: form.id
? t('admin.update')
: t('admin.add')
}}
</button>
</div>
</div>
</div>
<ElDialog
:model-value="visible"
:title="form.id ? t('admin.dept.edit') : t('admin.dept.add')"
width="480px"
align-center
append-to-body
:close-on-click-modal="false"
:close-on-press-escape="!isSaving"
:show-close="!isSaving"
@update:model-value="onVisibleChange"
>
<ElForm label-position="top" :model="form" @submit.prevent="emit('save')">
<ElFormItem :label="t('admin.dept.fields.name')" required>
<ElInput v-model="form.name" :placeholder="t('admin.dept.fields.namePlaceholder')" />
</ElFormItem>
<ElFormItem :label="t('admin.dept.fields.code')">
<ElInput v-model="form.code" :placeholder="t('admin.dept.fields.codePlaceholder')" />
</ElFormItem>
<ElFormItem :label="t('admin.dept.fields.company')">
<ElInput v-model="form.company" :placeholder="t('admin.dept.fields.companyPlaceholder')" />
</ElFormItem>
<ElFormItem :label="t('admin.dept.fields.description')">
<ElInput
v-model="form.description"
type="textarea"
:rows="4"
:placeholder="t('admin.dept.fields.descriptionPlaceholder')"
/>
</ElFormItem>
</ElForm>
<template #footer>
<ElButton :disabled="isSaving" @click="emit('close')">{{ t('admin.cancel') }}</ElButton>
<ElButton type="primary" :loading="isSaving" @click="emit('save')">
{{ form.id ? t('admin.update') : t('admin.add') }}
</ElButton>
</template>
</ElDialog>
</template>
@@ -1,44 +1,72 @@
/**
* features/admin/modules/departments/components/DepartmentMembersModal.vue
* 用途:展示部门对应的员工数量和名单。
* 依赖:部门成员只读 API 响应与 Vue 事件。
* 逻辑:DepartmentsPage 点击员工图标后传入数据,本组件只负责呈现与关闭。
* 用途:只读展示某个部门的员工数量和名单。
* 依赖:element-plus 对话框和表格、部门成员响应类型。
* 逻辑:DepartmentsPage 拉到名单后传入。本组件不请求接口,只展示和关闭。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { Users, X } from 'lucide-vue-next';
import { ElButton, ElDialog, ElTable, ElTableColumn } from 'element-plus';
import type { AdminDepartmentMembersResponse } from '@/features/admin/types/admin.types';
defineProps<{ visible: boolean; data: AdminDepartmentMembersResponse | null }>();
defineProps<{
visible: boolean;
data: AdminDepartmentMembersResponse | null;
}>();
const emit = defineEmits<{ close: [] }>();
const { t } = useI18n();
/**
* 对话框关闭时通知页面收起。
* @param open - Element 对话框的打开状态
*/
function onVisibleChange(open: boolean): void {
if (!open) emit('close');
}
</script>
<template>
<div v-if="visible && data" class="admin-modal-overlay items-center" @click.self="emit('close')">
<section class="admin-modal-panel max-w-2xl max-h-[90vh] animate-fade-in-up">
<header class="px-8 py-6 border-b border-subtle flex items-center justify-between">
<div>
<h3 class="text-lg font-bold text-primary">{{ t('admin.dept.members.title', { name: data.department.name }) }}</h3>
<p class="text-sm text-muted mt-1">{{ t('admin.dept.members.count', { count: data.count }) }}</p>
</div>
<button type="button" class="btn-icon-ds rounded-full" :title="t('admin.close')" @click="emit('close')"><X class="w-5 h-5" /></button>
</header>
<div class="max-h-[60vh] overflow-y-auto p-6">
<div v-if="data.members.length === 0" class="py-12 text-center text-muted">
<Users class="w-9 h-9 mx-auto mb-3 opacity-60" />
{{ t('admin.dept.members.empty') }}
</div>
<ul v-else class="divide-y divide-subtle">
<li v-for="member in data.members" :key="member.id" class="py-3 flex items-center justify-between gap-4">
<div class="min-w-0">
<p class="font-medium text-primary">{{ member.real_name || member.username }}</p>
<p class="text-xs text-muted truncate">{{ member.employee_id || member.username }} · {{ member.email || '-' }}</p>
</div>
<span class="text-xs text-muted whitespace-nowrap">{{ member.status }}</span>
</li>
</ul>
</div>
</section>
</div>
<ElDialog
:model-value="visible && !!data"
:title="data ? t('admin.dept.members.title', { name: data.department.name }) : ''"
width="680px"
align-center
append-to-body
:close-on-click-modal="false"
@update:model-value="onVisibleChange"
>
<template v-if="data">
<p class="section-desc">{{ t('admin.dept.members.count', { count: data.count }) }}</p>
<ElTable
class="dept-members-table"
:data="data.members"
row-key="id"
max-height="60vh"
:empty-text="t('admin.dept.members.empty')"
>
<ElTableColumn :label="t('admin.user.fields.realName')" min-width="140">
<template #default="{ row }">{{ row.real_name || row.username }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.user.fields.employeeId')" min-width="120">
<template #default="{ row }">{{ row.employee_id || '-' }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.user.fields.email')" min-width="180">
<template #default="{ row }">{{ row.email || '-' }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.user.headers.status')" min-width="100">
<template #default="{ row }">{{ row.status || '-' }}</template>
</ElTableColumn>
</ElTable>
</template>
<template #footer>
<ElButton @click="emit('close')">{{ t('admin.close') }}</ElButton>
</template>
</ElDialog>
</template>
<style scoped>
.dept-members-table {
margin-top: 16px;
}
</style>
@@ -1,11 +1,12 @@
/**
* features/admin/modules/departments/composables/useDepartmentsAdmin.ts
* 用途:部门管理列表、搜索过滤、列排序、创建/编辑弹窗、删除。
* 依赖:admin.api、department.types、useMessage、useTableSort。
* 逻辑:DepartmentsPage 调用本 composable;排序状态委托 shared useTableSort。
* 依赖:admin.api、department.types、useMessage、useTableSort、element-plus 的确认框。
* 逻辑:DepartmentsPage 调用本 composable。表头排序由页面把 Element 的 sort-change 交给 applySort,仍在本地对过滤后的列表排序。删除用 ElMessageBox,不再使用 DeleteConfirmDialog。
*/
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessageBox } from 'element-plus';
import {
createAdminDepartment,
deleteAdminDepartment,
@@ -14,6 +15,7 @@ import {
} from '@/features/admin/api/admin.api';
import { useMessage } from '@/shared/composables/useMessage';
import { useTableSort } from '@/shared/composables/useTableSort';
import type { SortDir } from '@/shared/utils/table-sort';
import type { AdminDepartmentRow } from '@/features/admin/types/admin.types';
import {
createEmptyDepartmentForm,
@@ -24,6 +26,11 @@ import {
/** 部门表可排序列 */
export type DeptSortKey = 'name' | 'code' | 'company';
/**
* 部门管理页的列表、表单和删除状态。
* 核心逻辑:拉全量部门后在本地过滤和排序,保存与删除成功后再拉一次列表。
* @returns 页面绑定的状态和打开弹窗、排序、保存、删除方法
*/
export function useDepartmentsAdmin() {
const { t } = useI18n();
const msg = useMessage();
@@ -31,18 +38,15 @@ export function useDepartmentsAdmin() {
const departments = ref<AdminDepartmentRow[]>([]);
const form = ref<DepartmentFormState>(createEmptyDepartmentForm());
const searchQuery = ref('');
const { sortKey, sortDir, toggleSort, sortItems } = useTableSort<DeptSortKey>({
const { sortKey, sortDir, sortItems } = useTableSort<DeptSortKey>({
initialKey: 'name',
initialDir: 'asc',
});
const isLoading = ref(true);
const isListLoading = ref(false);
const isSaving = ref(false);
const showFormModal = ref(false);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
/**
* 先按关键词过滤,再按当前排序列排序。
* 核心逻辑:模糊匹配四字段 → useTableSort.sortItems。
@@ -71,11 +75,14 @@ export function useDepartmentsAdmin() {
* @returns Promise<void>
*/
const loadDepartments = async (): Promise<void> => {
isListLoading.value = true;
try {
departments.value = await listAdminDepartments();
} catch (e) {
console.error('Failed to load departments', e);
departments.value = [];
} finally {
isListLoading.value = false;
}
};
@@ -90,33 +97,18 @@ export function useDepartmentsAdmin() {
};
/**
* 打开删除确认对话框并绑定确认后的删除动作。
* @param message - 确认文案
* @param action - 用户确认后执行的异步删除逻辑
* 把 Element 表头排序写回本地排序状态。
* 核心逻辑:第三次点击清空排序时回到接口原顺序;有效列只排当前过滤结果,不请求接口。
* @param key - 名称、编码、公司;空字符串表示取消排序
* @param dir - asc、desc,或空
*/
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
deleteConfirmMessage.value = message;
deleteConfirmAction = action;
showDeleteConfirmDialog.value = true;
};
/** 关闭删除确认对话框并清空待执行动作。 */
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmAction = null;
};
/**
* 执行删除确认对话框中绑定的删除动作。
* @returns Promise<void>
*/
const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
const applySort = (key: DeptSortKey | '', dir: SortDir | ''): void => {
if (key === '' || dir === '') {
sortKey.value = undefined;
return;
}
sortKey.value = key;
sortDir.value = dir;
};
/** 打开「添加部门」弹窗并重置表单。 */
@@ -173,19 +165,27 @@ export function useDepartmentsAdmin() {
};
/**
* 删除指定部门,删除前弹出确认框。
* 删除指定部门。先用 Element 确认框询问,取消则不请求。
* 核心逻辑:MessageBox 在取消时 reject,这里吞掉;确定后再调删除接口并刷新列表。
* @param id - 部门主键
*/
const deleteDepartment = (id: number): void => {
openDeleteConfirm(t('admin.dept.confirmDelete'), async () => {
try {
await deleteAdminDepartment(id);
await loadDepartments();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
});
const deleteDepartment = async (id: number): Promise<void> => {
try {
await ElMessageBox.confirm(t('admin.dept.confirmDelete'), t('common.deleteDialog.defaultTitle'), {
type: 'warning',
confirmButtonText: t('common.deleteDialog.confirm'),
cancelButtonText: t('common.deleteDialog.cancel'),
});
} catch {
return;
}
try {
await deleteAdminDepartment(id);
await loadDepartments();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
};
return {
@@ -196,18 +196,15 @@ export function useDepartmentsAdmin() {
sortKey,
sortDir,
isLoading,
isListLoading,
isSaving,
showFormModal,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
toggleSort,
applySort,
openCreateModal,
openEditModal,
closeFormModal,
saveDepartment,
deleteDepartment,
closeDeleteConfirm,
confirmDelete,
};
}
@@ -8,7 +8,7 @@
*/
import { describe, expect, it, vi } from 'vitest';
import { defineComponent, h, ref } from 'vue';
import { mount } from '@vue/test-utils';
import { flushPromises, mount } from '@vue/test-utils';
import { createMemoryHistory, createRouter } from 'vue-router';
import i18n from '@/i18n';
import IntegrationConnectorPage from './IntegrationConnectorPage.vue';
@@ -79,8 +79,10 @@ function mountPage() {
}
describe('IntegrationConnectorPage credential list', () => {
it('按重设计列渲染:类型徽标 + 非密账号 + 来源徽标 + 启停开关,不再显示 secret_ref 原文', () => {
it('按重设计列渲染:类型徽标 + 非密账号 + 来源徽标 + 启停开关,不再显示 secret_ref 原文', async () => {
const wrapper = mountPage();
// Element 表格要等列宽计算完才把单元格写进文档,原生 table 是同步的。
await flushPromises();
const text = wrapper.text();
// password 类型:类型标签 + 非密账号(username 值)+ 来源本地化;状态不走文字(开关 + 悬停提示)
expect(text).toContain('tiptop-erp');
@@ -1,31 +1,41 @@
<!--
features/admin/modules/integration-connector/IntegrationConnectorPage.vue
用途:集成连接器管理页——四个配置实体(客户端实例/接口定义/绑定/凭据引用)tab 列表 +
能力清单与手动调用测试;创建/编辑抽屉 + 行内连接测试;调用日志 tab
承载筛选/分页列表/详情抽屉(能力无关通用口径)。
依赖:useIntegrationConnectorAdmin、抽屉与调用测试弹窗组件、useI18n。
逻辑:按 tab 展示列表与「新增」;客户端列表展示类型/环境徽章、行内启停开关与
连接测试结果(徽章 + 可展开详情);接口定义与绑定列表均以状态徽章 + 生命周期行内
按钮(发布/撤回/退役/恢复,绑定发布由后端就绪门禁校验接口已发布且客户端启用)
驱动状态,表单内状态只读;凭据列表布尔启停走行内开关
(与客户端实例一致,表头同为「启用」,开关不带状态文字,精确状态走悬停提示);
能力清单为只读注册表(能力中文名为主行 + 注册名次行,写入/幂等本地化,未注册翻译兜底原值);
接口/绑定列表的客户端与接口
引用列统一展示「名称 + 编码」两行;类型/环境/状态取值均本地化,
未知值兜底原样显示;配置「绑定」是让自动调拨跑起来的最小闭环核心。
-->
/**
* features/admin/modules/integration-connector/IntegrationConnectorPage.vue
* 用途:集成连接器管理页。一张卡片里放标题、新增、六个页签和对应表格。
* 依赖:AdminListPage、AdminListTabs、useIntegrationConnectorAdmin、element-plus、表单抽屉、调用弹窗、调用日志面板。
* 逻辑:路由挂载本页。页签切换仍走 selectTab;能力清单和调用日志只读。创建/编辑抽屉和调用日志面板仍由子组件负责。
*/
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Plus, Edit, Trash2, Plug, PlayCircle } from 'lucide-vue-next';
import { Plus } from '@element-plus/icons-vue';
import {
ElButton,
ElConfigProvider,
ElSwitch,
ElTable,
ElTableColumn,
ElTag,
} from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/features/admin/styles/element-trial.css';
import AdminListPage from '@/features/admin/components/AdminListPage.vue';
import AdminListTabs from '@/features/admin/components/AdminListTabs.vue';
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
import IntegrationConnectorFormDrawer from './components/IntegrationConnectorFormDrawer.vue';
import IntegrationCapabilityCallModal from './components/IntegrationCapabilityCallModal.vue';
import IntegrationCallLogsPanel from './components/IntegrationCallLogsPanel.vue';
import { CONNECTOR_TYPE_OPTIONS, ENVIRONMENT_OPTIONS } from './types/integration-connector.types';
import { useIntegrationConnectorAdmin } from './composables/useIntegrationConnectorAdmin';
import type { IntegrationBindingRow } from './types/integration-connector.types';
import type {
IntegrationBindingRow,
IntegrationClientInstanceRow,
IntegrationCredentialReferenceRow,
IntegrationInterfaceDefinitionRow,
} from './types/integration-connector.types';
const { t } = useI18n();
const { elementLocale } = useElementProvider();
const {
clients, interfaces, bindings, credentials, capabilities, credentialTypes,
@@ -54,6 +64,14 @@ const tabs: Array<{ key: TabKey; labelKey: string }> = [
// 均不属于可编辑实体);初始取 activeEntity,保证携带实体态进入页面时列表与 tab 一致。
const activeTab = ref<TabKey>(activeEntity.value);
/**
* 六个页签交给公共页签组件。名称用实体键,文字用现有文案。
*/
const connectorTabs = computed(() => tabs.map((tab) => ({
name: tab.key,
label: t(tab.labelKey),
})));
/** 客户端选项带 connector_type:接口表单联动展示连接器类型用。 */
const clientOptions = computed(() => clients.value.map((c) => ({ code: c.code, name: c.name, connector_type: c.connector_type })));
/** 接口选项带 client_instance_code:绑定表单联动带出并锁定客户端实例用。 */
@@ -102,13 +120,15 @@ function statusLabel(value: string) {
return t(`admin.integrationConnector.statusLabels.${value}`, value);
}
/** 能力本地化标签;未注册翻译的能力兜底原值(能力名含点号,i18n 按嵌套路径组织)。 */
/** 能力本地化标签。空名称不查文案。未注册翻译时兜底原值(能力名含点号,i18n 按嵌套路径组织)。 */
function capabilityLabelOf(name: string) {
if (!name) return '';
return t(`admin.integrationConnector.capabilityLabels.${name}`, name);
}
/** 幂等语义本地化标签;未知值兜底原样显示。 */
/** 幂等语义本地化标签。空值不查文案,未知值兜底原样显示。 */
function idempotencyLabel(value: string) {
if (!value) return '';
return t(`admin.integrationConnector.idempotencyLabels.${value}`, value);
}
@@ -129,11 +149,24 @@ function credentialAccountText(row: { secret_provider: string; secret_fields: Re
return values.length ? values.join(' / ') : '—';
}
/** 状态徽标配色:启用中绿 / 轮换中橙 / 其余中性。 */
function statusBadgeClass(value: string) {
if (value === 'active' || value === 'published') return 'bg-emerald-50 text-emerald-700';
if (value === 'rotating') return 'bg-amber-50 text-amber-700';
return 'bg-surface-soft text-secondary';
/**
* 状态标签颜色。启用和已发布为成功,轮换中为警告,其余为中性。
* @param value - 状态码
*/
function statusTagType(value: string): 'success' | 'warning' | 'info' {
if (value === 'active' || value === 'published') return 'success';
if (value === 'rotating') return 'warning';
return 'info';
}
/**
* 环境标签颜色。生产为成功,测试为警告。
* @param value - 环境码
*/
function envTagType(value: string): 'success' | 'warning' | 'info' {
if (value === 'prod') return 'success';
if (value === 'test') return 'warning';
return 'info';
}
/** 行内测试结果(无结果返回 null,供模板 v-if 使用)。 */
@@ -141,13 +174,6 @@ function testResultOf(code: string) {
return testResults.value[code] ?? null;
}
/** 测试徽章配色:成功绿 / 失败红。 */
function testBadgeClass(code: string) {
return testResultOf(code)?.ok
? 'bg-green-100 text-green-700 hover:bg-green-200'
: 'bg-red-100 text-red-700 hover:bg-red-200';
}
/** 测试徽章文案。 */
function testBadgeText(code: string) {
return testResultOf(code)?.ok
@@ -162,377 +188,337 @@ function testDetailText(code: string) {
return r.message ? `${r.code} · ${r.message}` : r.code;
}
function selectTab(key: TabKey) {
/**
* 切换页签。能力清单和调用日志只读,不改当前可编辑实体。
* @param key - 页签名
*/
function selectTab(key: TabKey): void {
activeTab.value = key;
// capability/calls tab 只读展示(无新增/表单入口),activeEntity 保持最后一个可编辑实体供抽屉复用。
if (key !== 'capability' && key !== 'calls') activeEntity.value = key;
}
/**
* 公共页签只回传字符串,这里收成六个已知页签后再切换。
* @param name - AdminListTabs 当前 name
*/
function onListTab(name: string): void {
if (name === 'client' || name === 'interface' || name === 'binding' || name === 'credential' || name === 'capability' || name === 'calls') {
selectTab(name);
}
}
</script>
<template>
<section class="admin-table-section animate-fade-in-up">
<div class="admin-table-header admin-table-header--stacked">
<div>
<ElConfigProvider :locale="elementLocale">
<AdminListPage :loading="isLoading">
<template #title>
<h2 class="section-title">{{ t('admin.integrationConnector.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.integrationConnector.subtitle') }}</p>
</div>
<button
v-if="activeTab !== 'capability' && activeTab !== 'calls'"
type="button"
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-all shadow-lg shadow-brand-200 active:scale-95 text-sm font-medium"
@click="openCreateModal(activeEntity)"
</template>
<template #actions>
<ElButton
v-if="activeTab !== 'capability' && activeTab !== 'calls'"
type="primary"
:icon="Plus"
@click="openCreateModal(activeEntity)"
>
{{ t('admin.integrationConnector.add') }}
</ElButton>
</template>
<template #tabs>
<AdminListTabs :model-value="activeTab" :items="connectorTabs" @update:model-value="onListTab" />
</template>
<template v-if="!isLoading">
<ElTable
v-if="activeTab === 'client'"
class="hx-admin-table"
:data="clients"
row-key="code"
:empty-text="t('admin.integrationConnector.empty')"
>
<Plus class="w-4 h-4" />
<span>{{ t('admin.integrationConnector.add') }}</span>
</button>
</div>
<div class="flex gap-1 border-b border-default" role="tablist">
<button
v-for="tab in tabs"
:key="tab.key"
type="button"
role="tab"
class="px-4 py-2.5 text-sm font-medium border-b-2 -mb-px transition-colors"
:class="activeTab === tab.key ? 'border-brand-600 text-brand-600' : 'border-transparent text-muted hover:text-secondary'"
:aria-selected="activeTab === tab.key"
@click="selectTab(tab.key)"
>
{{ t(tab.labelKey) }}
</button>
</div>
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<!-- 客户端实例 -->
<div v-if="activeTab === 'client'" class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.name') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.connectorType') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.environment') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.endpoint') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.fields.enabled') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.testStatus') }}</th>
<th class="px-6 py-4 text-right text-xs w-36">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="clients.length === 0"><td colspan="7" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<template v-for="row in clients" :key="row.code">
<tr>
<td class="px-6 py-4">
<p class="text-sm font-medium text-primary">{{ row.name }}</p>
<p class="text-xs text-muted mono mt-0.5">{{ row.code }}</p>
</td>
<td class="px-6 py-4">
<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium bg-surface-soft text-secondary">{{ connectorTypeLabel(row.connector_type) }}</span>
</td>
<td class="px-6 py-4">
<span
class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium"
:class="row.environment === 'prod' ? 'bg-green-100 text-green-700' : row.environment === 'test' ? 'bg-amber-100 text-amber-700' : 'bg-surface-soft text-secondary'"
>{{ envLabel(row.environment) }}</span>
</td>
<td class="px-6 py-4 max-w-[240px]">
<span v-if="row.endpoint" class="block truncate text-xs font-mono text-secondary" :title="row.endpoint">{{ row.endpoint }}</span>
<span v-else class="text-xs text-muted">—</span>
</td>
<td class="px-6 py-4">
<button
type="button"
role="switch"
:aria-checked="row.enabled"
:title="t('admin.integrationConnector.fields.enabled')"
class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors"
:class="row.enabled ? 'bg-brand-600' : 'bg-slate-300'"
data-testid="client-toggle"
:disabled="lifecycleBusy"
@click="toggleClient(row)"
>
<span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform" :class="row.enabled ? 'translate-x-4' : 'translate-x-0.5'" />
</button>
</td>
<td class="px-6 py-4">
<span v-if="testingClientCode === row.code" class="text-xs text-muted">{{ t('admin.integrationConnector.msg.testing') }}</span>
<button
v-else-if="testResultOf(row.code)"
type="button"
class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium"
:class="testBadgeClass(row.code)"
:title="t('admin.integrationConnector.testDetailToggle')"
data-testid="client-test-badge"
@click="expandedTestCode = expandedTestCode === row.code ? '' : row.code"
>
{{ testBadgeText(row.code) }}
</button>
<span v-else class="text-xs text-muted">—</span>
</td>
<td class="px-6 py-4 text-right">
<div class="inline-flex items-center gap-1">
<button type="button" class="p-2 rounded-lg text-muted hover:bg-brand-50 hover:text-brand-600" :title="t('admin.integrationConnector.test')" @click="testConnection(row.code)">
<Plug class="w-4 h-4" />
</button>
<button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('client', row)">
<Edit class="w-4 h-4" />
</button>
<button type="button" class="p-2 rounded-lg text-muted hover:bg-red-50 hover:text-red-600" :title="t('admin.delete')" @click="deleteClient(row)">
<Trash2 class="w-4 h-4" />
</button>
</div>
</td>
</tr>
<!-- 测试详情展开行:原因码 + 脱敏消息 -->
<tr v-if="expandedTestCode === row.code && testResultOf(row.code)">
<td colspan="7" class="px-6 py-3 bg-surface-soft" data-testid="client-test-detail">
<p class="text-xs font-mono text-secondary break-all">{{ testDetailText(row.code) }}</p>
</td>
</tr>
<ElTableColumn :label="t('admin.integrationConnector.headers.name')" min-width="180">
<template #default="{ row }">
<div>{{ row.name }}</div>
<p class="hx-element-hint">{{ row.code }}</p>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.integrationConnector.headers.connectorType')" min-width="140">
<template #default="{ row }">
<ElTag effect="light">{{ connectorTypeLabel(row.connector_type) }}</ElTag>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.integrationConnector.headers.environment')" min-width="120">
<template #default="{ row }">
<ElTag :type="envTagType(row.environment)" effect="light">{{ envLabel(row.environment) }}</ElTag>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.integrationConnector.headers.endpoint')" min-width="200">
<template #default="{ row }">
<span v-if="row.endpoint" class="connector-ellipsis" :title="row.endpoint">{{ row.endpoint }}</span>
<span v-else>—</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.integrationConnector.fields.enabled')" width="100">
<template #default="{ row }">
<ElSwitch
:model-value="row.enabled"
data-testid="client-toggle"
:disabled="lifecycleBusy"
:title="t('admin.integrationConnector.fields.enabled')"
@change="toggleClient(row as IntegrationClientInstanceRow)"
/>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.integrationConnector.headers.testStatus')" min-width="140">
<template #default="{ row }">
<span v-if="testingClientCode === row.code">{{ t('admin.integrationConnector.msg.testing') }}</span>
<template v-else-if="testResultOf(row.code)">
<ElTag
:type="testResultOf(row.code)?.ok ? 'success' : 'danger'"
effect="light"
class="connector-test-tag"
data-testid="client-test-badge"
:title="t('admin.integrationConnector.testDetailToggle')"
@click="expandedTestCode = expandedTestCode === row.code ? '' : row.code"
>
{{ testBadgeText(row.code) }}
</ElTag>
<p v-if="expandedTestCode === row.code" class="hx-element-hint" data-testid="client-test-detail">
{{ testDetailText(row.code) }}
</p>
</template>
</tbody>
</table>
</div>
<span v-else>—</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.integrationConnector.headers.actions')" width="200" align="right">
<template #default="{ row }">
<ElButton link type="primary" @click="testConnection(row.code)">{{ t('admin.integrationConnector.test') }}</ElButton>
<ElButton link type="primary" @click="openEditModal('client', row as IntegrationClientInstanceRow)">{{ t('admin.edit') }}</ElButton>
<ElButton link type="danger" @click="deleteClient(row as IntegrationClientInstanceRow)">{{ t('admin.delete') }}</ElButton>
</template>
</ElTableColumn>
</ElTable>
<!-- 接口定义:状态徽章 + 生命周期行内按钮(发布/撤回/退役/恢复,后端转移表校验) -->
<div v-else-if="activeTab === 'interface'" class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.code') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.name') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.clientInstance') }}</th>
<th class="px-6 py-4 text-left text-xs w-28">{{ t('admin.integrationConnector.headers.status') }}</th>
<th class="px-6 py-4 text-right text-xs w-48">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="interfaces.length === 0"><td colspan="5" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<tr v-for="row in interfaces" :key="row.code">
<td class="px-6 py-4 text-sm font-medium text-primary mono">{{ row.code }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.name }}</td>
<td class="px-6 py-4">
<p class="text-sm text-primary">{{ clientNameOf(row.client_instance_code) || row.client_instance_code }}</p>
<p class="text-xs text-muted mono mt-0.5">{{ row.client_instance_code }}</p>
</td>
<td class="px-6 py-4">
<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium" :class="statusBadgeClass(row.status)" data-testid="interface-status">{{ statusLabel(row.status) }}</span>
</td>
<td class="px-6 py-4 text-right">
<div class="inline-flex items-center gap-1">
<!-- 生命周期按钮按当前状态显隐:draft→发布;published→撤回+退役;retired→恢复;按钮不换行防窄列折字 -->
<button
v-if="row.status === 'draft'"
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-brand-600 hover:bg-brand-50 disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="interface-publish"
:disabled="lifecycleBusy"
@click="changeInterfaceLifecycle(row, 'publish')"
>{{ t('admin.integrationConnector.lifecycle.publish') }}</button>
<template v-else-if="row.status === 'published'">
<button
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-secondary hover:bg-surface-soft disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="interface-unpublish"
:disabled="lifecycleBusy"
@click="changeInterfaceLifecycle(row, 'unpublish')"
>{{ t('admin.integrationConnector.lifecycle.unpublish') }}</button>
<button
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-amber-600 hover:bg-amber-50 disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="interface-retire"
:disabled="lifecycleBusy"
@click="changeInterfaceLifecycle(row, 'retire')"
>{{ t('admin.integrationConnector.lifecycle.retire') }}</button>
</template>
<button
v-else-if="row.status === 'retired'"
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-secondary hover:bg-surface-soft disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="interface-reopen"
:disabled="lifecycleBusy"
@click="changeInterfaceLifecycle(row, 'reopen')"
>{{ t('admin.integrationConnector.lifecycle.reopen') }}</button>
<button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('interface', row)">
<Edit class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<ElTable
v-else-if="activeTab === 'interface'"
class="hx-admin-table"
:data="interfaces"
row-key="code"
:empty-text="t('admin.integrationConnector.empty')"
>
<ElTableColumn prop="code" :label="t('admin.integrationConnector.headers.code')" min-width="160" />
<ElTableColumn prop="name" :label="t('admin.integrationConnector.headers.name')" min-width="160" />
<ElTableColumn :label="t('admin.integrationConnector.headers.clientInstance')" min-width="180">
<template #default="{ row }">
<div>{{ clientNameOf(row.client_instance_code) || row.client_instance_code }}</div>
<p class="hx-element-hint">{{ row.client_instance_code }}</p>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.integrationConnector.headers.status')" width="120">
<template #default="{ row }">
<ElTag :type="statusTagType(row.status)" effect="light" data-testid="interface-status">
{{ statusLabel(row.status) }}
</ElTag>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.integrationConnector.headers.actions')" width="280" align="right">
<template #default="{ row }">
<ElButton
v-if="row.status === 'draft'"
link
type="primary"
data-testid="interface-publish"
:disabled="lifecycleBusy"
@click="changeInterfaceLifecycle(row as IntegrationInterfaceDefinitionRow, 'publish')"
>
{{ t('admin.integrationConnector.lifecycle.publish') }}
</ElButton>
<template v-else-if="row.status === 'published'">
<ElButton
link
data-testid="interface-unpublish"
:disabled="lifecycleBusy"
@click="changeInterfaceLifecycle(row as IntegrationInterfaceDefinitionRow, 'unpublish')"
>
{{ t('admin.integrationConnector.lifecycle.unpublish') }}
</ElButton>
<ElButton
link
type="warning"
data-testid="interface-retire"
:disabled="lifecycleBusy"
@click="changeInterfaceLifecycle(row as IntegrationInterfaceDefinitionRow, 'retire')"
>
{{ t('admin.integrationConnector.lifecycle.retire') }}
</ElButton>
</template>
<ElButton
v-else-if="row.status === 'retired'"
link
data-testid="interface-reopen"
:disabled="lifecycleBusy"
@click="changeInterfaceLifecycle(row as IntegrationInterfaceDefinitionRow, 'reopen')"
>
{{ t('admin.integrationConnector.lifecycle.reopen') }}
</ElButton>
<ElButton link type="primary" @click="openEditModal('interface', row as IntegrationInterfaceDefinitionRow)">{{ t('admin.edit') }}</ElButton>
</template>
</ElTableColumn>
</ElTable>
<!-- 绑定:状态徽章 + 生命周期行内按钮(发布/撤回/退役/恢复,后端转移表 + 发布就绪门禁校验) -->
<div v-else-if="activeTab === 'binding'" class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.capability') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.clientInstance') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.interfaceDef') }}</th>
<th class="px-6 py-4 text-left text-xs w-28">{{ t('admin.integrationConnector.headers.status') }}</th>
<th class="px-6 py-4 text-right text-xs w-48">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="bindings.length === 0"><td colspan="5" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<tr v-for="row in bindings" :key="row.id">
<!-- 能力引用列与客户端/接口引用列同款「名称 + 编码」两行;无中文翻译时只显注册名避免重复 -->
<td class="px-6 py-4">
<p class="text-sm text-primary">{{ capabilityLabelOf(row.capability) }}</p>
<p v-if="capabilityLabelOf(row.capability) !== row.capability" class="text-xs text-muted mono mt-0.5">{{ row.capability }}</p>
</td>
<td class="px-6 py-4">
<!-- 有序步骤:逐步渲染客户端(与接口步骤列对齐) -->
<p v-for="(step, idx) in bindingStepsOf(row)" :key="`c-${step.interface_code}-${idx}`" class="text-sm text-primary">
<span class="mr-1 text-xs text-muted">{{ idx + 1 }}.</span>{{ clientNameOf(step.client_code) || step.client_code }}
</p>
</td>
<td class="px-6 py-4">
<!-- 有序步骤编排:编号 + 接口名,悬停显示接口编码;旧单步行兜底为一步 -->
<p v-for="(step, idx) in bindingStepsOf(row)" :key="`i-${step.interface_code}-${idx}`" class="text-sm text-primary">
<span class="mr-1 text-xs text-muted">{{ idx + 1 }}.</span><span :title="step.interface_code">{{ interfaceNameOf(step.interface_code) || step.interface_code }}</span>
</p>
</td>
<td class="px-6 py-4">
<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium" :class="statusBadgeClass(row.status)" data-testid="binding-status">{{ statusLabel(row.status) }}</span>
</td>
<td class="px-6 py-4 text-right">
<div class="inline-flex items-center gap-1">
<!-- 生命周期按钮按当前状态显隐:draft→发布;published→撤回+退役;retired→恢复;按钮不换行防窄列折字 -->
<button
v-if="row.status === 'draft'"
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-brand-600 hover:bg-brand-50 disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="binding-publish"
:disabled="lifecycleBusy"
@click="changeBindingLifecycle(row, 'publish')"
>{{ t('admin.integrationConnector.lifecycle.publish') }}</button>
<template v-else-if="row.status === 'published'">
<button
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-secondary hover:bg-surface-soft disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="binding-unpublish"
:disabled="lifecycleBusy"
@click="changeBindingLifecycle(row, 'unpublish')"
>{{ t('admin.integrationConnector.lifecycle.unpublish') }}</button>
<button
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-amber-600 hover:bg-amber-50 disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="binding-retire"
:disabled="lifecycleBusy"
@click="changeBindingLifecycle(row, 'retire')"
>{{ t('admin.integrationConnector.lifecycle.retire') }}</button>
</template>
<button
v-else-if="row.status === 'retired'"
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-secondary hover:bg-surface-soft disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="binding-reopen"
:disabled="lifecycleBusy"
@click="changeBindingLifecycle(row, 'reopen')"
>{{ t('admin.integrationConnector.lifecycle.reopen') }}</button>
<button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('binding', row)">
<Edit class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<ElTable
v-else-if="activeTab === 'binding'"
class="hx-admin-table"
:data="bindings"
row-key="id"
:empty-text="t('admin.integrationConnector.empty')"
>
<ElTableColumn :label="t('admin.integrationConnector.headers.capability')" min-width="200">
<template #default="{ row }">
<div>{{ capabilityLabelOf(row.capability) }}</div>
<p v-if="capabilityLabelOf(row.capability) !== row.capability" class="hx-element-hint">{{ row.capability }}</p>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.integrationConnector.headers.clientInstance')" min-width="180">
<template #default="{ row }">
<p v-for="(step, idx) in bindingStepsOf(row as IntegrationBindingRow)" :key="`c-${step.interface_code}-${idx}`">
{{ idx + 1 }}. {{ clientNameOf(step.client_code) || step.client_code }}
</p>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.integrationConnector.headers.interfaceDef')" min-width="180">
<template #default="{ row }">
<p v-for="(step, idx) in bindingStepsOf(row as IntegrationBindingRow)" :key="`i-${step.interface_code}-${idx}`">
{{ idx + 1 }}. <span :title="step.interface_code">{{ interfaceNameOf(step.interface_code) || step.interface_code }}</span>
</p>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.integrationConnector.headers.status')" width="120">
<template #default="{ row }">
<ElTag :type="statusTagType(row.status)" effect="light" data-testid="binding-status">
{{ statusLabel(row.status) }}
</ElTag>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.integrationConnector.headers.actions')" width="280" align="right">
<template #default="{ row }">
<ElButton
v-if="row.status === 'draft'"
link
type="primary"
data-testid="binding-publish"
:disabled="lifecycleBusy"
@click="changeBindingLifecycle(row as IntegrationBindingRow, 'publish')"
>
{{ t('admin.integrationConnector.lifecycle.publish') }}
</ElButton>
<template v-else-if="row.status === 'published'">
<ElButton
link
data-testid="binding-unpublish"
:disabled="lifecycleBusy"
@click="changeBindingLifecycle(row as IntegrationBindingRow, 'unpublish')"
>
{{ t('admin.integrationConnector.lifecycle.unpublish') }}
</ElButton>
<ElButton
link
type="warning"
data-testid="binding-retire"
:disabled="lifecycleBusy"
@click="changeBindingLifecycle(row as IntegrationBindingRow, 'retire')"
>
{{ t('admin.integrationConnector.lifecycle.retire') }}
</ElButton>
</template>
<ElButton
v-else-if="row.status === 'retired'"
link
data-testid="binding-reopen"
:disabled="lifecycleBusy"
@click="changeBindingLifecycle(row as IntegrationBindingRow, 'reopen')"
>
{{ t('admin.integrationConnector.lifecycle.reopen') }}
</ElButton>
<ElButton link type="primary" @click="openEditModal('binding', row as IntegrationBindingRow)">{{ t('admin.edit') }}</ElButton>
</template>
</ElTableColumn>
</ElTable>
<!-- 凭据引用 -->
<div v-else-if="activeTab === 'credential'" class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.code') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.connectorType') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.account') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.secretProvider') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.fields.enabled') }}</th>
<th class="px-6 py-4 text-right text-xs w-32">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="credentials.length === 0"><td colspan="6" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<tr v-for="row in credentials" :key="row.code">
<td class="px-6 py-4 text-sm font-medium text-primary mono">{{ row.code }}</td>
<td class="px-6 py-4 text-sm">
<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium bg-surface-soft text-secondary">{{ credentialTypeLabel(row.credential_type) }}</span>
</td>
<td class="px-6 py-4 text-sm text-secondary mono">{{ credentialAccountText(row) }}</td>
<td class="px-6 py-4 text-sm">
<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium bg-surface-soft text-secondary" :title="row.secret_provider === 'db' ? statusLabel('db') : row.secret_ref">{{ secretProviderLabel(row.secret_provider) }}</span>
</td>
<td class="px-6 py-4">
<!-- 行内启停开关:布尔语义,与客户端实例开关完全同款(含 title 用同一 i18n 键);rotating 视为启用侧,点击即停用;解析层只认 active,停用即断流 -->
<button
type="button"
role="switch"
:aria-checked="row.status !== 'retired'"
:title="t('admin.integrationConnector.fields.enabled')"
class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors"
:class="row.status !== 'retired' ? 'bg-brand-600' : 'bg-slate-300'"
data-testid="credential-status-toggle"
:disabled="lifecycleBusy"
@click="toggleCredential(row)"
>
<span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform" :class="row.status !== 'retired' ? 'translate-x-4' : 'translate-x-0.5'" />
</button>
</td>
<td class="px-6 py-4 text-right">
<div class="inline-flex items-center gap-1">
<button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('credential', row)">
<Edit class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<ElTable
v-else-if="activeTab === 'credential'"
class="hx-admin-table"
:data="credentials"
row-key="code"
:empty-text="t('admin.integrationConnector.empty')"
>
<ElTableColumn prop="code" :label="t('admin.integrationConnector.headers.code')" min-width="160" />
<ElTableColumn :label="t('admin.integrationConnector.headers.connectorType')" min-width="140">
<template #default="{ row }">
<ElTag effect="light">{{ credentialTypeLabel(row.credential_type) }}</ElTag>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.integrationConnector.headers.account')" min-width="160">
<template #default="{ row }">{{ credentialAccountText(row as IntegrationCredentialReferenceRow) }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.integrationConnector.headers.secretProvider')" min-width="160">
<template #default="{ row }">
<ElTag effect="light" :title="row.secret_provider === 'db' ? statusLabel('db') : row.secret_ref">
{{ secretProviderLabel(row.secret_provider) }}
</ElTag>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.integrationConnector.fields.enabled')" width="100">
<template #default="{ row }">
<ElSwitch
:model-value="row.status !== 'retired'"
data-testid="credential-status-toggle"
:disabled="lifecycleBusy"
:title="t('admin.integrationConnector.fields.enabled')"
@change="toggleCredential(row as IntegrationCredentialReferenceRow)"
/>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.integrationConnector.headers.actions')" width="100" align="right">
<template #default="{ row }">
<ElButton link type="primary" @click="openEditModal('credential', row as IntegrationCredentialReferenceRow)">{{ t('admin.edit') }}</ElButton>
</template>
</ElTableColumn>
</ElTable>
<!-- 调用日志:筛选 + 分页列表 + 详情抽屉(能力无关通用口径;只读 tab,无新增入口) -->
<IntegrationCallLogsPanel v-else-if="activeTab === 'calls'" />
<!-- 能力清单 -->
<div v-else class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.name') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.write') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.idempotency') }}</th>
<th class="px-6 py-4 text-right text-xs w-28">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="capabilities.length === 0"><td colspan="4" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<tr v-for="row in capabilities" :key="row.name">
<!-- 中文名称为主行,注册名作为精确标识(绑定引用用)保留为次行;无中文翻译时只显注册名避免重复 -->
<td class="px-6 py-4">
<p class="text-sm font-medium text-primary">{{ capabilityLabelOf(row.name) }}</p>
<p v-if="capabilityLabelOf(row.name) !== row.name" class="text-xs text-muted mono mt-0.5">{{ row.name }}</p>
</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.write ? t('admin.integrationConnector.writeLabels.yes') : t('admin.integrationConnector.writeLabels.no') }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ idempotencyLabel(row.idempotency) }}</td>
<td class="px-6 py-4 text-right">
<button type="button" class="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm font-medium text-brand-600 hover:bg-brand-50" @click="openCallModal(row.name)">
<PlayCircle class="w-4 h-4" />
{{ t('admin.integrationConnector.call') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
<ElTable
v-else
class="hx-admin-table"
:data="capabilities"
row-key="name"
:empty-text="t('admin.integrationConnector.empty')"
>
<ElTableColumn :label="t('admin.integrationConnector.headers.name')" min-width="220">
<template #default="{ row }">
<div>{{ capabilityLabelOf(row.name) }}</div>
<p v-if="capabilityLabelOf(row.name) !== row.name" class="hx-element-hint">{{ row.name }}</p>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.integrationConnector.headers.write')" width="100">
<template #default="{ row }">
{{ row.write ? t('admin.integrationConnector.writeLabels.yes') : t('admin.integrationConnector.writeLabels.no') }}
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.integrationConnector.headers.idempotency')" min-width="160">
<template #default="{ row }">{{ idempotencyLabel(row.idempotency) }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.integrationConnector.headers.actions')" width="120" align="right">
<template #default="{ row }">
<ElButton link type="primary" @click="openCallModal(row.name)">{{ t('admin.integrationConnector.call') }}</ElButton>
</template>
</ElTableColumn>
</ElTable>
</template>
</AdminListPage>
<IntegrationConnectorFormDrawer
:visible="showFormModal"
@@ -561,5 +547,18 @@ function selectTab(key: TabKey) {
@close="closeCallModal"
@run="runCall"
/>
</section>
</ElConfigProvider>
</template>
<style scoped>
.connector-ellipsis {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.connector-test-tag {
cursor: pointer;
}
</style>
@@ -11,12 +11,14 @@
* param_mapping_json),client 由各步接口归属自带、不再发送旧单步顶层字段;
* 凭据状态只经列表行内开关流转(启用↔停用,表单不维护状态);
* 全部行内状态操作经 lifecycleBusy 互斥(进行中忽略新触发);接口/绑定退役
* 接近终态需 window.confirm 二次确认,可逆转移直达;
* 连接测试结果按行存放(列表徽章+展开详情);
* 启停支持行内开关(失败回滚);删除带确认。保存/删除后刷新对应列表。
* 接近终态仍走现有 window.confirm,可逆转移直达;
* 连接测试结果按行存放(列表标签+展开详情);
* 启停支持行内开关(失败回滚);删除用 Element 确认框,取消则返回。
* 首屏 isLoading 盖住整张卡片;保存、删除和生命周期刷新后的 isListLoading 只盖表格。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessageBox } from 'element-plus';
import { useMessage } from '@/shared/composables/useMessage';
import {
callIntegrationCapability,
@@ -87,7 +89,10 @@ export function useIntegrationConnectorAdmin() {
const credentials = ref<IntegrationCredentialReferenceRow[]>([]);
const capabilities = ref<IntegrationCapabilityRow[]>([]);
const credentialTypes = ref<IntegrationCredentialTypeSpec[]>([]);
/** 首屏整卡加载。为 true 时列表卡片先不画出表格。 */
const isLoading = ref(true);
/** 首屏之后的列表刷新。只盖住当前表格,不把标题和页签再盖住。 */
const isListLoading = ref(false);
// ---- 表单弹窗态 ----
const activeEntity = ref<EditableEntity>('client');
@@ -145,11 +150,21 @@ export function useIntegrationConnectorAdmin() {
}
};
/**
* 刷新一个实体的列表,并只在表格上显示加载。
* 核心逻辑:保存成功后按当前实体重拉;加载标记在请求结束后关掉,失败继续抛给调用方。
* @param entity - 要刷新的客户端、接口、绑定或凭据
*/
const reloadOne = async (entity: EditableEntity) => {
if (entity === 'client') await loadClients();
else if (entity === 'interface') await loadInterfaces();
else if (entity === 'binding') await loadBindings();
else await loadCredentials();
isListLoading.value = true;
try {
if (entity === 'client') await loadClients();
else if (entity === 'interface') await loadInterfaces();
else if (entity === 'binding') await loadBindings();
else await loadCredentials();
} finally {
isListLoading.value = false;
}
};
// ---- 弹窗打开/关闭 ----
@@ -380,10 +395,13 @@ export function useIntegrationConnectorAdmin() {
if (action === 'retire' && !window.confirm(t('admin.integrationConnector.msg.retireInterfaceConfirm'))) return;
try {
await changeIntegrationInterfaceLifecycle(row.code, action);
isListLoading.value = true;
await loadInterfaces();
msg.success(t('admin.integrationConnector.msg.statusUpdated'));
} catch (e) {
msg.error((e as Error).message || t('admin.integrationConnector.msg.statusUpdateFailed'));
} finally {
isListLoading.value = false;
}
});
};
@@ -394,10 +412,13 @@ export function useIntegrationConnectorAdmin() {
if (action === 'retire' && !window.confirm(t('admin.integrationConnector.msg.retireBindingConfirm'))) return;
try {
await changeIntegrationBindingLifecycle(row.id, action);
isListLoading.value = true;
await loadBindings();
msg.success(t('admin.integrationConnector.msg.statusUpdated'));
} catch (e) {
msg.error((e as Error).message || t('admin.integrationConnector.msg.statusUpdateFailed'));
} finally {
isListLoading.value = false;
}
});
};
@@ -431,24 +452,39 @@ export function useIntegrationConnectorAdmin() {
}
};
/** 删除客户端实例:先确认(提示语带名称),确认后才调 API。 */
/**
* 删除客户端实例。先用 Element 确认框询问,取消则不请求。
* 核心逻辑:确认框取消时 reject,这里直接返回;确定后才调删除接口并刷新列表。
* @param row - 要删除的客户端实例行
*/
const deleteClient = async (row: IntegrationClientInstanceRow) => {
const summary = t('admin.integrationConnector.msg.deleteConfirm', { code: row.code, name: row.name });
if (!window.confirm(summary)) return;
try {
await ElMessageBox.confirm(summary, t('common.deleteDialog.defaultTitle'), {
type: 'warning',
confirmButtonText: t('common.deleteDialog.confirm'),
cancelButtonText: t('common.deleteDialog.cancel'),
});
} catch {
return;
}
try {
await deleteIntegrationClientInstance(row.code);
const { [row.code]: _removed, ...rest } = testResults.value;
testResults.value = rest;
isListLoading.value = true;
await loadClients();
msg.success(t('admin.integrationConnector.msg.deleted'));
} catch (e) {
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
isListLoading.value = false;
}
};
return {
clients, interfaces, bindings, credentials, capabilities, credentialTypes,
isLoading, activeEntity, showFormModal, isSaving,
isLoading, isListLoading, activeEntity, showFormModal, isSaving,
clientForm, interfaceForm, bindingForm, credentialForm,
showCallModal, callCapability, callParamsText, callContextText, callResult, callBusy,
testingClientCode, testResults,
@@ -1,13 +1,13 @@
/**
* features/admin/modules/knowledge-base/KnowledgeBasePage.vue
* 知识库配置页(治理面)。路由:/admin/knowledge-base
* 用途:管理端知识库配置页入口。
* 依赖:KbAdminPanel。
* 逻辑:路由 /admin/knowledge-base。卡片骨架在 KbAdminPanel 的 AdminListPage 里,本页不再套第二层卡片。
*/
<script setup lang="ts">
import KbAdminPanel from '@/features/kb/components/KbAdminPanel.vue';
</script>
<template>
<section class="admin-table-section overflow-hidden animate-fade-in-up">
<KbAdminPanel />
</section>
<KbAdminPanel />
</template>
@@ -1,18 +1,31 @@
/**
* features/admin/modules/linked-services/LinkedServicesPage.vue
* 关联服务管理独立页面:表格列表 + 新增/编辑弹窗。
* 依赖:useLinkedServicesAdmin、LinkedServiceFormModal、DeleteConfirmDialog。
* 逻辑:路由 /admin/linked-services;启用项自动出现在 Chat/工作台侧栏底部。
* 用途:关联服务列表。一张卡片里放标题、新增按钮和表格。
* 依赖:AdminListPage、useLinkedServicesAdmin、useElementProvider、element-plus、关联服务表单对话框。
* 逻辑:路由 /admin/linked-services。启用项会出现在对话和工作台侧栏。删除用 Element 确认框。
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Edit, Plus, Trash2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import { Plus } from '@element-plus/icons-vue';
import {
ElButton,
ElConfigProvider,
ElSwitch,
ElTable,
ElTableColumn,
} from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/features/admin/styles/element-trial.css';
import AdminListPage from '@/features/admin/components/AdminListPage.vue';
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
import type { AdminLinkedServiceRow } from '@/features/admin/types/linked-service.types';
import LinkedServiceFormModal from './components/LinkedServiceFormModal.vue';
import { useLinkedServicesAdmin } from './composables/useLinkedServicesAdmin';
const { t } = useI18n();
const { elementLocale } = useElementProvider();
const {
services,
@@ -20,8 +33,6 @@ const {
isLoading,
isSaving,
showFormModal,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
openCreateModal,
openEditModal,
@@ -29,93 +40,68 @@ const {
saveService,
toggleEnabled,
deleteServiceItem,
closeDeleteConfirm,
confirmDelete,
} = useLinkedServicesAdmin();
/**
* 打开编辑对话框。表格行类型较宽,这里收成关联服务行。
* @param row - 当前表格行
*/
function editService(row: AdminLinkedServiceRow): void {
openEditModal(row);
}
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="admin-table-section animate-fade-in-up">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<ElConfigProvider :locale="elementLocale">
<AdminListPage :loading="isLoading">
<template #title>
<h2 class="section-title">{{ t('admin.linkedServices.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.linkedServices.subtitle') }}</p>
</template>
<template #actions>
<ElButton type="primary" :icon="Plus" @click="openCreateModal">
{{ t('admin.linkedServices.add') }}
</ElButton>
</template>
<template v-else>
<div class="admin-table-header admin-table-header--stacked">
<div>
<h2 class="section-title">{{ t('admin.linkedServices.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.linkedServices.subtitle') }}</p>
</div>
<button
type="button"
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-all shadow-lg shadow-brand-200 active:scale-95 text-sm font-medium"
@click="openCreateModal"
>
<Plus class="w-4 h-4" />
<span>{{ t('admin.linkedServices.add') }}</span>
</button>
</div>
<div class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.linkedServices.headers.name') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.linkedServices.headers.url') }}</th>
<th class="px-6 py-4 text-left text-xs w-28">{{ t('admin.linkedServices.headers.status') }}</th>
<th class="px-6 py-4 text-left text-xs w-24">{{ t('admin.linkedServices.headers.sortOrder') }}</th>
<th class="px-6 py-4 text-right text-xs w-40">{{ t('admin.linkedServices.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="services.length === 0">
<td colspan="5" class="px-6 admin-table-empty">{{ t('admin.linkedServices.empty') }}</td>
</tr>
<tr v-for="row in services" :key="row.id">
<td class="px-6 py-4 text-sm font-medium text-primary">{{ row.name }}</td>
<td class="px-6 py-4 text-sm text-secondary font-mono break-all">{{ row.url }}</td>
<td class="px-6 py-4">
<button
type="button"
class="inline-flex items-center rounded-full px-2.5 py-1 text-xs font-medium transition-colors"
:class="row.is_enabled
? 'bg-emerald-50 text-emerald-700 hover:bg-emerald-100'
: 'bg-surface-soft text-muted hover:bg-surface'"
@click="toggleEnabled(row)"
>
{{ row.is_enabled ? t('admin.linkedServices.status.enabled') : t('admin.linkedServices.status.disabled') }}
</button>
</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.sort_order }}</td>
<td class="px-6 py-4 text-right">
<div class="inline-flex items-center gap-1">
<button
type="button"
class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary"
:title="t('admin.edit')"
@click="openEditModal(row)"
>
<Edit class="w-4 h-4" />
</button>
<button
type="button"
class="p-2 rounded-lg text-muted hover:bg-red-50 hover:text-red-600"
:title="t('admin.delete')"
@click="deleteServiceItem(row.id)"
>
<Trash2 class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<ElTable
class="hx-admin-table"
:data="services"
row-key="id"
:empty-text="t('admin.linkedServices.empty')"
>
<ElTableColumn prop="name" :label="t('admin.linkedServices.headers.name')" min-width="160" />
<ElTableColumn prop="url" :label="t('admin.linkedServices.headers.url')" min-width="240">
<template #default="{ row }">
<span class="linked-service-url">{{ row.url }}</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.linkedServices.headers.status')" width="120">
<template #default="{ row }">
<ElSwitch
:model-value="row.is_enabled"
:title="row.is_enabled ? t('admin.linkedServices.status.enabled') : t('admin.linkedServices.status.disabled')"
@change="toggleEnabled(row as AdminLinkedServiceRow)"
/>
</template>
</ElTableColumn>
<ElTableColumn prop="sort_order" :label="t('admin.linkedServices.headers.sortOrder')" width="100" />
<ElTableColumn :label="t('admin.linkedServices.headers.actions')" width="140" align="right">
<template #default="{ row }">
<ElButton link type="primary" @click="editService(row as AdminLinkedServiceRow)">
{{ t('admin.edit') }}
</ElButton>
<ElButton link type="danger" @click="deleteServiceItem((row as AdminLinkedServiceRow).id)">
{{ t('admin.delete') }}
</ElButton>
</template>
</ElTableColumn>
</ElTable>
</AdminListPage>
<LinkedServiceFormModal
:visible="showFormModal"
@@ -124,12 +110,11 @@ onMounted(() => {
@close="closeFormModal"
@save="saveService"
/>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@cancel="closeDeleteConfirm"
@confirm="confirmDelete"
/>
</section>
</ElConfigProvider>
</template>
<style scoped>
.linked-service-url {
word-break: break-all;
}
</style>
@@ -1,11 +1,20 @@
/**
* features/admin/modules/linked-services/components/LinkedServiceFormModal.vue
* 关联服务创建/编辑居中弹窗。
* 依赖:LinkedServiceFormState、admin 通用 modal 样式。
* 逻辑:LinkedServicesPage 打开本组件;提交时 emit save。
* 用途:关联服务创建和编辑对话框。名称、地址、排序和启用开关。
* 依赖:element-plus 对话框和表单、LinkedServiceFormState。
* 逻辑:LinkedServicesPage 打开本组件。提交时 emit save,由 composable 调接口。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import {
ElButton,
ElDialog,
ElForm,
ElFormItem,
ElInput,
ElInputNumber,
ElSwitch,
} from 'element-plus';
import type { LinkedServiceFormState } from '@/features/admin/types/linked-service.types';
defineProps<{
@@ -20,51 +29,58 @@ const emit = defineEmits<{
}>();
const { t } = useI18n();
/**
* 对话框关闭时通知页面收起。
* @param open - Element 对话框的打开状态
*/
function onVisibleChange(open: boolean): void {
if (!open) emit('close');
}
</script>
<template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
<div class="admin-modal-panel max-w-lg max-h-[92vh] scale-100">
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
<h3 class="section-title">
{{ form.id ? t('admin.linkedServices.edit') : t('admin.linkedServices.add') }}
</h3>
<p class="section-desc mt-1">{{ t('admin.linkedServices.formHint') }}</p>
</div>
<div class="px-5 sm:px-8 py-5 space-y-5 overflow-y-auto">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.linkedServices.fields.name') }}</label>
<input
v-model="form.name"
type="text"
class="input-field text-sm"
:placeholder="t('admin.linkedServices.placeholders.name')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.linkedServices.fields.url') }}</label>
<input
v-model="form.url"
type="url"
class="input-field text-sm font-mono"
:placeholder="t('admin.linkedServices.placeholders.url')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.linkedServices.fields.sortOrder') }}</label>
<input v-model.number="form.sort_order" type="number" class="input-field text-sm" min="0" />
</div>
<label class="inline-flex items-center gap-2 text-sm text-secondary cursor-pointer">
<input v-model="form.is_enabled" type="checkbox" class="w-4 h-4 rounded text-brand-600 border-default" />
{{ t('admin.linkedServices.fields.enabled') }}
</label>
</div>
<div class="admin-modal-footer">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button type="button" class="btn-primary disabled:opacity-70" :disabled="isSaving" @click="emit('save')">
{{ isSaving ? t('admin.save') + '...' : form.id ? t('admin.update') : t('admin.add') }}
</button>
</div>
</div>
</div>
<ElDialog
:model-value="visible"
:title="form.id ? t('admin.linkedServices.edit') : t('admin.linkedServices.add')"
width="480px"
align-center
append-to-body
:close-on-click-modal="false"
:close-on-press-escape="!isSaving"
:show-close="!isSaving"
@update:model-value="onVisibleChange"
>
<p class="section-desc">{{ t('admin.linkedServices.formHint') }}</p>
<ElForm class="linked-service-form" label-position="top" :model="form" @submit.prevent="emit('save')">
<ElFormItem :label="t('admin.linkedServices.fields.name')" required>
<ElInput v-model="form.name" :placeholder="t('admin.linkedServices.placeholders.name')" />
</ElFormItem>
<ElFormItem :label="t('admin.linkedServices.fields.url')" required>
<ElInput v-model="form.url" :placeholder="t('admin.linkedServices.placeholders.url')" />
</ElFormItem>
<ElFormItem :label="t('admin.linkedServices.fields.sortOrder')">
<ElInputNumber v-model="form.sort_order" :min="0" controls-position="right" />
</ElFormItem>
<ElFormItem :label="t('admin.linkedServices.fields.enabled')">
<ElSwitch v-model="form.is_enabled" />
</ElFormItem>
</ElForm>
<template #footer>
<ElButton :disabled="isSaving" @click="emit('close')">{{ t('admin.cancel') }}</ElButton>
<ElButton type="primary" :loading="isSaving" @click="emit('save')">
{{ form.id ? t('admin.update') : t('admin.add') }}
</ElButton>
</template>
</ElDialog>
</template>
<style scoped>
.linked-service-form {
margin-top: 16px;
}
.linked-service-form :deep(.el-input-number) {
width: 9rem;
}
</style>
@@ -1,11 +1,12 @@
/**
* features/admin/modules/linked-services/composables/useLinkedServicesAdmin.ts
* 关联服务管理:列表、新增/编辑弹窗、启用开关、删除。
* 依赖:admin.api、linked-service.types、linked-nav.store、useMessage。
* 逻辑:LinkedServicesPage 调用本 composable;保存/删除后刷新侧栏入口缓存。
* 依赖:admin.api、linked-service.types、linked-nav.store、useMessage、element-plus 确认框。
* 逻辑:LinkedServicesPage 调用本 composable;保存/删除后刷新侧栏入口缓存。删除用 ElMessageBox。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessageBox } from 'element-plus';
import {
createLinkedService,
deleteLinkedService,
@@ -32,10 +33,6 @@ export function useLinkedServicesAdmin() {
const isSaving = ref(false);
const showFormModal = ref(false);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
/**
* 拉取关联服务列表。
* @returns Promise<void>
@@ -60,29 +57,6 @@ export function useLinkedServicesAdmin() {
isLoading.value = false;
};
/** 打开删除确认对话框。 */
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
deleteConfirmMessage.value = message;
deleteConfirmAction = action;
showDeleteConfirmDialog.value = true;
};
/** 关闭删除确认对话框。 */
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmAction = null;
};
/** 执行删除确认动作。 */
const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
}
};
/** 打开「新增关联服务」弹窗。 */
const openCreateModal = (): void => {
form.value = createEmptyLinkedServiceForm();
@@ -160,21 +134,29 @@ export function useLinkedServicesAdmin() {
};
/**
* 删除指定关联服务。
* 删除指定关联服务。先用 Element 确认框询问,取消则不请求。
* 核心逻辑:确定后删除、刷新列表,并更新侧栏入口缓存。
* @param id - 主键
*/
const deleteServiceItem = (id: number): void => {
openDeleteConfirm(t('admin.linkedServices.confirmDelete'), async () => {
try {
await deleteLinkedService(id);
await loadServices();
void linkedNav.refresh();
msg.success(t('admin.linkedServices.msg.deleted'));
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
});
const deleteServiceItem = async (id: number): Promise<void> => {
try {
await ElMessageBox.confirm(t('admin.linkedServices.confirmDelete'), t('common.deleteDialog.defaultTitle'), {
type: 'warning',
confirmButtonText: t('common.deleteDialog.confirm'),
cancelButtonText: t('common.deleteDialog.cancel'),
});
} catch {
return;
}
try {
await deleteLinkedService(id);
await loadServices();
void linkedNav.refresh();
msg.success(t('admin.linkedServices.msg.deleted'));
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
};
return {
@@ -183,8 +165,6 @@ export function useLinkedServicesAdmin() {
isLoading,
isSaving,
showFormModal,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
openCreateModal,
openEditModal,
@@ -192,7 +172,5 @@ export function useLinkedServicesAdmin() {
saveService,
toggleEnabled,
deleteServiceItem,
closeDeleteConfirm,
confirmDelete,
};
}
@@ -1,24 +1,49 @@
/**
* features/admin/modules/permissions/PermissionsPage.vue
* 用途:应用权限页。已种子权限组时以角色包为主、矩阵只读;否则保留历史按人勾选。
* 依赖:usePermissionsAdmin、RoleEditModal、UserPickerDialog、PaginationBar、roleLabel、getUserAvatarLabel。
* 逻辑:路由 /admin/permissions;点人数打开选人弹窗,确定后必须确认增减才写库。
* 依赖:AdminListPage、AdminListTabs、usePermissionsAdmin、useElementProvider、element-plus、RoleEditModal、RoleMembersConfirmDialog、UserPickerDialog、BatchPermissionModal。
* 逻辑:路由 /admin/permissions。骨架用 AdminListPage。角色/矩阵用 AdminListTabs。
* 点人数打开选人弹窗,确定后必须确认增减才写库。删除和重写入口确认用 ElMessageBox。
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { computed, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Download, FileText, Plus, Shield, Users } from 'lucide-vue-next';
import { Download, Plus, Upload, User } from '@element-plus/icons-vue';
import {
ElButton,
ElCheckbox,
ElConfigProvider,
ElInput,
ElLoading,
ElOption,
ElPagination,
ElSelect,
ElSpace,
ElTable,
ElTableColumn,
ElTag,
} from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/features/admin/styles/element-trial.css';
import AdminListPage from '@/features/admin/components/AdminListPage.vue';
import AdminListTabs from '@/features/admin/components/AdminListTabs.vue';
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
import BatchPermissionModal from '@/features/admin/modules/users/components/BatchPermissionModal.vue';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import { getUserAvatarLabel } from '@/shared/utils/user-avatar';
import UserPickerDialog from '@/shared/components/UserPickerDialog.vue';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import type { AdminUserRow } from '@/features/admin/types/admin.types';
import type { PermissionRoleRow } from '@/features/admin/types/permissionRole.types';
import { adminRoleLabel, LEGACY_ROLE_OPTIONS } from '@/features/admin/utils/roleLabel';
import RoleEditModal from './components/RoleEditModal.vue';
import RoleMembersConfirmDialog from './components/RoleMembersConfirmDialog.vue';
import { usePermissionsAdmin } from './composables/usePermissionsAdmin';
const vLoading = ElLoading.directive;
const { t } = useI18n();
const { elementLocale } = useElementProvider();
const csvInputRef = ref<HTMLInputElement | null>(null);
const {
agents,
@@ -28,13 +53,13 @@ const {
permissionFilters,
selectedUserIds,
paginatedUsers,
allUsersSelectedOnPage,
permissionPage,
permissionPageSize,
permissionPageSizeOptions,
permissionTotalRows,
permissionTotalPages,
allUsersSelectedOnPage,
isLoading,
isListLoading,
isSaving,
activeTab,
rolesConfigured,
@@ -43,8 +68,6 @@ const {
showRoleEditor,
editingExisting,
roleDraft,
editingMemberCount,
showRoleSaveConfirm,
pickerRole,
showPicker,
pickerSelectedIds,
@@ -64,7 +87,6 @@ const {
openEditRole,
closeRoleEditor,
requestSaveRole,
persistRole,
removeRole,
openMembersPicker,
handlePickerConfirm,
@@ -72,285 +94,273 @@ const {
applyMembers,
} = usePermissionsAdmin();
/** 角色表只在已配置权限组、并且停在角色页时显示。 */
const showRoles = computed(() => rolesConfigured.value && activeTab.value === 'roles');
/** 未配置权限组时直接看矩阵;已配置时跟页签走。 */
const showMatrix = computed(() => !rolesConfigured.value || activeTab.value === 'matrix');
/** 角色表和权限矩阵两个页签。没有权限组时不渲染这一条。 */
const permissionTabs = computed(() => [
{ name: 'roles', label: t('admin.permRoles.tabs.roles') },
{ name: 'matrix', label: t('admin.permRoles.tabs.matrix') },
]);
/**
* 公共页签回传字符串,这里收成角色或矩阵。
* @param name - AdminListTabs 当前 name
*/
function onPermissionTab(name: string): void {
if (name === 'roles' || name === 'matrix') activeTab.value = name;
}
/**
* 角色筛选。清空时写回空字符串,矩阵仍按「所有角色」过滤。
* @param value - 选中的角色编码;清空不是字符串
*/
function onRoleFilterChange(value: unknown): void {
permissionFilters.value.role = typeof value === 'string' ? value : '';
}
/**
* 打开隐藏的 CSV 文件框,选中后仍走 importPermissions。
*/
function openCsvImport(): void {
csvInputRef.value?.click();
}
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="section-gap animate-fade-in-up">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<div class="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
<div>
<h2 class="section-title">{{ t('admin.perm.title') }}</h2>
<p class="section-desc mt-1">
{{ rolesConfigured ? t('admin.permRoles.subtitle') : t('admin.perm.subtitle') }}
</p>
</div>
<div class="flex flex-wrap gap-3">
<button
<ElConfigProvider :locale="elementLocale">
<AdminListPage :loading="isLoading">
<template #title>
<h2 class="section-title">{{ t('admin.perm.title') }}</h2>
<p class="section-desc mt-1">
{{ rolesConfigured ? t('admin.permRoles.subtitle') : t('admin.perm.subtitle') }}
</p>
</template>
<template #actions>
<div class="perm-actions">
<ElSpace wrap>
<ElButton
v-if="!rolesConfigured && selectedUserIds.length > 0"
type="button"
class="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 transition-all shadow-lg shadow-indigo-200 active:scale-95"
type="primary"
:icon="User"
@click="openBatchPermissionModal"
>
<Users class="w-4 h-4" />
<span class="font-medium">{{ t('admin.perm.batchAssign') }}</span>
</button>
<label
v-if="!rolesConfigured"
class="flex items-center gap-2 px-4 py-2 btn-secondary cursor-pointer text-sm font-medium transition-all shadow-sm"
>
<input type="file" accept=".csv" class="hidden" @change="importPermissions" />
<FileText class="w-4 h-4" />
{{ t('admin.perm.batchAssign') }}
</ElButton>
<ElButton v-if="!rolesConfigured" :icon="Upload" @click="openCsvImport">
{{ t('admin.perm.importCsv') }}
</label>
<button
type="button"
class="flex items-center gap-2 px-4 py-2 btn-secondary text-sm font-medium transition-all shadow-sm"
@click="exportPermissions"
>
<Download class="w-4 h-4" />
</ElButton>
<ElButton :icon="Download" @click="exportPermissions">
{{ t('admin.perm.exportCsv') }}
</button>
<button
v-if="rolesConfigured"
type="button"
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 text-sm font-medium"
@click="openCreateRole"
>
<Plus class="w-4 h-4" />
</ElButton>
<ElButton v-if="rolesConfigured" type="primary" :icon="Plus" @click="openCreateRole">
{{ t('admin.permRoles.create') }}
</button>
</ElButton>
</ElSpace>
<input
ref="csvInputRef"
type="file"
accept=".csv"
class="perm-csv-input"
@change="importPermissions"
/>
</div>
</div>
<div v-if="rolesConfigured" class="flex gap-1 border-b border-default">
<button
type="button"
class="px-4 py-2 text-sm font-medium"
:class="activeTab === 'roles' ? 'border-b-2 border-brand-600 text-brand-700' : 'text-muted'"
@click="activeTab = 'roles'"
</template>
<template v-if="rolesConfigured" #tabs>
<AdminListTabs :model-value="activeTab" :items="permissionTabs" @update:model-value="onPermissionTab" />
</template>
<template v-if="showMatrix" #filters>
<ElInput
v-model="permissionFilters.username"
clearable
class="perm-filter-search"
:placeholder="t('admin.perm.filterName')"
/>
<ElInput
v-model="permissionFilters.department"
clearable
class="perm-filter-search"
:placeholder="t('admin.perm.filterDept')"
/>
<ElSelect
:model-value="permissionFilters.role || undefined"
class="perm-filter-role"
clearable
:placeholder="t('admin.perm.allRoles')"
@update:model-value="onRoleFilterChange"
>
{{ t('admin.permRoles.tabs.roles') }}
</button>
<button
type="button"
class="px-4 py-2 text-sm font-medium"
:class="activeTab === 'matrix' ? 'border-b-2 border-brand-600 text-brand-700' : 'text-muted'"
@click="activeTab = 'matrix'"
<ElOption v-for="role in roles" :key="role.code" :label="role.name" :value="role.code" />
<template v-if="!roles.length">
<ElOption
v-for="option in LEGACY_ROLE_OPTIONS"
:key="option.code"
:label="t(option.i18nKey)"
:value="option.code"
/>
</template>
</ElSelect>
<span v-if="rolesConfigured" class="hx-element-hint perm-matrix-hint">
{{ t('admin.permRoles.matrixHint') }}
</span>
</template>
<ElTable
v-if="showRoles"
v-loading="isListLoading"
class="hx-admin-table"
:data="roles"
row-key="code"
:empty-text="t('admin.wecom.noData')"
>
<ElTableColumn :label="t('admin.permRoles.headers.name')" min-width="180">
<template #default="{ row }">
<div>{{ row.name }}</div>
<div v-if="row.is_default || row.is_platform_admin" class="perm-role-badges">
<ElTag v-if="row.is_default" effect="light">{{ t('admin.permRoles.badge.default') }}</ElTag>
<ElTag v-if="row.is_platform_admin" type="warning" effect="light">
{{ t('admin.permRoles.badge.admin') }}
</ElTag>
</div>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.permRoles.headers.description')" min-width="200">
<template #default="{ row }">
<span class="perm-secondary">{{ row.description || '-' }}</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.permRoles.headers.members')" width="120">
<template #default="{ row }">
<ElButton
v-if="!row.is_platform_admin"
link
type="primary"
@click="openMembersPicker(row as PermissionRoleRow)"
>
{{ t('admin.permRoles.memberCount', { count: row.member_count }) }}
</ElButton>
<span v-else class="perm-secondary">
{{ t('admin.permRoles.memberCount', { count: row.member_count }) }}
</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.permRoles.headers.apps')" min-width="220">
<template #default="{ row }">
<span class="perm-secondary">
{{
row.is_platform_admin
? t('admin.permRoles.allApps')
: (row.agent_names || []).join('、') || '-'
}}
</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.user.headers.actions')" width="160" align="right">
<template #default="{ row }">
<ElButton link type="primary" @click="openEditRole(row as PermissionRoleRow)">
{{ t('admin.edit') }}
</ElButton>
<ElButton
v-if="!row.is_system && !row.is_platform_admin"
link
type="danger"
@click="removeRole(row as PermissionRoleRow)"
>
{{ t('admin.delete') }}
</ElButton>
</template>
</ElTableColumn>
</ElTable>
<ElTable
v-if="showMatrix"
v-loading="isListLoading"
class="hx-admin-table"
:data="paginatedUsers"
row-key="id"
:empty-text="t('admin.user.noUsers')"
>
<ElTableColumn v-if="!rolesConfigured" width="64" align="center" fixed="left">
<template #header>
<ElCheckbox
class="perm-check"
:model-value="allUsersSelectedOnPage"
@change="toggleAllUsers"
/>
</template>
<template #default="{ row }">
<ElCheckbox
class="perm-check"
:model-value="selectedUserIds.includes(row.id)"
@change="toggleUserSelection(row.id)"
/>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.perm.headers.user')" min-width="200" fixed="left">
<template #default="{ row }">
<span class="perm-user">
<span class="perm-avatar">{{ getUserAvatarLabel(row) }}</span>
<span class="perm-ellipsis" :title="row.username">{{ row.username }}</span>
</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.perm.headers.realName')" min-width="140">
<template #default="{ row }">
<span class="perm-ellipsis" :title="row.real_name || '-'">{{ row.real_name || '-' }}</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.perm.headers.dept')" min-width="160">
<template #default="{ row }">
<span class="perm-secondary perm-ellipsis" :title="row.department || '-'">
{{ row.department || '-' }}
</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.user.headers.role')" min-width="140">
<template #default="{ row }">
{{ adminRoleLabel(t, row.role, row.role_name) }}
</template>
</ElTableColumn>
<ElTableColumn
v-for="agent in agents"
:key="agent.id"
:label="agent.name"
min-width="120"
align="center"
>
{{ t('admin.permRoles.tabs.matrix') }}
</button>
</div>
<template #header>
<div class="perm-agent-head">
<span>{{ agent.name }}</span>
<ElTag v-if="agent.type" effect="light">{{ agent.type }}</ElTag>
</div>
</template>
<template #default="{ row }">
<ElCheckbox
class="perm-check"
:model-value="userHasAgent(row as AdminUserRow, agent.id)"
:disabled="rolesConfigured"
@change="toggleUserAgentPermission(row as AdminUserRow, agent.id)"
/>
</template>
</ElTableColumn>
</ElTable>
<div v-if="rolesConfigured && activeTab === 'roles'" class="space-y-4">
<template v-if="rolesConfigured">
<div class="admin-table-section admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-sm">{{ t('admin.permRoles.headers.name') }}</th>
<th class="px-6 py-4 text-left text-sm">{{ t('admin.permRoles.headers.description') }}</th>
<th class="px-6 py-4 text-left text-sm">{{ t('admin.permRoles.headers.members') }}</th>
<th class="px-6 py-4 text-left text-sm">{{ t('admin.permRoles.headers.apps') }}</th>
<th class="px-6 py-4 text-right text-sm">{{ t('admin.user.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="role in roles" :key="role.code">
<td class="px-6 py-4">
<div class="font-medium text-primary">{{ role.name }}</div>
<div class="mt-1 flex flex-wrap gap-1.5">
<span
v-if="role.is_default"
class="inline-flex rounded-full border border-brand-100 bg-brand-50 px-2 py-0.5 text-[11px] text-brand-700"
>
{{ t('admin.permRoles.badge.default') }}
</span>
<span
v-if="role.is_platform_admin"
class="inline-flex items-center gap-1 rounded-full border border-purple-100 bg-purple-50 px-2 py-0.5 text-[11px] text-purple-700"
>
<Shield class="w-3 h-3" />
{{ t('admin.permRoles.badge.admin') }}
</span>
</div>
</td>
<td class="px-6 py-4 text-sm text-muted max-w-xs">{{ role.description || '-' }}</td>
<td class="px-6 py-4">
<button
v-if="!role.is_platform_admin"
type="button"
class="text-brand-600 hover:text-brand-800 font-semibold"
@click="openMembersPicker(role)"
>
{{ t('admin.permRoles.memberCount', { count: role.member_count }) }}
</button>
<span v-else class="text-sm text-muted">
{{ t('admin.permRoles.memberCount', { count: role.member_count }) }}
</span>
</td>
<td class="px-6 py-4 text-sm text-muted">
{{
role.is_platform_admin
? t('admin.permRoles.allApps')
: (role.agent_names || []).join('、') || '-'
}}
</td>
<td class="px-6 py-4 text-right whitespace-nowrap">
<button
type="button"
class="text-brand-600 hover:text-brand-900 font-medium text-xs px-3 py-1.5 rounded-lg hover:bg-brand-50"
@click="openEditRole(role)"
>
{{ t('admin.edit') }}
</button>
<button
v-if="!role.is_system && !role.is_platform_admin"
type="button"
class="text-red-600 hover:text-red-800 font-medium text-xs px-3 py-1.5 rounded-lg hover:bg-red-50"
@click="removeRole(role)"
>
{{ t('admin.delete') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>
</div>
<template v-if="!rolesConfigured || activeTab === 'matrix'">
<p v-if="rolesConfigured" class="text-sm text-muted">{{ t('admin.permRoles.matrixHint') }}</p>
<div class="admin-table-filters--inline">
<input
v-model="permissionFilters.username"
:placeholder="t('admin.perm.filterName')"
class="admin-table-filter-input w-48"
/>
<input
v-model="permissionFilters.department"
:placeholder="t('admin.perm.filterDept')"
class="admin-table-filter-input w-48"
/>
<select v-model="permissionFilters.role" class="admin-table-filter-input w-40">
<option value="">{{ t('admin.perm.allRoles') }}</option>
<option v-for="role in roles" :key="role.code" :value="role.code">{{ role.name }}</option>
<template v-if="!roles.length">
<option
v-for="option in LEGACY_ROLE_OPTIONS"
:key="option.code"
:value="option.code"
>
{{ t(option.i18nKey) }}
</option>
</template>
</select>
</div>
<div class="admin-table-section admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th v-if="!rolesConfigured" class="px-4 py-4 w-12 text-center sticky left-0 admin-table-sticky-head z-20">
<input
type="checkbox"
class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500"
:checked="allUsersSelectedOnPage"
@change="toggleAllUsers"
/>
</th>
<th class="px-6 py-4 text-left text-sm sticky left-0 admin-table-sticky-head z-20 w-56">
{{ t('admin.perm.headers.user') }}
</th>
<th class="px-6 py-4 text-left text-sm w-36">{{ t('admin.perm.headers.realName') }}</th>
<th class="px-6 py-4 text-left text-sm w-40 border-r border-subtle">
{{ t('admin.perm.headers.dept') }}
</th>
<th class="px-6 py-4 text-left text-sm w-32">{{ t('admin.user.headers.role') }}</th>
<th
v-for="agent in agents"
:key="agent.id"
class="px-4 py-4 text-center text-sm min-w-[100px]"
>
<div class="flex flex-col items-center gap-1">
<span>{{ agent.name }}</span>
<span class="text-[10px] text-muted font-normal border border-default px-1 rounded">
{{ agent.type }}
</span>
</div>
</th>
</tr>
</thead>
<tbody>
<tr v-for="user in paginatedUsers" :key="user.id">
<td v-if="!rolesConfigured" class="px-4 py-4 text-center sticky left-0 admin-table-sticky-cell z-20">
<input
type="checkbox"
class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500"
:checked="selectedUserIds.includes(user.id)"
@change="toggleUserSelection(user.id)"
/>
</td>
<td class="px-6 py-4 sticky left-0 admin-table-sticky-cell z-20">
<div class="flex items-center gap-3">
<div
class="w-8 h-8 rounded-full bg-gradient-to-br from-brand-100 to-indigo-100 text-brand-600 flex items-center justify-center font-bold text-sm"
>
{{ getUserAvatarLabel(user) }}
</div>
<div class="font-medium text-primary text-sm truncate max-w-[120px]" :title="user.username">
{{ user.username }}
</div>
</div>
</td>
<td class="px-6 py-4">
<div class="text-sm text-primary truncate" :title="user.real_name || '-'">
{{ user.real_name || '-' }}
</div>
</td>
<td class="px-6 py-4 border-r border-subtle">
<div class="text-sm text-muted truncate" :title="user.department">
{{ user.department || '-' }}
</div>
</td>
<td class="px-6 py-4 text-sm text-primary">
{{ adminRoleLabel(t, user.role, user.role_name) }}
</td>
<td
v-for="agent in agents"
:key="agent.id"
class="px-4 py-4 text-center border-l border-dashed border-subtle"
>
<input
type="checkbox"
class="admin-checkbox-lg"
:checked="userHasAgent(user, agent.id)"
:disabled="rolesConfigured"
@change="toggleUserAgentPermission(user, agent.id)"
/>
</td>
</tr>
</tbody>
</table>
</div>
<PaginationBar
v-model:page="permissionPage"
<template v-if="showMatrix" #pagination>
<ElPagination
v-model:current-page="permissionPage"
v-model:page-size="permissionPageSize"
:total="permissionTotalRows"
:pages="permissionTotalPages"
:page-size-options="permissionPageSizeOptions"
class="mt-5"
:page-sizes="permissionPageSizeOptions"
layout="total, sizes, prev, pager, next"
background
/>
</template>
</template>
</AdminListPage>
<BatchPermissionModal
:visible="showBatchPermissionModal"
@@ -374,16 +384,6 @@ onMounted(() => {
@update:draft="roleDraft = $event"
/>
<DeleteConfirmDialog
v-model="showRoleSaveConfirm"
:title="t('admin.permRoles.saveConfirm.title')"
:message="t('admin.permRoles.saveConfirm.message', { count: editingMemberCount })"
:confirm-text="t('admin.save')"
confirm-tone="primary"
:confirm-loading="isSaving"
@confirm="persistRole"
/>
<UserPickerDialog
v-model="showPicker"
:users="pickerUsers"
@@ -400,5 +400,84 @@ onMounted(() => {
@cancel="cancelMembersConfirm"
@confirm="applyMembers"
/>
</section>
</ElConfigProvider>
</template>
<style scoped>
.perm-actions {
display: flex;
justify-content: flex-end;
}
.perm-csv-input {
display: none;
}
:deep(.perm-filter-search) {
width: 16rem;
}
:deep(.perm-filter-role) {
width: 11rem;
}
.perm-matrix-hint {
margin-top: 0;
flex: 1 1 12rem;
min-width: 12rem;
}
.perm-role-badges {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-top: 4px;
}
.perm-secondary {
color: var(--el-text-color-secondary);
}
.perm-user {
display: inline-flex;
align-items: center;
gap: 12px;
max-width: 100%;
min-width: 0;
}
.perm-avatar {
display: flex;
height: 2.25rem;
width: 2.25rem;
flex: none;
align-items: center;
justify-content: center;
border-radius: 9999px;
background-image: linear-gradient(to bottom right, #0ea5e9, #4f46e5);
font-size: var(--el-font-size-extra-small);
font-weight: 700;
color: #fff;
}
.perm-ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
min-width: 0;
}
.perm-agent-head {
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
line-height: 1.3;
}
.perm-check :deep(.el-checkbox) {
height: auto;
margin-right: 0;
vertical-align: middle;
}
</style>
@@ -1,13 +1,23 @@
/**
* features/admin/modules/permissions/components/RoleEditModal.vue
* 用途:新建/编辑权限组:名称、应用入口,以及挂在各应用下的功能权限。
* 依赖:permissionRole.types、rolePackage.utils、vue-i18n、lucide-vue-next。
* 逻辑:PermissionsPage 打开;应用按对话形态分组;能力默认折叠,点右侧展开后再勾选。
* 依赖:permissionRole.types、rolePackage.utils、vue-i18n、element-plus。
* 逻辑:PermissionsPage 打开;应用按对话形态分组;能力默认折叠,点右侧展开后再勾选。样式跟权限页已引入的 Element 皮肤走。
*/
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { ChevronDown, Search } from 'lucide-vue-next';
import { ArrowDown, Search } from '@element-plus/icons-vue';
import {
ElButton,
ElCheckbox,
ElDialog,
ElForm,
ElFormItem,
ElIcon,
ElInput,
ElTag,
} from 'element-plus';
import type {
PermissionRoleCatalog,
PermissionRoleCatalogAgent,
@@ -41,6 +51,14 @@ const { t, te } = useI18n();
const appQuery = ref('');
const expandedAgentIds = ref<number[]>([]);
/**
* 对话框关闭时通知页面收起编辑框。
* @param open - Element 对话框的打开状态
*/
function onVisibleChange(open: boolean): void {
if (!open) emit('close');
}
watch(
() => props.visible,
(open) => {
@@ -171,266 +189,257 @@ function toggleFeature(agent: PermissionRoleCatalogAgent, key: string, checked:
</script>
<template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in">
<div class="admin-modal-panel max-w-3xl max-h-[92vh] scale-100">
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
<h3 class="section-title">
{{ isCreate ? t('admin.permRoles.edit.createTitle') : t('admin.permRoles.edit.title') }}
</h3>
<p class="section-desc mt-1">{{ t('admin.permRoles.edit.subtitle') }}</p>
</div>
<div class="px-5 sm:px-8 py-5 space-y-5 overflow-y-auto">
<div class="space-y-4">
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
{{ t('admin.permRoles.edit.name') }}
</label>
<input
:value="draft.name"
type="text"
class="w-full border-default rounded-xl px-4 py-3 text-sm"
@input="patch({ name: ($event.target as HTMLInputElement).value })"
/>
</div>
<div v-if="isCreate" class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
{{ t('admin.permRoles.edit.code') }}
</label>
<input
:value="draft.code"
type="text"
class="w-full border-default rounded-xl px-4 py-3 text-sm"
:placeholder="t('admin.permRoles.edit.codeHint')"
@input="patch({ code: ($event.target as HTMLInputElement).value })"
/>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
{{ t('admin.permRoles.edit.description') }}
</label>
<textarea
:value="draft.description"
rows="2"
class="w-full border-default rounded-xl px-4 py-3 text-sm"
@input="patch({ description: ($event.target as HTMLTextAreaElement).value })"
/>
</div>
</div>
<label class="flex items-center gap-2 text-sm text-primary">
<input
type="checkbox"
class="w-4 h-4 rounded text-brand-600"
:checked="draft.is_default"
:disabled="draft.is_default && !isCreate"
@change="patch({ is_default: ($event.target as HTMLInputElement).checked })"
/>
<ElDialog
:model-value="visible"
:title="isCreate ? t('admin.permRoles.edit.createTitle') : t('admin.permRoles.edit.title')"
width="680px"
align-center
append-to-body
:close-on-click-modal="false"
:close-on-press-escape="!isSaving"
:show-close="!isSaving"
@update:model-value="onVisibleChange"
>
<ElForm class="perm-role-form" label-position="top" :model="draft" @submit.prevent>
<p class="hx-element-hint">{{ t('admin.permRoles.edit.subtitle') }}</p>
<ElFormItem :label="t('admin.permRoles.edit.name')">
<ElInput
:model-value="draft.name"
@update:model-value="patch({ name: String($event) })"
/>
</ElFormItem>
<ElFormItem v-if="isCreate" :label="t('admin.permRoles.edit.code')">
<ElInput
:model-value="draft.code"
:placeholder="t('admin.permRoles.edit.codeHint')"
@update:model-value="patch({ code: String($event) })"
/>
</ElFormItem>
<ElFormItem :label="t('admin.permRoles.edit.description')">
<ElInput
:model-value="draft.description"
type="textarea"
:rows="4"
@update:model-value="patch({ description: String($event) })"
/>
</ElFormItem>
<ElFormItem>
<ElCheckbox
:model-value="draft.is_default"
:disabled="draft.is_default && !isCreate"
@change="patch({ is_default: Boolean($event) })"
>
{{ t('admin.permRoles.edit.isDefault') }}
</label>
<div class="space-y-2">
<div class="flex flex-wrap items-end justify-between gap-2">
<div>
<div class="text-xs font-semibold uppercase tracking-wider text-muted">
{{ t('admin.permRoles.edit.apps') }}
</div>
<p class="mt-1 text-xs text-muted">
{{ isPlatformAdmin ? t('admin.permRoles.edit.adminAllApps') : t('admin.permRoles.edit.appsHint') }}
</p>
</div>
<span class="text-xs font-medium text-brand-700">
</ElCheckbox>
</ElFormItem>
<ElFormItem class="role-apps-item">
<template #label>
<span class="role-apps-label">
<span>{{ t('admin.permRoles.edit.apps') }}</span>
<ElTag effect="light">
{{ t('admin.permRoles.edit.selectedCount', { count: selectedCount }) }}
</span>
</div>
<div class="relative">
<Search class="pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted" />
<input
v-model="appQuery"
type="search"
class="w-full rounded-xl border-default py-2 pl-9 pr-3 text-sm"
:placeholder="t('admin.permRoles.edit.filterPlaceholder')"
/>
</div>
<div class="role-app-list">
<p v-if="!groupedAgents.length" class="px-4 py-8 text-center text-sm text-muted">
{{ t('admin.permRoles.edit.noMatch') }}
</p>
<section v-for="group in groupedAgents" :key="group.mode" class="role-app-group">
<h4 class="role-app-group-title">{{ group.label }}</h4>
<div
v-for="agent in group.agents"
:key="agent.id"
class="role-app-row"
:class="agentSelected(agent.id) ? 'is-on' : ''"
>
<div class="flex items-center gap-2.5">
<label
class="flex min-w-0 flex-1 items-center gap-2.5"
:class="isPlatformAdmin ? 'cursor-default' : 'cursor-pointer'"
</ElTag>
</span>
</template>
<p class="hx-element-hint">
{{ isPlatformAdmin ? t('admin.permRoles.edit.adminAllApps') : t('admin.permRoles.edit.appsHint') }}
</p>
<ElInput
v-model="appQuery"
clearable
:prefix-icon="Search"
:placeholder="t('admin.permRoles.edit.filterPlaceholder')"
/>
<div class="role-app-list">
<p v-if="!groupedAgents.length" class="role-app-empty">
{{ t('admin.permRoles.edit.noMatch') }}
</p>
<section v-for="group in groupedAgents" :key="group.mode" class="role-app-group">
<h4 class="role-app-group-title">{{ group.label }}</h4>
<div
v-for="agent in group.agents"
:key="agent.id"
class="role-app-row"
:class="{ 'is-on': agentSelected(agent.id) }"
>
<div class="role-app-main">
<ElCheckbox
class="role-agent-check"
:model-value="agentSelected(agent.id)"
:disabled="isPlatformAdmin"
@change="toggleAgent(agent.id)"
>
<span class="perm-ellipsis">{{ agent.name }}</span>
</ElCheckbox>
<ElButton
v-if="agentFeatures(agent).length"
link
type="primary"
:aria-expanded="isExpanded(agent.id)"
@click="toggleExpanded(agent.id)"
>
{{ t('admin.permRoles.edit.featureCount', { count: agentFeatures(agent).length }) }}
<ElIcon class="role-expand-icon" :class="{ 'is-open': isExpanded(agent.id) }">
<ArrowDown />
</ElIcon>
</ElButton>
</div>
<div v-if="isExpanded(agent.id) && agentFeatures(agent).length" class="role-feat-row">
<div
v-for="feature in agentFeatures(agent)"
:key="feature.key"
class="role-feat"
:class="{ 'is-on': draft.feature_permissions[feature.key] }"
:title="featureHint(feature)"
>
<ElCheckbox
:model-value="Boolean(draft.feature_permissions[feature.key])"
@change="toggleFeature(agent, feature.key, Boolean($event))"
>
<input
type="checkbox"
class="role-check appearance-none"
:checked="agentSelected(agent.id)"
:disabled="isPlatformAdmin"
@change="toggleAgent(agent.id)"
/>
<span class="min-w-0 truncate text-sm font-medium text-primary">{{ agent.name }}</span>
</label>
<button
v-if="agentFeatures(agent).length"
type="button"
class="role-expand"
:aria-expanded="isExpanded(agent.id)"
@click="toggleExpanded(agent.id)"
>
{{ t('admin.permRoles.edit.featureCount', { count: agentFeatures(agent).length }) }}
<ChevronDown class="h-3.5 w-3.5 transition-transform" :class="isExpanded(agent.id) ? 'rotate-180' : ''" />
</button>
</div>
<div v-if="isExpanded(agent.id) && agentFeatures(agent).length" class="role-feat-row">
<label
v-for="feature in agentFeatures(agent)"
:key="feature.key"
class="role-feat"
:class="draft.feature_permissions[feature.key] ? 'is-on' : ''"
:title="featureHint(feature)"
>
<input
type="checkbox"
class="role-check role-check--sm appearance-none"
:checked="Boolean(draft.feature_permissions[feature.key])"
@change="toggleFeature(agent, feature.key, ($event.target as HTMLInputElement).checked)"
/>
<span class="truncate">{{ featureLabel(feature) }}</span>
</label>
<span class="perm-ellipsis">{{ featureLabel(feature) }}</span>
</ElCheckbox>
</div>
</div>
</section>
</div>
</div>
</section>
</div>
</div>
<div class="admin-modal-footer">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button type="button" class="btn-primary disabled:opacity-70" :disabled="isSaving" @click="emit('save')">
{{ isSaving ? t('admin.save') + '...' : t('admin.save') }}
</button>
</div>
</div>
</div>
</ElFormItem>
</ElForm>
<template #footer>
<ElButton :disabled="isSaving" @click="emit('close')">{{ t('admin.cancel') }}</ElButton>
<ElButton type="primary" :loading="isSaving" @click="emit('save')">
{{ t('admin.save') }}
</ElButton>
</template>
</ElDialog>
</template>
<style scoped>
.perm-role-form {
max-height: min(68vh, 640px);
overflow: auto;
}
.role-apps-item :deep(.el-form-item__label) {
width: 100%;
padding-right: 0;
}
.role-apps-item :deep(.el-form-item__content) {
display: flex;
flex-direction: column;
align-items: stretch;
}
.role-apps-label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
width: 100%;
}
.role-app-list {
width: 100%;
margin-top: 12px;
overflow: hidden;
border: 1px solid var(--border-default);
border-radius: 16px;
background: var(--bg-surface);
border: 1px solid var(--el-border-color);
border-radius: var(--el-border-radius-base);
background: var(--el-bg-color);
}
.role-app-empty {
margin: 0;
padding: 32px 16px;
text-align: center;
color: var(--el-text-color-secondary);
}
.role-app-group + .role-app-group {
border-top: 1px solid var(--border-subtle);
border-top: 1px solid var(--el-border-color-lighter);
}
.role-app-group-title {
margin: 0;
padding: 10px 14px 4px;
font-size: 11px;
font-weight: 600;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--text-muted);
background: var(--bg-surface-soft);
font-size: var(--el-font-size-extra-small);
font-weight: 400;
color: var(--el-text-color-secondary);
background: var(--el-fill-color-light);
}
.role-app-row {
padding: 9px 14px;
}
.role-app-row + .role-app-row {
border-top: 1px solid var(--border-subtle);
border-top: 1px solid var(--el-border-color-lighter);
}
.role-app-row.is-on {
background: color-mix(in srgb, var(--status-info-bg) 72%, var(--bg-surface));
background: var(--el-color-primary-light-9);
}
.role-app-row:hover {
background: var(--bg-surface-soft);
.role-app-main {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.role-app-row.is-on:hover {
background: color-mix(in srgb, var(--status-info-bg) 88%, var(--bg-surface));
.role-app-main :deep(.el-button) {
flex: none;
}
.role-agent-check {
min-width: 0;
flex: 1;
}
.role-agent-check :deep(.el-checkbox__label) {
min-width: 0;
}
.role-expand-icon {
margin-left: 2px;
transition: transform 0.2s;
}
.role-expand-icon.is-open {
transform: rotate(180deg);
}
.role-feat-row {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin: 8px 0 2px 28px;
}
.role-check {
-webkit-appearance: none;
appearance: none;
width: 16px;
height: 16px;
flex: none;
margin: 0;
border: 1.5px solid #64748b;
border-radius: 4px;
background-color: #fff;
background-image: none;
cursor: pointer;
}
.role-check:hover:not(:disabled) {
border-color: var(--status-info-fg);
}
.role-check:checked {
background: var(--status-info-fg);
border-color: var(--status-info-fg);
background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'><path fill='none' stroke='white' stroke-width='2.2' stroke-linecap='round' stroke-linejoin='round' d='M3.5 8.5l3 3 6-6'/></svg>");
background-repeat: no-repeat;
background-position: center;
background-size: 12px 12px;
}
.role-check:disabled {
cursor: default;
opacity: 0.55;
}
.role-check--sm {
width: 14px;
height: 14px;
}
.role-expand {
display: inline-flex;
align-items: center;
gap: 2px;
flex: none;
padding: 2px 6px;
border: 0;
border-radius: 6px;
background: transparent;
color: var(--text-muted);
font-size: 11px;
font-weight: 600;
cursor: pointer;
}
.role-expand:hover {
background: var(--bg-surface-strong);
color: var(--text-secondary);
}
.role-feat {
display: inline-flex;
align-items: center;
gap: 6px;
max-width: 100%;
padding: 3px 8px 3px 6px;
border: 1px solid var(--border-default);
padding: 2px 8px 2px 6px;
border: 1px solid var(--el-border-color);
border-radius: 999px;
background: var(--bg-surface);
color: var(--text-secondary);
font-size: 12px;
font-weight: 600;
line-height: 1.35;
cursor: pointer;
}
.role-feat:hover {
border-color: color-mix(in srgb, var(--status-info-fg) 35%, var(--border-default));
color: var(--status-info-fg);
background: var(--el-bg-color);
}
.role-feat.is-on {
border-color: color-mix(in srgb, var(--status-info-fg) 40%, transparent);
background: var(--status-info-bg);
color: var(--status-info-fg);
border-color: var(--el-color-primary-light-5);
background: var(--el-color-primary-light-9);
}
.role-feat :deep(.el-checkbox) {
height: auto;
margin-right: 0;
max-width: 100%;
}
.perm-ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>
@@ -1,14 +1,16 @@
/**
* features/admin/modules/permissions/components/RoleMembersConfirmDialog.vue
* 用途:选人确定后展示将改入/移出的人及来源角色,确认才写库。
* 依赖:permissionRole.types、vue-i18n。
* 逻辑:PermissionsPage 在 UserPickerDialog 之后打开;取消不改变成员。
* 依赖:permissionRole.types、vue-i18n、element-plus 对话框。
* 逻辑:PermissionsPage 在 UserPickerDialog 之后打开;取消不改变成员。样式跟权限页已引入的 Element 皮肤走。
*/
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElButton, ElDialog, ElTag } from 'element-plus';
import type { PermissionRoleMembersPreview, PermissionRolePerson } from '@/features/admin/types/permissionRole.types';
defineProps<{
const props = defineProps<{
visible: boolean;
preview: PermissionRoleMembersPreview | null;
isSaving: boolean;
@@ -21,68 +23,108 @@ const emit = defineEmits<{
const { t } = useI18n();
/**
* 把人员和来源角色拼成一行。
* @param person - 预览里的成员
* @returns 姓名 · 原角色
*/
function personLine(person: PermissionRolePerson): string {
const name = person.real_name || person.username;
const from = person.role_name || person.role;
return `${name} · ${from}`;
}
/**
* 是否有需要写库的增减。
* @returns 有改入或移出时为 true
*/
const hasChanges = computed(() => Boolean(props.preview && (props.preview.added.length || props.preview.removed.length)));
/**
* 点关闭或按 Esc 时通知页面放弃本次调整。
* @param open - Element 对话框的打开状态
*/
function onVisibleChange(open: boolean): void {
if (!open) emit('cancel');
}
</script>
<template>
<div v-if="visible && preview" class="admin-modal-overlay items-center">
<div class="admin-modal-panel max-w-lg max-h-[90vh] animate-fade-in-up">
<div class="px-8 py-6 border-b border-subtle">
<h3 class="text-lg font-bold text-primary">{{ t('admin.permRoles.confirm.title') }}</h3>
<p class="text-sm text-muted mt-1">
{{ t('admin.permRoles.confirm.subtitle', { name: preview.role_name }) }}
</p>
</div>
<div class="p-8 space-y-4 overflow-y-auto">
<div v-if="preview.added.length">
<div class="text-xs font-semibold uppercase tracking-wider text-muted mb-2">
{{ t('admin.permRoles.confirm.added', { count: preview.added.length }) }}
</div>
<ul class="space-y-1 text-sm text-primary">
<li v-for="person in preview.added" :key="person.id">
{{ personLine(person) }}
<span
v-if="preview.stolen.some((row) => row.id === person.id)"
class="ml-1 text-amber-700"
>
{{ t('admin.permRoles.confirm.stolenHint') }}
</span>
</li>
</ul>
<ElDialog
:model-value="visible && Boolean(preview)"
:title="t('admin.permRoles.confirm.title')"
width="480px"
align-center
append-to-body
:close-on-click-modal="false"
:close-on-press-escape="!isSaving"
:show-close="!isSaving"
@update:model-value="onVisibleChange"
>
<div v-if="preview" class="perm-member-body">
<p class="hx-element-hint">
{{ t('admin.permRoles.confirm.subtitle', { name: preview.role_name }) }}
</p>
<div v-if="preview.added.length" class="perm-member-block">
<div class="hx-element-hint">
{{ t('admin.permRoles.confirm.added', { count: preview.added.length }) }}
</div>
<div v-if="preview.removed.length">
<div class="text-xs font-semibold uppercase tracking-wider text-muted mb-2">
{{ t('admin.permRoles.confirm.removed', { count: preview.removed.length }) }}
</div>
<ul class="space-y-1 text-sm text-primary">
<li v-for="person in preview.removed" :key="person.id">{{ personLine(person) }}</li>
</ul>
<p class="text-xs text-muted mt-2">
{{ t('admin.permRoles.confirm.backToDefault') }}
</p>
<ul class="perm-member-list">
<li v-for="person in preview.added" :key="person.id">
{{ personLine(person) }}
<ElTag
v-if="preview.stolen.some((row) => row.id === person.id)"
class="perm-stolen-tag"
type="warning"
effect="light"
>
{{ t('admin.permRoles.confirm.stolenHint') }}
</ElTag>
</li>
</ul>
</div>
<div v-if="preview.removed.length" class="perm-member-block">
<div class="hx-element-hint">
{{ t('admin.permRoles.confirm.removed', { count: preview.removed.length }) }}
</div>
<p
v-if="!preview.added.length && !preview.removed.length"
class="text-sm text-muted"
>
{{ t('admin.permRoles.confirm.noChanges') }}
</p>
</div>
<div class="admin-modal-footer admin-modal-footer--muted px-8 py-6">
<button type="button" class="btn-ghost" @click="emit('cancel')">{{ t('admin.cancel') }}</button>
<button
type="button"
class="btn-primary disabled:opacity-50"
:disabled="isSaving || (!preview.added.length && !preview.removed.length)"
@click="emit('confirm')"
>
{{ isSaving ? t('admin.save') + '...' : t('admin.permRoles.confirm.apply') }}
</button>
<ul class="perm-member-list">
<li v-for="person in preview.removed" :key="person.id">{{ personLine(person) }}</li>
</ul>
<p class="hx-element-hint">{{ t('admin.permRoles.confirm.backToDefault') }}</p>
</div>
<p v-if="!preview.added.length && !preview.removed.length" class="hx-element-hint">
{{ t('admin.permRoles.confirm.noChanges') }}
</p>
</div>
</div>
<template #footer>
<ElButton :disabled="isSaving" @click="emit('cancel')">{{ t('admin.cancel') }}</ElButton>
<ElButton type="primary" :loading="isSaving" :disabled="!hasChanges" @click="emit('confirm')">
{{ t('admin.permRoles.confirm.apply') }}
</ElButton>
</template>
</ElDialog>
</template>
<style scoped>
.perm-member-body {
max-height: min(60vh, 420px);
overflow: auto;
}
.perm-member-block + .perm-member-block {
margin-top: 16px;
}
.perm-member-list {
margin: 8px 0 0;
padding-left: 1.25rem;
}
.perm-member-list li + li {
margin-top: 4px;
}
.perm-stolen-tag {
margin-left: 6px;
}
</style>
@@ -1,12 +1,14 @@
/**
* features/admin/modules/permissions/composables/usePermissionsAdmin.ts
* 用途:应用权限页:权限组 CRUD/选人确认,以及用户×应用核对矩阵。
* 依赖:admin.api、UserPickerDialog 数据、rolePackage.utils、useMessage。
* 依赖:admin.api、UserPickerDialog 数据、rolePackage.utils、useMessage、element-plus 的确认框。
* 逻辑:已种子权限组时矩阵只读、禁止按人打勾;未种子时保留历史批量勾选。
* 保存角色仅在应用/能力勾选变化时弹出「重写入口」确认。
* 保存仅在应用/能力勾选变化时用 ElMessageBox 确认;删除也先确认。
* 首屏用 isLoading 盖整张卡片,之后刷新列表只用 isListLoading。
*/
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessageBox } from 'element-plus';
import * as XLSX from 'xlsx';
import {
applyAdminPermissionRoleMembers,
@@ -52,6 +54,7 @@ export function usePermissionsAdmin() {
const permissionFilters = ref<PermissionFilters>(createEmptyPermissionFilters());
const selectedUserIds = ref<number[]>([]);
const isLoading = ref(true);
const isListLoading = ref(false);
const isSaving = ref(false);
const permissionPage = ref(1);
const permissionPageSize = ref(10);
@@ -69,7 +72,6 @@ export function usePermissionsAdmin() {
feature_permissions: {},
});
const editingRoleCode = ref('');
const showRoleSaveConfirm = ref(false);
const pickerRole = ref<PermissionRoleRow | null>(null);
const showPicker = ref(false);
@@ -178,6 +180,7 @@ export function usePermissionsAdmin() {
/**
* 并行拉取角色包、目录与核对矩阵数据。
* 核心逻辑:只在首屏把 isLoading 设为 true,让整张卡片转圈;列表刷新不走这里。
*/
const loadAll = async (): Promise<void> => {
isLoading.value = true;
@@ -186,6 +189,20 @@ export function usePermissionsAdmin() {
isLoading.value = false;
};
/**
* 列表已经画出来之后再刷新,只把加载态记在表格上。
* 核心逻辑:不改变 task 里的接口,只包一层 isListLoading。
* @param task - 现有的角色或用户列表刷新
*/
const refreshVisibleLists = async (task: () => Promise<unknown>): Promise<void> => {
isListLoading.value = true;
try {
await task();
} finally {
isListLoading.value = false;
}
};
const toggleUserSelection = (userId: number): void => {
const index = selectedUserIds.value.indexOf(userId);
if (index === -1) {
@@ -232,7 +249,7 @@ export function usePermissionsAdmin() {
agent_ids: batchPermissionForm.value.agent_ids,
action: batchPermissionForm.value.action,
});
await loadUsers();
await refreshVisibleLists(() => loadUsers());
showBatchPermissionModal.value = false;
selectedUserIds.value = [];
} catch (e) {
@@ -287,6 +304,11 @@ export function usePermissionsAdmin() {
XLSX.writeFile(wb, 'user_permissions.csv');
};
/**
* 导入权限 CSV。隐藏的文件框选中文件后由页面传入 change 事件。
* 核心逻辑:角色包启用时拒绝按人导入;成功后只刷新用户矩阵。
* @param event - 文件 input 的 change 事件
*/
const importPermissions = async (event: Event): Promise<void> => {
if (rolesConfigured.value) {
msg.warning(t('admin.permRoles.directGrantDisabled'));
@@ -302,7 +324,7 @@ export function usePermissionsAdmin() {
isSaving.value = true;
try {
await importAdminPermissions(formData);
await loadUsers();
await refreshVisibleLists(() => loadUsers());
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
@@ -344,9 +366,11 @@ export function usePermissionsAdmin() {
showRoleEditor.value = true;
};
/**
* 关闭权限组编辑框。
*/
const closeRoleEditor = (): void => {
showRoleEditor.value = false;
showRoleSaveConfirm.value = false;
};
/**
@@ -375,8 +399,9 @@ export function usePermissionsAdmin() {
/**
* 已有成员且应用/能力勾选变化时先确认;只改名称或说明直接保存。
* 核心逻辑:确认框取消时 MessageBox reject,这里直接返回,不调用保存。
*/
const requestSaveRole = (): void => {
const requestSaveRole = async (): Promise<void> => {
if (!roleDraft.value.name.trim()) {
msg.warning(t('admin.permRoles.msg.nameRequired'));
return;
@@ -391,12 +416,27 @@ export function usePermissionsAdmin() {
feature_permissions: (payload.feature_permissions as Record<string, boolean>) || {},
});
if (editingExisting.value && editingMemberCount.value > 0 && grantsChanged) {
showRoleSaveConfirm.value = true;
return;
try {
await ElMessageBox.confirm(
t('admin.permRoles.saveConfirm.message', { count: editingMemberCount.value }),
t('admin.permRoles.saveConfirm.title'),
{
type: 'warning',
confirmButtonText: t('admin.save'),
cancelButtonText: t('admin.cancel'),
},
);
} catch {
return;
}
}
void persistRole();
await persistRole();
};
/**
* 把当前草稿写入权限组。新建走创建接口,编辑走更新接口。
* 核心逻辑:校验已在 requestSaveRole 完成;成功后关弹窗并只刷新表格。
*/
const persistRole = async (): Promise<void> => {
isSaving.value = true;
try {
@@ -406,9 +446,8 @@ export function usePermissionsAdmin() {
} else {
await createAdminPermissionRole(payload);
}
showRoleSaveConfirm.value = false;
showRoleEditor.value = false;
await Promise.all([loadRoles(), loadUsers()]);
await refreshVisibleLists(() => Promise.all([loadRoles(), loadUsers()]));
msg.success(t('admin.permRoles.msg.saved'));
} catch (e) {
console.error(e);
@@ -419,17 +458,28 @@ export function usePermissionsAdmin() {
};
/**
* 删除无人使用的非内置权限组。
* 删除非内置、非管理员权限组。
* 核心逻辑:先用 Element 确认框询问,取消则不请求;确定后再调删除接口并刷新角色表。
* @param role - 当前行的权限组
*/
const removeRole = async (role: PermissionRoleRow): Promise<void> => {
if (role.is_system || role.is_platform_admin) {
msg.warning(t('admin.permRoles.msg.systemLocked'));
return;
}
try {
await ElMessageBox.confirm(role.name || role.code, t('common.deleteDialog.defaultTitle'), {
type: 'warning',
confirmButtonText: t('common.deleteDialog.confirm'),
cancelButtonText: t('common.deleteDialog.cancel'),
});
} catch {
return;
}
isSaving.value = true;
try {
await deleteAdminPermissionRole(role.code);
await loadRoles();
await refreshVisibleLists(() => loadRoles());
msg.success(t('admin.permRoles.msg.deleted'));
} catch (e) {
console.error(e);
@@ -488,7 +538,7 @@ export function usePermissionsAdmin() {
await applyAdminPermissionRoleMembers(pickerRole.value.code, pickerSelectedIds.value);
showMembersConfirm.value = false;
membersPreview.value = null;
await Promise.all([loadRoles(), loadUsers(), loadPickerUsers()]);
await refreshVisibleLists(() => Promise.all([loadRoles(), loadUsers(), loadPickerUsers()]));
msg.success(t('admin.permRoles.msg.membersUpdated'));
} catch (e) {
console.error(e);
@@ -515,6 +565,7 @@ export function usePermissionsAdmin() {
permissionTotalPages,
allUsersSelectedOnPage,
isLoading,
isListLoading,
isSaving,
activeTab,
rolesConfigured,
@@ -524,7 +575,6 @@ export function usePermissionsAdmin() {
editingExisting,
roleDraft,
editingMemberCount,
showRoleSaveConfirm,
pickerRole,
showPicker,
pickerSelectedIds,
@@ -1,17 +1,49 @@
/**
* features/admin/modules/platform-apps/PlatformAppsPage.vue
* 用途:平台应用说明(新手指南)管理——按 Agent 维护指南资料上传、启停与排序。
* 依赖:admin.api 指南 CRUD/上传、vue-i18n、lucide 图标。
* 逻辑:Admin 路由挂载;选择应用后拉取指南列表,弹窗内上传并保存元数据。
* 用途:平台应用说明(新手指南)管理。按应用筛选指南,维护上传、启停与排序。
* 依赖:AdminListPage、useElementProvider、element-plus、admin.api 指南 CRUD/上传、vue-i18n。
* 逻辑:Admin 路由挂载。选择应用后拉取指南列表。创建/编辑用对话框,删除用 Element 确认框。
*/
<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { computed, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Plus, Trash2, Edit2, Play, FileText, Image as ImageIcon } from 'lucide-vue-next';
import { listAdminAgents, listAdminAgentGuides, createAdminAgentGuide, updateAdminAgentGuide, deleteAdminAgentGuide, uploadAdminAgentGuideFile } from '@/features/admin/api/admin.api';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import { Plus } from '@element-plus/icons-vue';
import {
ElAlert,
ElButton,
ElConfigProvider,
ElDialog,
ElForm,
ElFormItem,
ElInput,
ElLoading,
ElMessageBox,
ElOption,
ElSelect,
ElTable,
ElTableColumn,
ElTag,
ElUpload,
} from 'element-plus';
import type { UploadRequestOptions } from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/features/admin/styles/element-trial.css';
import AdminListPage from '@/features/admin/components/AdminListPage.vue';
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
import {
createAdminAgentGuide,
deleteAdminAgentGuide,
listAdminAgentGuides,
listAdminAgents,
updateAdminAgentGuide,
uploadAdminAgentGuideFile,
} from '@/features/admin/api/admin.api';
const vLoading = ElLoading.directive;
const { t } = useI18n();
const { elementLocale } = useElementProvider();
const agents = ref<any[]>([]);
const selectedAgentId = ref<number | ''>('');
@@ -21,6 +53,7 @@ const isLoading = ref(false);
const isModalOpen = ref(false);
const isEditing = ref(false);
const editingId = ref<number | null>(null);
const isSaving = ref(false);
const form = ref({
file_name: '',
@@ -30,13 +63,11 @@ const form = ref({
file_size: 0,
remark: '',
sort_order: 0,
status: 1
status: 1,
});
const isUploading = ref(false);
const uploadError = ref('');
const deleteDialogOpen = ref(false);
const pendingDeleteGuideId = ref<number | null>(null);
const safetyVideoUsages = new Set([
'training_safety_video',
@@ -45,12 +76,25 @@ const safetyVideoUsages = new Set([
'training_safety_team_video',
]);
/**
* 判断用途是否必须对应视频文件。
* @param usage - 指南用途编码
* @returns 培训视频或安全视频为 true
*/
const isVideoUsage = (usage: string) => usage === 'training_video' || safetyVideoUsages.has(usage);
/**
* 判断用途是否必须对应 PDF 文件。
* @param usage - 指南用途编码
* @returns 培训试题或安全 PDF 为 true
*/
const isPdfUsage = (usage: string) => usage === 'training_exam_pdf' || usage === 'training_safety_pdf';
/**
* 把指南用途编码翻译成管理端可读名称。
* AI 触发时机:平台应用说明列表与弹窗下拉都依赖这层映射,新增资料用途时必须统一从这里出文案,避免表格和表单各自写死分叉。
* 核心逻辑:列表和弹窗下拉共用这一层,避免两处文案分叉。
* @param usage - 指南用途编码
* @returns 已有 i18n 文案
*/
const getGuideUsageLabel = (usage: string) => {
if (usage === 'training_video') return t('admin.platformApps.trainingVideo');
@@ -63,6 +107,25 @@ const getGuideUsageLabel = (usage: string) => {
return t('admin.platformApps.generalGuide');
};
/**
* 表格没有行时的说明。未选应用和该应用没有指南用不同文案。
* @returns 已有 i18n 空状态
*/
const tableEmptyText = computed(() => (
selectedAgentId.value
? t('admin.platformApps.emptyGuides')
: t('admin.platformApps.selectAgentFirst')
));
/**
* 当前选中应用的名称,供表格「Agent应用」列展示。
* @returns 应用名;未选中时为 -
*/
const currentAgentName = computed(() => {
const agent = agents.value.find(a => a.id === selectedAgentId.value);
return agent ? agent.name : '-';
});
/**
* 拉取 Agent 列表并默认选中第一项,再加载其指南。
*/
@@ -93,10 +156,19 @@ const fetchGuides = async () => {
}
};
const currentAgentName = computed(() => {
const agent = agents.value.find(a => a.id === selectedAgentId.value);
return agent ? agent.name : '-';
});
/**
* 切换应用筛选并重新拉取指南。
* 核心逻辑:ElSelect 不用空字符串当选项值,清空时写回 '',避免下拉显示默认「请选择」。
* @param value - 选中的应用 id;清空时为空
*/
const onAgentChange = (value: number | string | undefined) => {
if (value === undefined || value === '') {
selectedAgentId.value = '';
} else {
selectedAgentId.value = Number(value);
}
void fetchGuides();
};
onMounted(() => {
fetchAgents();
@@ -116,7 +188,7 @@ const openCreateModal = () => {
file_size: 0,
remark: '',
sort_order: 0,
status: 1
status: 1,
};
uploadError.value = '';
isModalOpen.value = true;
@@ -137,7 +209,7 @@ const openEditModal = (guide: any) => {
file_size: guide.file_size,
remark: guide.remark,
sort_order: guide.sort_order,
status: guide.status
status: guide.status,
};
uploadError.value = '';
isModalOpen.value = true;
@@ -145,15 +217,14 @@ const openEditModal = (guide: any) => {
/**
* 上传指南文件并回填 path/type/size;必要时校正 guide_usage 与文件类型一致性。
* @param event - input file change 事件
* @param file - 用户选择的指南文件
*/
const handleFileUpload = async (event: Event) => {
const file = (event.target as HTMLInputElement).files?.[0];
const handleFileUpload = async (file: File) => {
if (!file) return;
isUploading.value = true;
uploadError.value = '';
try {
const res = await uploadAdminAgentGuideFile(file);
form.value.file_path = res.file_path;
@@ -175,53 +246,67 @@ const handleFileUpload = async (event: Event) => {
}
};
/**
* 把 Element 上传组件选中的文件交给现有上传逻辑。
* 核心逻辑:不请求组件 action 地址,仍调用 uploadAdminAgentGuideFile。
* @param options - ElUpload 自定义请求参数,file 为原始文件
*/
const uploadGuideRequest = async (options: UploadRequestOptions) => {
await handleFileUpload(options.file);
};
/**
* 提交新建或更新指南元数据。
* 核心逻辑:编辑走 update,新建补上 agent_id 后走 create;请求体与原来一致。
*/
const submitForm = async () => {
if (!selectedAgentId.value || !form.value.file_path || !form.value.file_name) return;
if (isSaving.value || !selectedAgentId.value || !form.value.file_path || !form.value.file_name) return;
isSaving.value = true;
try {
if (isEditing.value && editingId.value) {
await updateAdminAgentGuide(editingId.value, form.value);
} else {
await createAdminAgentGuide({
...form.value,
agent_id: selectedAgentId.value
agent_id: selectedAgentId.value,
});
}
isModalOpen.value = false;
await fetchGuides();
} catch (error) {
console.error('Failed to save guide:', error);
} finally {
isSaving.value = false;
}
};
const deleteGuide = (id: number) => {
pendingDeleteGuideId.value = id;
deleteDialogOpen.value = true;
};
/**
* 确认后删除指南(由 DeleteConfirmDialog 的 @confirm 触发)。
* @param id - 指南主键,取自 pendingDeleteGuideId
* 删除指南。先弹出 Element 确认框,取消则不请求。
* 核心逻辑:正文用平台应用已有删除提示,标题和按钮用通用删除对话框文案。MessageBox 取消时 reject,这里直接返回。
* @param id - 指南主键
*/
const confirmDeleteGuide = async () => {
const id = pendingDeleteGuideId.value;
if (!id) return;
const deleteGuide = async (id: number) => {
try {
await ElMessageBox.confirm(t('admin.platformApps.confirmDelete'), t('common.deleteDialog.defaultTitle'), {
type: 'warning',
confirmButtonText: t('common.deleteDialog.confirm'),
cancelButtonText: t('common.deleteDialog.cancel'),
});
} catch {
return;
}
try {
await deleteAdminAgentGuide(id);
await fetchGuides();
} catch (error) {
console.error('Failed to delete guide:', error);
} finally {
pendingDeleteGuideId.value = null;
deleteDialogOpen.value = false;
}
};
/**
* 切换指南启停状态。
* 核心逻辑:仍调用 updateAdminAgentGuide,只提交翻转后的 status。
* @param guide - 列表行指南对象
*/
const toggleStatus = async (guide: any) => {
@@ -245,192 +330,196 @@ const formatSize = (bytes: number) => {
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
/**
* 按文件类型返回列表图标组件。
* @param type - 文件类型(video/pdf/其它)
*/
const getIcon = (type: string) => {
if (type === 'video') return Play;
if (type === 'pdf') return FileText;
return ImageIcon;
};
</script>
<template>
<div class="flex flex-col h-full gap-6">
<div class="flex items-center justify-between">
<div>
<h2 class="text-2xl font-bold tracking-tight text-default">
{{ t('admin.nav.platformApps') }}
</h2>
<p class="text-sm text-muted mt-1">
{{ t('admin.platformApps.subtitle') }}
</p>
</div>
</div>
<div class="surface-panel rounded-2xl p-6 shadow-sm border border-subtle flex-1 flex flex-col gap-6">
<div class="flex items-center justify-between">
<div class="flex items-center gap-4">
<label class="font-medium text-sm text-default">{{ t('admin.platformApps.selectAgent') }}</label>
<select v-model="selectedAgentId" class="input-field w-64" @change="fetchGuides">
<option v-for="agent in agents" :key="agent.id" :value="agent.id">
{{ agent.name }}
</option>
</select>
</div>
<button v-if="selectedAgentId" type="button" class="btn-primary" @click="openCreateModal">
<Plus class="w-5 h-5 mr-1" />
<span>{{ t('admin.platformApps.addGuide') }}</span>
</button>
</div>
<ElConfigProvider :locale="elementLocale">
<AdminListPage>
<template #title>
<h2 class="section-title">{{ t('admin.nav.platformApps') }}</h2>
<p class="section-desc mt-1">{{ t('admin.platformApps.subtitle') }}</p>
</template>
<template #actions>
<ElButton v-if="selectedAgentId" type="primary" :icon="Plus" @click="openCreateModal">
{{ t('admin.platformApps.addGuide') }}
</ElButton>
</template>
<template #filters>
<ElSelect
:model-value="selectedAgentId === '' ? undefined : selectedAgentId"
class="platform-apps-filter-agent"
:placeholder="t('admin.platformApps.selectAgent')"
@update:model-value="onAgentChange"
>
<ElOption v-for="agent in agents" :key="agent.id" :label="agent.name" :value="agent.id" />
</ElSelect>
</template>
<div v-if="isLoading" class="flex items-center justify-center py-10">
<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600" />
</div>
<ElTable
v-loading="isLoading"
class="hx-admin-table"
:data="guides"
row-key="id"
:empty-text="tableEmptyText"
>
<ElTableColumn prop="file_type" :label="t('admin.platformApps.colType')" width="100" />
<ElTableColumn :label="t('admin.platformApps.colFileName')" min-width="220">
<template #default="{ row }">
<div :title="row.file_name">{{ row.file_name }}</div>
<p v-if="row.remark" class="hx-element-hint platform-apps-remark" :title="row.remark">
{{ row.remark }}
</p>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.platformApps.guideUsage')" min-width="180">
<template #default="{ row }">
{{ getGuideUsageLabel(row.guide_usage || 'general') }}
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.platformApps.colAgent')" min-width="140">
<template #default>{{ currentAgentName }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.platformApps.colFileSize')" width="120">
<template #default="{ row }">{{ formatSize(row.file_size) }}</template>
</ElTableColumn>
<ElTableColumn prop="sort_order" :label="t('admin.platformApps.colSort')" width="90" />
<ElTableColumn :label="t('admin.platformApps.colStatus')" width="120">
<template #default="{ row }">
<ElTag
:type="row.status === 1 ? 'success' : 'info'"
effect="light"
class="platform-apps-status"
@click="toggleStatus(row)"
>
{{ row.status === 1 ? t('admin.platformApps.statusEnabled') : t('admin.platformApps.statusDisabled') }}
</ElTag>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.platformApps.colActions')" width="160" align="right">
<template #default="{ row }">
<ElButton link type="primary" @click="openEditModal(row)">
{{ t('common.edit') }}
</ElButton>
<ElButton link type="danger" @click="deleteGuide(row.id)">
{{ t('common.delete') }}
</ElButton>
</template>
</ElTableColumn>
</ElTable>
</AdminListPage>
<div v-else-if="!selectedAgentId" class="flex flex-col items-center justify-center py-20 text-muted">
{{ t('admin.platformApps.selectAgentFirst') }}
</div>
<div v-else-if="guides.length === 0" class="flex flex-col items-center justify-center py-20 text-muted">
{{ t('admin.platformApps.emptyGuides') }}
</div>
<div v-else class="overflow-x-auto rounded-xl border border-subtle">
<table class="w-full text-left text-sm whitespace-nowrap">
<thead class="bg-muted text-muted uppercase text-xs font-semibold tracking-wider border-b border-subtle">
<tr>
<th class="px-6 py-4">{{ t('admin.platformApps.colType') }}</th>
<th class="px-6 py-4">{{ t('admin.platformApps.colFileName') }}</th>
<th class="px-6 py-4">{{ t('admin.platformApps.guideUsage') }}</th>
<th class="px-6 py-4">{{ t('admin.platformApps.colAgent') }}</th>
<th class="px-6 py-4">{{ t('admin.platformApps.colFileSize') }}</th>
<th class="px-6 py-4">{{ t('admin.platformApps.colSort') }}</th>
<th class="px-6 py-4">{{ t('admin.platformApps.colStatus') }}</th>
<th class="px-6 py-4 text-right">{{ t('admin.platformApps.colActions') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-subtle">
<tr v-for="guide in guides" :key="guide.id" class="hover:bg-muted/50 transition-colors">
<td class="px-6 py-4">
<component :is="getIcon(guide.file_type)" class="w-5 h-5 text-muted" />
</td>
<td class="px-6 py-4">
<div class="font-medium text-default">{{ guide.file_name }}</div>
<div class="text-xs text-muted mt-1 truncate max-w-[200px]">{{ guide.remark }}</div>
</td>
<td class="px-6 py-4 text-muted">
<span>{{ getGuideUsageLabel(guide.guide_usage || 'general') }}</span>
</td>
<td class="px-6 py-4">
<span class="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-brand-50 text-brand-700 border border-brand-100">
{{ currentAgentName }}
</span>
</td>
<td class="px-6 py-4 text-muted">{{ formatSize(guide.file_size) }}</td>
<td class="px-6 py-4 text-muted">{{ guide.sort_order }}</td>
<td class="px-6 py-4">
<button
class="px-2 py-1 text-xs font-medium rounded-full transition-colors"
:class="guide.status === 1 ? 'bg-green-100 text-green-700 hover:bg-green-200' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'"
@click="toggleStatus(guide)"
>
{{ guide.status === 1 ? t('admin.platformApps.statusEnabled') : t('admin.platformApps.statusDisabled') }}
</button>
</td>
<td class="px-6 py-4 text-right space-x-2">
<button type="button" class="btn-icon-ds" @click="openEditModal(guide)" :title="t('common.edit')">
<Edit2 class="w-4 h-4" />
</button>
<button type="button" class="btn-icon-ds text-red-500 hover:bg-red-50" @click="deleteGuide(guide.id)" :title="t('common.delete')">
<Trash2 class="w-4 h-4" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- Modal -->
<div v-if="isModalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
<div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl w-full max-w-lg overflow-hidden flex flex-col max-h-[90vh]">
<div class="px-6 py-4 border-b border-subtle flex justify-between items-center">
<h3 class="text-lg font-bold text-default">{{ isEditing ? t('admin.platformApps.editGuide') : t('admin.platformApps.addGuide') }}</h3>
<button @click="isModalOpen = false" class="text-muted hover:text-default text-xl leading-none">&times;</button>
</div>
<div class="p-6 overflow-y-auto space-y-4">
<div v-if="!isEditing" class="space-y-2">
<label class="text-sm font-medium text-default">{{ t('admin.platformApps.uploadFile') }}</label>
<input
type="file"
accept="video/mp4,video/webm,application/pdf,image/png,image/jpeg"
class="w-full text-sm text-muted file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
@change="handleFileUpload"
/>
<div v-if="isUploading" class="text-sm text-blue-600 mt-2 flex items-center gap-2">
<div class="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"></div> {{ t('admin.platformApps.uploading') }}
</div>
<div v-if="uploadError" class="text-sm text-red-500 mt-2">{{ uploadError }}</div>
<div v-if="form.file_path && !isUploading" class="text-sm text-green-600 mt-2">{{ t('admin.platformApps.uploadReady') }}</div>
</div>
<div class="space-y-2">
<label class="text-sm font-medium text-default">{{ t('admin.platformApps.fileName') }}</label>
<input v-model="form.file_name" type="text" class="input-field w-full" :placeholder="t('admin.platformApps.fileNamePlaceholder')" />
</div>
<div class="space-y-2">
<label class="text-sm font-medium text-default">{{ t('admin.platformApps.remark') }}</label>
<textarea v-model="form.remark" class="input-field w-full h-20" :placeholder="t('admin.platformApps.remarkPlaceholder')"></textarea>
</div>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-2">
<label class="text-sm font-medium text-default">{{ t('admin.platformApps.guideUsage') }}</label>
<select v-model="form.guide_usage" class="input-field w-full">
<option value="general">{{ t('admin.platformApps.generalGuide') }}</option>
<option value="training_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingVideo') }}</option>
<option value="training_exam_pdf" :disabled="form.file_type !== 'pdf'">{{ t('admin.platformApps.trainingExamPdf') }}</option>
<option value="training_safety_company_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingSafetyCompanyVideo') }}</option>
<option value="training_safety_department_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingSafetyDepartmentVideo') }}</option>
<option value="training_safety_team_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingSafetyTeamVideo') }}</option>
<option value="training_safety_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingSafetyVideo') }}</option>
<option value="training_safety_pdf" :disabled="form.file_type !== 'pdf'">{{ t('admin.platformApps.trainingSafetyPdf') }}</option>
</select>
<p class="text-xs text-muted">{{ t('admin.platformApps.guideUsageHint') }}</p>
</div>
<div class="space-y-2">
<label class="text-sm font-medium text-default">{{ t('admin.platformApps.sortOrder') }}</label>
<input v-model.number="form.sort_order" type="number" class="input-field w-full" />
<p class="text-xs text-muted">{{ t('admin.platformApps.sortOrderHint') }}</p>
</div>
<div class="space-y-2">
<label class="text-sm font-medium text-default">{{ t('admin.platformApps.status') }}</label>
<select v-model="form.status" class="input-field w-full">
<option :value="1">{{ t('admin.platformApps.enable') }}</option>
<option :value="0">{{ t('admin.platformApps.disable') }}</option>
</select>
</div>
</div>
</div>
<div class="px-6 py-4 border-t border-subtle bg-muted flex justify-end gap-3">
<button type="button" class="btn-secondary" @click="isModalOpen = false">{{ t('admin.cancel') }}</button>
<button
type="button"
class="btn-primary"
@click="submitForm"
:disabled="isUploading || !form.file_path || !form.file_name"
<ElDialog
v-model="isModalOpen"
:title="isEditing ? t('admin.platformApps.editGuide') : t('admin.platformApps.addGuide')"
width="680px"
align-center
append-to-body
:close-on-click-modal="false"
:close-on-press-escape="!isSaving"
:show-close="!isSaving"
>
<ElForm label-position="top" :model="form" @submit.prevent="submitForm">
<ElFormItem v-if="!isEditing" :label="t('admin.platformApps.uploadFile')">
<ElUpload
action="#"
:http-request="uploadGuideRequest"
:show-file-list="false"
accept="video/mp4,video/webm,application/pdf,image/png,image/jpeg"
:disabled="isUploading"
>
{{ t('admin.platformApps.save') }}
</button>
<ElButton :loading="isUploading" :disabled="isUploading">
{{ t('admin.platformApps.uploadFile') }}
</ElButton>
</ElUpload>
<p v-if="isUploading" class="hx-element-hint">{{ t('admin.platformApps.uploading') }}</p>
<ElAlert
v-if="uploadError"
:title="uploadError"
type="error"
:closable="false"
show-icon
/>
<ElAlert
v-else-if="form.file_path && !isUploading"
:title="t('admin.platformApps.uploadReady')"
type="success"
:closable="false"
show-icon
/>
</ElFormItem>
<ElFormItem :label="t('admin.platformApps.fileName')">
<ElInput v-model="form.file_name" :placeholder="t('admin.platformApps.fileNamePlaceholder')" />
</ElFormItem>
<ElFormItem :label="t('admin.platformApps.remark')">
<ElInput
v-model="form.remark"
type="textarea"
:rows="4"
:placeholder="t('admin.platformApps.remarkPlaceholder')"
/>
</ElFormItem>
<div class="platform-apps-form-grid">
<ElFormItem :label="t('admin.platformApps.guideUsage')">
<ElSelect v-model="form.guide_usage">
<ElOption value="general" :label="t('admin.platformApps.generalGuide')" />
<ElOption value="training_video" :label="t('admin.platformApps.trainingVideo')" :disabled="form.file_type !== 'video'" />
<ElOption value="training_exam_pdf" :label="t('admin.platformApps.trainingExamPdf')" :disabled="form.file_type !== 'pdf'" />
<ElOption value="training_safety_company_video" :label="t('admin.platformApps.trainingSafetyCompanyVideo')" :disabled="form.file_type !== 'video'" />
<ElOption value="training_safety_department_video" :label="t('admin.platformApps.trainingSafetyDepartmentVideo')" :disabled="form.file_type !== 'video'" />
<ElOption value="training_safety_team_video" :label="t('admin.platformApps.trainingSafetyTeamVideo')" :disabled="form.file_type !== 'video'" />
<ElOption value="training_safety_video" :label="t('admin.platformApps.trainingSafetyVideo')" :disabled="form.file_type !== 'video'" />
<ElOption value="training_safety_pdf" :label="t('admin.platformApps.trainingSafetyPdf')" :disabled="form.file_type !== 'pdf'" />
</ElSelect>
<p class="hx-element-hint">{{ t('admin.platformApps.guideUsageHint') }}</p>
</ElFormItem>
<ElFormItem :label="t('admin.platformApps.sortOrder')">
<ElInput v-model.number="form.sort_order" type="number" />
<p class="hx-element-hint">{{ t('admin.platformApps.sortOrderHint') }}</p>
</ElFormItem>
<ElFormItem :label="t('admin.platformApps.status')">
<ElSelect v-model="form.status">
<ElOption :value="1" :label="t('admin.platformApps.enable')" />
<ElOption :value="0" :label="t('admin.platformApps.disable')" />
</ElSelect>
</ElFormItem>
</div>
</div>
</div>
<DeleteConfirmDialog v-model="deleteDialogOpen" title="{{ t('admin.platformApps.deleteGuide') }}" message="{{ t('admin.platformApps.confirmDelete') }}" confirm-tone="danger" @confirm="confirmDeleteGuide" />
</div>
</ElForm>
<template #footer>
<ElButton :disabled="isSaving" @click="isModalOpen = false">{{ t('admin.cancel') }}</ElButton>
<ElButton
type="primary"
:loading="isSaving"
:disabled="isUploading || !form.file_path || !form.file_name"
@click="submitForm"
>
{{ t('admin.platformApps.save') }}
</ElButton>
</template>
</ElDialog>
</ElConfigProvider>
</template>
<style scoped>
:deep(.platform-apps-filter-agent) {
width: 16rem;
}
.platform-apps-form-grid {
display: grid;
grid-template-columns: 1fr 1fr;
column-gap: 16px;
}
.platform-apps-remark {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.platform-apps-status {
cursor: pointer;
}
</style>
File diff suppressed because it is too large. Load diff
@@ -1,13 +1,33 @@
/**
* features/admin/modules/procurement-contract/components/ContractRiskRulesPanel.vue
* 用途:采购合同风险红线规则列表与新增/编辑(含迁移种子默认规则)。
* 依赖:procurement-contract.api、DeleteConfirmDialog、useMessage、vue-i18n。
* 逻辑:由 ProcurementContractPage「风险规则」Tab 挂载;CRUD 走 Admin rules API。
* 用途:采购合同风险规则表格、编辑对话框和删除确认。
* 依赖:procurement-contract.api、element-plus、useMessage、vue-i18n。
* 逻辑:由 ProcurementContractPage「风险规则」页签放入 AdminListPage 的表格区。
* 进入页签或切换状态筛选时拉列表;「新增规则」在页面页头。本组件不再套卡片。
* 样式随页面已引入的 Element 皮肤。
*/
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { CircleHelp, Plus, ShieldAlert, ShieldCheck, SlidersHorizontal } from 'lucide-vue-next';
import { QuestionFilled } from '@element-plus/icons-vue';
import {
ElAlert,
ElButton,
ElDialog,
ElForm,
ElFormItem,
ElIcon,
ElInput,
ElInputNumber,
ElLoading,
ElMessageBox,
ElOption,
ElSelect,
ElTable,
ElTableColumn,
ElTag,
ElTooltip,
} from 'element-plus';
import {
createAdminContractRiskRule,
deleteAdminContractRiskRule,
@@ -15,16 +35,23 @@ import {
updateAdminContractRiskRule,
type ContractRiskRuleRow,
} from '@/features/admin/api/procurement-contract.api';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import { useMessage } from '@/shared/composables/useMessage';
const props = withDefaults(defineProps<{
/** 状态筛选。空字符串表示全部;由页面筛选条写入。 */
statusFilter?: string;
}>(), {
statusFilter: '',
});
const vLoading = ElLoading.directive;
const { t } = useI18n();
const msg = useMessage();
const loading = ref(false);
const saving = ref(false);
const rules = ref<ContractRiskRuleRow[]>([]);
const filterStatus = ref('');
const showForm = ref(false);
const editing = ref<ContractRiskRuleRow | null>(null);
@@ -51,10 +78,6 @@ const clauseCategories = [
'other',
] as const;
const showDeleteConfirm = ref(false);
const pendingDelete = ref<ContractRiskRuleRow | null>(null);
const deleting = ref(false);
const isEditMode = computed(() => Boolean(editing.value));
const formTitleText = computed(() =>
isEditMode.value
@@ -69,49 +92,28 @@ const keywordLogicHint = computed(() =>
? t('admin.procurementContract.keywordPresentLogicHint')
: t('admin.procurementContract.keywordMissingLogicHint'),
);
/**
* 汇总当前列表里的规则数量,供页面筛选行右侧展示。
* 核心逻辑:数量跟当前筛选结果走,不另请求统计接口。
*/
const ruleStats = computed(() => ({
total: rules.value.length,
enabled: rules.value.filter((rule) => rule.status === 'enabled').length,
highRisk: rules.value.filter((rule) => rule.risk_level === 'high').length,
}));
/**
* 生成风险规则统计卡片,帮助管理员先扫状态再进入列表维护。
*/
const ruleSummaryCards = computed(() => [
{
key: 'total',
label: t('admin.procurementContract.ruleStatTotal'),
value: ruleStats.value.total,
icon: SlidersHorizontal,
className: 'border-slate-200 bg-white text-slate-600',
},
{
key: 'enabled',
label: t('admin.procurementContract.ruleStatEnabled'),
value: ruleStats.value.enabled,
icon: ShieldCheck,
className: 'border-emerald-100 bg-emerald-50/80 text-emerald-700',
},
{
key: 'highRisk',
label: t('admin.procurementContract.ruleStatHighRisk'),
value: ruleStats.value.highRisk,
icon: ShieldAlert,
className: 'border-rose-100 bg-rose-50/80 text-rose-700',
},
]);
/**
* 加载风险规则列表。
* @param options.silent - 为 true 时不切换 loading,避免启停时整表闪烁
* 核心逻辑:状态筛选取页面传入的空字符串时不传给接口,表示全部。
* @param options.silent - 为 true 时不切换 loading,避免保存后整表闪烁
*/
async function loadRules(options?: { silent?: boolean }): Promise<void> {
const silent = Boolean(options?.silent);
if (!silent) loading.value = true;
try {
rules.value = await listAdminContractRiskRules({
status: filterStatus.value || undefined,
status: props.statusFilter || undefined,
});
} catch (e: unknown) {
console.error(e);
@@ -121,16 +123,13 @@ async function loadRules(options?: { silent?: boolean }): Promise<void> {
}
}
/**
* 响应筛选条件变更并刷新规则列表。
*/
async function onFilterStatusChange(): Promise<void> {
await loadRules();
}
onMounted(() => {
void loadRules();
});
watch(
() => props.statusFilter,
() => {
void loadRules();
},
{ immediate: true },
);
/**
* 重置规则表单为新建默认值。
@@ -150,7 +149,7 @@ function resetForm(): void {
}
/**
* 打开新建规则弹窗。
* 打开新建规则对话框。
*/
function openCreate(): void {
resetForm();
@@ -158,7 +157,8 @@ function openCreate(): void {
}
/**
* 打开编辑规则弹窗(种子规则也可改,code 只读)。
* 打开编辑规则对话框。内置规则的分类、关键词和触发条件不可改。
* @param row - 当前规则行
*/
function openEdit(row: ContractRiskRuleRow): void {
editing.value = row;
@@ -177,17 +177,25 @@ function openEdit(row: ContractRiskRuleRow): void {
}
/**
* 关闭规则表单。
* 关闭规则对话框。编辑对象等到关闭动画结束后再清,避免标题闪一下。
*/
function closeForm(): void {
showForm.value = false;
}
/**
* 对话框关闭后丢掉正在编辑的规则。
*/
function onFormClosed(): void {
editing.value = null;
}
/**
* 提交新建或更新规则。
* 核心逻辑:关键词按中英文逗号拆开;合同类型固定为通用采购,与现有保存接口一致。
*/
async function submitForm(): Promise<void> {
if (saving.value) return;
if (!formTitle.value.trim() || !formCategory.value.trim()) {
msg.error(t('admin.procurementContract.ruleRequiredFields'));
return;
@@ -240,8 +248,9 @@ async function submitForm(): Promise<void> {
}
/**
* 切换规则启停(种子与自定义规则均可)。
* 核心逻辑:先乐观更新本地行,成功后再静默对齐服务端;失败则回滚。
* 切换规则启停。
* 核心逻辑:先改本地行,成功后再对齐服务端;当前筛选对不上时把该行移出列表。失败则回滚。
* @param row - 当前规则行
*/
async function toggleStatus(row: ContractRiskRuleRow): Promise<void> {
const prev = row.status;
@@ -250,9 +259,8 @@ async function toggleStatus(row: ContractRiskRuleRow): Promise<void> {
try {
const updated = await updateAdminContractRiskRule(row.id, { status: next });
Object.assign(row, updated);
// 当前筛选为「启用/停用」时,状态变更后该项应离开列表
if (filterStatus.value && filterStatus.value !== next) {
rules.value = rules.value.filter((r) => r.id !== row.id);
if (props.statusFilter && props.statusFilter !== next) {
rules.value = rules.value.filter((item) => item.id !== row.id);
}
} catch (e: unknown) {
row.status = prev;
@@ -261,41 +269,34 @@ async function toggleStatus(row: ContractRiskRuleRow): Promise<void> {
}
/**
* 打开删除确认。
* 确认后删除规则。取消确认框时不请求接口。
* @param row - 待删除的规则
*/
function openDelete(row: ContractRiskRuleRow): void {
pendingDelete.value = row;
showDeleteConfirm.value = true;
}
/**
* 关闭删除确认。
*/
function closeDelete(): void {
showDeleteConfirm.value = false;
pendingDelete.value = null;
}
/**
* 确认删除规则。
*/
async function confirmDelete(): Promise<void> {
const row = pendingDelete.value;
if (!row) return;
deleting.value = true;
async function deleteRule(row: ContractRiskRuleRow): Promise<void> {
try {
await ElMessageBox.confirm(
t('admin.procurementContract.confirmDeleteRule', { title: row.title }),
t('common.deleteDialog.defaultTitle'),
{
type: 'warning',
confirmButtonText: t('common.deleteDialog.confirm'),
cancelButtonText: t('common.deleteDialog.cancel'),
},
);
} catch {
return;
}
try {
await deleteAdminContractRiskRule(row.id);
closeDelete();
rules.value = rules.value.filter((r) => r.id !== row.id);
rules.value = rules.value.filter((item) => item.id !== row.id);
} catch (e: unknown) {
msg.error(e instanceof Error ? e.message : t('admin.procurementContract.actionFailed'));
} finally {
deleting.value = false;
}
}
/**
* 风险等级文案。
* @param level - high / medium / low
*/
function riskLabel(level: string): string {
if (level === 'high') return t('admin.procurementContract.riskHigh');
@@ -304,8 +305,19 @@ function riskLabel(level: string): string {
return level;
}
/**
* 风险等级对应的标签色。
* @param level - high / medium / low
*/
function riskTagType(level: string): 'danger' | 'warning' | 'info' {
if (level === 'high') return 'danger';
if (level === 'medium') return 'warning';
return 'info';
}
/**
* 触发类型文案。
* @param type - keyword_present 或缺失触发
*/
function triggerLabel(type: string): string {
if (type === 'keyword_present') return t('admin.procurementContract.triggerPresent');
@@ -313,7 +325,8 @@ function triggerLabel(type: string): string {
}
/**
* 状态文案。
* 启停文案。
* @param status - enabled / disabled
*/
function statusLabel(status: string): string {
if (status === 'enabled') return t('admin.procurementContract.enable');
@@ -322,8 +335,16 @@ function statusLabel(status: string): string {
}
/**
* 规则关键词展示文本。
* @param row - 风险规则行;关键词为空时返回短横线占位,避免表格空洞。
* 启停对应的标签色。
* @param status - enabled / disabled
*/
function statusTagType(status: string): 'success' | 'info' {
return status === 'enabled' ? 'success' : 'info';
}
/**
* 把规则关键词拼成一行展示。没有关键词时用短横线占位。
* @param row - 风险规则行
*/
function keywordText(row: ContractRiskRuleRow): string {
const keywords = row.keywords || [];
@@ -331,10 +352,9 @@ function keywordText(row: ContractRiskRuleRow): string {
}
/**
* 将内部条款分类编码转换为与规则弹窗一致的可读名称。
* 核心逻辑:规则仍保存稳定编码,列表仅负责展示本地化文案。
* @param category - 后端返回的条款分类编码。
* @returns 用户可读的分类名称;历史未知编码保持原样,避免丢失信息。
* 将条款分类编码转成与规则对话框一致的名称。
* 核心逻辑:规则仍保存稳定编码,列表只展示已有文案;未知编码保持原样。
* @param category - 后端返回的条款分类编码
*/
function categoryLabel(category: string): string {
const key = `admin.procurementContract.category_${category}`;
@@ -342,249 +362,204 @@ function categoryLabel(category: string): string {
return translated === key ? category : translated;
}
defineExpose({ loadRules, openCreate });
defineExpose({ loadRules, openCreate, ruleStats });
</script>
<template>
<div class="space-y-5">
<div class="grid gap-3 md:grid-cols-3">
<div
v-for="card in ruleSummaryCards"
:key="card.key"
class="rounded-xl border px-4 py-3 shadow-sm"
:class="card.className"
>
<div class="flex items-center justify-between gap-3">
<div>
<div class="text-xs font-medium text-muted">{{ card.label }}</div>
<div class="mt-1 text-2xl font-semibold text-primary">{{ card.value }}</div>
</div>
<span class="inline-flex h-9 w-9 items-center justify-center rounded-lg bg-white/80 shadow-sm">
<component :is="card.icon" class="h-4 w-4" />
</span>
<ElTable
v-loading="loading"
class="hx-admin-table"
:data="rules"
row-key="id"
:empty-text="loading ? t('admin.procurementContract.loading') : t('admin.procurementContract.emptyRules')"
>
<ElTableColumn :label="t('admin.procurementContract.colRuleTitle')" min-width="180">
<template #default="{ row }">{{ row.title }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.procurementContract.colCategory')" min-width="120">
<template #default="{ row }">
<ElTag effect="light">{{ categoryLabel(row.clause_category) }}</ElTag>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.procurementContract.colKeywords')" min-width="220">
<template #default="{ row }">
<div class="rule-keywords" :title="keywordText(row as ContractRiskRuleRow)">
{{ keywordText(row as ContractRiskRuleRow) }}
</div>
</div>
</div>
<div class="flex flex-col gap-3 rounded-xl border border-subtle bg-white px-4 py-3 shadow-sm sm:flex-row sm:items-center sm:justify-between">
<div class="flex items-center gap-3">
<label class="flex shrink-0 items-center gap-2 text-sm font-medium text-secondary">
<span>{{ t('admin.procurementContract.colStatus') }}</span>
<select
v-model="filterStatus"
class="input-field h-10 w-48 min-w-48 py-0 text-sm"
@change="onFilterStatusChange"
>
<option value="">{{ t('admin.procurementContract.all') }}</option>
<option value="enabled">{{ t('admin.procurementContract.enable') }}</option>
<option value="disabled">{{ t('admin.procurementContract.disable') }}</option>
</select>
</label>
</div>
<button type="button" class="btn-primary inline-flex h-10 items-center gap-2 px-4 shadow-sm" @click="openCreate">
<Plus class="h-4 w-4" />
{{ t('admin.procurementContract.addRule') }}
</button>
</div>
<div class="overflow-hidden rounded-xl border border-subtle bg-white shadow-sm">
<div class="overflow-auto">
<table class="w-full min-w-[1030px] whitespace-nowrap text-sm">
<thead class="bg-slate-50/80 text-xs font-semibold text-muted">
<tr>
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colRuleTitle') }}</th>
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colCategory') }}</th>
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colKeywords') }}</th>
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colTrigger') }}</th>
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colRisk') }}</th>
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colStatus') }}</th>
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colSort') }}</th>
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colActions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="loading">
<td colspan="8" class="px-4 py-8 text-center text-muted">
{{ t('admin.procurementContract.loading') }}
</td>
</tr>
<tr v-else-if="!rules.length">
<td colspan="8" class="px-4 py-8 text-center text-muted">
{{ t('admin.procurementContract.emptyRules') }}
</td>
</tr>
<tr v-for="row in rules" :key="row.id" class="border-t border-subtle transition-colors hover:bg-slate-50/70">
<td class="px-5 py-4 align-top">
<div class="font-semibold text-primary">{{ row.title }}</div>
</td>
<td class="px-5 py-4 align-top">
<span class="inline-flex rounded-md border border-slate-200 bg-slate-50 px-2 py-1 text-xs font-medium text-slate-700">
{{ categoryLabel(row.clause_category) }}
</span>
</td>
<td class="max-w-[260px] px-5 py-4 align-top text-xs text-muted" :title="keywordText(row)">
<div class="line-clamp-2 whitespace-normal leading-5">{{ keywordText(row) }}</div>
</td>
<td class="px-5 py-4 align-top text-secondary">{{ triggerLabel(row.trigger_type) }}</td>
<td class="px-5 py-4 align-top">
<span
class="inline-flex rounded-full px-2.5 py-1 text-xs font-semibold"
:class="{
'bg-rose-50 text-rose-700': row.risk_level === 'high',
'bg-amber-50 text-amber-800': row.risk_level === 'medium',
'bg-sky-50 text-sky-700': row.risk_level === 'low',
}"
>
{{ riskLabel(row.risk_level) }}
</span>
</td>
<td class="px-5 py-4 align-top">
<span
class="inline-flex rounded-full px-2.5 py-1 text-xs font-semibold"
:class="row.status === 'enabled' ? 'bg-emerald-50 text-emerald-700' : 'bg-slate-100 text-slate-600'"
>
{{ statusLabel(row.status) }}
</span>
</td>
<td class="px-5 py-4 align-top font-mono text-xs text-muted">{{ row.sort_order }}</td>
<td class="px-5 py-4 align-top">
<div class="flex items-center gap-2">
<button
type="button"
class="inline-flex h-8 items-center rounded-lg border border-[#d8e0ec] bg-white px-3 text-xs font-semibold text-[#2f80d1] transition-colors hover:border-[#2f80d1] hover:bg-[#eaf4ff]"
@click="openEdit(row)"
>
{{ t('admin.edit') }}
</button>
<button
type="button"
class="inline-flex h-8 items-center rounded-lg border border-[#d8e0ec] bg-white px-3 text-xs font-semibold text-[#172033] transition-colors hover:border-[#667792] hover:bg-slate-50"
@click="toggleStatus(row)"
>
{{ row.status === 'enabled' ? t('admin.procurementContract.disable') : t('admin.procurementContract.enable') }}
</button>
<button
type="button"
class="inline-flex h-8 items-center rounded-lg border border-rose-200 bg-white px-3 text-xs font-semibold text-rose-600 transition-colors hover:border-rose-300 hover:bg-rose-50"
@click="openDelete(row)"
>
{{ t('admin.delete') }}
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div
v-if="showForm"
class="admin-modal-overlay animate-fade-in"
@click.self="closeForm"
>
<div class="admin-modal-panel max-w-2xl max-h-[92vh] my-auto scale-100" role="dialog" aria-modal="true">
<div class="admin-modal-header flex items-center justify-between gap-3">
<h3 class="section-title">{{ formTitleText }}</h3>
<button type="button" class="btn-ghost h-9 px-3 text-sm" @click="closeForm">
{{ t('admin.close') }}
</button>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.procurementContract.colTrigger')" min-width="160">
<template #default="{ row }">{{ triggerLabel(row.trigger_type) }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.procurementContract.colRisk')" width="110">
<template #default="{ row }">
<ElTag :type="riskTagType(row.risk_level)" effect="light">{{ riskLabel(row.risk_level) }}</ElTag>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.procurementContract.colStatus')" width="100">
<template #default="{ row }">
<ElTag :type="statusTagType(row.status)" effect="light">{{ statusLabel(row.status) }}</ElTag>
</template>
</ElTableColumn>
<ElTableColumn prop="sort_order" :label="t('admin.procurementContract.colSort')" width="90" />
<ElTableColumn :label="t('admin.procurementContract.colActions')" width="220" align="right">
<template #default="{ row }">
<div class="contract-row-actions">
<ElButton link type="primary" @click="openEdit(row as ContractRiskRuleRow)">
{{ t('admin.edit') }}
</ElButton>
<ElButton link @click="toggleStatus(row as ContractRiskRuleRow)">
{{ row.status === 'enabled' ? t('admin.procurementContract.disable') : t('admin.procurementContract.enable') }}
</ElButton>
<ElButton link type="danger" @click="deleteRule(row as ContractRiskRuleRow)">
{{ t('admin.delete') }}
</ElButton>
</div>
<div class="admin-modal-body min-h-0 !space-y-0 grid grid-cols-1 gap-4 sm:grid-cols-2 items-start">
<label class="flex flex-col gap-1.5 text-sm">
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colRuleTitle') }}</span>
<input v-model="formTitle" type="text" class="input-field w-full" />
</label>
<label class="flex flex-col gap-1.5 text-sm">
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colCategory') }}</span>
<select v-model="formCategory" class="input-field w-full" :disabled="isBuiltinRule">
<option v-for="category in clauseCategories" :key="category" :value="category">
{{ t(`admin.procurementContract.category_${category}`) }}
</option>
</select>
</label>
<label class="flex flex-col gap-1.5 text-sm sm:col-span-2">
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colKeywords') }}</span>
<input
v-model="formKeywords"
type="text"
class="input-field w-full"
:disabled="isBuiltinRule"
:placeholder="t('admin.procurementContract.ruleKeywordsPlaceholder')"
</template>
</ElTableColumn>
</ElTable>
<ElDialog
v-model="showForm"
:title="formTitleText"
width="680px"
align-center
append-to-body
destroy-on-close
:close-on-click-modal="false"
:close-on-press-escape="!saving"
:show-close="!saving"
@closed="onFormClosed"
>
<ElForm label-position="top" @submit.prevent="submitForm">
<div class="contract-form-grid">
<ElFormItem :label="t('admin.procurementContract.colRuleTitle')" required>
<ElInput v-model="formTitle" />
</ElFormItem>
<ElFormItem :label="t('admin.procurementContract.colCategory')" required>
<ElSelect v-model="formCategory" class="contract-field" :disabled="isBuiltinRule">
<ElOption
v-for="category in clauseCategories"
:key="category"
:label="t(`admin.procurementContract.category_${category}`)"
:value="category"
/>
<span class="text-xs leading-5 text-muted">{{ keywordLogicHint }}</span>
</label>
<label class="flex flex-col gap-1.5 text-sm">
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colTrigger') }}</span>
<select v-model="formTriggerType" class="input-field w-full" :disabled="isBuiltinRule">
<option value="keyword_missing">{{ t('admin.procurementContract.triggerMissing') }}</option>
<option value="keyword_present">{{ t('admin.procurementContract.triggerPresent') }}</option>
</select>
<span v-if="isBuiltinRule" class="text-xs leading-5 text-amber-700">{{ t('admin.procurementContract.builtinRuleLogicHint') }}</span>
</label>
<label class="flex flex-col gap-1.5 text-sm">
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colRisk') }}</span>
<select v-model="formRiskLevel" class="input-field w-full">
<option value="high">{{ t('admin.procurementContract.riskHigh') }}</option>
<option value="medium">{{ t('admin.procurementContract.riskMedium') }}</option>
<option value="low">{{ t('admin.procurementContract.riskLow') }}</option>
</select>
</label>
<label class="flex flex-col gap-1.5 text-sm">
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colStatus') }}</span>
<select v-model="formStatus" class="input-field w-full">
<option value="enabled">{{ t('admin.procurementContract.enable') }}</option>
<option value="disabled">{{ t('admin.procurementContract.disable') }}</option>
</select>
</label>
<div class="flex flex-col gap-1.5 text-sm">
<div class="flex items-center gap-1.5">
<label for="risk-rule-sort-order" class="font-medium text-secondary">{{ t('admin.procurementContract.colSort') }}</label>
<span class="group relative inline-flex">
<button
type="button"
class="inline-flex text-muted transition-colors hover:text-brand-600 focus:outline-none focus-visible:text-brand-600"
</ElSelect>
</ElFormItem>
<ElFormItem class="contract-form-span" :label="t('admin.procurementContract.colKeywords')" required>
<ElInput
v-model="formKeywords"
:disabled="isBuiltinRule"
:placeholder="t('admin.procurementContract.ruleKeywordsPlaceholder')"
/>
<p class="hx-element-hint">{{ keywordLogicHint }}</p>
</ElFormItem>
<ElFormItem :label="t('admin.procurementContract.colTrigger')">
<ElSelect v-model="formTriggerType" class="contract-field" :disabled="isBuiltinRule">
<ElOption :label="t('admin.procurementContract.triggerMissing')" value="keyword_missing" />
<ElOption :label="t('admin.procurementContract.triggerPresent')" value="keyword_present" />
</ElSelect>
<ElAlert
v-if="isBuiltinRule"
type="warning"
:closable="false"
:title="t('admin.procurementContract.builtinRuleLogicHint')"
/>
</ElFormItem>
<ElFormItem :label="t('admin.procurementContract.colRisk')">
<ElSelect v-model="formRiskLevel" class="contract-field">
<ElOption :label="t('admin.procurementContract.riskHigh')" value="high" />
<ElOption :label="t('admin.procurementContract.riskMedium')" value="medium" />
<ElOption :label="t('admin.procurementContract.riskLow')" value="low" />
</ElSelect>
</ElFormItem>
<ElFormItem :label="t('admin.procurementContract.colStatus')">
<ElSelect v-model="formStatus" class="contract-field">
<ElOption :label="t('admin.procurementContract.enable')" value="enabled" />
<ElOption :label="t('admin.procurementContract.disable')" value="disabled" />
</ElSelect>
</ElFormItem>
<ElFormItem>
<template #label>
<span class="contract-sort-label">
{{ t('admin.procurementContract.colSort') }}
<ElTooltip :content="t('admin.procurementContract.ruleSortHint')" placement="top">
<ElIcon
class="contract-help-icon"
tabindex="0"
:aria-label="t('admin.procurementContract.ruleSortHint')"
>
<CircleHelp class="h-4 w-4" />
</button>
<span class="pointer-events-none absolute bottom-full left-1/2 z-10 mb-2 hidden w-60 -translate-x-1/2 rounded-lg border border-subtle bg-white px-3 py-2 text-xs font-normal leading-5 text-secondary shadow-lg group-hover:block group-focus-within:block">
{{ t('admin.procurementContract.ruleSortHint') }}
</span>
</span>
</div>
<input id="risk-rule-sort-order" v-model.number="formSortOrder" type="number" class="input-field w-full" min="0" />
</div>
<label class="flex flex-col gap-1.5 text-sm sm:col-span-2">
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colRiskHint') }}</span>
<textarea v-model="formRiskHint" rows="2" class="input-field w-full resize-y" />
</label>
<label class="flex flex-col gap-1.5 text-sm sm:col-span-2">
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colSuggestion') }}</span>
<textarea v-model="formSuggestion" rows="2" class="input-field w-full resize-y" />
</label>
<label class="flex flex-col gap-1.5 text-sm sm:col-span-2">
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colNegotiation') }}</span>
<textarea v-model="formNegotiation" rows="2" class="input-field w-full resize-y" />
</label>
</div>
<div class="admin-modal-footer flex justify-end gap-2">
<button type="button" class="btn-ghost h-10 px-4" @click="closeForm">
{{ t('admin.cancel') }}
</button>
<button type="button" class="btn-primary h-10 px-4 disabled:opacity-70" :disabled="saving" @click="submitForm">
{{ saving ? t('admin.procurementContract.saving') : t('admin.procurementContract.saveChanges') }}
</button>
</div>
<QuestionFilled />
</ElIcon>
</ElTooltip>
</span>
</template>
<ElInputNumber
v-model="formSortOrder"
class="contract-field"
:min="0"
:step="1"
controls-position="right"
/>
</ElFormItem>
<ElFormItem class="contract-form-span" :label="t('admin.procurementContract.colRiskHint')" required>
<ElInput v-model="formRiskHint" type="textarea" :rows="4" />
</ElFormItem>
<ElFormItem class="contract-form-span" :label="t('admin.procurementContract.colSuggestion')" required>
<ElInput v-model="formSuggestion" type="textarea" :rows="4" />
</ElFormItem>
<ElFormItem class="contract-form-span" :label="t('admin.procurementContract.colNegotiation')">
<ElInput v-model="formNegotiation" type="textarea" :rows="4" />
</ElFormItem>
</div>
</div>
<DeleteConfirmDialog
v-model="showDeleteConfirm"
:message="t('admin.procurementContract.confirmDeleteRule', { title: pendingDelete?.title || '' })"
:confirm-loading="deleting"
@confirm="confirmDelete"
@cancel="closeDelete"
/>
</div>
</ElForm>
<template #footer>
<ElButton :disabled="saving" @click="closeForm">{{ t('admin.cancel') }}</ElButton>
<ElButton type="primary" :loading="saving" @click="submitForm">
{{ t('admin.procurementContract.saveChanges') }}
</ElButton>
</template>
</ElDialog>
</template>
<style scoped>
.contract-row-actions {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 2px 8px;
}
.rule-keywords {
display: -webkit-box;
overflow: hidden;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
white-space: normal;
line-height: 1.4;
}
.contract-form-grid {
display: grid;
grid-template-columns: 1fr 1fr;
column-gap: 16px;
}
.contract-form-span {
grid-column: 1 / -1;
}
.contract-field {
width: 100%;
}
.contract-sort-label {
display: inline-flex;
align-items: center;
gap: 4px;
}
.contract-help-icon {
cursor: help;
}
</style>
@@ -1,490 +1,276 @@
/**
* features/admin/modules/questions/QuestionsPage.vue
* 常用问题管理:Tab「常用问题」+「热点发现」(离线聚合候选)。
* 依赖:useQuestionsAdmin、HotFaqCandidatesPanel、QuestionFormModal。
* 逻辑:路由 /admin/questions;热点候选晋升后写入 QuickQuestion 并由 Phase 1 FAQ 在线命中。
* 用途:常用问题管理页。一张卡片里放标题、添加按钮、页签、筛选和表格。
* 依赖:AdminListPage、AdminListTabs、useQuestionsAdmin、useElementProvider、element-plus、QuestionFormModal、HotFaqCandidatesPanel。
* 逻辑:路由 /admin/questions。骨架用 AdminListPage,页签用 AdminListTabs。
* 筛选、表格留在本页;热点候选由页签内容区的面板自己渲染。删除在 composable 里用 Element 确认框。
*/
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { computed, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Edit, Plus, Trash2, Zap } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import { Plus } from '@element-plus/icons-vue';
import {
ElButton,
ElCheckbox,
ElConfigProvider,
ElInput,
ElLoading,
ElOption,
ElSelect,
ElTable,
ElTableColumn,
ElTag,
} from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/features/admin/styles/element-trial.css';
import AdminListPage from '@/features/admin/components/AdminListPage.vue';
import AdminListTabs from '@/features/admin/components/AdminListTabs.vue';
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
import type { AdminQuickQuestionRow } from '@/features/admin/types/question.types';
import HotFaqCandidatesPanel from './components/HotFaqCandidatesPanel.vue';
import QuestionFormModal from './components/QuestionFormModal.vue';
import { useQuestionsAdmin } from './composables/useQuestionsAdmin';
const vLoading = ElLoading.directive;
const { t } = useI18n();
const { elementLocale } = useElementProvider();
const activeTab = ref<'manual' | 'hot'>('manual');
const {
filteredQuestions,
agents,
form,
isLoading,
isSaving,
showFormModal,
showDeleteConfirmDialog,
deleteConfirmMessage,
filterAgentId,
filterCacheOnly,
filterStaleOnly,
staleCount,
searchKeyword,
loadAll,
openCreateModal,
openEditModal,
closeFormModal,
saveQuestion,
saveReviewQuestion,
deleteQuestion,
closeDeleteConfirm,
confirmDelete,
truncateQuestionPreview,
truncateAnswerPreview,
} = useQuestionsAdmin();
/**
* 常用问题和热点发现两个页签。待审数量大于 0 时显示在第一个页签上。
*/
const questionTabs = computed(() => [
{
name: 'manual',
label: t('admin.question.tabs.manual'),
badge: staleCount.value > 0 ? staleCount.value : undefined,
},
{
name: 'hot',
label: t('admin.question.tabs.hotDiscovery'),
},
]);
/**
* 只接受本页的两个页签名,避免公共页签回传任意字符串。
* @param name - AdminListTabs 当前选中的 name
*/
function onQuestionTabChange(name: string): void {
if (name === 'manual' || name === 'hot') activeTab.value = name;
}
/**
* 应用筛选。清空时写回空字符串,表示全部应用。
* @param value - 选中的应用 id;清空为 undefined
*/
function onAgentFilterChange(value: number | undefined): void {
filterAgentId.value = value ?? '';
}
/**
* 打开编辑弹窗。表格插槽行类型较宽,这里收成常用问题行。
* @param row - 当前表格行
*/
function editQuestion(row: AdminQuickQuestionRow): void {
openEditModal(row);
}
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="admin-table-section animate-fade-in-up">
<div class="admin-table-header admin-table-header--stacked mb-4">
<div>
<ElConfigProvider :locale="elementLocale">
<AdminListPage>
<template #title>
<h2 class="section-title">{{ t('admin.question.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.question.subtitle') }}</p>
</div>
<button
v-if="activeTab === 'manual'"
type="button"
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-all shadow-lg shadow-brand-200 active:scale-95 text-sm font-medium"
@click="openCreateModal"
>
<Plus class="w-4 h-4" />
<span>{{ t('admin.question.add') }}</span>
</button>
</div>
<div class="mb-6 flex gap-1 border-b border-default">
<button
type="button"
class="px-4 py-2.5 text-sm font-medium border-b-2 -mb-px transition-colors"
:class="activeTab === 'manual' ? 'border-brand-600 text-brand-600' : 'border-transparent text-muted hover:text-secondary'"
@click="activeTab = 'manual'"
>
{{ t('admin.question.tabs.manual') }}
<span
v-if="staleCount > 0"
class="ml-1.5 inline-flex min-w-[1.25rem] items-center justify-center rounded-full bg-amber-100 px-1.5 py-0.5 text-[10px] font-semibold text-amber-800"
</template>
<template #actions>
<ElButton
v-if="activeTab === 'manual'"
type="primary"
:icon="Plus"
@click="openCreateModal"
>
{{ staleCount }}
{{ t('admin.question.add') }}
</ElButton>
</template>
<template #tabs>
<AdminListTabs :model-value="activeTab" :items="questionTabs" @update:model-value="onQuestionTabChange" />
</template>
<template v-if="activeTab === 'manual'" #filters>
<ElInput
v-model="searchKeyword"
clearable
class="question-filter-search"
:placeholder="t('admin.question.filters.search')"
/>
<ElSelect
:model-value="filterAgentId === '' ? undefined : filterAgentId"
class="question-filter-agent"
clearable
:placeholder="t('admin.question.filters.allAgents')"
@update:model-value="onAgentFilterChange"
>
<ElOption
v-for="agent in agents"
:key="agent.id"
:label="agent.name"
:value="agent.id"
/>
</ElSelect>
<ElCheckbox v-model="filterCacheOnly">{{ t('admin.question.filters.cacheOnly') }}</ElCheckbox>
<ElCheckbox v-model="filterStaleOnly">{{ t('admin.question.filters.staleOnly') }}</ElCheckbox>
<span class="question-filter-count">
{{ t('admin.question.filters.resultCount', { count: filteredQuestions.length }) }}
</span>
</button>
<button
type="button"
class="px-4 py-2.5 text-sm font-medium border-b-2 -mb-px transition-colors"
:class="activeTab === 'hot' ? 'border-brand-600 text-brand-600' : 'border-transparent text-muted hover:text-secondary'"
@click="activeTab = 'hot'"
>
{{ t('admin.question.tabs.hotDiscovery') }}
</button>
</div>
<HotFaqCandidatesPanel v-if="activeTab === 'hot'" />
<template v-else>
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<div class="mb-4 flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
<div class="flex flex-1 flex-wrap items-center gap-3">
<input
v-model="searchKeyword"
type="search"
class="input-field text-sm w-full max-w-xs"
:placeholder="t('admin.question.filters.search')"
/>
<select v-model="filterAgentId" class="input-field text-sm w-full max-w-[200px]">
<option value="">{{ t('admin.question.filters.allAgents') }}</option>
<option v-for="agent in agents" :key="agent.id" :value="agent.id">
{{ agent.name }}
</option>
</select>
<label class="inline-flex items-center gap-2 text-sm text-secondary whitespace-nowrap">
<input v-model="filterCacheOnly" type="checkbox" class="accent-brand-600" />
<span>{{ t('admin.question.filters.cacheOnly') }}</span>
</label>
<label class="inline-flex items-center gap-2 text-sm text-secondary whitespace-nowrap">
<input v-model="filterStaleOnly" type="checkbox" class="accent-brand-600" />
<span>{{ t('admin.question.filters.staleOnly') }}</span>
</label>
</div>
<p class="text-xs text-muted">
{{ t('admin.question.filters.resultCount', { count: filteredQuestions.length }) }}
</p>
</div>
<div class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.question.headers.title') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.question.headers.agent') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.question.headers.content') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.question.headers.answer') }}</th>
<th class="px-6 py-4 text-left text-xs w-28">{{ t('admin.question.headers.cache') }}</th>
<th class="px-6 py-4 text-left text-xs w-20">{{ t('admin.question.headers.hits') }}</th>
<th class="px-6 py-4 text-left text-xs w-16">{{ t('admin.question.headers.order') }}</th>
<th class="px-6 py-4 text-right text-xs w-28">{{ t('admin.question.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="filteredQuestions.length === 0">
<td colspan="8" class="px-6 admin-table-empty">{{ t('admin.question.noData') }}</td>
</tr>
<tr v-for="q in filteredQuestions" :key="q.id" class="group">
<td class="px-6 py-4">
<div class="flex items-center gap-2">
<div class="font-medium text-primary text-sm">{{ q.title }}</div>
<span
v-if="q.stale_at"
class="inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-medium bg-amber-50 text-amber-800 border border-amber-100"
>
{{ t('admin.question.badges.stale') }}
</span>
<span
v-if="!q.is_enabled"
class="inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-medium bg-surface-soft text-muted border border-default"
>
{{ t('admin.question.badges.disabled') }}
</span>
</div>
</td>
<td class="px-6 py-4">
<span
class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-50 text-blue-700 border border-blue-100"
>
{{ q.agent_name || 'Unknown' }}
</span>
</td>
<td class="px-6 py-4">
<p class="text-sm text-secondary truncate max-w-[180px]" :title="q.question">
{{ truncateQuestionPreview(q.question) }}
</p>
</td>
<td class="px-6 py-4">
<p
v-if="q.cache_enabled && q.answer"
class="text-sm text-secondary truncate max-w-[160px]"
:title="q.answer"
>
{{ truncateAnswerPreview(q.answer) }}
</p>
<span v-else class="text-xs text-muted">—</span>
</td>
<td class="px-6 py-4">
<span
v-if="q.cache_enabled"
class="inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium bg-emerald-50 text-emerald-700 border border-emerald-100"
>
<Zap class="w-3 h-3" />
{{ t('admin.question.badges.cacheOn') }}
</span>
<span
v-else
class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium bg-surface-soft text-muted border border-default"
>
{{ t('admin.question.badges.cacheOff') }}
</span>
</td>
<td class="px-6 py-4 text-sm text-muted tabular-nums">{{ q.hit_count || 0 }}</td>
<td class="px-6 py-4 text-sm text-muted tabular-nums">{{ q.sort_order }}</td>
<td class="px-6 py-4">
<div class="flex justify-end gap-1">
<button
type="button"
class="p-1.5 text-indigo-600 hover:bg-indigo-50 rounded-lg transition-colors"
@click="openEditModal(q)"
>
<Edit class="w-4 h-4" />
</button>
<button
type="button"
class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
@click="deleteQuestion(q.id)"
>
<Trash2 class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<ElTable
v-if="activeTab === 'manual'"
v-loading="isLoading"
class="hx-admin-table"
:data="filteredQuestions"
row-key="id"
:empty-text="t('admin.question.noData')"
>
<ElTableColumn :label="t('admin.question.headers.title')" min-width="200">
<template #default="{ row }">
<div class="question-title">
<span>{{ (row as AdminQuickQuestionRow).title }}</span>
<ElTag v-if="(row as AdminQuickQuestionRow).stale_at" type="warning" effect="light">
{{ t('admin.question.badges.stale') }}
</ElTag>
<ElTag v-if="!(row as AdminQuickQuestionRow).is_enabled" type="info" effect="light">
{{ t('admin.question.badges.disabled') }}
</ElTag>
</div>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.question.headers.agent')" min-width="140">
<template #default="{ row }">
<ElTag effect="light">{{ (row as AdminQuickQuestionRow).agent_name || 'Unknown' }}</ElTag>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.question.headers.content')" min-width="180">
<template #default="{ row }">
<span class="question-ellipsis" :title="(row as AdminQuickQuestionRow).question">
{{ truncateQuestionPreview((row as AdminQuickQuestionRow).question) }}
</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.question.headers.answer')" min-width="160">
<template #default="{ row }">
<span
v-if="(row as AdminQuickQuestionRow).cache_enabled && (row as AdminQuickQuestionRow).answer"
class="question-ellipsis"
:title="(row as AdminQuickQuestionRow).answer || ''"
>
{{ truncateAnswerPreview((row as AdminQuickQuestionRow).answer || '') }}
</span>
<span v-else>—</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.question.headers.cache')" width="120">
<template #default="{ row }">
<ElTag
:type="(row as AdminQuickQuestionRow).cache_enabled ? 'success' : 'info'"
effect="light"
>
{{
(row as AdminQuickQuestionRow).cache_enabled
? t('admin.question.badges.cacheOn')
: t('admin.question.badges.cacheOff')
}}
</ElTag>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.question.headers.hits')" width="88">
<template #default="{ row }">{{ (row as AdminQuickQuestionRow).hit_count || 0 }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.question.headers.order')" width="88">
<template #default="{ row }">{{ (row as AdminQuickQuestionRow).sort_order }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.question.headers.actions')" width="140" align="right">
<template #default="{ row }">
<ElButton link type="primary" @click="editQuestion(row as AdminQuickQuestionRow)">
{{ t('admin.question.actions.edit') }}
</ElButton>
<ElButton link type="danger" @click="deleteQuestion((row as AdminQuickQuestionRow).id)">
{{ t('admin.question.actions.delete') }}
</ElButton>
</template>
</ElTableColumn>
</ElTable>
<HotFaqCandidatesPanel v-if="activeTab === 'hot'" />
</AdminListPage>
<QuestionFormModal
:visible="showFormModal"
:form="form"
:agents="agents"
:is-saving="isSaving"
@close="closeFormModal"
@save="saveQuestion"
@review="saveReviewQuestion"
/>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@cancel="closeDeleteConfirm"
@confirm="confirmDelete"
/>
</template>
</section>
</ElConfigProvider>
</template>
<style scoped>
:deep(.question-filter-search) {
width: 16rem;
}
:deep(.question-filter-agent) {
width: 11rem;
}
.question-filter-count {
margin-left: auto;
color: var(--el-text-color-secondary);
font-size: var(--el-font-size-small);
}
.question-title {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.question-ellipsis {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>
@@ -1,14 +1,29 @@
/**
* features/admin/modules/questions/components/HotFaqCandidatesPanel.vue
* 热点 FAQ 候选列表:离线聚合结果展示、刷新、晋升、忽略。
* 依赖:useHotFaqCandidates。
* 逻辑:QuestionsPage「热点发现」Tab 挂载本组件。
* 用途:热点 FAQ 候选列表。展示离线聚合结果,并提供刷新、晋升、忽略。
* 依赖:useHotFaqCandidates、element-plus 的表格、筛选和按钮。
* 逻辑:QuestionsPage「热点发现」页签把本组件放在内容区,不再套一层 AdminListPage。样式随页面入口引入。
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { ArrowUpCircle, Info, RefreshCw, XCircle } from 'lucide-vue-next';
import { useHotFaqCandidates } from '../composables/useHotFaqCandidates';
import { InfoFilled, Refresh } from '@element-plus/icons-vue';
import {
ElButton,
ElInput,
ElLoading,
ElOption,
ElSelect,
ElTable,
ElTableColumn,
ElTag,
} from 'element-plus';
import {
useHotFaqCandidates,
type HotFaqCandidateRow,
} from '../composables/useHotFaqCandidates';
const vLoading = ElLoading.directive;
const { t } = useI18n();
@@ -30,159 +45,214 @@ const {
truncatePreview,
} = useHotFaqCandidates();
/**
* 切换热点候选的应用筛选。
* 核心逻辑:清空时写回空字符串,表示全部应用;随后按应用重新拉取候选。
* @param value - 选中的应用 id;清空为 undefined
*/
function onAgentFilterChange(value: number | undefined): void {
filterAgentId.value = value ?? '';
void loadCandidates();
}
/**
* 表格行主键。同一应用下的归一化问句唯一。
* @param row - 候选行
*/
function candidateRowKey(row: HotFaqCandidateRow): string {
return `${row.agent_id}-${row.q_norm}`;
}
/**
* 读取聚合规则里的文案或数字。
* 核心逻辑:规则结构由接口返回,字段缺失时显示空字符串。
* @param group - selection 或 answer
* @param field - 规则字段名
*/
function ruleValue(group: 'selection' | 'answer', field: string): string {
const source = rules.value?.[group];
if (!source || typeof source !== 'object') return '';
const value = (source as Record<string, unknown>)[field];
if (value == null || value === '') return '';
return String(value);
}
onMounted(() => {
void loadAll();
});
const onAgentFilterChange = () => {
void loadCandidates();
};
</script>
<template>
<div class="space-y-4">
<div class="rounded-2xl border border-default bg-surface-soft/40 p-4 text-sm text-secondary">
<div class="hot-faq-panel">
<div class="hot-faq-intro">
<p>{{ t('admin.hotFaq.intro') }}</p>
<button
type="button"
class="mt-2 inline-flex items-center gap-1 text-xs font-medium text-brand-600 hover:underline"
@click="showRules = !showRules"
>
<Info class="w-3.5 h-3.5" />
<ElButton link type="primary" :icon="InfoFilled" @click="showRules = !showRules">
{{ showRules ? t('admin.hotFaq.hideRules') : t('admin.hotFaq.showRules') }}
</button>
<div v-if="showRules && rules" class="mt-3 space-y-2 text-xs text-muted border-t border-subtle pt-3">
<div>
<span class="font-semibold text-secondary">{{ t('admin.hotFaq.rules.selection') }}</span>
{{ (rules as any).selection?.description }}
</div>
<ul class="list-disc pl-5 space-y-0.5">
<li>{{ t('admin.hotFaq.rules.windowDays', { n: (rules as any).selection?.window_days }) }}</li>
<li>{{ t('admin.hotFaq.rules.minCount', { n: (rules as any).selection?.min_count }) }}</li>
<li>{{ t('admin.hotFaq.rules.minUsers', { n: (rules as any).selection?.min_users }) }}</li>
</ElButton>
<div v-if="showRules && rules" class="hot-faq-rules">
<p>
<strong>{{ t('admin.hotFaq.rules.selection') }}</strong>
{{ ruleValue('selection', 'description') }}
</p>
<ul>
<li>{{ t('admin.hotFaq.rules.windowDays', { n: ruleValue('selection', 'window_days') }) }}</li>
<li>{{ t('admin.hotFaq.rules.minCount', { n: ruleValue('selection', 'min_count') }) }}</li>
<li>{{ t('admin.hotFaq.rules.minUsers', { n: ruleValue('selection', 'min_users') }) }}</li>
</ul>
<div class="pt-1">
<span class="font-semibold text-secondary">{{ t('admin.hotFaq.rules.answer') }}</span>
{{ (rules as any).answer?.description }}
</div>
<p>
<strong>{{ t('admin.hotFaq.rules.answer') }}</strong>
{{ ruleValue('answer', 'description') }}
</p>
</div>
</div>
<div class="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
<div class="flex flex-1 flex-wrap items-center gap-3">
<input
v-model="searchKeyword"
type="search"
class="input-field text-sm w-full max-w-xs"
:placeholder="t('admin.hotFaq.filters.search')"
/>
<select
v-model="filterAgentId"
class="input-field text-sm w-full max-w-[200px]"
@change="onAgentFilterChange"
>
<option value="">{{ t('admin.hotFaq.filters.allAgents') }}</option>
<option v-for="agent in agents" :key="agent.id" :value="agent.id">
{{ agent.name }}
</option>
</select>
</div>
<div class="flex flex-wrap items-center gap-2">
<span class="text-xs text-muted">
{{ t('admin.hotFaq.stats.summary', {
count: stats.total_candidates ?? 0,
asks: stats.total_ask_count_7d ?? 0,
}) }}
</span>
<button
type="button"
class="btn-ghost text-sm"
:disabled="isRefreshing"
@click="refreshCandidates(true)"
>
{{ t('admin.hotFaq.actions.dryRun') }}
</button>
<button
type="button"
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 text-sm font-medium disabled:opacity-70"
:disabled="isRefreshing"
@click="refreshCandidates(false)"
>
<RefreshCw class="w-4 h-4" :class="{ 'animate-spin': isRefreshing }" />
{{ t('admin.hotFaq.actions.refresh') }}
</button>
</div>
<div class="hot-faq-filters">
<ElInput
v-model="searchKeyword"
clearable
class="hot-faq-filter-search"
:placeholder="t('admin.hotFaq.filters.search')"
/>
<ElSelect
:model-value="filterAgentId === '' ? undefined : filterAgentId"
class="hot-faq-filter-agent"
clearable
:placeholder="t('admin.hotFaq.filters.allAgents')"
@update:model-value="onAgentFilterChange"
>
<ElOption v-for="agent in agents" :key="agent.id" :label="agent.name" :value="agent.id" />
</ElSelect>
<span class="hot-faq-stats">
{{ t('admin.hotFaq.stats.summary', {
count: stats.total_candidates ?? 0,
asks: stats.total_ask_count_7d ?? 0,
}) }}
</span>
<ElButton :disabled="isRefreshing" @click="refreshCandidates(true)">
{{ t('admin.hotFaq.actions.dryRun') }}
</ElButton>
<ElButton type="primary" :icon="Refresh" :loading="isRefreshing" @click="refreshCandidates(false)">
{{ t('admin.hotFaq.actions.refresh') }}
</ElButton>
</div>
<div v-if="isLoading" class="flex items-center justify-center py-16">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<div v-else class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.hotFaq.headers.query') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.hotFaq.headers.agent') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.hotFaq.headers.answer') }}</th>
<th class="px-6 py-4 text-left text-xs w-20">{{ t('admin.hotFaq.headers.asks') }}</th>
<th class="px-6 py-4 text-left text-xs w-20">{{ t('admin.hotFaq.headers.users') }}</th>
<th class="px-6 py-4 text-left text-xs w-24">{{ t('admin.hotFaq.headers.tokens') }}</th>
<th class="px-6 py-4 text-left text-xs w-20">{{ t('admin.hotFaq.headers.dominance') }}</th>
<th class="px-6 py-4 text-right text-xs w-36">{{ t('admin.hotFaq.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="filteredItems.length === 0">
<td colspan="8" class="px-6 admin-table-empty">{{ t('admin.hotFaq.noData') }}</td>
</tr>
<tr v-for="row in filteredItems" :key="`${row.agent_id}-${row.q_norm}`">
<td class="px-6 py-4">
<div class="font-medium text-primary text-sm">{{ row.canonical_query }}</div>
<p v-if="row.sample_queries?.length" class="text-[11px] text-muted mt-1 truncate max-w-[200px]">
{{ row.sample_queries.slice(0, 2).join(' / ') }}
</p>
</td>
<td class="px-6 py-4">
<span class="inline-flex px-2.5 py-0.5 rounded-full text-xs bg-blue-50 text-blue-700 border border-blue-100">
{{ row.agent_name || row.agent_id }}
</span>
</td>
<td class="px-6 py-4">
<p class="text-sm text-secondary truncate max-w-[180px]" :title="row.answer">
{{ truncatePreview(row.answer) }}
</p>
</td>
<td class="px-6 py-4 text-sm tabular-nums text-muted">{{ row.ask_count_7d }}</td>
<td class="px-6 py-4 text-sm tabular-nums text-muted">{{ row.user_count_7d }}</td>
<td class="px-6 py-4 text-sm tabular-nums text-muted">{{ row.avg_tokens }}</td>
<td class="px-6 py-4 text-sm tabular-nums text-muted">
{{ row.answer_dominance != null ? `${Math.round(row.answer_dominance * 100)}%` : '—' }}
</td>
<td class="px-6 py-4">
<div class="flex justify-end gap-1">
<button
type="button"
class="inline-flex items-center gap-1 px-2.5 py-1.5 text-xs font-medium text-emerald-700 bg-emerald-50 hover:bg-emerald-100 rounded-lg border border-emerald-100"
:title="t('admin.hotFaq.actions.promote')"
@click="promoteCandidate(row)"
>
<ArrowUpCircle class="w-3.5 h-3.5" />
{{ t('admin.hotFaq.actions.promote') }}
</button>
<button
type="button"
class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg"
:title="t('admin.hotFaq.actions.dismiss')"
@click="dismissCandidate(row)"
>
<XCircle class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<ElTable
v-loading="isLoading"
class="hx-admin-table"
:data="filteredItems"
:row-key="candidateRowKey"
:empty-text="t('admin.hotFaq.noData')"
>
<ElTableColumn :label="t('admin.hotFaq.headers.query')" min-width="200">
<template #default="{ row }">
<div>{{ (row as HotFaqCandidateRow).canonical_query }}</div>
<p
v-if="(row as HotFaqCandidateRow).sample_queries?.length"
class="hx-element-hint question-ellipsis"
:title="(row as HotFaqCandidateRow).sample_queries?.slice(0, 2).join(' / ')"
>
{{ (row as HotFaqCandidateRow).sample_queries?.slice(0, 2).join(' / ') }}
</p>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.hotFaq.headers.agent')" min-width="140">
<template #default="{ row }">
<ElTag effect="light">
{{ (row as HotFaqCandidateRow).agent_name || (row as HotFaqCandidateRow).agent_id }}
</ElTag>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.hotFaq.headers.answer')" min-width="180">
<template #default="{ row }">
<span class="question-ellipsis" :title="(row as HotFaqCandidateRow).answer">
{{ truncatePreview((row as HotFaqCandidateRow).answer) }}
</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.hotFaq.headers.asks')" width="100">
<template #default="{ row }">{{ (row as HotFaqCandidateRow).ask_count_7d }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.hotFaq.headers.users')" width="100">
<template #default="{ row }">{{ (row as HotFaqCandidateRow).user_count_7d }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.hotFaq.headers.tokens')" width="110">
<template #default="{ row }">{{ (row as HotFaqCandidateRow).avg_tokens }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.hotFaq.headers.dominance')" width="110">
<template #default="{ row }">
{{
(row as HotFaqCandidateRow).answer_dominance != null
? `${Math.round(((row as HotFaqCandidateRow).answer_dominance || 0) * 100)}%`
: '—'
}}
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.hotFaq.headers.actions')" width="220" align="right">
<template #default="{ row }">
<ElButton link type="primary" @click="promoteCandidate(row as HotFaqCandidateRow)">
{{ t('admin.hotFaq.actions.promote') }}
</ElButton>
<ElButton link type="danger" @click="dismissCandidate(row as HotFaqCandidateRow)">
{{ t('admin.hotFaq.actions.dismiss') }}
</ElButton>
</template>
</ElTableColumn>
</ElTable>
</div>
</template>
<style scoped>
.hot-faq-intro {
padding: 16px 32px 0;
color: var(--el-text-color-regular);
font-size: var(--el-font-size-base);
}
.hot-faq-rules {
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid var(--el-border-color-lighter);
color: var(--el-text-color-secondary);
font-size: var(--el-font-size-extra-small);
}
.hot-faq-rules ul {
margin: 8px 0;
padding-left: 1.25rem;
}
.hot-faq-filters {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
padding: 16px 32px;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.hot-faq-filters :deep(.el-input),
.hot-faq-filters :deep(.el-select) {
flex: none;
}
:deep(.hot-faq-filter-search) {
width: 16rem;
}
:deep(.hot-faq-filter-agent) {
width: 11rem;
}
.hot-faq-stats {
margin-left: auto;
color: var(--el-text-color-secondary);
font-size: var(--el-font-size-small);
}
.question-ellipsis {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>
@@ -1,13 +1,27 @@
/**
* features/admin/modules/questions/components/QuestionFormModal.vue
* 常用问题 / FAQ 缓存创建与编辑居中弹窗。
* 依赖:QuestionFormState、admin 通用 modal 样式。
* 逻辑:QuestionsPage 打开本组件;提交时 emit save,由 composable 调 API。
* is_enabled 仅控制工作台首页入口;cache_enabled 单独控制聊天是否跳过 Dify。
* 用途:常用问题 / FAQ 缓存的创建与编辑对话框。字段多,宽 680px,两列短字段。
* 依赖:element-plus 对话框和表单、QuestionFormState、AdminAgentOption。
* 逻辑:QuestionsPage 打开本组件。提交时 emit save 或 review,由 useQuestionsAdmin 调接口。样式跟页面已引入的 Element 皮肤走。
* is_enabled 仅控制工作台首页入口;cache_enabled 单独控制聊天是否跳过 Dify。
*/
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import {
ElAlert,
ElButton,
ElCheckbox,
ElDatePicker,
ElDialog,
ElForm,
ElFormItem,
ElInput,
ElInputNumber,
ElOption,
ElSelect,
ElTag,
} from 'element-plus';
import type { AdminAgentOption } from '@/features/admin/types/admin.types';
import type { QuestionFormState } from '@/features/admin/types/question.types';
@@ -31,173 +45,226 @@ const answerRequired = computed(() => props.form.cache_enabled);
/** 是否处于 KB 更新后的待复审状态。 */
const isStale = computed(() => Boolean(props.form.stale_at));
/**
* 待复审原因的现有文案。
* 核心逻辑:删除和更新共用同一段提示,只替换原因短语。
*/
const staleReasonLabel = computed(() => (
props.form.stale_reason === 'kb_document_deleted'
? t('admin.question.stale.reasonDeleted')
: t('admin.question.stale.reasonUpdated')
));
/**
* 对话框关闭时通知页面收起并重置表单。提交过程中不收起。
* @param open - Element 对话框的打开状态
*/
function onVisibleChange(open: boolean): void {
if (open || props.isSaving) return;
emit('close');
}
/**
* 过期时间选择。清空后写回空字符串,提交时仍按长期有效处理。
* @param value - 日期组件回传的值;只有字符串会写进表单
*/
function onExpiresChange(value: string | number | Date | string[] | number[] | Date[] | null | undefined): void {
props.form.expires_at = typeof value === 'string' ? value : '';
}
/**
* 按当前状态提交保存或完成复审。
*/
function submitForm(): void {
if (isStale.value) {
emit('review');
return;
}
emit('save');
}
</script>
<template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
<div class="admin-modal-panel max-w-3xl max-h-[92vh] scale-100">
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
<h3 class="section-title">
{{ form.id ? t('admin.question.edit') : t('admin.question.add') }}
</h3>
<p class="text-sm text-muted mt-1">{{ t('admin.question.formHint') }}</p>
</div>
<ElDialog
:model-value="visible"
:title="form.id ? t('admin.question.edit') : t('admin.question.add')"
width="680px"
align-center
append-to-body
:close-on-click-modal="false"
:close-on-press-escape="!isSaving"
:show-close="!isSaving"
@update:model-value="onVisibleChange"
>
<div class="question-dialog-body">
<p class="hx-element-hint">{{ t('admin.question.formHint') }}</p>
<ElAlert
v-if="isStale"
class="question-stale"
type="warning"
:closable="false"
show-icon
:title="t('admin.question.stale.bannerTitle')"
>
<p>
{{ t('admin.question.stale.bannerBody', {
doc: form.stale_kb_document_title || t('admin.question.stale.unknownDoc'),
reason: staleReasonLabel,
}) }}
</p>
<p>{{ t('admin.question.stale.bannerHint') }}</p>
</ElAlert>
<div class="px-5 sm:px-8 py-5 space-y-6 overflow-y-auto">
<div
v-if="isStale"
class="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900"
>
<p class="font-medium">{{ t('admin.question.stale.bannerTitle') }}</p>
<p class="mt-1 text-xs text-amber-800">
{{ t('admin.question.stale.bannerBody', {
doc: form.stale_kb_document_title || t('admin.question.stale.unknownDoc'),
reason: form.stale_reason === 'kb_document_deleted'
? t('admin.question.stale.reasonDeleted')
: t('admin.question.stale.reasonUpdated'),
}) }}
</p>
<p class="mt-1 text-xs text-amber-700">{{ t('admin.question.stale.bannerHint') }}</p>
</div>
<ElForm label-position="top" :model="form" @submit.prevent="submitForm">
<p class="question-section-label">{{ t('admin.question.sections.basic') }}</p>
<div class="question-form">
<ElFormItem class="question-form-span" :label="t('admin.question.fields.title')" required>
<ElInput v-model="form.title" :placeholder="t('admin.question.fields.titlePlaceholder')" />
</ElFormItem>
<ElFormItem :label="t('admin.question.fields.targetAgent')" required>
<ElSelect
v-model="form.agent_id"
class="question-field-full"
:placeholder="t('admin.perm.batchModal.selectAgents')"
>
<ElOption v-for="agent in agents" :key="agent.id" :label="agent.name" :value="agent.id" />
</ElSelect>
</ElFormItem>
<ElFormItem :label="t('admin.question.fields.sortOrder')">
<ElInputNumber v-model="form.sort_order" class="question-field-full" :min="0" controls-position="right" />
</ElFormItem>
<ElFormItem class="question-form-span">
<ElCheckbox v-model="form.is_enabled">
<span class="question-check-label">{{ t('admin.question.fields.isEnabled') }}</span>
<span class="hx-element-hint question-check-hint">{{ t('admin.question.fields.isEnabledHelp') }}</span>
</ElCheckbox>
</ElFormItem>
<ElFormItem class="question-form-span">
<ElCheckbox v-model="form.cache_enabled">{{ t('admin.question.fields.cacheEnabled') }}</ElCheckbox>
</ElFormItem>
<section class="space-y-4">
<h4 class="text-xs font-bold uppercase tracking-wider text-muted">
{{ t('admin.question.sections.basic') }}
</h4>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="space-y-1.5 md:col-span-2">
<label class="label-field">{{ t('admin.question.fields.title') }}</label>
<input
v-model="form.title"
type="text"
class="input-field text-sm"
:placeholder="t('admin.question.fields.titlePlaceholder')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.question.fields.targetAgent') }}</label>
<select v-model="form.agent_id" class="input-field text-sm">
<option :value="undefined" disabled>{{ t('admin.perm.batchModal.selectAgents') }}</option>
<option v-for="agent in agents" :key="agent.id" :value="agent.id">
{{ agent.name }}
</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.question.fields.sortOrder') }}</label>
<input v-model.number="form.sort_order" type="number" class="input-field text-sm" />
</div>
<div class="md:col-span-2 space-y-3">
<label class="flex items-start gap-2 text-sm text-secondary cursor-pointer">
<input v-model="form.is_enabled" type="checkbox" class="mt-0.5 accent-brand-600" />
<span>
<span class="block">{{ t('admin.question.fields.isEnabled') }}</span>
<span class="block text-xs text-muted mt-0.5">{{ t('admin.question.fields.isEnabledHelp') }}</span>
</span>
</label>
<label class="flex items-start gap-2 text-sm text-secondary cursor-pointer">
<input v-model="form.cache_enabled" type="checkbox" class="mt-0.5 accent-brand-600" />
<span>{{ t('admin.question.fields.cacheEnabled') }}</span>
</label>
</div>
</div>
</section>
<section class="space-y-4">
<h4 class="text-xs font-bold uppercase tracking-wider text-muted">
{{ t('admin.question.sections.matching') }}
</h4>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.question.fields.content') }}</label>
<textarea
<p class="question-section-label question-form-span">{{ t('admin.question.sections.matching') }}</p>
<ElFormItem class="question-form-span" :label="t('admin.question.fields.content')" required>
<ElInput
v-model="form.question"
rows="3"
class="input-field text-sm resize-y min-h-[88px]"
type="textarea"
:rows="4"
:placeholder="t('admin.question.fields.contentPlaceholder')"
/>
<p class="text-xs text-muted">{{ t('admin.question.fields.contentHelp') }}</p>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.question.fields.aliases') }}</label>
<textarea
<p class="hx-element-hint">{{ t('admin.question.fields.contentHelp') }}</p>
</ElFormItem>
<ElFormItem class="question-form-span" :label="t('admin.question.fields.aliases')">
<ElInput
v-model="form.aliasesText"
rows="3"
class="input-field text-sm resize-y min-h-[88px] font-mono"
class="question-aliases"
type="textarea"
:rows="4"
:placeholder="t('admin.question.fields.aliasesPlaceholder')"
/>
<p class="text-xs text-muted">{{ t('admin.question.fields.aliasesHelp') }}</p>
</div>
</section>
<p class="hx-element-hint">{{ t('admin.question.fields.aliasesHelp') }}</p>
</ElFormItem>
<section class="space-y-4 rounded-2xl border border-default bg-surface-soft/60 p-4">
<div class="flex items-start justify-between gap-3">
<div>
<h4 class="text-xs font-bold uppercase tracking-wider text-muted">
{{ t('admin.question.sections.cache') }}
</h4>
<p class="text-xs text-muted mt-1">{{ t('admin.question.fields.cacheHelp') }}</p>
</div>
<span
class="inline-flex shrink-0 items-center rounded-full px-2.5 py-0.5 text-xs font-medium"
:class="form.cache_enabled ? 'bg-emerald-50 text-emerald-700 border border-emerald-100' : 'bg-surface-soft text-muted border border-default'"
>
<div class="question-form-span question-section-head">
<p class="question-section-label">{{ t('admin.question.sections.cache') }}</p>
<ElTag :type="form.cache_enabled ? 'success' : 'info'" effect="light">
{{ form.cache_enabled ? t('admin.question.badges.cacheOn') : t('admin.question.badges.cacheOff') }}
</span>
</ElTag>
</div>
<div class="space-y-1.5">
<label class="label-field">
{{ t('admin.question.fields.answer') }}
<span v-if="answerRequired" class="text-red-500">*</span>
</label>
<textarea
<p class="hx-element-hint question-form-span">{{ t('admin.question.fields.cacheHelp') }}</p>
<ElFormItem class="question-form-span" :label="t('admin.question.fields.answer')" :required="answerRequired">
<ElInput
v-model="form.answer"
rows="6"
class="input-field text-sm resize-y min-h-[140px]"
type="textarea"
:rows="6"
:placeholder="t('admin.question.fields.answerPlaceholder')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.question.fields.expiresAt') }}</label>
<input v-model="form.expires_at" type="datetime-local" class="input-field text-sm" />
<p class="text-xs text-muted">{{ t('admin.question.fields.expiresAtHelp') }}</p>
</div>
</section>
</div>
<div class="admin-modal-footer">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button
v-if="isStale"
type="button"
class="btn-primary disabled:opacity-70"
:disabled="isSaving"
@click="emit('review')"
>
{{
isSaving
? t('admin.save') + '...'
: t('admin.question.stale.completeReview')
}}
</button>
<button
v-else
type="button"
class="btn-primary disabled:opacity-70"
:disabled="isSaving"
@click="emit('save')"
>
{{
isSaving
? t('admin.save') + '...'
: form.id
? t('admin.update')
: t('admin.add')
}}
</button>
</div>
</ElFormItem>
<ElFormItem class="question-form-span" :label="t('admin.question.fields.expiresAt')">
<ElDatePicker
:model-value="form.expires_at || undefined"
class="question-field-full"
type="datetime"
value-format="YYYY-MM-DDTHH:mm"
format="YYYY-MM-DD HH:mm"
clearable
:placeholder="t('admin.question.fields.expiresAt')"
@update:model-value="onExpiresChange"
/>
<p class="hx-element-hint">{{ t('admin.question.fields.expiresAtHelp') }}</p>
</ElFormItem>
</div>
</ElForm>
</div>
</div>
<template #footer>
<ElButton :disabled="isSaving" @click="emit('close')">{{ t('admin.cancel') }}</ElButton>
<ElButton v-if="isStale" type="primary" :loading="isSaving" @click="emit('review')">
{{ t('admin.question.stale.completeReview') }}
</ElButton>
<ElButton v-else type="primary" :loading="isSaving" @click="emit('save')">
{{ form.id ? t('admin.update') : t('admin.add') }}
</ElButton>
</template>
</ElDialog>
</template>
<style scoped>
.question-dialog-body {
max-height: 70vh;
overflow-y: auto;
}
.question-stale {
margin-top: 12px;
}
.question-form {
display: grid;
grid-template-columns: 1fr 1fr;
column-gap: 16px;
margin-top: 12px;
}
.question-form :deep(.el-form-item) {
margin-bottom: 14px;
}
.question-form-span {
grid-column: 1 / -1;
}
.question-section-label {
margin: 8px 0 0;
font-size: var(--el-font-size-extra-small);
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
color: var(--el-text-color-secondary);
}
.question-section-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.question-check-label,
.question-check-hint {
display: block;
}
.question-form :deep(.question-field-full) {
width: 100%;
}
.question-aliases :deep(.el-textarea__inner) {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
@media (max-width: 640px) {
.question-form {
grid-template-columns: 1fr;
}
}
</style>
@@ -1,11 +1,12 @@
/**
* features/admin/modules/questions/composables/useQuestionsAdmin.ts
* 常用问题 / FAQ 缓存管理:列表筛选、创建/编辑弹窗、删除。
* 依赖:admin.api、question.types、useMessage。
* 逻辑:QuestionsPage 调用本 composable 驱动表格与居中表单弹窗。
* 用途:常用问题 / FAQ 缓存管理:列表筛选、创建/编辑弹窗、删除。
* 依赖:admin.api、question.types、useMessage、element-plus 的确认框。
* 逻辑:QuestionsPage 调用本 composable 驱动表格与表单弹窗。删除用 ElMessageBox,不再使用 DeleteConfirmDialog。
*/
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessageBox } from 'element-plus';
import {
deleteAdminQuickQuestion,
listAdminAgents,
@@ -40,10 +41,6 @@ export function useQuestionsAdmin() {
const filterStaleOnly = ref(false);
const searchKeyword = ref('');
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
const staleCount = computed(() => questions.value.filter((q) => Boolean(q.stale_at)).length);
const filteredQuestions = computed(() => {
@@ -85,26 +82,6 @@ export function useQuestionsAdmin() {
isLoading.value = false;
};
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
deleteConfirmMessage.value = message;
deleteConfirmAction = action;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmAction = null;
};
const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
}
};
/**
* 重置表单为空白状态。
*/
@@ -225,16 +202,28 @@ export function useQuestionsAdmin() {
}
};
const deleteQuestion = (id: number): void => {
openDeleteConfirm(t('admin.question.confirmDelete'), async () => {
try {
await deleteAdminQuickQuestion(id);
await loadQuestions();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
});
/**
* 删除指定常用问题。先用 Element 确认框询问,取消则不请求。
* 核心逻辑:MessageBox 在取消时 reject,这里吞掉;确定后再调删除接口并刷新列表。
* @param id - 常用问题主键
*/
const deleteQuestion = async (id: number): Promise<void> => {
try {
await ElMessageBox.confirm(t('admin.question.confirmDelete'), t('common.deleteDialog.defaultTitle'), {
type: 'warning',
confirmButtonText: t('common.deleteDialog.confirm'),
cancelButtonText: t('common.deleteDialog.cancel'),
});
} catch {
return;
}
try {
await deleteAdminQuickQuestion(id);
await loadQuestions();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
};
return {
@@ -245,8 +234,6 @@ export function useQuestionsAdmin() {
isLoading,
isSaving,
showFormModal,
showDeleteConfirmDialog,
deleteConfirmMessage,
filterAgentId,
filterCacheOnly,
filterStaleOnly,
@@ -259,8 +246,6 @@ export function useQuestionsAdmin() {
saveQuestion,
saveReviewQuestion,
deleteQuestion,
closeDeleteConfirm,
confirmDelete,
truncateQuestionPreview,
truncateAnswerPreview,
};
@@ -2,7 +2,7 @@
* features/admin/modules/users/UsersPage.vue
* 用途:用户管理独立页面(服务端筛选分页、用户/部门列排序、批量操作)。
* 依赖:useUsersAdmin、useElementProvider、element-plus、用户相关 Modal、adminRoleLabel、getUserAvatarLabel。
* 逻辑:路由 /admin/users;本页是 Element Plus 试点,筛选、表格、分页、工具栏和三个业务弹窗走组件库。
* 逻辑:路由 /admin/users。列表骨架用 AdminListPage;筛选、表格、分页和三个业务弹窗仍由本页组装。
* 删除和改角色用 Element 确认框。列表经 listAdminUsersPage 按页拉取。
*/
<script setup lang="ts">
@@ -29,6 +29,7 @@ import { adminRoleLabel } from '@/features/admin/utils/roleLabel';
import { getUserAvatarLabel } from '@/shared/utils/user-avatar';
import type { AdminUserRow } from '@/features/admin/types/admin.types';
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
import AdminListPage from '@/features/admin/components/AdminListPage.vue';
import BatchEditUserModal from './components/BatchEditUserModal.vue';
import BatchPermissionModal from './components/BatchPermissionModal.vue';
import UserFormModal from './components/UserFormModal.vue';
@@ -125,39 +126,37 @@ onMounted(() => {
<template>
<ElConfigProvider :locale="elementLocale">
<section v-loading="isLoading" class="admin-table-section min-h-64">
<template v-if="!isLoading">
<div class="admin-table-header admin-table-header--stacked">
<div>
<h2 class="section-title">{{ t('admin.user.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.user.subtitle') }}</p>
</div>
<ElSpace wrap>
<ElButton
v-if="selectedUserIds.length > 0"
type="danger"
:icon="Delete"
@click="batchDeleteUsers"
>
{{ t('admin.user.batchDelete') }} ({{ selectedUserIds.length }})
</ElButton>
<ElButton v-if="selectedUserIds.length > 0" :icon="Edit" @click="openBatchEditModal">
{{ t('admin.user.batchEdit') }} ({{ selectedUserIds.length }})
</ElButton>
<ElButton
v-if="selectedUserIds.length > 0 && !rolesConfigured"
:icon="User"
@click="openBatchPermissionModal"
>
{{ t('admin.user.batchPermission') }} ({{ selectedUserIds.length }})
</ElButton>
<ElButton type="primary" :icon="Plus" @click="openCreateUserModal">
{{ t('admin.user.addUser') }}
</ElButton>
</ElSpace>
</div>
<div class="users-element-filters">
<AdminListPage :loading="isLoading">
<template #title>
<h2 class="section-title">{{ t('admin.user.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.user.subtitle') }}</p>
</template>
<template #actions>
<ElSpace wrap>
<ElButton
v-if="selectedUserIds.length > 0"
type="danger"
:icon="Delete"
@click="batchDeleteUsers"
>
{{ t('admin.user.batchDelete') }} ({{ selectedUserIds.length }})
</ElButton>
<ElButton v-if="selectedUserIds.length > 0" :icon="Edit" @click="openBatchEditModal">
{{ t('admin.user.batchEdit') }} ({{ selectedUserIds.length }})
</ElButton>
<ElButton
v-if="selectedUserIds.length > 0 && !rolesConfigured"
:icon="User"
@click="openBatchPermissionModal"
>
{{ t('admin.user.batchPermission') }} ({{ selectedUserIds.length }})
</ElButton>
<ElButton type="primary" :icon="Plus" @click="openCreateUserModal">
{{ t('admin.user.addUser') }}
</ElButton>
</ElSpace>
</template>
<template #filters>
<ElInput
v-model="userFilters.username"
clearable
@@ -179,7 +178,7 @@ onMounted(() => {
>
<ElOption v-for="department in departments" :key="department.id" :label="department.name" :value="department.name" />
</ElSelect>
</div>
</template>
<ElTable
v-loading="isListLoading"
@@ -233,7 +232,7 @@ onMounted(() => {
</ElTableColumn>
</ElTable>
<div class="hx-admin-pager">
<template #pagination>
<ElPagination
v-model:current-page="userPage"
v-model:page-size="userPageSize"
@@ -242,8 +241,8 @@ onMounted(() => {
layout="total, sizes, prev, pager, next"
background
/>
</div>
</template>
</AdminListPage>
<UserFormModal
:visible="showUserModal"
@@ -278,31 +277,16 @@ onMounted(() => {
@close="showBatchPermissionModal = false"
@save="submitBatchPermission"
/>
</section>
</ElConfigProvider>
</template>
<style scoped>
.users-element-filters {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
padding: 16px 32px;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.users-element-filters :deep(.el-input),
.users-element-filters :deep(.el-select) {
flex: none;
}
.users-element-filters :deep(.users-filter-username) {
:deep(.users-filter-username) {
width: 10rem;
}
.users-element-filters :deep(.users-filter-name),
.users-element-filters :deep(.users-filter-dept) {
:deep(.users-filter-name),
:deep(.users-filter-dept) {
width: 11rem;
}
@@ -2,8 +2,8 @@
/**
* features/kb/components/KbAdminPanel.vue
* 知识库配置面板(治理面:分组、Dify)。
* 依赖:kb.api、Element Plus、DifySettingsDialog、DifyHealthDialog、Vue I18n。
* 逻辑:管理控制台加载知识库分组;列表、表头排序、文档数筛选、分页和删除确认用 Element。排序和筛选都作用在全量数据上,再分页。新增/编辑走 KbGroupDrawer。
* 依赖:kb.api、Element Plus、AdminListPage、DifySettingsDialog、DifyHealthDialog、Vue I18n。
* 逻辑:管理控制台加载知识库分组。列表骨架用 AdminListPage。表头排序、文档数筛选、分页和删除确认用 Element。排序和筛选都作用在全量数据上,再分页。新增/编辑走 KbGroupDrawer。
*/
import { computed, onMounted, ref, watch } from 'vue';
@@ -26,6 +26,7 @@ import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/features/admin/styles/element-trial.css';
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
import AdminListPage from '@/features/admin/components/AdminListPage.vue';
import KbGroupDrawer, { type KbGroupFormValue } from './KbGroupDrawer.vue';
import DifyHealthDialog from './DifyHealthDialog.vue';
import DifySettingsDialog from './DifySettingsDialog.vue';
@@ -269,50 +270,49 @@ defineExpose({ loadData });
<template>
<ElConfigProvider :locale="elementLocale">
<section class="admin-table-section">
<div class="admin-table-header admin-table-header--stacked">
<div class="min-w-0 flex-1">
<AdminListPage>
<template #title>
<h2 class="section-title">{{ t('kbAdmin.groupsTitle') }}</h2>
<p class="section-desc mt-1">{{ t('kbAdmin.groupManageSubtitle') }}</p>
</div>
<ElSpace wrap>
<ElButton :icon="Setting" @click="settingsDialogOpen = true">{{ t('kbAdmin.difySettings') }}</ElButton>
<ElButton :icon="CircleCheck" @click="healthDialogOpen = true">{{ t('kbAdmin.healthCheck') }}</ElButton>
<ElButton :icon="Tools" @click="router.push(WORKSPACE_PATHS.knowledgeBase)">{{ t('kbAdmin.goWorkspace') }}</ElButton>
<ElButton type="primary" :icon="Plus" @click="openCreateDrawer">{{ t('kbAdmin.form.create') }}</ElButton>
</ElSpace>
</div>
<div class="kb-admin-filters">
<div class="kb-element-filters">
<ElInput
v-model="searchKeyword"
clearable
:prefix-icon="Search"
:placeholder="t('kbAdmin.filters.searchPlaceholder')"
/>
</div>
</div>
<ElAlert
v-if="feedback"
class="kb-admin-alert"
:title="feedback"
:type="feedbackType === 'error' ? 'error' : 'success'"
show-icon
closable
@close="feedback = ''"
</template>
<template #actions>
<ElSpace wrap>
<ElButton :icon="Setting" @click="settingsDialogOpen = true">{{ t('kbAdmin.difySettings') }}</ElButton>
<ElButton :icon="CircleCheck" @click="healthDialogOpen = true">{{ t('kbAdmin.healthCheck') }}</ElButton>
<ElButton :icon="Tools" @click="router.push(WORKSPACE_PATHS.knowledgeBase)">{{ t('kbAdmin.goWorkspace') }}</ElButton>
<ElButton type="primary" :icon="Plus" @click="openCreateDrawer">{{ t('kbAdmin.form.create') }}</ElButton>
</ElSpace>
</template>
<template #filters>
<ElInput
v-model="searchKeyword"
clearable
class="kb-filter-search"
:prefix-icon="Search"
:placeholder="t('kbAdmin.filters.searchPlaceholder')"
/>
</template>
<ElTable
v-loading="isRefreshing"
class="hx-admin-table"
:data="pagedGroups"
row-key="id"
:default-sort="{ prop: 'updated_at', order: 'descending' }"
:empty-text="tableEmptyText"
@sort-change="onSortChange"
@filter-change="onFilterChange"
>
<ElAlert
v-if="feedback"
class="kb-admin-alert"
:title="feedback"
:type="feedbackType === 'error' ? 'error' : 'success'"
show-icon
closable
@close="feedback = ''"
/>
<ElTable
v-loading="isRefreshing"
class="hx-admin-table"
:data="pagedGroups"
row-key="id"
:default-sort="{ prop: 'updated_at', order: 'descending' }"
:empty-text="tableEmptyText"
@sort-change="onSortChange"
@filter-change="onFilterChange"
>
<ElTableColumn prop="name" :label="t('kbAdmin.table.name')" min-width="160" sortable="custom">
<template #default="{ row }">
<div class="truncate" :title="(row as KbGroup).name">{{ (row as KbGroup).name }}</div>
@@ -348,18 +348,18 @@ defineExpose({ loadData });
</template>
</ElTableColumn>
</ElTable>
<div v-if="filteredGroups.length > 0" class="hx-admin-pager">
<ElPagination
v-model:current-page="currentPage"
v-model:page-size="pageSize"
:total="filteredGroups.length"
:page-sizes="pageSizeOptions"
layout="total, sizes, prev, pager, next"
background
/>
</div>
</section>
<template v-if="filteredGroups.length > 0" #pagination>
<ElPagination
v-if="filteredGroups.length > 0"
v-model:current-page="currentPage"
v-model:page-size="pageSize"
:total="filteredGroups.length"
:page-sizes="pageSizeOptions"
layout="total, sizes, prev, pager, next"
background
/>
</template>
</AdminListPage>
<KbGroupDrawer
v-model:form="form"
@@ -376,28 +376,11 @@ defineExpose({ loadData });
</template>
<style scoped>
.kb-admin-filters {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px 24px;
padding: 16px 32px;
border-bottom: 1px solid var(--el-border-color-lighter);
:deep(.kb-filter-search) {
width: 16rem;
}
.kb-admin-alert {
margin: 16px 32px 0;
}
.kb-element-filters {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
}
.kb-element-filters :deep(.el-input) {
width: 16rem;
flex: none;
}
</style>