Merge branch 'dev' into departmental-structure

This commit is contained in:
HTEWJ\26070045 committed 2026-10-22 13:19:53 +08:00
commit ec47e012a7
310 files changed
+31263 -6681

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>
@@ -0,0 +1,35 @@
/**
* features/admin/composables/useElementProvider.ts
* 用途:管理端 Element Plus 试点的界面语言。
* 依赖:element-plus locale、vue-i18n。
* 逻辑:UsersPage、AgentsPage、KbAdminPanel 把 elementLocale 传给 ElConfigProvider;亮暗靠 html.dark 与 Element 暗色变量,不在这里重复切换。
*/
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import zhTw from 'element-plus/es/locale/lang/zh-tw';
import en from 'element-plus/es/locale/lang/en';
import th from 'element-plus/es/locale/lang/th';
const ELEMENT_LOCALES = {
'zh-CN': zhCn,
'zh-TW': zhTw,
en,
th,
} as const;
/**
* 取当前界面语言对应的 Element Plus 语言包。
* 核心逻辑:未知语言回退简体中文。
* @returns elementLocale,随 vue-i18n 语言变化
*/
export function useElementProvider() {
const { locale } = useI18n();
const elementLocale = computed(() => {
const key = locale.value as keyof typeof ELEMENT_LOCALES;
return ELEMENT_LOCALES[key] ?? zhCn;
});
return { elementLocale };
}
@@ -2,22 +2,36 @@
* features/admin/modules/agents/AgentsPage.vue
*
* 用途:管理控制台的应用管理页,提供应用列表、创建/编辑弹窗、测试与授权入口。
* 依赖:useAgentsAdmin 业务编排、AgentFormModal/AgentTestModal/AgentPermissionModal 弹窗。
* 逻辑:页面加载后拉取应用/用户/排程数据;权限组启用后隐藏按人授权按钮。
* 依赖:useAgentsAdmin 业务编排、Element Plus 表格与按钮、AgentFormModal/AgentTestModal/AgentPermissionModal 弹窗。
* 逻辑:页面加载后先展示应用列表;目录、用户和排程在后台补齐。权限组启用后隐藏按人授权按钮。
* 列表使用 Element stripe 斑马纹。选中行浅底画在单元格上,盖过斑马纹。
*/
<script setup lang="ts">
import { computed, ref, onMounted } from 'vue';
import { ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Bot, Plus, SquarePen, Trash2, Users } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import { Plus } from '@element-plus/icons-vue';
import {
ElButton,
ElConfigProvider,
ElEmpty,
ElLoading,
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 { useElementProvider } from '@/features/admin/composables/useElementProvider';
import AgentFormModal from './components/AgentFormModal.vue';
import AgentPermissionModal from './components/AgentPermissionModal.vue';
import AgentTestModal from './components/AgentTestModal.vue';
import { useAgentsAdmin } from './composables/useAgentsAdmin';
import { useAgentsTableColumnResize } from './composables/useAgentsTableColumnResize';
import type { AgentRow } from '@/features/admin/types/agent.types';
const { t } = useI18n();
const { elementLocale } = useElementProvider();
const vLoading = ElLoading.directive;
const {
agents,
@@ -44,8 +58,7 @@ const {
permissionAgent,
permissionUserIds,
rolesConfigured,
showDeleteConfirmDialog,
deleteConfirmMessage,
rolesChecked,
loadAll,
resetForm,
selectAgent,
@@ -63,23 +76,8 @@ const {
openPermissionModal,
togglePermissionUser,
savePermissions,
closeDeleteConfirm,
confirmDelete,
} = useAgentsAdmin();
const {
columnWidths,
tableMinWidth,
startColumnResize,
resetColumnWidths,
} = useAgentsTableColumnResize();
const tableHeaderColumns = computed(() => [
{ key: 'name', label: t('admin.agent.headers.name'), align: 'left' as const },
{ key: 'status', label: t('admin.agent.headers.status'), align: 'left' as const },
{ key: 'actions', label: t('admin.agent.headers.actions'), align: 'right' as const },
]);
/* 列表仅展示名称、状态和操作;类型/聚合/配置仍由编辑弹窗维护。 */
const formatAgentCode = (agent: AgentRow) => agent.agent_code || 'generic';
@@ -153,6 +151,23 @@ const openEditDialog = (agent: Parameters<typeof selectAgent>[0]): void => {
showFormDialog.value = true;
};
/**
* 点击表格行时打开编辑弹窗。
* 核心逻辑:Element 行对象按 id 找回完整应用,避免把表格行类型直接交给 selectAgent。
*/
const onRowClick = (row: { id?: number }): void => {
const agent = agents.value.find((item) => item.id === row.id);
if (agent) openEditDialog(agent);
};
/**
* 当前选中应用的行样式。
* 核心逻辑:编辑弹窗打开前,用 selectedAgentId 给对应行加上浅底。
*/
const agentRowClass = ({ row }: { row: AgentRow }): string => (
selectedAgentId.value === row.id ? 'agents-row-selected' : ''
);
/**
* 保存应用表单,成功后关闭弹窗。
* 核心逻辑:submitAgent 会处理校验、接口调用和列表刷新;仅在返回 true 时收起弹窗。
@@ -168,134 +183,74 @@ onMounted(() => {
</script>
<template>
<section class="admin-table-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" />
<ElConfigProvider :locale="elementLocale">
<section class="admin-table-section min-h-64">
<div class="admin-table-header admin-table-header--stacked">
<div>
<h2 class="section-title">{{ t('admin.agent.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.agent.subtitle') }}</p>
</div>
<ElButton type="primary" :icon="Plus" @click="openCreateDialog">
{{ t('admin.agent.new') }}
</ElButton>
</div>
<template v-else>
<div class="admin-table-header admin-table-header--stacked">
<div>
<h2 class="section-title">{{ t('admin.agent.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.agent.subtitle') }}</p>
</div>
<button type="button" class="btn-primary" @click="openCreateDialog">
<Plus class="w-5 h-5" />
<span class="font-medium">{{ t('admin.agent.new') }}</span>
</button>
</div>
<div class="admin-table-wrap">
<div v-if="agents.length === 0" class="admin-table-empty">
<Bot class="w-12 h-12 mx-auto text-muted mb-3" />
<p class="text-lg text-secondary">{{ t('admin.agent.noAgents') }}</p>
</div>
<table
v-else
class="admin-table agent-list-table table-fixed w-full"
:style="{ minWidth: `${tableMinWidth}px` }"
>
<colgroup>
<col
v-for="(width, index) in columnWidths"
:key="`col-${index}`"
:style="{ width: `${width}px` }"
/>
</colgroup>
<thead>
<tr>
<th
v-for="(column, index) in tableHeaderColumns"
:key="column.key"
class="relative px-4 py-3 text-xs"
:class="column.align === 'right' ? 'text-right' : 'text-left'"
>
<span class="truncate pr-2">{{ column.label }}</span>
<button
v-if="index < tableHeaderColumns.length - 1"
type="button"
class="agent-col-resize-handle"
:title="t('admin.agent.resizeColumn')"
@mousedown.prevent="startColumnResize(index, $event)"
@dblclick.prevent="resetColumnWidths"
/>
</th>
</tr>
</thead>
<tbody>
<tr
v-for="agent in agents"
:key="agent.id"
class="group cursor-pointer"
:class="{ 'bg-blue-50/50': selectedAgentId === agent.id }"
@click="openEditDialog(agent)"
<ElEmpty v-if="!isLoading && agents.length === 0" :description="t('admin.agent.noAgents')" />
<ElTable
v-else
v-loading="isLoading"
:data="agents"
row-key="id"
class="agents-element-table hx-admin-table"
stripe
:row-class-name="agentRowClass"
@row-click="onRowClick"
>
<ElTableColumn :label="t('admin.agent.headers.name')" min-width="280">
<template #default="{ row }">
<p class="truncate" :title="(row as AgentRow).name">
{{ (row as AgentRow).name }}
</p>
<p
v-if="(row as AgentRow).description"
class="truncate hx-element-hint"
:title="(row as AgentRow).description"
>
{{ (row as AgentRow).description }}
</p>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.agent.headers.status')" width="140">
<template #default="{ row }">
<ElTag :type="(row as AgentRow).is_active ? 'success' : 'info'" effect="light">
{{ (row as AgentRow).is_active ? t('admin.status.active') : t('admin.status.disabled') }}
</ElTag>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.agent.headers.actions')" min-width="280" align="right">
<template #default="{ row }">
<div class="inline-flex items-center justify-end" @click.stop>
<ElButton link type="primary" @click="openEditDialog(row as AgentRow)">
{{ t('admin.edit') }}
</ElButton>
<ElButton
v-if="rolesChecked && !rolesConfigured"
link
type="primary"
@click="openPermissionModal(row as AgentRow)"
>
<td class="px-4 py-4 align-middle">
<div class="agent-list-cell">
<p class="truncate text-sm font-semibold text-primary" :title="agent.name">{{ agent.name }}</p>
<p
v-if="agent.description"
class="truncate text-xs text-muted"
:title="agent.description"
>
{{ agent.description }}
</p>
</div>
</td>
<td class="px-4 py-4 align-middle">
<div class="agent-list-cell">
<span
class="inline-flex w-fit items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-xs font-medium"
:class="agent.is_active ? 'border-green-100 bg-green-50 text-green-700' : 'border-default bg-surface-soft text-secondary'"
>
<span class="h-1.5 w-1.5 shrink-0 rounded-full" :class="agent.is_active ? 'bg-green-500' : 'bg-surface-strong'" />
{{ agent.is_active ? t('admin.status.active') : t('admin.status.disabled') }}
</span>
</div>
</td>
<td class="px-4 py-4 align-middle text-right">
<div class="inline-flex items-center justify-end gap-2">
<button
type="button"
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-lg bg-blue-50 px-3 py-2 text-sm font-medium text-blue-600 transition-all hover:bg-blue-100"
:title="t('admin.edit')"
@click.stop="openEditDialog(agent)"
>
<SquarePen class="w-4 h-4 shrink-0" />
{{ t('admin.edit') }}
</button>
<button
v-if="!rolesConfigured"
type="button"
class="inline-flex shrink-0 items-center justify-center p-2 text-blue-600 bg-blue-50 hover:bg-blue-100 rounded-lg transition-all"
:title="t('admin.agent.manageAccess')"
@click.stop="openPermissionModal(agent)"
>
<Users class="w-5 h-5 shrink-0" />
</button>
<button
type="button"
class="inline-flex shrink-0 items-center whitespace-nowrap p-2 text-emerald-600 bg-emerald-50 hover:bg-emerald-100 rounded-lg transition-all"
:title="t('admin.agent.test')"
@click.stop="openTestModal(agent)"
>
{{ t('admin.agent.test') }}
</button>
<button
type="button"
class="inline-flex shrink-0 items-center justify-center p-2 text-muted hover:text-red-600 hover:bg-red-50 rounded-lg transition-all"
:title="t('admin.agent.delete')"
@click.stop="deleteAgent(agent.id)"
>
<Trash2 class="w-5 h-5 shrink-0" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</template>
{{ t('admin.agent.manageAccess') }}
</ElButton>
<ElButton link type="primary" @click="openTestModal(row as AgentRow)">
{{ t('admin.agent.test') }}
</ElButton>
<ElButton link type="danger" @click="deleteAgent((row as AgentRow).id)">
{{ t('admin.agent.delete') }}
</ElButton>
</div>
</template>
</ElTableColumn>
</ElTable>
<AgentTestModal
:visible="showTestModal"
@@ -342,45 +297,16 @@ onMounted(() => {
@save="savePermissions"
@toggle-user="togglePermissionUser"
/>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@confirm="confirmDelete"
@cancel="closeDeleteConfirm"
/>
</section>
</ElConfigProvider>
</template>
<style scoped>
.agent-list-table {
table-layout: fixed;
.agents-element-table :deep(.agents-row-selected td.el-table__cell) {
background: color-mix(in srgb, #0284c7 8%, var(--el-bg-color, #fff));
}
.agent-list-cell {
display: flex;
min-height: 2.5rem;
min-width: 0;
flex-direction: column;
justify-content: center;
gap: 0.125rem;
}
.agent-col-resize-handle {
position: absolute;
top: 0;
right: 0;
z-index: 1;
width: 8px;
height: 100%;
cursor: col-resize;
border: none;
background: transparent;
padding: 0;
}
.agent-col-resize-handle:hover,
.agent-col-resize-handle:active {
background-color: color-mix(in srgb, var(--border-default) 65%, transparent);
.agents-element-table :deep(.el-table__row) {
cursor: pointer;
}
</style>
@@ -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,11 +1,12 @@
/**
* features/admin/modules/agents/components/AgentPermissionModal.vue
*
* 为指定 Agent 批量勾选可访问用户的权限弹窗。
* 用途:为指定应用勾选可访问用户。
* 依赖:element-plus、admin.types、agent.types。
* 逻辑:AgentsPage 传入用户和已选 id;勾选变化交给父组件 togglePermissionUser。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { ElButton, ElCheckbox, ElDialog } from 'element-plus';
import type { AdminUserRow } from '@/features/admin/types/admin.types';
import type { AgentRow } from '@/features/admin/types/agent.types';
@@ -24,71 +25,68 @@ const emit = defineEmits<{
}>();
const { t } = useI18n();
/**
* 关闭弹窗。点遮罩或右上角关闭时 Element 会把打开状态写成 false。
* @param open - 对话框是否仍打开
*/
function onVisibleChange(open: boolean): void {
if (!open) emit('close');
}
</script>
<template>
<div v-if="visible && agent" class="admin-modal-overlay items-center">
<div class="admin-modal-panel max-w-2xl max-h-[90vh] animate-fade-in-up">
<div class="px-8 py-6 border-b border-subtle flex justify-between items-center">
<div>
<h3 class="text-lg font-bold text-primary">{{ t('admin.perm.agentModal.title') }}</h3>
<p class="text-sm text-muted">
{{ t('admin.perm.agentModal.agent') }}
<span class="font-medium text-blue-600">{{ agent.name }}</span>
</p>
</div>
<button type="button" class="btn-icon-ds rounded-full" @click="emit('close')">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<div class="flex-1 overflow-y-auto p-8">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div
v-for="user in users"
:key="user.id"
class="flex items-center gap-3 p-3 rounded-xl border transition-all cursor-pointer"
:class="selectedUserIds.includes(user.id) ? 'border-blue-200 bg-blue-50/50' : 'border-default hover-surface-soft'"
@click="emit('toggleUser', user.id)"
>
<div
class="w-5 h-5 rounded border flex items-center justify-center transition-colors"
:class="selectedUserIds.includes(user.id) ? 'bg-blue-600 border-blue-600' : 'bg-surface border-default'"
>
<svg
v-if="selectedUserIds.includes(user.id)"
xmlns="http://www.w3.org/2000/svg"
class="h-3.5 w-3.5 text-white"
viewBox="0 0 20 20"
fill="currentColor"
>
<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
</svg>
</div>
<div>
<div class="font-medium text-primary text-sm">{{ user.username }}</div>
<div class="text-xs text-muted">{{ user.real_name || user.email }}</div>
</div>
</div>
</div>
</div>
<div class="admin-modal-footer admin-modal-footer--muted px-8 py-6">
<button type="button" class="btn-ghost" @click="emit('close')">
{{ t('admin.cancel') }}
</button>
<button
type="button"
:disabled="isSaving"
class="btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
@click="emit('save')"
<ElDialog
:model-value="visible && !!agent"
:title="t('admin.perm.agentModal.title')"
width="680px"
align-center
append-to-body
:close-on-click-modal="false"
@update:model-value="onVisibleChange"
>
<template v-if="agent">
<p class="section-desc">{{ t('admin.perm.agentModal.agent') }}{{ agent.name }}</p>
<div class="agent-perm-list">
<ElCheckbox
v-for="user in users"
:key="user.id"
:model-value="selectedUserIds.includes(user.id)"
@change="emit('toggleUser', user.id)"
>
<div v-if="isSaving" class="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent" />
{{ t('admin.perm.agentModal.save') }}
</button>
<span>{{ user.username }}</span>
<span class="hx-element-hint">{{ user.real_name || user.email }}</span>
</ElCheckbox>
</div>
</div>
</div>
</template>
<template #footer>
<ElButton @click="emit('close')">{{ t('admin.cancel') }}</ElButton>
<ElButton type="primary" :loading="isSaving" @click="emit('save')">
{{ t('admin.perm.agentModal.save') }}
</ElButton>
</template>
</ElDialog>
</template>
<style scoped>
.agent-perm-list {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px 16px;
max-height: 65vh;
margin-top: 12px;
overflow-y: auto;
}
.agent-perm-list :deep(.el-checkbox) {
align-items: flex-start;
height: auto;
margin-right: 0;
}
@media (max-width: 640px) {
.agent-perm-list {
grid-template-columns: 1fr;
}
}
</style>
@@ -1,11 +1,12 @@
/**
* features/admin/modules/agents/components/AgentTestModal.vue
*
* Agent 连通性测试弹窗:展示请求 URL、输出信息与分析结果。
* 用途:应用连通性测试弹窗,展示请求地址、输出和分析结果。
* 依赖:element-plus、agent.types。
* 逻辑:AgentsPage 传入当前应用和测试结果;重新测试由父组件发起。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { ElButton, ElDialog } from 'element-plus';
import type { AgentRow, AgentTestResult } from '@/features/admin/types/agent.types';
defineProps<{
@@ -21,62 +22,98 @@ const emit = defineEmits<{
}>();
const { t } = useI18n();
/**
* 关闭弹窗。点遮罩或右上角关闭时 Element 会把打开状态写成 false。
* @param open - 对话框是否仍打开
*/
function onVisibleChange(open: boolean): void {
if (!open) emit('close');
}
</script>
<template>
<div v-if="visible && agent" class="admin-modal-overlay items-center">
<div class="admin-modal-panel max-w-3xl max-h-[90vh] animate-fade-in-up">
<div class="px-8 py-6 border-b border-subtle flex justify-between items-start">
<div>
<h3 class="text-lg font-bold text-primary">{{ t('admin.agent.testModalTitle') }}</h3>
<p class="section-desc mt-1">
{{ t('admin.agent.testModalAgent') }}:
<span class="font-medium text-blue-600">{{ agent.name }}</span>
</p>
<ElDialog
:model-value="visible && !!agent"
:title="t('admin.agent.testModalTitle')"
width="680px"
align-center
append-to-body
:close-on-click-modal="false"
@update:model-value="onVisibleChange"
>
<template v-if="agent">
<p class="section-desc">
{{ t('admin.agent.testModalAgent') }}:{{ agent.name }}
</p>
<div class="agent-test-body">
<div class="agent-test-toolbar">
<span v-if="result?.tested_at" class="hx-element-hint">{{ t('admin.agent.testedAt') }}:{{ result.tested_at }}</span>
<ElButton type="primary" :loading="isTesting" @click="emit('retest')">
{{ t('admin.agent.retest') }}
</ElButton>
</div>
<button type="button" class="btn-icon-ds rounded-full" @click="emit('close')">✕</button>
</div>
<div class="flex-1 overflow-y-auto p-8 space-y-5">
<div class="flex items-center justify-between">
<div class="text-sm text-secondary">
<span v-if="result?.tested_at">{{ t('admin.agent.testedAt') }}:{{ result.tested_at }}</span>
</div>
<button
type="button"
:disabled="isTesting"
class="btn-primary btn-sm disabled:opacity-50"
@click="emit('retest')"
>
{{ isTesting ? t('admin.agent.testing') : t('admin.agent.retest') }}
</button>
</div>
<div v-if="isTesting" class="text-sm text-muted">{{ t('admin.agent.testingInProgress') }}</div>
<p v-if="isTesting" class="hx-element-hint">{{ t('admin.agent.testingInProgress') }}</p>
<template v-if="result">
<div>
<div class="text-xs font-semibold text-muted uppercase tracking-wider mb-2">{{ t('admin.agent.requestUrl') }}</div>
<div class="hx-element-hint">{{ t('admin.agent.requestUrl') }}</div>
<div class="admin-code-block">{{ result.request_url || '-' }}</div>
</div>
<div>
<div class="text-xs font-semibold text-muted uppercase tracking-wider mb-2">{{ t('admin.agent.outputInfo') }}</div>
<pre class="admin-code-block max-h-64 overflow-y-auto whitespace-pre-wrap">{{ result.output_info || '-' }}</pre>
<div class="hx-element-hint">{{ t('admin.agent.outputInfo') }}</div>
<pre class="admin-code-block agent-test-output">{{ result.output_info || '-' }}</pre>
</div>
<div>
<div class="text-xs font-semibold text-muted uppercase tracking-wider mb-2">{{ t('admin.agent.analysis') }}</div>
<div
class="p-3 rounded-lg border text-sm"
:class="result.success ? 'bg-green-50 border-green-200 text-green-800' : 'bg-red-50 border-red-200 text-red-800'"
>
<div class="hx-element-hint">{{ t('admin.agent.analysis') }}</div>
<div class="agent-test-analysis" :class="result.success ? 'is-ok' : 'is-fail'">
{{ result.analysis }}
<span v-if="result.http_status">(HTTP {{ result.http_status }})</span>
</div>
</div>
</template>
</div>
</div>
</div>
</template>
</ElDialog>
</template>
<style scoped>
.agent-test-body {
display: flex;
flex-direction: column;
gap: 16px;
max-height: 65vh;
margin-top: 12px;
overflow-y: auto;
}
.agent-test-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.agent-test-output {
max-height: 16rem;
overflow-y: auto;
white-space: pre-wrap;
}
.agent-test-analysis {
padding: 12px;
border: 1px solid var(--el-border-color);
border-radius: var(--el-border-radius-base);
}
.agent-test-analysis.is-ok {
color: var(--el-color-success);
border-color: var(--el-color-success-light-5);
background: var(--el-color-success-light-9);
}
.agent-test-analysis.is-fail {
color: var(--el-color-danger);
border-color: var(--el-color-danger-light-5);
background: var(--el-color-danger-light-9);
}
</style>
@@ -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>
@@ -4,10 +4,12 @@
* Agent 管理模块的业务逻辑:列表 CRUD、连通性测试、权限分配。
* 从原 AdminView.vue 的 agents 相关 script 抽取,供 AgentsPage 使用。
* 权限组启用后拒绝打开按人授权弹窗,提示改到应用权限页的角色包。
* 删除确认使用 Element MessageBox。
*/
import { ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessageBox } from 'element-plus';
import {
createAdminAgent,
deleteAdminAgent,
@@ -238,6 +240,7 @@ export function useAgentsAdmin() {
const contentProfileOptions = ref<AdminContentProfileOption[]>([]);
const users = ref<AdminUserRow[]>([]);
const rolesConfigured = ref(false);
const rolesChecked = ref(false);
const scheduleTasks = ref<ScheduleTask[]>([]);
const trainingExamPdfGuides = ref<AgentGuideSummary[]>([]);
const isLoading = ref(true);
@@ -256,9 +259,6 @@ export function useAgentsAdmin() {
const permissionAgent = ref<AgentRow | null>(null);
const permissionUserIds = ref<number[]>([]);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
const activeUsers = () => users.value.filter((u) => u.status !== 'pending');
@@ -336,6 +336,8 @@ export function useAgentsAdmin() {
} catch (e) {
console.error('Error loading permission roles:', e);
rolesConfigured.value = false;
} finally {
rolesChecked.value = true;
}
};
@@ -364,18 +366,25 @@ export function useAgentsAdmin() {
}
};
/**
* 进入页面时先拉应用列表,再在后台补齐编辑弹窗要用的目录、用户和排程。
* 核心逻辑:加载遮罩只等应用列表。权限组、用户、排程和目录在后台拉取,未返回时不盖住表格。
*/
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await Promise.all([
try {
await loadAgents();
} finally {
isLoading.value = false;
}
void Promise.all([
loadRegistrySchema(),
loadIntentRouteOptions(),
loadContentProfileOptions(),
loadAgents(),
loadUsers(),
loadRolesConfigured(),
loadScheduleTasks(),
]);
isLoading.value = false;
};
const resetForm = (): void => {
@@ -405,27 +414,26 @@ export function useAgentsAdmin() {
void loadTrainingExamPdfGuides(agent.id);
};
const openDeleteConfirm = (
/**
* 用 Element 确认框询问后再执行删除。
* 核心逻辑:取消时 MessageBox 会 reject,这里吞掉,不调用 action。
* @param message - 确认文案
* @param action - 用户点确定后执行的删除
*/
const openDeleteConfirm = async (
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;
): Promise<void> => {
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
await ElMessageBox.confirm(message, t('common.deleteDialog.defaultTitle'), {
type: 'warning',
confirmButtonText: t('common.deleteDialog.confirm'),
cancelButtonText: t('common.deleteDialog.cancel'),
});
} catch {
return;
}
await action();
};
/**
@@ -613,7 +621,7 @@ export function useAgentsAdmin() {
};
const deleteAgent = async (id: number): Promise<void> => {
openDeleteConfirm(t('admin.agent.confirmDelete'), async () => {
await openDeleteConfirm(t('admin.agent.confirmDelete'), async () => {
try {
await deleteAdminAgent(id);
await loadAgents();
@@ -723,6 +731,7 @@ export function useAgentsAdmin() {
contentProfileOptions,
users,
rolesConfigured,
rolesChecked,
scheduleTasks,
trainingExamPdfGuides,
activeUsers,
@@ -739,8 +748,6 @@ export function useAgentsAdmin() {
showPermissionModal,
permissionAgent,
permissionUserIds,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
resetForm,
selectAgent,
@@ -758,7 +765,5 @@ export function useAgentsAdmin() {
openPermissionModal,
togglePermissionUser,
savePermissions,
closeDeleteConfirm,
confirmDelete,
};
}
@@ -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>
@@ -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,
};
@@ -261,7 +261,7 @@ watch(
type="date"
:value="params[field.key] ?? ''"
class="input-field w-full !text-sm !leading-5"
@input="setField(field.key, ($event.target as HTMLInputElement).value)"
@input="setField(field.key, ($event.target as HTMLInputElement).value === '' ? null : ($event.target as HTMLInputElement).value)"
/>
<input
v-else-if="field.type === 'datetime'"
@@ -341,7 +341,7 @@ watch(
v-model="multiSearch[field.key]"
type="text"
class="mb-1 w-full rounded-lg border border-default px-2 py-1.5 text-sm outline-none focus:border-blue-500"
:placeholder="$t('admin.schedule.form.dynamicParamsSearchPlaceholder')"
:placeholder="resolveText(field.placeholder_key, field.placeholder) || $t('admin.schedule.form.dynamicParamsSearchPlaceholder')"
/>
<p v-if="optionsLoading[field.options_source || '']" class="px-2 py-1 text-xs text-muted">
{{ $t('admin.schedule.form.dynamicParamsOptionsLoading') }}
@@ -877,7 +877,6 @@ onMounted(() => {
}
.edit-card .input-field, .impact-dialog .input-field, .impact-dialog .select-field { min-width: 0; padding: 8px 9px; font: inherit; font-size: 13px; }
.actions, .impact-dialog footer { display: flex; flex-wrap: wrap; gap: 8px; }
.impact-dialog footer { justify-content: flex-end; }
.link-list, .plain-list { margin: 0; padding-left: 1.1rem; color: #475569; font-size: 13px; }
.adoption-link { color: #0369a1; text-decoration: underline; text-underline-offset: 2px; }
.adoption-link:hover { color: #0c4a6e; }
@@ -924,10 +923,12 @@ onMounted(() => {
background: var(--overlay-soft); padding: 24px;
}
.impact-dialog {
display: grid; width: min(520px, 96vw); max-height: 82vh; gap: 14px; overflow: auto;
display: grid; grid-auto-rows: max-content; width: min(520px, 96vw); max-height: 82vh; gap: 14px; overflow-y: auto;
border-radius: 12px; background: #fff; padding: 18px; box-shadow: 0 24px 64px rgb(15 23 42 / .24);
}
.impact-dialog header { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
/* footer 用 sticky 钉在对话框可视底部:内容超高时确认/取消始终可见,不随表单或影响列表滚动消失(负 margin 抵消对话框 padding 实现通栏) */
.impact-dialog footer { position: sticky; bottom: -18px; justify-content: flex-end; margin: 4px -18px -18px; border-top: 1px solid var(--border-default); background: #fff; padding: 12px 18px; }
.impact-dialog h2, .impact-dialog p { margin: 0; }
.impact-summary {
display: grid; gap: 8px; border: 1px solid #fecaca; border-radius: 8px;
@@ -316,14 +316,15 @@ onMounted(() => { void load(); });
.identity-hero h1 { margin: 0; }
.identity-hero p { max-width: 760px; }
.identity-hero__meta { display: flex; align-items: center; gap: .75rem; flex-wrap: wrap; justify-content: flex-end; }
.identity-hero__status { display: inline-flex; align-items: center; gap: .48rem; padding: .5rem .75rem; border: 1px solid #bfe7f8; border-radius: 999px; background: #effaff; color: #087aaa; font-size: .78rem; font-weight: 700; white-space: nowrap; }
.identity-pulse { width: .5rem; height: .5rem; border-radius: 50%; background: #18b17c; box-shadow: 0 0 0 4px #dff8ed; }.identity-pulse--draft { background: #e09b22; box-shadow: 0 0 0 4px #fff2d5; }
/* 状态/品牌色统一 Tailwind 标准语义值(brand=sky 系 #0284c7、启用=green、草稿=amber),不再使用自造蓝绿 */
.identity-hero__status { display: inline-flex; align-items: center; gap: .48rem; padding: .5rem .75rem; border: 1px solid #bae6fd; border-radius: 999px; background: #f0f9ff; color: #0369a1; font-size: .78rem; font-weight: 700; white-space: nowrap; }
.identity-pulse { width: .5rem; height: .5rem; border-radius: 50%; background: #10b981; box-shadow: 0 0 0 4px #d1fae5; }.identity-pulse--draft { background: #f59e0b; box-shadow: 0 0 0 4px #fef3c7; }
.identity-hero__link { display: inline-flex; align-items: center; gap: .35rem; white-space: nowrap; }
.identity-flow { position: relative; display: grid; grid-template-columns: repeat(3, 1fr); gap: .6rem; padding: 1rem; overflow: hidden; border: 1px solid #dce9f2; border-radius: 1rem; background: linear-gradient(105deg, #f4fbff, #fff); }
.identity-flow__rail { position: absolute; top: 1.84rem; left: 12%; right: 12%; height: 1px; background: #cce5f2; }
.identity-flow__step { position: relative; z-index: 1; display: flex; gap: .75rem; align-items: flex-start; min-width: 0; }
.identity-flow__step > span { display: grid; place-items: center; flex: 0 0 1.65rem; height: 1.65rem; border: 1px solid #b9d8e8; border-radius: 50%; background: #fff; color: #6b8298; font-size: .66rem; font-weight: 800; }
.identity-flow__step--active > span { border-color: #0d93cf; background: #0d93cf; color: #fff; box-shadow: 0 0 0 4px #dff4fc; }
.identity-flow__step--active > span { border-color: #0284c7; background: #0284c7; color: #fff; box-shadow: 0 0 0 4px #e0f2fe; }
.identity-flow strong { display: block; color: #193652; font-size: .82rem; font-weight: 800; }
.identity-flow small { display: -webkit-box; overflow: hidden; margin-top: .15rem; color: #7a8fa6; font-size: .72rem; line-height: 1.45; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
.identity-loading { display: flex; align-items: center; gap: .5rem; padding: 2rem; color: #6f839b; font-size: .9rem; }
@@ -336,12 +337,12 @@ onMounted(() => { void load(); });
.identity-definition-list { display: grid; }
.identity-definition-row { display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto; gap: .75rem; align-items: center; padding: .78rem 1.35rem; border-bottom: 1px solid #edf3f7; transition: background .18s ease; }
.identity-definition-row:hover { background: #f7fbfd; }
.identity-definition-row__icon { display: grid; place-items: center; width: 2rem; height: 2rem; border-radius: .6rem; background: #e9f7fd; color: #0b90cc; }
.identity-definition-row__icon { display: grid; place-items: center; width: 2rem; height: 2rem; border-radius: .6rem; background: #f0f9ff; color: #0284c7; }
.identity-definition-row strong { color: #1a3856; font-size: .86rem; font-weight: 750; }
.identity-definition-row p { overflow: hidden; margin-top: .18rem; color: #8194a8; font-size: .72rem; text-overflow: ellipsis; white-space: nowrap; }
.identity-target, .identity-automation { padding: .32rem .52rem; border-radius: 999px; background: #f1f5f8; color: #677f98; font-size: .7rem; white-space: nowrap; }
.identity-automation-select { border: 1px solid #dce8ef; cursor: pointer; }
.identity-automation--enabled { background: #e4f8ef; color: #12865c; }
.identity-automation--enabled { background: #dcfce7; color: #15803d; }
.identity-empty { display: flex; align-items: center; gap: .55rem; min-height: 5.5rem; padding: 1.2rem 1.35rem; color: #7c91a7; font-size: .82rem; }
.identity-definition-form { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .85rem; padding: 1.1rem 1.35rem 1.35rem; background: linear-gradient(135deg, #f7fbfd 0%, #f3f9fc 100%); }
.identity-form-title { grid-column: 1 / -1; display: flex; align-items: center; gap: .42rem; color: #173857; font-size: .85rem; }
@@ -349,13 +350,13 @@ onMounted(() => { void load(); });
.identity-definition-form label { display: grid; gap: .35rem; color: #667f99; font-size: .72rem; font-weight: 700; }
.identity-label-with-tip { display: inline-flex; align-items: center; gap: .28rem; }
.identity-label-tip { width: .9rem; height: .9rem; color: #7d93a8; cursor: help; }
.identity-label-tip:focus-visible { border-radius: 50%; outline: 2px solid #7cc7eb; outline-offset: 2px; }
.identity-label-tip:focus-visible { border-radius: 50%; outline: 2px solid #7dd3fc; outline-offset: 2px; }
.identity-definition-form label small { color: #8295a8; font-size: .67rem; font-weight: 500; line-height: 1.35; }
.identity-definition-form .input-field, .identity-static-field { box-sizing: border-box; min-width: 0; height: 2.75rem; padding: 0 .8rem; border-color: #d9e7ef; background: #fff; font-size: .83rem; line-height: 1.25; }
.identity-definition-form select.input-field { padding-top: 0; padding-bottom: 0; line-height: 2.75rem; }
.identity-static-field { display: flex; align-items: center; padding: 0 .8rem; border: 1px solid #d9e7ef; border-radius: .65rem; color: #5f7893; }
.identity-source-help { display: grid; align-content: center; gap: .12rem; min-height: 2.75rem; padding: .48rem .7rem; border: 1px solid #d6eaf5; border-radius: .65rem; background: #edf8fe; color: #537189; font-size: .69rem; line-height: 1.35; }
.identity-source-help strong { color: #187eae; font-size: .72rem; }.identity-source-help small { color: #2e9068; font-size: .68rem; }
.identity-source-help strong { color: #0369a1; font-size: .72rem; }.identity-source-help small { color: #16a34a; font-size: .68rem; }
.identity-definition-form__submit { display: inline-flex; align-items: center; justify-content: center; gap: .4rem; align-self: end; min-height: 2.5rem; }
.identity-panel--publication { position: sticky; top: 1rem; padding: 1.25rem; }
.identity-publication__header { display: flex; align-items: center; justify-content: space-between; gap: .75rem; }
@@ -363,7 +364,7 @@ onMounted(() => { void load(); });
.identity-publication__hint { margin: .75rem 0 1rem; color: #75899f; font-size: .78rem; line-height: 1.6; }
.identity-version-list { display: flex; flex-wrap: wrap; gap: .5rem; padding-bottom: 1rem; border-bottom: 1px solid #e9f0f4; }
.identity-version { display: inline-flex; align-items: center; gap: .35rem; padding: .46rem .6rem; border: 1px solid #dbe7ee; border-radius: .6rem; background: #fff; color: #668099; font-size: .73rem; transition: all .18s ease; }
.identity-version:hover, .identity-version--selected { border-color: #0b91cd; background: #eefaff; color: #087cae; }
.identity-version:hover, .identity-version--selected { border-color: #0284c7; background: #f0f9ff; color: #0369a1; }
.identity-version span { font-weight: 800; }.identity-version small { font-size: .68rem; }
.identity-selection { margin: 1rem 0; }
.identity-published-definitions { margin: 1rem 0; }
@@ -374,12 +375,13 @@ onMounted(() => { void load(); });
.identity-published-definition small { margin-top: .15rem; color: #8194a8; font-size: .68rem; }
.identity-published-empty { margin: 0; color: #8194a8; font-size: .76rem; }
.identity-selection__heading { display: flex; justify-content: space-between; margin-bottom: .6rem; color: #274563; font-size: .78rem; font-weight: 750; }
.identity-selection__heading strong { color: #0a8bc4; }
.identity-selection__heading strong { color: #0284c7; }
.identity-check-row { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: .5rem; padding: .54rem 0; border-bottom: 1px dashed #e2ebf1; color: #37516c; font-size: .78rem; }
.identity-check-row input { accent-color: #0c94ce; }.identity-check-row small { color: #8496a8; font-size: .68rem; }
/* @tailwindcss/forms 接管原生 checkbox 后 accent-color 无效:勾选填充取 currentColor,用 color 指定选中蓝 */
.identity-check-row input { color: #0284c7; }.identity-check-row small { color: #8496a8; font-size: .68rem; }
.identity-publication__actions { display: grid; grid-template-columns: 1fr 1fr; gap: .65rem; padding-top: 1rem; }
.identity-publication__actions .btn-primary, .identity-publication__actions .btn-ghost { min-width: 0; font-size: .79rem; }
.identity-published { grid-column: 1 / -1; display: grid; grid-template-columns: auto auto minmax(0, 1fr); align-items: center; gap: .45rem; padding: .7rem; border-radius: .65rem; background: #eaf9f0; color: #16895e; font-size: .78rem; font-weight: 700; }.identity-published code { overflow: hidden; color: #56826f; font-size: .67rem; text-align: right; text-overflow: ellipsis; white-space: nowrap; }
.identity-published { grid-column: 1 / -1; display: grid; grid-template-columns: auto auto minmax(0, 1fr); align-items: center; gap: .45rem; padding: .7rem; border-radius: .65rem; background: #dcfce7; color: #15803d; font-size: .78rem; font-weight: 700; }.identity-published code { overflow: hidden; color: #16a34a; font-size: .67rem; text-align: right; text-overflow: ellipsis; white-space: nowrap; }
@media (max-width: 980px) { .identity-workbench { grid-template-columns: 1fr; }.identity-panel--publication { position: static; }.identity-hero { align-items: flex-start; flex-direction: column; gap: .85rem; }.identity-hero__meta { justify-content: flex-start; }.identity-flow__rail { display: none; } }
@media (max-width: 700px) { .identity-rules-page { gap: 1rem; }.identity-flow { grid-template-columns: 1fr; }.identity-definition-form { grid-template-columns: 1fr; }.identity-definition-row { grid-template-columns: auto minmax(0, 1fr); }.identity-target, .identity-automation { justify-self: start; }.identity-panel__heading { align-items: flex-start; flex-direction: column; }.identity-panel__heading > p { text-align: left; }.identity-definition-row__icon { grid-row: span 2; }.identity-publication__actions { grid-template-columns: 1fr; } }
@media (prefers-reduced-motion: reduce) { .identity-definition-row, .identity-version { transition: none; } }
@@ -146,8 +146,8 @@
<input v-model="parameter.name" class="input-field" :placeholder="t('admin.shippingInventory.parameterName')">
<select v-model="parameter.mode" class="select-field"><option value="single">{{ t('admin.shippingInventory.single') }}</option><option value="multi_text">{{ t('admin.shippingInventory.multiText') }}</option><option value="multi_select">{{ t('admin.shippingInventory.multiSelect') }}</option></select>
<input class="input-field" :value="parameter.values.join(', ')" :placeholder="t('admin.shippingInventory.parameterValues')" @input="parameter.values = splitValues(($event.target as HTMLInputElement).value)">
<label class="inline-check"><input v-model="parameter.required" type="checkbox">{{ t('admin.shippingInventory.required') }}</label>
<label class="inline-check"><input v-model="parameter.select_all" type="checkbox">{{ t('admin.shippingInventory.selectAll') }}</label>
<label class="inline-check"><input v-model="parameter.required" type="checkbox" class="admin-checkbox">{{ t('admin.shippingInventory.required') }}</label>
<label class="inline-check"><input v-model="parameter.select_all" type="checkbox" class="admin-checkbox">{{ t('admin.shippingInventory.selectAll') }}</label>
<button type="button" class="btn-danger btn-sm" @click="source.query_parameters_json.splice(index, 1)">{{ t('admin.delete') }}</button>
</div>
<button type="button" class="btn-secondary btn-sm full" @click="addParameter">{{ t('admin.shippingInventory.addParameter') }}</button>
@@ -172,8 +172,8 @@
<input v-model="parameter.name" class="input-field" :placeholder="t('admin.shippingInventory.parameterName')">
<select v-model="parameter.mode" class="select-field"><option value="single">{{ t('admin.shippingInventory.single') }}</option><option value="multi_text">{{ t('admin.shippingInventory.multiText') }}</option><option value="multi_select">{{ t('admin.shippingInventory.multiSelect') }}</option></select>
<input class="input-field" :value="parameter.values.join(', ')" :placeholder="t('admin.shippingInventory.parameterValues')" @input="parameter.values = splitValues(($event.target as HTMLInputElement).value)">
<label class="inline-check"><input v-model="parameter.required" type="checkbox">{{ t('admin.shippingInventory.required') }}</label>
<label class="inline-check"><input v-model="parameter.select_all" type="checkbox">{{ t('admin.shippingInventory.selectAll') }}</label>
<label class="inline-check"><input v-model="parameter.required" type="checkbox" class="admin-checkbox">{{ t('admin.shippingInventory.required') }}</label>
<label class="inline-check"><input v-model="parameter.select_all" type="checkbox" class="admin-checkbox">{{ t('admin.shippingInventory.selectAll') }}</label>
<button type="button" class="btn-danger btn-sm" @click="receiptConfig.query_parameters_json.splice(index, 1)">{{ t('admin.delete') }}</button>
</div>
<button type="button" class="btn-secondary btn-sm full" @click="addReceiptParameter">{{ t('admin.shippingInventory.addParameter') }}</button>
@@ -356,7 +356,8 @@
<div class="switch-field"><span>{{ t('admin.shippingInventory.enabled') }}</span><button type="button" class="status-switch" :class="{ on: mapping.enabled }" role="switch" :aria-checked="mapping.enabled" @click="mapping.enabled = !mapping.enabled"><i></i><b>{{ mapping.enabled ? t('admin.shippingInventory.enabledState') : t('admin.shippingInventory.disabledState') }}</b></button></div>
</template>
<div v-if="isEditableTab" class="form-actions full">
</form>
<div v-if="isEditableTab" class="form-actions">
<div
v-if="activeTab === 'sources' && selectedId"
class="source-enabled-footer"
@@ -385,7 +386,7 @@
}}</small>
</div>
<div class="form-actions-buttons">
<button v-if="!parsingReadOnly" type="submit" class="btn-primary" :disabled="saving || ruleReadOnly || templateReadOnly || inventoryFieldReadOnly">{{ saving ? t('admin.shippingInventory.saving') : t('admin.save') }}</button>
<button v-if="!parsingReadOnly" type="button" class="btn-primary" :disabled="saving || ruleReadOnly || templateReadOnly || inventoryFieldReadOnly" @click="saveCurrent">{{ saving ? t('admin.shippingInventory.saving') : t('admin.save') }}</button>
<button v-if="activeTab === 'rules' && selectedId && selectedRuleStatus === 'draft'" type="button" class="btn-secondary btn-sm" @click="publishCurrentRule">{{ t('admin.shippingInventory.publish') }}</button>
<button v-if="activeTab === 'rules' && selectedId && selectedRuleStatus === 'published'" type="button" class="btn-secondary btn-sm" @click="retireCurrentRule">{{ t('admin.shippingInventory.retire') }}</button>
<button v-if="activeTab === 'templates' && selectedId && selectedTemplateStatus === 'draft'" type="button" class="btn-secondary btn-sm" @click="publishCurrentTemplate">{{ t('admin.shippingInventory.publishTemplate') }}</button>
@@ -399,7 +400,6 @@
<button type="button" class="btn-ghost btn-sm" @click="closeDrawer">{{ t('admin.cancel') }}</button>
</div>
</div>
</form>
</aside>
</div>
</div>
@@ -1653,23 +1653,28 @@ onMounted(load);
.row-secondary { color: #94a3b8; font-size: 11px; }
.status-dot { position: absolute; top: 18px; right: 12px; width: 7px; height: 7px; border-radius: 50%; }
.status-dot.on { background: #22c55e; }
.status-dot.off { background: #b2bdc9; }
.status-dot.off { background: #94a3b8; }
.drawer-mask { position: fixed; z-index: 40; inset: 0; display: flex; justify-content: flex-end; background: var(--overlay-soft); }
.workbench-actions { display: flex; flex-wrap: wrap; gap: 10px; }
.clone-template-mask { z-index: 80; align-items: center; justify-content: center; padding: 20px; }
.clone-template-dialog { width: min(480px, 100%); border-radius: 10px; background: #fff; box-shadow: 0 18px 48px rgb(15 23 42 / 25%); }
.clone-template-header { display: flex; justify-content: space-between; gap: 16px; border-bottom: 1px solid #e2e8f0; padding: 18px 20px; }.clone-template-header h3 { margin: 0; color: #1e293b; font-size: 16px; font-weight: 600; }.clone-template-header p { margin: 5px 0 0; color: #64748b; font-size: 12px; line-height: 1.5; }
.clone-template-form { display: grid; gap: 14px; padding: 20px; }.clone-template-form label { display: grid; gap: 6px; color: #64748b; font-size: 12px; font-weight: 500; }.clone-template-form .input-field { min-width: 0; padding: 8px 9px; font: inherit; font-size: 13px; }.clone-template-form small { color: #94a3b8; font-size: 11px; line-height: 1.45; }.clone-template-actions { display: flex; justify-content: flex-end; gap: 10px; border-top: 1px solid #edf2f7; padding-top: 14px; }
.batch-validation-dialog { display: grid; width: min(780px, 100%); max-height: min(720px, calc(100vh - 40px)); grid-template-rows: auto minmax(0, 1fr); overflow: hidden; border-radius: 12px; background: #fff; box-shadow: 0 20px 56px rgb(15 23 42 / 28%); }.batch-selection, .batch-progress { display: grid; min-height: 0; gap: 14px; padding: 18px 20px; }.batch-selection { grid-template-rows: auto minmax(0, 1fr) auto; }.batch-selection-toolbar { display: flex; align-items: end; justify-content: space-between; gap: 14px; }.batch-selection-toolbar label { display: grid; flex: 1; gap: 5px; color: #62788a; font-size: 11px; font-weight: 700; }.batch-selection-toolbar .input-field { min-width: 0; padding: 8px 9px; font: inherit; font-size: 13px; }.batch-selection-actions { display: flex; align-items: center; gap: 8px; }.batch-selection-actions > b { flex: 0 0 auto; border-radius: 999px; background: #e9f7fd; padding: 6px 9px; color: #13759d; font-size: 11px; white-space: nowrap; }.batch-selection-actions .btn-ghost { padding: 6px 8px; white-space: nowrap; }.batch-source-list, .batch-run-list { min-height: 0; overflow-y: auto; border: 1px solid #dce8ef; border-radius: 8px; background: #fbfdfe; }.batch-source-list { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); align-content: start; gap: 1px; background: #e3edf3; }.batch-source-option { display: flex; min-width: 0; align-items: flex-start; gap: 9px; background: #fff; padding: 10px 11px; cursor: pointer; }.batch-source-option:hover { background: #f4fbfe; }.batch-source-option input { margin: 3px 0 0; accent-color: #168ebc; }.batch-source-option span { display: grid; min-width: 0; gap: 3px; }.batch-source-option b { overflow: hidden; color: #344b60; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }.batch-source-option small { overflow: hidden; color: #8a9aab; font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }.batch-empty { grid-column: 1 / -1; margin: 0; padding: 28px 12px; color: #8797a7; font-size: 12px; text-align: center; }.batch-progress { grid-template-rows: auto auto auto minmax(0, 1fr) auto; }.batch-progress-heading { display: flex; align-items: end; justify-content: space-between; gap: 16px; }.batch-progress-heading > div { display: grid; gap: 3px; }.batch-progress-heading span { color: #16759f; font-size: 11px; font-weight: 800; }.batch-progress-heading strong { color: #334c60; font-size: 13px; }.batch-progress-heading > b { color: #1c6f96; font-size: 18px; font-variant-numeric: tabular-nums; }.batch-progress-bar { height: 7px; overflow: hidden; border-radius: 999px; background: #e8f0f5; }.batch-progress-bar i { display: block; height: 100%; border-radius: inherit; background: linear-gradient(90deg, #22a1c7, #4bb8d7); transition: width .25s ease; }.batch-stat-grid { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 6px; }.batch-stat-grid button { display: grid; gap: 2px; border: 1px solid #e0eaf0; border-radius: 7px; background: #fff; padding: 8px; color: #708393; font: inherit; text-align: left; cursor: pointer; }.batch-stat-grid button:hover, .batch-stat-grid button.active { border-color: #8fd0e7; background: #eef9fd; }.batch-stat-grid b { color: #314b60; font-size: 16px; font-variant-numeric: tabular-nums; }.batch-stat-grid span { overflow: hidden; font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }.batch-run-list { display: grid; align-content: start; }.batch-run { display: grid; grid-template-columns: 9px minmax(0, 1fr) minmax(0, .9fr); align-items: center; gap: 9px; border-bottom: 1px solid #e8eff3; padding: 9px 11px; }.batch-run:last-child { border-bottom: 0; }.batch-run-marker { width: 7px; height: 7px; border-radius: 50%; background: #a9b8c5; }.batch-run > div { display: grid; min-width: 0; gap: 2px; }.batch-run b, .batch-run small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.batch-run b { color: #385166; font-size: 12px; }.batch-run > div small { color: #8a9baa; font-size: 10px; }.batch-run-error { color: #ae493b; font-size: 10px; }.batch-run.is-completed .batch-run-marker { background: #32a665; }.batch-run.is-completed_empty .batch-run-marker { background: #e7a628; }.batch-run.is-failed .batch-run-marker { background: #db6552; }
.editor-drawer { width: min(760px, 100vw); height: 100%; overflow-y: auto; border-left: 1px solid var(--border-default); background: var(--bg-surface); box-shadow: -12px 0 32px rgb(15 23 42 / 18%); }
.drawer-header { position: sticky; z-index: 1; top: 0; display: flex; justify-content: space-between; gap: 16px; border-bottom: 1px solid var(--border-default); background: var(--bg-surface); padding: 18px 20px; }
.drawer-title-row { display: flex; align-items: center; gap: 9px; }.drawer-header h3 { margin: 0; color: #1e293b; font-size: 16px; font-weight: 600; }.source-run-status { flex: 0 0 auto; border: 1px solid #f2d3cd; border-radius: 999px; background: #fff4f1; padding: 3px 7px; color: #a53f30; font-size: 11px; font-weight: 700; }.source-run-status.enabled { border-color: #c7e7d0; background: #eefaf1; color: #247442; }
.batch-validation-dialog { display: grid; width: min(780px, 100%); max-height: min(720px, calc(100vh - 40px)); grid-template-rows: auto minmax(0, 1fr); overflow: hidden; border-radius: 12px; background: #fff; box-shadow: 0 20px 56px rgb(15 23 42 / 28%); }.batch-selection, .batch-progress { display: grid; min-height: 0; gap: 14px; padding: 18px 20px; }.batch-selection { grid-template-rows: auto minmax(0, 1fr) auto; }.batch-selection-toolbar { display: flex; align-items: end; justify-content: space-between; gap: 14px; }.batch-selection-toolbar label { display: grid; flex: 1; gap: 5px; color: #62788a; font-size: 11px; font-weight: 700; }.batch-selection-toolbar .input-field { min-width: 0; padding: 8px 9px; font: inherit; font-size: 13px; }.batch-selection-actions { display: flex; align-items: center; gap: 8px; }.batch-selection-actions > b { flex: 0 0 auto; border-radius: 999px; background: #e9f7fd; padding: 6px 9px; color: #13759d; font-size: 11px; white-space: nowrap; }.batch-selection-actions .btn-ghost { padding: 6px 8px; white-space: nowrap; }.batch-source-list, .batch-run-list { min-height: 0; overflow-y: auto; border: 1px solid #dce8ef; border-radius: 8px; background: #fbfdfe; }.batch-source-list { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); align-content: start; gap: 1px; background: #e3edf3; }.batch-source-option { display: flex; min-width: 0; align-items: flex-start; gap: 9px; background: #fff; padding: 10px 11px; cursor: pointer; }.batch-source-option:hover { background: #f4fbfe; }/* accent-color 在 @tailwindcss/forms 接管的原生 checkbox 上无效:勾选填充取 currentColor,用 color 指定选中蓝色 */
.batch-source-option input { margin: 3px 0 0; color: #168ebc; }.batch-source-option span { display: grid; min-width: 0; gap: 3px; }.batch-source-option b { overflow: hidden; color: #344b60; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }.batch-source-option small { overflow: hidden; color: #8a9aab; font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }.batch-empty { grid-column: 1 / -1; margin: 0; padding: 28px 12px; color: #8797a7; font-size: 12px; text-align: center; }.batch-progress { grid-template-rows: auto auto auto minmax(0, 1fr) auto; }.batch-progress-heading { display: flex; align-items: end; justify-content: space-between; gap: 16px; }.batch-progress-heading > div { display: grid; gap: 3px; }.batch-progress-heading span { color: #16759f; font-size: 11px; font-weight: 800; }.batch-progress-heading strong { color: #334c60; font-size: 13px; }.batch-progress-heading > b { color: #1c6f96; font-size: 18px; font-variant-numeric: tabular-nums; }.batch-progress-bar { height: 7px; overflow: hidden; border-radius: 999px; background: #e8f0f5; }.batch-progress-bar i { display: block; height: 100%; border-radius: inherit; background: linear-gradient(90deg, #22a1c7, #4bb8d7); transition: width .25s ease; }.batch-stat-grid { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 6px; }.batch-stat-grid button { display: grid; gap: 2px; border: 1px solid #e0eaf0; border-radius: 7px; background: #fff; padding: 8px; color: #708393; font: inherit; text-align: left; cursor: pointer; }.batch-stat-grid button:hover, .batch-stat-grid button.active { border-color: #8fd0e7; background: #eef9fd; }.batch-stat-grid b { color: #314b60; font-size: 16px; font-variant-numeric: tabular-nums; }.batch-stat-grid span { overflow: hidden; font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }.batch-run-list { display: grid; align-content: start; }.batch-run { display: grid; grid-template-columns: 9px minmax(0, 1fr) minmax(0, .9fr); align-items: center; gap: 9px; border-bottom: 1px solid #e8eff3; padding: 9px 11px; }.batch-run:last-child { border-bottom: 0; }.batch-run-marker { width: 7px; height: 7px; border-radius: 50%; background: #a9b8c5; }.batch-run > div { display: grid; min-width: 0; gap: 2px; }.batch-run b, .batch-run small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.batch-run b { color: #385166; font-size: 12px; }.batch-run > div small { color: #8a9baa; font-size: 10px; }.batch-run-error { color: #ae493b; font-size: 10px; }.batch-run.is-completed .batch-run-marker { background: #32a665; }.batch-run.is-completed_empty .batch-run-marker { background: #e7a628; }.batch-run.is-failed .batch-run-marker { background: #db6552; }
/* 抽屉为 flex 三段式:头部/底部操作栏固定,.editor-form 独占剩余高度并内部滚动,操作栏位置不受内容增减影响 */
.editor-drawer { display: flex; flex-direction: column; width: min(760px, 100vw); height: 100%; overflow: hidden; border-left: 1px solid var(--border-default); background: var(--bg-surface); box-shadow: -12px 0 32px rgb(15 23 42 / 18%); }
.drawer-header { flex: 0 0 auto; display: flex; justify-content: space-between; gap: 16px; border-bottom: 1px solid var(--border-default); background: var(--bg-surface); padding: 18px 20px; }
/* 状态徽标统一 Tailwind 标准语义色:未启用=rose(与 components-ds 危险态一致)、启用=green(与 .status-switch 一致),不再用自造色值 */
.drawer-title-row { display: flex; align-items: center; gap: 9px; }.drawer-header h3 { margin: 0; color: #1e293b; font-size: 16px; font-weight: 600; }.source-run-status { flex: 0 0 auto; border: 1px solid #fecdd3; border-radius: 999px; background: #fff1f2; padding: 3px 7px; color: #be123c; font-size: 11px; font-weight: 700; }.source-run-status.enabled { border-color: #bbf7d0; background: #f0fdf4; color: #15803d; }
.drawer-header p { margin: 5px 0 0; color: #64748b; font-size: 12px; line-height: 1.5; }
.drawer-close { width: 30px; height: 30px; border: 0; border-radius: 6px; background: transparent; color: #64748b; font-size: 24px; line-height: 1; cursor: pointer; }
.drawer-close:hover { background: #f1f5f9; color: #334155; }
.editor-form { display: grid; align-content: start; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; padding: 20px; }
/* grid-auto-rows 必须 max-content:本表单是受限高度的滚动网格,Chrome 会把包含 overflow:hidden 子项(.path-card)的隐式 auto 行压缩到远小于内容的高度,裁掉查询条件/按钮;显式 max-content 强制行高按内容 sizing */
.editor-form { flex: 1 1 auto; min-height: 0; overflow-y: auto; display: grid; grid-auto-rows: max-content; align-content: start; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; padding: 20px; }
.editor-form label { display: flex; flex-direction: column; gap: 6px; color: #64748b; font-size: 12px; font-weight: 500; }
.editor-form input, .editor-form select { min-width: 0; border: 1px solid var(--border-default); border-radius: 6px; background: var(--bg-surface); padding: 8px 9px; color: var(--text-secondary); font: inherit; font-size: 13px; font-weight: 400; }
/* checkbox/radio 必须排除:此处的 color 与 background 简写优先级更高,会覆盖 @tailwindcss/forms 的 :checked 样式(填充取 currentColor + 白色对钩背景图),导致勾选态与未勾选态渲染完全一致、无法分辨 */
.editor-form input:not([type='checkbox']):not([type='radio']), .editor-form select { min-width: 0; border: 1px solid var(--border-default); border-radius: 6px; background: var(--bg-surface); padding: 8px 9px; color: var(--text-secondary); font: inherit; font-size: 13px; font-weight: 400; }
.editor-form small { color: #94a3b8; font-size: 11px; font-weight: 400; line-height: 1.45; }
.inventory-mapping-tabs { display: flex; gap: 4px; margin: 0 0 14px; border-bottom: 1px solid #e2e8f0; }
.inventory-mapping-tabs button { border: 0; border-bottom: 2px solid transparent; background: transparent; padding: 8px 12px; color: #64748b; font: inherit; font-size: 13px; cursor: pointer; }
@@ -1698,7 +1703,7 @@ onMounted(load);
.path-card { display: grid; grid-column: 1 / -1; border: 1px solid #dbe8ee; border-radius: 10px; background: #fff; overflow: hidden; }
.path-card-header { display: flex; align-items: center; gap: 10px; border: 0; background: #f7fbfd; padding: 10px 12px; cursor: pointer; font: inherit; text-align: left; }.path-card-header:hover { background: #eff7fa; }
.path-card-title { display: grid; flex: 1 1 auto; min-width: 0; gap: 2px; }.path-card-title b { color: #145f5a; font-size: 12px; font-weight: 800; }.path-card-title small { color: #94a3b8; font-size: 11px; font-weight: 400; }
.path-badge { flex: 0 0 auto; border-radius: 999px; background: #eef2f5; padding: 3px 8px; color: #7b8998; font-size: 11px; font-weight: 700; }.path-card.configured .path-badge.on { background: #e6f6ec; color: #19703a; }
.path-badge { flex: 0 0 auto; border-radius: 999px; background: #f1f5f9; padding: 3px 8px; color: #64748b; font-size: 11px; font-weight: 700; }.path-card.configured .path-badge.on { background: #dcfce7; color: #15803d; }
.path-card-toggle { flex: 0 0 auto; color: #4d849f; font-size: 14px; line-height: 1; }
.path-card-body { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; border-top: 1px solid #e6eef4; padding: 14px 12px; }.path-card-body .full { grid-column: 1 / -1; }
.condition-row, .mapping-row, .template-mapping { display: grid; align-items: center; gap: 8px; border-radius: 8px; background: #f8fafc; padding: 9px; }
@@ -1727,7 +1732,8 @@ onMounted(load);
.condition-empty { color: #8190a0; font-size: 12px; }
.inline-check { flex-direction: row !important; align-items: center; gap: 4px !important; white-space: nowrap; font-size: 11px !important; }
.switch-field { display: flex; flex-direction: column; gap: 6px; color: #64748b; font-size: 12px; font-weight: 500; }.status-switch { display: inline-flex; width: fit-content; align-items: center; gap: 7px; border: 0; background: transparent; padding: 2px 0; color: #94a3b8; font: inherit; font-size: 12px; cursor: pointer; }.status-switch i { position: relative; width: 34px; height: 20px; border-radius: 999px; background: #cbd5e1; transition: background .18s; }.status-switch i::after { position: absolute; top: 3px; left: 3px; width: 14px; height: 14px; border-radius: 50%; background: #fff; box-shadow: 0 1px 2px rgb(15 23 42 / 25%); content: ''; transition: transform .18s; }.status-switch.on { color: #15803d; }.status-switch.on i { background: #22c55e; }.status-switch.on i::after { transform: translateX(14px); }.status-switch b { font-weight: 500; }
.form-actions { position: sticky; z-index: 2; bottom: 0; display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 10px; grid-column: 1 / -1; margin: 6px -20px -20px; border-top: 1px solid #dce6ef; background: rgb(255 255 255 / 96%); box-shadow: 0 -8px 18px rgb(15 23 42 / 7%); padding: 14px 20px; backdrop-filter: blur(8px); }
/* 底部操作栏是抽屉 flex 布局的独立层级:固定在抽屉底部,不随表单内容滚动/折叠区展开移动。模板中该栏位于 </form> 之后(不在 form 内),保存按钮为 type=button 显式 click 调用 saveCurrent,输入框回车提交仍走 form @submit */
.form-actions { flex: 0 0 auto; display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 10px; border-top: 1px solid var(--border-default); background: rgb(255 255 255 / 96%); box-shadow: 0 -8px 18px rgb(15 23 42 / 7%); padding: 14px 20px; backdrop-filter: blur(8px); }
.source-enabled-footer { display: flex; margin-right: auto; min-width: 0; align-items: center; gap: 10px; }
.source-enabled-label { flex: 0 0 auto; color: #475569; font-size: 13px; font-weight: 600; }
.source-enabled-hint { overflow: hidden; color: #94a3b8; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }
@@ -1741,7 +1747,7 @@ onMounted(load);
.audit-table td strong, .audit-table td small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.audit-table td strong { color: #263850; font-weight: 600; }.audit-table td small { margin-top: 4px; color: #94a3b8; }
.audit-cell { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.audit-status { display: inline-flex; border-radius: 999px; padding: 3px 8px; font-size: 11px; white-space: nowrap; }.audit-status.ready { background: #dcfce7; color: #15803d; }.audit-status.failed { background: #fef2f2; color: #b91c1c; }.audit-status.neutral { background: #f1f5f9; color: #64748b; }
.audit-detail dl { display: grid; grid-template-columns: 130px minmax(0, 1fr); gap: 0; margin: 0; padding: 18px 20px; }.audit-detail dt, .audit-detail dd { margin: 0; padding: 11px 0; border-bottom: 1px solid #edf2f7; font-size: 13px; }.audit-detail dt { color: #64748b; }.audit-detail dd { overflow-wrap: anywhere; color: #334155; }
.audit-detail dl { flex: 1 1 auto; min-height: 0; overflow-y: auto; display: grid; grid-auto-rows: max-content; grid-template-columns: 130px minmax(0, 1fr); gap: 0; margin: 0; padding: 18px 20px; }.audit-detail dt, .audit-detail dd { margin: 0; padding: 11px 0; border-bottom: 1px solid #edf2f7; font-size: 13px; }.audit-detail dt { color: #64748b; }.audit-detail dd { overflow-wrap: anywhere; color: #334155; }
.object-list .empty-state { grid-column: 1 / -1; display: grid; min-height: 260px; place-items: center; }
.empty-state { border: 1px dashed #c9d7e5; border-radius: 10px; background: #f9fbfd; padding: 38px 18px; color: #7b899a; font-size: 13px; text-align: center; }
@media (max-width: 980px) { .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card { grid-template-columns: 1fr 1fr; } .mapping-value-row { grid-template-columns: minmax(0, 1.6fr) minmax(180px, 1fr); }.readiness-audit { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@@ -206,8 +206,8 @@ onBeforeUnmount(stopSampleRefresh);
.wizard-page { min-height: 100%; padding: 24px; background: #f6f8fc; }
.wizard-shell { width: 100%; }
.wizard-heading { margin-bottom: 28px; }.wizard-heading h1, .wizard-heading p { margin: 0; }
.stepper { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0; margin: 0 0 18px; padding: 0; list-style: none; }.stepper li { display: flex; align-items: center; gap: 10px; color: #94a3b8; font-size: .86rem; font-weight: 650; }.stepper li:not(:last-child)::after { width: 100%; height: 1px; margin-left: 10px; background: #dbe4f0; content: ''; }.stepper li.active { color: #1677d2; }.stepper li.complete { color: #0f8a65; }.stepper-icon { display: inline-grid; flex: 0 0 auto; width: 32px; height: 32px; place-items: center; border: 1px solid currentColor; border-radius: 50%; background: #fff; }.stepper .complete .stepper-icon { color: #fff; border-color: #0f8a65; background: #0f8a65; }.stepper small { display: block; margin-bottom: 1px; color: #94a3b8; font-size: .68rem; font-weight: 700; text-transform: uppercase; }
.wizard-card { min-height: 360px; padding: clamp(24px, 4vw, 44px); border: 1px solid #e1e8f2; border-radius: 12px; background: #fff; box-shadow: 0 8px 24px rgb(15 23 42 / .06); }.wizard-card__heading { margin-bottom: 28px; padding-bottom: 18px; border-bottom: 1px solid #edf1f7; }.wizard-card__heading span { color: #1677d2; font-size: .76rem; font-weight: 750; letter-spacing: .06em; text-transform: uppercase; }.wizard-card__heading h2 { margin: 6px 0 0; color: #1e293b; font-size: 1.25rem; }
.stepper { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0; margin: 0 0 18px; padding: 0; list-style: none; }.stepper li { display: flex; align-items: center; gap: 10px; color: #94a3b8; font-size: .86rem; font-weight: 650; }.stepper li:not(:last-child)::after { width: 100%; height: 1px; margin-left: 10px; background: #dbe4f0; content: ''; }/* 步骤状态色统一 Tailwind 标准值:激活=brand-600、完成=green-600 */.stepper li.active { color: #0284c7; }.stepper li.complete { color: #16a34a; }.stepper-icon { display: inline-grid; flex: 0 0 auto; width: 32px; height: 32px; place-items: center; border: 1px solid currentColor; border-radius: 50%; background: #fff; }.stepper .complete .stepper-icon { color: #fff; border-color: #16a34a; background: #16a34a; }.stepper small { display: block; margin-bottom: 1px; color: #94a3b8; font-size: .68rem; font-weight: 700; text-transform: uppercase; }
.wizard-card { min-height: 360px; padding: clamp(24px, 4vw, 44px); border: 1px solid #e1e8f2; border-radius: 12px; background: #fff; box-shadow: 0 8px 24px rgb(15 23 42 / .06); }.wizard-card__heading { margin-bottom: 28px; padding-bottom: 18px; border-bottom: 1px solid #edf1f7; }.wizard-card__heading span { color: #0284c7; font-size: .76rem; font-weight: 750; letter-spacing: .06em; text-transform: uppercase; }.wizard-card__heading h2 { margin: 6px 0 0; color: #1e293b; font-size: 1.25rem; }
.wizard-actions { display: flex; align-items: center; gap: 10px; margin-top: 18px; }.wizard-actions__spacer { flex: 1; }
@media (max-width: 640px) { .wizard-page { padding: 24px 16px; }.stepper { grid-template-columns: 1fr; gap: 10px; }.stepper li:not(:last-child)::after { display: none; }.wizard-card { min-height: 300px; border-radius: 14px; }.wizard-actions { flex-wrap: wrap; }.wizard-actions__spacer { display: none; }.btn-secondary:first-child { margin-right: auto; } }
</style>
@@ -353,7 +353,7 @@ ul { margin: 8px 0; padding-left: 20px; color: #b91c1c; font-size: 13px; }
.metrics div { display: grid; gap: 4px; }
.metrics dt { color: #64748b; font-size: 12px; }
.metrics dd { margin: 0; color: #1e293b; font-size: 14px; font-weight: 600; }
.conflict-card { border: 1px solid #fecaca; background: #fff7f7; border-radius: 8px; padding: 12px; margin-top: 10px; }
.conflict-card { border: 1px solid #fecaca; background: #fef2f2; border-radius: 8px; padding: 12px; margin-top: 10px; }
.conflict-card strong { color: #991b1b; font-size: 13px; }
.conflict-card .reasons { color: #b45309; font-size: 12px; }
@media (max-width: 767px) {
@@ -688,8 +688,9 @@ watch(
}
.migration-backdrop { position: fixed; z-index: 30; inset: 0; display: grid; place-items: center; padding: 1rem; background: rgb(15 23 42 / 45%); }
.migration-dialog { display: grid; width: min(100%, 42rem); max-height: min(44rem, calc(100vh - 2rem)); gap: 1rem; overflow: auto; padding: 1.5rem; border-radius: 1rem; background: var(--bg-surface); box-shadow: 0 20px 40px rgb(15 23 42 / 25%); }
.migration-dialog h2,.migration-dialog p { margin: 0; }.migration-note { color: var(--text-muted); font-size: .875rem; }.migration-changes { display: grid; gap: .75rem; }.migration-changes article { display: grid; gap: .45rem; padding: .85rem; border: 1px solid var(--border-default); border-radius: .75rem; }.migration-changes span { color: var(--text-muted); font-size: .8125rem; }.migration-changes label { display: grid; gap: .3rem; color: var(--text-secondary); font-size: .8125rem; font-weight: 600; }.migration-changes select { min-height: 2.25rem; border: 1px solid var(--border-default); border-radius: .5rem; background: var(--bg-surface); color: var(--text-primary); font: inherit; }.migration-dialog footer { display: flex; justify-content: flex-end; gap: .5rem; }
.migration-dialog { display: grid; grid-auto-rows: max-content; width: min(100%, 42rem); max-height: min(44rem, calc(100vh - 2rem)); gap: 1rem; overflow-y: auto; padding: 1.5rem; border-radius: 1rem; background: var(--bg-surface); box-shadow: 0 20px 40px rgb(15 23 42 / 25%); }
.migration-dialog h2,.migration-dialog p { margin: 0; }.migration-note { color: var(--text-muted); font-size: .875rem; }.migration-changes { display: grid; gap: .75rem; }.migration-changes article { display: grid; gap: .45rem; padding: .85rem; border: 1px solid var(--border-default); border-radius: .75rem; }.migration-changes span { color: var(--text-muted); font-size: .8125rem; }.migration-changes label { display: grid; gap: .3rem; color: var(--text-secondary); font-size: .8125rem; font-weight: 600; }.migration-changes select { min-height: 2.25rem; border: 1px solid var(--border-default); border-radius: .5rem; background: var(--bg-surface); color: var(--text-primary); font: inherit; }/* footer 用 sticky 钉在对话框可视底部:breaking changes 列表长时取消/确认迁移按钮始终可见,不需滚回底部 */
.migration-dialog footer { position: sticky; bottom: -1.5rem; display: flex; justify-content: flex-end; gap: .5rem; margin: 0 -1.5rem -1.5rem; border-top: 1px solid var(--border-default); background: var(--bg-surface); padding: 1rem 1.5rem 1.25rem; }
@media (max-width: 960px) {
.header-main,
@@ -127,5 +127,5 @@ onBeforeUnmount(stopPolling);
</template>
<style scoped>
.sample-step { display: grid; gap: 18px; max-width: 640px; }.upload-panel,.reuse-panel,.parse-status,.selected-sample { border: 1px solid var(--border-default); border-radius: 12px; background: var(--bg-surface); }.upload-panel { display: grid; grid-template-columns: auto 1fr auto; gap: 14px; align-items: center; padding: 18px; background: var(--bg-surface-soft); }.upload-panel__icon { display: grid; width: 42px; height: 42px; place-items: center; border-radius: 10px; color: var(--status-info-fg); background: var(--status-info-bg); }.upload-panel h3,.reuse-panel h3,.parse-status p,.selected-sample span { margin: 0; }.upload-panel h3,.reuse-panel h3 { color: var(--text-primary); font-size: 1rem; }.upload-panel p,.reuse-panel p { margin: 5px 0 0; color: var(--text-muted); font-size: .84rem; }.upload-action { display: inline-flex; min-height: 38px; align-items: center; border-radius: 8px; padding: 0 13px; color: #fff; background: #1677d2; font-weight: 700; cursor: pointer; }.upload-action input { position: absolute; width: 1px; height: 1px; overflow: hidden; opacity: 0; }.parse-status,.selected-sample { display: flex; gap: 10px; align-items: center; padding: 13px 15px; color: var(--status-info-fg); background: var(--status-info-bg); }.parse-status strong,.selected-sample strong { display: block; color: var(--text-primary); }.parse-status p,.selected-sample span { display: block; margin-top: 3px; color: var(--text-muted); font-size: .83rem; }.refresh-status { margin-top: 6px; padding: 0; border: 0; color: inherit; background: transparent; font: inherit; font-size: .8rem; font-weight: 700; cursor: pointer; text-decoration: underline; }.parse-status.failed { color: var(--status-error-fg); border-color: var(--status-error-border); background: var(--status-error-bg); }.parse-status.failed > span { display: grid; width: 19px; height: 19px; place-items: center; border-radius: 50%; color: #fff; background: var(--status-error-fg); font-weight: 800; }.selected-sample { color: var(--status-success-fg); border-color: var(--status-success-border); background: var(--status-success-bg); }.reuse-panel { padding: 18px; }.reuse-panel__heading { margin-bottom: 14px; }.field { display: grid; gap: 7px; color: var(--text-secondary); font-size: .88rem; font-weight: 700; }.field .select-field { min-height: 44px; font: inherit; } @media (max-width: 640px) { .upload-panel { grid-template-columns: auto 1fr; }.upload-action { grid-column: 1 / -1; justify-content: center; } }
.sample-step { display: grid; gap: 18px; max-width: 640px; }.upload-panel,.reuse-panel,.parse-status,.selected-sample { border: 1px solid var(--border-default); border-radius: 12px; background: var(--bg-surface); }.upload-panel { display: grid; grid-template-columns: auto 1fr auto; gap: 14px; align-items: center; padding: 18px; background: var(--bg-surface-soft); }.upload-panel__icon { display: grid; width: 42px; height: 42px; place-items: center; border-radius: 10px; color: var(--status-info-fg); background: var(--status-info-bg); }.upload-panel h3,.reuse-panel h3,.parse-status p,.selected-sample span { margin: 0; }.upload-panel h3,.reuse-panel h3 { color: var(--text-primary); font-size: 1rem; }.upload-panel p,.reuse-panel p { margin: 5px 0 0; color: var(--text-muted); font-size: .84rem; }.upload-action { display: inline-flex; min-height: 38px; align-items: center; border-radius: 8px; padding: 0 13px; color: #fff; background: #0284c7; font-weight: 700; cursor: pointer; }.upload-action input { position: absolute; width: 1px; height: 1px; overflow: hidden; opacity: 0; }.parse-status,.selected-sample { display: flex; gap: 10px; align-items: center; padding: 13px 15px; color: var(--status-info-fg); background: var(--status-info-bg); }.parse-status strong,.selected-sample strong { display: block; color: var(--text-primary); }.parse-status p,.selected-sample span { display: block; margin-top: 3px; color: var(--text-muted); font-size: .83rem; }.refresh-status { margin-top: 6px; padding: 0; border: 0; color: inherit; background: transparent; font: inherit; font-size: .8rem; font-weight: 700; cursor: pointer; text-decoration: underline; }.parse-status.failed { color: var(--status-error-fg); border-color: var(--status-error-border); background: var(--status-error-bg); }.parse-status.failed > span { display: grid; width: 19px; height: 19px; place-items: center; border-radius: 50%; color: #fff; background: var(--status-error-fg); font-weight: 800; }.selected-sample { color: var(--status-success-fg); border-color: var(--status-success-border); background: var(--status-success-bg); }.reuse-panel { padding: 18px; }.reuse-panel__heading { margin-bottom: 14px; }.field { display: grid; gap: 7px; color: var(--text-secondary); font-size: .88rem; font-weight: 700; }.field .select-field { min-height: 44px; font: inherit; } @media (max-width: 640px) { .upload-panel { grid-template-columns: auto 1fr; }.upload-action { grid-column: 1 / -1; justify-content: center; } }
</style>
@@ -1419,8 +1419,10 @@ onMounted(async () => {
<style scoped>
.compact-button { padding: 6px 10px; font-size: 12px; }
.impact-overlay { position: fixed; z-index: 60; inset: 0; display: grid; place-items: center; background: var(--overlay-soft); padding: 24px; }
.impact-dialog { display: grid; width: min(720px, 96vw); max-height: 82vh; gap: 14px; overflow: hidden; border-radius: 12px; background: var(--bg-surface); padding: 18px; box-shadow: 0 24px 64px rgb(15 23 42 / .24); }
.impact-dialog { display: grid; grid-auto-rows: max-content; width: min(720px, 96vw); max-height: 82vh; gap: 14px; overflow-y: auto; border-radius: 12px; background: var(--bg-surface); padding: 18px; box-shadow: 0 24px 64px rgb(15 23 42 / .24); }
.impact-dialog header, .impact-dialog footer { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
/* footer 用 sticky 钉在对话框可视底部:发布影响列表等长内容滚动时,确认/取消按钮始终可见(原 overflow:hidden 会把 footer 整条裁掉) */
.impact-dialog footer { position: sticky; bottom: -18px; margin: 4px -18px -18px; border-top: 1px solid var(--border-default); background: var(--bg-surface); padding: 12px 18px; }
.impact-dialog h2, .impact-dialog p { margin: 0; }
.impact-list { display: grid; gap: 8px; overflow: auto; }
.impact-list article { border: 1px solid #e2e8f0; border-radius: 8px; padding: 10px 12px; }
@@ -1,24 +1,44 @@
/**
* features/admin/modules/users/UsersPage.vue
* 用途:用户管理独立页面(服务端筛选分页、用户/部门列排序、批量操作)。
* 依赖:useUsersAdmin、SortableTableHeader、PaginationBar、用户相关 Modal、adminRoleLabel、getUserAvatarLabel。
* 逻辑:路由 /admin/users;列表经 listAdminUsersPage 按页拉取;权限组启用后只选角色、关闭按人授权。
* 依赖:useUsersAdmin、useElementProvider、element-plus、用户相关 Modal、adminRoleLabel、getUserAvatarLabel。
* 逻辑:路由 /admin/users。列表骨架用 AdminListPage;筛选、表格、分页和三个业务弹窗仍由本页组装。
* 删除和改角色用 Element 确认框。列表经 listAdminUsersPage 按页拉取。
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { computed, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Edit, Plus, Trash2, Users } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import SortableTableHeader from '@/shared/components/SortableTableHeader.vue';
import { Delete, Edit, Plus, User } from '@element-plus/icons-vue';
import {
ElButton,
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 { 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';
import { useUsersAdmin } from './composables/useUsersAdmin';
const vLoading = ElLoading.directive;
const { t } = useI18n();
const { elementLocale } = useElementProvider();
const {
agents,
@@ -31,290 +51,256 @@ const {
userFilters,
sortKey,
sortDir,
// hideRejected,
selectedUserIds,
users,
usersTotal,
userPage,
userPageSize,
userPageSizeOptions,
usersPages,
allPaginatedUsersSelected,
showUserModal,
editingUser,
showBatchEditModal,
batchEditForm,
showBatchPermissionModal,
batchPermissionForm,
showDeleteConfirmDialog,
deleteConfirmMessage,
showRoleConfirm,
roleConfirmMessage,
loadAll,
toggleSort,
applyServerSort,
openCreateUserModal,
openEditUserModal,
saveUser,
// cleanRejectedUsers,
batchDeleteUsers,
toggleUserSelection,
toggleAllUsers,
openBatchEditModal,
openBatchPermissionModal,
submitBatchEdit,
submitBatchPermission,
closeDeleteConfirm,
confirmDelete,
confirmRoleChange,
closeRoleConfirm,
} = useUsersAdmin();
const pageSizes = computed(() => [...userPageSizeOptions]);
const defaultSort = computed(() => ({
prop: sortKey.value || 'username',
order: sortDir.value === 'desc' ? 'descending' as const : 'ascending' as const,
}));
/**
* 把 Element 表格的勾选结果写回已选用户 id。
* @param rows - 当前保留的选中行
*/
function onSelectionChange(rows: AdminUserRow[]): void {
selectedUserIds.value = rows.map((row) => row.id);
}
/**
* 部门筛选。清空时写回空字符串,列表接口仍按「全部部门」查询。
* @param value - 选中的部门名;清空为 undefined
*/
function onDepartmentChange(value: string | undefined): void {
userFilters.value.department = value ?? '';
}
/**
* 把 Element 表头排序交给服务端查询。
* 核心逻辑:取消排序时保持当前方向;有效排序走 applyServerSort 并回到第一页。
* @param payload.prop - 列字段
* @param payload.order - ascending、descending 或空
*/
function onSortChange(payload: { prop: string | null; order: string | null }): void {
const field = payload.prop;
if ((field === 'username' || field === 'department') && payload.order) {
applyServerSort(field, payload.order === 'descending' ? 'desc' : 'asc');
}
}
/**
* 打开编辑弹窗。表格插槽行类型较宽,这里收成用户行。
* @param row - 当前表格行
*/
function editUser(row: AdminUserRow): void {
openEditUserModal(row);
}
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="admin-table-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>
<template v-else>
<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>
<div class="flex flex-wrap gap-3">
<!-- 暂隐藏:清理已拒绝
<button
type="button"
class="flex items-center gap-2 px-4 py-2 bg-red-50 text-red-600 rounded-xl hover:bg-red-100 transition-all border border-red-200 text-sm font-medium"
@click="cleanRejectedUsers"
>
<Trash2 class="w-4 h-4" />
<span>{{ t('admin.user.cleanRejected') }}</span>
</button>
-->
<button
<ElConfigProvider :locale="elementLocale">
<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="button"
class="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-xl hover:bg-red-700 transition-all shadow-lg shadow-red-200 active:scale-95 text-sm font-medium"
type="danger"
:icon="Delete"
@click="batchDeleteUsers"
>
<Trash2 class="w-4 h-4" />
<span>{{ t('admin.user.batchDelete') }} ({{ selectedUserIds.length }})</span>
</button>
<button
v-if="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 text-sm font-medium"
@click="openBatchEditModal"
>
<Edit class="w-4 h-4" />
<span>{{ t('admin.user.batchEdit') }} ({{ selectedUserIds.length }})</span>
</button>
<button
{{ 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"
type="button"
class="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-xl hover:bg-purple-700 transition-all shadow-lg shadow-purple-200 active:scale-95 text-sm font-medium"
:icon="User"
@click="openBatchPermissionModal"
>
<Users class="w-4 h-4" />
<span>{{ t('admin.user.batchPermission') }} ({{ selectedUserIds.length }})</span>
</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 transition-all shadow-lg shadow-brand-200 active:scale-95 text-sm font-medium"
@click="openCreateUserModal"
{{ 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
class="users-filter-username"
:placeholder="t('admin.user.filterUsername')"
/>
<ElInput
v-model="userFilters.real_name"
clearable
class="users-filter-name"
:placeholder="t('admin.user.filterRealName')"
/>
<ElSelect
:model-value="userFilters.department || undefined"
class="users-filter-dept"
clearable
:placeholder="t('admin.user.allDepts')"
@update:model-value="onDepartmentChange"
>
<Plus class="w-4 h-4" />
<span class="font-medium">{{ t('admin.user.addUser') }}</span>
</button>
</div>
</div>
<ElOption v-for="department in departments" :key="department.id" :label="department.name" :value="department.name" />
</ElSelect>
</template>
<div class="admin-table-filters--inline gap-3">
<input v-model="userFilters.username" :placeholder="t('admin.user.filterUsername')" class="admin-table-filter-input w-40" />
<input v-model="userFilters.real_name" :placeholder="t('admin.user.filterRealName')" class="admin-table-filter-input w-44" />
<select v-model="userFilters.department" class="admin-table-filter-input w-40">
<option value="">{{ t('admin.user.allDepts') }}</option>
<option v-for="d in departments" :key="d.id" :value="d.name">{{ d.name }}</option>
</select>
<!-- 暂隐藏:隐藏已拒绝
<div class="flex items-center gap-2">
<input id="hideRejectedUsers" v-model="hideRejected" type="checkbox" class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500 border-default" />
<label for="hideRejectedUsers" class="text-sm text-secondary select-none">{{ t('admin.user.hideRejected') }}</label>
</div>
-->
</div>
<div class="admin-table-wrap relative">
<div
v-if="isListLoading"
class="absolute inset-0 z-10 flex items-center justify-center rounded-2xl bg-surface/60"
<ElTable
v-loading="isListLoading"
class="hx-admin-table"
:data="users"
row-key="id"
:default-sort="defaultSort"
:empty-text="t('admin.user.noUsers')"
@selection-change="onSelectionChange"
@sort-change="onSortChange"
>
<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600" />
</div>
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 w-12 text-center">
<input
type="checkbox"
class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500 cursor-pointer border-default"
:checked="allPaginatedUsersSelected"
@change="toggleAllUsers(users)"
/>
</th>
<th class="px-6 py-4 text-left text-xs">
<SortableTableHeader
column-key="username"
:label="t('admin.user.headers.user')"
:active-key="sortKey"
:direction="sortDir"
@sort="toggleSort"
/>
</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.user.fields.realName') }}</th>
<th class="px-6 py-4 text-left text-xs">
<SortableTableHeader
column-key="department"
:label="t('admin.user.headers.dept')"
:active-key="sortKey"
:direction="sortDir"
@sort="toggleSort"
/>
</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.user.headers.role') }}</th>
<th class="px-6 py-4 text-right text-xs">{{ t('admin.user.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="usersTotal === 0 && !isListLoading">
<td colspan="6" class="px-6 admin-table-empty">{{ t('admin.user.noUsers') }}</td>
</tr>
<tr v-for="user in users" :key="user.id" class="group">
<td class="px-6 py-4 text-center">
<input
type="checkbox"
class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500 cursor-pointer border-default"
:checked="selectedUserIds.includes(user.id)"
@change="toggleUserSelection(user.id)"
/>
</td>
<td class="px-6 py-4">
<div class="flex items-center">
<div class="h-9 w-9 rounded-full bg-gradient-to-br from-brand-500 to-indigo-600 text-white flex items-center justify-center text-xs font-bold shadow-sm">
{{ getUserAvatarLabel(user) }}
</div>
<div class="ml-3 text-sm font-medium text-primary">{{ user.username }}</div>
</div>
</td>
<td class="px-6 py-4 text-sm text-primary">{{ user.real_name || '-' }}</td>
<td class="px-6 py-4 text-sm text-muted">{{ user.department || '-' }}</td>
<td class="px-6 py-4">
<span
class="px-2.5 py-0.5 rounded-full text-xs font-medium border"
:class="user.is_platform_admin
? 'bg-purple-50 text-purple-700 border-purple-100'
: 'bg-blue-50 text-blue-700 border-blue-100'"
>
{{ adminRoleLabel(t, user.role, user.role_name) }}
<ElTableColumn type="selection" width="64" reserve-selection />
<ElTableColumn prop="username" :label="t('admin.user.headers.user')" sortable="custom" min-width="180">
<template #default="{ row }">
<span class="inline-flex items-center gap-3">
<span class="users-avatar">
{{ getUserAvatarLabel(row) }}
</span>
<div
v-if="user.feature_permissions?.training_hr_manage || user.feature_permissions?.['maintenance.ledger_write']"
class="mt-2 flex flex-wrap gap-1.5"
>
<span
v-if="user.feature_permissions?.training_hr_manage"
class="inline-flex rounded-full border border-brand-100 bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-700"
>
{{ t('admin.user.fields.trainingHrManage') }}
</span>
<span
v-if="user.feature_permissions?.['maintenance.ledger_write']"
class="inline-flex rounded-full border border-brand-100 bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-700"
>
{{ t('admin.permRoles.features.maintenance_ledger_write') }}
</span>
</div>
</td>
<td class="px-6 py-4 text-right">
<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 transition-colors"
@click="openEditUserModal(user)"
>
{{ t('admin.edit') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
<span>{{ row.username }}</span>
</span>
</template>
</ElTableColumn>
<ElTableColumn prop="real_name" :label="t('admin.user.fields.realName')" min-width="120">
<template #default="{ row }">{{ row.real_name || '-' }}</template>
</ElTableColumn>
<ElTableColumn prop="department" :label="t('admin.user.headers.dept')" sortable="custom" min-width="140">
<template #default="{ row }">{{ row.department || '-' }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.user.headers.role')" min-width="180">
<template #default="{ row }">
<ElTag :type="row.is_platform_admin ? 'warning' : 'primary'" effect="light">
{{ adminRoleLabel(t, row.role, row.role_name) }}
</ElTag>
<div
v-if="row.feature_permissions?.training_hr_manage || row.feature_permissions?.['maintenance.ledger_write']"
class="mt-2 flex flex-wrap gap-1.5"
>
<ElTag v-if="row.feature_permissions?.training_hr_manage" size="small">
{{ t('admin.user.fields.trainingHrManage') }}
</ElTag>
<ElTag v-if="row.feature_permissions?.['maintenance.ledger_write']" size="small">
{{ t('admin.permRoles.features.maintenance_ledger_write') }}
</ElTag>
</div>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.user.headers.actions')" width="100" align="right">
<template #default="{ row }">
<ElButton link type="primary" @click="editUser(row as AdminUserRow)">{{ t('admin.edit') }}</ElButton>
</template>
</ElTableColumn>
</ElTable>
<div class="px-4 pb-4 pt-2">
<PaginationBar
v-model:page="userPage"
v-model:page-size="userPageSize"
:total="usersTotal"
:pages="usersPages"
:page-size-options="[...userPageSizeOptions]"
/>
</div>
</template>
<template #pagination>
<ElPagination
v-model:current-page="userPage"
v-model:page-size="userPageSize"
:total="usersTotal"
:page-sizes="pageSizes"
layout="total, sizes, prev, pager, next"
background
/>
</template>
</AdminListPage>
<UserFormModal
:visible="showUserModal"
:form="editingUser"
:agents="agents"
:departments="departments"
:roles="roles"
:roles-configured="rolesConfigured"
:is-saving="isSaving"
@close="showUserModal = false"
@save="saveUser"
/>
<UserFormModal
:visible="showUserModal"
:form="editingUser"
:agents="agents"
:departments="departments"
:roles="roles"
:roles-configured="rolesConfigured"
:is-saving="isSaving"
@close="showUserModal = false"
@save="saveUser"
/>
<BatchEditUserModal
:visible="showBatchEditModal"
:form="batchEditForm"
:departments="departments"
:roles="roles"
:roles-configured="rolesConfigured"
:selected-count="selectedUserIds.length"
:is-saving="isSaving"
@close="showBatchEditModal = false"
@save="submitBatchEdit"
/>
<BatchEditUserModal
:visible="showBatchEditModal"
:form="batchEditForm"
:departments="departments"
:roles="roles"
:roles-configured="rolesConfigured"
:selected-count="selectedUserIds.length"
:is-saving="isSaving"
@close="showBatchEditModal = false"
@save="submitBatchEdit"
/>
<BatchPermissionModal
:visible="showBatchPermissionModal"
:form="batchPermissionForm"
:agents="agents"
:selected-count="selectedUserIds.length"
:is-saving="isSaving"
@close="showBatchPermissionModal = false"
@save="submitBatchPermission"
/>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@confirm="confirmDelete"
@cancel="closeDeleteConfirm"
/>
<DeleteConfirmDialog
v-model="showRoleConfirm"
:title="t('admin.permRoles.userRoleConfirmTitle')"
:message="roleConfirmMessage"
:confirm-text="t('admin.save')"
confirm-tone="primary"
:confirm-loading="isSaving"
@confirm="confirmRoleChange"
@cancel="closeRoleConfirm"
/>
</section>
<BatchPermissionModal
:visible="showBatchPermissionModal"
:form="batchPermissionForm"
:agents="agents"
:selected-count="selectedUserIds.length"
:is-saving="isSaving"
@close="showBatchPermissionModal = false"
@save="submitBatchPermission"
/>
</ElConfigProvider>
</template>
<style scoped>
:deep(.users-filter-username) {
width: 10rem;
}
:deep(.users-filter-name),
:deep(.users-filter-dept) {
width: 11rem;
}
.users-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;
}
</style>
@@ -1,17 +1,19 @@
/**
* features/admin/modules/users/components/BatchEditUserModal.vue
* 用途:批量编辑用户部门/角色/状态弹窗。权限组启用后角色下拉读权限组列表。
* 依赖:admin.types、permissionRole.types、user.types、roleLabel.LEGACY_ROLE_OPTIONS。
* 逻辑:UsersPage 传入角色列表;未选字段表示保持不变。
* 依赖:element-plus、admin.types、permissionRole.types、user.types、roleLabel.LEGACY_ROLE_OPTIONS。
* 逻辑:UsersPage 传入角色列表;未选字段表示保持不变。本弹窗属于用户管理 Element Plus 试点。
*/
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElButton, ElDialog, ElForm, ElFormItem, ElOption, ElSelect } from 'element-plus';
import type { AdminDepartmentRow } from '@/features/admin/types/admin.types';
import type { PermissionRoleRow } from '@/features/admin/types/permissionRole.types';
import type { BatchEditForm } from '@/features/admin/types/user.types';
import { LEGACY_ROLE_OPTIONS } from '@/features/admin/utils/roleLabel';
defineProps<{
const props = defineProps<{
visible: boolean;
form: BatchEditForm;
departments: AdminDepartmentRow[];
@@ -23,55 +25,61 @@ defineProps<{
const emit = defineEmits<{ close: []; save: [] }>();
const { t } = useI18n();
/**
* 角色下拉,首项为保持不变。
*/
const roleOptions = computed(() => {
const keep = { value: '', label: t('admin.batchEdit.fields.keepUnchanged') };
if (props.rolesConfigured) {
return [keep, ...props.roles.map((role) => ({ value: role.code, label: role.name }))];
}
return [keep, ...LEGACY_ROLE_OPTIONS.map((option) => ({ value: option.code, label: t(option.i18nKey) }))];
});
/**
* 关闭弹窗并通知父页面收起。
* @param open - Element 对话框的打开状态
*/
function onVisibleChange(open: boolean): void {
if (!open) emit('close');
}
</script>
<template>
<div v-if="visible" class="admin-modal-overlay items-center">
<div class="admin-modal-panel max-w-md animate-fade-in-up">
<div class="px-8 py-6 border-b border-subtle">
<h3 class="text-lg font-bold text-primary">{{ t('admin.batchEdit.title') }}</h3>
<p class="text-sm text-muted">{{ t('admin.batchEdit.selected', { count: selectedCount }) }}</p>
</div>
<div class="p-8 space-y-4">
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.batchEdit.fields.dept') }}</label>
<select v-model="form.department" class="input-field text-sm">
<option value="">{{ t('admin.batchEdit.fields.keepUnchanged') }}</option>
<option v-for="d in departments" :key="d.id" :value="d.name">{{ d.name }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.batchEdit.fields.role') }}</label>
<select v-if="rolesConfigured" v-model="form.role" class="input-field text-sm">
<option value="">{{ t('admin.batchEdit.fields.keepUnchanged') }}</option>
<option v-for="role in roles" :key="role.code" :value="role.code">{{ role.name }}</option>
</select>
<select v-else v-model="form.role" class="input-field text-sm">
<option value="">{{ t('admin.batchEdit.fields.keepUnchanged') }}</option>
<option
v-for="option in LEGACY_ROLE_OPTIONS"
:key="option.code"
:value="option.code"
>
{{ t(option.i18nKey) }}
</option>
</select>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.batchEdit.fields.status') }}</label>
<select v-model="form.status" class="input-field text-sm">
<option value="">{{ t('admin.batchEdit.fields.keepUnchanged') }}</option>
<option value="active">{{ t('admin.status.active') }}</option>
<option value="disabled">{{ t('admin.status.disabled') }}</option>
</select>
</div>
</div>
<div class="admin-modal-footer admin-modal-footer--muted px-8 py-6">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button type="button" class="btn-primary disabled:opacity-50" :disabled="isSaving" @click="emit('save')">
{{ isSaving ? t('admin.save') + '...' : t('admin.batchEdit.update') }}
</button>
</div>
</div>
</div>
<ElDialog
:model-value="visible"
:title="t('admin.batchEdit.title')"
width="480px"
align-center
append-to-body
:close-on-click-modal="false"
@update:model-value="onVisibleChange"
>
<p class="hx-element-hint">{{ t('admin.batchEdit.selected', { count: selectedCount }) }}</p>
<ElForm label-position="top" :model="form">
<ElFormItem :label="t('admin.batchEdit.fields.dept')">
<ElSelect v-model="form.department" class="w-full">
<ElOption :label="t('admin.batchEdit.fields.keepUnchanged')" value="" />
<ElOption v-for="department in departments" :key="department.id" :label="department.name" :value="department.name" />
</ElSelect>
</ElFormItem>
<ElFormItem :label="t('admin.batchEdit.fields.role')">
<ElSelect v-model="form.role" class="w-full">
<ElOption v-for="option in roleOptions" :key="option.value || 'keep'" :label="option.label" :value="option.value" />
</ElSelect>
</ElFormItem>
<ElFormItem :label="t('admin.batchEdit.fields.status')">
<ElSelect v-model="form.status" class="w-full">
<ElOption :label="t('admin.batchEdit.fields.keepUnchanged')" value="" />
<ElOption :label="t('admin.status.active')" value="active" />
<ElOption :label="t('admin.status.disabled')" value="disabled" />
</ElSelect>
</ElFormItem>
</ElForm>
<template #footer>
<ElButton @click="emit('close')">{{ t('admin.cancel') }}</ElButton>
<ElButton type="primary" :loading="isSaving" @click="emit('save')">{{ t('admin.batchEdit.update') }}</ElButton>
</template>
</ElDialog>
</template>
@@ -1,9 +1,21 @@
/**
* features/admin/modules/users/components/BatchPermissionModal.vue
* 批量分配/移除用户 Agent 权限弹窗。
* 用途:批量分配、移除或覆盖用户 Agent 权限。
* 依赖:element-plus、admin.types、user.types。
* 逻辑:UsersPage 传入已选人数与 Agent 列表;动作为 add / remove / set。本弹窗属于用户管理 Element Plus 试点。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import {
ElButton,
ElCheckbox,
ElCheckboxGroup,
ElDialog,
ElForm,
ElFormItem,
ElRadio,
ElRadioGroup,
} from 'element-plus';
import type { AdminAgentOption } from '@/features/admin/types/admin.types';
import type { BatchPermissionForm } from '@/features/admin/types/user.types';
@@ -17,54 +29,46 @@ defineProps<{
const emit = defineEmits<{ close: []; save: [] }>();
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 items-center">
<div class="admin-modal-panel max-w-lg animate-fade-in-up">
<div class="px-8 py-6 border-b border-subtle">
<h3 class="text-lg font-bold text-primary">{{ t('admin.perm.batchModal.title') }}</h3>
<p class="text-sm text-muted">{{ t('admin.perm.batchModal.selected', { count: selectedCount }) }}</p>
</div>
<div class="p-8 space-y-6">
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.perm.batchModal.action') }}</label>
<div class="flex gap-4">
<label class="flex items-center gap-2 cursor-pointer">
<input v-model="form.action" type="radio" value="add" class="text-blue-600 focus:ring-blue-500" />
<span class="text-sm">{{ t('admin.perm.batchModal.add') }}</span>
</label>
<label class="flex items-center gap-2 cursor-pointer">
<input v-model="form.action" type="radio" value="remove" class="text-blue-600 focus:ring-blue-500" />
<span class="text-sm">{{ t('admin.perm.batchModal.remove') }}</span>
</label>
<label class="flex items-center gap-2 cursor-pointer">
<input v-model="form.action" type="radio" value="set" class="text-blue-600 focus:ring-blue-500" />
<span class="text-sm">{{ t('admin.perm.batchModal.set') }}</span>
</label>
</div>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.perm.batchModal.selectAgents') }}</label>
<div class="grid grid-cols-2 gap-3 max-h-60 overflow-y-auto p-1">
<label
v-for="agent in agents"
:key="agent.id"
class="flex items-center gap-2 p-3 border border-default rounded-lg cursor-pointer hover-surface-soft transition-colors"
:class="form.agent_ids.includes(agent.id) ? 'border-blue-500 bg-blue-50' : ''"
>
<input v-model="form.agent_ids" type="checkbox" :value="agent.id" class="w-4 h-4 text-blue-600 rounded focus:ring-blue-500" />
<span class="text-sm font-medium text-secondary">{{ agent.name }}</span>
</label>
</div>
</div>
</div>
<div class="admin-modal-footer admin-modal-footer--muted px-8 py-6">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button type="button" class="btn-primary disabled:opacity-50" :disabled="isSaving" @click="emit('save')">
{{ isSaving ? t('admin.save') + '...' : t('admin.perm.batchModal.apply') }}
</button>
</div>
</div>
</div>
<ElDialog
:model-value="visible"
:title="t('admin.perm.batchModal.title')"
width="480px"
align-center
append-to-body
:close-on-click-modal="false"
@update:model-value="onVisibleChange"
>
<p class="hx-element-hint">{{ t('admin.perm.batchModal.selected', { count: selectedCount }) }}</p>
<ElForm label-position="top" :model="form">
<ElFormItem :label="t('admin.perm.batchModal.action')">
<ElRadioGroup v-model="form.action">
<ElRadio value="add">{{ t('admin.perm.batchModal.add') }}</ElRadio>
<ElRadio value="remove">{{ t('admin.perm.batchModal.remove') }}</ElRadio>
<ElRadio value="set">{{ t('admin.perm.batchModal.set') }}</ElRadio>
</ElRadioGroup>
</ElFormItem>
<ElFormItem :label="t('admin.perm.batchModal.selectAgents')">
<ElCheckboxGroup v-model="form.agent_ids" class="grid max-h-60 grid-cols-2 gap-2 overflow-y-auto">
<ElCheckbox v-for="agent in agents" :key="agent.id" :value="agent.id">
{{ agent.name }}
</ElCheckbox>
</ElCheckboxGroup>
</ElFormItem>
</ElForm>
<template #footer>
<ElButton @click="emit('close')">{{ t('admin.cancel') }}</ElButton>
<ElButton type="primary" :loading="isSaving" @click="emit('save')">{{ t('admin.perm.batchModal.apply') }}</ElButton>
</template>
</ElDialog>
</template>
@@ -1,17 +1,30 @@
/**
* features/admin/modules/users/components/UserFormModal.vue
* 用途:创建/编辑用户弹窗。权限组启用后只选角色,不再按人勾应用或功能权限。
* 依赖:admin.types、user.types、permissionRole.types、roleLabel.LEGACY_ROLE_OPTIONS。
* 逻辑:UsersPage 传入角色列表;未种子权限组时保留历史 Agent / 培训 HR 勾选,角色下拉用旧枚举。
* 依赖:element-plus、admin.types、user.types、permissionRole.types、roleLabel.LEGACY_ROLE_OPTIONS。
* 逻辑:UsersPage 传入角色列表;未种子权限组时保留历史 Agent / 功能权限勾选,角色下拉用旧枚举。
* 本弹窗属于用户管理 Element Plus 试点。
*/
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import {
ElButton,
ElCheckbox,
ElCheckboxGroup,
ElDialog,
ElForm,
ElFormItem,
ElInput,
ElOption,
ElSelect,
} from 'element-plus';
import type { AdminAgentOption, AdminDepartmentRow } from '@/features/admin/types/admin.types';
import type { PermissionRoleRow } from '@/features/admin/types/permissionRole.types';
import type { UserFormState } from '@/features/admin/types/user.types';
import { LEGACY_ROLE_OPTIONS } from '@/features/admin/utils/roleLabel';
defineProps<{
const props = defineProps<{
visible: boolean;
form: UserFormState;
agents: AdminAgentOption[];
@@ -24,150 +37,142 @@ defineProps<{
const emit = defineEmits<{
close: [];
save: [];
'update:form': [UserFormState];
}>();
const { t } = useI18n();
/**
* 角色下拉。已配置权限组时用组名称,否则用历史角色枚举。
*/
const roleOptions = computed(() => {
if (props.rolesConfigured) {
return props.roles.map((role) => ({ value: role.code, label: role.name }));
}
return LEGACY_ROLE_OPTIONS.map((option) => ({ value: option.code, label: t(option.i18nKey) }));
});
/**
* 关闭弹窗并通知父页面收起。
* @param open - Element 对话框的打开状态
*/
function onVisibleChange(open: boolean): void {
if (!open) emit('close');
}
/**
* 部门选择。清空时写回空字符串,表示不指定部门。
* @param value - 选中的部门名;清空为 undefined
*/
function onDepartmentChange(value: string | undefined): void {
props.form.department = value ?? '';
}
</script>
<template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in">
<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.user.editUser') : t('admin.user.createUser') }}</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="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!form.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.realName') }}
</label>
<input v-model="form.real_name" type="text" class="w-full border-default rounded-xl px-4 py-3 text-sm" />
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!form.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.employeeId') }}
</label>
<input v-model="form.employee_id" type="text" class="w-full border-default rounded-xl px-4 py-3 text-sm" />
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!form.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.phone') }}
</label>
<input v-model="form.phone_number" type="text" class="w-full border-default rounded-xl px-4 py-3 text-sm" />
</div>
<div v-if="!rolesConfigured" class="space-y-1.5 col-span-1 md:col-span-2">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.user.fields.allowedAgents') }}</label>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3 mt-2">
<label
v-for="agent in agents"
:key="agent.id"
class="flex items-center gap-2 p-3 border border-default rounded-lg cursor-pointer hover-surface-soft transition-colors"
:class="form.agent_ids.includes(agent.id) ? 'border-blue-500 bg-blue-50' : ''"
>
<input v-model="form.agent_ids" type="checkbox" :value="agent.id" class="w-4 h-4 text-blue-600 rounded focus:ring-blue-500" />
<span class="text-sm font-medium text-secondary">{{ agent.name }}</span>
</label>
<ElDialog
:model-value="visible"
:title="form.id ? t('admin.user.editUser') : t('admin.user.createUser')"
width="680px"
align-center
append-to-body
:close-on-click-modal="false"
@update:model-value="onVisibleChange"
>
<div class="max-h-[65vh] overflow-y-auto pr-1">
<ElForm class="users-element-form" label-position="top" :model="form">
<ElFormItem :label="t('admin.user.fields.realName')" :required="!form.id">
<ElInput v-model="form.real_name" />
</ElFormItem>
<ElFormItem :label="t('admin.user.fields.employeeId')" :required="!form.id">
<ElInput v-model="form.employee_id" />
</ElFormItem>
<ElFormItem :label="t('admin.user.fields.phone')" :required="!form.id">
<ElInput v-model="form.phone_number" />
</ElFormItem>
<ElFormItem :label="t('admin.user.fields.username')" :required="!form.id">
<ElInput v-model="form.username" :disabled="!!form.id" />
</ElFormItem>
<ElFormItem :label="t('admin.user.fields.email')" :required="!form.id">
<ElInput v-model="form.email" />
</ElFormItem>
<ElFormItem :label="t('admin.user.fields.department')">
<ElSelect
:model-value="form.department || undefined"
class="w-full"
clearable
:placeholder="t('admin.user.allDepts')"
@update:model-value="onDepartmentChange"
>
<ElOption v-for="department in departments" :key="department.id" :label="department.name" :value="department.name" />
</ElSelect>
</ElFormItem>
<ElFormItem v-if="!rolesConfigured" class="users-form-span" :label="t('admin.user.fields.allowedAgents')">
<ElCheckboxGroup v-model="form.agent_ids">
<div class="grid grid-cols-1 gap-2 sm:grid-cols-2">
<ElCheckbox v-for="agent in agents" :key="agent.id" :value="agent.id">
{{ agent.name }}
</ElCheckbox>
</div>
</ElCheckboxGroup>
<p v-if="agents.length === 0" class="hx-element-hint">{{ t('admin.user.fields.noAgents') }}</p>
</ElFormItem>
<ElFormItem class="users-form-span" :label="t('admin.user.fields.role')" required>
<ElSelect v-model="form.role" class="w-full">
<ElOption v-for="option in roleOptions" :key="option.value" :label="option.label" :value="option.value" />
</ElSelect>
<p v-if="rolesConfigured" class="hx-element-hint">{{ t('admin.permRoles.userFormHint') }}</p>
</ElFormItem>
<ElFormItem v-if="!rolesConfigured" class="users-form-span" :label="t('admin.user.fields.featurePermissions')">
<div class="flex flex-col gap-3">
<ElCheckbox v-model="form.feature_permissions.training_hr_manage">
<span class="block">{{ t('admin.user.fields.trainingHrManage') }}</span>
<span class="hx-element-hint">{{ t('admin.user.fields.trainingHrManageHint') }}</span>
</ElCheckbox>
<ElCheckbox v-model="form.feature_permissions['contract_payment.access']">
<span class="block">{{ t('admin.user.fields.contractPaymentAccess') }}</span>
<span class="hx-element-hint">{{ t('admin.user.fields.contractPaymentAccessHint') }}</span>
</ElCheckbox>
<ElCheckbox v-model="form.feature_permissions['order_delivery_reply.manage']">
<span class="block">{{ t('admin.user.fields.orderDeliveryReplyManage') }}</span>
<span class="hx-element-hint">{{ t('admin.user.fields.orderDeliveryReplyManageHint') }}</span>
</ElCheckbox>
<ElCheckbox v-model="form.feature_permissions['order_delivery_reply.access']">
<span class="block">{{ t('admin.user.fields.orderDeliveryReplyAccess') }}</span>
<span class="hx-element-hint">{{ t('admin.user.fields.orderDeliveryReplyAccessHint') }}</span>
</ElCheckbox>
</div>
<p v-if="agents.length === 0" class="text-sm text-muted italic">{{ t('admin.user.fields.noAgents') }}</p>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!form.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.username') }}
</label>
<input v-model="form.username" type="text" class="w-full border-default rounded-xl px-4 py-3 text-sm" :disabled="!!form.id" />
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!form.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.email') }}
</label>
<input v-model="form.email" type="email" class="w-full border-default rounded-xl px-4 py-3 text-sm" />
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.user.fields.department') }}</label>
<select v-model="form.department" class="w-full border-default rounded-xl px-4 py-3 text-sm">
<option value="">{{ t('admin.user.allDepts') }}</option>
<option v-for="d in departments" :key="d.id" :value="d.name">{{ d.name }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.role') }}
</label>
<select v-if="rolesConfigured" v-model="form.role" class="w-full border-default rounded-xl px-4 py-3 text-sm">
<option v-for="role in roles" :key="role.code" :value="role.code">{{ role.name }}</option>
</select>
<select v-else v-model="form.role" class="w-full border-default rounded-xl px-4 py-3 text-sm">
<option
v-for="option in LEGACY_ROLE_OPTIONS"
:key="option.code"
:value="option.code"
>
{{ t(option.i18nKey) }}
</option>
</select>
<p v-if="rolesConfigured" class="text-xs text-muted">{{ t('admin.permRoles.userFormHint') }}</p>
</div>
<div v-if="!rolesConfigured" class="space-y-2 rounded-2xl border border-default bg-surface px-4 py-4">
<div class="text-xs font-semibold uppercase tracking-wider text-muted">{{ t('admin.user.fields.featurePermissions') }}</div>
<label class="flex items-start gap-3 rounded-xl border border-default bg-white px-4 py-3">
<input
v-model="form.feature_permissions.training_hr_manage"
type="checkbox"
class="mt-0.5 h-4 w-4 rounded border-default text-brand-600 focus:ring-brand-500"
/>
<span class="space-y-1">
<span class="block text-sm font-medium text-primary">{{ t('admin.user.fields.trainingHrManage') }}</span>
<span class="block text-xs leading-5 text-muted">{{ t('admin.user.fields.trainingHrManageHint') }}</span>
</span>
</label>
<label class="flex items-start gap-3 rounded-xl border border-default bg-white px-4 py-3">
<input
v-model="form.feature_permissions['contract_payment.access']"
type="checkbox"
class="mt-0.5 h-4 w-4 rounded border-default text-brand-600 focus:ring-brand-500"
/>
<span class="space-y-1">
<span class="block text-sm font-medium text-primary">{{ t('admin.user.fields.contractPaymentAccess') }}</span>
<span class="block text-xs leading-5 text-muted">{{ t('admin.user.fields.contractPaymentAccessHint') }}</span>
</span>
</label>
<label class="flex items-start gap-3 rounded-xl border border-default bg-white px-4 py-3">
<input
v-model="form.feature_permissions['order_delivery_reply.manage']"
type="checkbox"
class="mt-0.5 h-4 w-4 rounded border-default text-brand-600 focus:ring-brand-500"
/>
<span class="space-y-1">
<span class="block text-sm font-medium text-primary">{{ t('admin.user.fields.orderDeliveryReplyManage') }}</span>
<span class="block text-xs leading-5 text-muted">{{ t('admin.user.fields.orderDeliveryReplyManageHint') }}</span>
</span>
</label>
<label class="flex items-start gap-3 rounded-xl border border-default bg-white px-4 py-3">
<input
v-model="form.feature_permissions['order_delivery_reply.access']"
type="checkbox"
class="mt-0.5 h-4 w-4 rounded border-default text-brand-600 focus:ring-brand-500"
/>
<span class="space-y-1">
<span class="block text-sm font-medium text-primary">{{ t('admin.user.fields.orderDeliveryReplyAccess') }}</span>
<span class="block text-xs leading-5 text-muted">{{ t('admin.user.fields.orderDeliveryReplyAccessHint') }}</span>
</span>
</label>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!form.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.password') }}
<span v-if="form.id" class="text-muted font-normal lowercase">{{ t('admin.user.fields.passwordHint') }}</span>
</label>
<input v-model="form.password" type="password" class="w-full border-default rounded-xl px-4 py-3 text-sm" />
</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>
</ElFormItem>
<ElFormItem class="users-form-span" :label="t('admin.user.fields.password')" :required="!form.id">
<ElInput v-model="form.password" type="password" show-password />
<p v-if="form.id" class="hx-element-hint">{{ t('admin.user.fields.passwordHint') }}</p>
</ElFormItem>
</ElForm>
</div>
</div>
<template #footer>
<ElButton @click="emit('close')">{{ t('admin.cancel') }}</ElButton>
<ElButton type="primary" :loading="isSaving" @click="emit('save')">{{ t('admin.save') }}</ElButton>
</template>
</ElDialog>
</template>
<style scoped>
.users-element-form {
display: grid;
grid-template-columns: 1fr 1fr;
column-gap: 16px;
}
.users-element-form :deep(.el-form-item) {
margin-bottom: 14px;
}
.users-element-form :deep(.users-form-span) {
grid-column: 1 / -1;
}
@media (max-width: 640px) {
.users-element-form {
grid-template-columns: 1fr;
}
}
</style>
@@ -3,10 +3,12 @@
* 用途:用户管理模块业务逻辑(CRUD、服务端筛选分页、用户/部门列排序、批量操作)。
* 依赖:admin.api、useMessage、useTableSort、permissionRole.types。
* 逻辑:UsersPage 调用本 composable;列表经 listAdminUsersPage 按页拉取,排序参数随请求下发。
* 权限组启用后创建用户预填默认角色,改角色须确认;批量按人授权入口关闭。
* 权限组启用后创建用户预填默认角色;删除和改角色用 Element 确认框。批量按人授权入口关闭。
* Element Plus 表格通过 applyServerSort 写入列排序。
*/
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessageBox } from 'element-plus';
import {
batchDeleteAdminUsers,
batchUpdateAdminPermissions,
@@ -68,10 +70,6 @@ export function useUsersAdmin() {
const showUserModal = ref(false);
const editingUser = ref<UserFormState>(createEmptyUserForm());
const originalUserRole = ref('user');
const showRoleConfirm = ref(false);
const roleConfirmMessage = ref('');
let pendingUserSave: (() => Promise<void>) | null = null;
let pendingBatchSave: (() => Promise<void>) | null = null;
const showBatchEditModal = ref(false);
const batchEditForm = ref<BatchEditForm>({ department: '', role: '', status: '' });
@@ -79,9 +77,6 @@ export function useUsersAdmin() {
const showBatchPermissionModal = ref(false);
const batchPermissionForm = ref<BatchPermissionForm>({ agent_ids: [], action: 'add' });
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
/** 当前页是否已全部选中 */
const allPaginatedUsersSelected = computed(
@@ -194,25 +189,41 @@ export function useUsersAdmin() {
}, 300);
}, { deep: true });
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;
/**
* 用 Element 确认框询问后再执行删除。
* 核心逻辑:取消时 MessageBox 会 reject,这里吞掉,不调用 action。
* @param message - 确认文案
* @param action - 用户点确定后执行的删除
*/
const openDeleteConfirm = async (message: string, action: () => Promise<void> | void): Promise<void> => {
try {
await ElMessageBox.confirm(message, t('common.deleteDialog.defaultTitle'), {
type: 'warning',
confirmButtonText: t('common.deleteDialog.confirm'),
cancelButtonText: t('common.deleteDialog.cancel'),
});
} catch {
return;
}
await action();
};
/**
* 执行待确认的删除操作。
* 核心逻辑:先快照 action 并立即关闭弹窗,再 await 删除与刷新,避免异步完成前弹窗无法关闭。
* 用 Element 确认框询问改角色,确定后执行保存。
* 核心逻辑:与删除确认同一组件,避免一页两种确认框。取消则不保存。
* @param message - 角色变更说明
* @param action - 用户点确定后提交
*/
const confirmDelete = async (): Promise<void> => {
const action = deleteConfirmAction;
closeDeleteConfirm();
if (!action) return;
const confirmRoleThen = async (message: string, action: () => Promise<void>): Promise<void> => {
try {
await ElMessageBox.confirm(message, t('admin.permRoles.userRoleConfirmTitle'), {
type: 'warning',
confirmButtonText: t('admin.save'),
cancelButtonText: t('admin.cancel'),
});
} catch {
return;
}
await action();
};
@@ -296,11 +307,10 @@ export function useUsersAdmin() {
: nextRole !== originalUserRole.value;
const touchesAdmin = isAdminRoleCode(nextRole) || isAdminRoleCode(originalUserRole.value);
if (roleChanged) {
roleConfirmMessage.value = touchesAdmin
const message = touchesAdmin
? t('admin.permRoles.userAdminConfirm')
: t('admin.permRoles.userRoleConfirm', { role: nextRole });
pendingUserSave = persistUser;
showRoleConfirm.value = true;
await confirmRoleThen(message, persistUser);
return;
}
await persistUser();
@@ -348,28 +358,6 @@ export function useUsersAdmin() {
}
};
/**
* 确认改角色(含管理员)后再提交。
*/
const confirmRoleChange = async (): Promise<void> => {
const userSave = pendingUserSave;
const batchSave = pendingBatchSave;
pendingUserSave = null;
pendingBatchSave = null;
showRoleConfirm.value = false;
if (userSave) {
await userSave();
return;
}
if (batchSave) await batchSave();
};
const closeRoleConfirm = (): void => {
pendingUserSave = null;
pendingBatchSave = null;
showRoleConfirm.value = false;
};
const cleanRejectedUsers = async (): Promise<void> => {
openDeleteConfirm(t('admin.user.confirmClean'), async () => {
try {
@@ -446,11 +434,10 @@ export function useUsersAdmin() {
return;
}
if (data.role) {
roleConfirmMessage.value = isAdminRoleCode(data.role)
const message = isAdminRoleCode(data.role)
? t('admin.permRoles.userAdminConfirm')
: t('admin.permRoles.batchRoleConfirm');
pendingBatchSave = () => persistBatchEdit(data);
showRoleConfirm.value = true;
await confirmRoleThen(message, () => persistBatchEdit(data));
return;
}
await persistBatchEdit(data);
@@ -504,6 +491,19 @@ export function useUsersAdmin() {
scheduleLoadUsers(true);
};
/**
* 按指定列和方向重新查询第一页。
* 核心逻辑:方向未变时不请求;变更后回到第一页再拉取。
* @param key - username 或 department,与后端 sort_by 白名单一致
* @param dir - asc 或 desc
*/
const applyServerSort = (key: UserSortKey, dir: 'asc' | 'desc'): void => {
if (sortKey.value === key && sortDir.value === dir) return;
sortKey.value = key;
sortDir.value = dir;
scheduleLoadUsers(true);
};
return {
users,
agents,
@@ -530,12 +530,9 @@ export function useUsersAdmin() {
batchEditForm,
showBatchPermissionModal,
batchPermissionForm,
showDeleteConfirmDialog,
deleteConfirmMessage,
showRoleConfirm,
roleConfirmMessage,
loadAll,
toggleSort,
applyServerSort,
openCreateUserModal,
openEditUserModal,
saveUser,
@@ -547,9 +544,5 @@ export function useUsersAdmin() {
openBatchPermissionModal,
submitBatchEdit,
submitBatchPermission,
closeDeleteConfirm,
confirmDelete,
confirmRoleChange,
closeRoleConfirm,
};
}
@@ -0,0 +1,110 @@
/**
* features/admin/styles/element-trial.css
* 用途:管理端 Element Plus 的字体、字号、颜色、圆角、控件高度,以及和 Tailwind 共存的修正。
* 依赖:tokens.css 的 --text-* / --bg-* / --border-*,element-plus 暗色变量,Tailwind preflight。
* 逻辑:由 UsersPage、AgentsPage、KbAdminPanel 在暗色 CSS 之后引入,所以 html.dark 能盖过 Element 默认暗色。
* 字号和颜色以本文变量为准。页面不要再用 text-sm / text-muted 改表格和按钮。
*/
:root,
html.dark {
--el-color-primary: #0284c7;
--el-color-primary-light-3: #4da3d6;
--el-color-primary-light-5: #81c2e3;
--el-color-primary-light-7: #b4daf0;
--el-color-primary-light-8: #cde6f4;
--el-color-primary-light-9: #e6f3fa;
--el-color-primary-dark-2: #0269a0;
--el-font-family: "PingFang SC", "Microsoft YaHei", "Segoe UI", system-ui, sans-serif;
--el-font-size-extra-large: 20px;
--el-font-size-large: 18px;
--el-font-size-medium: 16px;
--el-font-size-base: 14px;
--el-font-size-small: 13px;
--el-font-size-extra-small: 12px;
--el-text-color-primary: var(--text-primary);
--el-text-color-regular: var(--text-secondary);
--el-text-color-secondary: var(--text-muted);
--el-text-color-placeholder: var(--text-muted);
--el-text-color-disabled: var(--text-muted);
--el-border-color: var(--border-default);
--el-border-color-light: var(--border-subtle);
--el-border-color-lighter: var(--border-subtle);
--el-bg-color: var(--bg-surface);
--el-bg-color-overlay: var(--bg-surface);
--el-fill-color-blank: var(--bg-surface);
--el-fill-color-light: var(--bg-surface-soft);
--el-border-radius-base: 8px;
--el-component-size: 32px;
}
.el-button {
display: inline-flex;
align-items: center;
justify-content: center;
}
.el-button .el-icon,
.el-button svg {
display: inline-flex;
flex: none;
}
/* Tailwind forms 会给单行输入框内部的 input 加边框。聚焦时左右两边会多出两条蓝线。
多行输入框的边框就画在 .el-textarea__inner 上,不能一起清掉。 */
.el-input__inner,
.el-select__input,
.el-range-input,
.el-input__inner:hover,
.el-select__input:hover,
.el-range-input:hover,
.el-input__inner:focus,
.el-select__input:focus,
.el-range-input:focus {
border: 0;
outline: none;
background-color: transparent;
box-shadow: none;
--tw-ring-shadow: 0 0 #0000;
--tw-ring-offset-shadow: 0 0 #0000;
}
.el-textarea__inner {
background-color: var(--el-input-bg-color, var(--el-fill-color-blank));
box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color)) inset;
}
.el-textarea__inner:hover {
box-shadow: 0 0 0 1px var(--el-input-hover-border-color, var(--el-border-color-hover)) inset;
}
.el-textarea__inner:focus {
outline: none;
box-shadow: 0 0 0 1px var(--el-input-focus-border-color, var(--el-color-primary)) inset;
--tw-ring-shadow: 0 0 #0000;
--tw-ring-offset-shadow: 0 0 #0000;
}
/* 列表首尾列与页头 32px 对齐;分页贴在表格下方 */
.hx-admin-table .el-table__cell:first-child .cell {
padding-left: 32px;
}
.hx-admin-table .el-table__cell:last-child .cell {
padding-right: 32px;
}
.hx-admin-pager {
display: flex;
justify-content: flex-end;
padding: 12px 32px;
border-top: 1px solid var(--el-border-color-lighter);
}
/* 表单里的补充说明,字号和颜色走 Element 变量 */
.hx-element-hint {
margin-top: 4px;
font-size: var(--el-font-size-extra-small);
line-height: 1.4;
color: var(--el-text-color-secondary);
}