Merge branch 'dev' into hugo-shipping-notice

# Conflicts:
#	backend/app/api/chat.py
#	backend/app/services/agent_runtime_context/dify_inputs.py
#	backend/app/services/maintenance_chat_service.py
This commit is contained in:
hugo committed 2026-07-07 13:25:16 +08:00
commit fc694a8f43
55 files changed
+2107 -192

No files matched your search

@@ -116,6 +116,7 @@ export interface AdminAgentRegistrySchema {
models?: string[];
required_fields?: string[];
forced_capabilities?: Record<string, boolean>;
default_intent_routes?: string[];
handler_config_schema?: Record<string, unknown>;
}>;
handler_config_schemas: Record<string, unknown>;
@@ -7,8 +7,8 @@
*/
<script setup lang="ts">
import { computed, watch } from 'vue';
import { FileDown, Plus, Trash2, X } from 'lucide-vue-next';
import { computed, ref, watch } from 'vue';
import { ChevronDown, FileDown, Plus, Search, Trash2, X } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import type { AgentFormState, AgentGuideSummary } from '@/features/admin/types/agent.types';
import type { ScheduleTask } from '@/shared/types/schedule.types';
@@ -52,6 +52,8 @@ const emit = defineEmits<{
const { t } = useI18n();
const optionLabels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
const advancedOpen = ref(false);
const intentRouteSearch = ref('');
const showDifyFields = computed(() => props.form.runtime_provider === 'dify' || props.form.runtime_provider === 'hybrid');
const showIframeFields = computed(() => props.form.runtime_provider === 'iframe');
@@ -67,6 +69,30 @@ const currentCatalogEntry = computed(() => (
const taskProgressForced = computed(() => catalogForcesTaskProgress(currentCatalogEntry.value));
const selectedIntentRouteOptions = computed(() => (
props.form.intent_routes
.map((key) => props.intentRouteOptions.find((item) => item.key === key))
.filter(Boolean) as IntentRouteOption[]
));
const intentRouteSummary = computed(() => {
if (!selectedIntentRouteOptions.value.length) return t('admin.agent.registry.intentRoutesNone');
return t('admin.agent.registry.intentRoutesSummary', {
count: selectedIntentRouteOptions.value.length,
names: selectedIntentRouteOptions.value.map((item) => item.label).join('、'),
});
});
const filteredIntentRouteOptions = computed(() => {
const keyword = intentRouteSearch.value.trim().toLowerCase();
if (!keyword) return props.intentRouteOptions;
return props.intentRouteOptions.filter((route) => (
route.key.toLowerCase().includes(keyword)
|| route.label.toLowerCase().includes(keyword)
|| String(route.description || '').toLowerCase().includes(keyword)
));
});
/**
* 切换 intent_route 勾选状态。
*/
@@ -84,6 +110,13 @@ const toggleIntentRoute = (route: string, checked: boolean) => {
void props.syncContentProfileFromIntentRoutes(props.form);
};
/**
* 移除已选 intent_route tag。
*/
const removeIntentRoute = (route: string) => {
toggleIntentRoute(route, false);
};
/**
* 套用 content_profile 默认欢迎语与推荐问题。
*/
@@ -303,29 +336,73 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
</div>
<div class="space-y-4">
<div class="space-y-2">
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.registry.intentRoutesLabel') }}</label>
<div class="grid grid-cols-1 gap-2 sm:grid-cols-2">
<label
v-for="route in intentRouteOptions"
:key="route.key"
class="inline-flex items-start gap-2 rounded-xl border border-default bg-white px-3 py-2 text-sm text-secondary"
>
<input
type="checkbox"
class="mt-0.5 accent-brand-600"
:checked="form.intent_routes.includes(route.key)"
@change="toggleIntentRoute(route.key, ($event.target as HTMLInputElement).checked)"
/>
<span>
<span class="font-medium text-primary">{{ route.label }}</span>
<span v-if="route.description" class="mt-1 block text-xs leading-5 text-muted">
{{ route.description }}
</span>
<div class="rounded-xl border border-default bg-white">
<button
type="button"
class="flex w-full items-center justify-between gap-3 px-4 py-3 text-left"
@click="advancedOpen = !advancedOpen"
>
<div>
<div class="text-sm font-semibold text-primary">{{ t('admin.agent.registry.advancedTitle') }}</div>
<div class="mt-1 text-xs text-muted">{{ intentRouteSummary }}</div>
</div>
<ChevronDown class="h-4 w-4 text-muted transition-transform" :class="{ 'rotate-180': advancedOpen }" />
</button>
<div v-if="advancedOpen" class="border-t border-default px-4 py-4">
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.registry.intentRoutesLabel') }}</label>
<div class="mt-2 flex flex-wrap gap-2 rounded-xl border border-default px-3 py-2">
<span
v-for="route in selectedIntentRouteOptions"
:key="route.key"
class="inline-flex items-center gap-1 rounded-full bg-surface-soft px-2.5 py-1 text-xs text-secondary"
>
{{ route.label }}
<button type="button" @click="removeIntentRoute(route.key)">
<X class="h-3 w-3" />
</button>
</span>
</label>
<span v-if="!selectedIntentRouteOptions.length" class="text-sm text-muted">
{{ t('admin.agent.registry.intentRoutesPlaceholder') }}
</span>
</div>
<div class="mt-3 rounded-xl border border-default">
<div class="flex items-center gap-2 border-b border-default px-3 py-2">
<Search class="h-4 w-4 text-muted" />
<input
v-model="intentRouteSearch"
type="search"
class="w-full bg-transparent text-sm outline-none"
:placeholder="t('admin.agent.registry.intentRoutesSearch')"
/>
</div>
<div class="max-h-56 overflow-y-auto p-2">
<label
v-for="route in filteredIntentRouteOptions"
:key="route.key"
class="flex cursor-pointer items-start gap-2 rounded-lg px-2 py-2 text-sm hover:bg-surface-soft"
>
<input
type="checkbox"
class="mt-0.5 accent-brand-600"
:checked="form.intent_routes.includes(route.key)"
@change="toggleIntentRoute(route.key, ($event.target as HTMLInputElement).checked)"
/>
<span>
<span class="font-medium text-primary">{{ route.label }}</span>
<span v-if="route.description" class="mt-1 block text-xs leading-5 text-muted">
{{ route.description }}
</span>
</span>
</label>
</div>
</div>
<p class="mt-2 text-xs leading-5 text-muted">{{ t('admin.agent.registry.intentRoutesHint') }}</p>
</div>
<p class="text-xs leading-5 text-muted">{{ t('admin.agent.registry.intentRoutesHint') }}</p>
</div>
<div class="space-y-2">
@@ -33,6 +33,18 @@ const shippingCatalogEntry: AgentTypeCatalogEntry = {
handler_config_schema: {},
};
const fixedAssetsCatalogEntry: AgentTypeCatalogEntry = {
agent_code: 'fixed_assets',
label: '固资管理',
conversation_mode_default: 'chat',
runtime_provider_default: 'dify',
default_intent_routes: ['text2sql'],
handler_config_schema: {
intent_routes: { type: 'array', items: 'string' },
content_profile: { type: 'string' },
},
};
describe('useAgentsAdminRegistry catalog switch', () => {
it('pruneHandlerFormFieldsForCatalog clears intent routes and content profile for empty schema', () => {
const form = createEmptyAgentForm();
@@ -68,4 +80,24 @@ describe('useAgentsAdminRegistry catalog switch', () => {
expect(payload.handler_config).toBeNull();
});
it('applyCatalogDefaultsToForm applies default_intent_routes when catalog supports intent_routes', () => {
const form = createEmptyAgentForm();
applyCatalogDefaultsToForm(form, genericCatalogEntry);
form.intent_routes = ['hr_leave'];
applyCatalogDefaultsToForm(form, fixedAssetsCatalogEntry);
expect(form.intent_routes).toEqual(['text2sql']);
});
it('applyCatalogDefaultsToForm clears intent routes when catalog schema lacks intent_routes', () => {
const form = createEmptyAgentForm();
applyCatalogDefaultsToForm(form, fixedAssetsCatalogEntry);
expect(form.intent_routes).toEqual(['text2sql']);
applyCatalogDefaultsToForm(form, shippingCatalogEntry);
expect(form.intent_routes).toEqual([]);
});
});
@@ -32,6 +32,8 @@ export interface AgentTypeCatalogEntry {
runtime_provider_default: string;
default_intent_routes?: string[];
runtime_handler?: string | null;
models?: string[];
@@ -232,6 +234,11 @@ export function applyCatalogDefaultsToForm(
pruneHandlerFormFieldsForCatalog(form, entry);
const schemaFields = new Set(handlerConfigSchemaFieldNames(entry));
if (schemaFields.has('intent_routes')) {
form.intent_routes = normalizeIntentRoutes(entry.default_intent_routes || []);
}
}
@@ -40,6 +40,7 @@ const { t } = useI18n();
<option value="">{{ t('admin.batchEdit.fields.keepUnchanged') }}</option>
<option value="user">{{ t('admin.role.user') }}</option>
<option value="hr">{{ t('admin.role.hr') }}</option>
<option value="maintenance_manager">{{ t('admin.role.maintenanceManager') }}</option>
<option value="admin">{{ t('admin.role.admin') }}</option>
</select>
</div>
@@ -88,6 +88,7 @@ const { t } = useI18n();
<select v-model="form.role" class="w-full border-default rounded-xl px-4 py-3 text-sm">
<option value="user">{{ t('admin.role.user') }}</option>
<option value="hr">{{ t('admin.role.hr') }}</option>
<option value="maintenance_manager">{{ t('admin.role.maintenanceManager') }}</option>
<option value="admin">{{ t('admin.role.admin') }}</option>
</select>
</div>
@@ -6,6 +6,7 @@ import { getAuthHeaders } from '@/shared/utils/auth';
import { requestJson } from '@/shared/api/client';
import type {
AssetHistorySearchResult,
AssetImageResolveResult,
ChatCrossAgentHistoryItem,
ChatMessage,
ChatQueryPreviewPage,
@@ -104,4 +105,16 @@ export const searchAssetHistoryFiles = (
return requestJson<AssetHistorySearchResult>(`/api/chat/asset-history/search?${qs.toString()}`, auth());
};
export const resolveAssetImagePreview = (
agentId: number,
query: { asset_id?: string; asset_name?: string },
) => {
const qs = new URLSearchParams({
agent_id: String(agentId),
});
if (query.asset_id) qs.set('asset_id', query.asset_id);
if (query.asset_name) qs.set('asset_name', query.asset_name);
return requestJson<AssetImageResolveResult>(`/api/chat/asset-image/resolve?${qs.toString()}`, auth());
};
export type { ChatSessionItem, ChatCrossAgentHistoryItem };
@@ -30,7 +30,7 @@ const titleText = computed(() => props.assetId || props.assetName || '资产履
<template>
<div
v-if="open"
class="dialog-overlay z-[120] items-center"
class="dialog-overlay z-[150] items-center"
@click.self="emit('close')"
>
<div class="dialog-panel flex max-h-[88vh] w-[min(96vw,900px)] max-w-[900px] flex-col">
@@ -41,6 +41,7 @@ const props = defineProps<{
canSendMessage: boolean;
isShippingNoticeAgent: boolean;
isMaintenanceAgent?: boolean;
canManageMaintenance?: boolean;
shippingSuggestedPrompt: string;
shippingFocusTaskNo?: string;
shippingFocusReason?: string;
@@ -202,7 +203,7 @@ watch(
ref="textareaRef"
v-model="inputValue"
rows="1"
:placeholder="isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $t('chat.voiceListening') : shippingFocusTaskNo ? $t('chat.shippingNoticeUi.focusInputPlaceholder', { taskId: shippingFocusTaskNo }) : $t('chat.askAnything')"
:placeholder="isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $t('chat.voiceListening') : shippingFocusTaskNo ? $t('chat.shippingNoticeUi.focusInputPlaceholder', { taskId: shippingFocusTaskNo }) : isMaintenanceAgent ? $t('maintenance.chat.inputPlaceholder') : $t('chat.askAnything')"
class="w-full resize-none border-none bg-transparent px-2.5 py-1.5 text-[15px] leading-relaxed text-primary placeholder-slate-400 focus:border-transparent focus:outline-none focus:ring-0"
style="min-height: 40px; max-height: 220px;"
:disabled="isVoiceTranscribing"
@@ -259,7 +260,7 @@ watch(
</div>
<div
v-if="isMaintenanceAgent"
v-if="isMaintenanceAgent && canManageMaintenance"
class="flex flex-wrap items-center gap-2 px-3 pb-1 text-xs text-muted"
>
<button
@@ -19,6 +19,7 @@ const emit = defineEmits<{
close: [];
'change-page': [delta: number];
'open-asset-history': [payload: { assetId: string; assetName: string }];
'open-asset-image': [payload: { assetId: string; assetName: string }];
}>();
const totalPages = computed(() =>
@@ -26,19 +27,34 @@ const totalPages = computed(() =>
);
const assetIdColumnIndex = computed(() => props.state.columns.findIndex((column) => column === '资产编号'));
const assetNameColumnIndex = computed(() => props.state.columns.findIndex((column) => column === '资产名称'));
const imageColumnIndex = computed(() => props.state.columns.findIndex((column) => column === '图片'));
function isHighlightColumn(column: string): boolean {
return column === '资产编号' || column === '图片';
}
function normalizeCellText(cell: unknown): string {
return String(cell ?? '').trim();
}
function canOpenAssetHistory(row: unknown[], cellIndex: number): boolean {
return cellIndex === assetIdColumnIndex.value && !!normalizeCellText(row[cellIndex]);
if (cellIndex === assetIdColumnIndex.value) {
return !!normalizeCellText(row[cellIndex]);
}
if (cellIndex === imageColumnIndex.value) {
return !!normalizeCellText(row[assetIdColumnIndex.value]);
}
return false;
}
function emitAssetHistory(row: unknown[]): void {
function emitAssetAction(row: unknown[], cellIndex: number): void {
const assetId = normalizeCellText(row[assetIdColumnIndex.value]);
const assetName = assetNameColumnIndex.value >= 0 ? normalizeCellText(row[assetNameColumnIndex.value]) : '';
if (!assetId) return;
if (cellIndex === imageColumnIndex.value) {
emit('open-asset-image', { assetId, assetName });
return;
}
emit('open-asset-history', { assetId, assetName });
}
</script>
@@ -97,7 +113,10 @@ function emitAssetHistory(row: unknown[]): void {
<th
v-for="column in state.columns"
:key="`query-preview-col-${column}`"
class="border border-slate-200 px-3 py-2 text-left font-semibold text-primary"
:class="[
'border border-slate-200 px-3 py-2 text-left font-semibold',
isHighlightColumn(column) ? 'text-blue-800' : 'text-primary',
]"
>
{{ column }}
</th>
@@ -117,8 +136,8 @@ function emitAssetHistory(row: unknown[]): void {
<button
v-if="canOpenAssetHistory(row, cellIndex)"
type="button"
class="whitespace-pre-wrap break-all text-left font-medium text-brand-600 underline-offset-2 transition hover:underline"
@click="emitAssetHistory(row)"
class="whitespace-pre-wrap break-all text-left font-semibold text-blue-700 underline-offset-2 transition hover:text-blue-800 hover:underline"
@click="emitAssetAction(row, cellIndex)"
>
{{ cell ?? '-' }}
</button>
@@ -31,6 +31,7 @@ const embeddedIframeSrc = computed(() => {
const url = agent.iframe_url;
return url ? String(url) : undefined;
});
const canManageMaintenance = computed(() => ['admin', 'maintenance_manager'].includes(String(page.currentUser?.role || '')));
const hideWelcomePanel = computed(() => isTrainingAgentPage.value);
const isTrainingWorkspaceExpanded = ref(false);
const maintenancePanel = ref<'ledger' | 'record' | null>(null);
@@ -224,6 +225,7 @@ watch(() => page.currentAgentId, () => {
:can-send-message="page.canSendMessage"
:is-shipping-notice-agent="page.isShippingNoticeAgent"
:is-maintenance-agent="isMaintenanceAgentPage"
:can-manage-maintenance="canManageMaintenance"
:shipping-suggested-prompt="page.shippingSuggestedPrompt"
:shipping-focus-task-no="page.focusedShippingTaskNo"
:shipping-focus-reason="page.shippingFocusReason"
@@ -245,7 +247,7 @@ watch(() => page.currentAgentId, () => {
</div>
<aside
v-if="isMaintenanceAgentPage && maintenancePanel"
v-if="isMaintenanceAgentPage && canManageMaintenance && maintenancePanel"
class="relative flex flex-col border-l border-default bg-surface shadow-[-8px_0_24px_rgba(15,23,42,0.06)]"
:class="[
isMaintenancePanelFullscreen ? 'absolute inset-y-0 right-0 z-30' : '',
@@ -11,6 +11,7 @@ import ChatLeaveAgentDialog from '@/features/chat/components/ChatLeaveAgentDialo
import ChatOALoginDialog from '@/features/chat/components/ChatOALoginDialog.vue';
import ChatGuideModal from '@/features/chat/components/ChatGuideModal.vue';
import { Loader2 } from 'lucide-vue-next';
import { nextTick } from 'vue';
import { useChatPageContext } from '@/features/chat/composables/chat.context';
import { getAuthHeaders } from '@/shared/utils/auth';
@@ -23,14 +24,29 @@ function onFeedbackSubmitted() {
page.msg.success(page.t('chat.feedbackSubmitSuccess'));
page.showGeneralFeedbackDialog = false;
}
async function handleQueryPreviewAssetHistory(assetId: string, assetName: string) {
page.queryPreview.close();
await nextTick();
await page.assetHistory.openHistory(assetId, assetName);
}
async function handleQueryPreviewAssetImage(assetId: string, assetName: string) {
page.queryPreview.close();
await nextTick();
await page.assetImage.openImage(assetId, assetName);
}
</script>
<template>
<FilePreviewModal
v-model="page.filePreviewVisible"
:file="page.previewFile"
:files="page.previewFiles"
:current-index="page.currentPreviewIndex"
:agent-id="page.currentAgentId"
:auth-headers="getAuthHeaders()"
@update:current-index="page.setPreviewFileIndex"
/>
<GeneralFeedbackDialog
v-model="page.showGeneralFeedbackDialog"
@@ -46,7 +62,8 @@ function onFeedbackSubmitted() {
:state="page.queryPreviewState"
@close="page.queryPreview.close"
@change-page="page.queryPreview.changePage"
@open-asset-history="({ assetId, assetName }) => page.assetHistory.openHistory(assetId, assetName)"
@open-asset-history="({ assetId, assetName }) => handleQueryPreviewAssetHistory(assetId, assetName)"
@open-asset-image="({ assetId, assetName }) => handleQueryPreviewAssetImage(assetId, assetName)"
/>
<div
v-if="page.assetHistory.loading"
@@ -57,6 +74,15 @@ function onFeedbackSubmitted() {
<span>正在搜索该资产的履历资料,请耐心等待...</span>
</div>
</div>
<div
v-if="page.assetImage.loading"
class="pointer-events-none fixed inset-x-0 top-20 z-[145] flex justify-center px-4"
>
<div class="flex items-center gap-2 rounded-full border border-brand-200 bg-white/95 px-4 py-2 text-sm text-brand-700 shadow-lg backdrop-blur">
<Loader2 class="h-4 w-4 animate-spin text-brand-500" />
<span>正在搜索该资产的图片资料,请耐心等待...</span>
</div>
</div>
<ChatLeaveAgentDialog
v-model:open="page.showLeaveAgentDialog"
v-model:keyword="page.leaveAgentKeyword"
@@ -5,8 +5,9 @@
* 逻辑:由 ChatMessageList 按消息逐条挂载;正文渲染与特殊交互委托 useChatPageMarkdown 等页面编排层提供的 handlers。
*/
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { computed, nextTick, ref, watch } from 'vue';
import { Check, Copy, Download, Edit2, Eye, LayoutGrid, MessageSquareText, RotateCw, X } from 'lucide-vue-next';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue';
import MaintenanceDeviceResultCard from './MaintenanceDeviceResultCard.vue';
import ShippingInventoryMappingMessage, { type ShippingMappingHandlers } from './ShippingInventoryMappingMessage.vue';
@@ -23,6 +24,7 @@ export interface ChatMessageBubbleHandlers {
renderMarkdown: (text: string) => string;
onMarkdownClick: (event: MouseEvent) => void;
openAssetHistory: (assetId: string, assetName?: string) => void;
openAssetImage: (assetId: string, assetName?: string) => void;
getInlineDownloadFiles: (text: string) => { cleanedText: string; files: InlineDownloadFile[] };
downloadInlineFile: (file: InlineDownloadFile) => void;
getShippingInventoryMappingPayload: (msg: ChatMessage) => ShippingInventoryMappingFormPayload | null;
@@ -76,6 +78,10 @@ const emit = defineEmits<{
'open-feedback': [];
}>();
const authStore = useAuthStore();
const INLINE_DOWNLOAD_ALLOWED_EMPLOYEE_ID = '17070141';
const RESTRICTED_INLINE_DOWNLOAD_FILE_NAME = '资产明细全量导出表.csv';
const isLeaveMessage = computed(() =>
message.type === 'leave-form'
|| message.type === 'leave-confirmation'
@@ -185,6 +191,8 @@ const FIXED_ASSET_HEADER_LABELS: Record<string, string> = {
custodian_name: '保管人',
custodian_dept: '保管部门',
department_name: '保管部门',
image: '图片',
picture: '图片',
storage_location: '存放位置名称',
location_name: '存放位置名称',
asset_status: '资产状态',
@@ -209,16 +217,17 @@ const FIXED_ASSET_HEADER_LABELS: Record<string, string> = {
snapshot_time: '快照时间',
};
const FIXED_ASSET_CANONICAL_COLUMNS = [
{ key: 'id', label: '序号', aliases: ['id'] },
{ key: 'asset_id', label: '资产编号', aliases: ['asset_id', 'asset_no'] },
{ key: 'asset_name', label: '资产名称', aliases: ['asset_name'] },
{ key: 'custodian_person', label: '保管人', aliases: ['custodian_person', 'custodian_name'] },
{ key: 'custodian_dept', label: '保管部门', aliases: ['custodian_dept', 'department_name'] },
{ key: 'account_period', label: '账套', aliases: ['account_period', 'operating_center_code'] },
{ key: 'supplier', label: '供应商', aliases: ['supplier', 'vendor_name'] },
{ key: 'asset_status', label: '资产状态', aliases: ['asset_status'] },
{ key: 'quantity', label: '数量', aliases: ['quantity'] },
{ key: 'acquisition_date', label: '取得时间', aliases: ['acquisition_date', 'acquired_date'] },
{ key: 'id', label: '序号', aliases: ['id', '序号'] },
{ key: 'asset_id', label: '资产编号', aliases: ['asset_id', 'asset_no', '资产编号'] },
{ key: 'asset_name', label: '资产名称', aliases: ['asset_name', '资产名称'] },
{ key: 'custodian_person', label: '保管人', aliases: ['custodian_person', 'custodian_name', '保管人', '保管人姓名'] },
{ key: 'custodian_dept', label: '保管部门', aliases: ['custodian_dept', 'department_name', '保管部门', '保管部门名称'] },
{ key: 'image', label: '图片', aliases: ['image', 'picture', '图片'] },
{ key: 'account_period', label: '账套', aliases: ['account_period', 'operating_center_code', '账套'] },
{ key: 'supplier', label: '供应商', aliases: ['supplier', 'vendor_name', '供应商', '供应厂商'] },
{ key: 'asset_status', label: '资产状态', aliases: ['asset_status', '资产状态'] },
{ key: 'quantity', label: '数量', aliases: ['quantity', '数量'] },
{ key: 'acquisition_date', label: '取得时间', aliases: ['acquisition_date', 'acquired_date', '取得时间', '取得日期'] },
] as const;
const INLINE_DIALOG_PAGE_SIZE = 15;
@@ -362,6 +371,18 @@ function buildFixedAssetInlineTable(rawHeaders: string[], dataRows: string[][]):
const canonicalHeaders = FIXED_ASSET_CANONICAL_COLUMNS.map((column) => column.key);
const allRows = dataRows.map((row, rowIndex) => FIXED_ASSET_CANONICAL_COLUMNS.map((column) => {
if (column.key === 'id') return String(rowIndex + 1);
if (column.key === 'image') {
const assetIdColumnIndex = findInlineTableHeaderIndex(rawHeaders, ['asset_id', 'asset_no', '资产编号']);
const rawAssetId = assetIdColumnIndex >= 0 ? row[assetIdColumnIndex] ?? '' : '';
const normalizedAssetId = String(rawAssetId ?? '').trim();
const imageColumnIndex = findInlineTableHeaderIndex(rawHeaders, ['image', 'picture', '图片']);
const rawImageValue = imageColumnIndex >= 0 ? row[imageColumnIndex] ?? '' : '';
const normalizedImageValue = String(rawImageValue ?? '').trim();
if (normalizedImageValue) {
return normalizeInlineTableCell(normalizedImageValue);
}
return normalizedAssetId ? '查看' : '无';
}
const columnIndex = findInlineTableHeaderIndex(rawHeaders, [...column.aliases]);
const rawValue = columnIndex >= 0 ? row[columnIndex] ?? '' : '';
const normalizedValue = column.key === 'acquisition_date'
@@ -488,6 +509,33 @@ const activeInlinePageRows = computed(() => {
});
const activeInlineRangeStart = computed(() => (activeInlineFilteredRows.value.length === 0 ? 0 : (inlineDialogPage.value - 1) * INLINE_DIALOG_PAGE_SIZE + 1));
const activeInlineRangeEnd = computed(() => Math.min(inlineDialogPage.value * INLINE_DIALOG_PAGE_SIZE, activeInlineFilteredRows.value.length));
const currentUserEmployeeId = computed(() => String(authStore.user?.employee_id || '').trim());
/**
* 判断当前文件是否命中“仅指定工号可下载”的特殊管控。
* AI 触发时机:当聊天内嵌 CSV 预览头部要决定是否展示【下载数据】按钮,或真正执行下载前需要二次校验时调用。
* 核心逻辑:仅对 `资产明细全量导出表.csv` 启用强限制,其他附件继续沿用现有下载能力,避免误伤普通文件预览。
* 参数约束:传入文件名允许为空;空值或非目标文件一律视为不命中管控。
*/
function requiresRestrictedInlineDownload(file: InlineDownloadFile | null | undefined): boolean {
const fileName = String(file?.name || '').trim();
return fileName === RESTRICTED_INLINE_DOWNLOAD_FILE_NAME;
}
/**
* 校验当前用户是否有权下载当前内嵌文件。
* AI 触发时机:当页面需要控制【下载数据】按钮显隐,或下载函数执行前做权限兜底时调用。
* 核心逻辑:命中特殊管控文件时,只放行工号 `17070141`;其余文件保持原权限不变。
* 参数约束:仅负责前端展示层和交互层兜底,不替代后端鉴权;若后续接入通用权限系统,应优先复用统一能力。
*/
function canDownloadInlineFile(file: InlineDownloadFile | null | undefined): boolean {
if (!requiresRestrictedInlineDownload(file)) {
return true;
}
return currentUserEmployeeId.value === INLINE_DOWNLOAD_ALLOWED_EMPLOYEE_ID;
}
const canDownloadActiveInlineFile = computed(() => canDownloadInlineFile(activeInlineDialogEntry.value?.file));
watch(activeInlineTotalPages, (totalPages) => {
if (inlineDialogPage.value > totalPages) {
@@ -543,14 +591,32 @@ function changeInlineDialogPage(nextPage: number): void {
function canOpenInlineAssetHistory(cellIndex: number, cellValue: string): boolean {
const normalizedValue = String(cellValue || '').trim();
return cellIndex === activeInlineFilterIndexes.value.assetId && !!normalizedValue && normalizedValue !== '-';
const imageIndex = activeInlineDialogEntry.value?.table.rawHeaders.findIndex((header) => header === 'image' || header === '图片') ?? -1;
if (cellIndex === activeInlineFilterIndexes.value.assetId) {
return !!normalizedValue && normalizedValue !== '-';
}
if (cellIndex === imageIndex) {
return true;
}
return false;
}
function openInlineAssetHistory(row: string[]): void {
function isInlineHighlightHeader(header: string): boolean {
return header === '资产编号' || header === '图片';
}
async function openInlineAssetHistory(row: string[], cellIndex: number): Promise<void> {
const indexes = activeInlineFilterIndexes.value;
const assetId = indexes.assetId >= 0 ? String(row[indexes.assetId] || '').trim() : '';
const assetName = indexes.assetName >= 0 ? String(row[indexes.assetName] || '').trim() : '';
if (!assetId || assetId === '-') return;
const imageIndex = activeInlineDialogEntry.value?.table.rawHeaders.findIndex((header) => header === 'image' || header === '图片') ?? -1;
closeInlinePreviewDialog();
await nextTick();
if (cellIndex === imageIndex) {
handlers.openAssetImage(assetId, assetName === '-' ? '' : assetName);
return;
}
handlers.openAssetHistory(assetId, assetName === '-' ? '' : assetName);
}
@@ -560,6 +626,9 @@ function openInlineAssetHistory(row: string[]): void {
* @param file - 从当前消息内容解析出的单个可下载文件。
*/
function handleInlineDownload(file: InlineDownloadFile): void {
if (!canDownloadInlineFile(file)) {
return;
}
const table = buildInlinePreviewTable(file);
if (!table.isCsv || table.headers.length === 0) {
handlers.downloadInlineFile(file);
@@ -854,6 +923,7 @@ function handleInlineDownload(file: InlineDownloadFile): void {
</div>
<div class="flex items-center gap-2">
<button
v-if="canDownloadActiveInlineFile"
type="button"
class="inline-flex items-center gap-2 rounded-xl border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-medium text-brand-700 transition hover:bg-brand-100"
@click="handleInlineDownload(activeInlineDialogEntry.file)"
@@ -909,7 +979,10 @@ function handleInlineDownload(file: InlineDownloadFile): void {
<th
v-for="(header, headerIndex) in activeInlineDialogEntry.table.headers"
:key="`${activeInlineDialogEntry.file.name}-dialog-header-${headerIndex}`"
class="border border-slate-200 px-3 py-2 text-left font-semibold text-primary"
:class="[
'border border-slate-200 px-3 py-2 text-left font-semibold',
isInlineHighlightHeader(header) ? 'text-blue-800' : 'text-primary',
]"
>
{{ header || '-' }}
</th>
@@ -929,8 +1002,8 @@ function handleInlineDownload(file: InlineDownloadFile): void {
<button
v-if="canOpenInlineAssetHistory(cellIndex, cell)"
type="button"
class="whitespace-pre-wrap break-all text-left font-medium text-brand-600 underline-offset-2 transition hover:underline"
@click="openInlineAssetHistory(row)"
class="whitespace-pre-wrap break-all text-left font-semibold text-blue-700 underline-offset-2 transition hover:text-blue-800 hover:underline"
@click="openInlineAssetHistory(row, cellIndex)"
>
{{ cell || '-' }}
</button>
@@ -1030,6 +1103,21 @@ function handleInlineDownload(file: InlineDownloadFile): void {
font-weight: 600;
}
:deep(.chat-markdown .chat-fixed-asset-highlight-header) {
color: rgb(30 64 175);
}
:deep(.chat-markdown .chat-asset-history-link) {
color: rgb(29 78 216);
font-weight: 600;
text-decoration: none;
}
:deep(.chat-markdown .chat-asset-history-link:hover) {
color: rgb(30 64 175);
text-decoration: underline;
}
:deep(.dark .chat-markdown th),
:deep(.dark .chat-markdown td) {
border-color: rgb(51 65 85);
@@ -1039,6 +1127,15 @@ function handleInlineDownload(file: InlineDownloadFile): void {
background: rgb(30 41 59);
}
:deep(.dark .chat-markdown .chat-fixed-asset-highlight-header),
:deep(.dark .chat-markdown .chat-asset-history-link) {
color: rgb(147 197 253);
}
:deep(.dark .chat-markdown .chat-asset-history-link:hover) {
color: rgb(191 219 254);
}
:deep(.chat-markdown details) {
margin-top: 1rem;
border: 1px solid rgb(226 232 240);
@@ -15,6 +15,9 @@ interface MaintenanceDeviceResultPayload {
matched?: boolean;
device?: MaintenanceDevice;
records?: MaintenanceRecord[];
summary?: {
ledgerMatched?: boolean;
};
actions?: Array<{ id: string; label: string }>;
}
@@ -32,6 +35,8 @@ const payload = computed<MaintenanceDeviceResultPayload | null>(() => {
const device = computed(() => payload.value?.device || null);
const records = computed(() => payload.value?.records || []);
const hasResult = computed(() => Boolean(device.value || records.value.length));
const ledgerMatched = computed(() => payload.value?.summary?.ledgerMatched !== false);
const statusLabel = computed(() => {
const status = device.value?.deviceStatus;
@@ -67,15 +72,20 @@ const rows = computed(() => {
</script>
<template>
<section v-if="device" class="mt-3 rounded-xl border border-slate-300 bg-white p-3 text-sm text-slate-800 shadow-sm">
<section v-if="hasResult" class="mt-3 rounded-xl border border-slate-300 bg-white p-3 text-sm text-slate-800 shadow-sm">
<div class="flex items-center justify-between gap-3 rounded-t-lg border border-slate-200 bg-slate-50 px-3 py-2">
<h3 class="font-semibold">{{ t('maintenance.chat.deviceLedgerInfo') }}</h3>
<span class="rounded-full bg-emerald-50 px-2.5 py-0.5 text-xs font-semibold text-emerald-700">
{{ t('maintenance.chat.matched') }}
<h3 class="font-semibold">
{{ device ? t('maintenance.chat.deviceLedgerInfo') : t('maintenance.chat.recordInfo') }}
</h3>
<span
class="rounded-full px-2.5 py-0.5 text-xs font-semibold"
:class="ledgerMatched ? 'bg-emerald-50 text-emerald-700' : 'bg-amber-50 text-amber-700'"
>
{{ ledgerMatched ? t('maintenance.chat.matched') : t('maintenance.chat.recordMatched') }}
</span>
</div>
<div class="overflow-hidden border-x border-b border-slate-200">
<div v-if="device" class="overflow-hidden border-x border-b border-slate-200">
<table class="w-full table-fixed text-sm">
<tbody>
<tr v-for="(row, rowIndex) in rows" :key="rowIndex" class="border-t border-slate-200 first:border-t-0">
@@ -16,6 +16,21 @@ interface UseChatAssetHistoryOptions {
warn: (message: string) => void;
}
/**
* 把后端返回的技术性错误翻译成用户可理解的提示。
* AI 触发时机:当资产履历查询失败,但原始错误包含英文配置名、共享盘术语等技术细节时调用。
* 核心逻辑:优先识别已知的履历共享盘配置异常,返回面向业务用户的中文说明;其他错误保持原文,避免吞掉真实上下文。
* 参数约束:仅处理展示文案,不改变错误对象本身;返回值必须适合作为 toast/警告弹窗直接展示。
*/
function normalizeAssetHistoryErrorMessage(message: string): string {
const normalizedMessage = String(message || '').trim();
const lowerCaseMessage = normalizedMessage.toLowerCase();
if (lowerCaseMessage.includes('asset history share is not configured')) {
return '当前系统暂未配置资产履历文件目录,暂时无法查看履历,请联系管理员处理。';
}
return normalizedMessage || '检索资产履历失败';
}
export function useChatAssetHistory(options: UseChatAssetHistoryOptions) {
const open = ref(false);
const loading = ref(false);
@@ -35,7 +50,7 @@ export function useChatAssetHistory(options: UseChatAssetHistoryOptions) {
* 检索资产履历并直接打开最佳预览结果。
* AI 触发时机:当用户点击聊天表格中的“资产编号”,希望直接查看该资产履历时调用。
* 核心逻辑:点击后先切入“检索中”状态,再按“资产编号 + 资产名称”查询共享盘候选文件,命中后默认取排序最优的第一条直接预览;
* 未命中或查询失败时,仅给用户展示友好提示,不再弹出中间候选列表。
* 未命中或查询失败时,仅给用户展示友好提示,不再弹出中间候选列表;若后端返回技术性英文报错,会先转换成业务可读提示。
* 参数约束:至少要提供资产编号或资产名称之一;候选文件排序由后端负责,本方法默认信任第一条结果。
*/
const openHistory = async (nextAssetId: string, nextAssetName = '') => {
@@ -69,7 +84,8 @@ export function useChatAssetHistory(options: UseChatAssetHistoryOptions) {
}
await openHistoryFilePreview(bestMatch);
} catch (err: unknown) {
const message = err instanceof Error ? err.message : '检索资产履历失败';
const rawMessage = err instanceof Error ? err.message : '检索资产履历失败';
const message = normalizeAssetHistoryErrorMessage(rawMessage);
error.value = message;
options.warn(`履历查询失败:${message}`);
} finally {
@@ -0,0 +1,89 @@
/**
* features/chat/composables/useChatAssetImage.ts
* 用途:管理固定资产图片检索、友好提示与预览跳转。
* 依赖:chat.api、useChatSourceFiles 暴露的 openPreview、聊天提示消息。
* 逻辑:用户点击“图片 -> 查看”后,本 composable 统一向后端索要最佳图片,再复用现有文件预览弹窗在站内展示。
*/
import { ref } from 'vue';
import type { ComputedRef } from 'vue';
import { resolveAssetImagePreview } from '../api/chat.api';
import type { SourceFileLink } from '../types/chat.types';
interface UseChatAssetImageOptions {
agentId: ComputedRef<number>;
openPreviewGallery: (files: SourceFileLink[], initialIndex?: number) => Promise<void>;
warn: (message: string) => void;
}
/**
* 把后端返回的图片检索错误翻译成业务用户能看懂的提示。
* AI 触发时机:当用户点击“图片 -> 查看”失败,但原始报错包含接口路径、外部系统术语等技术细节时调用。
* 核心逻辑:优先识别已知的配置/检索异常并转成中文说明;未知错误保留原始文本,方便排查。
* 参数与输出约束:只负责展示文案,不吞掉真实错误对象;返回值必须适合作为 toast 直接展示。
*/
function normalizeAssetImageErrorMessage(message: string): string {
const normalizedMessage = String(message || '').trim();
const lowerCaseMessage = normalizedMessage.toLowerCase();
if (lowerCaseMessage.includes('固定资产图片文档库未配置')) {
return '当前系统暂未配置固定资产图片文档库,暂时无法查看图片,请联系管理员处理。';
}
if (lowerCaseMessage.includes('未找到资产')) {
return normalizedMessage;
}
return normalizedMessage || '检索固定资产图片失败';
}
export function useChatAssetImage(options: UseChatAssetImageOptions) {
const loading = ref(false);
/**
* 检索固定资产图片并直接打开预览。
* AI 触发时机:当用户点击聊天表格或 CSV 预览里的“图片 -> 查看”时调用。
* 核心逻辑:先向后端请求全部命中的图片文件,再把图片组交给通用 FilePreviewModal 预览。
* 参数约束:至少要提供资产编号或资产名称之一;后端负责登录外部文档库和挑选最佳图片。
*/
const openImage = async (nextAssetId: string, nextAssetName = '') => {
const normalizedAssetId = String(nextAssetId || '').trim();
const normalizedAssetName = String(nextAssetName || '').trim();
if (loading.value) return;
if (!normalizedAssetId && !normalizedAssetName) {
options.warn('当前资产缺少可用于检索图片的编号或名称');
return;
}
loading.value = true;
try {
const result = await resolveAssetImagePreview(options.agentId.value, {
asset_id: normalizedAssetId,
asset_name: normalizedAssetName,
});
const items = Array.isArray(result?.items) && result.items.length
? result.items
: (result?.item ? [result.item] : []);
if (!items.length) {
const displayName = normalizedAssetId || normalizedAssetName;
options.warn(`未找到资产 ${displayName} 的图片文件,请联系管理员补充。`);
return;
}
await options.openPreviewGallery(
items.map((item) => ({
name: item.name,
url: item.url,
actualExt: item.actual_ext,
})),
0,
);
} catch (err: unknown) {
const rawMessage = err instanceof Error ? err.message : '检索固定资产图片失败';
const message = normalizeAssetImageErrorMessage(rawMessage);
options.warn(`图片查询失败:${message}`);
} finally {
loading.value = false;
}
};
return {
loading,
openImage,
};
}
@@ -26,6 +26,7 @@ import { useChatSessions } from './useChatSessions';
import { useChatShipping } from './useChatShipping';
import { useChatSourceFiles } from './useChatSourceFiles';
import { useChatAssetHistory } from './useChatAssetHistory';
import { useChatAssetImage } from './useChatAssetImage';
import { useChatStore } from '../stores/chat.store';
import { useTrainingWorkspace } from './useTrainingWorkspace';
import { matchesTrainingAgent } from '../training/trainingWorkspace.utils';
@@ -159,6 +160,8 @@ export function useChatPage() {
const {
filePreviewVisible,
previewFile,
previewFiles,
currentPreviewIndex,
getSourceTitle,
getSourceMeta,
getSourceBrief,
@@ -167,6 +170,8 @@ export function useChatPage() {
getDisplayRetrieverResources,
shouldExpandSourceDetails,
openPreview,
openPreviewGallery,
setPreviewFileIndex,
parsePlmPreviewLink,
} = sourceFiles;
const assetHistory = useChatAssetHistory({
@@ -174,6 +179,11 @@ export function useChatPage() {
openPreview,
warn: (text) => msg.warning(text),
});
const assetImage = useChatAssetImage({
agentId: currentAgentId,
openPreviewGallery,
warn: (text) => msg.warning(text),
});
watch(currentAgentId, (id) => {
chatStore.setCurrentAgentId(id > 0 ? id : null);
@@ -318,6 +328,8 @@ export function useChatPage() {
resetPeripheralState,
filePreviewVisible,
previewFile,
previewFiles,
currentPreviewIndex,
});
({ loadConversation, startNewChat } = conversationApi);
@@ -366,6 +378,7 @@ export function useChatPage() {
parsePlmPreviewLink,
openPreview,
openAssetHistory: assetHistory.openHistory,
openAssetImage: assetImage.openImage,
getMessageLinks,
getDisplayRetrieverResources,
getSourceLinks,
@@ -507,6 +520,7 @@ export function useChatPage() {
queryPreviewError: queryPreview.error,
queryPreviewState: queryPreview.state,
assetHistory,
assetImage,
...agent,
agentGuides: chatGuides.guides,
showGuideModal: chatGuides.showModal,
@@ -517,6 +531,9 @@ export function useChatPage() {
...attachmentApi,
filePreviewVisible,
previewFile,
previewFiles,
currentPreviewIndex,
setPreviewFileIndex,
isSidebarOpen,
sidebarCollapsed,
toggleBrowserPanel: browser.toggle,
@@ -1,4 +1,4 @@
/**
/**
* features/chat/composables/useChatSourceFiles.ts
* 检索来源 / 源文件链接解析与预览。
*/
@@ -204,6 +204,8 @@ export interface UseChatSourceFilesOptions {
export function useChatSourceFiles({ agentId, t, msg, isMobile }: UseChatSourceFilesOptions) {
const filePreviewVisible = ref(false);
const previewFile = ref<{ name: string; url: string; actualExt?: string } | null>(null);
const previewFiles = ref<Array<{ name: string; url: string; actualExt?: string }>>([]);
const currentPreviewIndex = ref(0);
const getSourceTitle = (item: Record<string, unknown>) =>
String(item?.document_name || item?.title || item?.source || 'Untitled Source');
@@ -398,6 +400,8 @@ export function useChatSourceFiles({ agentId, t, msg, isMobile }: UseChatSourceF
window.location.href = resolvedFile.url;
return;
}
previewFiles.value = [resolvedFile];
currentPreviewIndex.value = 0;
previewFile.value = resolvedFile;
filePreviewVisible.value = true;
} catch (error: unknown) {
@@ -406,6 +410,55 @@ export function useChatSourceFiles({ agentId, t, msg, isMobile }: UseChatSourceF
}
};
/**
* 打开多文件预览组,并支持在同一弹窗内切换。
* AI 触发时机:当后端一次返回同资产的多张图片,需要在当前系统内左右切换查看时调用。
* 核心逻辑:先解析每个文件的可预览 URL,再把文件列表和初始索引写入共享弹窗状态。
* 参数与输出约束:files 必须至少有 1 个可预览项;initialIndex 会被钳制到合法范围。
*/
const openPreviewGallery = async (files: SourceFileLink[], initialIndex = 0) => {
const normalizedFiles = Array.isArray(files) ? files : [];
if (!normalizedFiles.length) {
msg.warning(t('chat.previewUnavailable'));
return;
}
try {
const resolvedFiles = await Promise.all(normalizedFiles.map((file) => resolveSourceLink(file)));
if (!resolvedFiles.length) {
msg.warning(t('chat.previewUnavailable'));
return;
}
const safeIndex = Math.min(Math.max(initialIndex, 0), resolvedFiles.length - 1);
const initialFile = resolvedFiles[safeIndex] || resolvedFiles[0];
if (!initialFile) {
msg.warning(t('chat.previewUnavailable'));
return;
}
if (shouldBypassEmbeddedPreview(initialFile)) {
window.location.href = initialFile.url;
return;
}
previewFiles.value = resolvedFiles;
currentPreviewIndex.value = safeIndex;
previewFile.value = initialFile;
filePreviewVisible.value = true;
} catch (error: unknown) {
const message = error instanceof Error ? error.message : t('chat.previewUnavailable');
msg.warning(message);
}
};
/**
* 切换当前预览中的文件索引。
* 用途:供 FilePreviewModal 在多图模式下切换上一张、下一张或缩略图点击时回写当前文件。
*/
const setPreviewFileIndex = (nextIndex: number) => {
if (!previewFiles.value.length) return;
const safeIndex = Math.min(Math.max(nextIndex, 0), previewFiles.value.length - 1);
currentPreviewIndex.value = safeIndex;
previewFile.value = previewFiles.value[safeIndex] || null;
};
const parsePlmPreviewLink = (href: string): SourceFileLink | null => {
const rawHref = (href || '').trim();
if (!rawHref.startsWith('#plm-preview?')) return null;
@@ -419,6 +472,8 @@ export function useChatSourceFiles({ agentId, t, msg, isMobile }: UseChatSourceF
return {
filePreviewVisible,
previewFile,
previewFiles,
currentPreviewIndex,
getSourceTitle,
getSourceMeta,
getSourceBrief,
@@ -427,6 +482,8 @@ export function useChatSourceFiles({ agentId, t, msg, isMobile }: UseChatSourceF
getDisplayRetrieverResources,
shouldExpandSourceDetails,
openPreview,
openPreviewGallery,
setPreviewFileIndex,
parsePlmPreviewLink,
};
}
@@ -31,6 +31,8 @@ export interface ChatPageConversationContext {
resetPeripheralState: () => void;
filePreviewVisible: Ref<boolean>;
previewFile: Ref<unknown>;
previewFiles: Ref<unknown[]>;
currentPreviewIndex: Ref<number>;
}
export function createChatPageConversationApi(ctx: ChatPageConversationContext) {
@@ -76,6 +78,8 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
ctx.resetPeripheralState();
ctx.filePreviewVisible.value = false;
ctx.previewFile.value = null;
ctx.previewFiles.value = [];
ctx.currentPreviewIndex.value = 0;
void ctx.router.replace({ path: ctx.route.path, query: {} });
};
@@ -89,6 +93,8 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
ctx.resetPeripheralState();
ctx.filePreviewVisible.value = false;
ctx.previewFile.value = null;
ctx.previewFiles.value = [];
ctx.currentPreviewIndex.value = 0;
};
return { loadConversation, startNewChat, resetChatStateForAgentChange };
@@ -65,6 +65,7 @@ export interface ChatPageMarkdownContext {
parsePlmPreviewLink: (href: string) => SourceFileLink | null;
openPreview: (file: SourceFileLink) => Promise<void>;
openAssetHistory: (assetId: string, assetName?: string) => void;
openAssetImage: (assetId: string, assetName?: string) => void;
getMessageLinks: (message: Record<string, unknown>) => SourceFileLink[];
getDisplayRetrieverResources: (msgItem: Record<string, unknown>) => Record<string, unknown>[];
getSourceLinks: (resources?: unknown[]) => SourceFileLink[];
@@ -185,14 +186,109 @@ function normalizeAssetHistoryText(value: string): string {
return normalized;
}
const FIXED_ASSET_TABLE_TARGET_HEADERS = [
'序号',
'资产编号',
'资产名称',
'保管人',
'保管部门',
'图片',
'账套',
'供应商',
'资产状态',
'数量',
'取得时间',
];
const FIXED_ASSET_TABLE_HEADER_ALIASES: Record<string, string[]> = {
序号: ['序号', 'id'],
资产编号: ['资产编号', 'asset_id', 'asset_no'],
资产名称: ['资产名称', 'asset_name'],
保管人: ['保管人', '保管人姓名', 'custodian_name', 'custodian_person'],
保管部门: ['保管部门', '保管部门名称', 'department_name', 'custodian_dept'],
图片: ['图片', 'image', 'picture'],
账套: ['账套', 'account_period', 'operating_center_code'],
供应商: ['供应商', '供应厂商', 'supplier', 'vendor_name'],
资产状态: ['资产状态', 'asset_status'],
数量: ['数量', 'quantity'],
取得时间: ['取得时间', '取得日期', 'acquisition_date', 'acquired_date'],
};
function normalizeFixedAssetHeader(value: string): string {
const normalized = normalizeAssetHistoryText(value).toLowerCase();
if (!normalized) return '';
const targetHeader = FIXED_ASSET_TABLE_TARGET_HEADERS.find((header) => (
(FIXED_ASSET_TABLE_HEADER_ALIASES[header] || []).some((alias) => alias.toLowerCase() === normalized)
));
return targetHeader || '';
}
function isFixedAssetPreviewTable(headerLabels: string[]): boolean {
const normalizedHeaders = headerLabels
.map((label) => normalizeFixedAssetHeader(label))
.filter(Boolean);
return ['资产编号', '资产名称', '保管人', '保管部门', '账套', '资产状态', '数量', '取得时间']
.every((header) => normalizedHeaders.includes(header));
}
/**
* 把聊天结果表格里的“资产编号”列增强为可点击入口。
* 核心逻辑:只处理包含“资产编号”表头的表格,并从同行“资产名称”列一并带出检索关键词,避免误伤其他普通 Markdown 表格。
* 将 Dify 返回的旧版固定资产表格收敛成统一展示列顺序。
* 核心逻辑:按中文/英文别名识别表头后重建 thead/tbody,并补出“图片=查看”列,让旧会话与新会话都按同一业务结构展示。
*/
function normalizeFixedAssetPreviewTables(container: HTMLElement): void {
const tables = Array.from(container.querySelectorAll('table'));
tables.forEach((table) => {
const headerCells = Array.from(table.querySelectorAll('thead th'));
if (headerCells.length === 0) return;
const headerLabels = headerCells.map((cell) => normalizeAssetHistoryText(cell.textContent || ''));
if (!isFixedAssetPreviewTable(headerLabels)) return;
const headerIndexMap = new Map<string, number>();
headerLabels.forEach((label, index) => {
const normalized = normalizeFixedAssetHeader(label);
if (normalized && !headerIndexMap.has(normalized)) {
headerIndexMap.set(normalized, index);
}
});
const bodyRows = Array.from(table.querySelectorAll('tbody tr'));
const normalizedRows = bodyRows.map((row, rowIndex) => {
const cells = Array.from(row.querySelectorAll('td'));
const pickCellText = (header: string): string => {
if (header === '序号') return String(rowIndex + 1);
if (header === '图片') {
const assetIdIndex = headerIndexMap.get('资产编号');
const assetId = assetIdIndex !== undefined ? normalizeAssetHistoryText(cells[assetIdIndex]?.textContent || '') : '';
return assetId ? '查看' : '无';
}
const cellIndex = headerIndexMap.get(header);
return cellIndex !== undefined ? normalizeAssetHistoryText(cells[cellIndex]?.textContent || '') || '无' : '无';
};
return FIXED_ASSET_TABLE_TARGET_HEADERS.map((header) => pickCellText(header));
});
const thead = table.querySelector('thead');
const tbody = table.querySelector('tbody');
if (!thead || !tbody) return;
thead.innerHTML = `<tr>${FIXED_ASSET_TABLE_TARGET_HEADERS.map((header) => (
`<th class="${header === '资产编号' || header === '图片' ? 'chat-fixed-asset-highlight-header' : ''}">${header}</th>`
)).join('')}</tr>`;
tbody.innerHTML = normalizedRows.map((row) => (
`<tr>${row.map((cell) => `<td>${cell || '无'}</td>`).join('')}</tr>`
)).join('');
});
}
/**
* 把聊天结果表格里的“资产编号”和“图片”列增强为可点击入口。
* 核心逻辑:只处理包含“资产编号”表头的表格,并从同行“资产名称”列一并带出检索关键词;资产编号走履历检索,图片走图片预览检索。
*/
function enhanceAssetHistoryTableLinks(html: string): string {
if (!html || typeof document === 'undefined' || !html.includes('<table')) return html;
const container = document.createElement('div');
container.innerHTML = html;
normalizeFixedAssetPreviewTables(container);
const tables = Array.from(container.querySelectorAll('table'));
tables.forEach((table) => {
const headerCells = Array.from(table.querySelectorAll('thead th'));
@@ -201,6 +297,7 @@ function enhanceAssetHistoryTableLinks(html: string): string {
const assetIdIndex = headerLabels.findIndex((label) => label === '资产编号');
if (assetIdIndex < 0) return;
const assetNameIndex = headerLabels.findIndex((label) => label === '资产名称');
const imageIndex = headerLabels.findIndex((label) => label === '图片');
const rows = Array.from(table.querySelectorAll('tbody tr'));
rows.forEach((row) => {
const cells = Array.from(row.querySelectorAll('td'));
@@ -215,6 +312,18 @@ function enhanceAssetHistoryTableLinks(html: string): string {
link.textContent = assetId;
assetIdCell.innerHTML = '';
assetIdCell.appendChild(link);
if (imageIndex >= 0) {
const imageCell = cells[imageIndex];
if (!imageCell) return;
const imageText = normalizeAssetHistoryText(imageCell.textContent || '') || '查看';
const imageLink = document.createElement('a');
imageLink.href = `#asset-image?asset_id=${encodeURIComponent(assetId)}&asset_name=${encodeURIComponent(assetName)}`;
imageLink.className = 'chat-asset-history-link';
imageLink.textContent = imageText;
imageCell.innerHTML = '';
imageCell.appendChild(imageLink);
}
});
});
return container.innerHTML;
@@ -295,6 +404,12 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
ctx.openAssetHistory((params.get('asset_id') || '').trim(), (params.get('asset_name') || '').trim());
return;
}
if (rawHref.startsWith('#asset-image?')) {
event.preventDefault();
const params = new URLSearchParams(rawHref.slice('#asset-image?'.length));
ctx.openAssetImage((params.get('asset_id') || '').trim(), (params.get('asset_name') || '').trim());
return;
}
const preview = ctx.parsePlmPreviewLink(rawHref);
if (preview) {
event.preventDefault();
@@ -333,6 +448,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
renderMarkdown,
onMarkdownClick: handleChatMarkdownClick,
openAssetHistory: ctx.openAssetHistory,
openAssetImage: ctx.openAssetImage,
getInlineDownloadFiles: safeExtractInlineDownloadFiles,
downloadInlineFile,
getShippingInventoryMappingPayload: ctx.getShippingInventoryMappingPayload,
@@ -119,6 +119,25 @@ export interface AssetHistorySearchResult {
items: AssetHistoryFileItem[];
}
export interface AssetImageFileItem {
item_id: string;
version_id: string;
attachment_id: string;
name: string;
relative_path: string;
url: string;
actual_ext?: string;
size_bytes?: number;
}
export interface AssetImageResolveResult {
asset_id?: string;
asset_name?: string;
item: AssetImageFileItem;
items: AssetImageFileItem[];
total: number;
}
export interface ChatUploadResult {
id: string;
name?: string;
@@ -439,34 +439,30 @@ onMounted(loadRecords);
</div>
<div class="min-h-0 overflow-auto rounded-xl border border-default bg-surface">
<table class="min-w-full text-left text-sm">
<table class="w-full table-fixed text-left text-sm">
<thead class="bg-muted/50 text-secondary">
<tr>
<th class="px-3 py-2">{{ t('maintenance.record.table.deviceCode') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.deviceName') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.modelSpec') }}</th>
<th class="w-[24%] px-3 py-2">{{ t('maintenance.record.table.deviceCode') }}</th>
<th class="w-[22%] px-3 py-2">{{ t('maintenance.record.table.deviceName') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.faultDescription') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.status') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.repairer') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.operation') }}</th>
<th class="w-[14%] px-3 py-2">{{ t('maintenance.record.table.status') }}</th>
<th class="w-[18%] px-3 py-2 text-right">{{ t('maintenance.record.table.operation') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="loading">
<td colspan="7" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.record.table.loading') }}</td>
<td colspan="5" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.record.table.loading') }}</td>
</tr>
<tr v-else-if="!records.length">
<td colspan="7" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.record.table.empty') }}</td>
<td colspan="5" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.record.table.empty') }}</td>
</tr>
<tr v-for="record in records" v-else :key="record.id" class="border-t border-default">
<td class="px-3 py-2 font-semibold">{{ record.deviceCode }}</td>
<td class="px-3 py-2">{{ record.deviceName || '-' }}</td>
<td class="px-3 py-2">{{ record.modelSpec || '-' }}</td>
<td class="max-w-[260px] truncate px-3 py-2">{{ record.faultDescription }}</td>
<td class="truncate px-3 py-2 font-semibold" :title="record.deviceCode">{{ record.deviceCode }}</td>
<td class="truncate px-3 py-2" :title="record.deviceName || '-'">{{ record.deviceName || '-' }}</td>
<td class="truncate px-3 py-2" :title="record.faultDescription">{{ record.faultDescription }}</td>
<td class="px-3 py-2">{{ formatStatus(record.repairStatus) }}</td>
<td class="px-3 py-2">{{ record.repairer || '-' }}</td>
<td class="px-3 py-2">
<div class="flex gap-2">
<div class="flex justify-end gap-2">
<button type="button" class="admin-report-page-btn" @click="startEdit(record)">{{ t('maintenance.record.actions.edit') }}</button>
<button
type="button"