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,76 @@
/**
* frontend/eslint-rules/no-legacy-admin-controls.js
* 用途:管理端 Vue 里禁止再写原生表单控件、旧按钮样式和 lucide 图标。
* 依赖:vue-eslint-parser 提供的 VElement、VAttribute,以及脚本里的 ImportDeclaration。
* 逻辑:由 eslint.config.js 以 hxops/no-legacy-admin-controls 挂上。当前严重级别为 off。
* 改为 error 的步骤见 docs/ui/ELEMENT_MIGRATION.md §9。
*/
const LEGACY_TAGS = new Set(['button', 'input', 'select', 'textarea']);
const LEGACY_CLASSES = [
'btn-primary',
'btn-secondary',
'btn-ghost',
'btn-danger',
'input-field',
'select-field',
];
/**
* 判断属性是不是 class 或 :class。
* 核心逻辑:静态 class 的 key 是 VIdentifier;绑定 class 的 key 是 VDirectiveKey,参数名才是 class。
* @param key vue-eslint-parser 的属性键节点
* @returns 是 class 绑定则为 true
*/
function isClassAttribute(key) {
if (key?.type === 'VIdentifier') return key.name === 'class';
return key?.type === 'VDirectiveKey' && key.argument?.name === 'class';
}
/** @type {import('eslint').Rule.RuleModule} */
const rule = {
meta: {
type: 'problem',
docs: {
description: '管理端界面使用 Element Plus,不再新增原生控件和旧样式类',
},
schema: [],
messages: {
tag: '管理端请使用 Element Plus,不要新增 <{{name}}>。见 docs/ui/ELEMENT_MIGRATION.md。',
klass: '管理端请使用 Element Plus,不要新增样式类 {{name}}。见 docs/ui/ELEMENT_MIGRATION.md。',
lucide: '管理端按钮图标请使用 @element-plus/icons-vue,不要新增 lucide-vue-next。',
},
},
create(context) {
const templateVisitor = {
VElement(node) {
const name = node.rawName || node.name;
if (!LEGACY_TAGS.has(name)) return;
context.report({ node, messageId: 'tag', data: { name } });
},
VAttribute(node) {
if (!isClassAttribute(node.key)) return;
const raw = context.sourceCode.getText(node);
for (const name of LEGACY_CLASSES) {
if (!raw.includes(name)) continue;
context.report({ node, messageId: 'klass', data: { name } });
}
},
};
const scriptVisitor = {
ImportDeclaration(node) {
if (node.source?.value !== 'lucide-vue-next') return;
context.report({ node, messageId: 'lucide' });
},
};
// 模板节点不会出现在脚本的遍历里,必须交给 vue-eslint-parser 分开访问。
const defineTemplateBodyVisitor = context.sourceCode.parserServices?.defineTemplateBodyVisitor;
if (typeof defineTemplateBodyVisitor === 'function') {
return defineTemplateBodyVisitor(templateVisitor, scriptVisitor);
}
return scriptVisitor;
},
};
export default rule;
+43
View File
@@ -0,0 +1,43 @@
/**
* frontend/eslint.config.js
* 用途:前端 ESLint 配置。目前只挂管理端 Element 迁移规则,且严重级别为 off。
* 依赖:vue-eslint-parser、typescript-eslint、eslint-rules/no-legacy-admin-controls.js。
* 逻辑:npm run lint 会加载本文件,但不会因为历史原生控件失败。
* 启用步骤见 docs/ui/ELEMENT_MIGRATION.md §9。不要把 lint 接进 npm run build。
*/
import vueParser from 'vue-eslint-parser';
import tseslint from 'typescript-eslint';
import noLegacyAdminControls from './eslint-rules/no-legacy-admin-controls.js';
export default [
{
ignores: ['dist/**', 'node_modules/**', 'coverage/**'],
},
{
files: [
'src/features/admin/**/*.vue',
'src/features/kb/components/KbAdminPanel.vue',
'src/features/kb/components/KbGroupDrawer.vue',
],
languageOptions: {
parser: vueParser,
parserOptions: {
parser: tseslint.parser,
extraFileExtensions: ['.vue'],
ecmaVersion: 'latest',
sourceType: 'module',
},
},
plugins: {
hxops: {
rules: {
'no-legacy-admin-controls': noLegacyAdminControls,
},
},
},
rules: {
// 启用时改为 'error'。步骤见 docs/ui/ELEMENT_MIGRATION.md §9。
'hxops/no-legacy-admin-controls': 'off',
},
},
];
+1461 -4
View File
File diff suppressed because it is too large. Load diff
+7
View File
@@ -7,15 +7,18 @@
"dev": "vite",
"build": "vue-tsc -b && vite build",
"preview": "vite preview",
"lint": "eslint .",
"test:unit": "vitest run"
},
"dependencies": {
"@element-plus/icons-vue": "^2.3.2",
"@tailwindcss/forms": "^0.5.11",
"@tailwindcss/typography": "^0.5.19",
"@vue-office/docx": "^1.6.3",
"@vue-office/excel": "^1.7.14",
"@vue-office/pdf": "^1.6.5",
"cron-parser": "^5.5.0",
"element-plus": "^2.14.7",
"highlight.js": "^11.11.1",
"html2pdf.js": "^0.14.0",
"lucide-vue-next": "^0.575.0",
@@ -37,12 +40,16 @@
"@vue/test-utils": "^2.4.11",
"@vue/tsconfig": "^0.8.1",
"autoprefixer": "^10.4.24",
"eslint": "^10.12.0",
"eslint-plugin-vue": "^10.11.1",
"jsdom": "^29.1.1",
"postcss": "^8.5.6",
"tailwindcss": "^3.4.17",
"typescript": "~5.9.3",
"typescript-eslint": "^8.71.2",
"vite": "^8.0.0-beta.13",
"vitest": "^4.1.8",
"vue-eslint-parser": "^10.4.1",
"vue-tsc": "^3.1.5"
},
"overrides": {
+16 -5
View File
@@ -4,6 +4,7 @@
* 根组件:主题初始化、全局消息弹窗、401 登出监听、html lang 与 i18n locale 同步。
* 依赖:useTheme、useGlobalMessageDialog、auth、linked-nav.store。
* 逻辑:已登录时预取关联服务侧栏入口,避免页面切换后入口后闪现。
* 书签/刷新冷启动遇到 401 时只回登录页;本页已确认会话后中途失效才弹窗。
*/
import { useI18n } from 'vue-i18n';
import { watch, onMounted, onBeforeUnmount } from 'vue';
@@ -11,7 +12,7 @@ import { useTheme } from '@/shared/composables/useTheme';
import LevelMessageDialog from '@/shared/components/LevelMessageDialog.vue';
import { useGlobalMessageDialog } from '@/shared/composables/useGlobalMessageDialog';
import { useRouter } from 'vue-router';
import { getAuthHeaders, logoutAuth } from '@/shared/utils/auth';
import { getAuthHeaders, logoutAuth, markAuthSessionConfirmed, shouldPromptOnSessionUnauthorized } from '@/shared/utils/auth';
import { isPublicPath } from '@/shared/constants/routes';
import { useLinkedNavStore } from '@/features/sso/stores/linked-nav.store';
@@ -66,8 +67,9 @@ watch(themePreference, (newTheme) => {
});
/**
* 处理接口返回未登录状态,提示用户重新登录并清理失效的本地登录信息。
* 核心逻辑:忽略可选的关联服务/SSO 目录请求;其余未授权请求统一展示易懂提示,再执行登出。
* 处理接口返回未登录状态,清理失效的本地登录信息。
* 核心逻辑:忽略可选的关联服务/SSO 目录请求。书签或刷新带来的冷启动 401 只回登录页;
* 本页已经成功加载过首页后会话才中途失效时,再提示重新登录。
* @param event - 包含请求地址和状态码的全局未授权事件。
*/
const onUnauthorized = (event: Event) => {
@@ -75,10 +77,17 @@ const onUnauthorized = (event: Event) => {
// 侧栏入口目录是可选导航能力,加载失败只能隐藏入口,不能清除有效 HXOPS 登录态。
if (/\/api\/sso\/apps(?:\?|$)/.test(url)) return;
if (/\/api\/linked-services(?:\?|$)/.test(url)) return;
showMessageDialog('error', t('login.sessionExpiredHint'), t('login.sessionExpired'));
if (shouldPromptOnSessionUnauthorized()) {
showMessageDialog('error', t('login.sessionExpiredHint'), t('login.sessionExpired'));
}
logoutAuth();
};
/**
* 登出后离开需要登录的页面。
* 核心逻辑:带上当前 fullPath 作为 redirect,登录成功后回到书签原来的地址。
* @param event - hxops:logout,remote 为 true 表示其他标签页触发。
*/
const onLogout = (event: Event) => {
useLinkedNavStore().reset();
const detail = (event as CustomEvent<{ remote?: boolean }>).detail;
@@ -87,7 +96,8 @@ const onLogout = (event: Event) => {
}
const path = router.currentRoute.value.path;
if (!isPublicPath(path)) {
router.push('/login');
const redirect = router.currentRoute.value.fullPath;
router.push({ path: '/login', query: { redirect } });
}
};
@@ -104,6 +114,7 @@ onMounted(async () => {
try {
const res = await fetch('/api/user/home', { headers });
if (res.ok) {
markAuthSessionConfirmed();
const data = await res.json();
if (data.user && data.user.language) {
locale.value = data.user.language;
@@ -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);
}
@@ -673,6 +673,30 @@ export const confirmWorkspaceShippingOrderReviewCustomer = (
},
);
/**
* 确认客户改绑:直接修改已确认客户并按新客户重冻结订单快照。
* 核心逻辑:携带 expected_order_data_version 乐观锁;Excel 已产生/存在活动 Gate Attempt 时后端 409
* (SHIPPING.CUSTOMER_REBIND_BLOCKED),版本漂移返回 SHIPPING.ORDER_DATA_VERSION_MISMATCH,
* 均由调用方以 BusinessError localized message 展示。
* @param caseNo - 复核 Case 编号
* @param payload - 新客户 ID、expected_order_data_version(case 投影 order_data_version)与可选原因
*/
export const rebindWorkspaceShippingOrderReviewCustomer = (
caseNo: string,
payload: { customer_id: number; expected_order_data_version: number; reason?: string },
) => requestJson<{
case: ShippingOrderReviewCase | null;
customer_resolution: ShippingOrderReviewCustomerResolution | null;
rebind: { previous_customer_id?: number | null; customer_id: number; snapshot_id: number };
}>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/customer/rebind`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
},
);
/**
* 重新检测建单前重复订单。
*/
@@ -236,3 +236,27 @@ export const retryTransferSourceRpa = (sourceCode: string) =>
method: 'POST',
headers: jsonHeaders(),
});
/** 批量来源重试响应:triggered=是否写了 batch trigger;results 逐来源真实结果 */
export interface TransferRetryRpaBatchResult {
ok: boolean;
triggered: boolean;
trigger_path?: string;
error_code?: string;
results: Array<{
source_code: string;
ok: boolean;
reparsed?: boolean;
file_status?: string;
error_code?: string;
}>;
}
/** 批量重试(2026-10-09):多来源合并写一个 batch trigger 文件,
* Worker 单次浏览器会话串行导出全部来源(逐来源单文件会开/关 N 次浏览器) */
export const retryTransferSourcesRpaBatch = (sourceCodes: string[]) =>
requestJson<TransferRetryRpaBatchResult>(`${BASE}/sources/retry-rpa-batch`, {
method: 'POST',
headers: jsonHeaders(),
body: JSON.stringify({ source_codes: sourceCodes }),
});
@@ -4,12 +4,12 @@
* 用途:对话页主区域,组合侧栏、消息列表、输入栏、货代会话 Workflow 时间线与内置浏览器。
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingWorkflowTimeline、ContractPaymentChatPanel、VoucherCheckChatPanel、chunkLoadRecovery、chat.context。
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingWorkflowTimeline、ContractPaymentChatPanel、EquipmentAcceptanceChatPanel、VoucherCheckChatPanel、chunkLoadRecovery、chat.context。
* 逻辑:本文件只做页面结构编排;货代 Chat 仅上传/进度通知,履约写操作不在本页;
* 货代会话主区域:有会话即全屏批次进度中心(常驻),无会话为欢迎页+输入框;会话标题取自侧栏历史并传给中心;
* 右侧「本次处理」由 conversationId 驱动 Workflow projection,extractionRunNo 仅作进度装饰;
* 订单复核工作台异步分包,避免普通对话首屏拉取 PDF.js;合同付款预警、立账凭证 Agent 用 Tab 作业面替换消息列表与输入框。
* 订单复核工作台异步分包,避免普通对话首屏拉取 PDF.js;合同付款预警、设备验收预警、立账凭证 Agent 用作业面替换消息列表与输入框。
*/
@@ -47,7 +47,7 @@ import { useChatPageContext } from '@/features/chat/composables/chat.context';
import { matchesTrainingAgent } from '@/features/chat/training/trainingWorkspace.utils';
import { agentHasIntentUiProfile, resolveAgentCode, AGENT_CODE_IN_TRANSIT_TRANSFER, isContractPaymentAgent, isVoucherCheckAgent } from '@/shared/utils/agent-registry.utils';
import { agentHasIntentUiProfile, resolveAgentCode, AGENT_CODE_IN_TRANSIT_TRANSFER, isContractPaymentAgent, isEquipmentAcceptanceAgent, isVoucherCheckAgent } from '@/shared/utils/agent-registry.utils';
import {
SHIPPING_WORKFLOW_KEY,
@@ -79,6 +79,10 @@ const ContractPaymentChatPanel = defineRecoverableAsyncComponent(
() => import('@/features/contract-payment/components/ContractPaymentChatPanel.vue'),
);
const EquipmentAcceptanceChatPanel = defineRecoverableAsyncComponent(
() => import('@/features/equipment-acceptance/components/EquipmentAcceptanceChatPanel.vue'),
);
const VoucherCheckChatPanel = defineRecoverableAsyncComponent(
() => import('@/features/voucher-check/components/VoucherCheckChatPanel.vue'),
);
@@ -130,11 +134,14 @@ const isInTransitTransferAgent = computed(() => resolveAgentCode(page.currentAge
/** 合同付款预警 Agent:主区嵌台账 Tab,隐藏对话输入与历史。 */
const isContractPaymentAgentPage = computed(() => isContractPaymentAgent(page.currentAgent));
/** 设备验收预警 Agent:主区嵌停留列表,隐藏对话输入与历史。 */
const isEquipmentAcceptanceAgentPage = computed(() => isEquipmentAcceptanceAgent(page.currentAgent));
/** 立账凭证 Agent:主区嵌检核任务 / 企微发送记录 Tab,隐藏对话输入与历史。 */
const isVoucherCheckAgentPage = computed(() => isVoucherCheckAgent(page.currentAgent));
/** builtin 作业面 Agent 共用:隐藏新会话、历史列表与输入框。 */
const hideTaskChatSessionUi = computed(() => isContractPaymentAgentPage.value || isVoucherCheckAgentPage.value);
const hideTaskChatSessionUi = computed(() => isContractPaymentAgentPage.value || isEquipmentAcceptanceAgentPage.value || isVoucherCheckAgentPage.value);
/** 在途仓自动调拨业务流激活(来源选择/待处理等子视图)时隐藏聊天输入框,模拟业务页。 */
const transferFlowActive = ref(false);
@@ -489,6 +496,8 @@ watch(() => page.currentAgentId, () => {
<ContractPaymentChatPanel v-else-if="isContractPaymentAgentPage" />
<EquipmentAcceptanceChatPanel v-else-if="isEquipmentAcceptanceAgentPage" />
<VoucherCheckChatPanel v-else-if="isVoucherCheckAgentPage" />
<div v-else class="flex min-h-0 min-w-0 flex-1">
@@ -25,17 +25,20 @@ watch(() => props.open, (open) => {
</script>
<template>
<div v-if="open" class="admin-modal-overlay animate-fade-in items-center z-[170]">
<div class="admin-modal-panel max-w-xl max-h-[90vh] scale-100">
<div class="px-6 py-5 border-b border-subtle"><h3 class="section-title">{{ t('chat.shippingCustomer.title') }}</h3><p class="section-desc mt-1">{{ t('chat.shippingCustomer.subtitle') }}</p></div>
<div class="px-6 py-5 space-y-4 overflow-y-auto">
<div class="flex gap-2"><input v-model="query" class="input-field text-sm" :placeholder="t('chat.shippingCustomer.searchPlaceholder')" @keyup.enter="emit('search', query)" /><button type="button" class="btn-ghost" @click="emit('search', query)">{{ t('chat.shippingCustomer.search') }}</button></div>
<div class="space-y-2 max-h-80 overflow-y-auto">
<label v-for="customer in options" :key="customer.id" class="flex items-center gap-3 rounded-xl border border-default p-3 cursor-pointer hover:border-brand-300"><input v-model="selectedId" type="radio" :value="customer.id" /><span class="flex-1"><span class="font-medium text-primary">{{ customer.standard_name }}</span><span class="ml-2 font-mono text-xs text-muted">{{ customer.short_code }}</span></span></label>
<div v-if="!loading && !options.length" class="text-sm text-muted py-8 text-center">{{ t('chat.shippingCustomer.empty') }}</div>
<!-- Teleport 到 body:面板/工作区子树的层叠上下文会让页内 fixed 遮罩被粘性列表穿透。 -->
<Teleport to="body">
<div v-if="open" class="admin-modal-overlay animate-fade-in items-center z-[170]">
<div class="admin-modal-panel max-w-xl max-h-[90vh] scale-100">
<div class="px-6 py-5 border-b border-subtle"><h3 class="section-title">{{ t('chat.shippingCustomer.title') }}</h3><p class="section-desc mt-1">{{ t('chat.shippingCustomer.subtitle') }}</p></div>
<div class="px-6 py-5 space-y-4 overflow-y-auto">
<div class="flex min-w-0 gap-2"><input v-model="query" class="input-field min-w-0 flex-1 text-sm" :placeholder="t('chat.shippingCustomer.searchPlaceholder')" @keyup.enter="emit('search', query)" /><button type="button" class="btn-ghost shrink-0 whitespace-nowrap" @click="emit('search', query)">{{ t('chat.shippingCustomer.search') }}</button></div>
<div class="space-y-2 max-h-80 overflow-y-auto">
<label v-for="customer in options" :key="customer.id" class="flex cursor-pointer items-center gap-3 rounded-xl border p-3" :class="selectedId === customer.id ? 'border-brand-500 bg-brand-50' : 'border-default hover:border-brand-300'"><input v-model="selectedId" type="radio" :value="customer.id" class="accent-brand-600" /><span class="flex-1"><span class="font-medium text-primary">{{ customer.standard_name }}</span><span class="ml-2 font-mono text-xs text-muted">{{ customer.short_code }}</span></span></label>
<div v-if="!loading && !options.length" class="text-sm text-muted py-8 text-center">{{ t('chat.shippingCustomer.empty') }}</div>
</div>
</div>
<div class="admin-modal-footer"><button type="button" class="btn-ghost" @click="emit('close')">{{ t('common.cancel') }}</button><button type="button" class="btn-primary" :disabled="!selectedId || loading" @click="selectedId && emit('confirm', selectedId)">{{ t('chat.shippingCustomer.confirm') }}</button></div>
</div>
<div class="admin-modal-footer"><button type="button" class="btn-ghost" @click="emit('close')">{{ t('common.cancel') }}</button><button type="button" class="btn-primary" :disabled="!selectedId || loading" @click="selectedId && emit('confirm', selectedId)">{{ t('chat.shippingCustomer.confirm') }}</button></div>
</div>
</div>
</Teleport>
</template>
@@ -4,6 +4,8 @@
* 依赖:Vue computed、lucide 图标、消息附件/Leave/Shipping 子组件、chat.types 与页面级 handlers。
* 逻辑:由 ChatMessageList 按消息逐条挂载;货代履约写按钮不在气泡内渲染,仅展示只读卡与深链通知。
* 用户附件区支持 summaryOnly:下方已有抽取进度卡时只显示附件摘要。
* 助手 Markdown 排版在本组件内收口:全局 base 只恢复标题字重,列表序号/圆点、
* 层级缩进与标题字号层级由 scoped 样式统一补齐,避免回答渲染成无结构平铺文本。
* 兼容:同时承接采购合同审查、库存映射、订单提取和 Mermaid 展示。
*/
<script setup lang="ts">
@@ -1140,6 +1142,109 @@ function handleInlineDownload(file: InlineDownloadFile): void {
max-width: 100%;
}
/* ── Markdown 正文排版:标题层级 / 列表序号 / 层级缩进 ─────────────────────
背景:Tailwind preflight 会把 ul/ol 重置为无序号、无圆点、无缩进,Dify 返回的
结构化回答(### 标题 + 多级列表 + 有序步骤)会被渲染成平铺文本;
全局 base 层只恢复了标题字重,这里按聊天回答的高频结构统一补齐排版。 */
:deep(.chat-markdown h1),
:deep(.chat-markdown h2),
:deep(.chat-markdown h3) {
margin: 1em 0 0.5em;
font-size: 1.125rem;
line-height: 1.45;
}
:deep(.chat-markdown h4),
:deep(.chat-markdown h5),
:deep(.chat-markdown h6) {
margin: 0.875em 0 0.375em;
font-size: 1rem;
line-height: 1.5;
}
:deep(.chat-markdown p) {
margin: 0.5em 0;
}
:deep(.chat-markdown strong) {
font-weight: 600;
color: var(--text-primary);
}
/* 列表缩进与序号:无序列表逐层 disc/circle/square 区分层级;有序列表(操作步骤)
无论嵌套在第几层都保持 1. 2. 3. 数字序号,与回答里“步骤”的业务语义一致 */
:deep(.chat-markdown ul),
:deep(.chat-markdown ol) {
margin: 0.375rem 0;
padding-left: 1.375rem;
}
:deep(.chat-markdown ul) {
list-style-type: disc;
}
:deep(.chat-markdown ol) {
list-style-type: decimal;
}
:deep(.chat-markdown ul ul) {
list-style-type: circle;
}
:deep(.chat-markdown ul ul ul) {
list-style-type: square;
}
:deep(.chat-markdown li) {
margin: 0.25rem 0;
}
:deep(.chat-markdown li::marker) {
color: var(--text-muted);
}
:deep(.chat-markdown li > p) {
margin: 0.25rem 0;
}
:deep(.chat-markdown li > ul),
:deep(.chat-markdown li > ol) {
margin: 0.25rem 0;
}
/* 气泡内首尾元素贴边,避免首行/末行出现额外空隙 */
:deep(.chat-markdown > :first-child) {
margin-top: 0;
}
:deep(.chat-markdown > :last-child) {
margin-bottom: 0;
}
/* 链接 / 引用 / 分隔线:颜色走主题令牌,暗色由变量自适应 */
:deep(.chat-markdown a) {
color: rgb(29 78 216);
text-decoration: underline;
text-underline-offset: 2px;
}
:deep(.dark .chat-markdown a) {
color: rgb(147 197 253);
}
:deep(.chat-markdown blockquote) {
margin: 0.5em 0;
padding: 0.125rem 0.875rem;
border-left: 3px solid var(--border-default);
color: var(--text-muted);
}
:deep(.chat-markdown hr) {
margin: 1em 0;
border: 0;
border-top: 1px solid var(--border-default);
}
:deep(.chat-markdown .chat-mermaid-diagram) {
max-width: 100%;
overflow: auto;
@@ -1,12 +1,14 @@
<!--
features/chat/components/messages/TransferBacklogSummaryCard.vue
用途:待处理异常卡(可恢复/已关闭/结果未知三组)——列与匹配窗口一致,
支持关键字/结果筛选、多选批量操作(重查/恢复处理/标记无需处理)与行级快捷操作。
支持关键字/结果筛选、多选批量操作(重查/恢复/关闭)与行级快捷操作。
依赖:props.items、i18n chat.transfer.*、transferBatch.deriveBatchNo、transferFormat.formatQuantity。
逻辑:仅 blocked_recoverable 可勾选与操作;result_unknown / manually_closed 只读;
可恢复行按 result_code 细分徽标(blocked_file_removed=文件已移除);
blocked_file_removed 行行内仅留「标记无需继续处理」(重查不可恢复——消失证据
blocked_file_removed 行行内仅留「关闭」(重查不可恢复——消失证据
无法由重查翻回,唯一出口=人工关闭或等文件重新同步);
批量按钮与行内按钮同用短文案键(重查/恢复/关闭,2026-10-12 文案一致化,
完整语义经 title 悬浮),勾选计数保留;
勾选集合为卡片本地态,操作经 emit 交父组件调用批量端点并刷新。
-->
<script setup lang="ts">
@@ -157,18 +159,22 @@ function resultLabelKey(item: TransferBacklogItem): string {
class="rounded-lg border border-brand-200 bg-brand-50 px-3 py-1 text-xs font-bold text-brand-700 transition hover:bg-brand-100 disabled:cursor-not-allowed disabled:opacity-40"
data-testid="transfer-backlog-batch-resume"
:disabled="busy"
:title="$t('chat.transfer.resumeAction')"
@click="emit('resume', selectedActionableIds)"
>
{{ $t('chat.transfer.resumeAction') }}({{ selectedActionableIds.length }})
<!-- [2026-10-12 文案一致化] 批量按钮与行内按钮同用短文案键(恢复/关闭),
勾选计数保留;完整语义经 title 悬浮透出(与行内按钮同模式) -->
{{ $t('chat.transfer.resumeActionShort') }}({{ selectedActionableIds.length }})
</button>
<button
type="button"
class="rounded-lg border border-red-200 bg-red-50 px-3 py-1 text-xs font-bold text-red-600 transition hover:bg-red-100 disabled:cursor-not-allowed disabled:opacity-40"
data-testid="transfer-backlog-batch-close"
:disabled="busy"
:title="$t('chat.transfer.manualClose')"
@click="emit('batchClose', selectedActionableIds)"
>
{{ $t('chat.transfer.manualClose') }}({{ selectedActionableIds.length }})
{{ $t('chat.transfer.manualCloseShort') }}({{ selectedActionableIds.length }})
</button>
<button
type="button"
@@ -10,6 +10,7 @@
import { computed, ref } from 'vue';
import { deriveBatchNo } from './transferBatch';
import { formatQuantity } from './transferFormat';
import { parseApiUtcDate } from '@/shared/utils/dateTime';
import type { TransferMatchingItem } from '../../types/transfer.types';
const props = defineProps<{
@@ -71,10 +72,11 @@ function rowKey(item: TransferMatchingItem): string {
return `${item.item_id ?? 'na'}|${item.invoice_no}`;
}
/** 查询时刻展示(HH:mm);无 checked_at 不渲染。 */
/** 查询时刻展示(HH:mm);后端 naive ISO 按 UTC 解析后转浏览器本地时区
* (仓库约定 parseApiUtcDate,2026-09-29 修复 UTC+8 展示异常);无 checked_at 不渲染。 */
function checkedTime(item: TransferMatchingItem): string {
if (!item.checked_at) return '';
const date = new Date(item.checked_at);
const date = parseApiUtcDate(item.checked_at);
return Number.isNaN(date.getTime()) ? '' : date.toTimeString().slice(0, 5);
}
</script>
@@ -10,7 +10,7 @@ import { mount } from '@vue/test-utils';
import { describe, expect, it } from 'vitest';
import i18n from '@/i18n';
import TransferMatchCard from './TransferMatchCard.vue';
import type { TransferMatchingSummary, TransferSourceProgress } from '../../types/transfer.types';
import type { TransferMatchingItem, TransferMatchingSummary, TransferSourceProgress } from '../../types/transfer.types';
/** 最小合法匹配摘要(TransferMatchingSummary 全必填字段齐备,计数为 0) */
function buildSummary(): TransferMatchingSummary {
@@ -70,3 +70,81 @@ describe('TransferMatchCard 来源失败顶栏', () => {
expect(wrapper.find('[data-testid="transfer-match-failed-sources"]').exists()).toBe(false);
});
});
/** [2026-10-12 单据数口径修正] 预计 ERP 单据数按执行建单五元组去重。
* 行分组键 = (external_org, source_code, receipt_date, from_warehouse,
* to_warehouse),与后端 execution_service.prepare_execution 同口径:
* 同组多行执行期合并一张 ERP 单,预估数不得等于可执行行数。 */
function buildItem(overrides: Partial<TransferMatchingItem>): TransferMatchingItem {
return {
item_id: 1,
source_code: 'DBS-AWSBI',
material_no: 'MAT-001',
material_name: '连接器组件',
specification: 'A 型',
invoice_no: 'HOM-001',
receipt_date: '2026-08-05',
from_warehouse: 'DBS-TRANSIT',
from_quantity: '100',
to_warehouse: 'HUB-CN01',
to_quantity: '100',
result: 'executable',
external_org: 'HX-CN01',
...overrides,
};
}
/** 计数卡第 5 格 = 预计 ERP 单据(可执行/未成熟/阻断/数量/单据/待查/失效)。 */
function estimateCardText(wrapper: ReturnType<typeof mount>): string {
const cells = wrapper.find('[data-testid="transfer-match-counts"]').findAll('div.rounded-lg');
return cells[4]?.text() ?? '';
}
describe('TransferMatchCard 预计 ERP 单据数(五元组去重)', () => {
const sameGroupA = buildItem({ item_id: 1, invoice_no: 'HOM-001' });
const sameGroupB = buildItem({ item_id: 2, invoice_no: 'HOX-002' });
const crossDate = buildItem({ item_id: 3, invoice_no: 'HOM-003', receipt_date: '2026-08-04' });
it('计数卡:同组两行 + 跨日一行 → 预估 2(不等于可执行行数 3)', () => {
// [断言意图] 锁定五元组去重口径:receipt_date 入键,同组合并、跨组拆分,
// 历史快照旧口径(=行数)持久值不再上屏。
const wrapper = mount(TransferMatchCard, {
props: {
summary: buildSummary(),
items: [sameGroupA, sameGroupB, crossDate],
selected: new Set<number>(),
},
global: { plugins: [i18n] },
});
expect(estimateCardText(wrapper).replace(/\D/g, '')).toBe('2');
});
it('生成按钮旁预估随勾选联动:勾选同组两行仍为 1,跨组勾选后为 2', async () => {
// [断言意图] 底部预估回答「点生成会出几张单」:仅统计勾选的可执行行并
// 按五元组分组;同组两行勾选=1 张(合并),追加跨日行勾选=2 张。
const wrapper = mount(TransferMatchCard, {
props: {
summary: buildSummary(),
items: [sameGroupA, sameGroupB, crossDate],
selected: new Set<number>([1, 2]),
},
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="transfer-estimate-selected"]').text()).toContain(':1');
await wrapper.setProps({ selected: new Set<number>([1, 2, 3]) });
expect(wrapper.find('[data-testid="transfer-estimate-selected"]').text()).toContain(':2');
});
it('阻断行不参与预估:勾选阻断行不改变单据数', () => {
const blocked = buildItem({ item_id: 4, invoice_no: 'HOM-BLOCKED', result: 'blocked_quantity_mismatch' });
const wrapper = mount(TransferMatchCard, {
props: {
summary: buildSummary(),
items: [sameGroupA, blocked],
selected: new Set<number>([1, 4]),
},
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="transfer-estimate-selected"]').text()).toContain(':1');
});
});
@@ -15,13 +15,19 @@
emit execute(itemIds);来源级解析/文件失败经 sources.error_code 透出
(防"安静全 0"),但路由未解析失败(TRANSFER.ROUTE_NOT_RESOLVED)不进顶栏
——路由失败保持行级(result=blocked_route_not_resolved 行内展示),
顶栏按 error_code 客户端排除,历史卡片回放同样生效。
顶栏按 error_code 客户端排除,历史卡片回放同样生效;
[2026-10-12 单据数口径修正] 预计 ERP 单据数(计数卡=全部可执行行、
生成按钮旁=勾选可执行行)按执行建单五元组 (external_org, source_code,
receipt_date, from_warehouse, to_warehouse) 去重实时计算(与后端
execution_service 同键),同组多行合并一张单——原「=可执行行数」口径
高估单据数误导用户。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { deriveBatchNo } from './transferBatch';
import { formatQuantity } from './transferFormat';
import { parseApiUtcDate } from '@/shared/utils/dateTime';
import type { TransferMatchingItem, TransferMatchingSummary, TransferSourceProgress } from '../../types/transfer.types';
const { t } = useI18n();
@@ -143,13 +149,43 @@ const executableCheckedItemIds = computed(() =>
props.items.filter((item) => isSelectable(item) && isChecked(item)).map((item) => item.item_id as number),
);
/** [2026-10-12 单据数口径修正] 执行建单五元组键(与后端 execution_service.
* prepare_execution 分组建单同键同 .trim() 规范化):(external_org, source_code,
* receipt_date, from_warehouse, to_warehouse),同组多行执行期合并一张 ERP 单。
* 老卡片行缺 external_org 按 '' 参与(分组退化为四元组,仅跨组织同仓库配置下有差异)。 */
function documentGroupKey(item: TransferMatchingItem): string {
return [
(item.external_org ?? '').trim(),
(item.source_code ?? '').trim(),
(item.receipt_date ?? '').trim(),
(item.from_warehouse ?? '').trim(),
(item.to_warehouse ?? '').trim(),
].join('\u001f');
}
/** 预计 ERP 单据数(计数卡):全部可执行行按五元组去重的组数。客户端实时计算,
* 使历史快照中旧口径(=可执行行数)的持久化估计值不再上屏误导。 */
const estimatedDocumentCountAll = computed(
() => new Set(props.items.filter((item) => item.result === 'executable').map(documentGroupKey)).size,
);
/** 预计 ERP 单据数(生成按钮旁):按当前勾选的可执行行分组计数,回答
* 「点生成会出几张单」;未勾选为 0。 */
const estimatedDocumentCountSelected = computed(
() => new Set(
props.items.filter((item) => item.result === 'executable' && isChecked(item)).map(documentGroupKey),
).size,
);
/**
* 库存查询时刻小字(HH:mm);无效/缺省 checked_at 返回 null 不渲染。
* 库存查询时刻小字(HH:mm);后端 naive ISO 按 UTC 解析后转浏览器本地时区
* (仓库约定 parseApiUtcDate,2026-09-29 修复 UTC+8 展示异常);
* 无效/缺省 checked_at 返回 null 不渲染。
* @param item 匹配明细行;checked_at 为后端 ISO 时间
*/
function checkedAtLabel(item: TransferMatchingItem): string | null {
if (!item.checked_at) return null;
const date = new Date(item.checked_at);
const date = parseApiUtcDate(item.checked_at);
if (Number.isNaN(date.getTime())) return null;
const hh = String(date.getHours()).padStart(2, '0');
const mm = String(date.getMinutes()).padStart(2, '0');
@@ -217,7 +253,9 @@ function reasonTitle(item: TransferMatchingItem): string | undefined {
<div class="text-[11px] text-muted">{{ $t('chat.transfer.estimatedQuantity') }}</div>
</div>
<div class="rounded-lg bg-surface-soft p-2 text-center">
<div class="text-lg font-black text-brand-600">{{ summary.estimated_external_write_count }}</div>
<!-- [2026-10-12 单据数口径修正] 按执行建单五元组去重(客户端计算),
不再透传旧口径持久值(=可执行行数)——同组多行合并一张 ERP 单 -->
<div class="text-lg font-black text-brand-600">{{ estimatedDocumentCountAll }}</div>
<div class="text-[11px] text-muted">{{ $t('chat.transfer.estimatedExternalWrites') }}</div>
</div>
<!-- 待查库存:文件已落地、尚未查过 ERP 库存的行数(历史回放缺省 0) -->
@@ -390,9 +428,10 @@ function reasonTitle(item: TransferMatchingItem): string | undefined {
</div>
<div class="mt-3 flex items-center justify-end gap-3 border-t border-subtle pt-3">
<span class="text-xs text-muted">
<span class="text-xs text-muted" data-testid="transfer-estimate-selected">
{{ $t('chat.transfer.selectedCount', { count: selectedCount }) }} ·
{{ $t('chat.transfer.estimatedExternalWrites') }}:{{ summary.estimated_external_write_count }}
<!-- [2026-10-12 单据数口径修正] 随勾选联动:按勾选可执行行五元组分组计数 -->
{{ $t('chat.transfer.estimatedExternalWrites') }}:{{ estimatedDocumentCountSelected }}
</span>
<button
type="button"
@@ -385,9 +385,13 @@ async function onSourceRetry(sourceCodes: string[]) {
const codes = Array.isArray(sourceCodes) ? sourceCodes : [sourceCodes];
retryingSource.value = new Set([...retryingSource.value, ...codes]);
try {
// 逐来源触发,避免一次并发 EPR/RPA 竞态;失败中断剩余。
for (const code of codes) {
await transfer.retrySourceRpa(code);
// 多来源一次批量端点(合并单 batch trigger,Worker 单次浏览器会话串行导出);
// 单来源沿用原接口(行级 ↻ 一源一文件语义不变)。
const [first, ...rest] = codes;
if (rest.length > 0) {
await transfer.retrySourcesRpaBatch(codes);
} else if (first !== undefined) {
await transfer.retrySourceRpa(first);
}
} catch (e) {
reportError(e);
@@ -4,8 +4,8 @@
* 确认提交、重试收料 RPA。
* 依赖:@vue/test-utils、i18n。
* 逻辑:平台 DBS/Crane 仅分组;实例为选择与执行边界(决策 2/3/4);
* 确认需至少一个 has_ready_file(兜底告警),提交范围静默过滤为 ready-only
* (无 ready 文件的勾选项不进匹配,2026-09-29 来源错误分层);
* 确认需至少一个 has_ready_file(兜底告警);混合选择(含非就绪项)先披露范围
* 再确认(知情部分确认 2026-10-09,替代历史静默剔除),提交范围 ready-only;
* 重试门禁=仅 fetching 在途不可重试(ready 亦可强制重抓,2026-09-29 去管控)。
*/
import { mount } from '@vue/test-utils';
@@ -54,18 +54,21 @@ describe('TransferSourceSelectCard', () => {
expect(wrapper.emitted('confirm')).toBeUndefined();
});
it('“全选可见”勾选全部启用实例,确认时静默剔除无 ready 文件来源', async () => {
// [断言意图] 门禁新语义:有 ready 文件的勾选项照常放行,无 ready 文件的勾选项
// (DBS-AWSSG none)静默剔除——确认范围只含可执行来源,不再整包提交。
it('“全选可见”勾选全部启用实例,混合选择先披露再确认 ready-only', async () => {
// [断言意图] 知情部分确认(2026-10-09):混合选择(2 ready + 1 none)点确认先出现
// 披露条且不提交;披露后确认只携带具备 ready 文件的来源码。
const wrapper = mountCard();
await wrapper.find('[data-testid="transfer-source-select-visible"]').trigger('click');
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
expect(wrapper.find('[data-testid="transfer-source-partial-confirm"]').exists()).toBe(true);
expect(wrapper.emitted('confirm')).toBeUndefined();
await wrapper.find('[data-testid="transfer-source-partial-proceed"]').trigger('click');
expect(wrapper.emitted('confirm')?.[0][0]).toEqual(['DBS-AWSBI', 'CRANE-SZ']);
});
it('勾选 ready+parse_failed 确认时只提交 ready 来源', async () => {
it('勾选 ready+parse_failed 先披露,披露后确认只提交 ready 来源', async () => {
// [断言意图] 解析失败来源(has_ready_file=false)勾选后不阻断确认,
// 但确认事件只携带具备 ready 文件的来源码。
// 但须经披露条确认,确认事件只携带具备 ready 文件的来源码。
const sources = [
{ source_code: 'DSV-OK', display_name: 'ok', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' as const },
{ source_code: 'DSV-BAD', display_name: 'bad', platform: 'dbs', enabled: true, has_ready_file: false, file_status: 'parse_failed' as const },
@@ -74,9 +77,64 @@ describe('TransferSourceSelectCard', () => {
await wrapper.find('[data-testid="transfer-source-option-DSV-OK"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-option-DSV-BAD"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
expect(wrapper.emitted('confirm')).toBeUndefined();
await wrapper.find('[data-testid="transfer-source-partial-proceed"]').trigger('click');
expect(wrapper.emitted('confirm')?.[0][0]).toEqual(['DSV-OK']);
});
it('混合选择披露条展示可匹配/暂不可匹配计数与状态分组', async () => {
// [断言意图] 披露必须让「抓取中」与「真失败」可区分:摘要含三段计数,
// 分组明细含「抓取中 1」——用户知情后再决定是否仅匹配就绪来源。
const sources = [
{ source_code: 'DSV-OK', display_name: 'ok', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' as const },
{ source_code: 'DSV-FETCH', display_name: 'fetching', platform: 'dbs', enabled: true, has_ready_file: false, file_status: 'fetching' as const },
];
const wrapper = mountCard({}, sources);
await wrapper.find('[data-testid="transfer-source-option-DSV-OK"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-option-DSV-FETCH"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
const summary = wrapper.find('[data-testid="transfer-source-partial-summary"]').text();
expect(summary).toContain('可匹配 1 个');
expect(summary).toContain('暂不可匹配 1 个');
expect(summary).toContain('抓取中 1');
});
it('披露后「取消」收回披露条且不提交,确认按钮还原', async () => {
// [断言意图] 披露是可退出的确认步:取消后回到选择状态、零副作用。
const wrapper = mountCard();
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSBI"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSSG"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
expect(wrapper.find('[data-testid="transfer-source-partial-confirm"]').exists()).toBe(true);
await wrapper.find('[data-testid="transfer-source-partial-cancel"]').trigger('click');
expect(wrapper.find('[data-testid="transfer-source-partial-confirm"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="transfer-source-confirm"]').exists()).toBe(true);
expect(wrapper.emitted('confirm')).toBeUndefined();
});
it('披露展示期间调整勾选即收回披露(旧口径失效)', async () => {
// [断言意图] 披露基于确认瞬间的选择快照:勾选变化后旧披露必须失效收回,
// 防止按过期口径提交。
const wrapper = mountCard();
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSBI"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSSG"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
expect(wrapper.find('[data-testid="transfer-source-partial-confirm"]').exists()).toBe(true);
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSSG"] input').setValue(false);
expect(wrapper.find('[data-testid="transfer-source-partial-confirm"]').exists()).toBe(false);
expect(wrapper.emitted('confirm')).toBeUndefined();
});
it('全就绪选择不出现披露,确认直达提交', async () => {
// [断言意图] 知情披露只在混合状态出现:全部就绪时确认一步直达(常态零额外点击)。
const wrapper = mountCard();
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSBI"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-option-CRANE-SZ"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
expect(wrapper.find('[data-testid="transfer-source-partial-confirm"]').exists()).toBe(false);
expect(wrapper.emitted('confirm')?.[0][0]).toEqual(['DBS-AWSBI', 'CRANE-SZ']);
});
it('parse_failed 显示解析失败徽标且可重试', async () => {
// [断言意图] 当日收料文件解析失败(file_status=parse_failed)不得误报就绪;
// 与 none/failed/expired 一样允许重新触发收料 RPA。
@@ -180,6 +238,16 @@ describe('TransferSourceSelectCard', () => {
expect(wrapper.emitted('retry')?.[0][0]).toEqual(['DBS-AWSBI', 'DBS-AWSSG', 'CRANE-SZ']);
});
it('空数据来源显示「无收料数据」徽标而非抓取失败', async () => {
// [断言意图] 抓取成功但当日无收料记录(file_status=no_data)属业务结果,
// 必须如实展示"无收料数据",不得与"抓取失败"混淆(2026-10-08 PRD01 误标事故)。
const wrapper = mountCard({}, [
{ source_code: 'CRANE-NODATA', display_name: '空数据在途仓', platform: 'crane', enabled: true, has_ready_file: false, file_status: 'no_data' },
]);
expect(wrapper.find('[data-testid="transfer-source-status-CRANE-NODATA"]').text()).toBe('无收料数据');
expect((wrapper.find('[data-testid="transfer-source-retry-CRANE-NODATA"]').element as HTMLButtonElement).disabled).toBe(false);
});
it('已过期来源显示「文件已过期」徽标且可重试', async () => {
// [断言意图] 保留期已到的来源不得误报就绪(has_ready_file=false);
// expired 状态与 none/failed 一样允许重新触发收料 RPA。
@@ -6,14 +6,15 @@
逻辑:匹配参数区(调拨类型 + 收料日期,确认时一并提交)→ 选择辅助/上下文操作条
(有选中时原位替换辅助区,承载批量重试/下载/清空选择)→ 平台分组来源列表
(平台仅分组不可直接执行)→ 底部唯一实心主按钮「确认范围并匹配」(未选禁用);
确认只提交具备 ready 文件的来源(勾选的无 ready 项如 parse_failed/none 静默剔除,
门禁「至少一 ready」保留为兜底告警);重试除抓取中(fetching)外均可触发
确认只提交具备 ready 文件的来源:混合选择(含非就绪项)先披露范围再确认
(知情部分确认 2026-10-09,替代历史静默剔除),全就绪直达;
门禁「至少一 ready」保留为兜底告警;重试除抓取中(fetching)外均可触发
(ready 亦可强制重抓,2026-09-29 去管控),徽标独立文案;
调拨类型决定收料数据范围(类型 1 仅纳入 INVOICE 前缀 HOM/HOX/WTP),
类型 2/3 一期占位(禁用,后端同样 fail-closed)。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from '@/shared/composables/useMessage';
import { eligibleReceiptDateTo } from './transferDate';
@@ -89,6 +90,37 @@ const confirmDisabled = computed(() =>
);
const downloadDisabled = computed(() => props.busy || !selectedHasReadyFile.value);
// ---- [知情部分确认 2026-10-09] 混合选择(含非就绪项)先披露范围再确认,替代历史静默剔除 ----
/** 披露条可见性:仅在「已选含就绪 + 非就绪」混合状态点确认后出现。 */
const showPartialConfirm = ref(false);
/** 已选来源中具备 ready 文件的数量。 */
const selectedReadyCount = computed(() =>
[...selected.value].filter((code) => props.sources.find((s) => s.source_code === code)?.has_ready_file).length,
);
const selectedUnreadyCount = computed(() => selectedCount.value - selectedReadyCount.value);
/** 非就绪状态分组展示顺序:先在途(fetching)后终态。 */
const unreadyStatusOrder = ['fetching', 'failed', 'parse_failed', 'no_data', 'expired', 'none'] as const;
/** 非就绪状态 → 徽标文案 key(复用既有状态徽标词汇,披露条逐组计数)。 */
const UNREADY_STATUS_LABEL_KEYS: Record<(typeof unreadyStatusOrder)[number], string> = {
fetching: 'chat.transfer.fileFetching',
failed: 'chat.transfer.fileFailed',
parse_failed: 'chat.transfer.fileParseFailed',
no_data: 'chat.transfer.fileNoData',
expired: 'chat.transfer.fileExpired',
none: 'chat.transfer.fileNone',
};
/** 非就绪来源按状态分组计数(固定顺序),让「抓取中」与「真失败」可区分。 */
const unreadyBreakdownText = computed(() => unreadyStatusOrder
.map((status) => ({
status,
count: [...selected.value].filter(
(code) => props.sources.find((s) => s.source_code === code)?.file_status === status,
).length,
}))
.filter((item) => item.count > 0)
.map((item) => `${t(UNREADY_STATUS_LABEL_KEYS[item.status])} ${item.count}`)
.join(' · '));
function toggle(sourceCode: string, checked: boolean) {
const next = new Set(selected.value);
if (checked) next.add(sourceCode);
@@ -141,23 +173,49 @@ function downloadSelected(): void {
if (codes.length) emit('download', codes);
}
/** 确认范围并匹配:只提交具备 ready 文件的来源;无 ready 文件的勾选项(如 parse_failed/none)
* 静默剔除(历史上是「至少一 ready 则整包提交」,会把不可执行来源带进匹配);
* 「至少一 ready」门禁保留为兜底告警(全部无 ready 时拦截)。 */
/** 确认范围并匹配:只提交具备 ready 文件的来源。混合选择(含非就绪项)先展示披露条
* (知情部分确认 2026-10-09,替代历史「至少一 ready 则静默剔除整包」),用户确认后
* 才提交 ready-only;全就绪直达。「至少一 ready」门禁保留为兜底告警。 */
function confirm() {
if (selectedCount.value === 0) {
notifyWarning(t('chat.transfer.needSelectSource'), t('chat.transfer.sourceSelectTitle'));
return;
}
const readyCodes = [...selected.value].filter(
(code) => props.sources.find((s) => s.source_code === code)?.has_ready_file,
);
const readyCodes = selectedReadyCodes();
if (readyCodes.length === 0) {
notifyWarning(t('chat.transfer.needReadyFile'), t('chat.transfer.sourceSelectTitle'));
return;
}
if (selectedUnreadyCount.value > 0) {
showPartialConfirm.value = true;
return;
}
emit('confirm', readyCodes, { from: dateFrom.value || undefined, to: dateTo.value || undefined }, transferType.value);
}
/** 已选来源中的 ready 来源码(每次 emit 时现算,避免披露期间勾选变化导致口径过期)。 */
function selectedReadyCodes(): string[] {
return [...selected.value].filter(
(code) => props.sources.find((s) => s.source_code === code)?.has_ready_file,
);
}
/** 披露后确认:仅提交就绪来源(其余来源就绪后可重新匹配补入,后端增量圈行不破坏已有行)。 */
function proceedPartialConfirm() {
const readyCodes = selectedReadyCodes();
showPartialConfirm.value = false;
emit('confirm', readyCodes, { from: dateFrom.value || undefined, to: dateTo.value || undefined }, transferType.value);
}
/** 披露后取消:收回披露条,可调整勾选或等待其余来源就绪。 */
function cancelPartialConfirm() {
showPartialConfirm.value = false;
}
// 勾选变化即收回披露:用户在调整范围,旧披露口径已失效。
watch(selected, () => {
showPartialConfirm.value = false;
});
</script>
<template>
@@ -278,7 +336,10 @@ function confirm() {
</span>
</div>
<div v-for="platform in platforms" :key="platform" class="mb-3 rounded-lg border border-subtle">
<!-- [ZONE 3] 来源列表:上限随视口伸缩(60vh)而非固定值——来源多时列表尽量占满可用高度再内部滚动,
避免固定小限高把列表压成几行+卡片下方大量留白;来源少时卡片自然收缩不受影响 -->
<div class="max-h-[60vh] space-y-3 overflow-y-auto" data-testid="transfer-source-list">
<div v-for="platform in platforms" :key="platform" class="rounded-lg border border-subtle">
<div class="flex items-center justify-between rounded-t-lg bg-surface-soft px-3 py-1.5">
<b class="text-xs text-secondary">{{ platform.toUpperCase() }}</b>
<label class="text-[11px] text-muted">
@@ -329,6 +390,14 @@ function confirm() {
>
{{ t('chat.transfer.fileFailed') }}
</span>
<!-- 无收料数据(no_data):抓取成功但当日无收料记录,属业务结果而非故障;当日稍后到货可重抓补数 -->
<span
v-else-if="source.file_status === 'no_data'"
class="inline-flex items-center gap-1 rounded-full bg-sky-50 px-2 py-0.5 text-[10px] font-bold text-sky-700"
:data-testid="`transfer-source-status-${source.source_code}`"
>
{{ t('chat.transfer.fileNoData') }}
</span>
<span
v-else-if="source.file_status === 'expired'"
class="inline-flex items-center gap-1 rounded-full bg-orange-50 px-2 py-0.5 text-[10px] font-bold text-orange-700"
@@ -365,9 +434,42 @@ function confirm() {
</div>
</div>
</div>
</div>
<div class="flex items-center justify-end border-t border-subtle pt-3">
<!-- [知情部分确认] 混合状态点确认后按钮区原位替换为披露条(同槽位切换惯例):
明确本次仅纳入就绪来源、逐状态分组展示未就绪项,用户显式确认后才提交。 -->
<div
v-if="showPartialConfirm"
class="flex w-full flex-col gap-1.5 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2"
data-testid="transfer-source-partial-confirm"
>
<p class="text-xs font-bold text-amber-700" data-testid="transfer-source-partial-summary">
{{ $t('chat.transfer.partialConfirmSummary', { total: selectedCount, ready: selectedReadyCount, unready: selectedUnreadyCount }) }}
<span v-if="unreadyBreakdownText" class="font-normal">{{ $t('chat.transfer.partialConfirmBreakdown', { items: unreadyBreakdownText }) }}</span>
</p>
<p class="text-xs text-amber-700">{{ $t('chat.transfer.partialConfirmHint') }}</p>
<div class="flex items-center justify-end gap-2">
<button
type="button"
class="rounded-lg border border-default px-3 py-1.5 text-xs font-bold text-secondary hover-surface-soft"
data-testid="transfer-source-partial-cancel"
@click="cancelPartialConfirm"
>
{{ $t('chat.transfer.partialConfirmCancel') }}
</button>
<button
type="button"
class="rounded-lg bg-brand-600 px-4 py-1.5 text-xs font-bold text-white hover:bg-brand-700"
data-testid="transfer-source-partial-proceed"
@click="proceedPartialConfirm"
>
{{ $t('chat.transfer.partialConfirmProceed') }}
</button>
</div>
</div>
<button
v-else
type="button"
class="rounded-lg bg-brand-600 px-4 py-1.5 text-sm font-bold text-white hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-40"
:disabled="confirmDisabled"
@@ -5,6 +5,9 @@
逻辑:主卡内部 section = 「当前阶段/状态/正式OT → 下一步 → 动作区」;
状态文案严格绑定 user_status;blocking_reason 只作下一步问题说明;按钮显隐由后端 retryable + primary_action.parameters 决定;
主动作按钮文案 fail-closed:后端下发动作码但无受控 i18n 文案时整体隐藏该按钮(含图标),禁止渲染无文字裸按钮;
阶段能力禁用态:视图层把 preparation.capabilities 的 disabled_reason 并进动作对象
(capabilityDisabledReason),命中时按钮渲染 disabled + 原因 tooltip(capabilityDisabled 命名空间),
与 submitFormalGateAction 的点击拦截同源(展示=执行同源),禁止可点样式诱导用户点击后才被拦截;
loading 仅代表「权威投影读取中」而非系统运行态:已知阶段/状态/阻断仍照常展示
(与投影同源或后端 automation 运行态),空态自然落到「待机/状态待确认」,
禁止把读取占位误述为「系统处理中」,也不做骨架→真值的二次刷新;
@@ -45,12 +48,17 @@ const props = defineProps<{
| null;
retryable?: boolean;
blockingReason?: ShippingProcessingBlockingReason | null;
primaryAction?: ShippingProcessingPrimaryAction | null;
primaryAction?: (ShippingProcessingPrimaryAction & {
/** 阶段能力禁用原因(视图层从 preparation.capabilities 并入);非空=按钮渲染禁用态。 */
capabilityDisabledReason?: string | null;
}) | null;
recoveryActions?: Array<{
code: string;
i18nKey?: string | null;
label_key?: string | null;
parameters?: Record<string, unknown>;
/** 阶段能力禁用原因(视图层从 preparation.capabilities 并入);非空=按钮渲染禁用态。 */
capabilityDisabledReason?: string | null;
}>;
/** 正式 Gate 原始状态仅用于区分未入队、运行中与外部回执等待;不参与按钮裁决。 */
gateStatus?: string | null;
@@ -296,6 +304,11 @@ const businessActionLabel = computed(() => {
});
const businessActionTitle = computed(() => {
// 能力禁用原因优先于重试中提示:禁用态按钮的 tooltip 必须解释"为什么不可点"。
const capabilityText = capabilityDisabledText(
props.primaryAction ? capabilityDisabledReasonOf(props.primaryAction) : null,
);
if (capabilityText) return capabilityText;
const retryingFlag = Boolean(props.retrying);
if (retryingFlag) {
return t('chat.shippingOrderReview.currentTask.actionRetryRunningTooltip');
@@ -305,6 +318,29 @@ const businessActionTitle = computed(() => {
const actionIsRetry = computed(() => String(props.primaryAction?.code || '').trim().startsWith('retry_'));
const actionIsInventoryRpa = computed(() => String(props.primaryAction?.code || '').trim() === 'retry_inventory_preparation');
/**
* 阶段能力禁用态裁决:与视图层 submitFormalGateAction 的点击拦截同源(展示=执行同源)。
* 核心逻辑:视图层把 preparation.capabilities 的 disabled_reason 并进动作对象;本卡只负责
* 渲染禁用态与原因 tooltip,不自行推断业务能力。原因文案复用 capabilityDisabled 命名空间,
* 未登记的 reason fail-closed 禁用但不给 tooltip(禁止裸露内部原因码)。
*/
function capabilityDisabledReasonOf(action: { capabilityDisabledReason?: string | null }): string | null {
const reason = String(action.capabilityDisabledReason || '').trim();
return reason || null;
}
function capabilityDisabledText(reason: string | null | undefined): string {
const normalized = String(reason || '').trim();
if (!normalized) return '';
const key = `chat.shippingOrderReview.lifecycle.prepare.capabilityDisabled.${normalized}`;
return te(key) ? t(key) : '';
}
const businessActionCapabilityDisabled = computed(() => (
Boolean(props.primaryAction && capabilityDisabledReasonOf(props.primaryAction))
));
const recoveryActions = computed(() => (props.recoveryActions || []).filter((action) => {
const code = String(action.code || '').trim();
if (!code || isNonTaskCapabilityAction(code) || isInternalInventoryAction(code)) return false;
@@ -329,6 +365,8 @@ function recoveryActionLabel(action: (typeof recoveryActions.value)[number]): st
}
function handleBusinessActionClick() {
// 能力禁用态兜底:disabled 按钮通常不派发 click,此处防御键盘等旁路触发。
if (businessActionCapabilityDisabled.value) return;
const primaryActionCode = String(props.primaryAction?.code || '').trim();
if (!primaryActionCode || primaryActionCode === 'retry') return;
emit('action', primaryActionCode, props.primaryAction?.parameters ?? {});
@@ -464,9 +502,10 @@ type ReviewCurrentUserStatus =
<button
v-if="showBusinessAction"
type="button"
class="inline-flex items-center gap-1 rounded-md bg-sky-700 px-3 py-1.5 text-xs font-medium text-white shadow-sm transition hover:bg-sky-800 disabled:opacity-50 dark:bg-sky-600 dark:hover:bg-sky-500"
class="inline-flex items-center gap-1 rounded-md bg-sky-700 px-3 py-1.5 text-xs font-medium text-white shadow-sm transition hover:bg-sky-800 disabled:opacity-50 disabled:cursor-not-allowed dark:bg-sky-600 dark:hover:bg-sky-500"
:data-testid="actionIsRetry ? 'review-current-processing-retry' : 'review-current-task-primary-action'"
:disabled="retrying || locating"
:data-capability-disabled="businessActionCapabilityDisabled ? 'true' : undefined"
:disabled="retrying || locating || businessActionCapabilityDisabled"
:title="businessActionTitle"
@click="handleBusinessActionClick"
>
@@ -482,9 +521,11 @@ type ReviewCurrentUserStatus =
v-for="action in recoveryActions"
:key="action.code"
type="button"
class="inline-flex items-center gap-1 rounded-md border border-sky-300 bg-surface px-2.5 py-1.5 text-xs font-medium text-sky-800 shadow-sm transition hover:bg-sky-50 disabled:opacity-50 dark:border-sky-700 dark:bg-sky-900 dark:text-sky-100 dark:hover:bg-sky-800"
class="inline-flex items-center gap-1 rounded-md border border-sky-300 bg-surface px-2.5 py-1.5 text-xs font-medium text-sky-800 shadow-sm transition hover:bg-sky-50 disabled:opacity-50 disabled:cursor-not-allowed dark:border-sky-700 dark:bg-sky-900 dark:text-sky-100 dark:hover:bg-sky-800"
:data-testid="`review-current-task-recovery-${action.code}`"
:disabled="retrying || locating"
:data-capability-disabled="capabilityDisabledReasonOf(action) ? 'true' : undefined"
:disabled="retrying || locating || Boolean(capabilityDisabledReasonOf(action))"
:title="capabilityDisabledText(capabilityDisabledReasonOf(action))"
@click="$emit('action', action.code, action.parameters || {})"
>
{{ recoveryActionLabel(action) }}
@@ -1,21 +1,52 @@
/**
* features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts
* 用途:锁定唯一标准客户候选的工作台提示,避免将可自动确认状态误报为未识别。
* 依赖:vitest、@vue/test-utils、vue-i18n、ReviewCustomerResolutionPanel。
* 逻辑:unique_candidate 显示自动确认说明和明确按钮;其他未确认状态维持人工选择入口。
* 用途:锁定客户识别面板两态行为——未确认态保留候选确认流程;已确认态折叠为摘要条并提供「修改客户」改绑入口。
* 依赖:vitest、@vue/test-utils、vue-i18n、ReviewCustomerResolutionPanel、shipping.api(mock)。
* 逻辑:已确认摘要条默认折叠(已确认徽标 + 标准客户名 + chevron),展开仅显示既有识别详情;
* rebindAllowed=false 时改绑按钮禁用并展示原因;选定新客户经影响确认弹窗提交改绑 API 并 emit refreshed。
* 改绑 i18n 键由 Task 3 落 chat.json,这里在 vue-i18n mock 中前置补齐同路径键。
*/
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { flushPromises, mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import ReviewCustomerResolutionPanel from './ReviewCustomerResolutionPanel.vue';
import ShippingCustomerConfirmDialog from '@/features/chat/components/ShippingCustomerConfirmDialog.vue';
import {
listWorkspaceShippingCustomerOptions,
rebindWorkspaceShippingOrderReviewCustomer,
} from '@/features/chat/api/shipping.api';
import { useMessage } from '@/shared/composables/useMessage';
const messageSpies = vi.hoisted(() => ({
success: vi.fn(),
warning: vi.fn(),
error: vi.fn(),
info: vi.fn(),
}));
vi.mock('@/features/chat/api/shipping.api', () => ({
confirmWorkspaceShippingOrderReviewCustomer: vi.fn(),
listWorkspaceShippingCustomerOptions: vi.fn(),
retryWorkspaceShippingOrderReviewCustomerResolution: vi.fn(),
rebindWorkspaceShippingOrderReviewCustomer: vi.fn(),
}));
vi.mock('@/shared/composables/useMessage', () => ({
useMessage: () => messageSpies,
}));
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
common: { cancel: '取消' },
chat: {
shippingCustomer: { loadFailed: '加载失败', confirmFailed: '确认失败' },
shippingCustomer: {
loadFailed: '加载失败',
confirmFailed: '确认失败',
confirm: '确认',
},
shippingOrderReview: {
customerResolution: {
title: '客户确认', subtitle: '请选择标准客户', uniqueCandidateHint: '已找到唯一标准客户候选;保存校验时系统会自动确认,也可手动确认。',
@@ -24,6 +55,13 @@ const i18n = createI18n({
standardCustomer: '标准客户', customerCode: '客户编码', matchedInputs: '匹配输入', candidates: '候选客户', pdfReparseHint: '请重新识别 PDF',
inputLabels: { customerCode: '客户编码', customerName: '客户名称', address: '地址', email: '邮箱', domain: '域名', other: '其他' },
status: { unique_candidate: '唯一候选', unmatched: '未匹配', confirmed: '已确认' },
// 改绑键:与 Task 3 将落入 locales/*/chat.json 的键路径保持一致
rebindButton: '修改客户',
rebindDisabledExcelExists: '已产生发货通知/Excel,请先走撤销流程',
rebindConfirmTitle: '确认修改客户',
rebindConfirmImpact: '将更新订单客户并重新冻结订单快照;已生成的发货通知/Excel 需重新生成',
rebindSuccessToast: '客户已更新,可回通知准备重新生成 Excel',
rebindFailedToast: '修改客户失败,请稍后重试',
},
resume: { autoCreated: '已自动建单', waitingManualConfirm: '等待人工确认' },
},
@@ -32,32 +70,110 @@ const i18n = createI18n({
},
});
function mountPanel(status: string) {
const resolvedResolution = {
resolved: true,
status: 'confirmed',
rebind_allowed: true,
customer_id: 11,
raw_name: 'acme',
standard_name: 'ACME 标准客户',
short_code: 'ACME',
input_values: [
{ definition_code: 'customer_code', definition_label: null, raw_value: 'ACME', normalized_value: 'ACME' },
],
};
function mountPanel(resolution: Record<string, unknown>, extraProps: Record<string, unknown> = {}) {
return mount(ReviewCustomerResolutionPanel, {
props: {
caseNo: 'CASE-CUSTOMER-1',
editable: true,
resolution: { resolved: false, status, raw_name: 'ACME' },
orderDataVersion: 4,
resolution,
...extraProps,
},
global: {
plugins: [i18n],
stubs: { ShippingCustomerConfirmDialog: true },
// teleport 就地渲染:改绑影响确认弹窗 Teleport 到 body,stub 后断言仍在 wrapper 内可达。
stubs: { ShippingCustomerConfirmDialog: true, teleport: true },
},
});
}
describe('ReviewCustomerResolutionPanel', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(listWorkspaceShippingCustomerOptions).mockResolvedValue([]);
});
it('唯一候选展示自动确认说明和明确确认入口', () => {
const wrapper = mountPanel('unique_candidate');
const wrapper = mountPanel({ resolved: false, status: 'unique_candidate', raw_name: 'ACME' });
expect(wrapper.text()).toContain('保存校验时系统会自动确认');
expect(wrapper.get('[data-testid="review-select-customer"]').text()).toContain('确认唯一候选');
});
it('非唯一未确认状态维持人工选择客户入口', () => {
const wrapper = mountPanel('unmatched');
const wrapper = mountPanel({ resolved: false, status: 'unmatched', raw_name: 'ACME' });
expect(wrapper.text()).not.toContain('保存校验时系统会自动确认');
expect(wrapper.get('[data-testid="review-select-customer"]').text()).toContain('选择标准客户');
});
it('已确认态默认折叠为摘要条,展开仅显示既有识别详情', async () => {
const wrapper = mountPanel(resolvedResolution);
// 断言意图:摘要条可见(已确认徽标 + 标准客户名),识别详情默认不展开
expect(wrapper.get('[data-testid="review-customer-resolution-badge"]').text()).toContain('已确认');
expect(wrapper.text()).toContain('ACME 标准客户');
expect(wrapper.find('[data-testid="review-customer-resolution-details"]').exists()).toBe(false);
// 断言意图:改绑入口在摘要条上存在
expect(wrapper.get('[data-testid="review-rebind-customer"]').exists()).toBe(true);
// 断言意图:chevron 展开后显示既有识别详情(命中输入),不再是整块识别面板
await wrapper.get('[data-testid="review-customer-resolution-toggle"]').trigger('click');
expect(wrapper.get('[data-testid="review-customer-resolution-details"]').exists()).toBe(true);
expect(wrapper.text()).toContain('匹配输入');
});
it('rebindAllowed=false 时改绑按钮禁用并以 tooltip 说明原因', () => {
const wrapper = mountPanel({ ...resolvedResolution, rebind_allowed: false });
const rebindButton = wrapper.get('[data-testid="review-rebind-customer"]');
// 断言意图:edit_window.header=false(Excel 已产生/活动 Attempt)时按钮禁用
expect(rebindButton.attributes('disabled')).toBeDefined();
// 断言意图:禁用原因经 tooltip 透出,而非静默置灰
expect(rebindButton.attributes('title')).toContain('撤销');
});
it('选定新客户并确认影响后提交改绑 API 且 emit refreshed', async () => {
vi.mocked(rebindWorkspaceShippingOrderReviewCustomer).mockResolvedValue({
case: null,
customer_resolution: null,
rebind: { previous_customer_id: 11, customer_id: 42, snapshot_id: 9 },
});
const wrapper = mountPanel(resolvedResolution);
// [STEP 1] 打开复用的客户搜索选择弹窗并选定目标客户
await wrapper.get('[data-testid="review-rebind-customer"]').trigger('click');
await flushPromises();
const selectDialog = wrapper.findComponent(ShippingCustomerConfirmDialog);
expect(selectDialog.exists()).toBe(true);
selectDialog.vm.$emit('confirm', 42);
await flushPromises();
// [STEP 2] 影响确认弹窗出现后提交
await wrapper.get('[data-testid="review-rebind-confirm-submit"]').trigger('click');
await flushPromises();
// 断言意图:携带乐观锁版本调用改绑 API
expect(rebindWorkspaceShippingOrderReviewCustomer).toHaveBeenCalledTimes(1);
expect(rebindWorkspaceShippingOrderReviewCustomer).toHaveBeenCalledWith(
'CASE-CUSTOMER-1',
{ customer_id: 42, expected_order_data_version: 4 },
);
// 断言意图:成功 toast + 复用 refreshed 事件走既有刷新链
expect(messageSpies.success).toHaveBeenCalled();
expect(wrapper.emitted('refreshed')).toHaveLength(1);
});
});
@@ -1,9 +1,11 @@
<!--
features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue
用途:复核工作台固定「建单前客户确认」区域(与重新识别 PDF 分层)。
依赖:vue-i18n、ShippingCustomerConfirmDialog、shipping.api 客户确认/重识别接口。
逻辑:未解决时完整展开置顶;已解决且 compact 时缩为一行摘要;
选择标准客户 / 重新识别客户;成功后 emit refreshed 刷新建单资格。
用途:复核工作台固定「建单前客户确认」区域,两态渲染:未确认走识别候选确认流程;已确认折叠为一行摘要条并提供「修改客户」改绑入口。
依赖:vue-i18n、ShippingCustomerConfirmDialog、shipping.api 客户确认/重识别/改绑接口。
逻辑:resolved=false 时完整展开置顶(现状不动);resolved=true 时默认折叠摘要条(已确认徽标+标准客户名+chevron+修改客户按钮),
chevron 展开既有识别详情(不含 ODM 范围);改绑走「复用客户搜索选定 → 影响确认弹窗 → rebind API → 成功 toast → emit refreshed」。
resolution.rebind_allowed=false(Excel 已产生/活动 Attempt,后端投影下发)时按钮禁用并以 tooltip 说明;
后端 fail-closed 兜底,409 的 BusinessError localized message 直接经 toast 展示。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
@@ -14,6 +16,7 @@ import ShippingCustomerConfirmDialog from '@/features/chat/components/ShippingCu
import {
confirmWorkspaceShippingOrderReviewCustomer,
listWorkspaceShippingCustomerOptions,
rebindWorkspaceShippingOrderReviewCustomer,
retryWorkspaceShippingOrderReviewCustomerResolution,
} from '@/features/chat/api/shipping.api';
import type {
@@ -25,7 +28,10 @@ const props = defineProps<{
caseNo: string;
resolution: ShippingOrderReviewCustomerResolution | null | undefined;
editable: boolean;
/** 已解决时缩为一行摘要(放入「更多状态」) */
/** 已确认改绑入口可用性:edit_window.header 明确 false 时禁用;缺失/undefined 视为可用(后端权威守卫兜底) */
/** 改绑乐观锁版本:case 投影的 order_data_version(正式任务当前版本),缺省时后端按版本冲突拒绝 */
orderDataVersion?: number | null;
/** 已解决时缩为一行摘要(历史兼容属性;已确认态现在恒为折叠摘要条) */
compact?: boolean;
}>();
@@ -39,8 +45,15 @@ const busy = ref(false);
const dialogOpen = ref(false);
const options = ref<ShippingCustomerOption[]>([]);
const loadingOptions = ref(false);
/** 已确认态识别详情是否展开(默认折叠为一行摘要条) */
const confirmedDetailsExpanded = ref(false);
/** 改绑影响确认弹窗显隐与待提交的新客户 */
const rebindConfirmOpen = ref(false);
const pendingRebindCustomerId = ref<number | null>(null);
const resolved = computed(() => Boolean(props.resolution?.resolved));
/** 改绑可用性:prop 缺省视为可用,与 formalHeaderEditable 的 fail-open 语义对齐(后端 409 兜底) */
const rebindAllowed = computed(() => props.resolution?.rebind_allowed === true);
const hasUniqueCandidate = computed(() => (
!resolved.value
&& String(props.resolution?.status || '').trim() === 'unique_candidate'
@@ -66,6 +79,15 @@ const displayName = computed(() => {
const inputValues = computed(() => props.resolution?.input_values || []);
const candidateRows = computed(() => props.resolution?.candidates || []);
/** 改绑影响确认弹窗中展示的待提交客户名;选项已卸载时回落展示 ID。 */
const pendingRebindCustomerLabel = computed(() => {
const customerId = pendingRebindCustomerId.value;
if (customerId == null) return '—';
const match = options.value.find((item) => item.id === customerId);
if (match) return `${match.standard_name} (${match.short_code})`;
return `#${customerId}`;
});
function inputLabel(definitionCode: string | null | undefined): string {
const code = String(definitionCode || '').trim().toLowerCase();
if (code.includes('customer') && code.includes('code')) return t('chat.shippingOrderReview.customerResolution.inputLabels.customerCode');
@@ -84,8 +106,13 @@ function candidateValue(candidate: unknown, key: string): string {
return String(row[key] ?? '').trim() || '—';
}
/** 切换已确认摘要条的识别详情展开/折叠。 */
function toggleConfirmedDetails() {
confirmedDetailsExpanded.value = !confirmedDetailsExpanded.value;
}
/**
* 打开标准客户选择弹窗并加载选项。
* 打开标准客户选择弹窗并加载选项(未确认确认流程入口,also 供父级经 ref 外部触发)。
*/
async function openSelectDialog() {
if (!props.editable || busy.value) return;
@@ -106,7 +133,25 @@ defineExpose({
});
/**
* 按关键词搜索标准客户。
* 打开改绑客户选择弹窗(已确认态「修改客户」入口;复用同一搜索选择弹窗)。
* AI 触发时机:用户在已确认摘要条点击「修改客户」时进入;rebindAllowed=false 时按钮已禁用,这里仅兜底防抖。
*/
async function openRebindDialog() {
if (!rebindAllowed.value || busy.value) return;
dialogOpen.value = true;
loadingOptions.value = true;
try {
options.value = await listWorkspaceShippingCustomerOptions();
} catch (error: unknown) {
options.value = [];
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.loadFailed'));
} finally {
loadingOptions.value = false;
}
}
/**
* 按关键词搜索标准客户(客户选择弹窗复用入口)。
*/
async function searchCustomers(query: string) {
loadingOptions.value = true;
@@ -120,7 +165,20 @@ async function searchCustomers(query: string) {
}
/**
* 确认标准客户并通知父级刷新 Case / 建单资格。
* 客户选择弹窗确认分发:已确认态进入改绑影响确认(不重走识别确认);未确认态走既有确认建单链路。
*/
function onCustomerDialogConfirm(customerId: number) {
if (resolved.value) {
pendingRebindCustomerId.value = customerId;
dialogOpen.value = false;
rebindConfirmOpen.value = true;
return;
}
void onConfirm(customerId);
}
/**
* 确认标准客户并通知父级刷新 Case / 建单资格(仅未确认态)。
*/
async function onConfirm(customerId: number) {
if (!props.caseNo || busy.value) return;
@@ -152,6 +210,34 @@ async function onConfirm(customerId: number) {
}
}
/**
* 提交改绑:携带 case 投影的 order_data_version 乐观锁调用 rebind API;成功后 toast 并 emit refreshed 走既有刷新链。
* 失败:BusinessError(含 409 守卫/版本冲突)展示后端 localized message;其余错误回落 rebindFailedToast。
*/
async function onRebindConfirmSubmit() {
const customerId = pendingRebindCustomerId.value;
if (!props.caseNo || customerId == null || busy.value) return;
busy.value = true;
try {
await rebindWorkspaceShippingOrderReviewCustomer(props.caseNo, {
customer_id: customerId,
expected_order_data_version: Number(props.orderDataVersion ?? 0),
});
rebindConfirmOpen.value = false;
pendingRebindCustomerId.value = null;
confirmedDetailsExpanded.value = false;
msg.success(t('chat.shippingOrderReview.customerResolution.rebindSuccessToast'));
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: t('chat.shippingOrderReview.customerResolution.rebindFailedToast');
msg.warning(message);
} finally {
busy.value = false;
}
}
/**
* 重新识别客户(不触发 PDF 重识别)。
*/
@@ -178,26 +264,74 @@ async function onRetry() {
class="rounded-xl border border-default bg-surface p-3 shadow-sm"
data-testid="review-customer-resolution-panel"
:data-compact="compact && resolved ? 'true' : 'false'"
:data-state="resolved ? 'resolved' : 'pending'"
>
<!-- 已解决摘要:一行展示客户与状态,避免占满侧栏首位 -->
<!-- 已确认态:折叠摘要条(已确认徽标 + 标准客户名 + chevron + 修改客户入口),不整体占位 -->
<template v-if="resolved">
<div
v-if="compact && resolved"
class="flex flex-wrap items-center justify-between gap-2"
data-testid="review-customer-resolution-compact"
>
<p class="text-xs text-secondary">
<span class="font-medium text-primary">{{ t('chat.shippingOrderReview.customerResolution.title') }}</span>
<span class="mx-1 text-muted">·</span>
<span>{{ displayName }}</span>
</p>
<span
class="rounded-full bg-emerald-100 px-2 py-0.5 text-[11px] font-medium text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100"
data-testid="review-customer-resolution-badge"
<button
type="button"
class="flex min-w-0 flex-1 items-center gap-2 text-left"
data-testid="review-customer-resolution-toggle"
:aria-expanded="confirmedDetailsExpanded"
@click="toggleConfirmedDetails"
>
{{ statusLabel }}
</span>
<span
class="shrink-0 rounded-full bg-emerald-100 px-2 py-0.5 text-[11px] font-medium text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100"
data-testid="review-customer-resolution-badge"
>
{{ statusLabel }}
</span>
<span class="truncate text-xs font-medium text-primary">{{ displayName }}</span>
<span class="shrink-0 text-[10px] text-muted" aria-hidden="true">{{ confirmedDetailsExpanded ? '▲' : '▼' }}</span>
</button>
<button
type="button"
class="shrink-0 rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-secondary hover:bg-surface-soft disabled:opacity-60"
data-testid="review-rebind-customer"
:disabled="!rebindAllowed || busy"
:title="rebindAllowed ? undefined : t('chat.shippingOrderReview.customerResolution.rebindDisabledExcelExists')"
@click="openRebindDialog"
>
{{ t('chat.shippingOrderReview.customerResolution.rebindButton') }}
</button>
</div>
<!-- 已确认展开区:既有识别详情(标准客户/编码/命中输入/候选),不含 ODM 范围 -->
<dl
v-if="confirmedDetailsExpanded"
class="mt-2 space-y-1 text-xs text-secondary"
data-testid="review-customer-resolution-details"
>
<div class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.standardCustomer') }}</dt>
<dd class="font-medium text-primary">{{ displayName }}</dd>
</div>
<div v-if="resolution?.short_code" class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.customerCode') }}</dt>
<dd class="font-mono font-medium text-primary">{{ resolution.short_code }}</dd>
</div>
<div v-if="inputValues.length" class="mt-2 border-t border-default pt-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.matchedInputs') }}</dt>
<dd v-for="item in inputValues" :key="`${item.definition_code}:${item.normalized_value}`" class="mt-1 flex flex-wrap gap-x-2">
<span class="text-muted">{{ inputLabel(item.definition_label || item.definition_code) }}</span>
<span class="font-mono text-primary">{{ item.raw_value || item.normalized_value || '—' }}</span>
</dd>
</div>
<div v-if="candidateRows.length > 1" class="mt-2 border-t border-default pt-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.candidates') }}</dt>
<dd v-for="candidate in candidateRows" :key="String(candidate.customer_id)" class="mt-1 flex flex-wrap gap-x-2">
<span class="text-primary">{{ candidateValue(candidate, 'standard_name') }}</span>
<span class="font-mono text-muted">{{ candidateValue(candidate, 'short_code') }}</span>
</dd>
</div>
</dl>
</template>
<!-- 未确认态:既有识别候选确认流程(现状不动) -->
<template v-else>
<header class="flex flex-wrap items-start justify-between gap-2">
<div>
@@ -209,10 +343,7 @@ async function onRetry() {
</p>
</div>
<span
class="rounded-full px-2.5 py-1 text-xs font-medium"
:class="resolved
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
: 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'"
class="rounded-full px-2.5 py-1 text-xs font-medium bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100"
data-testid="review-customer-resolution-badge"
>
{{ statusLabel }}
@@ -269,15 +400,57 @@ async function onRetry() {
<p class="mt-2 text-[11px] text-muted">
{{ t('chat.shippingOrderReview.customerResolution.pdfReparseHint') }}
</p>
</template>
<!-- 客户搜索选择弹窗:未确认态确认 / 已确认态改绑共用 -->
<ShippingCustomerConfirmDialog
:open="dialogOpen"
:options="options"
:loading="loadingOptions || busy"
@close="dialogOpen = false"
@search="searchCustomers"
@confirm="onConfirm"
@confirm="onCustomerDialogConfirm"
/>
</template>
<!-- 改绑影响确认弹窗:明示快照重冻结与通知/Excel 重生成影响后再提交。Teleport 到 body 避免粘性列穿透。 -->
<Teleport to="body">
<div
v-if="rebindConfirmOpen"
class="admin-modal-overlay animate-fade-in items-center z-[180]"
role="dialog"
aria-modal="true"
data-testid="review-rebind-confirm-dialog"
>
<div class="admin-modal-panel max-w-md scale-100">
<div class="px-6 py-5 border-b border-subtle">
<h3 class="section-title">{{ t('chat.shippingOrderReview.customerResolution.rebindConfirmTitle') }}</h3>
</div>
<div class="px-6 py-5 space-y-3 text-sm">
<p class="text-secondary">{{ t('chat.shippingOrderReview.customerResolution.rebindConfirmImpact') }}</p>
<p class="font-medium text-primary" data-testid="review-rebind-confirm-customer">{{ pendingRebindCustomerLabel }}</p>
</div>
<div class="admin-modal-footer">
<button
type="button"
class="btn-ghost"
data-testid="review-rebind-confirm-cancel"
:disabled="busy"
@click="rebindConfirmOpen = false"
>
{{ t('common.cancel') }}
</button>
<button
type="button"
class="btn-primary"
data-testid="review-rebind-confirm-submit"
:disabled="busy"
@click="onRebindConfirmSubmit"
>
{{ t('chat.shippingCustomer.confirm') }}
</button>
</div>
</div>
</div>
</Teleport>
</section>
</template>
@@ -7,7 +7,7 @@
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { getAuthHeaders } from '@/shared/utils/auth';
import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
import { applyStreamErrorToMessage, isUserFacingStreamError, type StreamErrorLabels } from '../utils/streamErrorMessage';
import type {
ChatMessage,
ChatMessageAttachment,
@@ -533,7 +533,7 @@ export function useChat() {
* - Dify Chatflow 失败时常以 `workflow_finished + data.status=failed` 返回,HTTP 仍是 200;
* - 若这里只按“终态成功”处理,页面会出现“没有任何响应”;
* - 因此需要优先从 top-level / nested data / error 对象里抽取失败文案;
* - 上下文过长与缺省失败文案走 chat.streamError.contextTooLong / workflowFailed。
* - 上下文过长与缺省失败文案走 chat.streamError.contextTooLong / workflowFailed,并按用户可读文案展示。
* @param data - SSE 事件 JSON
* @returns 用户可读错误;非失败终态返回空串
*/
@@ -766,11 +766,6 @@ export function useChat() {
run.status = workflowFailureMessage ? 'error' : 'done';
clearLikelyCompletedStreamTimer();
if (messages.value === runMessages) isThinking.value = false;
if (workflowFailureMessage) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
applyStreamErrorToMessage(botMsg, workflowFailureMessage, streamErrorLabels());
}
if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
@@ -797,6 +792,16 @@ export function useChat() {
botMsg.content += normalizedAnswer;
}
}
if (workflowFailureMessage) {
const botMsg = ensureBotMessage();
if (botMsg) {
// 后端 user_facing 与本函数生成的 i18n 文案都已是给用户看的,不再收成通用失败句。
const userFacing = isUserFacingStreamError(data)
|| workflowFailureMessage === t('chat.streamError.contextTooLong')
|| workflowFailureMessage === t('chat.streamError.workflowFailed');
applyStreamErrorToMessage(botMsg, workflowFailureMessage, streamErrorLabels(), { userFacing });
}
}
if (botMsgIndex !== null) {
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) applyEventMetadata(currentBotMsg, data);
@@ -807,7 +812,12 @@ export function useChat() {
// [STEP 2] SSE error 对用户来说也是当前轮终态,脱离活动视图后可继续发下一问,
// 同时保留底层连接在后台自然收尾,避免后续交互误触 abort。
detachActiveStreamFromView();
applyStreamErrorToMessage(botMsg, formatStreamError(data.message), streamErrorLabels());
applyStreamErrorToMessage(
botMsg,
formatStreamError(data.message),
streamErrorLabels(),
{ userFacing: isUserFacingStreamError(data) },
);
run.status = 'error';
clearLikelyCompletedStreamTimer();
if (messages.value === runMessages) isThinking.value = false;
@@ -35,6 +35,7 @@ import {
manualCloseTransferItem,
retryTransferItem,
retryTransferSourceRpa,
retryTransferSourcesRpaBatch,
} from '../api/transfer.api';
import type {
TransferBacklogItem,
@@ -458,6 +459,15 @@ export function useChatTransfer() {
return status;
}
/** 批量来源重试:一次批量端点调用(多来源合并单 batch trigger,Worker 单次浏览器
* 会话串行导出;逐来源循环会产生 N 个文件、开/关 N 次浏览器),随后刷新来源状态
* (loadSources 观察到 fetching 自动开始轮询)。 */
async function retrySourcesRpaBatch(sourceCodes: string[]) {
const result = await retryTransferSourcesRpaBatch(sourceCodes);
await loadSources();
return result;
}
/** 加载待处理异常列表与汇总 */
async function loadBacklog() {
const [items, summary] = await Promise.all([listTransferBacklog(), getTransferBacklogSummary()]);
@@ -559,6 +569,7 @@ export function useChatTransfer() {
manualClose,
loadSources,
retrySourceRpa,
retrySourcesRpaBatch,
loadBacklog,
loadBacklogSummary,
loadExecutableItems,
@@ -3,10 +3,11 @@
* 用途:统一发起 Chat Turn(POST /api/chat/turns/stream),复用与 sendMessage 相同的 SSE 渲染链路。
* 依赖:chat-turn.types、useChat 的 shipping UI 同步、streamErrorMessage、auth headers。
* 逻辑:useChat 构造 startChatTurn 并导出;货代/请假等业务只构造 actionType + payload。
* error / run.failed 若带 user_facing,则展示后端原文,同一轮只写一次。
*/
import { type Ref } from 'vue';
import { getAuthHeaders } from '@/shared/utils/auth';
import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
import { applyStreamErrorToMessage, isUserFacingStreamError, type StreamErrorLabels } from '../utils/streamErrorMessage';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage, ChatRun } from '../types/chat.types';
import { applyShippingUiStateToMessage } from './useChat';
@@ -210,8 +211,14 @@ export function createStartChatTurn(options: CreateStartChatTurnOptions) {
hasTerminalEvent = true;
run.status = 'error';
const botMsg = ensureBotMessage();
if (botMsg) {
applyStreamErrorToMessage(botMsg, options.formatStreamError(data.message), options.streamErrorLabels());
// run.failed 与兼容用的 error 帧会连发;已写入的失败提示不再追加第二遍。
if (botMsg && !botMsg.stream_error) {
applyStreamErrorToMessage(
botMsg,
options.formatStreamError(data.message),
options.streamErrorLabels(),
{ userFacing: isUserFacingStreamError(data) },
);
}
}
} catch {
@@ -408,6 +408,56 @@ describe('useShippingOrderReview build eligibility writes', () => {
});
it('records the auto-selected Case when a deep link carries only run_no (formal downstream)', async () => {
// 用户场景:历史记录等入口以 run_no 直链进入(URL 无 case_no/task_no),且唯一
// 文件已确认建单、处于正式下游阶段(选法 2 不拉 Case 快照)。
// 关键断言:自动选中的 CASE-1 必须落入 requestedCaseNo,否则 displayCase/
// activeReviewNavItem 无身份 → 任务详情不加载 → 五阶段页签全锁死 + 标题「未命名」。
api.getRun.mockResolvedValue({
run_no: 'RUN-1',
items: [{
case_no: 'CASE-1', document_id: 1, file_name: 'po.pdf', status: 'confirmed',
has_formal_ot: true, lifecycle_stage: 'freight_upload', confirmed_task_no: 'OT-1',
}],
});
api.getQueue.mockResolvedValue({
summary: { total: 1, needs_action: 0, processing: 0, completed: 1 },
items: [{
case_no: 'CASE-1', source_run_no: 'RUN-1', document_id: 1, file_name: 'po.pdf',
status: 'confirmed', has_formal_ot: true, lifecycle_stage: 'freight_upload',
confirmed_task_no: 'OT-1', issue_count: 0, available_actions: [],
}],
});
const review = useShippingOrderReview();
await review.load('RUN-1');
expect(review.requestedCaseNo.value).toBe('CASE-1');
// 选法 2:正式下游仍不得拉取 Case 快照。
expect(api.getCase).not.toHaveBeenCalled();
});
it('does not prefetch PDF preview on load or selectCase; ensurePreviewLoaded fetches on demand', async () => {
// 关键断言:进入工作台/切换文档不触发 preview 审计与下载。
const review = useShippingOrderReview();
@@ -90,6 +90,13 @@ export const REVIEW_BUILD_ELIGIBILITY_BLOCKED = 'SHIPPING.REVIEW_BUILD_ELIGIBILI
*/
export const PROGRESS_POLL_MS = 5000;
/**
* waiting_human / failed 的降频保活间隔。两者不是不可逆终态:自愈回收、
* RPA 回调仍会把任务继续推进(历史缺陷:一帧停死令界面永久冻结在旧阶段),
* 降频而非停转,状态回到活跃态自动恢复基础间隔。
*/
export const PROGRESS_POLL_IDLE_MS = 15000;
/** / Case */
export type DraftVersionConflict = {
localVersion: number;
@@ -449,6 +456,7 @@ export function useShippingOrderReview(options: {
// 浏览器端 window.setInterval 返回 number;勿用 ReturnType<typeof window.setInterval>,
// 其在 @types/node 与 DOM lib 混用时会解析为 NodeJS.Timeout 导致 TS2322。
let progressPollTimer: number | null = null;
let progressPollIntervalMs = PROGRESS_POLL_MS;
let stpCreatePollTimer: number | null = null;
let reparseCaseRefreshTimer: number | null = null;
@@ -639,15 +647,17 @@ export function useShippingOrderReview(options: {
if (!authoritativeOrderTaskNo.value && !targetRunNo) return;
showWorkflowProgress.value = true;
workflowProgressPolling.value = true;
// RPA 超时、可重试失败和人工复核都可能被后续回调推进,页面留存期间持续读取 Projection。
// 等待人工(waiting_human,即“中断”)视为线性终态:结果不会自行变化,继续轮询浪费资源。
// 注意:统一投影的用户态值是 waiting_human(旧字段是 needs_human),若沿用旧的
// needs_human 会让已中断任务永远匹配不到终态、一直空转轮询;failed 同理是停止状态。
// 可重试失败(retryable)不在此列,需保留轮询以便后续成功回调自动刷新工作流。
const UNIFIED_TERMINAL = new Set(['completed', 'cancelled', 'waiting_human', 'failed']);
// RPA 超时、可重试失败、人工复核与自愈回收都可能被后续回调推进,页面留存期间持续
// 读取 Projection。completed/cancelled 是不可逆终态,命中即停;waiting_human/failed
// 不是终态(自愈回收、回调仍会推进),历史缺陷是一帧停死令界面永久冻结在旧阶段——
// 改为降频保活,状态回到活跃态自动恢复基础间隔。
const WORKFLOW_STOP_STATUSES = new Set(['completed', 'cancelled']);
const WORKFLOW_SLOW_STATUSES = new Set(['waiting_human', 'failed']);
let lastUnifiedStatus = '';
let lastLifecycleFingerprint = '';
const RUN_TERMINAL = new Set(['completed', 'partially_completed', 'failed', 'cancelled']);
// Run 级 partially_completed 只代表解析阶段收尾,OT 随后仍会被 STP 建单产出;
// 命中即停会令提交订单后的轮询在 OT 诞生前死亡(历史缺陷),同样只降频不停转。
const RUN_STOP_STATUSES = new Set(['completed', 'cancelled']);
const tick = async () => {
// 页面不可见时暂停轮询(返回前台后下一拍自动恢复),避免后台标签持续占用服务端。
if (typeof document !== 'undefined' && document.hidden) return;
@@ -677,10 +687,13 @@ export function useShippingOrderReview(options: {
// 否则提交订单后秒级阻断时五阶段条卡在订单复核、自动跳转永不触发。
await refreshActiveAutomationLifecycle();
}
if (UNIFIED_TERMINAL.has(unifiedStatus)) {
if (WORKFLOW_STOP_STATUSES.has(unifiedStatus)) {
stopWorkflowProgressPolling();
return;
}
ensureWorkflowProgressInterval(
WORKFLOW_SLOW_STATUSES.has(unifiedStatus) ? PROGRESS_POLL_IDLE_MS : PROGRESS_POLL_MS,
);
return;
}
if (targetRunNo) {
@@ -695,15 +708,26 @@ export function useShippingOrderReview(options: {
userTaskNo: reviewProgressContext.value?.user_task_no,
});
if (synthesized) reviewProgressContext.value = synthesized;
if (RUN_TERMINAL.has(String(run.status || '').trim())) {
const runStatus = String(run.status || '').trim();
if (RUN_STOP_STATUSES.has(runStatus)) {
stopWorkflowProgressPolling();
return;
}
ensureWorkflowProgressInterval(runStatus === 'failed' ? PROGRESS_POLL_IDLE_MS : PROGRESS_POLL_MS);
}
} catch {
/* */
}
};
// 状态分级轮询:活跃态基础间隔;waiting_human/failed 降频保活。间隔变化才重建定时器。
const ensureWorkflowProgressInterval = (intervalMs: number) => {
if (progressPollTimer != null && progressPollIntervalMs === intervalMs) return;
if (progressPollTimer != null) window.clearInterval(progressPollTimer);
progressPollIntervalMs = intervalMs;
progressPollTimer = window.setInterval(() => { void tick(); }, intervalMs);
};
void tick();
progressPollIntervalMs = PROGRESS_POLL_MS;
progressPollTimer = window.setInterval(() => { void tick(); }, PROGRESS_POLL_MS);
};
@@ -1132,6 +1156,10 @@ export function useShippingOrderReview(options: {
if (generation !== caseLoadGeneration) return;
// [STREAM] Run 替代不等于其内全部 PDF 替代;当前文件只由队列 Stream 裁决。
const caseNo = preferredCaseNo || queue.items[0]?.case_no || run.items[0]?.case_no;
// [深链自愈] 历史记录切换等入口可能只带 run_no 进入(URL 无 case_no/task_no);
// 自动选中的 Case 必须回写 requestedCaseNo,否则正式下游(选法 2 不拉 Case)下
// displayCase/activeReviewNavItem 无身份,任务详情不加载、五阶段页签全锁死。
if (!preferredCaseNo) requestedCaseNo.value = caseNo || null;
// [选法 2] 正式任务下游阶段(通知准备/货代上传/通知完成)本阶段不拉复核编辑器
// (Case 快照 + Evidence),改由任务详情 + 统一投影驱动;进入「订单复核」才补拉。
const navItem = (queue.items || run.items).find(
@@ -0,0 +1,43 @@
/**
* features/chat/shipping/inlineSourceOptions.test.ts
*
* 用途:行级库存源下拉选项合并的纯函数单测——歧义行候选置顶、全量源兜底去重、空态回退。
* 依赖:被测 mergeInlineSourceOptions(无副作用纯函数)。
* 逻辑:断言合并顺序(候选在前、已启用源按后端下发序追加)、去重、大小写归一与空态。
*/
import { describe, expect, it } from 'vitest';
import { mergeInlineSourceOptions } from './inlineSourceOptions';
describe('mergeInlineSourceOptions', () => {
it('歧义行候选置顶,后接全部已启用源去重兜底(补源场景:新源出现在末尾)', () => {
const options = mergeInlineSourceOptions(
{ source_ambiguous: true, source_candidates: ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'] },
[{ source_code: 'DSV360_AWSCV' }, { source_code: 'DSV360_AWSDU' }],
);
expect(options.map((option) => option.value)).toEqual([
'DSV360_AWSCV',
'DSV360_AWSBI_BYAWSCMH01',
'DSV360_AWSDU',
]);
});
it('非歧义行仅给全部已启用源(保持既有行为,不前置候选)', () => {
const options = mergeInlineSourceOptions(
{ source_ambiguous: false, source_candidates: ['DSV360_AWSCV'] },
[{ source_code: 'DSV360_AWSDU' }],
);
expect(options.map((option) => option.value)).toEqual(['DSV360_AWSDU']);
});
it('歧义行候选缺省时退化为全部已启用源,编码统一大写', () => {
const options = mergeInlineSourceOptions(
{ source_ambiguous: true },
[{ source_code: 'dsv360_awssg' }],
);
expect(options.map((option) => option.value)).toEqual(['DSV360_AWSSG']);
});
it('两侧皆空返回空数组(调用方据此回退文本展示)', () => {
expect(mergeInlineSourceOptions({ source_ambiguous: true }, [])).toEqual([]);
});
});
@@ -0,0 +1,50 @@
/**
* features/chat/shipping/inlineSourceOptions.ts
*
* 用途:通知准备行级「库存源」编辑下拉的选项合并(纯函数,无副作用)。
* 依赖:无(仅入参结构约束,类型与 ui_state preparation 投影字段对齐)。
* 逻辑:多候选歧义行(source_ambiguous)的路由冻结候选置顶,后接全部已启用库存源
* (preparation.source_options)去重兜底——后端 override_line_inventory_source 已放开
* 「任一已启用源都允许」,管理端补源后新源即使不在候选内也可人工指定。
*/
/** 行级库存源下拉选项(value=源编码,label=展示编码,统一大写便于识别)。 */
export interface InlineSourceOption {
value: string;
label: string;
}
/** 准备行投影中与本合并相关的字段(ui_state preparation.lines[] 子集)。 */
export interface InlineSourceLine {
source_ambiguous?: boolean;
source_candidates?: Array<string>;
}
/** 后端下发的已启用库存源(ui_state preparation.source_options[] 子集)。 */
export interface EnabledSourceOption {
source_code?: string | null;
}
/**
* 合并行级库存源下拉选项:歧义行候选置顶 + 全部已启用源兜底,按源编码去重保序。
* @param line - 准备行(读 source_ambiguous / source_candidates)
* @param enabledSources - 后端下发的全部已启用库存源(保持后端排序)
* @returns 下拉选项;两侧皆空时返回空数组(调用方据此回退文本展示)
*/
export function mergeInlineSourceOptions(
line: InlineSourceLine,
enabledSources: ReadonlyArray<EnabledSourceOption>,
): InlineSourceOption[] {
const merged = new Map<string, InlineSourceOption>();
if (line.source_ambiguous) {
for (const raw of line.source_candidates || []) {
const code = String(raw || '').trim().toUpperCase();
if (code && !merged.has(code)) merged.set(code, { value: code, label: code });
}
}
for (const source of enabledSources) {
const code = String(source.source_code || '').trim().toUpperCase();
if (code && !merged.has(code)) merged.set(code, { value: code, label: code });
}
return [...merged.values()];
}
@@ -922,6 +922,8 @@ export interface ShippingTaskSummary {
owner_agent_id?: number | null;
/** 当前用户是否可写;管理员查看他人任务时为 false */
can_handle?: boolean;
/** 当前用户是否可下载正式 Excel(与导出端点同一谓词:创建者或管理员) */
can_download_export?: boolean;
/** 统一 ShippingProcessing status(列表轮询优先读此字段)。 */
shipping_processing_status?: string | null;
/** 统一 ShippingProcessing stage(任务中心紧凑进度)。 */
@@ -1529,6 +1531,8 @@ export interface ShippingTaskUiState {
part_number?: string | null;
required_qty?: string | number | null;
available_qty?: string | number | null;
/** 料号维度总可用量(忽略预约号、行允许源内汇总);无快照/未就绪为 null。 */
part_available_qty?: string | null;
shortage_qty?: string | number | null;
/** Match 正式匹配源;未匹配时为空,禁止用候选回填。 */
source_code?: string | null;
@@ -2552,6 +2556,8 @@ export interface ShippingOrderReviewCustomerResolution {
resolved: boolean;
status: string;
role?: string;
/** 「修改客户」按钮谓词(后端按 editable_scope.header 下发);缺省视为不可改绑。 */
rebind_allowed?: boolean;
extraction_id?: number | null;
raw_name?: string | null;
customer_id?: number | null;
@@ -67,6 +67,9 @@ export interface TransferMatchingItem {
stale?: boolean;
/** 行评估所用收料文件版本与来源最新可用文件是否一致;false = 文件已更新需重新匹配 */
file_current?: boolean;
/** [2026-10-12 单据数口径修正] 执行建单五元组首键(路由解析所得外部组织);
* 匹配评估路径透出,历史回放缺省——预估 ERP 单据数按五元组去重的分组输入 */
external_org?: string;
}
/** 来源实例级进度(决策 18:来源隔离展示) */
@@ -246,7 +249,7 @@ export interface TransferSourceOption {
platform: string;
enabled: boolean;
/** 收料文件状态:ready / fetching / failed / parse_failed / expired / none(只读投影货代收料事实;parse_failed=当日可用收料文件解析失败) */
file_status?: 'ready' | 'fetching' | 'failed' | 'parse_failed' | 'expired' | 'none';
file_status?: 'ready' | 'fetching' | 'failed' | 'no_data' | 'parse_failed' | 'expired' | 'none';
/** 是否已有当前可用的收料文件(门禁:无 ready 文件禁止确认匹配) */
has_ready_file?: boolean;
file_no?: string | null;
@@ -256,7 +259,7 @@ export interface TransferSourceOption {
/** 来源收料文件状态(门禁 + 状态标识 + 重试返回) */
export interface TransferSourceFileStatus {
source_code: string;
file_status: 'ready' | 'fetching' | 'failed' | 'parse_failed' | 'expired' | 'none';
file_status: 'ready' | 'fetching' | 'failed' | 'no_data' | 'parse_failed' | 'expired' | 'none';
has_ready_file: boolean;
file_no?: string | null;
file_sha256?: string | null;
@@ -1,8 +1,8 @@
/**
* features/chat/utils/streamErrorMessage.spec.ts
* 用途:验证流式异常不会把后端或浏览器技术正文展示给用户。
* 用途:验证流式异常的展示策略。
* 依赖:Vitest、streamErrorMessage。
* 逻辑:保留明确连接中断分类,其余中英文异常一律使用通用提示。
* 逻辑:已标记的用户提示原样展示;连接中断单独分类;未标记的技术正文使用通用提示。
*/
import { describe, expect, it } from 'vitest';
import { resolveStreamErrorText } from './streamErrorMessage';
@@ -20,8 +20,15 @@ describe('resolveStreamErrorText', () => {
expect(resolveStreamErrorText('response ended prematurely', true, labels)).toBe('回答不完整');
});
it('does not expose Chinese or English technical errors', () => {
it('shows backend user-facing copy instead of the generic fallback', () => {
const message = '研发培训的知识检索重排服务授权失败。请联系管理员在 Dify 中更新 Rerank 模型供应商的 API Key 后重新发布应用。';
expect(resolveStreamErrorText(message, false, labels, { userFacing: true })).toBe(message);
});
it('does not expose unmarked technical errors', () => {
// 未标记 user_facing 的技术正文仍收成通用提示,避免把节点 ID 或内部报错直接给用户。
expect(resolveStreamErrorText('Dify API Key 配置错误', false, labels)).toBe('请稍后重试');
expect(resolveStreamErrorText('HTTP 500 node_execution_id=abc', false, labels)).toBe('请稍后重试');
expect(resolveStreamErrorText('HTTP 500 node_execution_id=abc', false, labels, { userFacing: false })).toBe('请稍后重试');
});
});
@@ -2,8 +2,8 @@
* features/chat/utils/streamErrorMessage.ts
* 用途:将 SSE / 浏览器流式读错映射为用户可读文案。
* 依赖:vue-i18n chat.streamError 词条。
* 逻辑:useChat 在 catch 与 error 事件中调用 applyStreamErrorToMessage;
* 只识别明确的连接中断,其余异常正文不向用户透传。
* 逻辑:useChat / useChatTurn 在 catch 与 error 事件中调用 applyStreamErrorToMessage。
* 后端已标记 user_facing 的提示原样展示;连接中断单独分类;其余技术原文收成通用提示。
*/
import type { ChatMessage } from '../types/chat.types';
@@ -46,22 +46,44 @@ export function isUpstreamDisconnectError(message: string): boolean {
return UPSTREAM_DISCONNECT_PATTERNS.some((pattern) => normalized.includes(pattern));
}
export interface ResolveStreamErrorOptions {
/** 后端已转成可直接展示的提示(SSE user_facing=true,或前端自己的 i18n 文案)。 */
userFacing?: boolean;
}
/**
* 判断 SSE 事件是否携带后端已脱敏的用户提示。
* 核心逻辑:只认布尔 true,避免把字符串 "true" 或技术原文误当成可展示文案。
* @param data - SSE 事件 JSON
* @returns 为 true 时调用方应原样展示 message
*/
export function isUserFacingStreamError(data: Record<string, unknown>): boolean {
return data.user_facing === true;
}
/**
* 将原始错误信息映射为面向用户的提示文案。
* 核心逻辑:已标记的用户提示原样返回;浏览器断网和上游提前断开走专用文案;其余技术正文收成通用提示。
*
* @param rawMessage - 浏览器或后端返回的原始错误
* @param hasContent - 是否已有部分回答内容
* @param labels - i18n 文案集合
* @param options.userFacing - 为 true 时展示 rawMessage,不再收成通用提示
*/
export function resolveStreamErrorText(
rawMessage: string,
hasContent: boolean,
labels: StreamErrorLabels,
options?: ResolveStreamErrorOptions,
): string {
if (isNetworkDisconnectError(rawMessage)) {
const message = rawMessage.trim();
if (options?.userFacing && message) {
return message;
}
if (isNetworkDisconnectError(message)) {
return hasContent ? labels.partialInterrupted : labels.networkDisconnectedEmpty;
}
if (isUpstreamDisconnectError(rawMessage)) {
if (isUpstreamDisconnectError(message)) {
return hasContent ? labels.partialInterrupted : labels.upstreamDisconnected;
}
return labels.generic;
@@ -69,14 +91,16 @@ export function resolveStreamErrorText(
/**
* 把流式错误写入 assistant 消息:无内容时整段替换,有部分内容时在末尾追加提示。
* @param options.userFacing - 为 true 时保留后端或 i18n 已写好的句子
*/
export function applyStreamErrorToMessage(
msg: ChatMessage,
rawMessage: string,
labels: StreamErrorLabels,
options?: ResolveStreamErrorOptions,
): void {
const hasContent = Boolean(msg.content.trim());
const text = resolveStreamErrorText(rawMessage, hasContent, labels);
const text = resolveStreamErrorText(rawMessage, hasContent, labels, options);
msg.stream_error = true;
if (hasContent) {
msg.content += `\n\n${text}`;
@@ -701,8 +701,13 @@ async function mountView(query: Record<string, string> = {}) {
releaseShortageHint: '放行后本次发货按缺口处理。',
releaseReasonPlaceholder: '可填写放行原因(选填)',
releaseConfirm: '确认放行',
reservedQty: '预约数量',
partAvailableQty: '可用数量',
shortage: '库存不足',
pending: '库存匹配或通知文件尚未生成。',
capabilityDisabled: {
no_match_result: '暂无库存匹配结果,请先重新获取库存',
},
},
uploadComplete: {
title: '通知完成',
@@ -759,6 +764,8 @@ async function mountView(query: Record<string, string> = {}) {
actionCodes: {
confirm_customer: '确认客户',
resolve_field_conflicts: '处理字段冲突',
retry_inventory_preparation: '重新获取库存',
retry_inventory_matching: '重新匹配库存',
},
},
},
@@ -938,6 +945,23 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect((wrapper.vm as any).$route.query.case_no).toBe('CASE-NEW');
});
it('falls back to the requested Case identity for the header order summary on run_no-only deep links', async () => {
// 用户场景:历史记录切换生成的深链只带 mode+run_no(无 case_no/task_no)。
// 关键断言:标题订单摘要按 displayCase 身份(requestedCaseNo)匹配队列项,
// 展示文件名与 Case 号;不得因 URL 缺 case 参数而退化为「未命名」。
const previousRequestedCaseNo = requestedCaseNo.value;
requestedCaseNo.value = 'CASE-1';
try {
const wrapper = await mountView();
const summary = wrapper.find('[data-testid="review-selected-order-summary"]');
expect(summary.exists()).toBe(true);
expect(summary.text()).toContain('po.pdf');
expect(summary.text()).toContain('CASE-1');
} finally {
requestedCaseNo.value = previousRequestedCaseNo;
}
});
it('opens the replacement Case at its backend current stage after reparse completes', async () => {
const originalQueue = reviewQueue.value;
try {
@@ -1620,6 +1644,81 @@ describe('ShippingOrderReviewView layout phase 1', () => {
);
});
it('renders capability-disabled actions as disabled buttons with reason tooltip', async () => {
// 回归(展示=执行同源):A 渲染的 retry_inventory_matching 命中阶段能力 disabled
// (no_match_result)时,右卡必须直接渲染禁用态 + 原因 tooltip;
// 禁止可点样式诱导用户点击后才被 submitFormalGateAction 弹提示拦截。
activeCase.value = {
...activeCase.value,
status: 'confirmed', has_formal_ot: true, task_missing: false,
confirmed_task_id: 906, confirmed_task_no: 'SN-RPA-CAP-DISABLED',
};
shippingProcessingProjection.value = {
workItemType: 'order_task', workItemNo: 'SN-RPA-CAP-DISABLED',
status: 'failed', userStatus: 'retryable', stage: 'inventory_fetching',
progressVersion: 5, currentGate: { status: 'blocked_retryable' },
uiState: {
status: 'retryable', stage: 'inventory_fetching', lifecycleStage: 'fulfillment_prep',
primary_action: { code: 'retry_inventory_matching' },
secondary_actions: [{ code: 'retry_inventory_preparation', enabled: true }],
},
} as any;
const taskApi = await import('@/features/chat/api/shipping.api');
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-RPA-CAP-DISABLED', status: 'processing', lines: [], events: [],
ui_state: {
actions: { primary: null, secondary: [] },
process_gate: {
execution_no: 'EXEC-RPA-CAP-DISABLED',
current_blocking_gate: {
gate_code: 'inventory_preparation', evaluation_version: 2, status: 'blocked_retryable',
},
allowed_actions: ['retry_inventory_matching', 'retry_inventory_preparation'],
},
stage_context: {
preparation: {
status: 'blocked', source_locked: false,
source_options: [{ source_code: 'DSV' }],
failed_source_codes: ['DSV'],
capabilities: [
{
code: 'retry_inventory_matching', scope: 'task',
action_code: 'retry_inventory_matching', enabled: false,
disabled_reason: 'no_match_result',
},
{
code: 'retry_inventory_preparation', scope: 'task',
action_code: 'retry_inventory_preparation', enabled: true,
disabled_reason: null,
},
],
frozen_order_lines: [], lines: [],
},
},
summary: {}, steps: [],
},
} as any);
submitProcessGatePrimaryActionMock.mockClear();
messageMocks.info.mockClear();
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
await flushPromises();
// 主按钮:能力禁用 → disabled + 原因 tooltip(复用 capabilityDisabled.no_match_result 文案)。
const primary = wrapper.get('[data-testid="review-current-processing-retry"]');
expect(primary.attributes('disabled')).toBeDefined();
expect(primary.attributes('data-capability-disabled')).toBe('true');
expect(primary.attributes('title')).toContain('暂无库存匹配结果');
// 侧路按钮:能力 enabled → 保持可点,不受主按钮禁用影响。
const recovery = wrapper.get('[data-testid="review-current-task-recovery-retry_inventory_preparation"]');
expect(recovery.attributes('disabled')).toBeUndefined();
// 点击禁用按钮不得触发提交,也不得弹任何 info 提示(此前会弹未翻译 key)。
await primary.trigger('click');
await flushPromises();
expect(submitProcessGatePrimaryActionMock).not.toHaveBeenCalled();
expect(messageMocks.info).not.toHaveBeenCalled();
});
it('refreshes the processing projection after field-conflict adjudication refreshes the Case', async () => {
activeCase.value = {
...activeCase.value,
@@ -2022,6 +2121,65 @@ describe('ShippingOrderReviewView layout phase 1', () => {
}
});
it('does not auto-advance when switching formal-downstream files without an activeCase identity', async () => {
// 回归:正式下游(通知准备/货代上传/通知完成,选法 2)activeCase 刻意为 null,
// 切换前后 activeCase 身份(case_no/document_id)恒为空值;自动推进守卫若用
// activeCase 做“同一文件”判据,会把目标文件更晚的阶段误判成当前文件被推进,
// 弹出“已自动推进到货代上传”。文件身份必须用 requestedCaseNo(与阶段解析同源,
// selectCase/beginCrossRunSwitch 同步块内更新):切换必变更 → 静默;真实推进
// 不触碰 requestedCaseNo → 提示行为不变。
const originalQueue = reviewQueue.value;
try {
reviewQueue.value = {
...reviewQueue.value,
summary: { total: 2, needs_action: 2, processing: 0, completed: 0 },
items: [
{
...reviewQueue.value.items[0],
has_formal_ot: true,
lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
},
{
case_no: 'CASE-2', source_run_no: 'RUN-1', document_id: 2, file_name: 'po-2.pdf',
status: 'confirmed', has_formal_ot: true, issue_count: 0,
lifecycle_stage: 'freight_upload',
lifecycle_entries: [
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
},
],
};
// 选法 2 盲区:源文件无复核 Case 快照(懒加载失败/未完成时生产即如此),
// 此刻文件身份只剩 requestedCaseNo。
activeCase.value = null;
requestedCaseNo.value = 'CASE-1';
const wrapper = await mountView({ case_no: 'CASE-1', lifecycle_stage: 'fulfillment_prep' });
await flushPromises();
messageMocks.success.mockClear();
// 模拟真实 selectCase 正式下游分支的同步块:更新 requestedCaseNo + activeCase 保持 null。
requestedCaseNo.value = 'CASE-2';
await nextTick();
await flushPromises();
expect(messageMocks.success).not.toHaveBeenCalledWith('已自动推进到货代上传');
// 守卫不得替用户改写深链:切文件是展示上下文切换,不是流程推进。
expect((wrapper.vm as any).$route.query.lifecycle_stage).toBe('fulfillment_prep');
} finally {
reviewQueue.value = originalQueue;
}
});
it('does not open a lifecycle stage before the backend authorizes lifecycle entries', async () => {
// 未收到正式 ui_state.lifecycle_entries 时,前端只能等待实时裁决,
// 不能因页面默认值自行开放订单复核或其他生命周期阶段。
@@ -2686,7 +2844,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
lines: [{
snapshot_line_id: 1001, line_no: 1,
reservation_id: 'RSV-FROZEN', part_number: 'PN-FROZEN',
required_qty: '6', available_qty: null, shortage_qty: null, source_code: 'DBS',
required_qty: '6', available_qty: null, part_available_qty: '9', shortage_qty: null, source_code: 'DBS',
inventory_file_no: 'SIF-LINE-DBS', status: 'shortage',
draft_line_id: 'line-frozen',
inventory_allowed_actions: ['retry_inventory_preparation', 'retry_inventory_matching'],
@@ -2719,6 +2877,12 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(workspace.text()).toContain('RSV-FROZEN');
expect(workspace.text()).toContain('PN-FROZEN');
expect(workspace.text()).toContain('DBS');
// 断言意图:原可用数量列头改由 reservedQty 键渲染(预约数量),
// 新增料号总库存列紧随其后,值来自 part_available_qty。
const headers = workspace.findAll('thead th').map((th) => th.text());
expect(headers).toContain('预约数量');
expect(headers.indexOf('可用数量')).toBe(headers.indexOf('预约数量') + 1);
expect(workspace.text()).toContain('9');
expect(wrapper.find('[data-testid="review-fulfillment-frozen-order"]').exists()).toBe(false);
// 展示态行级动作收纳进更多菜单(⋯):逐项断言授权动作入口存在,不再有常显按钮。
await openLineOverflowMenu(wrapper, 1001);
@@ -2983,6 +3147,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-READY', status: 'processing', lines: [], events: [],
ui_state: {
edit_window: { header: true },
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
stage_context: {
preparation: {
@@ -3054,6 +3219,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-READY', status: 'processing', lines: [], events: [],
ui_state: {
edit_window: { header: true },
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
stage_context: {
preparation: {
@@ -3112,6 +3278,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-READY', status: 'processing', lines: [], events: [],
ui_state: {
edit_window: { header: true },
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
stage_context: {
preparation: {
@@ -52,6 +52,7 @@ import {
resolveExtractionActivityMessage,
resolveRunLifecycleUserStatus,
} from '../shipping/shippingProcessingLabels';
import { mergeInlineSourceOptions } from '../shipping/inlineSourceOptions';
import ReviewActionConfirmDialog, {
type ReviewConfirmAction,
type ReviewConfirmPayload,
@@ -107,6 +108,7 @@ import type {
ShippingOrderReviewDraftFieldMeta,
ShippingOrderReviewEvidence,
ShippingOrderReviewValueSource,
ShippingOrderExtractionLifecycleProgress,
ShippingProcessingLifecycleEntry,
ShippingTaskDetail,
ShippingFreightNoticeGroup,
@@ -364,16 +366,40 @@ const lifecycleCurrentStageCode = computed<ReviewLifecycleStageCode | null>(() =
function lifecycleEntryIsEnterable(entry: { state?: string | null } | undefined): boolean {
return entry?.state === 'current' || entry?.state === 'available';
}
// [只进不退] 自动定位的阶段序号下限:一旦到达过后道阶段,自动跳转永不回显示
// 前道阶段;仅显式 route 请求(用户手动点击阶段入口)可进入前置阶段可回看视图。
const lifecycleStageFloor = ref(-1);
const lifecycleActiveStageCode = computed<ReviewLifecycleStageCode | null>(() => {
const requested = String(route.query.lifecycle_stage || '').trim() as ReviewLifecycleStageCode;
const requestedStage = String(route.query.lifecycle_stage || '').trim();
const manualRequested = requestedStage !== '';
const requested = requestedStage as ReviewLifecycleStageCode;
const entry = lifecycleUiState.value.entries.find((item) => item.code === requested);
if (requested === 'intake_parse' && lifecycleUiState.value.intakeParseAuthorized === true) {
lifecycleStageFloor.value = Math.max(lifecycleStageFloor.value, 0);
return 'intake_parse';
}
const current = lifecycleCurrentStageCode.value;
// 用户可回看后端已授权的 available 前置阶段;自动推进由下方 watcher 在
// 「路由仍停留原 current 阶段且用户未固定查看」时处理,不能在这里抢占用户选择。
return lifecycleEntryIsEnterable(entry) ? requested : current;
const candidate = lifecycleEntryIsEnterable(entry) ? requested : current;
if (!candidate) {
return null;
}
// [只进不退] 非手动请求的自动定位不得回跳到已越过的更早阶段:保持在已到达
// 的最远阶段,等待投影收敛(回归:提交订单后页签闪回「接收解析」)。
if (!manualRequested) {
const candidateIdx = LIFECYCLE_STAGE_CODES.indexOf(candidate);
if (candidateIdx >= 0 && candidateIdx < lifecycleStageFloor.value) {
return LIFECYCLE_STAGE_CODES[lifecycleStageFloor.value] ?? null;
}
}
return candidate ?? null;
});
// [只进不退] 已到达阶段序号只升不降:自动定位永不回跳前道阶段(手动点击前道
// 阶段是显式回看,不下调下限)。
watch(lifecycleActiveStageCode, (code) => {
const idx = LIFECYCLE_STAGE_CODES.indexOf(code as ReviewLifecycleStageCode);
if (idx >= 0) lifecycleStageFloor.value = Math.max(lifecycleStageFloor.value, idx);
});
/** 当前后端投影明确在自动推进时,五阶段导航只为该阶段展示 Spinner,不改变授权。 */
const lifecycleProcessingStageCode = computed<ReviewLifecycleStageCode | null>(() => {
@@ -462,12 +488,12 @@ const isReviewContentReadOnly = computed(() => (
isReadOnly.value || isCompletedFormalTask.value || isStpAutoCreateInProgress.value
));
/** 二期编辑窗(D10):读正式任务 ui_state.edit_window;前端 fail-closed,锁定字段禁用/提示。 */
/** 二期编辑窗(D10):读正式任务 ui_state.edit_window(后端权威下发,见 ui_state._build_edit_window)。 */
const formalEditWindow = computed(() => formalTaskDetail.value?.ui_state?.edit_window ?? null);
/** 头字段可编辑:edit_window.header 缺省视为可编辑(后端为权威守卫)。 */
/** 头字段可编辑:仅 edit_window.header 显式为 true(无 Export Artifact 且无活动 Attempt)时显示。 */
function formalHeaderEditable(): boolean {
return formalEditWindow.value?.header !== false;
return formalEditWindow.value?.header === true;
}
/**
@@ -521,8 +547,9 @@ async function retryCurrentIntakeParse(): Promise<void> {
* 只切换前端工作面并同步可分享深链;禁止在导航点击中修改任何订单生命周期字段。
*/
const lifecycleStagePinnedByUserForCase = ref<string | null>(null);
/** 仅库存短缺放行可建立一次性自动推进许可,避免通用 Gate 恢复抢占用户导航。 */
/** 用户触发的推进类 Gate 动作可建立一次性自动推进许可(动作时阶段→新阶段),避免通用 Gate 恢复抢占用户导航。 */
const pendingReleaseAutoAdvanceCaseNo = ref<string | null>(null);
const pendingReleaseAutoAdvanceFromStage = ref<ReviewLifecycleStageCode | null>(null);
/**
* 当前重解析完成前的一次性导航许可。
*
@@ -560,34 +587,41 @@ function cancelPendingReparseNavigation() {
}
/**
* 消费库存短缺放行后的自动推进许可。
* 消费用户触发的推进类 Gate 动作(缺口放行、重新生成 Excel 等)建立的一次性推进许可。
*
* 仅当同一 Case 仍停留在放行前的通知准备路由、用户未在放行后手动选阶段,且后端
* 权威投影已推进时替换深链。异步 Job 的首个投影可直接到目标阶段,不能依赖 watch
* 是否曾观察到旧阶段。
* 仅当同一 Case 仍停留在动作发生时的阶段路由、用户未在动作后手动选阶段,且后端
* 权威投影已越过动作时阶段时替换深链。异步 Job 的首个投影可直接到目标阶段,不能
* 依赖 watch 是否曾观察到旧阶段。
*/
async function syncPendingReleaseAutoAdvance(): Promise<boolean> {
const caseNo = String(activeCase.value?.case_no || '').trim();
if (!caseNo || pendingReleaseAutoAdvanceCaseNo.value !== caseNo) return false;
const fromStage = pendingReleaseAutoAdvanceFromStage.value;
if (!caseNo || !fromStage || pendingReleaseAutoAdvanceCaseNo.value !== caseNo) return false;
const requested = String(route.query.lifecycle_stage || '').trim();
if (
requested !== 'fulfillment_prep'
requested !== fromStage
|| lifecycleStagePinnedByUserForCase.value === caseNo
) {
pendingReleaseAutoAdvanceCaseNo.value = null;
pendingReleaseAutoAdvanceFromStage.value = null;
return false;
}
const current = lifecycleCurrentStageCode.value;
const currentIndex = current ? LIFECYCLE_STAGE_CODES.indexOf(current) : -1;
if (currentIndex <= LIFECYCLE_STAGE_CODES.indexOf('fulfillment_prep')) return false;
if (currentIndex <= LIFECYCLE_STAGE_CODES.indexOf(fromStage)) return false;
pendingReleaseAutoAdvanceCaseNo.value = null;
pendingReleaseAutoAdvanceFromStage.value = null;
await selectLifecycleStage(current!, { replace: true });
return true;
}
async function selectLifecycleStage(code: ReviewLifecycleStageCode, options: { replace?: boolean } = {}) {
async function selectLifecycleStage(
code: ReviewLifecycleStageCode,
options: { replace?: boolean; followThrough?: boolean } = {},
) {
const target = lifecycleStageItems.value.find((item) => item.code === code);
if (!target || target.state === 'blocked') return;
// followThrough:提交订单入队后允许进入尚未点亮的目标阶段(任务去向确定,阶段条随后端刷新点亮)。
if (!target || (target.state === 'blocked' && !options.followThrough)) return;
// 用户主动回看后端 available 或已完成阶段时,异步投影抵达不得将其强制带回当前阶段。
// 自动推进均使用 replace,不会写入该意图。
if (!options.replace) {
@@ -596,6 +630,7 @@ async function selectLifecycleStage(code: ReviewLifecycleStageCode, options: { r
rememberPendingReparseStage(code);
if (pendingReleaseAutoAdvanceCaseNo.value === caseNo) {
pendingReleaseAutoAdvanceCaseNo.value = null;
pendingReleaseAutoAdvanceFromStage.value = null;
}
}
if (code === 'intake_parse' && intakeParseContextAuthorized.value && intakeTargetCaseNo.value) {
@@ -657,6 +692,7 @@ watch(
if (caseNo !== previousCaseNo) {
lifecycleStagePinnedByUserForCase.value = null;
pendingReleaseAutoAdvanceCaseNo.value = null;
pendingReleaseAutoAdvanceFromStage.value = null;
}
},
);
@@ -817,6 +853,33 @@ const LINE_SCOPE_INVENTORY_ACTIONS = new Set([
'override_line_inventory_source',
]);
/**
* 阶段能力按执行动作码索引(preparation.capabilities)。
* 核心逻辑:右卡按钮的禁用态渲染必须与 submitFormalGateAction 的点击拦截消费同一份
* 能力投影,保证「展示=执行同源」——禁止按钮渲染成可点、点击才被能力门禁弹提示。
*/
const stageCapabilityByActionCode = computed(() => {
const map = new Map<string, { enabled: boolean; disabled_reason?: string | null }>();
for (const cap of formalPreparationContext.value?.capabilities || []) {
const code = String(cap.action_code || '').trim();
if (code) map.set(code, cap);
}
return map;
});
/**
* 给右卡动作附加阶段能力禁用原因。
* @param action - 已统一到卡片域的动作对象(须含 code)
* @returns 原对象浅拷贝;能力禁用时带 capabilityDisabledReason,否则该字段为 null
*/
function withStageCapabilityState<T extends { code: string }>(
action: T,
): T & { capabilityDisabledReason?: string | null } {
const cap = stageCapabilityByActionCode.value.get(String(action.code || '').trim());
if (!cap || cap.enabled) return { ...action, capabilityDisabledReason: null };
return { ...action, capabilityDisabledReason: String(cap.disabled_reason || '').trim() || null };
}
const currentTaskPrimaryAction = computed(() => {
if (formalTaskProjectionPending.value) return null;
if (hasFormalOt.value) {
@@ -828,10 +891,10 @@ const currentTaskPrimaryAction = computed(() => {
// 故必须统一映射到卡片域,否则按钮会因 businessActionLabel 为空而 fail-closed 消失。
const action = currentTaskUiState.value?.primary_action ?? null;
if (!action?.code || LINE_SCOPE_INVENTORY_ACTIONS.has(action.code)) return null;
return {
return withStageCapabilityState({
code: String(action.code).trim(),
i18nKey: `workspace.shippingNotice.processGate.actionCodes.${action.code}`,
};
});
}
const projection = shippingProcessingProjection.value;
if (projection) {
@@ -914,6 +977,8 @@ const currentTaskRecoveryActions = computed(() => {
// [§2.4 单源] 任务级恢复按钮只读 A.secondary_actions;不再叠加 B.capabilities。
// capabilities 仍可作点击执行的 stageCapabilityBypass 查找(见 handleCurrentTaskAction),
// 但不得单独渲成右卡按钮——能力要展示须先并进 A。行级选源禁止出现在右卡。
// [展示=执行同源] A 已渲染的按钮若命中阶段能力 disabled(capabilityDisabledReason
// 非空),右卡必须渲染禁用态 + 原因 tooltip,禁止可点样式诱导用户点击后才被拦截。
return (currentTaskUiState.value?.secondary_actions || [])
.filter((action) => action.enabled
&& String(action.code || '').trim() !== 'download_excel'
@@ -923,7 +988,8 @@ const currentTaskRecoveryActions = computed(() => {
// 统一右卡 domain:actionCodes.<code>(见 currentTaskPrimaryAction 注;A 的 i18nKey 可能是 chat 域)。
i18nKey: `workspace.shippingNotice.processGate.actionCodes.${String(action.code || '').trim()}`,
}))
.filter((action): action is { code: string; i18nKey: string } => {
.map((action) => withStageCapabilityState(action))
.filter((action): action is { code: string; i18nKey: string; capabilityDisabledReason?: string | null } => {
const code = String(action.code || '').trim();
return Boolean(code) && !LINE_SCOPE_INVENTORY_ACTIONS.has(code);
});
@@ -1748,6 +1814,8 @@ function handleGateRecoveryAccepted(options: { releaseAutoAdvance?: boolean } =
// 放行前可能是用户手动进入通知准备;该历史意图不能阻止本次放行后的自动推进。
lifecycleStagePinnedByUserForCase.value = null;
pendingReleaseAutoAdvanceCaseNo.value = caseNo;
// 记录动作时阶段:只跟随「越过动作时阶段」的一次推进,且用户主动换页会取消。
pendingReleaseAutoAdvanceFromStage.value = lifecycleCurrentStageCode.value;
}
page.bumpWorkflowRefresh?.();
startWorkflowProgressPolling();
@@ -1845,7 +1913,7 @@ async function executeFormalTaskAction(
if (!formalGate) return;
const result = await submitProcessGatePrimaryAction(formalGate, { actionCode: action.code });
if (result.outcome === 'submitted' || result.outcome === 'refresh_needed') {
handleGateRecoveryAccepted();
handleGateRecoveryAccepted({ releaseAutoAdvance: true });
}
}
@@ -1915,7 +1983,7 @@ async function handleCurrentTaskAction(
if (serverAuthorizedGateAction) {
const result = await submitProcessGatePrimaryAction(processGate, { actionCode: normalizedCode });
if (result.outcome === 'submitted' || result.outcome === 'refresh_needed') {
handleGateRecoveryAccepted();
handleGateRecoveryAccepted({ releaseAutoAdvance: true });
}
return;
}
@@ -1980,7 +2048,7 @@ async function handleCurrentTaskAction(
if (!summary) return;
const result = await submitProcessGatePrimaryAction(summary, { actionCode: code });
if (result.outcome === 'submitted' || result.outcome === 'refresh_needed') {
handleGateRecoveryAccepted();
handleGateRecoveryAccepted({ releaseAutoAdvance: true });
}
break;
}
@@ -2258,8 +2326,11 @@ const processDetailPoNumber = computed(() => {
* 改源到任务级」计划(E)一并收敛。
*/
const selectedOrderSummary = computed(() => {
// 深链可能只带 run_no(历史记录切换等入口);此时 Case 身份在 requestedCaseNo →
// displayCase 上,必须优先按当前工作面身份匹配队列项,不能因 URL 缺 case 而显示「未命名」。
const activeNo = String(
route.query.case || route.query.case_no
displayCase.value?.case_no
|| route.query.case || route.query.case_no
|| '',
).trim();
const item = reviewQueue.value?.items?.find((candidate) => candidate.case_no === activeNo)
@@ -2287,11 +2358,19 @@ const showWorkbenchGrid = computed(
() => workbenchMode.value === 'formal_task' || !isConfirmProgressPrimary.value,
);
const lastLifecycleProgress = ref<ShippingOrderExtractionLifecycleProgress | null>(null);
// [阶段防回跳] 提交订单后的刷新窗口内,extractionLifecycleProgress 会被 Run 级
// lifecycle_progress(两段模型,恒为 intake_parse)短暂覆盖,页签因此闪回
// 「接收解析」。此处保持最近一次非空投影作为兜底,不再回落到 Run 级旧值;
// 数据到达后自然收敛到真实当前阶段(如通知准备)。
const lifecycleProgressForView = computed(() => (
extractionLifecycleProgress.value
|| reviewRun.value?.lifecycle_progress
|| lastLifecycleProgress.value
|| null
));
watch(lifecycleProgressForView, (value) => {
if (value) lastLifecycleProgress.value = value;
});
const lifecycleProgressStageItems = computed<ReviewLifecycleStageItem[]>(() => {
const progress = lifecycleProgressForView.value;
@@ -2568,8 +2647,12 @@ const formalPreparationLines = computed(() => {
...line,
required_qty: displayDecimalQty(line.required_qty),
available_qty: displayDecimalQty(line.available_qty),
// available_qty 语义为「预约匹配量」(列头:预约数量);part_available_qty 为料号总库存
// (列头:可用数量)。null 透传,由模板渲染待确认占位,避免把「无快照」误显示为 0。
part_available_qty:
line.part_available_qty == null ? null : displayDecimalQty(line.part_available_qty),
shortage_qty: displayDecimalQty(line.shortage_qty),
})) as Array<typeof rows[number] & { snapshot_line_id?: number | null; required_qty: string; available_qty: string; shortage_qty: string }>;
})) as Array<typeof rows[number] & { snapshot_line_id?: number | null; required_qty: string; available_qty: string; shortage_qty: string; part_available_qty: string | null }>;
});
/** 通知准备固定展示冻结订单明细;库存匹配结果只作为附加事实合并。 */
@@ -2620,20 +2703,9 @@ const formalPreparationSourceLocked = computed(() => Boolean(formalPreparationCo
/** 库存源选择不再有独立确认流:行进入就地编辑态后在下拉中改选,随行级「保存」统一提交
* (override_line_inventory_source Gate 动作,见 saveInlineEdit);展示态回退为文本。 */
/** 选源下拉项文案:源编码始终可见(等宽语义由样式层保证)。 */
function lineSourceOptionLabel(code: string): string {
// 兜底:只会展示源编码(如 DSV360_AWSSG),不展示冗长显示名。
return String(code || '').trim().toUpperCase();
}
/** 人工覆写库存源(方案 3·放开):后端下发全部已启用源 source_options,供行级下拉人工指定。 */
const formSourceOptions = computed(() => formalPreparationContext.value?.source_options || []);
function overrideSourceOptionLabel(code: string): string {
// 兜底:下拉只展示源编码(如 DSV360_AWSSG),不展示冗长 display_name,便于快速识别。
return String(code || '').trim().toUpperCase();
}
/** 整单 ODM 裁决列可见性:任一行候选多于一个时展示(候选已经客户范围过滤)。 */
const formalPreparationOdmColumnVisible = computed(() =>
(formalPreparationContext.value?.lines || []).some((line) => (line.odm_values?.length || 0) > 1),
@@ -2913,7 +2985,7 @@ async function confirmCloseLine() {
expected_draft_version: activeCase.value?.draft?.draft_version,
});
closeLineDialogLine.value = null;
handleGateRecoveryAccepted();
handleGateRecoveryAccepted({ releaseAutoAdvance: true });
} catch (error) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
} finally {
@@ -3017,20 +3089,14 @@ function isInlineEditing(line: { snapshot_line_id?: number | null }): boolean {
}
/**
* 编辑态库存源下拉选项:多文件冲突行优先取候选源,其余行取全部已启用源;
* 行级编辑态库存源下拉选项:歧义行候选置顶 + 全部已启用源兜底(合并去重,纯函数委托)。
* 无可用项返回空——此时编辑态库存源保持文本展示(无可选即不可改)。
*/
function inlineSourceOptions(line: {
source_ambiguous?: boolean;
source_candidates?: Array<string>;
}): Array<{ value: string; label: string }> {
if (line.source_ambiguous && (line.source_candidates?.length || 0) > 0) {
return (line.source_candidates || []).map((code) => ({ value: String(code), label: lineSourceOptionLabel(String(code)) }));
}
if (formSourceOptions.value.length) {
return formSourceOptions.value.map((s) => ({ value: String(s.source_code), label: overrideSourceOptionLabel(String(s.source_code)) }));
}
return [];
return mergeInlineSourceOptions(line, formSourceOptions.value);
}
/** 同步编辑态库存源草稿(与三个值列一致:改动仅在保存时提交)。 */
@@ -3482,9 +3548,11 @@ async function runFreightBatchAction(action: 'download' | 'confirm' | 'rpa') {
if (action === 'download') {
await downloadWorkspaceShippingNoticeExportArchive(selectedFreightBusinessNos.value);
} else if (action === 'confirm') {
await batchConfirmWorkspaceShippingNoticesUploaded(selectedFreightBusinessNos.value);
const summary = await batchConfirmWorkspaceShippingNoticesUploaded(selectedFreightBusinessNos.value);
warnBlockedFreightNoticeResults(summary.results);
} else {
await batchStartWorkspaceShippingNoticeRpaUpload(selectedFreightBusinessNos.value);
const summary = await batchStartWorkspaceShippingNoticeRpaUpload(selectedFreightBusinessNos.value);
warnBlockedFreightNoticeResults(summary.results);
}
// 确认/RPA 后重拉同 PO 通知聚合,使通知完成面能立即呈现最新 uploaded 状态。
if (action === 'confirm' || action === 'rpa') {
@@ -3520,9 +3588,11 @@ async function runFreightNoticeAction(
freightBatchBusy.value = action;
try {
if (action === 'confirm') {
await batchConfirmWorkspaceShippingNoticesUploaded([group.business_no]);
const summary = await batchConfirmWorkspaceShippingNoticesUploaded([group.business_no]);
warnBlockedFreightNoticeResults(summary.results);
} else if (action === 'rpa') {
await batchStartWorkspaceShippingNoticeRpaUpload([group.business_no]);
const summary = await batchStartWorkspaceShippingNoticeRpaUpload([group.business_no]);
warnBlockedFreightNoticeResults(summary.results);
} else {
if (String(formalTaskDetail.value?.business_no || '').trim() !== group.business_no) return;
await submitFormalGateAction('regenerate_excel_artifact');
@@ -3543,6 +3613,25 @@ async function runFreightNoticeAction(
}
}
/**
* 批量 RPA/确认结果逐单消费:被拦截项的原因必须浮出。
* 核心逻辑:批量接口恒返回 202 成功 envelope,逐单 blocked 藏在 results 里
* (历史缺陷:前端不检查,界面零反馈,用户以为点击无效——如「库存源尚未确定」)。
* blocked 携带后端本地化 message(AppError 在顶层、tool_response 在 result 内),
* 去重后合并为一条 warning;accepted 项的状态推进由既有投影刷新呈现。
* @param results - 批量接口返回的逐单结果数组。
*/
function warnBlockedFreightNoticeResults(results: Array<Record<string, unknown>> | undefined): void {
const reasons = new Set<string>();
for (const item of results || []) {
if (String(item?.status || '') !== 'blocked') continue;
const detail = item as { message?: unknown; code?: unknown; result?: { message?: unknown } };
const reason = String(detail.message || detail.result?.message || detail.code || '').trim();
if (reason) reasons.add(reason);
}
if (reasons.size) msg.warning(Array.from(reasons).join(';'));
}
/** 当前任务的 Excel 重生只可映射到其自身 business_no,禁止跨 PO/通知单展示。 */
function canRegenerateFreightNotice(group: ShippingFreightNoticeGroup): boolean {
return canRunFreightNoticeAction(group, 'regenerate_excel_artifact')
@@ -4041,7 +4130,8 @@ const submitFormalGateAction = async (
});
if (result.outcome === 'submitted' || result.outcome === 'refresh_needed') {
progressRetrying.value = false;
handleGateRecoveryAccepted();
// 用户触发的推进类动作(重新生成 Excel 等)成功后允许自动跳到新阶段一次。
handleGateRecoveryAccepted({ releaseAutoAdvance: true });
}
} catch (error) {
msg.error(resolveReviewErrorMessage(error));
@@ -4072,7 +4162,7 @@ const retryStpAutoCreate = async () => {
} else {
await reloadLatestDraft();
}
handleGateRecoveryAccepted();
handleGateRecoveryAccepted({ releaseAutoAdvance: true });
msg.success(t('chat.shippingOrderReview.autoProgress.retryStpSuccess'));
} catch (error) {
msg.error(resolveReviewErrorMessage(error));
@@ -4289,7 +4379,7 @@ const onUnifiedProcessingAction = async (item: ActionPresentationItem) => {
if (!formalGate) return;
const result = await submitProcessGatePrimaryAction(formalGate, { actionCode: authorized.code });
if (result.outcome === 'submitted' || result.outcome === 'refresh_needed') {
handleGateRecoveryAccepted();
handleGateRecoveryAccepted({ releaseAutoAdvance: true });
}
return;
}
@@ -4312,6 +4402,15 @@ const onValidate = async () => {
try {
const resume = await validate();
showReviewResumeOutcome(resume, msg, t, t('chat.shippingOrderReview.saveOrderAndValidateSuccess'));
// 入队即确定去向:正式任务创建后进入通知准备工作面(产品确认 2026-10-13),
// 不再回放提交前「接收解析」的初始阶段快照;后续获取库存/货代上传推进继续跟随。
const outcome = String(resume?.outcome || '').trim();
if (['auto_create_enqueued', 'already_queued', 'already_running'].includes(outcome)) {
lifecycleStagePinnedByUserForCase.value = null;
pendingReleaseAutoAdvanceCaseNo.value = null;
pendingReleaseAutoAdvanceFromStage.value = null;
await selectLifecycleStage('fulfillment_prep', { replace: true, followThrough: true });
}
} catch (error) {
msg.error(resolveReviewErrorMessage(error));
}
@@ -4875,20 +4974,21 @@ watch(
watch(
() => [
lifecycleCurrentStageCode.value,
String(activeCase.value?.case_no || '').trim(),
activeReviewDocumentId(),
// 文件身份必须用 requestedCaseNo(与 lifecycleUiState 解析阶段同源):正式下游
// (通知准备/货代上传/通知完成,选法 2)activeCase 刻意为 null,其 case_no/document_id
// 在这些文件之间恒为空值,用 activeCase 做身份会让"切换文件"被误判成"同一文件的
// 阶段推进"而弹出"已自动推进"。requestedCaseNo 在 selectCase/beginCrossRunSwitch/
// load 里与阶段重算同一同步块内更新,切换文件时本 watcher 必然看到变化而静默;
// 真正的自动推进只改队列投影、不触碰 requestedCaseNo,提示行为不变。
String(requestedCaseNo.value || activeCase.value?.case_no || '').trim(),
] as const,
async (current, previous) => {
const [currentStage, currentCaseNo, currentDocumentId] = current;
const [previousStage, previousCaseNo, previousDocumentId] = previous || [];
const [currentStage, currentFileKey] = current;
const [previousStage, previousFileKey] = previous || [];
if (await syncPendingReleaseAutoAdvance()) return;
// 切换文件时生命周期阶段会随新 Case 一起变更;这不是当前文件的自动推进,
// 切换文件时生命周期阶段会随新文件身份一起变更;这不是当前文件的自动推进,
// 不能跳转或弹出“已自动推进”提示。
if (
!previous
|| currentCaseNo !== previousCaseNo
|| currentDocumentId !== previousDocumentId
) return;
if (!previous || currentFileKey !== previousFileKey) return;
if (!currentStage || !previousStage || currentStage === previousStage) return;
const pendingReparse = pendingReparseNavigation.value;
if (
@@ -5329,8 +5429,8 @@ watch(
</div>
<div class="overflow-x-auto overscroll-x-contain" data-testid="review-fulfillment-prep-table-scroll">
<table class="review-fulfillment-prep-table min-w-[1060px] text-xs">
<thead class="border-b border-default bg-surface-muted/50 text-left"><tr><th v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="allPreparationWaveSelected" :disabled="!preparationWaveSelectableLines.length || preparationWaveBusy" :aria-label="t('chat.shippingOrderReview.fulfillmentDecision.selectReady')" @change="toggleAllPreparationLineSelection(($event.target as HTMLInputElement).checked)"></th><th v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationCustomerPoLineLabel() }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultReservation') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultPartNumber') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.requiredQty') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.inventorySource') }}</th><th v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.odmConflict.column') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineStatus') }}</th><th class="review-fulfillment-sticky-action-head whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lineOps.moreActions') }}</th></tr></thead>
<tbody><template v-for="(line, lineIndex) in formalPreparationDisplayLines" :key="line.snapshot_line_id || `${line.reservation_id}-${line.part_number}`"><tr :class="Number(line.shortage_qty || 0) > 0 ? 'border-b border-amber-100 bg-amber-50/40 last:border-0 dark:border-amber-950 dark:bg-amber-950/10' : 'border-b border-default last:border-0'"><td v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="selectedPreparationSnapshotLineIds.includes(String(line.snapshot_line_id))" :disabled="preparationWaveBusy || !preparationWaveSelectableLines.some((item) => String(item.snapshot_line_id) === String(line.snapshot_line_id))" :aria-label="`${t('chat.shippingOrderReview.fulfillmentDecision.selectReady')}: ${preparationLineCustomerPoLine(line)}`" :data-testid="`review-fulfillment-line-select-${line.snapshot_line_id || lineIndex}`" @change="togglePreparationLineSelection(String(line.snapshot_line_id || lineIndex), ($event.target as HTMLInputElement).checked)"></td><td v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationLineCustomerPoLine(line) }}</td><td class="whitespace-nowrap px-3 py-2 font-medium text-primary"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.reservation_id" type="text" class="w-28 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultReservation')" :data-testid="`review-fulfillment-line-edit-reservation-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.reservation_id || '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.part_number" type="text" class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultPartNumber')" :data-testid="`review-fulfillment-line-edit-part-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else class="block max-w-[220px] truncate" :title="line.part_number || '—'">{{ line.part_number || '—' }}</span></td><td class="whitespace-nowrap px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input :value="editingLine.required_qty" type="number" min="0" step="any" class="w-20 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.requiredQty')" :data-testid="`review-fulfillment-line-edit-qty-${line.snapshot_line_id}`" @input="updateInlineEditQty(($event.target as HTMLInputElement).value)" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.required_qty ?? '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="isInlineEditing(line) && inlineSourceOptions(line).length"><select class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-fulfillment-line-edit-source-${line.snapshot_line_id}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="editingLine?.source_code" :disabled="inlineEditSaving" @change="updateInlineEditSource(($event.target as HTMLSelectElement).value)"><option v-for="option in inlineSourceOptions(line)" :key="option.value" :value="option.value">{{ option.label }}</option></select></template><span v-else class="block max-w-[220px] truncate" :title="formalPreparationLineSource(line)">{{ formalPreparationLineSource(line) || '—' }}</span></td><td v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2"><div v-if="(line.odm_values?.length || 0) > 1 && !formalPreparationSourceLocked" class="flex items-center gap-1" :data-testid="`review-line-odm-${line.snapshot_line_id || lineIndex}`"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-odm-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.odmConflict.title')" :value="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || line.chosen_odm_id || ''" @change="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.odmConflict.placeholder') }}</option><option v-for="value in line.odm_values" :key="value" :value="value">{{ value }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-odm-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || lineOdmBusy" :aria-label="t('chat.shippingOrderReLine truncated
<thead class="border-b border-default bg-surface-muted/50 text-left"><tr><th v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="allPreparationWaveSelected" :disabled="!preparationWaveSelectableLines.length || preparationWaveBusy" :aria-label="t('chat.shippingOrderReview.fulfillmentDecision.selectReady')" @change="toggleAllPreparationLineSelection(($event.target as HTMLInputElement).checked)"></th><th v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationCustomerPoLineLabel() }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultReservation') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultPartNumber') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.requiredQty') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.inventorySource') }}</th><th v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.odmConflict.column') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.reservedQty') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.partAvailableQty') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineStatus') }}</th><th class="review-fulfillment-sticky-action-head whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lineOps.moreActions') }}</th></tr></thead>
<tbody><template v-for="(line, lineIndex) in formalPreparationDisplayLines" :key="line.snapshot_line_id || `${line.reservation_id}-${line.part_number}`"><tr :class="Number(line.shortage_qty || 0) > 0 ? 'border-b border-amber-100 bg-amber-50/40 last:border-0 dark:border-amber-950 dark:bg-amber-950/10' : 'border-b border-default last:border-0'"><td v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="selectedPreparationSnapshotLineIds.includes(String(line.snapshot_line_id))" :disabled="preparationWaveBusy || !preparationWaveSelectableLines.some((item) => String(item.snapshot_line_id) === String(line.snapshot_line_id))" :aria-label="`${t('chat.shippingOrderReview.fulfillmentDecision.selectReady')}: ${preparationLineCustomerPoLine(line)}`" :data-testid="`review-fulfillment-line-select-${line.snapshot_line_id || lineIndex}`" @change="togglePreparationLineSelection(String(line.snapshot_line_id || lineIndex), ($event.target as HTMLInputElement).checked)"></td><td v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationLineCustomerPoLine(line) }}</td><td class="whitespace-nowrap px-3 py-2 font-medium text-primary"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.reservation_id" type="text" class="w-28 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultReservation')" :data-testid="`review-fulfillment-line-edit-reservation-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.reservation_id || '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.part_number" type="text" class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultPartNumber')" :data-testid="`review-fulfillment-line-edit-part-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else class="block max-w-[220px] truncate" :title="line.part_number || '—'">{{ line.part_number || '—' }}</span></td><td class="whitespace-nowrap px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input :value="editingLine.required_qty" type="number" min="0" step="any" class="w-20 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.requiredQty')" :data-testid="`review-fulfillment-line-edit-qty-${line.snapshot_line_id}`" @input="updateInlineEditQty(($event.target as HTMLInputElement).value)" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.required_qty ?? '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="isInlineEditing(line) && inlineSourceOptions(line).length"><select class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-fulfillment-line-edit-source-${line.snapshot_line_id}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="editingLine?.source_code" :disabled="inlineEditSaving" @change="updateInlineEditSource(($event.target as HTMLSelectElement).value)"><option v-for="option in inlineSourceOptions(line)" :key="option.value" :value="option.value">{{ option.label }}</option></select></template><span v-else class="block max-w-[220px] truncate" :title="formalPreparationLineSource(line)">{{ formalPreparationLineSource(line) || '—' }}</span></td><td v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2"><div v-if="(line.odm_values?.length || 0) > 1 && !formalPreparationSourceLocked" class="flex items-center gap-1" :data-testid="`review-line-odm-${line.snapshot_line_id || lineIndex}`"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-odm-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.odmConflict.title')" :value="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || line.chosen_odm_id || ''" @change="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.odmConflict.placeholder') }}</option><option v-for="value in line.odm_values" :key="value" :value="value">{{ value }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-odm-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || lineOdmBusy" :aria-label="t('chat.shippingOrderReLine truncated
</table>
</div>
</div>
@@ -5958,14 +6058,16 @@ watch(
@open-details="openEligibilityDetails"
@navigate-exception="navigateExceptionField"
/>
<!-- 订单复核 Gate 统一收敛至右栏;主编辑列只保留字段、明细与证据。 -->
<!-- 订单复核 Gate 统一收敛至右栏;主编辑列只保留字段、明细与证据。
客户识别面板两态渲染(resolved 与否由面板内部分态):已确认折叠为摘要条并提供改绑入口,
不再在 resolved 后整体消失。 -->
<template v-if="showOrderReviewEditor && activeCase">
<ReviewCustomerResolutionPanel
v-if="!activeCase.customer_resolution?.resolved"
ref="customerResolutionWideRef"
:case-no="activeCase.case_no"
:resolution="activeCase.customer_resolution"
:editable="editable"
:order-data-version="activeCase.order_data_version"
@refreshed="handleReviewGateDataRefreshed"
/>
<ReviewFieldConflictPanel
@@ -0,0 +1,261 @@
/**
* features/equipment-acceptance/api/equipment-acceptance.api.ts
* 用途:设备验收预警同步列表、详情和手动同步。
* 依赖:统一 requestJson;后端 /api/equipment-acceptance。
* 逻辑:Chat 作业面调用。同步只读 E10。配置只保存天数和系统用户,不保存发送时刻。
* 保存配置自行声明 Content-Type: application/json,供 Flask get_json 解析。
* 发送记录只读已落库的行。每位收件人的 Excel 可再下载。
*/
import { requestBlob, requestJson } from '@/shared/api/client';
export interface EquipmentAcceptanceNode {
node_id?: string | null;
node_name?: string | null;
node_type?: number | null;
}
export interface EquipmentAcceptanceOperator {
node_id?: string | null;
user_id?: string | null;
handler_name?: string | null;
handler_job_num?: string | null;
}
export interface EquipmentAcceptanceOrder {
id: number;
acceptance_no?: string | null;
purchase_order_no?: string | null;
contract_no?: string | null;
timer_started_at?: string | null;
dwell_days?: number | null;
can_accept?: number | null;
cannot_accept_note?: string | null;
is_returned?: number | null;
flow_status_raw?: number | null;
finished_at?: string | null;
request_id?: string | null;
request_match_count: number;
owner_name?: string | null;
owner_job_num?: string | null;
applicant_name?: string | null;
applicant_job_num?: string | null;
monitor_status: string;
overdue?: boolean;
present_in_source: boolean;
synced_at?: string | null;
nodes: EquipmentAcceptanceNode[];
operators: EquipmentAcceptanceOperator[];
}
export interface EquipmentAcceptanceSummary {
watching: number;
overdue: number;
stopped: number;
not_started: number;
}
export interface EquipmentAcceptanceListResponse {
items: EquipmentAcceptanceOrder[];
total: number;
page: number;
page_size: number;
pages: number;
summary?: EquipmentAcceptanceSummary;
}
export interface EquipmentAcceptanceSyncResult {
upserted: number;
skipped_without_request_id: number;
absent: number;
by_status: Record<string, number>;
}
/**
* 分页查询已同步的验收单。
* 核心逻辑:focus 对应原型分组。空或 all 不过滤。
* @param params.focus - watching、overdue、stopped、not_started
* @param params.page - 页码,从 1 开始
* @param params.pageSize - 每页条数
* @returns 分页快照和全部单据汇总
*/
export function listEquipmentAcceptanceOrders(params?: {
focus?: string;
page?: number;
pageSize?: number;
}) {
const query = new URLSearchParams();
if (params?.focus && params.focus !== 'all') query.set('focus', params.focus);
if (params?.page) query.set('page', String(params.page));
if (params?.pageSize) query.set('page_size', String(params.pageSize));
const suffix = query.toString() ? `?${query.toString()}` : '';
return requestJson<EquipmentAcceptanceListResponse>(`/api/equipment-acceptance/orders${suffix}`);
}
/**
* 读取一张验收单的节点和操作人。
* @param orderId - 本地快照主键
* @returns 快照详情
*/
export function getEquipmentAcceptanceOrder(orderId: number) {
return requestJson<EquipmentAcceptanceOrder>(`/api/equipment-acceptance/orders/${orderId}`);
}
/**
* 从 E10 拉取验收单并更新本地快照。仅平台管理员可调用。
* @returns 本次写入、跳过和未见条数
*/
export function syncEquipmentAcceptance() {
return requestJson<EquipmentAcceptanceSyncResult>('/api/equipment-acceptance/sync', { method: 'POST' });
}
export interface EquipmentAcceptanceScanResult {
created: number;
updated: number;
cancelled: number;
}
export interface EquipmentAcceptanceSendResult {
sent: number;
failed: number;
records_sent: number;
records_failed: number;
}
/**
* 管理员立即同步 E10 并生成待发送记录。
* @returns 新增、更新和取消条数
*/
export function scanEquipmentAcceptanceAlerts() {
return requestJson<EquipmentAcceptanceScanResult>('/api/equipment-acceptance/alerts/scan', { method: 'POST' });
}
/**
* 管理员立即把待发送记录按收件人发到企业微信。
* @returns 成功和失败的收件人数
*/
export function sendEquipmentAcceptanceAlerts() {
return requestJson<EquipmentAcceptanceSendResult>('/api/equipment-acceptance/alerts/send', { method: 'POST' });
}
export interface EquipmentAcceptanceSendRecord {
id: number;
order_id?: number | null;
acceptance_no?: string | null;
purchase_order_no?: string | null;
tier: number;
threshold_days: number;
to_text?: string | null;
cc_text?: string | null;
status: string;
sent_at?: string | null;
error_message?: string | null;
created_at?: string | null;
files?: Array<{ id: number; excel_file_name?: string | null }>;
}
export interface EquipmentAcceptanceSendListResponse {
items: EquipmentAcceptanceSendRecord[];
total: number;
page: number;
page_size: number;
}
/**
* 分页读取发送记录。
* 核心逻辑:按创建时间倒序。还没有扫描写入时 items 为空。
* @param params.page - 从 1 开始
* @param params.pageSize - 每页条数
* @returns 当前页记录和总数
*/
export interface EquipmentAcceptanceSendFile {
id: number;
recipient_name?: string | null;
excel_file_name?: string | null;
excel_file_size?: number | null;
status: string;
sent_at?: string | null;
created_at?: string | null;
}
/**
* 列出最近按收件人归档的 Excel。不含文件内容。
* @returns 文件摘要
*/
export function listEquipmentAcceptanceSendFiles() {
return requestJson<{ items: EquipmentAcceptanceSendFile[] }>('/api/equipment-acceptance/send-files');
}
/**
* 下载一份当时发给收件人的 Excel。
* @param fileId - 归档文件主键
* @returns 文件字节和文件名
*/
export function downloadEquipmentAcceptanceSendFile(fileId: number) {
return requestBlob(`/api/equipment-acceptance/send-files/${fileId}/excel`);
}
export function listEquipmentAcceptanceSends(params?: { page?: number; pageSize?: number }) {
const search = new URLSearchParams();
if (params?.page) search.set('page', String(params.page));
if (params?.pageSize) search.set('page_size', String(params.pageSize));
const suffix = search.toString() ? `?${search.toString()}` : '';
return requestJson<EquipmentAcceptanceSendListResponse>(`/api/equipment-acceptance/sends${suffix}`);
}
export interface EquipmentAcceptanceConfigUser {
id: number;
username: string;
real_name?: string | null;
employee_id?: string | null;
department?: string | null;
wecom_bound?: boolean;
}
export interface EquipmentAcceptanceConfig {
days: number[];
round_4_enabled?: boolean;
buyer_manager_user_id?: number | null;
coo_user_id?: number | null;
executive_user_id?: number | null;
selected_users: EquipmentAcceptanceConfigUser[];
users: EquipmentAcceptanceConfigUser[];
updated_at?: string | null;
}
/**
* 读取四档天数和三个固定岗位。管理员响应里带候选人。
* @returns 当前配置
*/
export function getEquipmentAcceptanceConfig() {
return requestJson<EquipmentAcceptanceConfig>('/api/equipment-acceptance/config');
}
/**
* 保存四档天数、第 4 轮开关和三个岗位的系统用户。仅平台管理员。
* 核心逻辑:岗位传用户主键或 null,不传姓名。第 4 轮关闭时不通知总经理。
* @param payload.days - 四个逐档增大的天数
* @param payload.round4Enabled - 是否启用第 4 轮
* @param payload.buyerManagerUserId - 采购经副理
* @param payload.cooUserId - COO
* @param payload.executiveUserId - 总经理对应岗位
* @returns 保存后的配置。请求头带 application/json,避免 Flask 把正文当成空对象。
*/
export function saveEquipmentAcceptanceConfig(payload: {
days: number[];
round4Enabled: boolean;
buyerManagerUserId: number | null;
cooUserId: number | null;
executiveUserId: number | null;
}) {
return requestJson<EquipmentAcceptanceConfig>('/api/equipment-acceptance/config', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
days: payload.days,
round_4_enabled: payload.round4Enabled,
buyer_manager_user_id: payload.buyerManagerUserId,
coo_user_id: payload.cooUserId,
executive_user_id: payload.executiveUserId,
}),
});
}
@@ -0,0 +1,225 @@
<!--
features/equipment-acceptance/components/EquipmentAcceptanceChatPanel.vue
用途:设备验收预警 Chat 主区:停留列表、详情、发送记录、预警配置,以及管理员同步、扫描和发送。
依赖:停留列表、详情、发送记录、配置页、auth.store、equipment-acceptance.api、DeleteConfirmDialog、vue-router query。
逻辑:由 ChatViewContent 在 agent_code=equipment_acceptance 时替换消息列表与输入框。
view=config 打开预警配置;view=sends 打开发送记录;orderId 只在停留列表下钻。
同步只在停留列表。扫描和发送只在发送记录,且仅平台管理员可见。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { RefreshCw } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import { useMessage } from '@/shared/composables/useMessage';
import {
scanEquipmentAcceptanceAlerts,
sendEquipmentAcceptanceAlerts,
syncEquipmentAcceptance,
} from '../api/equipment-acceptance.api';
import EquipmentAcceptanceConfigPage from '../views/EquipmentAcceptanceConfigPage.vue';
import EquipmentAcceptanceDetailPage from '../views/EquipmentAcceptanceDetailPage.vue';
import EquipmentAcceptancePage from '../views/EquipmentAcceptancePage.vue';
import EquipmentAcceptanceSendsPage from '../views/EquipmentAcceptanceSendsPage.vue';
type WorkspaceView = 'ledger' | 'sends' | 'config';
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const auth = useAuthStore();
const msg = useMessage();
const syncing = ref(false);
const alertRunning = ref(false);
const pendingAlert = ref<'scan' | 'send' | null>(null);
const listPage = ref<{ reload: () => Promise<void> } | null>(null);
const sendsPage = ref<{ reload: () => Promise<void> } | null>(null);
const isAdmin = computed(() => Boolean(auth.isAdmin));
const activeView = computed<WorkspaceView>(() => {
if (route.query.view === 'config') return 'config';
if (route.query.view === 'sends') return 'sends';
return 'ledger';
});
const showAlertConfirm = computed({
get: () => pendingAlert.value !== null,
set: (open: boolean) => {
if (!open) pendingAlert.value = null;
},
});
const alertConfirmCopy = computed(() => (
pendingAlert.value === 'send'
? { title: t('admin.equipmentAcceptance.sendAlerts'), message: t('admin.equipmentAcceptance.sendConfirm') }
: { title: t('admin.equipmentAcceptance.scanAlerts'), message: t('admin.equipmentAcceptance.scanConfirm') }
));
const detailId = computed(() => {
if (activeView.value !== 'ledger') return null;
const raw = Number(route.query.orderId);
return Number.isInteger(raw) && raw > 0 ? raw : null;
});
const tabs = computed(() => ([
{ key: 'ledger' as const, label: t('admin.equipmentAcceptance.tabLedger') },
{ key: 'sends' as const, label: t('admin.equipmentAcceptance.tabSends') },
{ key: 'config' as const, label: t('admin.equipmentAcceptance.tabConfig') },
]));
/**
* 把当前 Tab 和详情写入 Chat 路由。
* 核心逻辑:配置和发送记录清掉 orderId。停留列表不写 view,避免旧链接被改掉。
* @param view - ledger、sends 或 config
* @param orderId - 本地快照主键,空表示列表
*/
async function syncQuery(view: WorkspaceView, orderId: number | null): Promise<void> {
const query = { ...route.query };
if (view === 'config' || view === 'sends') {
query.view = view;
delete query.orderId;
} else {
delete query.view;
if (orderId) query.orderId = String(orderId);
else delete query.orderId;
}
const sameView = String(route.query.view || '') === String(query.view || '');
const sameOrder = String(route.query.orderId || '') === String(query.orderId || '');
if (sameView && sameOrder) return;
await router.replace({ params: { ...route.params }, query });
}
/**
* 切换停留列表、发送记录和预警配置。
* @param view - 目标 Tab
*/
function selectView(view: WorkspaceView): void {
void syncQuery(view, null);
}
/**
* 管理员在发送记录页立即扫描或发送。
* 核心逻辑:公共确认框点确定后才调用。先取出动作再关掉弹窗,避免关闭时把待执行动作清掉。
*/
function confirmAlertAction(): void {
const action = pendingAlert.value;
pendingAlert.value = null;
if (action) void runAlertAction(action);
}
/**
* 执行已经确认的扫描或发送。
* 核心逻辑:扫描会同步 E10;发送把待发送记录推到企业微信。
* @param action - scan 或 send
*/
async function runAlertAction(action: 'scan' | 'send'): Promise<void> {
if (alertRunning.value) return;
alertRunning.value = true;
try {
if (action === 'scan') {
const result = await scanEquipmentAcceptanceAlerts();
msg.success(t('admin.equipmentAcceptance.scanDone', {
created: result.created,
updated: result.updated,
cancelled: result.cancelled,
}));
} else {
const result = await sendEquipmentAcceptanceAlerts();
msg.success(t('admin.equipmentAcceptance.sendDone', {
sent: result.sent,
failed: result.failed,
}));
}
await sendsPage.value?.reload();
} catch (error) {
msg.error(error instanceof BusinessError ? error.message : t('admin.equipmentAcceptance.syncFailed'));
} finally {
alertRunning.value = false;
}
}
/**
* 管理员从 E10 同步后刷新列表。
* 核心逻辑:成功提示写入、跳过和本次未见条数。失败展示业务错误。
*/
async function runSync(): Promise<void> {
if (syncing.value) return;
syncing.value = true;
try {
const result = await syncEquipmentAcceptance();
msg.success(t('admin.equipmentAcceptance.syncDone', {
upserted: result.upserted,
skipped: result.skipped_without_request_id,
absent: result.absent,
}));
await listPage.value?.reload();
} catch (error) {
msg.error(error instanceof BusinessError ? error.message : t('admin.equipmentAcceptance.syncFailed'));
} finally {
syncing.value = false;
}
}
</script>
<template>
<section class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-[var(--surface-muted,#f4f7fb)]">
<div class="flex flex-wrap items-center justify-between gap-2 px-5 pt-3">
<div class="min-w-0">
<h1 class="text-lg font-bold text-primary md:text-xl">{{ t('admin.equipmentAcceptance.title') }}</h1>
</div>
<div v-if="isAdmin && activeView === 'sends'" class="flex flex-wrap items-center gap-2">
<button class="btn-secondary-ds" type="button" :disabled="alertRunning" @click="pendingAlert = 'scan'">
{{ t('admin.equipmentAcceptance.scanAlerts') }}
</button>
<button class="btn-secondary-ds" type="button" :disabled="alertRunning" @click="pendingAlert = 'send'">
{{ t('admin.equipmentAcceptance.sendAlerts') }}
</button>
</div>
<button
v-if="isAdmin && activeView === 'ledger' && !detailId"
class="btn-secondary-ds"
type="button"
:disabled="syncing"
@click="runSync"
>
<RefreshCw class="h-4 w-4" aria-hidden="true" />{{ t('admin.equipmentAcceptance.sync') }}
</button>
</div>
<div class="mt-2 flex gap-0 border-b border-default px-5">
<button
v-for="tab in tabs"
:key="tab.key"
type="button"
class="mb-[-1px] border-b-2 px-3 py-2 text-sm font-bold"
:class="activeView === tab.key
? 'border-brand-500 text-brand-600'
: 'border-transparent text-muted hover:text-secondary'"
@click="selectView(tab.key)"
>
{{ tab.label }}
</button>
</div>
<EquipmentAcceptanceDetailPage
v-if="detailId"
:order-id="detailId"
@back="syncQuery('ledger', null)"
/>
<EquipmentAcceptanceConfigPage
v-else-if="activeView === 'config'"
:editable="isAdmin"
/>
<EquipmentAcceptanceSendsPage v-else-if="activeView === 'sends'" ref="sendsPage" />
<EquipmentAcceptancePage
v-else
ref="listPage"
@open-detail="syncQuery('ledger', $event)"
/>
<DeleteConfirmDialog
v-if="isAdmin"
v-model="showAlertConfirm"
:title="alertConfirmCopy.title"
:message="alertConfirmCopy.message"
confirm-tone="primary"
@confirm="confirmAlertAction"
/>
</section>
</template>
@@ -0,0 +1,331 @@
<!--
features/equipment-acceptance/views/EquipmentAcceptanceConfigPage.vue
用途:设备验收预警配置页。按升级轮次编辑天数、第 4 轮开关和三个固定岗位。
依赖:equipment-acceptance.api、UserPickerDialog、userPicker.utils、vue-i18n。
逻辑:由 Chat 作业面的「预警配置」Tab 嵌入。同一岗位在多个轮次里共用一个人。
发送时刻不在本页,由排程 Cron 配置。非管理员只能查看。
-->
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import UserPickerDialog from '@/shared/components/UserPickerDialog.vue';
import { useMessage } from '@/shared/composables/useMessage';
import { userPickerLabel } from '@/shared/utils/userPicker.utils';
import type { UserPickerPerson } from '@/shared/types/userPicker.types';
import {
getEquipmentAcceptanceConfig,
saveEquipmentAcceptanceConfig,
} from '../api/equipment-acceptance.api';
const props = defineProps<{
editable: boolean;
}>();
type RoleKey = 'buyer_manager' | 'coo' | 'executive';
type RoundLine =
| { kind: 'plain'; tag: 'ruleTo' | 'ruleCc'; text: string; note?: string }
| { kind: 'roles'; tag: 'ruleTo' | 'ruleCc'; roles: RoleKey[] };
const ROUNDS: Array<{ index: number; lines: RoundLine[] }> = [
{
index: 0,
lines: [
{ kind: 'plain', tag: 'ruleTo', text: 'ruleTo1' },
{ kind: 'plain', tag: 'ruleCc', text: 'ruleCc1', note: 'roundFixedNote' },
],
},
{
index: 1,
lines: [
{ kind: 'plain', tag: 'ruleTo', text: 'ruleTo2' },
{ kind: 'roles', tag: 'ruleCc', roles: ['coo', 'buyer_manager'] },
],
},
{
index: 2,
lines: [
{ kind: 'roles', tag: 'ruleTo', roles: ['coo'] },
{ kind: 'roles', tag: 'ruleCc', roles: ['buyer_manager'] },
],
},
{
index: 3,
lines: [
{ kind: 'roles', tag: 'ruleTo', roles: ['executive'] },
{ kind: 'roles', tag: 'ruleCc', roles: ['coo', 'buyer_manager'] },
],
},
];
const { t } = useI18n();
const msg = useMessage();
const loading = ref(false);
const saving = ref(false);
const days = ref<number[]>([30, 37, 44, 51]);
const round4Enabled = ref(false);
const roleIds = ref<Record<RoleKey, number | null>>({
buyer_manager: null,
coo: null,
executive: null,
});
const candidates = ref<UserPickerPerson[]>([]);
const knownUsers = ref<UserPickerPerson[]>([]);
const pickerOpen = ref(false);
const pickerRole = ref<RoleKey | null>(null);
const people = computed(() => {
const map = new Map<number, UserPickerPerson>();
for (const user of candidates.value) map.set(user.id, user);
for (const user of knownUsers.value) map.set(user.id, user);
return map;
});
const pickerSelectedIds = computed(() => {
const id = pickerRole.value ? roleIds.value[pickerRole.value] : null;
return id ? [id] : [];
});
/**
* 读取当前配置。管理员响应里包含候选人。
* 核心逻辑:失败时保留页面上的默认天数,并用统一错误提示。
*/
async function load(): Promise<void> {
loading.value = true;
try {
const result = await getEquipmentAcceptanceConfig();
days.value = result.days?.length === 4 ? [...result.days] : [30, 37, 44, 51];
round4Enabled.value = result.round_4_enabled === true;
roleIds.value = {
buyer_manager: result.buyer_manager_user_id ?? null,
coo: result.coo_user_id ?? null,
executive: result.executive_user_id ?? null,
};
candidates.value = result.users || [];
knownUsers.value = result.selected_users || [];
} catch (error) {
msg.error(error instanceof BusinessError ? error.message : t('admin.equipmentAcceptance.configLoadFailed'));
} finally {
loading.value = false;
}
}
/**
* 打开某个岗位的选人弹窗。每个岗位只保留最后选中的一人。
* @param role - buyer_manager、coo、executive
*/
function openPicker(role: RoleKey): void {
if (!props.editable) return;
pickerRole.value = role;
pickerOpen.value = true;
}
/**
* 把弹窗结果写回当前岗位。选了多人时只留最后一人。
* @param ids - 弹窗确定时的用户主键
*/
function applyPicker(ids: number[]): void {
const role = pickerRole.value;
if (!role) return;
roleIds.value[role] = ids[ids.length - 1] ?? null;
pickerRole.value = null;
}
/**
* 清空一个岗位,保存后表示该岗位未配置。
* @param role - 岗位键
*/
function clearRole(role: RoleKey): void {
roleIds.value[role] = null;
}
/**
* 保存天数、第 4 轮开关和三个岗位。天数须逐档增大。
* 核心逻辑:先在页面拦住空值和倒序,服务端再校验用户是否存在。
*/
async function save(): Promise<void> {
if (!props.editable || saving.value) return;
const nextDays = days.value.map((day) => Number(day));
const [first, second, third, fourth] = nextDays;
const increases = first !== undefined && second !== undefined && third !== undefined && fourth !== undefined
&& first < second && second < third && third < fourth;
if (nextDays.some((day) => !Number.isInteger(day) || day < 1) || !increases) {
msg.error(t('admin.equipmentAcceptance.configDaysInvalid'));
return;
}
saving.value = true;
try {
const result = await saveEquipmentAcceptanceConfig({
days: nextDays,
round4Enabled: round4Enabled.value,
buyerManagerUserId: roleIds.value.buyer_manager,
cooUserId: roleIds.value.coo,
executiveUserId: roleIds.value.executive,
});
days.value = [...result.days];
round4Enabled.value = result.round_4_enabled === true;
knownUsers.value = result.selected_users || [];
candidates.value = result.users || [];
msg.success(t('admin.equipmentAcceptance.configSaved'));
} catch (error) {
msg.error(error instanceof BusinessError ? error.message : t('admin.equipmentAcceptance.configSaveFailed'));
} finally {
saving.value = false;
}
}
/**
* 取出某个岗位已选的人。没有选择时为空。
* @param role - buyer_manager、coo、executive
* @returns 选人组件里的用户,或空
*/
function rolePerson(role: RoleKey): UserPickerPerson | undefined {
const id = roleIds.value[role];
if (!id) return undefined;
return people.value.get(id);
}
/**
* 芯片上的姓名。没有选择时返回空串。
* @param role - 岗位键
* @returns 展示名
*/
function roleName(role: RoleKey): string {
const person = rolePerson(role);
if (!person) return '';
return userPickerLabel(person).replace(/([^)]*)$/, '') || userPickerLabel(person);
}
/**
* 姓名首字,画在圆形头像里。
* @param role - 岗位键
* @returns 一个字符
*/
function roleInitial(role: RoleKey): string {
const name = roleName(role).trim();
return name.slice(0, 1) || '?';
}
/**
* 芯片第二行:工号和岗位名。
* @param role - 岗位键
* @returns 例如 26030025 · COO
*/
function roleMeta(role: RoleKey): string {
const person = rolePerson(role);
const roleText = t(`admin.equipmentAcceptance.role.${role}`);
const employeeId = String(person?.employee_id || person?.username || '').trim();
return employeeId ? `${employeeId} · ${roleText}` : roleText;
}
onMounted(() => {
void load();
});
</script>
<template>
<section class="min-h-0 flex-1 overflow-auto px-5 pb-6 pt-3">
<p class="mb-3 text-sm text-[#64748b]">{{ t('admin.equipmentAcceptance.configLead') }}</p>
<p v-if="loading" class="text-sm text-[#64748b]">{{ t('admin.equipmentAcceptance.loading') }}</p>
<template v-else>
<section class="overflow-hidden rounded-2xl border border-[#dce4ef] bg-white">
<div class="px-5 pb-2 pt-4">
<h2 class="text-sm font-bold text-[#142033]">{{ t('admin.equipmentAcceptance.configSheetTitle') }}</h2>
<p class="mt-1 text-xs text-[#64748b]">{{ t('admin.equipmentAcceptance.configSheetLead') }}</p>
</div>
<div class="px-3 pb-2">
<article
v-for="round in ROUNDS"
:key="round.index"
class="relative ml-4 grid grid-cols-1 gap-3 border-l-2 border-[#c9d4e3] py-4 pl-7 sm:grid-cols-[168px_minmax(0,1fr)] sm:gap-x-5"
:class="round.index === ROUNDS.length - 1 ? 'border-transparent' : ''"
>
<span class="absolute -left-[7px] top-6 h-3 w-3 rounded-full border-2 border-white bg-[#1d4e89] shadow-[0_0_0_1px_#c9d4e3]"></span>
<div class="flex flex-col gap-2">
<b class="text-xs text-[#64748b]">{{ t('admin.equipmentAcceptance.roundName', { n: round.index + 1 }) }}</b>
<label class="flex items-center gap-2 text-[13px] text-[#64748b]">
{{ t('admin.equipmentAcceptance.overPrefix') }}
<input
v-model.number="days[round.index]"
class="h-10 w-[72px] rounded-lg border border-[#d5dee8] bg-[#f8fafc] text-center text-[22px] font-semibold text-[#142033] disabled:opacity-70"
type="number"
min="1"
:disabled="!editable"
/>
{{ t('admin.equipmentAcceptance.dayUnit') }}
</label>
<template v-if="round.index === 3">
<label class="flex items-center gap-1.5 text-[13px] font-bold text-[#142033]">
<input v-model="round4Enabled" class="h-4 w-4 accent-[#1d4e89]" type="checkbox" :disabled="!editable" />
{{ t('admin.equipmentAcceptance.round4Enabled') }}
</label>
<small class="text-xs text-[#64748b]">{{ t('admin.equipmentAcceptance.round4ShortHint') }}</small>
</template>
</div>
<div class="flex flex-col gap-2" :class="round.index === 3 && !round4Enabled ? 'opacity-45' : ''">
<div v-for="(line, lineIndex) in round.lines" :key="`${round.index}-${lineIndex}`" class="flex items-start gap-2.5">
<span class="mt-1.5 w-9 shrink-0 text-xs font-bold text-[#64748b]">{{ t(`admin.equipmentAcceptance.${line.tag}`) }}</span>
<div class="min-w-0">
<template v-if="line.kind === 'plain'">
<p class="mt-1 text-sm font-semibold text-[#142033]">{{ t(`admin.equipmentAcceptance.${line.text}`) }}</p>
<p v-if="line.note" class="mt-1 text-xs text-[#94a3b8]">{{ t(`admin.equipmentAcceptance.${line.note}`) }}</p>
</template>
<div v-else class="flex flex-wrap gap-2">
<div
v-for="role in line.roles"
:key="role"
class="flex min-h-8 items-center gap-2 rounded-full bg-[#eef3f8] py-1 pl-1 pr-2"
>
<span class="grid h-6 w-6 place-items-center rounded-full bg-[#d7e4f2] text-xs font-bold text-[#1d4e89]">{{ roleInitial(role) }}</span>
<span class="flex flex-col leading-tight">
<strong class="text-[13px] text-[#142033]">{{ roleName(role) || t('admin.equipmentAcceptance.roleEmpty') }}</strong>
<span class="text-[11px] text-[#64748b]">{{ roleMeta(role) }}</span>
</span>
<button
v-if="editable"
class="text-xs font-bold text-[#1d4e89]"
type="button"
@click="openPicker(role)"
>
{{ roleIds[role] ? t('admin.equipmentAcceptance.replaceUser') : t('admin.equipmentAcceptance.selectUser') }}
</button>
<button
v-if="editable && roleIds[role]"
class="text-xs text-[#64748b]"
type="button"
@click="clearRole(role)"
>
{{ t('admin.equipmentAcceptance.clearUser') }}
</button>
</div>
</div>
</div>
</div>
</div>
</article>
</div>
<div class="flex items-center justify-between gap-4 border-t border-[#dce4ef] bg-[#fafbfd] px-5 py-3.5">
<span class="text-xs text-[#64748b]">{{ editable ? t('admin.equipmentAcceptance.configSaveHint') : t('admin.equipmentAcceptance.configReadOnly') }}</span>
<button
v-if="editable"
class="h-9 rounded-lg bg-[#1d4e89] px-4 text-[13px] font-bold text-white disabled:opacity-50"
type="button"
:disabled="saving"
@click="save"
>
{{ t('admin.equipmentAcceptance.saveConfig') }}
</button>
</div>
</section>
</template>
<UserPickerDialog
v-model="pickerOpen"
:users="candidates"
:selected-ids="pickerSelectedIds"
:title="t('admin.equipmentAcceptance.selectUser')"
:subtitle="t('admin.equipmentAcceptance.configPickOne')"
@confirm="applyPicker"
/>
</section>
</template>
@@ -0,0 +1,314 @@
<!--
features/equipment-acceptance/views/EquipmentAcceptanceDetailPage.vue
用途:一张验收单的详情卡片,展示状态徽章、停留进度、当前节点和操作人。
依赖:equipment-acceptance.api、vue-i18n、统一消息提示。
逻辑:由 Chat 作业面在选中某行后展示。操作人只显示姓名和工号。
进度条只按签核天数画到 30/37/44/51,不表示已经发送。
-->
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
getEquipmentAcceptanceOrder,
type EquipmentAcceptanceOrder,
} from '../api/equipment-acceptance.api';
const props = defineProps<{
orderId: number;
}>();
const emit = defineEmits<{
back: [];
}>();
type BadgeTone = 'red' | 'green' | 'gray';
const STOPPED_STATUSES = new Set([
'stopped_returned',
'stopped_cannot_accept',
'stopped_archived',
'stopped_force_finished',
'stopped_voided',
'stopped_revoked',
]);
const FLOW_STATUS_KEYS: Record<number, string> = {
0: 'draft',
1: 'approving',
3: 'archived',
4: 'forceFinished',
5: 'voided',
6: 'pendingSubmit',
7: 'withdrawn',
8: 'withdrawn',
99: 'withdrawn',
[-99]: 'withdrawn',
};
const REMINDER_DAYS = [30, 37, 44, 51];
const { t } = useI18n();
const msg = useMessage();
const loading = ref(false);
const order = ref<EquipmentAcceptanceOrder | null>(null);
/**
* 读取当前验收单详情。
* 核心逻辑:orderId 变化时重新请求。失败清空详情,避免上一张单残留。
*/
async function load(): Promise<void> {
loading.value = true;
try {
order.value = await getEquipmentAcceptanceOrder(props.orderId);
} catch (error) {
order.value = null;
msg.error(error instanceof BusinessError ? error.message : t('admin.equipmentAcceptance.detailLoadFailed'));
} finally {
loading.value = false;
}
}
/**
* 只取日期部分。没有值时显示横线。
* @param value - 接口时间字符串
* @returns 日期文本
*/
function dateText(value?: string | null): string {
if (!value) return '—';
return value.slice(0, 10);
}
/**
* 把 0/1 写成否/是。可以验收为空时显示未标明,退回在同步时已把空收成否。
* @param value - 标准 0 否、1 是
* @param emptyLabel - 空值文案
* @returns 展示文案
*/
function yesNo(value: number | null | undefined, emptyLabel: string): string {
if (value === 1) return t('common.yes');
if (value === 0) return t('common.no');
return emptyLabel;
}
/**
* 把流程状态原值写成名称。7、8、99、-99 都显示为撤销,字典没有的数字仍显示原值。
* @param value - flowstatus
* @returns 流程状态文案
*/
function flowText(value?: number | null): string {
if (value === undefined || value === null) return '—';
const key = FLOW_STATUS_KEYS[value];
return key ? t(`admin.equipmentAcceptance.flowStatusName.${key}`) : String(value);
}
/**
* 未开始或没有天数时显示横线,其余显示「N 天」。
* @param item - 当前验收单
* @returns 签核天数文案
*/
function dwellText(item: EquipmentAcceptanceOrder): string {
if (item.monitor_status === 'not_started' || item.dwell_days == null) return '—';
return t('admin.equipmentAcceptance.daysValue', { days: item.dwell_days });
}
/**
* 当前节点名称。没有节点时为空,模板改显示横线。
* @param item - 当前验收单
* @returns 节点名称列表
*/
function nodeNames(item: EquipmentAcceptanceOrder): string[] {
return (item.nodes || []).map((node) => node.node_name).filter((name): name is string => Boolean(name));
}
/**
* 当前处理人去重后拼成一行。
* @param item - 当前验收单
* @returns 处理人姓名
*/
function handlerNames(item: EquipmentAcceptanceOrder): string {
const names = Array.from(new Set(
(item.operators || []).map((person) => person.handler_name).filter((name): name is string => Boolean(name)),
));
return names.length ? names.join('、') : '—';
}
/**
* 与列表相同的徽章颜色。红是已逾期,绿是不再提醒,灰是未开始和未超时。
* @param item - 当前验收单
* @returns 文案和颜色
*/
function statusBadge(item: EquipmentAcceptanceOrder): { label: string; tone: BadgeTone } {
if (item.monitor_status === 'watching' && item.overdue) {
return { label: t('admin.equipmentAcceptance.badgeOverdue'), tone: 'red' };
}
if (item.monitor_status === 'watching') {
return { label: t('admin.equipmentAcceptance.badgeOnTime'), tone: 'gray' };
}
return {
label: t(`admin.equipmentAcceptance.statusLabel.${item.monitor_status}`),
tone: STOPPED_STATUSES.has(item.monitor_status) ? 'green' : 'gray',
};
}
/**
* 徽章底色。
* @param tone - 徽章颜色
* @returns Tailwind 类名
*/
function badgeClass(tone: BadgeTone): string {
if (tone === 'red') return 'bg-[#fff0ef] text-[#b42318]';
if (tone === 'green') return 'bg-[#eafaf1] text-[#067647]';
return 'bg-[#edf1f6] text-[#475569]';
}
/**
* 按签核天数在 0 到第 4 档之间画进度。没有天数时不画。
* 核心逻辑:刻度至少到 60 天,避免 51 天贴在条的尽头。
*/
const track = computed(() => {
const days = order.value?.dwell_days;
if (order.value?.monitor_status === 'not_started' || days == null) return null;
const lastMark = REMINDER_DAYS[REMINDER_DAYS.length - 1] ?? 51;
const scale = Math.max(60, lastMark + 9, days);
return {
width: `${Math.min(100, Math.round((days / scale) * 100))}%`,
marks: [0, ...REMINDER_DAYS, scale].map((day) => ({
day,
left: `${(day / scale) * 100}%`,
label: day === scale ? t('admin.equipmentAcceptance.daysValue', { days: scale }) : String(day),
})),
};
});
onMounted(() => {
void load();
});
watch(() => props.orderId, () => {
void load();
});
</script>
<template>
<section class="min-h-0 flex-1 overflow-auto px-5 pb-6 pt-3">
<button
class="mb-3 rounded-lg border border-[#dce4ef] bg-white px-3 py-1.5 text-xs font-bold text-[#142033]"
type="button"
@click="emit('back')"
>
{{ t('admin.equipmentAcceptance.back') }}
</button>
<p v-if="loading && !order" class="text-sm text-[#64748b]">{{ t('admin.equipmentAcceptance.loading') }}</p>
<article v-else-if="order" class="overflow-hidden rounded-xl border border-[#dce4ef] bg-white">
<div class="flex items-start justify-between gap-3 px-4 pt-4">
<h2 class="text-lg font-bold text-[#142033]">{{ order.acceptance_no || '—' }}</h2>
<span
class="inline-flex shrink-0 rounded-full px-2 py-0.5 text-[11px] font-extrabold"
:class="badgeClass(statusBadge(order).tone)"
>
{{ statusBadge(order).label }}
</span>
</div>
<div v-if="track" class="px-7 pt-5">
<div class="h-2 overflow-hidden rounded-full bg-[#e7edf5]">
<i class="block h-full rounded-full bg-gradient-to-r from-[#93c5fd] to-[#2563eb]" :style="{ width: track.width }"></i>
</div>
<div class="relative mt-1 h-4 text-[11px] text-[#64748b]">
<span
v-for="mark in track.marks"
:key="mark.day"
class="absolute -translate-x-1/2 whitespace-nowrap"
:style="{ left: mark.left }"
>
{{ mark.label }}
</span>
</div>
</div>
<div class="flex flex-wrap gap-1.5 px-4 pb-1 pt-4">
<span
v-for="(name, index) in nodeNames(order)"
:key="`${name}-${index}`"
class="rounded-full bg-[#dbeafe] px-2 py-1 text-[11px] font-extrabold text-[#1d4ed8]"
>
{{ name }}
</span>
<span v-if="!nodeNames(order).length" class="text-sm text-[#64748b]">—</span>
</div>
<dl class="mt-3 grid border-t border-[#dce4ef] px-4 sm:grid-cols-2">
<div class="grid grid-cols-[108px_minmax(0,1fr)] gap-2 border-b border-[#dce4ef] py-2.5 text-xs">
<dt class="font-bold text-[#64748b]">{{ t('admin.equipmentAcceptance.purchaseOrderNo') }}</dt>
<dd class="text-[#142033]">{{ order.purchase_order_no || '—' }}</dd>
</div>
<div class="grid grid-cols-[108px_minmax(0,1fr)] gap-2 border-b border-[#dce4ef] py-2.5 text-xs sm:pl-4">
<dt class="font-bold text-[#64748b]">{{ t('admin.equipmentAcceptance.applicant') }}</dt>
<dd class="text-[#142033]">{{ order.applicant_name || '—' }}</dd>
</div>
<div class="grid grid-cols-[108px_minmax(0,1fr)] gap-2 border-b border-[#dce4ef] py-2.5 text-xs">
<dt class="font-bold text-[#64748b]">{{ t('admin.equipmentAcceptance.dwellDays') }}</dt>
<dd class="text-[#142033]">{{ dwellText(order) }}</dd>
</div>
<div class="grid grid-cols-[108px_minmax(0,1fr)] gap-2 border-b border-[#dce4ef] py-2.5 text-xs sm:pl-4">
<dt class="font-bold text-[#64748b]">{{ t('admin.equipmentAcceptance.timerStart') }}</dt>
<dd class="text-[#142033]">{{ dateText(order.timer_started_at) }}</dd>
</div>
<div class="grid grid-cols-[108px_minmax(0,1fr)] gap-2 border-b border-[#dce4ef] py-2.5 text-xs sm:col-span-2">
<dt class="font-bold text-[#64748b]">{{ t('admin.equipmentAcceptance.currentHandlers') }}</dt>
<dd class="text-[#142033]">{{ handlerNames(order) }}</dd>
</div>
<div class="grid grid-cols-[108px_minmax(0,1fr)] gap-2 border-b border-[#dce4ef] py-2.5 text-xs">
<dt class="font-bold text-[#64748b]">{{ t('admin.equipmentAcceptance.canAccept') }}</dt>
<dd class="text-[#142033]">{{ yesNo(order.can_accept, t('admin.equipmentAcceptance.unspecified')) }}</dd>
</div>
<div class="grid grid-cols-[108px_minmax(0,1fr)] gap-2 border-b border-[#dce4ef] py-2.5 text-xs sm:col-span-2">
<dt class="font-bold text-[#64748b]">{{ t('admin.equipmentAcceptance.cannotAcceptNote') }}</dt>
<dd class="whitespace-pre-wrap text-[#142033]">{{ order.cannot_accept_note || '—' }}</dd>
</div>
<div class="grid grid-cols-[108px_minmax(0,1fr)] gap-2 border-b border-[#dce4ef] py-2.5 text-xs sm:pl-4">
<dt class="font-bold text-[#64748b]">{{ t('admin.equipmentAcceptance.returnFlag') }}</dt>
<dd class="text-[#142033]">{{ yesNo(order.is_returned, t('common.no')) }}</dd>
</div>
<div class="grid grid-cols-[108px_minmax(0,1fr)] gap-2 border-b border-[#dce4ef] py-2.5 text-xs">
<dt class="font-bold text-[#64748b]">{{ t('admin.equipmentAcceptance.flowStatus') }}</dt>
<dd class="text-[#142033]">{{ flowText(order.flow_status_raw) }}</dd>
</div>
<div class="grid grid-cols-[108px_minmax(0,1fr)] gap-2 border-b border-[#dce4ef] py-2.5 text-xs sm:pl-4">
<dt class="font-bold text-[#64748b]">{{ t('admin.equipmentAcceptance.finishedAt') }}</dt>
<dd class="text-[#142033]">{{ dateText(order.finished_at) }}</dd>
</div>
</dl>
<div class="px-4 pb-4 pt-4">
<h3 class="text-sm font-bold text-[#142033]">{{ t('admin.equipmentAcceptance.operators') }}</h3>
<p class="mt-1 text-xs text-[#64748b]">{{ t('admin.equipmentAcceptance.operatorsNote') }}</p>
<div class="mt-3 overflow-auto rounded-xl border border-[#dce4ef]">
<table class="w-full min-w-[640px] border-collapse text-left text-xs">
<thead class="bg-[#f8fbff] text-[#64748b]">
<tr>
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.operatorName') }}</th>
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.jobNum') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="(item, index) in order.operators"
:key="`${item.user_id}-${item.node_id}-${index}`"
class="border-t border-[#dce4ef]"
>
<td class="px-3 py-2.5 font-bold text-[#142033]">{{ item.handler_name || '—' }}</td>
<td class="px-3 py-2.5">{{ item.handler_job_num || '—' }}</td>
</tr>
<tr v-if="!order.operators.length">
<td colspan="2" class="px-3 py-6 text-center text-[#64748b]">—</td>
</tr>
</tbody>
</table>
</div>
</div>
</article>
</section>
</template>
@@ -0,0 +1,264 @@
<!--
features/equipment-acceptance/views/EquipmentAcceptancePage.vue
用途:设备验收预警停留列表,对齐原型的汇总卡、分组筛选和状态徽章。
依赖:equipment-acceptance.api、PaginationBar、统一消息提示、vue-i18n。
逻辑:由 Chat 作业面嵌入。点「查看详情」交给父级下钻。
已逾期只看接口给出的 overdue。发送结果在「发送记录」页,这里不显示第几档。
-->
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import { useMessage } from '@/shared/composables/useMessage';
import {
listEquipmentAcceptanceOrders,
type EquipmentAcceptanceOrder,
type EquipmentAcceptanceSummary,
} from '../api/equipment-acceptance.api';
const emit = defineEmits<{
'open-detail': [orderId: number];
}>();
type FocusKey = 'all' | 'watching' | 'overdue' | 'stopped' | 'not_started';
type BadgeTone = 'red' | 'green' | 'gray';
const STOPPED_STATUSES = new Set([
'stopped_returned',
'stopped_cannot_accept',
'stopped_archived',
'stopped_force_finished',
'stopped_voided',
'stopped_revoked',
]);
const filters: Array<{ key: FocusKey; label: string }> = [
{ key: 'all', label: 'filterAll' },
{ key: 'watching', label: 'filterWatching' },
{ key: 'overdue', label: 'filterOverdue' },
{ key: 'stopped', label: 'filterStopped' },
{ key: 'not_started', label: 'filterNotStarted' },
];
const { t } = useI18n();
const msg = useMessage();
const loading = ref(false);
const orders = ref<EquipmentAcceptanceOrder[]>([]);
const focus = ref<FocusKey>('all');
const page = ref(1);
const pageSize = ref(20);
const total = ref(0);
const pages = ref(1);
const summary = ref<EquipmentAcceptanceSummary>({
watching: 0,
overdue: 0,
stopped: 0,
not_started: 0,
});
/**
* 加载当前分组的验收单,并刷新全部单据的汇总数字。
* 核心逻辑:汇总不受当前筛选影响,由接口的 summary 给出。
* @param resetPage - 为 true 时回到第一页,用于更换筛选。
*/
async function load(resetPage = false): Promise<void> {
if (resetPage) page.value = 1;
loading.value = true;
try {
const result = await listEquipmentAcceptanceOrders({
focus: focus.value,
page: page.value,
pageSize: pageSize.value,
});
orders.value = result.items || [];
total.value = result.total || 0;
pages.value = result.pages || 1;
if (result.summary) summary.value = result.summary;
} catch (error) {
msg.error(error instanceof BusinessError ? error.message : t('admin.equipmentAcceptance.loadFailed'));
} finally {
loading.value = false;
}
}
/**
* 切换原型分组并回到第一页。
* @param next - all、watching、overdue、stopped、not_started
*/
function selectFocus(next: FocusKey): void {
if (focus.value === next) return;
focus.value = next;
void load(true);
}
/**
* 把节点名称拼成一格。没有节点时显示横线。
* @param order - 列表行
* @returns 节点名称
*/
function nodeNames(order: EquipmentAcceptanceOrder): string {
const names = (order.nodes || []).map((node) => node.node_name).filter((name): name is string => Boolean(name));
return names.length ? names.join('、') : '—';
}
/**
* 把当前处理人姓名去重后拼成一格。这些人不一定是未办。
* @param order - 列表行
* @returns 处理人姓名
*/
function handlerNames(order: EquipmentAcceptanceOrder): string {
const names = Array.from(new Set(
(order.operators || []).map((item) => item.handler_name).filter((name): name is string => Boolean(name)),
));
return names.length ? names.join('、') : '—';
}
/**
* 只取日期部分展示计时起点。
* @param value - 接口返回的时间字符串
* @returns 日期或横线
*/
function dateText(value?: string | null): string {
if (!value) return '—';
return value.slice(0, 10);
}
/**
* 未开始或没有天数时显示横线,其余显示「N 天」。
* @param order - 列表行
* @returns 签核天数文案
*/
function dwellText(order: EquipmentAcceptanceOrder): string {
if (order.monitor_status === 'not_started' || order.dwell_days == null) return '—';
return t('admin.equipmentAcceptance.daysValue', { days: order.dwell_days });
}
/**
* 按监控状态收成徽章。已逾期用红色,表示还要提醒。不再提醒用绿色,未开始和未超时用灰色。
* @param order - 列表行
* @returns 文案和颜色
*/
function statusBadge(order: EquipmentAcceptanceOrder): { label: string; tone: BadgeTone } {
if (order.monitor_status === 'watching' && order.overdue) {
return { label: t('admin.equipmentAcceptance.badgeOverdue'), tone: 'red' };
}
if (order.monitor_status === 'watching') {
return { label: t('admin.equipmentAcceptance.badgeOnTime'), tone: 'gray' };
}
return {
label: t(`admin.equipmentAcceptance.statusLabel.${order.monitor_status}`),
tone: STOPPED_STATUSES.has(order.monitor_status) ? 'green' : 'gray',
};
}
/**
* 徽章底色。红是已逾期,绿是不再提醒,灰是未超时、未开始和不在监控范围。
* @param tone - 徽章颜色
* @returns Tailwind 类名
*/
function badgeClass(tone: BadgeTone): string {
if (tone === 'red') return 'bg-[#fff0ef] text-[#b42318]';
if (tone === 'green') return 'bg-[#eafaf1] text-[#067647]';
return 'bg-[#edf1f6] text-[#475569]';
}
defineExpose({ reload: () => load(false) });
onMounted(() => {
void load();
});
</script>
<template>
<section class="flex min-h-0 flex-1 flex-col gap-3 px-5 pb-4 pt-3">
<div class="grid grid-cols-4 gap-3">
<article class="rounded-xl border border-[#dce4ef] bg-white px-4 py-3.5">
<b class="block text-[26px] font-bold leading-none text-[#142033]">{{ summary.watching }}</b>
<span class="mt-1 block text-xs text-[#64748b]">{{ t('admin.equipmentAcceptance.kpiWatching') }}</span>
</article>
<article class="rounded-xl border border-[#dce4ef] bg-white px-4 py-3.5">
<b class="block text-[26px] font-bold leading-none text-[#142033]">{{ summary.overdue }}</b>
<span class="mt-1 block text-xs text-[#64748b]">{{ t('admin.equipmentAcceptance.kpiOverdue') }}</span>
</article>
<article class="rounded-xl border border-[#dce4ef] bg-white px-4 py-3.5">
<b class="block text-[26px] font-bold leading-none text-[#142033]">{{ summary.stopped }}</b>
<span class="mt-1 block text-xs text-[#64748b]">{{ t('admin.equipmentAcceptance.kpiStopped') }}</span>
</article>
<article class="rounded-xl border border-[#dce4ef] bg-white px-4 py-3.5">
<b class="block text-[26px] font-bold leading-none text-[#142033]">{{ summary.not_started }}</b>
<span class="mt-1 block text-xs text-[#64748b]">{{ t('admin.equipmentAcceptance.filterNotStarted') }}</span>
</article>
</div>
<div class="flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border border-[#dce4ef] bg-white">
<div class="flex flex-wrap gap-2 p-3">
<button
v-for="item in filters"
:key="item.key"
type="button"
class="rounded-full border px-2.5 py-1 text-xs font-bold"
:class="focus === item.key
? 'border-[#bfdbfe] bg-[#eaf2ff] text-[#1d4ed8]'
: 'border-[#dce4ef] bg-white text-[#475569]'"
@click="selectFocus(item.key)"
>
{{ t(`admin.equipmentAcceptance.${item.label}`) }}
</button>
</div>
<div class="min-h-0 flex-1 overflow-auto">
<table class="min-w-[960px] w-full border-collapse text-left text-xs">
<thead class="sticky top-0 bg-[#f8fbff] text-[#64748b]">
<tr>
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.acceptanceNo') }}</th>
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.purchaseOrderNo') }}</th>
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.applicant') }}</th>
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.currentNodes') }}</th>
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.currentHandlers') }}</th>
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.timerStart') }}</th>
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.dwellDays') }}</th>
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.status') }}</th>
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="item in orders" :key="item.id" class="border-b border-[#dce4ef] hover:bg-[#f3f7ff]">
<td class="px-3 py-2.5 font-bold text-[#142033]">{{ item.acceptance_no || '—' }}</td>
<td class="px-3 py-2.5">{{ item.purchase_order_no || '—' }}</td>
<td class="px-3 py-2.5">{{ item.applicant_name || '—' }}</td>
<td class="px-3 py-2.5">{{ nodeNames(item) }}</td>
<td class="px-3 py-2.5">{{ handlerNames(item) }}</td>
<td class="px-3 py-2.5">{{ dateText(item.timer_started_at) }}</td>
<td class="px-3 py-2.5">{{ dwellText(item) }}</td>
<td class="px-3 py-2.5">
<span
class="inline-flex rounded-full px-2 py-0.5 text-[11px] font-extrabold"
:class="badgeClass(statusBadge(item).tone)"
>
{{ statusBadge(item).label }}
</span>
</td>
<td class="px-3 py-2.5">
<button class="font-extrabold text-[#175cd3]" type="button" @click="emit('open-detail', item.id)">
{{ t('admin.equipmentAcceptance.detail') }}
</button>
</td>
</tr>
<tr v-if="!loading && !orders.length">
<td colspan="9" class="px-3 py-9 text-center text-[#64748b]">{{ t('admin.equipmentAcceptance.empty') }}</td>
</tr>
</tbody>
</table>
</div>
</div>
<PaginationBar
class="shrink-0"
v-model:page="page"
v-model:page-size="pageSize"
:total="total"
:pages="pages"
@update:page="() => load()"
@update:page-size="() => load()"
/>
</section>
</template>
@@ -0,0 +1,229 @@
<!--
features/equipment-acceptance/views/EquipmentAcceptanceSendsPage.vue
用途:设备验收预警发送记录页,列出每张验收单某一档的主送、抄送、Excel 附件和结果。
依赖:equipment-acceptance.api、PaginationBar、统一消息提示、vue-i18n、lucide 图标。
逻辑:由 Chat 作业面的「发送记录」Tab 嵌入。Excel 附件列点击文件名下载。发送失败时悬停图标看原因。
-->
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { CircleAlert, Download } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import { useMessage } from '@/shared/composables/useMessage';
import { formatLocalDateTime } from '@/shared/utils/dateTime';
import {
downloadEquipmentAcceptanceSendFile,
listEquipmentAcceptanceSends,
type EquipmentAcceptanceSendRecord,
} from '../api/equipment-acceptance.api';
const { t, te } = useI18n();
const msg = useMessage();
const records = ref<EquipmentAcceptanceSendRecord[]>([]);
const downloadingId = ref<number | null>(null);
const loading = ref(false);
const page = ref(1);
const pageSize = ref(20);
const total = ref(0);
const pages = ref(1);
const failureTip = ref<{ text: string; left: number; top: number } | null>(null);
/**
* 拉取当前页发送记录。
* 核心逻辑:失败时清空表格并提示。空列表留给模板显示「还没有发送记录」。
*/
async function load(): Promise<void> {
loading.value = true;
try {
const result = await listEquipmentAcceptanceSends({ page: page.value, pageSize: pageSize.value });
records.value = result.items || [];
total.value = result.total || 0;
pages.value = Math.max(1, Math.ceil(total.value / pageSize.value));
} catch (error) {
records.value = [];
total.value = 0;
pages.value = 1;
msg.error(error instanceof BusinessError ? error.message : t('admin.equipmentAcceptance.sendsFailed'));
} finally {
loading.value = false;
}
}
/**
* 轮次列写成「超过 N 天」。
* @param item - 一条发送记录
* @returns 轮次文案
*/
function tierText(item: EquipmentAcceptanceSendRecord): string {
return t('admin.equipmentAcceptance.ruleOver', { days: item.threshold_days });
}
/**
* 结果用已知状态文案。未知状态保留原值。
* @param status - pending、sent、failed、cancelled
* @returns 结果文案
*/
function statusText(status: string): string {
const key = `admin.equipmentAcceptance.sendStatus.${status}`;
return te(key) ? t(key) : status;
}
/**
* 已发送显示本地时间,待发送没有时间时显示横线。
* @param value - 接口返回的发送时间
* @returns 时间或横线
*/
function sentText(value?: string | null): string {
if (!value) return '—';
const text = formatLocalDateTime(value);
return text === '-' ? '—' : text;
}
/**
* 在失败图标下方显示原因。用固定定位,避免被表格滚动容器裁掉。
* @param event - 悬停或聚焦事件
* @param message - 发送失败原因
*/
function openFailureTip(event: Event, message: string): void {
const target = event.currentTarget;
if (!(target instanceof HTMLElement)) return;
const rect = target.getBoundingClientRect();
const width = 280;
failureTip.value = {
text: message || t('admin.equipmentAcceptance.failureReasonEmpty'),
left: Math.max(8, Math.min(rect.left, window.innerWidth - width - 8)),
top: rect.bottom + 6,
};
}
/**
* 鼠标离开或失焦时关掉失败原因提示。
*/
function closeFailureTip(): void {
failureTip.value = null;
}
/**
* 下载一份已归档的收件人 Excel。
* 核心逻辑:接口返回当时发出的字节,由浏览器保存。
* @param file - 这一行上的 Excel 摘要
*/
async function downloadFile(file: { id: number; excel_file_name?: string | null }): Promise<void> {
if (downloadingId.value === file.id) return;
downloadingId.value = file.id;
try {
const { blob, filename } = await downloadEquipmentAcceptanceSendFile(file.id);
const objectUrl = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = objectUrl;
anchor.download = filename || file.excel_file_name || `equipment-acceptance-alert-${file.id}.xlsx`;
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
URL.revokeObjectURL(objectUrl);
} catch (error) {
msg.error(error instanceof BusinessError ? error.message : t('admin.equipmentAcceptance.excelDownloadFailed'));
} finally {
downloadingId.value = null;
}
}
onMounted(() => {
void load();
});
defineExpose({ reload: load });
</script>
<template>
<section class="flex min-h-0 flex-1 flex-col gap-3 px-5 pb-4 pt-3">
<p class="text-xs text-[#64748b]">{{ t('admin.equipmentAcceptance.sendsLead') }}</p>
<div class="flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border border-[#dce4ef] bg-white">
<div class="min-h-0 flex-1 overflow-auto">
<table class="min-w-[960px] w-full border-collapse text-left text-xs">
<thead class="sticky top-0 bg-[#f8fbff] text-[#64748b]">
<tr>
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.acceptanceNo') }}</th>
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.purchaseOrderNo') }}</th>
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.ruleTier') }}</th>
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.ruleTo') }}</th>
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.ruleCc') }}</th>
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.sendResult') }}</th>
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.excelColumn') }}</th>
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.sentAt') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="item in records" :key="item.id" class="border-b border-[#dce4ef]">
<td class="px-3 py-2.5 font-bold text-[#142033]">{{ item.acceptance_no || '—' }}</td>
<td class="px-3 py-2.5">{{ item.purchase_order_no || '—' }}</td>
<td class="px-3 py-2.5">{{ tierText(item) }}</td>
<td class="px-3 py-2.5">{{ item.to_text || '—' }}</td>
<td class="px-3 py-2.5">{{ item.cc_text || '—' }}</td>
<td class="px-3 py-2.5">
<span class="inline-flex items-center gap-1" :class="item.status === 'failed' ? 'font-bold text-[#b42318]' : ''">
{{ statusText(item.status) }}
<button
v-if="item.status === 'failed'"
class="inline-flex h-[22px] w-[22px] items-center justify-center rounded-full text-[#b42318] hover:bg-[#fff1f2]"
type="button"
:aria-label="t('admin.equipmentAcceptance.failureReasonAria')"
@mouseenter="openFailureTip($event, item.error_message || '')"
@mouseleave="closeFailureTip"
@focus="openFailureTip($event, item.error_message || '')"
@blur="closeFailureTip"
>
<CircleAlert class="h-4 w-4" />
</button>
</span>
</td>
<td class="px-3 py-2.5">
<div v-if="item.files?.length" class="flex max-w-[280px] flex-col gap-1">
<button
v-for="file in item.files"
:key="file.id"
class="inline-flex min-w-0 items-center gap-1 font-semibold text-[#2563eb] disabled:opacity-50"
type="button"
:disabled="downloadingId === file.id"
:title="t('admin.equipmentAcceptance.excelColumn')"
@click="downloadFile(file)"
>
<Download class="h-3.5 w-3.5 shrink-0" />
<span class="truncate">{{ file.excel_file_name }}</span>
</button>
</div>
<span v-else>—</span>
</td>
<td class="px-3 py-2.5">{{ sentText(item.sent_at) }}</td>
</tr>
<tr v-if="!loading && !records.length">
<td colspan="8" class="px-3 py-10 text-center text-[#64748b]">
{{ t('admin.equipmentAcceptance.sendsEmpty') }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
<PaginationBar
class="shrink-0"
v-model:page="page"
v-model:page-size="pageSize"
:total="total"
:pages="pages"
@update:page="() => load()"
@update:page-size="() => load()"
/>
<Teleport to="body">
<div
v-if="failureTip"
class="pointer-events-none fixed z-[80] max-w-[280px] whitespace-normal break-words rounded-lg bg-slate-900 px-2.5 py-1.5 text-xs leading-relaxed text-white shadow-lg"
role="tooltip"
:style="{ left: `${failureTip.left}px`, top: `${failureTip.top}px` }"
>
{{ failureTip.text }}
</div>
</Teleport>
</section>
</template>
@@ -1,16 +1,20 @@
<script setup lang="ts">
/**
* features/kb/components/DifyHealthDialog.vue
* 知识库 Dify 健康检查弹窗。
* 用途:展示知识库 Dify 连通性和本地同步计数。
* 依赖:Element Plus、kb.api 的健康检查接口。
* 逻辑:KbAdminPanel 打开本弹窗后拉取健康数据,失败时把文案交给父组件。结果用 Element 描述列表展示,不再套统计卡片。
*/
import { ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElAlert, ElButton, ElDescriptions, ElDescriptionsItem, ElDialog, ElLoading, ElTag } from 'element-plus';
import { getKbDifyHealth, type KbDifyHealth } from '../api/kb.api';
const props = defineProps<{ open: boolean }>();
const emit = defineEmits<{ close: []; error: [message: string] }>();
const { t } = useI18n();
const vLoading = ElLoading.directive;
const loading = ref(false);
const payload = ref<KbDifyHealth | null>(null);
@@ -30,54 +34,90 @@ watch(() => props.open, (open) => {
</script>
<template>
<div v-if="open" class="dialog-overlay" @click="close">
<div class="dialog-panel max-w-4xl p-6" @click.stop>
<div class="flex items-center justify-between gap-4">
<div>
<h3 class="section-title text-xl">{{ t('kbDifyHealth.title') }}</h3>
<p class="section-desc mt-1">{{ t('kbDifyHealth.subtitle') }}</p>
</div>
<div class="flex items-center gap-3">
<button type="button" class="btn-secondary btn-sm" @click="loadHealth">
{{ t('common.refresh') }}
</button>
<button type="button" class="btn-secondary btn-sm" @click="close">
{{ t('common.close') }}
</button>
</div>
</div>
<div v-if="loading" class="py-16 text-center text-sm text-muted">{{ t('kbDifyHealth.loading') }}</div>
<div v-else-if="payload" class="mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3">
<div class="dialog-stat-card">
<div class="label-field">Dify API</div>
<div class="mt-3 text-2xl font-semibold text-primary">{{ payload.api.reachable ? t('kbDifyHealth.reachable') : t('kbDifyHealth.unreachable') }}</div>
<div class="mt-2 break-all text-xs text-muted">{{ payload.dify_base_url || t('kbDifyHealth.notConfigured') }}</div>
</div>
<div class="dialog-stat-card">
<div class="label-field">{{ t('kbDifyHealth.datasetCount') }}</div>
<div class="mt-3 text-2xl font-semibold text-primary">{{ payload.api.dataset_count ?? '--' }}</div>
<div class="mt-2 text-xs text-muted">{{ t('kbDifyHealth.configured') }}{{ payload.dify_api_configured ? t('common.yes') : t('common.no') }}</div>
</div>
<div class="dialog-stat-card">
<div class="label-field">{{ t('kbDifyHealth.boundGroups') }}</div>
<div class="mt-3 text-2xl font-semibold text-primary">{{ payload.local_sync_health.dataset_bound_groups }}</div>
<div class="mt-2 text-xs text-muted">{{ t('kbDifyHealth.localSyncRecords') }}{{ payload.local_sync_health.sync_records }}</div>
</div>
<div class="dialog-stat-card">
<div class="label-field">{{ t('kbDifyHealth.syncingVersions') }}</div>
<div class="mt-3 text-2xl font-semibold text-primary">{{ payload.local_sync_health.syncing_versions }}</div>
</div>
<div class="dialog-stat-card">
<div class="label-field">{{ t('kbDifyHealth.syncedVersions') }}</div>
<div class="mt-3 text-2xl font-semibold text-primary">{{ payload.local_sync_health.synced_versions }}</div>
</div>
<div class="dialog-stat-card">
<div class="label-field">{{ t('kbDifyHealth.pendingSyncJobs') }}</div>
<div class="mt-3 text-2xl font-semibold text-primary">{{ payload.local_sync_health.pending_sync_jobs }}</div>
<div v-if="payload.api.error" class="mt-2 text-xs text-rose-500">{{ payload.api.error }}</div>
</div>
</div>
<ElDialog
:model-value="open"
:title="t('kbDifyHealth.title')"
width="680px"
align-center
append-to-body
:close-on-click-modal="false"
@update:model-value="(value) => { if (!value) close(); }"
>
<p class="section-desc">{{ t('kbDifyHealth.subtitle') }}</p>
<div v-loading="loading" class="dify-health-body">
<template v-if="payload">
<ElAlert
v-if="payload.api.error"
class="dify-health-alert"
:title="payload.api.error"
type="error"
show-icon
:closable="false"
/>
<ElDescriptions :column="1" border label-width="148px">
<ElDescriptionsItem label="Dify API">
<div class="dify-health-status">
<ElTag :type="payload.api.reachable ? 'success' : 'danger'" effect="light">
{{ payload.api.reachable ? t('kbDifyHealth.reachable') : t('kbDifyHealth.unreachable') }}
</ElTag>
<span class="hx-element-hint dify-health-url">{{ payload.dify_base_url || t('kbDifyHealth.notConfigured') }}</span>
</div>
</ElDescriptionsItem>
<ElDescriptionsItem :label="t('kbDifyHealth.datasetCount')">
{{ payload.api.dataset_count ?? '--' }}
</ElDescriptionsItem>
<ElDescriptionsItem :label="t('kbDifyHealth.configured')">
{{ payload.dify_api_configured ? t('common.yes') : t('common.no') }}
</ElDescriptionsItem>
</ElDescriptions>
<ElDescriptions class="dify-health-sync" :column="2" border label-width="148px">
<ElDescriptionsItem :label="t('kbDifyHealth.boundGroups')">
{{ payload.local_sync_health.dataset_bound_groups }}
</ElDescriptionsItem>
<ElDescriptionsItem :label="t('kbDifyHealth.localSyncRecords')">
{{ payload.local_sync_health.sync_records }}
</ElDescriptionsItem>
<ElDescriptionsItem :label="t('kbDifyHealth.syncingVersions')">
{{ payload.local_sync_health.syncing_versions }}
</ElDescriptionsItem>
<ElDescriptionsItem :label="t('kbDifyHealth.syncedVersions')">
{{ payload.local_sync_health.synced_versions }}
</ElDescriptionsItem>
<ElDescriptionsItem :label="t('kbDifyHealth.pendingSyncJobs')" :span="2">
{{ payload.local_sync_health.pending_sync_jobs }}
</ElDescriptionsItem>
</ElDescriptions>
</template>
</div>
</div>
<template #footer>
<ElButton :loading="loading" @click="loadHealth">{{ t('common.refresh') }}</ElButton>
<ElButton type="primary" @click="close">{{ t('common.close') }}</ElButton>
</template>
</ElDialog>
</template>
<style scoped>
.dify-health-body {
min-height: 8rem;
margin-top: 16px;
}
.dify-health-alert {
margin-bottom: 12px;
}
.dify-health-status {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 12px;
}
.dify-health-url {
word-break: break-all;
}
.dify-health-sync {
margin-top: 16px;
}
</style>
@@ -2,17 +2,34 @@
/**
* features/kb/components/DifySettingsDialog.vue
* 用途:提供知识库 Dify 连接及默认同步参数的查看、编辑和保存界面。
* 依赖:Vue 响应式 API、Vue I18n、kb.api 的 Dify 设置读写接口。
* 逻辑:KbAdminPanel 控制弹窗开关;本组件加载或保存设置后通过事件把结果反馈给父组件。
* 依赖:Vue 响应式 API、Element Plus、Vue I18n、kb.api 的 Dify 设置读写接口。
* 逻辑:KbAdminPanel 控制弹窗开关;本组件加载或保存设置后通过事件把结果反馈给父组件。表单按连接、检索、分段三块排,密钥默认遮挡;开关行按左标题、开关、右标题、数字四列对齐。
*/
import { reactive, ref, watch } from 'vue';
import { reactive, ref, useId, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import {
ElButton,
ElDialog,
ElForm,
ElFormItem,
ElInput,
ElInputNumber,
ElLoading,
ElOption,
ElSelect,
ElSwitch,
} from 'element-plus';
import { getKbDifySettings, updateKbDifySettings } from '../api/kb.api';
const props = defineProps<{ open: boolean }>();
const emit = defineEmits<{ close: []; saved: [message: string]; error: [message: string] }>();
const { t } = useI18n();
const vLoading = ElLoading.directive;
const rerankLabelId = useId();
const topKLabelId = useId();
const scoreSwitchLabelId = useId();
const scoreValueLabelId = useId();
const loading = ref(false);
const saving = ref(false);
@@ -108,94 +125,243 @@ watch(() => props.open, (open) => {
</script>
<template>
<div v-if="open" class="dialog-overlay" @click="close">
<div class="dialog-panel max-w-3xl max-h-[92vh] overflow-y-auto" @click.stop>
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle flex items-center justify-between gap-4">
<div>
<h3 class="section-title">{{ t('kbDifySettings.title') }}</h3>
<p class="section-desc mt-1">{{ t('kbDifySettings.subtitle') }}</p>
</div>
<button type="button" class="btn-secondary btn-sm" @click="close">
{{ t('common.close') }}
</button>
<ElDialog
:model-value="open"
width="680px"
align-center
append-to-body
:close-on-click-modal="false"
@update:model-value="(value) => { if (!value) close(); }"
>
<template #header="{ titleId, titleClass }">
<div class="dify-settings-heading">
<span :id="titleId" :class="titleClass">{{ t('kbDifySettings.title') }}</span>
<p class="dify-settings-subtitle">{{ t('kbDifySettings.subtitle') }}</p>
</div>
</template>
<div v-loading="loading" class="dify-settings-body">
<ElForm v-if="!loading" class="dify-settings-form" label-position="top" :model="form">
<section class="dify-settings-section">
<p class="dify-settings-section-title">{{ t('kbDifySettings.sections.connection') }}</p>
<div class="dify-settings-panel dify-settings-stack">
<ElFormItem :label="t('kbDifySettings.fields.baseUrl')">
<ElInput v-model="form.DIFY_API_BASE" placeholder="https://api.dify.ai/v1" />
</ElFormItem>
<ElFormItem :label="t('kbDifySettings.fields.apiKey')">
<ElInput v-model="form.DIFY_API_KEY" type="password" show-password autocomplete="off" placeholder="app-..." />
</ElFormItem>
</div>
</section>
<div v-if="loading" class="px-5 sm:px-8 py-16 text-center text-sm text-muted">{{ t('kbDifySettings.loading') }}</div>
<div v-else class="px-5 sm:px-8 py-5 grid gap-4 md:grid-cols-2">
<label class="space-y-1.5">
<span class="label-field block">{{ t('kbDifySettings.fields.baseUrl') }}</span>
<input v-model="form.DIFY_API_BASE" class="input-field text-sm" placeholder="https://api.dify.ai/v1" />
</label>
<label class="space-y-1.5">
<span class="label-field block">{{ t('kbDifySettings.fields.apiKey') }}</span>
<input v-model="form.DIFY_API_KEY" class="input-field text-sm" placeholder="app-..." />
</label>
<label class="space-y-1.5">
<span class="label-field block">{{ t('kbDifySettings.fields.permission') }}</span>
<select v-model="form.KB_DIFY_PERMISSION" class="input-field text-sm">
<option value="only_me">{{ t('kbDifySettings.options.permission.onlyMe') }}</option>
<option value="all_team_members">{{ t('kbDifySettings.options.permission.allTeamMembers') }}</option>
</select>
</label>
<label class="space-y-1.5">
<span class="label-field block">{{ t('kbDifySettings.fields.indexingTechnique') }}</span>
<select v-model="form.KB_DIFY_INDEXING_TECHNIQUE" class="input-field text-sm">
<option value="high_quality">{{ t('kbDifySettings.options.indexingTechnique.highQuality') }}</option>
<option value="economy">{{ t('kbDifySettings.options.indexingTechnique.economy') }}</option>
</select>
</label>
<label class="space-y-1.5">
<span class="label-field block">{{ t('kbDifySettings.fields.searchMethod') }}</span>
<select v-model="form.KB_DIFY_SEARCH_METHOD" class="input-field text-sm">
<option value="semantic_search">{{ t('kbDifySettings.options.searchMethod.semanticSearch') }}</option>
<option value="hybrid_search">{{ t('kbDifySettings.options.searchMethod.hybridSearch') }}</option>
<option value="full_text_search">{{ t('kbDifySettings.options.searchMethod.fullTextSearch') }}</option>
</select>
</label>
<label class="space-y-1.5">
<span class="label-field block">{{ t('kbDifySettings.fields.documentForm') }}</span>
<select v-model="form.KB_DIFY_DOC_FORM" class="input-field text-sm">
<option value="text_model">{{ t('kbDifySettings.options.documentForm.textModel') }}</option>
</select>
</label>
<label class="flex items-center gap-2 space-y-0">
<input v-model="form.KB_DIFY_RERANKING_ENABLE" type="checkbox" class="h-4 w-4" />
<span class="label-field">{{ t('kbDifySettings.fields.rerankingEnable') }}</span>
</label>
<label class="space-y-1.5">
<span class="label-field block">{{ t('kbDifySettings.fields.topK') }}</span>
<input v-model.number="form.KB_DIFY_TOP_K" type="number" min="1" max="10" step="1" class="input-field text-sm" />
</label>
<label class="flex items-center gap-2 space-y-0">
<input v-model="form.KB_DIFY_SCORE_THRESHOLD_ENABLED" type="checkbox" class="h-4 w-4" />
<span class="label-field">{{ t('kbDifySettings.fields.scoreThresholdEnabled') }}</span>
</label>
<label class="space-y-1.5">
<span class="label-field block">{{ t('kbDifySettings.fields.scoreThreshold') }}</span>
<input v-model.number="form.KB_DIFY_SCORE_THRESHOLD" type="number" min="0" max="1" step="0.01" class="input-field text-sm" :disabled="!form.KB_DIFY_SCORE_THRESHOLD_ENABLED" />
</label>
<label class="space-y-1.5">
<span class="label-field block">{{ t('kbDifySettings.fields.segmentMaxTokens') }}</span>
<input v-model.number="form.KB_DIFY_SEGMENT_MAX_TOKENS" type="number" min="1" step="1" class="input-field text-sm" />
</label>
<label class="space-y-1.5">
<span class="label-field block">{{ t('kbDifySettings.fields.segmentMaxTokensExcel') }}</span>
<input v-model.number="form.KB_DIFY_SEGMENT_MAX_TOKENS_EXCEL" type="number" min="1" step="1" class="input-field text-sm" />
</label>
<label class="space-y-1.5">
<span class="label-field block">{{ t('kbDifySettings.fields.segmentChunkOverlap') }}</span>
<input v-model.number="form.KB_DIFY_SEGMENT_CHUNK_OVERLAP" type="number" min="0" step="1" class="input-field text-sm" />
</label>
</div>
<section class="dify-settings-section">
<p class="dify-settings-section-title">{{ t('kbDifySettings.sections.retrieval') }}</p>
<div class="dify-settings-panel">
<div class="dify-settings-grid">
<ElFormItem :label="t('kbDifySettings.fields.permission')">
<ElSelect v-model="form.KB_DIFY_PERMISSION">
<ElOption value="only_me" :label="t('kbDifySettings.options.permission.onlyMe')" />
<ElOption value="all_team_members" :label="t('kbDifySettings.options.permission.allTeamMembers')" />
</ElSelect>
</ElFormItem>
<ElFormItem :label="t('kbDifySettings.fields.indexingTechnique')">
<ElSelect v-model="form.KB_DIFY_INDEXING_TECHNIQUE">
<ElOption value="high_quality" :label="t('kbDifySettings.options.indexingTechnique.highQuality')" />
<ElOption value="economy" :label="t('kbDifySettings.options.indexingTechnique.economy')" />
</ElSelect>
</ElFormItem>
<ElFormItem :label="t('kbDifySettings.fields.searchMethod')">
<ElSelect v-model="form.KB_DIFY_SEARCH_METHOD">
<ElOption value="semantic_search" :label="t('kbDifySettings.options.searchMethod.semanticSearch')" />
<ElOption value="hybrid_search" :label="t('kbDifySettings.options.searchMethod.hybridSearch')" />
<ElOption value="full_text_search" :label="t('kbDifySettings.options.searchMethod.fullTextSearch')" />
</ElSelect>
</ElFormItem>
<ElFormItem :label="t('kbDifySettings.fields.documentForm')">
<ElSelect v-model="form.KB_DIFY_DOC_FORM">
<ElOption value="text_model" :label="t('kbDifySettings.options.documentForm.textModel')" />
</ElSelect>
</ElFormItem>
</div>
<div class="admin-modal-footer">
<button type="button" class="btn-ghost" @click="close">
{{ t('common.cancel') }}
</button>
<button type="button" class="btn-primary" :disabled="saving" @click="save">
{{ saving ? t('kbDifySettings.saving') : t('kbDifySettings.save') }}
</button>
</div>
<div class="dify-settings-switch-grid">
<div class="dify-settings-switch-row">
<span :id="rerankLabelId">{{ t('kbDifySettings.fields.rerankingEnable') }}</span>
<ElSwitch v-model="form.KB_DIFY_RERANKING_ENABLE" :aria-labelledby="rerankLabelId" />
<span :id="topKLabelId">{{ t('kbDifySettings.fields.topK') }}</span>
<ElInputNumber
v-model="form.KB_DIFY_TOP_K"
:min="1"
:max="10"
:step="1"
controls-position="right"
:aria-labelledby="topKLabelId"
/>
</div>
<div class="dify-settings-switch-row">
<span :id="scoreSwitchLabelId">{{ t('kbDifySettings.fields.scoreThresholdEnabled') }}</span>
<ElSwitch v-model="form.KB_DIFY_SCORE_THRESHOLD_ENABLED" :aria-labelledby="scoreSwitchLabelId" />
<span :id="scoreValueLabelId">{{ t('kbDifySettings.fields.scoreThreshold') }}</span>
<ElInputNumber
v-model="form.KB_DIFY_SCORE_THRESHOLD"
:min="0"
:max="1"
:step="0.01"
:precision="2"
controls-position="right"
:disabled="!form.KB_DIFY_SCORE_THRESHOLD_ENABLED"
:aria-labelledby="scoreValueLabelId"
/>
</div>
</div>
</div>
</section>
<section class="dify-settings-section">
<p class="dify-settings-section-title">{{ t('kbDifySettings.sections.chunking') }}</p>
<div class="dify-settings-panel dify-settings-segments">
<ElFormItem :label="t('kbDifySettings.fields.segmentMaxTokens')">
<ElInputNumber v-model="form.KB_DIFY_SEGMENT_MAX_TOKENS" :min="1" :step="1" controls-position="right" />
<p class="dify-settings-hint">{{ t('kbDifySettings.hints.maxTokens') }}</p>
</ElFormItem>
<ElFormItem :label="t('kbDifySettings.fields.segmentMaxTokensExcel')">
<ElInputNumber v-model="form.KB_DIFY_SEGMENT_MAX_TOKENS_EXCEL" :min="1" :step="1" controls-position="right" />
<p class="dify-settings-hint">{{ t('kbDifySettings.hints.maxTokens') }}</p>
</ElFormItem>
<ElFormItem :label="t('kbDifySettings.fields.segmentChunkOverlap')">
<ElInputNumber v-model="form.KB_DIFY_SEGMENT_CHUNK_OVERLAP" :min="0" :step="1" controls-position="right" />
<p class="dify-settings-hint">{{ t('kbDifySettings.hints.tokens') }}</p>
</ElFormItem>
</div>
</section>
</ElForm>
</div>
</div>
<template #footer>
<ElButton @click="close">{{ t('common.cancel') }}</ElButton>
<ElButton type="primary" :loading="saving" @click="save">{{ t('kbDifySettings.save') }}</ElButton>
</template>
</ElDialog>
</template>
<style scoped>
.dify-settings-heading {
padding-right: 24px;
}
.dify-settings-subtitle {
margin: 4px 0 0;
color: var(--el-text-color-secondary);
font-size: var(--el-font-size-extra-small);
font-weight: 400;
line-height: 1.5;
}
.dify-settings-body {
min-height: 8rem;
}
.dify-settings-section + .dify-settings-section {
margin-top: 16px;
}
.dify-settings-section-title {
margin: 0 0 8px;
color: var(--el-text-color-primary);
font-size: var(--el-font-size-base);
font-weight: 600;
line-height: 1.4;
}
.dify-settings-panel {
padding: 16px;
border: 1px solid var(--el-border-color-lighter);
border-radius: var(--el-border-radius-base);
}
.dify-settings-stack,
.dify-settings-grid,
.dify-settings-segments {
display: grid;
gap: 12px 16px;
}
.dify-settings-grid,
.dify-settings-segments {
grid-template-columns: 1fr 1fr;
}
.dify-settings-segments {
grid-template-columns: 1fr 1fr 1fr;
}
.dify-settings-form :deep(.el-form-item) {
margin-bottom: 0;
}
.dify-settings-form :deep(.el-form-item__label) {
margin-bottom: 4px;
line-height: 1.4;
}
.dify-settings-form :deep(.el-select),
.dify-settings-stack :deep(.el-input),
.dify-settings-segments :deep(.el-input-number) {
width: 100%;
}
.dify-settings-segments :deep(.el-form-item__content) {
display: flex;
flex-direction: column;
align-items: stretch;
}
.dify-settings-hint {
margin: 4px 0 0;
color: var(--el-text-color-secondary);
font-size: var(--el-font-size-extra-small);
line-height: 1.4;
}
.dify-settings-switch-grid {
display: grid;
grid-template-columns: minmax(0, 1fr) auto max-content 8.5rem;
column-gap: 16px;
}
.dify-settings-switch-row {
display: grid;
grid-template-columns: subgrid;
grid-column: 1 / -1;
align-items: center;
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid var(--el-border-color-lighter);
color: var(--el-text-color-regular);
font-size: var(--el-font-size-base);
line-height: 1.4;
}
.dify-settings-form :deep(.el-input-number .el-input__inner) {
text-align: left;
}
.dify-settings-switch-row :deep(.el-input-number) {
width: 8.5rem;
}
@media (max-width: 640px) {
.dify-settings-grid,
.dify-settings-segments {
grid-template-columns: 1fr;
}
.dify-settings-switch-grid,
.dify-settings-switch-row {
grid-template-columns: 1fr;
row-gap: 8px;
}
.dify-settings-switch-row :deep(.el-input-number) {
width: 100%;
}
}
</style>
@@ -2,28 +2,34 @@
/**
* features/kb/components/KbAdminPanel.vue
* 知识库配置面板(治理面:分组、Dify)。
* 依赖:kb.api、DifySettingsDialog、DifyHealthDialog、DeleteConfirmDialog、Vue I18n。
* 逻辑:管理控制台加载知识库分组;分组列表在主表格过滤排序,新增/编辑通过右侧抽屉提交。
* 依赖:kb.api、Element Plus、AdminListPage、DifySettingsDialog、DifyHealthDialog、Vue I18n。
* 逻辑:管理控制台加载知识库分组。列表骨架用 AdminListPage。表头排序、文档数筛选、分页和删除确认用 Element。排序和筛选都作用在全量数据上,再分页。新增/编辑走 KbGroupDrawer。
*/
import { computed, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { CircleCheck, Plus, Search, Setting, Tools } from '@element-plus/icons-vue';
import {
Activity,
Pencil,
Plus,
RefreshCw,
Search,
Settings,
Trash2,
Wrench,
} from 'lucide-vue-next';
ElAlert,
ElButton,
ElConfigProvider,
ElInput,
ElLoading,
ElMessageBox,
ElPagination,
ElSpace,
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 { useElementProvider } from '@/features/admin/composables/useElementProvider';
import AdminListPage from '@/features/admin/components/AdminListPage.vue';
import KbGroupDrawer, { type KbGroupFormValue } from './KbGroupDrawer.vue';
import DifyHealthDialog from './DifyHealthDialog.vue';
import DifySettingsDialog from './DifySettingsDialog.vue';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import { WORKSPACE_PATHS } from '@/features/workspace/constants/routes';
import {
createKbGroup,
@@ -35,35 +41,42 @@ import {
import { formatDateTime } from '../utils/kb-display.utils';
type GroupFilterMode = 'all' | 'withDocs' | 'empty';
type GroupSortMode = 'updatedDesc' | 'updatedAsc' | 'docsDesc' | 'docsAsc' | 'nameAsc';
type GroupSortKey = 'name' | 'document_count' | 'updated_at';
const router = useRouter();
const { t } = useI18n();
const { elementLocale } = useElementProvider();
const vLoading = ElLoading.directive;
const groups = ref<KbGroup[]>([]);
const isSubmitting = ref(false);
const isDeleting = ref(false);
const isRefreshing = ref(false);
const isRefreshing = ref(true);
const editingGroupId = ref<number | null>(null);
const form = ref<KbGroupFormValue>({ name: '', description: '' });
const feedback = ref('');
const feedbackType = ref<'success' | 'error' | ''>('');
const settingsDialogOpen = ref(false);
const healthDialogOpen = ref(false);
const deleteDialogOpen = ref(false);
const drawerOpen = ref(false);
const deletingGroup = ref<KbGroup | null>(null);
const searchKeyword = ref('');
const filterMode = ref<GroupFilterMode>('all');
const sortMode = ref<GroupSortMode>('updatedDesc');
const sortKey = ref<GroupSortKey | ''>('updated_at');
const sortDir = ref<'asc' | 'desc' | ''>('desc');
const currentPage = ref(1);
const pageSize = ref(20);
const filterOptions: GroupFilterMode[] = ['all', 'withDocs', 'empty'];
const sortOptions: GroupSortMode[] = ['updatedDesc', 'updatedAsc', 'docsDesc', 'docsAsc', 'nameAsc'];
const pageSizeOptions = [10, 20, 50, 100];
const totalDocuments = computed(() => groups.value.reduce((total, group) => total + (group.document_count ?? 0), 0));
/**
* 文档数表头筛选项。
* 核心逻辑:不放「全部」;Element 筛选面板的重置会清空条件,等同于全部。
*/
const documentFilters = computed(() => [
{ text: t('kbAdmin.filters.withDocs'), value: 'withDocs' },
{ text: t('kbAdmin.filters.empty'), value: 'empty' },
]);
const filteredGroups = computed(() => {
const keyword = searchKeyword.value.trim().toLowerCase();
const matched = groups.value.filter((group) => {
@@ -77,16 +90,17 @@ const filteredGroups = computed(() => {
return matchesKeyword && matchesFilter;
});
if (!sortKey.value || !sortDir.value) return matched;
return [...matched].sort((a, b) => {
const docsA = a.document_count ?? 0;
const docsB = b.document_count ?? 0;
const updatedA = Date.parse(a.updated_at || '') || 0;
const updatedB = Date.parse(b.updated_at || '') || 0;
if (sortMode.value === 'updatedAsc') return updatedA - updatedB;
if (sortMode.value === 'docsDesc') return docsB - docsA;
if (sortMode.value === 'docsAsc') return docsA - docsB;
if (sortMode.value === 'nameAsc') return a.name.localeCompare(b.name, undefined, { numeric: true });
return updatedB - updatedA;
let result = 0;
if (sortKey.value === 'name') {
result = a.name.localeCompare(b.name, undefined, { numeric: true });
} else if (sortKey.value === 'document_count') {
result = (a.document_count ?? 0) - (b.document_count ?? 0);
} else {
result = (Date.parse(a.updated_at || '') || 0) - (Date.parse(b.updated_at || '') || 0);
}
return sortDir.value === 'asc' ? result : -result;
});
});
const pagedGroups = computed(() => {
@@ -94,19 +108,33 @@ const pagedGroups = computed(() => {
return filteredGroups.value.slice(start, start + pageSize.value);
});
/**
* 表格空状态文案。
* 核心逻辑:一个分组都没有时提示去创建;有分组但筛选后为空时提示调整条件。
*/
const tableEmptyText = computed(() => (
groups.value.length === 0 ? t('kbAdmin.groupsEmpty') : t('kbAdmin.filters.emptyResult')
));
/** 格式化分组更新时间,避免管理台表格直接暴露后端 ISO 时间字符串。 */
const formatGroupUpdatedAt = (value?: string | null) => formatDateTime(value);
/** 加载知识库治理页的分组数据,供页面初始渲染和操作后刷新复用。 */
/**
* 加载知识库治理页的分组数据,供页面初始渲染和操作后刷新复用。
* 核心逻辑:只等分组列表;失败写入页面提示,并用 finally 关掉表格加载态。
*/
const loadData = async () => {
isRefreshing.value = true;
const groupsResult = await getKbGroupsSafe();
if (groupsResult.ok) groups.value = groupsResult.data;
else {
feedback.value = groupsResult.error || t('kbAdmin.msg.loadGroupsFailed');
feedbackType.value = 'error';
try {
const groupsResult = await getKbGroupsSafe();
if (groupsResult.ok) groups.value = groupsResult.data;
else {
feedback.value = groupsResult.error || t('kbAdmin.msg.loadGroupsFailed');
feedbackType.value = 'error';
}
} finally {
isRefreshing.value = false;
}
isRefreshing.value = false;
};
/** 重置分组表单到新建状态,关闭抽屉或切换新建时清空当前编辑对象。 */
@@ -162,17 +190,27 @@ const handleSubmitGroup = async () => {
await loadData();
};
/** 打开分组删除确认弹窗,确认前不直接调用删除接口。 */
const handleDeleteGroup = (group: KbGroup) => {
deletingGroup.value = group;
deleteDialogOpen.value = true;
};
/** 确认删除当前选中的分组,并在成功后同步刷新列表与编辑表单状态。 */
const handleDeleteGroupConfirm = async () => {
if (!deletingGroup.value) return;
/**
* 确认后删除分组,并刷新列表。
* 核心逻辑:Element 确认框取消会 reject,这里直接返回,不调用删除接口。
* @param group - 待删除的分组
*/
const handleDeleteGroup = async (group: KbGroup) => {
try {
await ElMessageBox.confirm(
t('kbAdmin.deleteDialog.message', { name: group.name }),
t('kbAdmin.deleteDialog.title'),
{
type: 'warning',
confirmButtonText: t('common.deleteDialog.confirm'),
cancelButtonText: t('common.deleteDialog.cancel'),
},
);
} catch {
return;
}
isDeleting.value = true;
const result = await deleteKbGroup(deletingGroup.value.id);
const result = await deleteKbGroup(group.id);
isDeleting.value = false;
if (!result.ok) {
feedback.value = result.error || t('kbAdmin.msg.deleteFailed');
@@ -180,15 +218,46 @@ const handleDeleteGroupConfirm = async () => {
return;
}
if (editingGroupId.value === deletingGroup.value.id) closeDrawer();
if (editingGroupId.value === group.id) closeDrawer();
feedback.value = t('kbAdmin.msg.deleted');
feedbackType.value = 'success';
deleteDialogOpen.value = false;
deletingGroup.value = null;
await loadData();
};
watch([searchKeyword, filterMode, sortMode, pageSize], () => {
/**
* 按文档数表头筛选全部分组,并回到第一页。
* 核心逻辑:筛选发生在分页之前。未选或重置时显示全部;单选时只留有文档或空分组。
* @param filters - Element 按 column-key 给出的已选值
*/
function onFilterChange(filters: Record<string, string[]>): void {
const selected = filters.document_count ?? [];
if (selected.length === 1 && (selected[0] === 'withDocs' || selected[0] === 'empty')) {
filterMode.value = selected[0];
} else {
filterMode.value = 'all';
}
currentPage.value = 1;
}
/**
* 按表头把筛选后的全部分组重排,并回到第一页。
* 核心逻辑:排序发生在分页之前,所以翻页后顺序不变。第三次点击表头时 Element 清空排序,列表回到接口原顺序。
* @param payload.prop - 列字段
* @param payload.order - ascending、descending 或空
*/
function onSortChange(payload: { prop: string | null; order: string | null }): void {
const field = payload.prop;
if ((field === 'name' || field === 'document_count' || field === 'updated_at') && payload.order) {
sortKey.value = field;
sortDir.value = payload.order === 'ascending' ? 'asc' : 'desc';
} else {
sortKey.value = '';
sortDir.value = '';
}
currentPage.value = 1;
}
watch([searchKeyword, pageSize], () => {
currentPage.value = 1;
});
@@ -200,142 +269,97 @@ defineExpose({ loadData });
</script>
<template>
<div class="animate-fade-in-up">
<div class="kb-admin-header">
<div class="min-w-0 flex-1">
<h2 class="text-xl font-bold text-primary">{{ t('kbAdmin.groupsTitle') }}</h2>
<ElConfigProvider :locale="elementLocale">
<AdminListPage>
<template #title>
<h2 class="section-title">{{ t('kbAdmin.groupsTitle') }}</h2>
<p class="section-desc mt-1">{{ t('kbAdmin.groupManageSubtitle') }}</p>
</div>
<div class="flex w-full shrink-0 flex-col gap-2 sm:w-auto sm:flex-row sm:items-center sm:justify-end">
<div class="kb-admin-toolbar" role="toolbar" :aria-label="t('kbAdmin.toolbar')">
<button type="button" class="kb-admin-toolbar-btn" @click="settingsDialogOpen = true" :title="t('kbAdmin.difySettings')">
<Settings class="h-4 w-4 shrink-0" />
<span class="whitespace-nowrap">{{ t('kbAdmin.difySettings') }}</span>
</button>
<button type="button" class="kb-admin-toolbar-btn" @click="healthDialogOpen = true" :title="t('kbAdmin.healthCheck')">
<Activity class="h-4 w-4 shrink-0" />
<span class="whitespace-nowrap">{{ t('kbAdmin.healthCheck') }}</span>
</button>
<button type="button" class="kb-admin-toolbar-btn" @click="loadData" :title="t('common.refresh')">
<RefreshCw class="h-4 w-4 shrink-0" :class="{ 'animate-spin': isRefreshing }" />
<span class="whitespace-nowrap">{{ t('common.refresh') }}</span>
</button>
</div>
<button type="button" class="btn-secondary inline-flex w-full items-center justify-center gap-2 px-4 py-2.5 text-sm sm:w-auto" @click="router.push(WORKSPACE_PATHS.knowledgeBase)">
<Wrench class="h-4 w-4 shrink-0" />
<span class="whitespace-nowrap">{{ t('kbAdmin.goWorkspace') }}</span>
</button>
<button type="button" class="btn-primary inline-flex w-full items-center justify-center gap-2 px-4 py-2.5 text-sm sm:w-auto" @click="openCreateDrawer">
<Plus class="h-4 w-4 shrink-0" />
<span class="whitespace-nowrap">{{ t('kbAdmin.form.create') }}</span>
</button>
</div>
</div>
</template>
<template #actions>
<ElSpace wrap>
<ElButton :icon="Setting" @click="settingsDialogOpen = true">{{ t('kbAdmin.difySettings') }}</ElButton>
<ElButton :icon="CircleCheck" @click="healthDialogOpen = true">{{ t('kbAdmin.healthCheck') }}</ElButton>
<ElButton :icon="Tools" @click="router.push(WORKSPACE_PATHS.knowledgeBase)">{{ t('kbAdmin.goWorkspace') }}</ElButton>
<ElButton type="primary" :icon="Plus" @click="openCreateDrawer">{{ t('kbAdmin.form.create') }}</ElButton>
</ElSpace>
</template>
<template #filters>
<ElInput
v-model="searchKeyword"
clearable
class="kb-filter-search"
:prefix-icon="Search"
:placeholder="t('kbAdmin.filters.searchPlaceholder')"
/>
</template>
<div class="kb-admin-body">
<section class="admin-table-section">
<div class="admin-table-filters flex flex-col gap-4">
<div class="grid grid-cols-1 gap-3 lg:grid-cols-[minmax(16rem,1fr)_auto_minmax(11rem,14rem)] lg:items-center">
<label class="relative min-w-0">
<Search class="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted" />
<input v-model="searchKeyword" class="input-field w-full pl-9" :placeholder="t('kbAdmin.filters.searchPlaceholder')" />
</label>
<div class="inline-flex w-full overflow-hidden rounded-xl border border-default bg-surface lg:w-auto">
<button
v-for="option in filterOptions"
:key="option"
type="button"
class="min-w-0 flex-1 whitespace-nowrap px-4 py-2.5 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft hover:text-primary lg:flex-none"
:class="{ 'bg-brand-50 text-brand-700': filterMode === option }"
@click="filterMode = option"
>
{{ t(`kbAdmin.filters.${option}`) }}
</button>
</div>
<select v-model="sortMode" class="select-field w-full">
<option v-for="option in sortOptions" :key="option" :value="option">
{{ t(`kbAdmin.sort.${option}`) }}
</option>
</select>
</div>
<div class="flex flex-wrap items-center gap-3 text-xs text-muted">
<span>{{ t('kbAdmin.stats.groups', { count: groups.length }) }}</span>
<span>{{ t('kbAdmin.stats.documents', { count: totalDocuments }) }}</span>
<span>{{ t('kbAdmin.stats.visible', { count: filteredGroups.length }) }}</span>
</div>
</div>
<ElAlert
v-if="feedback"
class="kb-admin-alert"
:title="feedback"
:type="feedbackType === 'error' ? 'error' : 'success'"
show-icon
closable
@close="feedback = ''"
/>
<p v-if="feedback" class="mx-6 mt-4 rounded-xl border px-4 py-3 text-sm" :class="feedbackType === 'error' ? 'border-rose-200 bg-rose-50 text-rose-600' : 'border-emerald-200 bg-emerald-50 text-emerald-700'">
{{ feedback }}
</p>
<div v-if="groups.length === 0" class="admin-table-empty">{{ t('kbAdmin.groupsEmpty') }}</div>
<div v-else-if="filteredGroups.length === 0" class="admin-table-empty">{{ t('kbAdmin.filters.emptyResult') }}</div>
<div v-else>
<div class="admin-table-wrap hidden md:block">
<table class="admin-table table-fixed">
<thead>
<tr>
<th class="w-[20%] px-6 py-3 text-xs">{{ t('kbAdmin.table.name') }}</th>
<th class="w-[30%] px-6 py-3 text-xs">{{ t('kbAdmin.table.description') }}</th>
<th class="w-[12%] px-6 py-3 text-xs">{{ t('kbAdmin.table.documents') }}</th>
<th class="w-[26%] px-6 py-3 text-xs">{{ t('kbAdmin.table.updatedAt') }}</th>
<th class="w-[12%] px-6 py-3 text-right text-xs">{{ t('kbAdmin.table.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="group in pagedGroups" :key="group.id">
<td class="px-6 py-4 align-middle"><div class="truncate font-semibold text-primary" :title="group.name">{{ group.name }}</div></td>
<td class="px-6 py-4 align-middle text-sm text-muted">
<div class="truncate" :title="group.description || t('kbAdmin.noDescription')">
{{ group.description || t('kbAdmin.noDescription') }}
</div>
</td>
<td class="px-6 py-4 align-middle"><span class="kb-admin-badge whitespace-nowrap">{{ group.document_count ?? 0 }}</span></td>
<td class="px-6 py-4 align-middle text-sm text-muted"><div class="truncate" :title="formatGroupUpdatedAt(group.updated_at)">{{ formatGroupUpdatedAt(group.updated_at) }}</div></td>
<td class="px-6 py-4 align-middle">
<div class="flex justify-end gap-1.5">
<button type="button" class="btn-icon-ds border border-default" @click="openEditDrawer(group)" :title="t('common.edit')"><Pencil class="h-4 w-4" /></button>
<button type="button" class="btn-icon-ds border border-rose-200 text-rose-600 hover:bg-rose-50" @click="handleDeleteGroup(group)" :disabled="isDeleting" :title="t('common.delete')"><Trash2 class="h-4 w-4" /></button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="space-y-3 p-4 md:hidden">
<article v-for="group in pagedGroups" :key="group.id" class="kb-admin-card">
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<h3 class="font-semibold text-primary">{{ group.name }}</h3>
<p class="mt-1 line-clamp-2 text-sm text-muted" :title="group.description || t('kbAdmin.noDescription')">{{ group.description || t('kbAdmin.noDescription') }}</p>
</div>
<span class="kb-admin-badge">{{ group.document_count ?? 0 }}</span>
<ElTable
v-loading="isRefreshing"
class="hx-admin-table"
:data="pagedGroups"
row-key="id"
:default-sort="{ prop: 'updated_at', order: 'descending' }"
:empty-text="tableEmptyText"
@sort-change="onSortChange"
@filter-change="onFilterChange"
>
<ElTableColumn prop="name" :label="t('kbAdmin.table.name')" min-width="160" sortable="custom">
<template #default="{ row }">
<div class="truncate" :title="(row as KbGroup).name">{{ (row as KbGroup).name }}</div>
</template>
</ElTableColumn>
<ElTableColumn :label="t('kbAdmin.table.description')" min-width="220">
<template #default="{ row }">
<div class="truncate hx-element-hint" :title="(row as KbGroup).description || t('kbAdmin.noDescription')">
{{ (row as KbGroup).description || t('kbAdmin.noDescription') }}
</div>
<div class="mt-3 flex items-center justify-between gap-3">
<span class="text-xs text-muted">{{ formatGroupUpdatedAt(group.updated_at) }}</span>
<div class="flex gap-1.5">
<button type="button" class="btn-icon-ds border border-default" @click="openEditDrawer(group)" :title="t('common.edit')"><Pencil class="h-4 w-4" /></button>
<button type="button" class="btn-icon-ds border border-rose-200 text-rose-600" @click="handleDeleteGroup(group)" :title="t('common.delete')"><Trash2 class="h-4 w-4" /></button>
</div>
</div>
</article>
</div>
<div class="border-t border-default px-6 py-4">
<PaginationBar
v-model:page="currentPage"
v-model:page-size="pageSize"
:total="filteredGroups.length"
:page-size-options="pageSizeOptions"
/>
</div>
</div>
</section>
</div>
</div>
</template>
</ElTableColumn>
<ElTableColumn
prop="document_count"
column-key="document_count"
:label="t('kbAdmin.table.documents')"
width="160"
sortable="custom"
:filters="documentFilters"
:filter-multiple="false"
>
<template #default="{ row }">{{ (row as KbGroup).document_count ?? 0 }}</template>
</ElTableColumn>
<ElTableColumn prop="updated_at" :label="t('kbAdmin.table.updatedAt')" min-width="180" sortable="custom">
<template #default="{ row }">{{ formatGroupUpdatedAt((row as KbGroup).updated_at) }}</template>
</ElTableColumn>
<ElTableColumn :label="t('kbAdmin.table.actions')" width="160" align="right">
<template #default="{ row }">
<ElButton link type="primary" @click="openEditDrawer(row as KbGroup)">{{ t('common.edit') }}</ElButton>
<ElButton link type="danger" :disabled="isDeleting" @click="handleDeleteGroup(row as KbGroup)">
{{ t('common.delete') }}
</ElButton>
</template>
</ElTableColumn>
</ElTable>
<template v-if="filteredGroups.length > 0" #pagination>
<ElPagination
v-if="filteredGroups.length > 0"
v-model:current-page="currentPage"
v-model:page-size="pageSize"
:total="filteredGroups.length"
:page-sizes="pageSizeOptions"
layout="total, sizes, prev, pager, next"
background
/>
</template>
</AdminListPage>
<KbGroupDrawer
v-model:form="form"
@@ -348,5 +372,15 @@ defineExpose({ loadData });
<DifySettingsDialog :open="settingsDialogOpen" @close="settingsDialogOpen = false" @saved="(message) => { feedback = message; feedbackType = 'success'; void loadData(); }" @error="(message) => { feedback = message; feedbackType = 'error'; }" />
<DifyHealthDialog :open="healthDialogOpen" @close="healthDialogOpen = false" @error="(message) => { feedback = message; feedbackType = 'error'; }" />
<DeleteConfirmDialog v-model="deleteDialogOpen" :title="t('kbAdmin.deleteDialog.title')" :message="t('kbAdmin.deleteDialog.message', { name: deletingGroup?.name || '' })" :confirm-loading="isDeleting" @confirm="handleDeleteGroupConfirm" @cancel="() => { deleteDialogOpen = false; deletingGroup = null; }" />
</ElConfigProvider>
</template>
<style scoped>
:deep(.kb-filter-search) {
width: 16rem;
}
.kb-admin-alert {
margin: 16px 32px 0;
}
</style>
@@ -1,14 +1,16 @@
<script setup lang="ts">
/**
* features/kb/components/KbGroupDrawer.vue
* 知识库分组新建/编辑抽屉表单。
* 依赖:Vue I18n、lucide-vue-next、父级 KbAdminPanel 传入的表单状态。
* 逻辑:只负责抽屉展示、表单双向同步和提交/关闭事件;接口调用与列表刷新由父组件处理。
* 知识库分组新建/编辑弹窗。
* 依赖:Element Plus 对话框与表单、Vue I18n、父级 KbAdminPanel 传入的表单状态。
* 逻辑:只负责弹窗展示、表单双向同步和提交/关闭事件;接口调用与列表刷新由父组件处理。
* 字段只有名称和描述,用随内容增高的对话框,避免整屏抽屉留下大块空白。
*/
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { FolderPlus, X } from 'lucide-vue-next';
import { FolderAdd } from '@element-plus/icons-vue';
import { ElButton, ElDialog, ElForm, ElFormItem, ElInput } from 'element-plus';
export interface KbGroupFormValue {
name: string;
@@ -37,7 +39,11 @@ const submitText = computed(() => {
return props.mode === 'edit' ? t('kbAdmin.form.saveChanges') : t('kbAdmin.form.create');
});
/** 更新指定表单字段,并将完整表单值同步回父组件。 */
/**
* 更新指定表单字段,并将完整表单值同步回父组件。
* @param field - 要改的字段,只能是名称或描述
* @param value - 输入框当前文本
*/
const updateField = (field: keyof KbGroupFormValue, value: string) => {
emit('update:form', {
...props.form,
@@ -47,81 +53,53 @@ const updateField = (field: keyof KbGroupFormValue, value: string) => {
</script>
<template>
<Teleport to="body">
<Transition name="kb-admin-drawer">
<div v-if="open" class="fixed inset-0 z-[100] bg-overlay backdrop-blur-sm" @click.self="emit('close')">
<aside class="ml-auto flex h-full w-full max-w-[440px] flex-col border-l border-default bg-surface shadow-elevated">
<header class="flex items-start justify-between gap-4 border-b border-default px-6 py-5">
<div class="min-w-0">
<h3 class="text-lg font-semibold text-primary">{{ formTitle }}</h3>
<p class="section-desc mt-1">{{ formDescription }}</p>
</div>
<button type="button" class="btn-icon-ds shrink-0" @click="emit('close')" :title="t('common.close')">
<X class="h-5 w-5" />
</button>
</header>
<div class="flex-1 space-y-5 overflow-y-auto px-6 py-5">
<div>
<label class="label-field mb-2 block">{{ t('kbAdmin.form.groupName') }}</label>
<input
:value="form.name"
class="input-field"
:placeholder="t('kbAdmin.form.groupNamePlaceholder')"
@input="updateField('name', ($event.target as HTMLInputElement).value)"
/>
</div>
<div>
<label class="label-field mb-2 block">{{ t('kbAdmin.form.groupDesc') }}</label>
<textarea
:value="form.description"
rows="8"
class="input-field"
:placeholder="t('kbAdmin.form.groupDescPlaceholder')"
@input="updateField('description', ($event.target as HTMLTextAreaElement).value)"
/>
</div>
</div>
<footer class="flex justify-end gap-2 border-t border-default px-6 py-4">
<button type="button" class="btn-secondary inline-flex items-center gap-1.5 px-4 py-2 text-sm" @click="emit('close')">
<X class="h-4 w-4 shrink-0" />
{{ t('common.cancel') }}
</button>
<button
type="button"
class="btn-primary inline-flex items-center gap-1.5 px-5 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-60"
:disabled="submitting"
@click="emit('submit')"
>
<FolderPlus v-if="!submitting" class="h-4 w-4 shrink-0" />
{{ submitText }}
</button>
</footer>
</aside>
<ElDialog
:model-value="open"
width="480px"
align-center
append-to-body
:close-on-click-modal="!submitting"
:close-on-press-escape="!submitting"
:show-close="!submitting"
@close="emit('close')"
>
<template #header>
<div>
<h3 class="text-lg font-semibold text-primary">{{ formTitle }}</h3>
<p class="mt-1 text-sm text-muted">{{ formDescription }}</p>
</div>
</Transition>
</Teleport>
</template>
<ElForm class="kb-group-form" label-position="top" @submit.prevent="emit('submit')">
<ElFormItem :label="t('kbAdmin.form.groupName')">
<ElInput
:model-value="form.name"
:placeholder="t('kbAdmin.form.groupNamePlaceholder')"
@update:model-value="updateField('name', String($event))"
/>
</ElFormItem>
<ElFormItem :label="t('kbAdmin.form.groupDesc')">
<ElInput
:model-value="form.description"
type="textarea"
:rows="4"
:placeholder="t('kbAdmin.form.groupDescPlaceholder')"
@update:model-value="updateField('description', String($event))"
/>
</ElFormItem>
</ElForm>
<template #footer>
<ElButton :disabled="submitting" @click="emit('close')">{{ t('common.cancel') }}</ElButton>
<ElButton type="primary" :icon="FolderAdd" :loading="submitting" @click="emit('submit')">
{{ submitText }}
</ElButton>
</template>
</ElDialog>
</template>
<style scoped>
.kb-admin-drawer-enter-active,
.kb-admin-drawer-leave-active {
transition: opacity 0.18s ease;
}
.kb-admin-drawer-enter-active aside,
.kb-admin-drawer-leave-active aside {
transition: transform 0.18s ease;
}
.kb-admin-drawer-enter-from,
.kb-admin-drawer-leave-to {
opacity: 0;
}
.kb-admin-drawer-enter-from aside,
.kb-admin-drawer-leave-to aside {
transform: translateX(100%);
.kb-group-form :deep(.el-form-item:last-child) {
margin-bottom: 0;
}
</style>
@@ -0,0 +1,47 @@
/**
* features/order-delivery-reply/api/orderDeliveryReply.api.spec.ts
* 用途:锁定交期回复 JSON 写请求自行声明 Content-Type。
* 依赖:vitest、orderDeliveryReply.api。
* 逻辑:requestJson 不再为所有 body 补 application/json;漏掉该头时 Flask get_json 会把保存当成空正文。
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
const requestJson = vi.hoisted(() => vi.fn());
vi.mock('@/shared/api/client', () => ({
requestJson,
}));
import {
batchReplyOrderDelivery,
notifyOrderDeliveryBatch,
saveOrderDeliveryBatches,
} from './orderDeliveryReply.api';
describe('order delivery reply JSON writes', () => {
beforeEach(() => {
requestJson.mockReset();
requestJson.mockResolvedValue({});
});
it('sends Content-Type application/json when saving one line', async () => {
await saveOrderDeliveryBatches('SO-1', 2, [{ planned_date: '2026-10-13', qty: '1' }]);
const init = requestJson.mock.calls[0][1] as RequestInit;
// 断言:保存请求自己带 JSON 类型,不依赖公共客户端补头。
expect((init.headers as Record<string, string>)['Content-Type']).toBe('application/json');
expect(init.method).toBe('PUT');
expect(init.body).toBe(JSON.stringify({ batches: [{ planned_date: '2026-10-13', qty: '1' }] }));
});
it('sends Content-Type application/json for batch reply and batch notify', async () => {
await batchReplyOrderDelivery([]);
await notifyOrderDeliveryBatch([]);
for (const [, init] of requestJson.mock.calls as [string, RequestInit][]) {
// 断言:联合回复与批量通知同样声明 JSON 类型。
expect((init.headers as Record<string, string>)['Content-Type']).toBe('application/json');
expect(init.method).toBe('POST');
}
});
});
@@ -2,9 +2,27 @@
* 订单交期回复 API 类型与请求封装。
* 依赖:统一 requestJson(失败抛 BusinessError);后端 /api/order-delivery-reply。
* 逻辑:列表筛选分页、保存批次(单行/联合)、单行与批量通知、手动同步与最近同步状态。
* 带 JSON 正文的写请求在本文件声明 Content-Type: application/json,供 Flask get_json 解析。
* 按当前筛选导出 Excel(后端生成 xlsx,blob 触发下载)。
*/
import { requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
/**
* 组装带 JSON 正文的写请求。
* 核心逻辑:显式声明 application/json。浏览器对字符串正文默认是 text/plain,Flask get_json 会读成空对象。
* @param method - HTTP 方法
* @param payload - 将序列化为 JSON 的请求体
* @returns fetch 的 method、headers 与 body
*/
function jsonWrite(method: 'POST' | 'PUT', payload: unknown): RequestInit {
return {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
};
}
/** 已保存的交期批次(计划交期 + 数量 + 可选备注)。 */
export interface DeliveryBatch {
@@ -100,7 +118,7 @@ export const listOrderDeliveryLines = (params?: OrderDeliveryListParams) => {
return requestJson<OrderDeliveryListResponse>(`/api/order-delivery-reply/lines${suffix}`);
};
/** 保存单行交期批次(未锁定行整表替换)。 */
/** 保存单行交期批次(未锁定行整表替换)。请求头带 application/json,避免正文被 Flask 当成空对象。 */
export const saveOrderDeliveryBatches = (
orderNo: string,
lineNo: number,
@@ -108,17 +126,14 @@ export const saveOrderDeliveryBatches = (
) =>
requestJson<{ order_no: string; line_no: number; batches: DeliveryBatch[]; total_qty: string }>(
`/api/order-delivery-reply/lines/${encodeURIComponent(orderNo)}/${lineNo}/batches`,
{ method: 'PUT', body: JSON.stringify({ batches }) },
jsonWrite('PUT', { batches }),
);
/** 联合回复:对多行逐行保存批次(只保存,不通知不锁定)。 */
/** 联合回复:对多行逐行保存批次(只保存,不通知不锁定)。请求头带 application/json。 */
export const batchReplyOrderDelivery = (
items: { order_no: string; line_no: number; batches: { planned_date: string; qty: string | number; remark?: string | null }[] }[],
) =>
requestJson<BatchSummary>('/api/order-delivery-reply/batch-reply', {
method: 'POST',
body: JSON.stringify({ items }),
});
requestJson<BatchSummary>('/api/order-delivery-reply/batch-reply', jsonWrite('POST', { items }));
/** 单行发送通知业务部门(企微),成功后行级锁定。 */
export const notifyOrderDeliveryLine = (orderNo: string, lineNo: number) =>
@@ -127,12 +142,12 @@ export const notifyOrderDeliveryLine = (orderNo: string, lineNo: number) =>
{ method: 'POST' },
);
/** 批量通知勾选行;无批次/已锁定跳过,单行失败不回滚其它行。 */
/** 批量通知勾选行;无批次/已锁定跳过,单行失败不回滚其它行。请求头带 application/json。 */
export const notifyOrderDeliveryBatch = (lines: { order_no: string; line_no: number }[]) =>
requestJson<BatchSummary>('/api/order-delivery-reply/notify-batch', {
method: 'POST',
body: JSON.stringify({ lines }),
});
requestJson<BatchSummary>(
'/api/order-delivery-reply/notify-batch',
jsonWrite('POST', { lines }),
);
/** 手动触发 ERP 全量同步(范围与 07:00 排程一致)。 */
export const runOrderDeliverySync = () =>
@@ -144,3 +159,41 @@ export const runOrderDeliverySync = () =>
/** 最近一次同步运行记录;从未同步过返回 null。 */
export const getLatestOrderDeliverySync = () =>
requestJson<OrderDeliverySyncRun | null>('/api/order-delivery-reply/sync/latest');
/** 导出 Excel 查询参数(与列表筛选一致;导出全部命中行,不分页)。 */
export interface OrderDeliveryExportParams {
keyword?: string;
order_date?: string;
status?: '' | 'replied' | 'not_fully_replied';
}
/**
* 导出当前筛选下的全部订单行 Excel。
* 触发时机:工具栏「导出 Excel」按钮。后端生成 xlsx 文件流,此处 blob 触发浏览器下载,
* 文件名「订单交期回复_YYYY-MM-DD.xlsx」(日期取本地当天);失败抛 Error(HTTP 状态码)。
*/
export async function exportOrderDeliveryLines(params: OrderDeliveryExportParams): Promise<void> {
const query = new URLSearchParams();
if (params.keyword) query.set('keyword', params.keyword);
if (params.order_date) query.set('order_date', params.order_date);
if (params.status) query.set('status', params.status);
const response = await fetch(`/api/order-delivery-reply/lines/export?${query.toString()}`, {
method: 'GET',
headers: getAuthHeaders(),
});
if (!response.ok) {
throw new Error(`Export failed: HTTP ${response.status}`);
}
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
// 文件名日期取浏览器本地时区(toISOString 为 UTC,北京时间 0-8 点导出会差一天)
const now = new Date();
const localDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
link.download = `订单交期回复_${localDate}.xlsx`;
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
}
@@ -0,0 +1,171 @@
/**
* features/order-delivery-reply/views/OrderDeliveryReplyPage.chipEdit.spec.ts
* 用途:锁定「批次条就地编辑」核心契约(回归用)。
* 依赖:vitest、@vue/test-utils、vue-i18n、vue-router memory history。
* 逻辑:完整挂载工作台页(mock API/权限/消息):
* 1) 未回复行点击空批次条进入编辑态,填写日期+数量失焦 → 调用单行保存接口(整行批次);
* 2) 只填数量不填日期失焦 → 不保存且行内红字提示(batchMissingDate);
* 3) 多批次行改其中一条数量致合计≠订单数量 → 不保存且红字提示(qtyTotalMismatchLine)。
*/
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { flushPromises, mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import { createRouter, createMemoryHistory } from 'vue-router';
import OrderDeliveryReplyPage from './OrderDeliveryReplyPage.vue';
const hoisted = vi.hoisted(() => ({
listMock: vi.fn(),
saveMock: vi.fn(),
batchMock: vi.fn(),
notifyMock: vi.fn(),
syncMock: vi.fn(),
latestSyncMock: vi.fn(),
requestJsonMock: vi.fn(),
messageMocks: { info: vi.fn(), success: vi.fn(), warning: vi.fn(), error: vi.fn() },
}));
vi.mock('@/features/order-delivery-reply/api/orderDeliveryReply.api', () => ({
listOrderDeliveryLines: hoisted.listMock,
saveOrderDeliveryBatches: hoisted.saveMock,
batchReplyOrderDelivery: hoisted.batchMock,
notifyOrderDeliveryBatch: hoisted.notifyMock,
runOrderDeliverySync: hoisted.syncMock,
getLatestOrderDeliverySync: hoisted.latestSyncMock,
}));
vi.mock('@/shared/api/client', () => ({
requestJson: hoisted.requestJsonMock,
}));
vi.mock('@/shared/composables/useMessage', () => ({
useMessage: () => hoisted.messageMocks,
}));
vi.mock('@/features/auth/stores/auth.store', () => ({
useAuthStore: () => ({ hasFeaturePermission: () => true }),
}));
/** 两行样例:A 未回复(空批次,订单数量 1);B 部分回复(3 批次 30/50/20,订单数量 100)。 */
const sampleLines = [
{
id: 1,
order_no: '8301-T1',
line_no: 4,
qty: '1',
unit: 'SET',
status: 'not_replied' as const,
locked: false,
batches: [] as { seq?: number; planned_date: string; qty: string; remark?: string | null }[],
undelivered_qty: '1',
},
{
id: 2,
order_no: '8301-T2',
line_no: 1,
qty: '100',
unit: 'PCS',
status: 'partial_replied' as const,
locked: false,
batches: [
{ seq: 1, planned_date: '2026-09-04', qty: '30', remark: null },
{ seq: 2, planned_date: '2026-09-11', qty: '50', remark: null },
{ seq: 3, planned_date: '2026-09-23', qty: '20', remark: null },
],
undelivered_qty: '0',
},
];
const mountPage = async () => {
const router = createRouter({
history: createMemoryHistory(),
routes: [{ path: '/:pathMatch(.*)*', component: { template: '<div />' } }],
});
router.push('/chat/39');
await router.isReady();
const i18n = createI18n({ legacy: false, locale: 'zh-CN', messages: { 'zh-CN': {} } });
const wrapper = mount(OrderDeliveryReplyPage, {
global: {
plugins: [router, i18n],
stubs: { PaginationBar: true, DeleteConfirmDialog: true },
},
});
await flushPromises();
return wrapper;
};
describe('OrderDeliveryReplyPage 批次条就地编辑', () => {
beforeEach(() => {
vi.clearAllMocks();
hoisted.listMock.mockResolvedValue({ items: sampleLines, page: 1, page_size: 50, total: 2 });
hoisted.latestSyncMock.mockResolvedValue(null);
hoisted.saveMock.mockResolvedValue({ order_no: '8301-T1', line_no: 4, batches: [], total_qty: '1' });
hoisted.requestJsonMock.mockResolvedValue(undefined);
});
it('未回复行:点击空批次条进入编辑,填写日期+数量失焦后调用单行保存', async () => {
const wrapper = await mountPage();
// 未回复行(8301-T1:4)的可编辑空批次条:title 为 replyAction 键(i18n 缺失时回退键名)
const emptyChip = wrapper.find('div[title="workspace.orderDeliveryReply.replyAction"]');
expect(emptyChip.exists()).toBe(true);
await emptyChip.trigger('click');
await flushPromises();
// 编辑态输入条出现(data-chip-edit),自动聚焦日期框
const editor = wrapper.find('[data-chip-edit]');
expect(editor.exists()).toBe(true);
const dateInput = editor.find('[data-chip-date]');
expect((dateInput.element as HTMLInputElement).value).toBe('');
// 填写日期 + 数量后失焦提交
await dateInput.setValue('2026-10-20');
await editor.find('input[type="number"]').setValue('1');
await editor.trigger('focusout');
await flushPromises();
expect(hoisted.saveMock).toHaveBeenCalledTimes(1);
expect(hoisted.saveMock).toHaveBeenCalledWith('8301-T1', 4, [
{ planned_date: '2026-10-20', qty: '1', remark: null },
]);
});
it('未回复行:只填数量不填日期失焦 → 不保存且红字提示缺交期', async () => {
const wrapper = await mountPage();
const emptyChip = wrapper.find('div[title="workspace.orderDeliveryReply.replyAction"]');
await emptyChip.trigger('click');
await flushPromises();
const editor = wrapper.find('[data-chip-edit]');
await editor.find('input[type="number"]').setValue('1');
await editor.trigger('focusout');
await flushPromises();
expect(hoisted.saveMock).not.toHaveBeenCalled();
const hint = wrapper.find('p.text-status-error');
expect(hint.exists()).toBe(true);
expect(hint.text()).toContain('batchMissingDate');
});
it('多批次行:改第 2 条数量致合计≠订单数量失焦 → 不保存且红字提示', async () => {
const wrapper = await mountPage();
// B 行(8301-T2:1)首条批次条:title 为 editReplyAction 键
const chips = wrapper.findAll('div[title="workspace.orderDeliveryReply.editReplyAction"]');
expect(chips.length).toBeGreaterThanOrEqual(1);
await chips[0].trigger('click');
await flushPromises();
const editor = wrapper.find('[data-chip-edit]');
// 预填首条批次当前值
expect((editor.find('[data-chip-date]').element as HTMLInputElement).value).toBe('2026-09-04');
// 只改数量为 60 → 30→60 后合计 130 ≠ 100
await editor.find('input[type="number"]').setValue('60');
await editor.trigger('focusout');
await flushPromises();
expect(hoisted.saveMock).not.toHaveBeenCalled();
const hint = wrapper.find('p.text-status-error');
expect(hint.exists()).toBe(true);
expect(hint.text()).toContain('qtyTotalMismatchLine');
});
});
@@ -1,7 +1,8 @@
/**
* features/order-delivery-reply/views/OrderDeliveryReplyPage.vue
* 用途:订单交期回复工作台操作页——筛选分页、单行/联合回复批次、单行/批量通知、手动同步。
* 依赖:api/orderDeliveryReply.api(统一 requestJson)、useMessage、auth store(manage/access 权限)。
* 依赖:api/orderDeliveryReply.api(统一 requestJson)、useMessage、auth store(manage/access 权限)、
* shared DeleteConfirmDialog(批量通知二次确认)、PaginationBar。
* 逻辑:所有数据只读本地快照;保存与通知是两步(联合回复只保存,批量通知才发送并锁定);
* 保存/通知成功后即时刷新列表(需求 §9);仅 access 用户隐藏全部写操作。
* 回复弹窗数量守恒(2026-09-23 由「超额仅提醒」修订):每行各批次合计必须等于订单数量
@@ -10,10 +11,30 @@
* wecom_trace 上报打开回执——保证「点卡片 → 登录 → 直达该 Agent 对应内容与位置」。
* 列顺序:客户编号(简称副文案) → 订单日期 → 订单单号:项次 → 产品编号(品名副文案) →
* 客户产品编号 → 数量 → 约定交货日 → 交期回复状态 → 交期回复 → 交期回复人员 →
* 业务员(部门副文案) → 客户订单 → 规格 → 单位;独立的部门列/品名列已并入合并展示。
* 业务员(部门副文案) → 客户订单 → 规格 → 单位 → 通知时间(2026-10-09 自交期回复人员列拆出);
* 独立的部门列/品名列已并入合并展示。
* 浏览体验:页面高度收敛至视口(滚动全部发生在表格容器内 → 列头 sticky 固定、横向滚动条
* 常驻表格底缘);左侧冻结前四列标识区(勾选/客户编号/订单日期/订单单号:项次,
* 冻结单元格用实色背景防透出);筛选区与工具栏字号与表格统一(text-sm 14px)并压缩高度。
* 冻结单元格用 utilities.css 的 frozen-cell 实色基底防透出,并随行悬停/选中/直达高亮联动);
* 筛选区无外置字段标签(提示字占位已取消,含义由 placeholder/选项承担,aria-label 保留无障碍语义),
* 输入框/按钮显式 text-sm + h-9(36px),与合同付款预警 .contract-filter-input/.contract-filter-submit
* (14px/600/36px/圆角8px)渲染规格逐项一致。
* 交期回复列批次交互(2026-10-09):动作入口统一为批次条前的加号(lucide Plus,title/aria 复用
* replyAction/editReplyAction 键)——未回复=空批次条(不显示时间/数量)+ 加号回复;
* 已回复/部分回复=加号修改回复(仅未锁定可管理);「交期已锁定」徽标已取消(锁定状态由
* 无加号与交期回复人员列「已通知」体现)。全表批次条左缘对齐:所有行首条批次前保留
* w-6 加号占位,展开行其余批次条加 pl-7 缩进;>1 批时首条批次后保留展开/收起小箭头
* (▼ 全部 / ▲ 收起只留第一批)。
* 批次条就地编辑(2026-10-09):未锁定可管理行点击批次条原地变「日期+数量」输入(预填当前值;
* 未回复行空批次条点击=新增第一条批次),输入条渲染后自动聚焦日期框;回车/失焦自动保存单行
* 接口(整行批次提交,与弹窗保存同口径校验);校验失败红字持续显示并重聚焦日期框,直至修正
* 保存或 Esc 取消;双清空=放弃编辑;批次条不显示备注内容;多批次/备注仍走加号弹窗。
* 表格对齐(2026-10-09):除交期回复列(批次条按既定左对齐布局)外,全列内容水平居中、
* 行内容垂直居中,列头文字全部居中;交期回复状态徽标统一等宽(min-w-68px)。
* 设计系统(docs/ui/DESIGN_SYSTEM.md):根节点挂 page-shell;区块容器用 surface-panel;
* 弹窗用 dialog-overlay/panel/header/body/footer;输入用 input-field/select-field;
* 状态与交互色一律走 --status-* 令牌(badge-*/bg-row-*/frozen-cell-*),品牌强调用 brand-*。
* 批量通知确认使用共享 DeleteConfirmDialog(confirmTone=primary),不再用原生 window.confirm。
*/
<script setup lang="ts">
@@ -24,11 +45,14 @@ import { useAuthStore } from '@/features/auth/stores/auth.store';
import { useMessage } from '@/shared/composables/useMessage';
import { requestJson } from '@/shared/api/client';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import { ChevronDown, ChevronUp, Download, Plus } from 'lucide-vue-next';
import {
ORDER_DELIVERY_REPLY_MANAGE_PERMISSION,
} from '@/features/order-delivery-reply/constants';
import {
batchReplyOrderDelivery,
exportOrderDeliveryLines,
getLatestOrderDeliverySync,
listOrderDeliveryLines,
notifyOrderDeliveryBatch,
@@ -158,15 +182,13 @@ function toggleExpand(key: string) {
}
/* ============ 派生展示 ============ */
const repliedQty = (line: OrderDeliveryLine) =>
line.batches.reduce((sum, batch) => sum + Number(batch.qty || 0), 0);
const undelivered = (line: OrderDeliveryLine) => Number(line.undelivered_qty || 0);
type LineStatus = OrderDeliveryLine['status'];
/** 状态徽章:颜色走 badge-success/warning/error(--status-* 令牌,亮暗自适应)。 */
const statusMeta = (status: LineStatus) => {
const map: Record<LineStatus, { label: string; cls: string }> = {
not_replied: { label: t('workspace.orderDeliveryReply.statusNotReplied'), cls: 'bg-rose-50 text-rose-600' },
partial_replied: { label: t('workspace.orderDeliveryReply.statusPartial'), cls: 'bg-orange-50 text-orange-600' },
replied: { label: t('workspace.orderDeliveryReply.statusReplied'), cls: 'bg-emerald-50 text-emerald-600' },
not_replied: { label: t('workspace.orderDeliveryReply.statusNotReplied'), cls: 'badge-error' },
partial_replied: { label: t('workspace.orderDeliveryReply.statusPartial'), cls: 'badge-warning' },
replied: { label: t('workspace.orderDeliveryReply.statusReplied'), cls: 'badge-success' },
};
return map[status];
};
@@ -184,6 +206,7 @@ const quickDate = ref('');
const saving = ref(false);
function openReplyModal(lines: OrderDeliveryLine[], title: string, mode: 'single' | 'batch') {
cancelChipEdit(); // 打开弹窗前退出批次条就地编辑,避免弹窗与行内编辑态叠加
modalLines.value = lines.map((line) => ({
line,
batches: line.batches.map((batch) => ({
@@ -203,10 +226,12 @@ function openReplyModal(lines: OrderDeliveryLine[], title: string, mode: 'single
}
function openSingleReply(line: OrderDeliveryLine) {
if (chipSaving.value) return; // 保存进行中禁止开弹窗:弹窗按旧批次数据提交会覆盖刚保存的编辑
openReplyModal([line], t('workspace.orderDeliveryReply.modalTitleSingle', { order: line.order_no, item: line.line_no }), 'single');
}
function openBatchReply() {
if (chipSaving.value) return;
const lines = selectedLines.value.filter((line) => !line.locked);
if (!lines.length) return;
openReplyModal(lines, t('workspace.orderDeliveryReply.modalTitleBatch', { count: lines.length }), 'batch');
@@ -316,15 +341,153 @@ async function saveReplies() {
}
}
/* ============ 批次条就地编辑(2026-10-09) ============ */
// 未锁定且可管理的行:点击批次条原地变「日期+数量」输入,回车/失焦自动保存单行接口;
// 校验与弹窗同口径(lineIssueText:缺交期/缺数量、同单交期重复、合计≠订单数量),红字阻断保存;
// 双清空=放弃编辑(行内不提供删除,结构调整/备注/多批次走加号弹窗)。
const editingChip = ref<{ key: string; idx: number } | null>(null);
const chipDraft = reactive({ planned_date: '', qty: '' });
const chipIssue = ref('');
// 单行保存进行中标志:整行提交语义下,禁止并发(再点其他批次条/开弹窗),
// 否则两个 in-flight 保存或「弹窗基于旧批次数据」会互相覆盖丢编辑
const chipSaving = ref(false);
const isChipEditable = (line: OrderDeliveryLine) => canManage.value && !line.locked;
const isChipEditing = (line: OrderDeliveryLine, idx: number) =>
editingChip.value?.key === lineKey(line) && editingChip.value?.idx === idx;
function startChipEdit(line: OrderDeliveryLine, idx: number) {
if (!isChipEditable(line) || chipSaving.value) return;
// 未回复行批次列表为空:idx=0 表示「新增第一条批次」,同样可进入编辑
if (line.batches.length > 0 && idx >= line.batches.length) return;
const batch = line.batches[idx];
editingChip.value = { key: lineKey(line), idx };
chipDraft.planned_date = batch?.planned_date ?? '';
chipDraft.qty = batch ? String(Number(batch.qty)) : '';
chipIssue.value = '';
// 输入条渲染后自动聚焦日期框,点击即可填
void nextTick(() => {
document.querySelector<HTMLInputElement>('[data-chip-edit] [data-chip-date]')?.focus();
});
}
function cancelChipEdit() {
editingChip.value = null;
chipIssue.value = '';
}
/** 失焦提交:relatedTarget 仍在输入条内(日期↔数量切换)时不提交。 */
function onChipFocusout(event: FocusEvent, line: OrderDeliveryLine, idx: number) {
const next = event.relatedTarget as Node | null;
if (next && (event.currentTarget as HTMLElement).contains(next)) return;
chipCommit(line, idx);
}
function chipCommit(line: OrderDeliveryLine, idx: number) {
if (!isChipEditing(line, idx) || chipSaving.value) return;
// 注意:v-model 在 type="number" 输入框上会自动把值转成 number,
// 这里必须统一 String() 容错,否则 qty.trim() 抛 TypeError 中断整个失焦提交
const date = String(chipDraft.planned_date ?? '').trim();
const qty = String(chipDraft.qty ?? '').trim();
// 双清空=放弃编辑;只填其一致「缺交期/缺数量」红字,保持编辑态
if (!date && !(qty !== '' && Number(qty) > 0)) {
cancelChipEdit();
return;
}
// 整行批次合并提交,与弹窗保存完全同口径:
// 编辑已有批次=仅替换该条;未回复行空批次条=新增第一条(line.batches 为空数组)
const source = line.batches[idx];
const edited: EditableBatch = { planned_date: date, qty, remark: source?.remark || '' };
const merged: EditableBatch[] =
idx < line.batches.length
? line.batches.map((b, i) =>
i === idx ? edited : { planned_date: b.planned_date, qty: String(Number(b.qty)), remark: b.remark || '' },
)
: [edited];
const issue = lineIssueText({ line, batches: merged });
if (issue) {
chipIssue.value = issue;
// 校验失败:保持编辑态并重新聚焦日期框,红字提示持续可见,直至修正保存或 Esc 取消
void nextTick(() => {
document.querySelector<HTMLInputElement>('[data-chip-edit] [data-chip-date]')?.focus();
});
return;
}
const cleaned = merged
.filter((b) => b.planned_date && Number(b.qty) > 0)
.map((b) => ({ planned_date: b.planned_date, qty: b.qty, remark: b.remark.trim() || null }));
if (!cleaned.length) {
cancelChipEdit();
return;
}
void saveChipEdit(line, idx, cleaned);
}
async function saveChipEdit(
line: OrderDeliveryLine,
idx: number,
cleaned: { planned_date: string; qty: string; remark: string | null }[],
) {
const target = { key: lineKey(line), idx };
chipSaving.value = true;
try {
await saveOrderDeliveryBatches(line.order_no, line.line_no, cleaned);
msg.success(t('workspace.orderDeliveryReply.saveSingleDone'));
// 仅当用户未切去编辑其他批次条时才退出编辑态
if (editingChip.value?.key === target.key && editingChip.value?.idx === target.idx) {
cancelChipEdit();
}
await loadLines();
// loadLines 重建行 DOM:若用户已切去编辑其他批次条,重聚焦其日期框,
// 否则焦点丢失后后续「失焦提交」永远不会触发(表现为填了不保存)
if (editingChip.value) {
void nextTick(() => {
document.querySelector<HTMLInputElement>('[data-chip-edit] [data-chip-date]')?.focus();
});
}
} catch (error) {
msg.error(error instanceof Error ? error.message : t('workspace.orderDeliveryReply.saveFailedTitle'));
const message = error instanceof Error ? error.message : '';
if (message.includes('LINE_NOT_FOUND') || message.includes('不在同步范围') || message.includes('not found')) {
editingChip.value = null;
chipIssue.value = '';
await loadLines();
}
} finally {
chipSaving.value = false;
}
}
/* ============ 导出 Excel(2026-10-09) ============ */
const exporting = ref(false);
/** 按当前筛选(appliedFilters)导出全部命中行;后端生成 xlsx,前端 blob 触发下载。 */
async function doExportExcel() {
exporting.value = true;
try {
await exportOrderDeliveryLines({ ...appliedFilters });
msg.success(t('workspace.orderDeliveryReply.exportDone'));
} catch (error) {
msg.error(error instanceof Error ? error.message : t('workspace.orderDeliveryReply.exportFailed'));
} finally {
exporting.value = false;
}
}
/* ============ 通知 ============ */
const notifying = ref(false);
const notifyConfirmVisible = ref(false);
/** 批量通知入口:先弹共享 DeleteConfirmDialog(primary 语气)二次确认,确认后执行 doNotifyBatch。 */
function requestNotifyBatch() {
if (!notifiableSelected.value.length) return;
notifyConfirmVisible.value = true;
}
/** 批量通知:部分成功 warning 汇总,全部失败 error;提示后刷新列表让锁定即时生效。 */
async function doNotifyBatch() {
const lines = notifiableSelected.value;
if (!lines.length) return;
const ok = window.confirm(t('workspace.orderDeliveryReply.notifyBatchConfirm', { count: lines.length }));
if (!ok) return;
notifying.value = true;
try {
const summary = await notifyOrderDeliveryBatch(lines.map((line) => ({ order_no: line.order_no, line_no: line.line_no })));
@@ -373,15 +536,16 @@ function clearHighlight() {
}
const isLineHighlighted = (line: OrderDeliveryLine) => highlightKey.value === lineKey(line);
const rowCls = (line: OrderDeliveryLine) =>
isLineHighlighted(line) ? 'bg-amber-50' : selected.value.includes(lineKey(line)) ? 'bg-blue-50/60' : '';
/** 冻结单元格必须实色背景(防透出滚动内容),且与整行高亮/勾选色联动;高亮优先于勾选。 */
const frozenCellCls = (line: OrderDeliveryLine) =>
isLineHighlighted(line)
? 'bg-amber-100 group-hover:bg-amber-200'
: selected.value.includes(lineKey(line))
? 'bg-blue-100 group-hover:bg-blue-200'
: 'bg-white group-hover:bg-slate-100';
/** 行交互态:直达高亮(warning)优先于勾选选中(info),均走状态令牌(亮暗自适应)。 */
const rowCls = (line: OrderDeliveryLine) => {
if (isLineHighlighted(line)) return 'bg-row-highlight';
return selected.value.includes(lineKey(line)) ? 'bg-row-selected' : '';
};
/** 冻结单元格用 utilities.css 的 frozen-cell(实色基底防透出滚动内容),状态与整行联动;高亮优先于勾选。 */
const frozenCellCls = (line: OrderDeliveryLine) => {
if (isLineHighlighted(line)) return 'frozen-cell frozen-cell--highlight';
return selected.value.includes(lineKey(line)) ? 'frozen-cell frozen-cell--selected' : 'frozen-cell';
};
/** 列表就绪后定位目标行:滚动到视口中央 + 高亮 8 秒;行不在当前筛选结果中时静默跳过。 */
async function focusTargetLine(orderNo: string, lineNo: number) {
@@ -395,11 +559,12 @@ async function focusTargetLine(orderNo: string, lineNo: number) {
highlightTimer = setTimeout(clearHighlight, 8000);
}
/** 上报企微卡片打开回执(WecomNotifyAudit.opened_at);仅留痕,失败不影响页面使用。 */
/** 上报企微卡片打开回执(WecomNotifyAudit.opened_at);仅留痕,失败不影响页面使用。请求头带 application/json,后端 get_json 才读得到 trace_id。 */
async function reportWecomTraceOpened(traceId: string) {
try {
await requestJson('/api/user/wecom/deeplink-opened', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ trace_id: traceId }),
});
} catch {
@@ -429,15 +594,17 @@ onMounted(async () => {
</script>
<template>
<!-- 全页统一字号:与表头一致(text-sm 14px),根容器设定基准,子元素不再覆写;
唯一例外:交期回复状态/交期已锁定徽标保持 text-xs(12px)加粗 -->
<!-- 高度收敛至视口(h-screen + overflow-hidden):页面自身不滚动,滚动全部在表格容器内,
列头 sticky 固定、横向滚动条常驻表格底缘;聊天壳 iframe 与独立路由均适用 -->
<div class="flex h-screen flex-col gap-4 overflow-hidden p-6 text-sm">
<!-- 全页基准字号:text-sm 14px(表头/筛选区/工具栏/表格统一),子元素按需覆写;
例外:页头标题 text-lg→md:text-xl(18/20px,与合同付款预警页头对齐)、徽章类 badge 基类自带 text-xs(12px)
高度收敛至视口(h-screen + overflow-hidden):页面自身不滚动,滚动全部在表格容器内,
列头 sticky 固定、横向滚动条常驻表格底缘;聊天壳 iframe 与独立路由均适用。
page-shell:iframe 嵌入路由无外层布局壳,由本页根节点补齐 L1 页面底色与前景色 -->
<div class="page-shell flex h-screen flex-col gap-4 overflow-hidden p-6 text-sm">
<!-- 页头:标题 + 最近同步 + 手动刷新 -->
<div class="flex flex-wrap items-center gap-3">
<h1 class="font-bold text-primary">{{ t('workspace.nav.orderDeliveryReply') }}</h1>
<span class="rounded-full px-3 py-1" :class="latestSyncFailed ? 'bg-rose-50 text-rose-600' : 'bg-blue-50 text-blue-600'">
<!-- 页头标题字号与合同付款预警页头一致:小屏 text-lg 18px、≥768px md:text-xl 20px -->
<h1 class="text-lg font-bold text-primary md:text-xl">{{ t('workspace.nav.orderDeliveryReply') }}</h1>
<span class="badge whitespace-nowrap" :class="latestSyncFailed ? 'badge-error' : 'badge-info'">
{{ latestSyncText }}
</span>
<div class="flex-1" />
@@ -446,72 +613,70 @@ onMounted(async () => {
</button>
</div>
<!-- 搜索区:合并关键词搜索(订单/产品/客户命中任一字段),字号与表格统一(text-sm),shrink-0 防压缩 -->
<div class="flex shrink-0 flex-wrap items-end gap-3 rounded-2xl border border-default bg-surface px-4 py-2.5">
<label class="flex flex-col gap-1 text-muted">
{{ t('workspace.orderDeliveryReply.filterKeyword') }}
<input v-model="filters.keyword" class="h-8 min-w-[340px] rounded-lg border border-default px-3 text-primary outline-none focus:border-blue-500" :placeholder="t('workspace.orderDeliveryReply.filterKeywordPh')" @keyup.enter="doSearch" />
</label>
<label class="flex flex-col gap-1 text-muted">
{{ t('workspace.orderDeliveryReply.filterOrderDate') }}
<input v-model="filters.order_date" type="date" class="h-8 rounded-lg border border-default px-3 text-primary outline-none focus:border-blue-500" />
</label>
<label class="flex flex-col gap-1 text-muted">
{{ t('workspace.orderDeliveryReply.filterStatus') }}
<!-- 状态筛选选择即生效(无需再点查询);其余条件仍由「查询」统一提交 -->
<select v-model="filters.status" class="min-w-[140px] rounded-lg border border-default bg-white px-3 py-[5px] text-sm leading-5 text-primary outline-none focus:border-blue-500" @change="doSearch">
<option value="">{{ t('workspace.orderDeliveryReply.statusAll') }}</option>
<option value="replied">{{ t('workspace.orderDeliveryReply.statusReplied') }}</option>
<option value="not_fully_replied">{{ t('workspace.orderDeliveryReply.statusNotFully') }}</option>
</select>
</label>
<button type="button" class="btn-primary h-8" @click="doSearch">{{ t('workspace.orderDeliveryReply.search') }}</button>
<button type="button" class="btn-ghost h-8" @click="doReset">{{ t('workspace.orderDeliveryReply.reset') }}</button>
<div class="flex-1" />
<span class="text-muted">{{ t('workspace.orderDeliveryReply.totalCount', { count: total }) }}</span>
<!-- 搜索区:合并关键词搜索(订单/产品/客户命中任一字段),shrink-0 防压缩;surface-panel 为设计系统 L2 区块容器(无 hover 阴影)。
外置字段标签已取消(2026-10-09:去掉提示字及其占位,单行紧凑布局与合同付款预警筛选一致):
字段含义由输入框 placeholder / 选项承担,无障碍语义用 aria-label 保留(复用 filterKeyword 等 i18n 键)。
输入控件显式 text-sm(14px)+h-9(36px):与 .contract-filter-input(14px/36px/圆角8px)渲染规格逐项一致 -->
<div class="surface-panel flex shrink-0 flex-wrap items-center gap-3 px-4 py-2.5">
<input v-model="filters.keyword" class="input-field h-9 w-auto min-w-[340px] rounded-lg px-3 py-1 text-sm" :placeholder="t('workspace.orderDeliveryReply.filterKeywordPh')" :aria-label="t('workspace.orderDeliveryReply.filterKeyword')" @keyup.enter="doSearch" />
<input v-model="filters.order_date" type="date" class="input-field h-9 w-auto rounded-lg px-3 py-1 text-sm" :aria-label="t('workspace.orderDeliveryReply.filterOrderDate')" />
<!-- 状态筛选选择即生效(无需再点查询);其余条件仍由「查询」统一提交 -->
<select v-model="filters.status" class="select-field h-9 w-auto min-w-[140px] rounded-lg px-3 py-1 text-sm" :aria-label="t('workspace.orderDeliveryReply.filterStatus')" @change="doSearch">
<option value="">{{ t('workspace.orderDeliveryReply.statusAll') }}</option>
<option value="replied">{{ t('workspace.orderDeliveryReply.statusReplied') }}</option>
<option value="not_fully_replied">{{ t('workspace.orderDeliveryReply.statusNotFully') }}</option>
</select>
<!-- 查询/重置:text-sm(14px)+font-semibold(600)+h-9(36px),与合同付款预警 .contract-filter-submit 完全一致 -->
<button type="button" class="btn-primary h-9 text-sm font-semibold" @click="doSearch">{{ t('workspace.orderDeliveryReply.search') }}</button>
<button type="button" class="btn-ghost h-9 text-sm font-semibold" @click="doReset">{{ t('workspace.orderDeliveryReply.reset') }}</button>
</div>
<!-- 工具栏:全选 + 联合回复 + 批量通知(shrink-0 防压缩,py-2 紧凑高度) -->
<div class="flex shrink-0 flex-wrap items-center gap-3 rounded-2xl border border-default bg-surface px-4 py-2">
<div class="surface-panel flex shrink-0 flex-wrap items-center gap-3 px-4 py-2">
<label class="flex items-center gap-2 text-primary">
<input type="checkbox" class="h-4 w-4 rounded border-default text-blue-600" :checked="allChecked" :indeterminate.prop="someChecked" @change="togglePageAll(($event.target as HTMLInputElement).checked)" />
<input type="checkbox" class="admin-checkbox" :checked="allChecked" :indeterminate.prop="someChecked" @change="togglePageAll(($event.target as HTMLInputElement).checked)" />
{{ t('workspace.orderDeliveryReply.selectAll') }}
</label>
<span class="text-muted">{{ t('workspace.orderDeliveryReply.selectedCount', { count: selectedLines.length }) }}</span>
<template v-if="canManage">
<button type="button" class="btn-primary h-8" :disabled="selectedLines.length === 0" @click="openBatchReply">
<button type="button" class="btn-primary h-9 text-sm font-semibold" :disabled="selectedLines.length === 0" @click="openBatchReply">
{{ t('workspace.orderDeliveryReply.batchReply') }}
</button>
<button type="button" class="btn-primary h-8" :disabled="notifiableSelected.length === 0 || notifying" @click="doNotifyBatch">
<button type="button" class="btn-primary h-9 text-sm font-semibold" :disabled="notifiableSelected.length === 0 || notifying" @click="requestNotifyBatch">
{{ t('workspace.orderDeliveryReply.batchNotify') }}
</button>
</template>
<div class="flex-1" />
<span class="whitespace-nowrap rounded-full bg-slate-100 px-3 py-1 text-muted">{{ t('workspace.orderDeliveryReply.toolbarHint') }}</span>
<!-- 导出 Excel(2026-10-09 增补,原提示文字胶囊取消):按当前筛选导出全部行 -->
<button type="button" class="btn-primary h-9 text-sm font-semibold" :disabled="exporting" @click="doExportExcel">
<Download class="h-4 w-4" aria-hidden="true" />
{{ t('workspace.orderDeliveryReply.exportExcel') }}
</button>
</div>
<!-- 列表 -->
<div class="min-h-0 flex-1 overflow-auto rounded-2xl border border-default bg-surface">
<table class="w-full border-collapse">
<div class="surface-panel min-h-0 flex-1 overflow-auto">
<table class="w-full border-collapse text-center">
<!-- z-30 高于表体冻结单元格(z-20):纵向滚动时冻结列不会盖住表头 -->
<thead class="sticky top-0 z-30 bg-slate-50 text-muted [&_th]:whitespace-nowrap">
<thead class="sticky top-0 z-30 bg-surface-soft text-muted [&_th]:whitespace-nowrap">
<tr>
<!-- 左侧冻结标识区(前四列):勾选/客户编号/订单日期/订单单号:项次,宽度固定保证偏移对齐 -->
<th class="sticky left-0 z-30 w-8 bg-slate-50 px-2 py-2" />
<th class="sticky left-8 z-30 w-32 min-w-[8rem] bg-slate-50 px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colCustomer') }}</th>
<th class="sticky left-[10rem] z-30 w-24 bg-slate-50 px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colOrderDate') }}</th>
<th class="sticky left-[16rem] z-30 w-40 min-w-[10rem] border-r border-default bg-slate-50 px-2 py-2 text-left shadow-[2px_0_6px_-2px_rgba(15,23,42,0.12)]">{{ t('workspace.orderDeliveryReply.colOrderLine') }}</th>
<th class="px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colPartNo') }}</th>
<th class="px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colCustomerPartNo') }}</th>
<th class="px-2 py-2 text-right">{{ t('workspace.orderDeliveryReply.colQty') }}</th>
<th class="px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colAgreedDate') }}</th>
<th class="px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colStatus') }}</th>
<th class="px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colReply') }}</th>
<th class="px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colReplyPerson') }}</th>
<th class="px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colSalesperson') }}</th>
<th class="px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colCustomerPo') }}</th>
<th class="px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colSpec') }}</th>
<th class="px-2 py-2 text-left">{{ t('workspace.orderDeliveryReply.colUnit') }}</th>
<th class="sticky left-0 z-30 w-8 bg-surface-soft px-2 py-2" />
<th class="sticky left-8 z-30 w-32 min-w-[8rem] bg-surface-soft px-2 py-2 text-center">{{ t('workspace.orderDeliveryReply.colCustomer') }}</th>
<th class="sticky left-[10rem] z-30 w-24 bg-surface-soft px-2 py-2 text-center">{{ t('workspace.orderDeliveryReply.colOrderDate') }}</th>
<th class="sticky left-[16rem] z-30 w-40 min-w-[10rem] border-r border-default bg-surface-soft px-2 py-2 text-center shadow-sticky-col">{{ t('workspace.orderDeliveryReply.colOrderLine') }}</th>
<th class="px-2 py-2 text-center">{{ t('workspace.orderDeliveryReply.colPartNo') }}</th>
<th class="px-2 py-2 text-center">{{ t('workspace.orderDeliveryReply.colCustomerPartNo') }}</th>
<th class="px-2 py-2 text-center">{{ t('workspace.orderDeliveryReply.colQty') }}</th>
<th class="px-2 py-2 text-center">{{ t('workspace.orderDeliveryReply.colAgreedDate') }}</th>
<th class="px-2 py-2 text-center">{{ t('workspace.orderDeliveryReply.colStatus') }}</th>
<th class="px-2 py-2 text-center">{{ t('workspace.orderDeliveryReply.colReply') }}</th>
<th class="px-2 py-2 text-center">{{ t('workspace.orderDeliveryReply.colReplyPerson') }}</th>
<th class="px-2 py-2 text-center">{{ t('workspace.orderDeliveryReply.colSalesperson') }}</th>
<th class="px-2 py-2 text-center">{{ t('workspace.orderDeliveryReply.colCustomerPo') }}</th>
<th class="px-2 py-2 text-center">{{ t('workspace.orderDeliveryReply.colSpec') }}</th>
<th class="px-2 py-2 text-center">{{ t('workspace.orderDeliveryReply.colUnit') }}</th>
<th class="px-2 py-2 text-center">{{ t('workspace.orderDeliveryReply.colNotifiedTime') }}</th>
</tr>
</thead>
<tbody>
@@ -519,15 +684,15 @@ onMounted(async () => {
v-for="line in items"
:key="lineKey(line)"
:data-line-key="lineKey(line)"
class="group border-t border-default hover:bg-slate-50"
class="hover-row border-t border-default"
:class="rowCls(line)"
>
<!-- 冻结单元格必须实色背景(半透明会透出滚动内容),并用 group-hover 与整行悬停/选中/直达高亮联动 -->
<!-- 冻结单元格:frozen-cell 实色基底(半透明会透出滚动内容),悬停/选中/直达高亮由 CSS 联动 -->
<td
class="sticky left-0 z-20 px-2 py-1.5"
:class="frozenCellCls(line)"
>
<input type="checkbox" class="h-4 w-4 rounded border-default text-blue-600" :checked="selected.includes(lineKey(line))" @change="toggleLine(line, ($event.target as HTMLInputElement).checked)" />
<input type="checkbox" class="admin-checkbox" :checked="selected.includes(lineKey(line))" @change="toggleLine(line, ($event.target as HTMLInputElement).checked)" />
</td>
<td
class="sticky left-8 z-20 w-32 min-w-[8rem] max-w-[8rem] px-2 py-1.5"
@@ -542,70 +707,132 @@ onMounted(async () => {
:class="frozenCellCls(line)"
>{{ line.order_date || '—' }}</td>
<td
class="sticky left-[16rem] z-20 w-40 min-w-[10rem] max-w-[10rem] overflow-hidden whitespace-nowrap border-r border-default px-2 py-1.5 font-mono shadow-[2px_0_6px_-2px_rgba(15,23,42,0.12)]"
class="sticky left-[16rem] z-20 w-40 min-w-[10rem] max-w-[10rem] overflow-hidden whitespace-nowrap border-r border-default px-2 py-1.5 font-mono text-left shadow-sticky-col"
:class="frozenCellCls(line)"
>{{ line.order_no }}:{{ line.line_no }}</td>
<td class="px-2 py-1.5" :title="line.part_name || ''">
<div class="max-w-[10rem] truncate font-mono">{{ line.part_no || '—' }}</div>
<div class="max-w-[14rem] truncate text-muted">{{ line.part_name || '' }}</div>
<!-- 截断盒 mx-auto:限宽盒在列内居中(继承 text-center),截断能力保留 -->
<div class="mx-auto max-w-[10rem] truncate font-mono">{{ line.part_no || '—' }}</div>
<div class="mx-auto max-w-[14rem] truncate text-muted">{{ line.part_name || '' }}</div>
</td>
<td class="whitespace-nowrap px-2 py-1.5 font-mono">{{ line.customer_part_no || '—' }}</td>
<td class="px-2 py-2 text-right tabular-nums">{{ line.qty ?? '—' }}</td>
<td class="px-2 py-2 text-center tabular-nums">{{ line.qty ?? '—' }}</td>
<td class="whitespace-nowrap px-2 py-1.5">{{ line.agreed_date || '—' }}</td>
<td class="px-2 py-1.5">
<span class="whitespace-nowrap rounded-full px-2.5 py-0.5 text-xs font-semibold" :class="statusMeta(line.status).cls">
<span class="badge inline-block min-w-[68px] whitespace-nowrap text-center font-semibold" :class="statusMeta(line.status).cls">
{{ statusMeta(line.status).label }}
</span>
</td>
<!-- 交期回复:无批次=回复交期;有批次可展开;锁定=已锁定 -->
<td class="px-2 py-1.5 align-top">
<!-- 交期回复:动作入口为批次条前的加号(lucide Plus);未回复=空批次条(不显示时间/数量);
所有行首条批次条前保留等宽加号占位(无动作时为透明占位)、展开行其余批次条加 pl-7 缩进,
保证全表批次条左缘对齐;「交期已锁定」徽标已取消(锁定状态由无加号与交期回复人员列「已通知」体现);
>1 批时首条批次后有展开/收起小箭头 -->
<td class="px-2 py-1.5">
<template v-if="line.batches.length === 0">
<span class="text-muted">{{ t('workspace.orderDeliveryReply.statusNotReplied') }}</span>
<div v-if="canManage" class="mt-0.5">
<button type="button" class="rounded-md border border-blue-200 bg-blue-50 px-2 py-0.5 text-blue-600" @click="openSingleReply(line)">
{{ t('workspace.orderDeliveryReply.replyAction') }}
<div class="flex items-center gap-1">
<button
v-if="canManage"
type="button"
class="btn-ghost h-6 w-6 shrink-0 rounded-md p-0"
:disabled="chipSaving"
:title="t('workspace.orderDeliveryReply.replyAction')"
:aria-label="t('workspace.orderDeliveryReply.replyAction')"
@click="openSingleReply(line)"
>
<Plus class="h-4 w-4" />
</button>
<span v-else class="w-6 shrink-0" aria-hidden="true" />
<!-- 未回复空批次条:可管理时可点击就地填写交期+数量(回车/失焦自动保存单行接口);不显示占位文字 -->
<div
v-if="isChipEditing(line, 0)"
data-chip-edit
class="flex items-center gap-1 rounded border-l-[3px] border-brand-500 bg-surface-soft px-1.5 py-0.5"
:class="chipSaving ? 'opacity-60' : ''"
@focusout="onChipFocusout($event, line, 0)"
@keydown.enter.prevent="chipCommit(line, 0)"
@keydown.esc.prevent="cancelChipEdit"
>
<input v-model="chipDraft.planned_date" data-chip-date type="date" class="h-6 w-[125px] rounded border border-default bg-surface px-1 text-sm text-primary outline-none focus:border-brand-500" :aria-label="t('workspace.orderDeliveryReply.filterOrderDate')" />
<input v-model="chipDraft.qty" type="number" min="0" class="h-6 w-16 rounded border border-default bg-surface px-1 text-sm text-primary outline-none focus:border-brand-500" :aria-label="t('workspace.orderDeliveryReply.colQty')" @focus="($event.target as HTMLInputElement).select()" />
<span v-if="line.unit" class="text-muted">{{ line.unit }}</span>
</div>
<div
v-else-if="isChipEditable(line)"
class="h-6 w-24 cursor-pointer rounded border-l-[3px] border-brand-500 bg-surface-soft transition-colors hover-surface-strong"
:title="t('workspace.orderDeliveryReply.replyAction')"
@click="startChipEdit(line, 0)"
/>
<div v-else class="h-6 w-24 rounded border-l-[3px] border-brand-500 bg-surface-soft" />
</div>
<p v-if="isChipEditing(line, 0) && chipIssue" class="mt-0.5 text-xs text-status-error">{{ chipIssue }}</p>
</template>
<template v-else>
<div class="flex items-center gap-2">
<span class="whitespace-nowrap rounded-full border border-default bg-slate-50 px-2 py-0.5 text-muted">
{{ t('workspace.orderDeliveryReply.batchCount', { count: line.batches.length }) }} ·
{{ t('workspace.orderDeliveryReply.repliedOf', { replied: repliedQty(line), remain: undelivered(line) }) }}
<span v-if="repliedQty(line) > undelivered(line)" class="ml-1 font-semibold text-orange-500">{{ t('workspace.orderDeliveryReply.overTag') }}</span>
</span>
<button v-if="line.batches.length > 1" type="button" class="rounded-full border border-default px-2 py-0.5 text-blue-600" @click="toggleExpand(lineKey(line))">
{{ expanded.includes(lineKey(line)) ? t('workspace.orderDeliveryReply.collapse') : t('workspace.orderDeliveryReply.expand', { count: line.batches.length - 1 }) }}
</button>
</div>
<div class="mt-0.5 flex flex-col gap-0.5">
<div class="flex flex-col gap-0.5">
<div
v-for="(batch, idx) in line.batches"
:key="batch.seq ?? idx"
v-show="expanded.includes(lineKey(line)) || idx === 0"
class="max-w-[230px] truncate rounded border-l-[3px] border-blue-500 bg-blue-50/50 px-2 py-0.5 text-secondary"
v-show="idx === 0 || expanded.includes(lineKey(line))"
class="flex items-center gap-1"
:class="idx > 0 ? 'pl-7' : ''"
>
{{ batch.planned_date }} · <b class="text-blue-600">{{ batch.qty }}</b> {{ line.unit }}
<i v-if="batch.remark" class="ml-1 not-italic text-muted">{{ batch.remark }}</i>
<template v-if="idx === 0">
<button
v-if="canManage && !line.locked"
type="button"
class="btn-ghost h-6 w-6 shrink-0 rounded-md p-0"
:disabled="chipSaving"
:title="t('workspace.orderDeliveryReply.editReplyAction')"
:aria-label="t('workspace.orderDeliveryReply.editReplyAction')"
@click="openSingleReply(line)"
>
<Plus class="h-4 w-4" />
</button>
<span v-else class="w-6 shrink-0" aria-hidden="true" />
</template>
<!-- 批次条:未锁定可管理行点击原地编辑(日期+数量,回车/失焦自动保存) -->
<div
v-if="isChipEditing(line, idx)"
data-chip-edit
class="flex items-center gap-1 rounded border-l-[3px] border-brand-500 bg-surface-soft px-1.5 py-0.5"
:class="chipSaving ? 'opacity-60' : ''"
@focusout="onChipFocusout($event, line, idx)"
@keydown.enter.prevent="chipCommit(line, idx)"
@keydown.esc.prevent="cancelChipEdit"
>
<input v-model="chipDraft.planned_date" data-chip-date type="date" class="h-6 w-[125px] rounded border border-default bg-surface px-1 text-sm text-primary outline-none focus:border-brand-500" :aria-label="t('workspace.orderDeliveryReply.filterOrderDate')" />
<input v-model="chipDraft.qty" type="number" min="0" class="h-6 w-16 rounded border border-default bg-surface px-1 text-sm text-primary outline-none focus:border-brand-500" :aria-label="t('workspace.orderDeliveryReply.colQty')" @focus="($event.target as HTMLInputElement).select()" />
<span v-if="line.unit" class="text-muted">{{ line.unit }}</span>
</div>
<div
v-else
class="max-w-[230px] truncate rounded border-l-[3px] border-brand-500 bg-surface-soft px-2 py-0.5 text-secondary"
:class="isChipEditable(line) ? 'cursor-pointer transition-colors hover-surface-strong' : ''"
:title="isChipEditable(line) ? t('workspace.orderDeliveryReply.editReplyAction') : undefined"
@click="startChipEdit(line, idx)"
>
{{ batch.planned_date }} · <b class="text-brand-600">{{ batch.qty }}</b> {{ line.unit }}
</div>
<button
v-if="idx === 0 && line.batches.length > 1"
type="button"
class="btn-ghost h-6 w-6 shrink-0 rounded-md p-0"
:title="expanded.includes(lineKey(line)) ? t('workspace.orderDeliveryReply.collapse') : t('workspace.orderDeliveryReply.expand', { count: line.batches.length - 1 })"
:aria-label="expanded.includes(lineKey(line)) ? t('workspace.orderDeliveryReply.collapse') : t('workspace.orderDeliveryReply.expand', { count: line.batches.length - 1 })"
@click="toggleExpand(lineKey(line))"
>
<ChevronUp v-if="expanded.includes(lineKey(line))" class="h-4 w-4" />
<ChevronDown v-else class="h-4 w-4" />
</button>
</div>
</div>
<div class="mt-0.5">
<span v-if="line.locked" class="rounded-full bg-emerald-50 px-2.5 py-0.5 text-xs font-semibold text-emerald-600">{{ t('workspace.orderDeliveryReply.lockedTag') }}</span>
<button v-else-if="canManage" type="button" class="rounded-md border border-blue-200 bg-blue-50 px-2 py-0.5 text-blue-600" @click="openSingleReply(line)">
{{ t('workspace.orderDeliveryReply.editReplyAction') }}
</button>
</div>
<p v-if="editingChip && editingChip.key === lineKey(line) && chipIssue" class="mt-0.5 text-xs text-status-error">{{ chipIssue }}</p>
</template>
</td>
<!-- 交期回复人员:锁定行附带已通知对象与时间(原「通知业务部门」列已取消,信息并入此处) -->
<!-- 交期回复人员:通知时间已拆至独立「通知时间」列(2026-10-09),本列仅工号/姓名/待通知提示 -->
<td class="px-2 py-1.5">
<template v-if="line.notified_employee_id || line.notified_user_name">
<div class="font-mono">{{ line.notified_employee_id || '' }}</div>
<div class="text-muted">{{ line.notified_user_name || '' }}</div>
<div v-if="line.locked" class="text-emerald-600">
{{ t('workspace.orderDeliveryReply.notifiedTag', { name: line.salesperson_name || line.salesperson_code || '' }) }}
<span class="text-muted">{{ line.notified_at || '' }}</span>
</div>
</template>
<span v-else class="text-muted">{{ t('workspace.orderDeliveryReply.pendingNotify') }}</span>
</td>
@@ -614,20 +841,21 @@ onMounted(async () => {
<div class="whitespace-nowrap">{{ line.salesperson_name || line.salesperson_code || '—' }}</div>
<div class="text-muted">{{ line.dept_name || line.dept_code || '' }}</div>
</td>
<td class="px-2 py-1.5 font-mono" :title="line.customer_po || ''"><span class="block max-w-[10rem] truncate">{{ line.customer_po || '—' }}</span></td>
<td class="px-2 py-1.5" :title="line.spec || ''"><span class="block max-w-[10rem] truncate">{{ line.spec || '—' }}</span></td>
<td class="px-2 py-1.5 font-mono" :title="line.customer_po || ''"><span class="mx-auto block max-w-[10rem] truncate">{{ line.customer_po || '—' }}</span></td>
<td class="px-2 py-1.5" :title="line.spec || ''"><span class="mx-auto block max-w-[10rem] truncate">{{ line.spec || '—' }}</span></td>
<td class="px-2 py-1.5">{{ line.unit || '—' }}</td>
<!-- 通知时间(2026-10-09 自「交期回复人员」列拆出独立列):锁定行展示通知时间戳,单行不折行 -->
<td class="whitespace-nowrap px-2 py-1.5" :class="line.locked ? 'text-status-success' : 'text-muted'">{{ line.locked ? (line.notified_at || '—') : '—' }}</td>
</tr>
<tr v-if="!loading && items.length === 0">
<td colspan="15" class="px-4 py-16 text-center text-muted">{{ t('workspace.orderDeliveryReply.empty') }}</td>
<td colspan="16" class="px-4 py-16 text-center text-muted">{{ t('workspace.orderDeliveryReply.empty') }}</td>
</tr>
</tbody>
</table>
</div>
<!-- 分页:复用管理控制台-数据报表的 PaginationBar(摘要 + 每页条数 + 页码按钮) -->
<!-- 分页:复用管理控制台-数据报表的 PaginationBar(摘要 + 每页条数 + 页码按钮),组件自带字号不再强改 -->
<PaginationBar
class="[&_*]:!text-sm"
:page="page"
:page-size="pageSize"
:total="total"
@@ -636,30 +864,29 @@ onMounted(async () => {
@update:page-size="changePageSize"
/>
<!-- 回复弹窗 -->
<div v-if="modalVisible" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40" @click.self="modalVisible = false">
<div class="flex max-h-[88vh] w-[min(960px,94vw)] flex-col overflow-hidden rounded-2xl bg-white shadow-2xl">
<div class="flex items-center gap-3 border-b border-default px-5 py-4">
<!-- 回复弹窗:dialog-overlay/panel/header/body/footer 设计系统 L2 结构 -->
<div v-if="modalVisible" class="dialog-overlay items-center" @click.self="modalVisible = false">
<div class="dialog-panel max-h-[88vh] w-[min(960px,94vw)]">
<div class="dialog-header">
<h3 class="font-bold text-primary">{{ modalTitle }}</h3>
<div class="flex-1" />
<button type="button" class="text-muted" @click="modalVisible = false">×</button>
<button type="button" class="btn-ghost h-8 w-8 px-0 text-lg leading-none" @click="modalVisible = false">×</button>
</div>
<div class="flex-1 overflow-auto px-5 py-4">
<div class="dialog-body">
<!-- 快速统一交期:仅联合回复弹窗显示;单行回复/修改回复弹窗已取消该区(2026-10-07),直接逐批次填写 -->
<div v-if="modalMode === 'batch'" class="mb-4 flex flex-wrap items-end gap-3 rounded-xl border border-default bg-blue-50/40 px-4 py-3">
<div v-if="modalMode === 'batch'" class="flex flex-wrap items-end gap-3 rounded-xl border border-default bg-surface-soft px-4 py-3">
<label class="flex flex-col gap-1 text-muted">
{{ t('workspace.orderDeliveryReply.quickDate') }}
<input v-model="quickDate" type="date" class="h-9 rounded-lg border border-default px-3 text-primary" />
<input v-model="quickDate" type="date" class="input-field h-9 w-auto rounded-lg px-3 py-1.5" />
</label>
<button type="button" class="h-9 rounded-lg border border-default px-3 text-primary" @click="applyQuickDate">
<button type="button" class="btn-secondary btn-sm h-9" @click="applyQuickDate">
{{ t('workspace.orderDeliveryReply.applyQuickDate') }}
</button>
<span class="text-muted">{{ t('workspace.orderDeliveryReply.modalHint') }}</span>
</div>
<!-- 每行批次编辑器 -->
<div v-for="entry in modalLines" :key="lineKey(entry.line)" class="mb-4 overflow-hidden rounded-xl border border-default">
<div class="flex flex-wrap items-center gap-2 bg-slate-50 px-3 py-2">
<span class="rounded bg-indigo-50 px-2 py-0.5 font-semibold text-indigo-600">{{ entry.line.order_no }}</span>
<div v-for="entry in modalLines" :key="lineKey(entry.line)" class="overflow-hidden rounded-xl border border-default">
<div class="flex flex-wrap items-center gap-2 bg-surface-soft px-3 py-2">
<span class="rounded bg-surface-strong px-2 py-0.5 font-semibold text-primary">{{ entry.line.order_no }}</span>
<span>{{ t('workspace.orderDeliveryReply.itemLabel', { item: entry.line.line_no }) }}</span>
<span class="text-muted">{{ entry.line.customer_no }} · {{ entry.line.customer_short_name }}</span>
<span class="text-muted">{{ entry.line.part_no }} · {{ entry.line.part_name }}</span>
@@ -668,27 +895,36 @@ onMounted(async () => {
</span>
</div>
<div class="flex flex-col gap-2 px-3 py-3">
<div v-for="(batch, idx) in entry.batches" :key="idx" class="grid grid-cols-[170px_120px_1fr_36px] items-center gap-2">
<input v-model="batch.planned_date" type="date" class="h-9 rounded-lg border border-default px-2 text-primary" />
<input v-model="batch.qty" type="number" min="0" :placeholder="t('workspace.orderDeliveryReply.qtyPh')" class="h-9 rounded-lg border border-default px-2 text-primary" />
<input v-model="batch.remark" :placeholder="t('workspace.orderDeliveryReply.remarkPh')" class="h-9 rounded-lg border border-default px-2 text-primary" />
<button type="button" class="h-9 rounded-lg bg-rose-50 text-rose-600" :title="t('workspace.orderDeliveryReply.removeBatch')" @click="entry.batches.splice(idx, 1)">✕</button>
<div v-for="(batch, idx) in entry.batches" :key="idx" class="grid grid-cols-[170px_120px_1fr_40px] items-center gap-2">
<input v-model="batch.planned_date" type="date" class="input-field h-9 rounded-lg px-2 py-1.5" />
<input v-model="batch.qty" type="number" min="0" :placeholder="t('workspace.orderDeliveryReply.qtyPh')" class="input-field h-9 rounded-lg px-2 py-1.5" />
<input v-model="batch.remark" :placeholder="t('workspace.orderDeliveryReply.remarkPh')" class="input-field h-9 rounded-lg px-2 py-1.5" />
<button type="button" class="btn-danger btn-sm" :title="t('workspace.orderDeliveryReply.removeBatch')" @click="entry.batches.splice(idx, 1)">✕</button>
</div>
<button type="button" class="w-full rounded-lg border border-dashed border-slate-300 py-2 text-blue-600" @click="entry.batches.push({ planned_date: '', qty: '', remark: '' })">
<button type="button" class="w-full rounded-lg border border-dashed border-default py-2 text-brand-600 transition-colors hover-surface-soft" @click="entry.batches.push({ planned_date: '', qty: '', remark: '' })">
{{ t('workspace.orderDeliveryReply.addBatch') }}
</button>
<!-- 行级实时校验提示:缺交期/缺数量按批次序号指出,合计不等给出已填/应填;随填写实时切换 -->
<p v-if="lineIssueText(entry)" class="text-rose-500">{{ lineIssueText(entry) }}</p>
<p v-if="lineIssueText(entry)" class="text-status-error">{{ lineIssueText(entry) }}</p>
</div>
</div>
</div>
<div class="flex justify-end gap-3 border-t border-default bg-slate-50 px-5 py-3">
<button type="button" class="btn-ghost" @click="modalVisible = false">{{ t('common.cancel') }}</button>
<div class="dialog-footer">
<button type="button" class="btn-secondary" @click="modalVisible = false">{{ t('common.cancel') }}</button>
<button type="button" class="btn-primary" :disabled="saving" @click="saveReplies">
{{ saving ? t('workspace.orderDeliveryReply.saving') : t('workspace.orderDeliveryReply.saveReply') }}
</button>
</div>
</div>
</div>
<!-- 批量通知二次确认:共享 DeleteConfirmDialog(primary 语气,非删除;确认/取消文案用组件默认 i18n) -->
<DeleteConfirmDialog
v-model="notifyConfirmVisible"
:title="t('workspace.orderDeliveryReply.batchNotify')"
:message="t('workspace.orderDeliveryReply.notifyBatchConfirm', { count: notifiableSelected.length })"
confirm-tone="primary"
@confirm="doNotifyBatch"
/>
</div>
</template>
@@ -1,6 +1,7 @@
/**
* features/workspace/composables/useWorkspace.ts
* 工作台编排层:组合各子 composable,挂载生命周期,provide 给 Layout 与子页面。
* 未登录进入时跳登录页并保留当前 fullPath,供书签登录后回跳。
*/
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
@@ -10,6 +11,7 @@ import { useTheme } from '@/shared/composables/useTheme';
import { useMessage } from '@/shared/composables/useMessage';
import { useIsMobile } from '@/shared/composables/useIsMobile';
import { WORKSPACE_PATHS } from '../constants/routes';
import { isPublicPath } from '@/shared/constants/routes';
import type { WorkspaceUser } from '../types/workspace.types';
import { useChatHistory } from '@/features/chat/composables/useChatHistory';
import { useWorkspaceHome } from './useWorkspaceHome';
@@ -32,17 +34,18 @@ export function useWorkspace() {
const currentUser = ref<WorkspaceUser | null>(null);
const isSidebarCollapsed = ref(false);
const sessionRef: { handleLogout?: () => void } = {};
const sessionRef: { handleSessionExpired?: () => void } = {};
const home = useWorkspaceHome(deps, {
currentUser,
isLoading,
onUnauthorized: () => sessionRef.handleLogout?.(),
// 401 只清工作台状态并回到登录页(保留 redirect)。不走手动登出,避免丢掉书签回跳地址。
onUnauthorized: () => sessionRef.handleSessionExpired?.(),
});
const session = useWorkspaceSession(deps, {
currentUser,
clearHome: home.clearHomeData,
});
sessionRef.handleLogout = session.handleLogout;
sessionRef.handleSessionExpired = session.handleSessionExpired;
const profile = useWorkspaceProfile(deps);
const schedule = useWorkspaceSchedule(deps);
@@ -69,7 +72,11 @@ export function useWorkspace() {
session.loadAuthUser();
if (!session.isLoggedIn.value) {
await router.replace('/login');
// 保留书签地址。裸跳 /login 会丢掉 redirect,登录后回不到 /workspace。
const redirect = route.fullPath;
await router.replace(
isPublicPath(route.path) ? '/login' : { path: '/login', query: { redirect } },
);
return;
}
@@ -3,10 +3,11 @@
* 应用管理/最近更新:首页数据、布局分区、收藏、快捷问题。
* 依赖:requestJson、auth 存储、auth.store。
* 逻辑:拉取 /api/user/home 后把 feature_permissions 写回登录态,供侧栏和路由守卫使用。
* 首页成功才标记会话已确认;401 只交给全局登出回登录页,冷启动不弹「请先登录」。
*/
import { computed, ref, type Ref } from 'vue';
import { config } from '@/config';
import { getAuthHeaders, patchStoredAuthUser } from '@/shared/utils/auth';
import { getAuthHeaders, markAuthSessionConfirmed, patchStoredAuthUser } from '@/shared/utils/auth';
import { BusinessError, requestJson } from '@/shared/api/client';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import {
@@ -103,6 +104,12 @@ export function useWorkspaceHome(deps: WorkspaceDeps, options: HomeOptions) {
selectedCategory.value = null;
};
/**
* 拉取工作台首页。
* 核心逻辑:成功后标记本页会话已确认。401 不再弹出「请先登录」——书签或刷新带失效登录态时,
* 全局 hxops:unauthorized 会清会话并带回登录页;使用中途失效才由 App 提示。
* @returns 无;失败时 401 走 onUnauthorized,其他错误只打日志
*/
const fetchHome = async () => {
try {
const data = await requestJson<any>('/api/user/home', { headers: getAuthHeaders() });
@@ -187,9 +194,10 @@ export function useWorkspaceHome(deps: WorkspaceDeps, options: HomeOptions) {
return config.workspace.modules[key] !== false;
});
}
markAuthSessionConfirmed();
} catch (e) {
if ((e as BusinessError)?.status === 401) {
msg.error(t('login.loginRequired'));
// 冷启动(书签 /workspace)失效会话会走到这里。不弹错误框,避免登录页上盖一层「请先登录」。
onUnauthorized();
return;
}
@@ -1,11 +1,13 @@
/**
* features/workspace/composables/useWorkspaceSession.ts
* 登录态:当前用户、知识库权限判断、登出与 401 清理。
* 依赖:logoutAuth、getStoredAuthUser。
* 依赖:logoutAuth、getStoredAuthUser、isPublicPath。
* 逻辑:从本地登录态恢复 id/username/role/feature_permissions,供工作台侧栏判断专项权限。
* 会话失效回登录页时保留当前 fullPath,登录成功后回到书签地址。
*/
import { computed, type Ref } from 'vue';
import { logoutAuth, getStoredAuthUser, isPlatformAdminUser } from '@/shared/utils/auth';
import { isPublicPath } from '@/shared/constants/routes';
import { KB_ACCESS_DENIED_MESSAGE } from '../types/workspace.types';
import type { WorkspaceUser } from '../types/workspace.types';
import type { WorkspaceDeps } from './workspace.deps';
@@ -16,7 +18,7 @@ interface SessionOptions {
}
export function useWorkspaceSession(deps: WorkspaceDeps, options: SessionOptions) {
const { router } = deps;
const { router, route } = deps;
const { currentUser } = options;
const isLoggedIn = computed(() => !!currentUser.value && currentUser.value.role !== 'guest');
@@ -68,10 +70,29 @@ export function useWorkspaceSession(deps: WorkspaceDeps, options: SessionOptions
options.clearHome();
};
/**
* 用户主动退出。
* 核心逻辑:清登录态后进入登录页,不带回跳,避免退出后又进刚才的页面。
*/
const handleLogout = () => {
logoutAuth();
applyLoggedOutState();
router.push('/login');
// replace 清掉全局登出监听先写入的 redirect,主动退出后不再回到刚才的页面。
router.replace('/login');
};
/**
* 首页等接口 401 后的会话失效处理。
* 核心逻辑:先记下当前 fullPath,再清登录态;登录页带 redirect,成功后回到书签原来的地址。
* 不弹错误框,冷启动打开 /workspace 时登录页就是结果。
*/
const handleSessionExpired = () => {
const redirect = route.fullPath;
logoutAuth();
applyLoggedOutState();
if (!isPublicPath(route.path)) {
router.replace({ path: '/login', query: { redirect } });
}
};
const onAuthLogout = () => {
@@ -86,6 +107,7 @@ export function useWorkspaceSession(deps: WorkspaceDeps, options: SessionOptions
loadAuthUser,
applyLoggedOutState,
handleLogout,
handleSessionExpired,
onAuthLogout,
};
}
@@ -147,6 +147,8 @@ function notice(businessNo: string, poNumber: string, partNumber: string) {
id: Number(businessNo.slice(-2)), task_no: `SN-${businessNo}`, business_no: businessNo,
item_kind: 'task', todo_ref: `SN-${businessNo}`, source_type: 'post_ot_fulfillment_wave',
po_number: poNumber, customer_name: 'Customer', upload_status: 'pending',
// 后端 SUMMARY 契约:下载能力与导出端点同一谓词(创建者或管理员)。
can_download_export: true,
ui_state: { stage: { code: 'freight_upload', label: '货代上传' }, lifecycle_entries: [] },
notice_line_summary: [
{ line_no: '10', part_number: partNumber, shipment_qty: '4', available_qty: '9' },
@@ -38,7 +38,7 @@ import { useShippingTodoBadge } from '../composables/useShippingTodoBadge';
import { useMessage } from '@/shared/composables/useMessage';
import { BusinessError } from '@/shared/api/client';
import {
isFreightUploadRow,
isBatchDownloadableRow,
lifecycleStageCodeOf,
todoItemKey,
type LifecycleStageCode,
@@ -134,8 +134,8 @@ const filteredTasks = computed(() => (
? tasks.value
: tasks.value.filter((item) => lifecycleStageCodeOf(item) === lifecycleStageFilter.value)
));
/** 批量可选行:货代上传阶段的正式 Notice(业务约束:批量仅该阶段可用)。 */
const selectableRows = computed(() => filteredTasks.value.filter((item) => isFreightUploadRow(item)));
/** 批量可选行:货代上传阶段的正式 Notice 且当前用户可下载(与批量导出端点同口径)。 */
const selectableRows = computed(() => filteredTasks.value.filter((item) => isBatchDownloadableRow(item)));
const selectedBusinessNoSet = computed(() => new Set(selectedBusinessNos.value));
/** 当前桶是否为通知完成明细报表视图。 */
@@ -366,7 +366,7 @@ async function loadTodos(resetPage = false, options?: { silent?: boolean }) {
tasks.value = result.items || [];
const visibleBusinessNos = new Set(
tasks.value
.filter((item) => isFreightUploadRow(item))
.filter((item) => isBatchDownloadableRow(item))
.map((item) => String(item.business_no || '').trim()),
);
selectedBusinessNos.value = selectedBusinessNos.value.filter((value) => visibleBusinessNos.has(value));
Loaded 100 of 310 files, more files were not shown because too many files have changed in this diff. Show more