<script lang="ts" setup>
|
import type { FileType } from 'ant-design-vue/es/upload/interface';
|
import type { MenuRecordRaw } from '@vben/types';
|
|
import type { AgentConversationApi } from '#/api/agent/conversation';
|
import type { AgentTaskApi } from '#/api/agent/conversation';
|
|
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
|
import { Page } from '@vben/common-ui';
|
import { useAccessStore } from '@vben/stores';
|
import { downloadFileFromBlobPart } from '@vben/utils';
|
|
import { message } from 'ant-design-vue';
|
|
import {
|
agentImportErrorMessage,
|
createDocumentTask,
|
createAgentConversation,
|
deleteAgentConversation,
|
downloadAgentConversationAttachment,
|
downloadAgentReport,
|
getAgentCapabilities,
|
getAgentModels,
|
getAuthorizedAgentCapabilities,
|
getAgentConversation,
|
listAgentConversations,
|
sendAgentAction,
|
sendAgentMessage,
|
streamAgentConversationEvents,
|
uploadAgentAttachment,
|
} from '#/api/agent/conversation';
|
|
import TaskCenterDrawer from './components/TaskCenterDrawer.vue';
|
|
defineOptions({ name: 'AgentDataEntry' });
|
|
const accessStore = useAccessStore();
|
|
const MAX_BYTES = 8 * 1024 * 1024;
|
const ACCEPT = '.csv,.xlsx,.docx,.pdf';
|
|
const authorizationScope = ref('');
|
const models = ref<AgentConversationApi.BusinessModelInfo[]>([]);
|
const selectedModelId = ref<number>();
|
const conversations = ref<AgentConversationApi.ConversationSummary[]>([]);
|
const active = ref<AgentConversationApi.Conversation>();
|
const loading = ref(false);
|
const busy = ref(false);
|
const creating = ref(false);
|
const newOpen = ref(false);
|
const newScenarios = ref<string[]>([]);
|
const newText = ref('');
|
const newTimeRange = ref<string[]>([]);
|
const newRecordLimit = ref<number>();
|
const newIndustry = ref('');
|
const newSkipRestDays = ref(false);
|
const newRestDayDescription = ref('');
|
const newRegion = ref('');
|
type ConstraintKey =
|
| 'industry'
|
| 'instruction'
|
| 'record_limit'
|
| 'region'
|
| 'rest_day_description'
|
| 'scenario_paths'
|
| 'skip_rest_days'
|
| 'time_range';
|
const newPriorities = ref<Record<ConstraintKey, boolean>>({
|
industry: false,
|
instruction: false,
|
record_limit: false,
|
region: false,
|
rest_day_description: false,
|
scenario_paths: false,
|
skip_rest_days: false,
|
time_range: false,
|
});
|
const newFiles = ref<File[]>([]);
|
const newAttachmentIds = ref<number[]>([]);
|
const durableTasksEnabled = ref(false);
|
const taskCenter = ref<{ open: (taskId?: string) => Promise<void> }>();
|
const interruptFile = ref<File>();
|
const mappingDraft = ref<Record<string, string>>({});
|
const reviseText = ref('');
|
const syncMes = ref(true);
|
const eventState = ref<'connected' | 'connecting' | 'idle' | 'retrying'>('idle');
|
interface ExecutionProgress {
|
candidateCount: number;
|
issueCount: number;
|
label: string;
|
modelId?: number;
|
percent: number;
|
stage: string;
|
}
|
const executionProgress = ref<ExecutionProgress>();
|
let eventAbort: AbortController | undefined;
|
let eventGeneration = 0;
|
let eventRefreshTimer: ReturnType<typeof setTimeout> | undefined;
|
|
const attachmentPreview = ref<{
|
filename: string;
|
kind: 'image' | 'pdf';
|
open: boolean;
|
url: string;
|
}>({ filename: '', kind: 'image', open: false, url: '' });
|
|
const modelOptions = computed(() =>
|
models.value.map((model) => ({
|
label: `${model.name || model.model} · ${model.platform}`,
|
value: model.id,
|
})),
|
);
|
const interrupt = computed(() => active.value?.interrupts?.at(-1));
|
const card = computed(() => interrupt.value?.card);
|
const actions = computed(() => {
|
const list = [...(card.value?.actions ?? [])];
|
// 卡片可能在提交开关关闭时生成,以服务端当前开关为准补回确认动作
|
if (
|
card.value?.kind === 'preview' &&
|
active.value?.commit_enabled &&
|
!list.includes('confirm')
|
) {
|
list.push('confirm');
|
}
|
return list;
|
});
|
const isGatewayModule = computed(() => active.value?.module_id === 'mdm.item');
|
const previewValueLabels: Record<string, Record<string, string>> = {
|
status: { '0': '启用', '1': '停用' },
|
types: {
|
'1': 'IQC(来料检验)',
|
'2': 'IPQC(过程检验)',
|
'3': 'OQC(出货检验)',
|
'4': 'RQC(退料检验)',
|
},
|
};
|
const previewColumns = computed(() => [
|
{ title: '行号', dataIndex: 'row_index', key: 'row_index', width: 60 },
|
...(active.value?.row_fields ?? []).map((field) => ({
|
title: field.label,
|
dataIndex: field.name,
|
key: field.name,
|
width: 140,
|
customRender: ({ text }: { text: unknown }) =>
|
previewValueLabels[field.name]?.[String(text ?? '')] ?? text,
|
})),
|
]);
|
const previewRows = computed(() =>
|
(active.value?.rows ?? []).map((row, index) => ({
|
candidate_id: row.candidate_id,
|
row_index: index + 1,
|
...row.values,
|
})),
|
);
|
const eventStateText = computed(() => {
|
if (active.value?.finished) return '已同步';
|
return {
|
connected: '实时更新',
|
connecting: '正在连接',
|
idle: '未连接',
|
retrying: '断线重连',
|
}[eventState.value];
|
});
|
const eventStateColor = computed(() => {
|
if (active.value?.finished || eventState.value === 'connected') return 'green';
|
if (eventState.value === 'retrying') return 'orange';
|
return 'blue';
|
});
|
|
interface ScenarioOption {
|
description: string;
|
label: string;
|
name: string;
|
value: string;
|
}
|
|
function flattenMenuScenarios(
|
menus: MenuRecordRaw[],
|
parentNames: string[] = [],
|
): ScenarioOption[] {
|
return menus.flatMap((menu) => {
|
const names = [...parentNames, menu.name].filter(Boolean);
|
const current = menu.show === false
|
? []
|
: [
|
{
|
description: menu.path,
|
label: names.join(' / '),
|
name: menu.name,
|
value: menu.path,
|
},
|
];
|
return [
|
...current,
|
...flattenMenuScenarios(menu.children ?? [], names),
|
];
|
});
|
}
|
|
const scenarioOptions = computed(() => {
|
const seen = new Set<string>();
|
return flattenMenuScenarios(accessStore.accessMenus).filter((item) => {
|
if (!item.value || seen.has(item.value)) return false;
|
seen.add(item.value);
|
return true;
|
});
|
});
|
|
function togglePriority(key: ConstraintKey) {
|
newPriorities.value[key] = !newPriorities.value[key];
|
}
|
|
function buildConstraints(): AgentConversationApi.ConversationConstraints {
|
const scenarioByPath = new Map(
|
scenarioOptions.value.map((item) => [item.value, item.label]),
|
);
|
return {
|
industry: newIndustry.value.trim() || undefined,
|
instruction: newText.value.trim() || undefined,
|
priority_fields: Object.entries(newPriorities.value)
|
.filter(([, enabled]) => enabled)
|
.map(([key]) => key),
|
record_limit: newRecordLimit.value,
|
region: newRegion.value.trim() || undefined,
|
rest_day_description: newRestDayDescription.value.trim() || undefined,
|
scenario_paths: newScenarios.value.map((path) =>
|
`${scenarioByPath.get(path) ?? path} (${path})`,
|
),
|
skip_rest_days:
|
newSkipRestDays.value || newPriorities.value.skip_rest_days
|
? newSkipRestDays.value
|
: undefined,
|
time_end: newTimeRange.value[1],
|
time_start: newTimeRange.value[0],
|
};
|
}
|
|
function hasNewConditions() {
|
return Boolean(
|
newScenarios.value.length ||
|
newTimeRange.value.length ||
|
newRecordLimit.value ||
|
newIndustry.value.trim() ||
|
newSkipRestDays.value ||
|
newRestDayDescription.value.trim() ||
|
newRegion.value.trim(),
|
);
|
}
|
|
function resetNewConditions() {
|
newScenarios.value = [];
|
newText.value = '';
|
newTimeRange.value = [];
|
newRecordLimit.value = undefined;
|
newIndustry.value = '';
|
newSkipRestDays.value = false;
|
newRestDayDescription.value = '';
|
newRegion.value = '';
|
for (const key of Object.keys(newPriorities.value) as ConstraintKey[]) {
|
newPriorities.value[key] = false;
|
}
|
}
|
|
watch(
|
() => interrupt.value?.interrupt_id,
|
() => {
|
reviseText.value = '';
|
mappingDraft.value = {};
|
interruptFile.value = undefined;
|
const value = card.value?.sync_mes;
|
syncMes.value =
|
typeof value === 'boolean'
|
? value
|
: (active.value?.sync_mes ?? active.value?.mes_sync_default ?? true);
|
},
|
);
|
|
function statusText(status?: string) {
|
const map: Record<string, string> = {
|
SUCCEEDED: '导入成功',
|
PARTIAL_FAILED: '部分失败',
|
FAILED: '失败',
|
UNKNOWN: '结果未知',
|
RUNNING: '提交中',
|
attached: '已上传',
|
blocked: '已阻断',
|
cancelled: '已取消',
|
classified: '已识别场景',
|
commit_disabled: '未提交',
|
confirmed: '已确认',
|
created: '待上传文件',
|
queued: '排队处理中',
|
error: '出错',
|
failed: '失败',
|
mapping_applied: '映射已更新',
|
needs_review: '待确认',
|
parsed: '已解析',
|
preview_ready: '待确认',
|
revise: '待重新校验',
|
stale: '已过期,需重检',
|
validated: '待确认',
|
};
|
return map[status ?? ''] ?? status ?? '进行中';
|
}
|
|
function statusColor(status?: string) {
|
if (status === 'SUCCEEDED' || status === 'confirmed') return 'green';
|
if (
|
status === 'PARTIAL_FAILED' ||
|
status === 'revise' ||
|
status === 'stale'
|
) {
|
return 'orange';
|
}
|
if (
|
status === 'FAILED' ||
|
status === 'failed' ||
|
status === 'error' ||
|
status === 'blocked' ||
|
status === 'cancelled'
|
) {
|
return 'red';
|
}
|
return 'blue';
|
}
|
|
function checkFile(raw: File) {
|
const name = raw.name.toLowerCase();
|
if (!ACCEPT.split(',').some((ext) => name.endsWith(ext))) {
|
message.error('仅支持 CSV、XLSX、DOCX 或 PDF 文件');
|
return false;
|
}
|
if (raw.size > MAX_BYTES) {
|
message.error('文件不能超过 8 MiB');
|
return false;
|
}
|
return true;
|
}
|
|
function beforeNewUpload(fileInfo: FileType) {
|
const raw = fileInfo as unknown as File;
|
if (!checkFile(raw)) return false;
|
const duplicate = newFiles.value.some(
|
(item) =>
|
item.name === raw.name && item.size === raw.size && item.lastModified === raw.lastModified,
|
);
|
if (!duplicate) newFiles.value = [...newFiles.value, raw].slice(0, 20);
|
newAttachmentIds.value = [];
|
return false;
|
}
|
|
function clearNewFiles() {
|
newFiles.value = [];
|
newAttachmentIds.value = [];
|
}
|
|
function beforeInterruptUpload(fileInfo: FileType) {
|
const raw = fileInfo as unknown as File;
|
if (!checkFile(raw)) return false;
|
interruptFile.value = raw;
|
return false;
|
}
|
|
async function boot() {
|
loading.value = true;
|
try {
|
const [capabilities, authorization, list, modelList] = await Promise.all([
|
getAgentCapabilities(),
|
getAuthorizedAgentCapabilities(),
|
listAgentConversations({ page_size: 50 }),
|
getAgentModels().catch(() => []),
|
]);
|
authorizationScope.value = authorization.scope_summary;
|
models.value = modelList;
|
if (!selectedModelId.value) {
|
selectedModelId.value = active.value?.model_id ?? modelList[0]?.id;
|
}
|
const visibleScenarioPaths = new Set(scenarioOptions.value.map((item) => item.value));
|
newScenarios.value = newScenarios.value.filter((path) =>
|
visibleScenarioPaths.has(path),
|
);
|
durableTasksEnabled.value = capabilities.durable_tasks?.enabled ?? false;
|
conversations.value = list.items ?? [];
|
} catch (error) {
|
message.error(agentImportErrorMessage(error));
|
} finally {
|
loading.value = false;
|
}
|
}
|
|
async function ensureNewAttachments() {
|
if (newAttachmentIds.value.length === newFiles.value.length) {
|
return newAttachmentIds.value;
|
}
|
newAttachmentIds.value = [];
|
for (const file of newFiles.value) {
|
newAttachmentIds.value.push(await uploadAgentAttachment(file));
|
}
|
return newAttachmentIds.value;
|
}
|
|
async function reloadConversations() {
|
try {
|
const list = await listAgentConversations({ page_size: 50 });
|
conversations.value = list.items ?? [];
|
} catch {
|
// 列表刷新失败不阻塞主流程
|
}
|
}
|
|
function abortEventStream() {
|
eventGeneration += 1;
|
eventAbort?.abort();
|
eventAbort = undefined;
|
if (eventRefreshTimer) clearTimeout(eventRefreshTimer);
|
eventRefreshTimer = undefined;
|
eventState.value = 'idle';
|
}
|
|
async function refreshActive(conversationId: string) {
|
const snapshot = await getAgentConversation(conversationId);
|
if (active.value?.conversation_id !== conversationId) return;
|
active.value = snapshot;
|
await reloadConversations();
|
if (snapshot.finished) abortEventStream();
|
}
|
|
function queueEventRefresh(conversationId: string) {
|
if (eventRefreshTimer) clearTimeout(eventRefreshTimer);
|
eventRefreshTimer = setTimeout(() => {
|
eventRefreshTimer = undefined;
|
void refreshActive(conversationId).catch(() => {
|
// SSE 会继续重连,快照读取失败不重复弹窗打扰操作。
|
});
|
}, 120);
|
}
|
|
function handleConversationEvent(
|
conversationId: string,
|
event: AgentConversationApi.ConversationEvent,
|
) {
|
if (active.value?.conversation_id !== conversationId) return;
|
if (event.type === 'progress') {
|
const payload = event.payload;
|
executionProgress.value = {
|
candidateCount: Number(payload.candidate_count ?? 0),
|
issueCount: Number(payload.issue_count ?? 0),
|
label: String(payload.label ?? '正在处理'),
|
modelId:
|
typeof payload.model_id === 'number' ? payload.model_id : undefined,
|
percent: Math.min(100, Math.max(0, Number(payload.percent ?? 0))),
|
stage: String(payload.stage ?? 'processing'),
|
};
|
return;
|
}
|
queueEventRefresh(conversationId);
|
}
|
|
function waitForRetry(delay: number, signal: AbortSignal) {
|
return new Promise<void>((resolve) => {
|
const timer = setTimeout(resolve, delay);
|
signal.addEventListener(
|
'abort',
|
() => {
|
clearTimeout(timer);
|
resolve();
|
},
|
{ once: true },
|
);
|
});
|
}
|
|
function startEventStream(conversationId: string) {
|
abortEventStream();
|
const generation = eventGeneration;
|
const controller = new AbortController();
|
eventAbort = controller;
|
eventState.value = 'connecting';
|
void (async () => {
|
let cursor = 0;
|
let retryDelay = 1000;
|
while (!controller.signal.aborted && generation === eventGeneration) {
|
try {
|
cursor = await streamAgentConversationEvents(
|
conversationId,
|
cursor,
|
controller.signal,
|
(event) => handleConversationEvent(conversationId, event),
|
() => {
|
eventState.value = 'connected';
|
retryDelay = 1000;
|
},
|
);
|
if (!controller.signal.aborted) eventState.value = 'connecting';
|
} catch {
|
if (controller.signal.aborted) return;
|
eventState.value = 'retrying';
|
try {
|
await refreshActive(conversationId);
|
} catch {
|
// 轮询兜底失败后继续指数退避。
|
}
|
await waitForRetry(retryDelay, controller.signal);
|
retryDelay = Math.min(retryDelay * 2, 30_000);
|
}
|
}
|
})();
|
}
|
|
async function openConversation(conversationId: string) {
|
if (busy.value) return;
|
busy.value = true;
|
try {
|
const conversation = await getAgentConversation(conversationId);
|
active.value = conversation;
|
selectedModelId.value = conversation.model_id ?? models.value[0]?.id;
|
} catch (error) {
|
message.error(agentImportErrorMessage(error));
|
} finally {
|
busy.value = false;
|
}
|
}
|
|
function changeModel(value: number) {
|
selectedModelId.value = value;
|
}
|
|
async function createConversation() {
|
if (!newFiles.value.length && !newText.value.trim() && !hasNewConditions()) {
|
message.warning('请上传文件、填写补录说明或设置补录条件');
|
return;
|
}
|
creating.value = true;
|
try {
|
if (newFiles.value.length > 1) {
|
message.warning('多文件请使用后台分析,归并检查完成后再进入补录');
|
return;
|
}
|
const [attachmentId] = await ensureNewAttachments();
|
const description = newText.value.trim();
|
const baseTitle =
|
newFiles.value[0]?.name || description.slice(0, 60) || '新建补录';
|
active.value = await createAgentConversation({
|
attachment_id: attachmentId ? String(attachmentId) : undefined,
|
constraints: buildConstraints(),
|
model_id: selectedModelId.value,
|
text: description || undefined,
|
title: baseTitle,
|
});
|
newOpen.value = false;
|
clearNewFiles();
|
resetNewConditions();
|
await reloadConversations();
|
} catch (error) {
|
message.error(agentImportErrorMessage(error));
|
} finally {
|
creating.value = false;
|
}
|
}
|
|
async function startBackgroundAnalysis() {
|
if (!durableTasksEnabled.value) {
|
message.info('持久任务服务尚未启用');
|
return;
|
}
|
if (!newFiles.value.length) {
|
message.warning('后台分析需要先选择数据文件');
|
return;
|
}
|
creating.value = true;
|
try {
|
const attachmentIds = await ensureNewAttachments();
|
if (!attachmentIds.length) return;
|
const task = await createDocumentTask({
|
attachment_ids: attachmentIds,
|
constraints: buildConstraints(),
|
});
|
newOpen.value = false;
|
resetNewConditions();
|
message.success('后台分析任务已创建,可关闭页面后继续执行');
|
await taskCenter.value?.open(task.task_id);
|
} catch (error) {
|
message.error(agentImportErrorMessage(error));
|
} finally {
|
creating.value = false;
|
}
|
}
|
|
async function continueFromTask(task: AgentTaskApi.Task) {
|
if (task.result?.continuation_supported === false) {
|
message.info('多文件结果需先在证据明细中处理冲突,当前暂不进入单文件提交');
|
return;
|
}
|
const attachmentId = task.result?.attachment_id;
|
if (!attachmentId) {
|
message.error('任务结果缺少附件引用,无法进入补录');
|
return;
|
}
|
busy.value = true;
|
try {
|
active.value = await createAgentConversation({
|
attachment_id: String(attachmentId),
|
model_id: selectedModelId.value,
|
module_id: task.result?.module_id || undefined,
|
text: '后台文档分析已完成,请继续进行字段核验和补录确认。',
|
title: task.result?.filename || '后台分析补录',
|
});
|
await reloadConversations();
|
message.success('已进入补录确认流程');
|
} catch (error) {
|
message.error(agentImportErrorMessage(error));
|
} finally {
|
busy.value = false;
|
}
|
}
|
|
async function apply(result: AgentConversationApi.Conversation, tip?: string) {
|
active.value = result;
|
selectedModelId.value = result.model_id ?? selectedModelId.value;
|
if (tip) message.success(tip);
|
await reloadConversations();
|
}
|
|
async function act(
|
action: string,
|
payload: Record<string, unknown> = {},
|
tip?: string,
|
) {
|
const current = active.value;
|
const pending = interrupt.value;
|
if (!current || !pending) return;
|
busy.value = true;
|
try {
|
const result = await sendAgentAction(current.conversation_id, {
|
action,
|
interrupt_id: pending.interrupt_id,
|
model_id: selectedModelId.value,
|
payload,
|
revision: pending.revision,
|
});
|
await apply(result, tip);
|
} catch (error) {
|
message.error(agentImportErrorMessage(error));
|
} finally {
|
busy.value = false;
|
}
|
}
|
|
function chooseModule(moduleId: string) {
|
return act('choose_scenario', { module_id: moduleId }, '已选择业务场景');
|
}
|
|
async function confirmMapping() {
|
const missing = card.value?.missing_fields ?? [];
|
const mapping: Record<string, string> = {};
|
for (const field of missing) {
|
const column = mappingDraft.value[field.name];
|
if (!column) {
|
message.warning(`请为「${field.label}」选择对应列`);
|
return;
|
}
|
mapping[field.name] = column;
|
}
|
await act('confirm_mapping', { mapping }, '映射已提交,重新校验');
|
}
|
|
async function uploadForFileInterrupt() {
|
const current = active.value;
|
if (!current) return;
|
if (!interruptFile.value) {
|
message.warning('请先选择文件');
|
return;
|
}
|
busy.value = true;
|
try {
|
const attachmentId = await uploadAgentAttachment(interruptFile.value);
|
const result = await sendAgentMessage(current.conversation_id, {
|
attachment_id: String(attachmentId),
|
model_id: selectedModelId.value,
|
text: '已上传要补录的文件。',
|
});
|
interruptFile.value = undefined;
|
await apply(result);
|
} catch (error) {
|
message.error(agentImportErrorMessage(error));
|
} finally {
|
busy.value = false;
|
}
|
}
|
|
async function revise() {
|
const text = reviseText.value.trim();
|
const payload: Record<string, unknown> = {};
|
if (text) payload.text = text;
|
if (isGatewayModule.value) payload.sync_mes = syncMes.value;
|
if (!text && !isGatewayModule.value) {
|
message.warning('请输入修订内容,例如“第2行 名称 改为 XXX”');
|
return;
|
}
|
await act('revise', payload, '已提交修订,重新校验');
|
reviseText.value = '';
|
}
|
|
async function toggleSync(value: boolean) {
|
syncMes.value = value;
|
await act('revise', { sync_mes: value }, '已更新同步选项,重新校验');
|
}
|
|
function confirmImport() {
|
return act('confirm', {}, '已确认,正在提交');
|
}
|
|
function cancelConversation() {
|
return act('cancel', {}, '已取消本次补录');
|
}
|
|
async function downloadReport() {
|
const current = active.value;
|
if (!current) return;
|
try {
|
const response = await downloadAgentReport(current.conversation_id);
|
const disposition = String(
|
response.headers?.['content-disposition'] ?? '',
|
);
|
const match = /filename\*?=(?:UTF-8'')?"?([^";]+)"?/i.exec(disposition);
|
downloadFileFromBlobPart({
|
fileName: match?.[1] || `${current.title || '补录回执'}.xlsx`,
|
source: response.data,
|
});
|
} catch (error) {
|
message.error(agentImportErrorMessage(error));
|
}
|
}
|
|
function decodeAttachmentFilename(
|
headers: Record<string, string> | undefined,
|
fallback: string,
|
) {
|
const encoded = headers?.['x-agent-filename-b64'];
|
if (!encoded) return fallback;
|
try {
|
const binary = atob(encoded);
|
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
return new TextDecoder().decode(bytes);
|
} catch {
|
return fallback;
|
}
|
}
|
|
function canPreview(filename?: string) {
|
return /\.(pdf|png|jpe?g|gif|webp|bmp)$/i.test(filename || '');
|
}
|
|
async function previewAttachment(
|
attachment: AgentConversationApi.ConversationAttachment,
|
) {
|
const current = active.value;
|
if (!current) return;
|
try {
|
const response = await downloadAgentConversationAttachment(
|
current.conversation_id,
|
attachment.attachment_id,
|
'inline',
|
);
|
const filename = decodeAttachmentFilename(
|
response.headers,
|
attachment.filename || `附件-${attachment.attachment_id}`,
|
);
|
closeAttachmentPreview();
|
attachmentPreview.value = {
|
filename,
|
kind: /\.pdf$/i.test(filename) ? 'pdf' : 'image',
|
open: true,
|
url: URL.createObjectURL(response.data),
|
};
|
} catch (error) {
|
message.error(agentImportErrorMessage(error));
|
}
|
}
|
|
function closeAttachmentPreview() {
|
if (attachmentPreview.value.url) URL.revokeObjectURL(attachmentPreview.value.url);
|
attachmentPreview.value = { filename: '', kind: 'image', open: false, url: '' };
|
}
|
|
async function downloadAttachment(
|
attachment: AgentConversationApi.ConversationAttachment,
|
) {
|
const current = active.value;
|
if (!current) return;
|
try {
|
const response = await downloadAgentConversationAttachment(
|
current.conversation_id,
|
attachment.attachment_id,
|
'download',
|
);
|
downloadFileFromBlobPart({
|
fileName: decodeAttachmentFilename(
|
response.headers,
|
attachment.filename || `附件-${attachment.attachment_id}`,
|
),
|
source: response.data,
|
});
|
} catch (error) {
|
message.error(agentImportErrorMessage(error));
|
}
|
}
|
|
async function removeConversation(
|
item: AgentConversationApi.ConversationSummary,
|
) {
|
try {
|
await deleteAgentConversation(item.conversation_id);
|
if (active.value?.conversation_id === item.conversation_id) {
|
abortEventStream();
|
active.value = undefined;
|
}
|
await reloadConversations();
|
message.success('会话及附件已删除');
|
} catch (error) {
|
message.error(agentImportErrorMessage(error));
|
}
|
}
|
|
onMounted(boot);
|
onBeforeUnmount(() => {
|
abortEventStream();
|
closeAttachmentPreview();
|
});
|
|
watch(
|
() => active.value?.conversation_id,
|
(conversationId) => {
|
executionProgress.value = undefined;
|
if (conversationId && !active.value?.finished) startEventStream(conversationId);
|
else abortEventStream();
|
},
|
);
|
</script>
|
|
<template>
|
<Page auto-content-height>
|
<div class="flex h-full gap-3 p-3">
|
<aside
|
class="flex w-64 shrink-0 flex-col overflow-hidden rounded-lg border border-border bg-card"
|
>
|
<div class="border-b border-border p-3">
|
<a-button type="primary" block @click="newOpen = true">
|
新建补录
|
</a-button>
|
<div class="mt-2 text-xs text-gray-500">
|
上传文件后自动识别业务场景,确认前会完整校验。
|
</div>
|
</div>
|
<div class="flex-1 overflow-y-auto p-2">
|
<a-spin :spinning="loading">
|
<a-empty
|
v-if="!conversations.length"
|
description="暂无补录会话"
|
/>
|
<div
|
v-for="item in conversations"
|
:key="item.conversation_id"
|
class="mb-1 flex w-full cursor-pointer items-start gap-1 rounded-md p-2 text-left transition-colors hover:bg-gray-100 dark:hover:bg-gray-800"
|
:class="{
|
'bg-blue-50 dark:bg-blue-900/30':
|
item.conversation_id === active?.conversation_id,
|
}"
|
role="button"
|
tabindex="0"
|
@click="openConversation(item.conversation_id)"
|
@keydown.enter="openConversation(item.conversation_id)"
|
>
|
<div class="min-w-0 flex-1">
|
<div class="truncate text-sm font-medium">
|
{{ item.title || '未命名补录' }}
|
</div>
|
<div class="mt-1 flex items-center gap-2 text-xs text-gray-500">
|
<a-tag :color="statusColor(item.status)" class="!mr-0">
|
{{ statusText(item.status) }}
|
</a-tag>
|
<span class="truncate">
|
{{ item.module_title || '待识别' }}
|
</span>
|
</div>
|
</div>
|
<a-popconfirm
|
cancel-text="取消"
|
ok-text="删除"
|
title="删除会话及已上传附件?"
|
@confirm="removeConversation(item)"
|
>
|
<a-button
|
class="shrink-0"
|
danger
|
size="small"
|
type="text"
|
@click.stop
|
>
|
删除
|
</a-button>
|
</a-popconfirm>
|
</div>
|
</a-spin>
|
</div>
|
</aside>
|
|
<section
|
class="flex min-w-0 flex-1 flex-col overflow-hidden rounded-lg border border-border bg-card"
|
>
|
<header
|
class="flex items-center justify-between border-b border-border px-4 py-3"
|
>
|
<div class="min-w-0">
|
<div class="truncate text-base font-semibold">
|
{{ active?.title || '模块数据补录' }}
|
</div>
|
<div class="mt-1 flex items-center gap-2 text-xs text-gray-500">
|
<a-tag :color="statusColor(active?.status)" class="!mr-0">
|
{{ statusText(active?.status) }}
|
</a-tag>
|
<span v-if="active?.module_title">{{ active.module_title }}</span>
|
<span v-if="active?.total">共 {{ active.total }} 行</span>
|
<span v-if="active?.data_scope_summary || authorizationScope">
|
数据范围:{{ active?.data_scope_summary || authorizationScope }}
|
</span>
|
<span
|
v-if="modelOptions.length"
|
class="flex items-center gap-1"
|
title="切换后从下一次分析开始生效"
|
>
|
模型:
|
<a-select
|
:disabled="busy"
|
:options="modelOptions"
|
:value="selectedModelId"
|
class="w-56"
|
size="small"
|
@change="changeModel"
|
/>
|
</span>
|
<a-tag
|
v-if="active"
|
:color="eventStateColor"
|
class="!mr-0"
|
aria-live="polite"
|
>
|
{{ eventStateText }}
|
</a-tag>
|
</div>
|
<div
|
v-if="active?.attachments?.length"
|
class="mt-1 flex flex-wrap items-center gap-2 text-xs text-gray-500"
|
>
|
<span>附件:</span>
|
<span
|
v-for="attachment in active.attachments"
|
:key="attachment.attachment_id"
|
class="flex items-center gap-1 rounded border border-border px-2 py-0.5"
|
>
|
<span class="max-w-60 truncate">
|
{{ attachment.filename || `附件 ${attachment.attachment_id}` }}
|
</span>
|
<a-button
|
v-if="canPreview(attachment.filename)"
|
class="!h-5 !px-1"
|
size="small"
|
type="link"
|
@click="previewAttachment(attachment)"
|
>
|
预览
|
</a-button>
|
<a-button
|
class="!h-5 !px-1"
|
size="small"
|
type="link"
|
@click="downloadAttachment(attachment)"
|
>
|
下载
|
</a-button>
|
</span>
|
</div>
|
</div>
|
<div class="flex shrink-0 items-center gap-2">
|
<a-tooltip
|
:title="
|
durableTasksEnabled
|
? '查看跨页面执行的文档任务'
|
: '持久任务服务尚未启用'
|
"
|
>
|
<a-button @click="taskCenter?.open()">后台任务</a-button>
|
</a-tooltip>
|
<a-button
|
v-if="active?.receipt?.command_id"
|
:disabled="busy"
|
@click="downloadReport"
|
>
|
下载回执
|
</a-button>
|
</div>
|
</header>
|
|
<div
|
v-if="executionProgress && active"
|
class="border-b border-border bg-blue-50/70 px-4 py-2 dark:bg-blue-950/20"
|
aria-live="polite"
|
>
|
<div class="mb-1 flex items-center justify-between gap-4 text-xs">
|
<span class="font-medium text-blue-700 dark:text-blue-300">
|
{{ executionProgress.label }}
|
</span>
|
<span class="text-gray-500">
|
已发现 {{ executionProgress.candidateCount }} 条候选
|
<template v-if="executionProgress.issueCount">
|
· {{ executionProgress.issueCount }} 项待核对
|
</template>
|
</span>
|
</div>
|
<a-progress
|
:percent="executionProgress.percent"
|
:status="executionProgress.stage === 'error' ? 'exception' : 'active'"
|
size="small"
|
/>
|
</div>
|
|
<div class="flex-1 overflow-y-auto p-4">
|
<a-empty
|
v-if="!active"
|
description="从左侧选择会话,或点击「新建补录」开始"
|
/>
|
<div v-else class="space-y-3">
|
<div
|
v-for="item in active.messages"
|
:key="item.message_id"
|
class="flex"
|
:class="item.role === 'user' ? 'justify-end' : 'justify-start'"
|
>
|
<div
|
class="max-w-[80%] rounded-lg px-3 py-2 text-sm"
|
:class="
|
item.role === 'user'
|
? 'bg-blue-500 text-white'
|
: 'bg-gray-100 dark:bg-gray-800'
|
"
|
>
|
<div class="whitespace-pre-wrap">{{ item.text }}</div>
|
<div
|
v-for="(msgCard, index) in item.cards || []"
|
:key="`${item.message_id}-${index}`"
|
class="mt-2 rounded-md border border-border bg-card p-2 text-gray-800 dark:text-gray-100"
|
>
|
<template v-if="msgCard.kind === 'receipt'">
|
<div class="mb-1 font-semibold">
|
{{ msgCard.title || '导入回执' }}
|
</div>
|
<div class="text-xs text-gray-500">
|
成功 {{ msgCard.summary?.success ?? 0 }},跳过
|
{{ msgCard.summary?.skipped ?? 0 }},失败
|
{{ msgCard.summary?.failed ?? 0 }}
|
</div>
|
<a-table
|
class="mt-2"
|
:columns="[
|
{ title: '编码', dataIndex: 'code', width: 160 },
|
{ title: '名称', dataIndex: 'name' },
|
{ title: '结果', dataIndex: 'status', width: 90 },
|
]"
|
:data-source="msgCard.rows || []"
|
:pagination="false"
|
row-key="candidate_id"
|
size="small"
|
>
|
<template #bodyCell="{ column, record }">
|
<a-tag
|
v-if="column.dataIndex === 'status'"
|
:color="record.status === 'SUCCESS' ? 'green' : 'red'"
|
>
|
{{ record.status }}
|
</a-tag>
|
</template>
|
</a-table>
|
<a-button
|
class="mt-2"
|
size="small"
|
type="link"
|
@click="downloadReport"
|
>
|
下载报表
|
</a-button>
|
</template>
|
</div>
|
</div>
|
</div>
|
</div>
|
</div>
|
|
<footer v-if="active && interrupt" class="border-t border-border p-3">
|
<a-spin :spinning="busy">
|
<!-- 场景选择 -->
|
<div v-if="interrupt.kind === 'scenario'">
|
<div class="mb-2 font-medium">{{ card?.title }}</div>
|
<div class="mb-2 text-xs text-gray-500">{{ card?.body }}</div>
|
<div class="flex flex-wrap gap-2">
|
<a-button
|
v-for="candidate in card?.candidates || []"
|
:key="candidate.module_id"
|
:disabled="busy"
|
@click="chooseModule(candidate.module_id)"
|
>
|
{{ candidate.title }}
|
<a-tag class="ml-1" color="blue">
|
{{ candidate.capability }}
|
</a-tag>
|
</a-button>
|
<a-button
|
v-if="actions.includes('cancel')"
|
danger
|
:disabled="busy"
|
@click="cancelConversation"
|
>
|
取消
|
</a-button>
|
</div>
|
</div>
|
|
<!-- 字段映射 -->
|
<div v-else-if="interrupt.kind === 'mapping'">
|
<div class="mb-2 font-medium">{{ card?.title }}</div>
|
<div class="mb-2 text-xs text-gray-500">{{ card?.body }}</div>
|
<div class="space-y-2">
|
<div
|
v-for="field in card?.missing_fields || []"
|
:key="field.name"
|
class="flex items-center gap-2"
|
>
|
<span class="w-28 text-sm">{{ field.label }}</span>
|
<a-select
|
v-model:value="mappingDraft[field.name]"
|
class="min-w-56"
|
placeholder="选择文件中对应的列"
|
:options="
|
(card?.columns || []).map((column) => ({
|
label: column,
|
value: column,
|
}))
|
"
|
/>
|
</div>
|
</div>
|
<div class="mt-3 flex gap-2">
|
<a-button
|
type="primary"
|
:loading="busy"
|
@click="confirmMapping"
|
>
|
确认映射
|
</a-button>
|
<a-button danger :disabled="busy" @click="cancelConversation">
|
取消
|
</a-button>
|
</div>
|
</div>
|
|
<!-- 补传文件 -->
|
<div v-else-if="interrupt.kind === 'file'">
|
<div class="mb-2 font-medium">{{ card?.title }}</div>
|
<div class="mb-2 text-xs text-gray-500">{{ card?.body }}</div>
|
<a-upload
|
accept=".csv,.xlsx,.docx,.pdf"
|
:before-upload="beforeInterruptUpload"
|
:max-count="1"
|
:show-upload-list="false"
|
>
|
<a-button>{{ interruptFile ? '重新选择' : '选择文件' }}</a-button>
|
</a-upload>
|
<span v-if="interruptFile" class="ml-2 text-xs text-gray-500">
|
{{ interruptFile.name }}
|
</span>
|
<div class="mt-3">
|
<a-button
|
type="primary"
|
:disabled="!interruptFile"
|
:loading="busy"
|
@click="uploadForFileInterrupt"
|
>
|
上传并继续
|
</a-button>
|
</div>
|
</div>
|
|
<!-- 校验 / 预览确认 -->
|
<div v-else-if="['preview', 'validation'].includes(interrupt.kind)">
|
<div class="mb-2 flex items-center justify-between">
|
<span class="font-medium">{{ card?.title }}</span>
|
<span class="text-xs text-gray-500">
|
{{ card?.notice }}
|
</span>
|
</div>
|
|
<a-alert
|
v-if="card?.issues?.length"
|
class="mb-2"
|
type="error"
|
show-icon
|
>
|
<template #message>
|
阻断项 {{ card.issues.length }} 条,需修订后重新校验
|
</template>
|
<ul class="mt-1 list-decimal pl-4 text-xs">
|
<li v-for="(issue, index) in card.issues" :key="index">
|
{{ issue.message }}
|
<span v-if="issue.code" class="text-gray-400">
|
({{ issue.code }})
|
</span>
|
</li>
|
</ul>
|
</a-alert>
|
|
<a-alert
|
v-if="card?.warnings?.length"
|
class="mb-2"
|
type="warning"
|
show-icon
|
>
|
<template #message>
|
提示 {{ card.warnings.length }} 条,不阻断提交
|
</template>
|
<ul class="mt-1 list-decimal pl-4 text-xs">
|
<li v-for="(item, index) in card.warnings" :key="index">
|
{{ item.message }}
|
</li>
|
</ul>
|
</a-alert>
|
|
<a-alert
|
v-if="card?.repair_guidance?.length"
|
class="mb-2"
|
type="info"
|
show-icon
|
>
|
<template #message>业务大模型核对建议</template>
|
<ul class="mt-1 list-disc pl-4 text-xs">
|
<li v-for="(item, index) in card.repair_guidance" :key="index">
|
<span v-if="item.field" class="font-medium">{{ item.field }}:</span>
|
{{ item.guidance }}
|
</li>
|
</ul>
|
</a-alert>
|
|
<div
|
v-if="card?.summary"
|
class="mb-2 flex flex-wrap gap-3 text-xs text-gray-600 dark:text-gray-300"
|
>
|
<span>共 {{ card.summary.total ?? 0 }} 行</span>
|
<span class="text-green-600">
|
新建 {{ card.summary.create ?? 0 }}
|
</span>
|
<span class="text-orange-500">
|
跳过 {{ card.summary.skip ?? 0 }}
|
</span>
|
<span class="text-red-500">
|
阻断 {{ card.summary.blocked ?? 0 }}
|
</span>
|
</div>
|
|
<div v-if="card?.side_effects?.length" class="mb-2 text-xs text-gray-500">
|
预期影响:{{ card.side_effects.join(';') }}
|
</div>
|
|
<div
|
v-if="isGatewayModule"
|
class="mb-2 flex items-center gap-2 text-sm"
|
>
|
<span>同步到 MES</span>
|
<a-switch
|
:checked="syncMes"
|
:disabled="busy"
|
@change="toggleSync"
|
/>
|
<span class="text-xs text-gray-500">
|
关闭后仅创建 ERP 物料
|
</span>
|
</div>
|
|
<a-table
|
v-if="previewRows.length"
|
class="mb-2"
|
:columns="previewColumns"
|
:data-source="previewRows"
|
:pagination="false"
|
:scroll="{ x: 'max-content', y: 320 }"
|
row-key="candidate_id"
|
size="small"
|
bordered
|
/>
|
|
<div class="flex gap-2">
|
<a-input
|
v-model:value="reviseText"
|
class="flex-1"
|
placeholder="如需修改,输入修订说明,例如:第2行 名称 改为 XXX"
|
:disabled="busy"
|
@press-enter="revise"
|
/>
|
<a-button :disabled="busy" @click="revise">修订并重检</a-button>
|
<a-button
|
v-if="actions.includes('confirm')"
|
type="primary"
|
:disabled="busy || card?.can_commit === false"
|
:loading="busy"
|
@click="confirmImport"
|
>
|
确认导入
|
</a-button>
|
<a-button
|
v-if="actions.includes('cancel')"
|
danger
|
:disabled="busy"
|
@click="cancelConversation"
|
>
|
取消
|
</a-button>
|
</div>
|
</div>
|
|
<a-alert
|
v-else
|
type="info"
|
show-icon
|
:message="card?.title || '当前步骤需要处理'"
|
:description="card?.body"
|
/>
|
</a-spin>
|
</footer>
|
</section>
|
|
<TaskCenterDrawer
|
ref="taskCenter"
|
:enabled="durableTasksEnabled"
|
@continue="continueFromTask"
|
/>
|
|
<a-modal
|
v-model:open="attachmentPreview.open"
|
:footer="null"
|
:title="attachmentPreview.filename"
|
width="80%"
|
@cancel="closeAttachmentPreview"
|
>
|
<iframe
|
v-if="attachmentPreview.kind === 'pdf'"
|
:src="attachmentPreview.url"
|
class="h-[70vh] w-full border-0"
|
title="附件预览"
|
/>
|
<img
|
v-else
|
:src="attachmentPreview.url"
|
alt="附件预览"
|
class="max-h-[70vh] w-full object-contain"
|
/>
|
</a-modal>
|
|
<a-modal
|
v-model:open="newOpen"
|
title="新建补录"
|
:confirm-loading="creating"
|
:width="760"
|
>
|
<div class="space-y-3">
|
<div>
|
<div class="mb-1 flex items-center justify-between text-sm">
|
<span>业务场景(可多选)</span>
|
<a-button
|
size="small"
|
:type="newPriorities.scenario_paths ? 'primary' : 'default'"
|
@click="togglePriority('scenario_paths')"
|
>优先</a-button>
|
</div>
|
<a-select
|
v-model:value="newScenarios"
|
class="w-full"
|
mode="multiple"
|
:max-tag-count="3"
|
:options="scenarioOptions"
|
option-filter-prop="label"
|
placeholder="请选择当前补录涉及的菜单模块"
|
show-search
|
>
|
<template #option="option">
|
<div class="py-1">
|
<div class="font-medium">{{ option.label }}</div>
|
<div v-if="option.description" class="mt-0.5 text-xs text-gray-500">
|
{{ option.description }}
|
</div>
|
</div>
|
</template>
|
</a-select>
|
<div class="mt-1 text-xs text-gray-500">
|
开启“优先”后按硬约束处理;最终模块仍必须通过能力与数据权限校验。
|
</div>
|
</div>
|
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
|
<div>
|
<div class="mb-1 flex items-center justify-between text-sm">
|
<span>时间范围</span>
|
<a-button size="small" :type="newPriorities.time_range ? 'primary' : 'default'" @click="togglePriority('time_range')">优先</a-button>
|
</div>
|
<a-range-picker v-model:value="newTimeRange" class="w-full" value-format="YYYY-MM-DD" />
|
</div>
|
<div>
|
<div class="mb-1 flex items-center justify-between text-sm">
|
<span>数据条数</span>
|
<a-button size="small" :type="newPriorities.record_limit ? 'primary' : 'default'" @click="togglePriority('record_limit')">优先</a-button>
|
</div>
|
<a-input-number v-model:value="newRecordLimit" class="w-full" :min="1" :max="100000" placeholder="例如:500" />
|
</div>
|
<div>
|
<div class="mb-1 flex items-center justify-between text-sm">
|
<span>行业</span>
|
<a-button size="small" :type="newPriorities.industry ? 'primary' : 'default'" @click="togglePriority('industry')">优先</a-button>
|
</div>
|
<a-input v-model:value="newIndustry" maxlength="80" placeholder="例如:汽车零部件" />
|
</div>
|
<div>
|
<div class="mb-1 flex items-center justify-between text-sm">
|
<span>区域</span>
|
<a-button size="small" :type="newPriorities.region ? 'primary' : 'default'" @click="togglePriority('region')">优先</a-button>
|
</div>
|
<a-input v-model:value="newRegion" maxlength="120" placeholder="例如:华东 / 江苏南通" />
|
</div>
|
<div>
|
<div class="mb-1 flex items-center justify-between text-sm">
|
<span>跳过休息日</span>
|
<a-button size="small" :type="newPriorities.skip_rest_days ? 'primary' : 'default'" @click="togglePriority('skip_rest_days')">优先</a-button>
|
</div>
|
<div class="flex h-8 items-center gap-2">
|
<a-switch v-model:checked="newSkipRestDays" />
|
<span class="text-xs text-gray-500">{{ newSkipRestDays ? '跳过' : '不跳过' }}</span>
|
</div>
|
</div>
|
<div>
|
<div class="mb-1 flex items-center justify-between text-sm">
|
<span>休息日描述</span>
|
<a-button size="small" :type="newPriorities.rest_day_description ? 'primary' : 'default'" @click="togglePriority('rest_day_description')">优先</a-button>
|
</div>
|
<a-input v-model:value="newRestDayDescription" maxlength="300" placeholder="例如:周日及法定节假日" />
|
</div>
|
</div>
|
<div>
|
<div class="mb-1 flex items-center justify-between text-sm">
|
<span>补录说明(可选)</span>
|
<a-button size="small" :type="newPriorities.instruction ? 'primary' : 'default'" @click="togglePriority('instruction')">优先</a-button>
|
</div>
|
<a-textarea
|
v-model:value="newText"
|
:rows="2"
|
placeholder="例如:导入一批供应商档案"
|
/>
|
</div>
|
<div>
|
<div class="mb-1 text-sm">数据文件</div>
|
<a-upload
|
accept=".csv,.xlsx,.docx,.pdf"
|
:before-upload="beforeNewUpload"
|
:max-count="20"
|
multiple
|
:show-upload-list="false"
|
>
|
<a-button>选择文件</a-button>
|
</a-upload>
|
<span v-if="newFiles.length" class="ml-2 text-xs text-gray-500">
|
已选择 {{ newFiles.length }} 个文件
|
</span>
|
<a-button v-if="newFiles.length" class="ml-2" size="small" type="link" @click="clearNewFiles">
|
清空
|
</a-button>
|
<div v-if="newFiles.length" class="mt-2 max-h-20 overflow-auto text-xs text-gray-500">
|
<div v-for="file in newFiles" :key="`${file.name}:${file.size}:${file.lastModified}`">
|
{{ file.name }}
|
</div>
|
</div>
|
<div class="mt-1 text-xs text-gray-500">
|
支持一次选择最多 20 个 CSV、XLSX、DOCX 与可复制文本的 PDF,单个文件不超过 8
|
MiB。多文件会在后台做跨文件重复和冲突检查;扫描件暂不支持。
|
</div>
|
</div>
|
</div>
|
<template #footer>
|
<div class="flex flex-wrap justify-end gap-2">
|
<a-button :disabled="creating" @click="newOpen = false">
|
取消
|
</a-button>
|
<a-tooltip
|
:title="
|
!durableTasksEnabled
|
? '需先启用 PostgreSQL 与 Redis 持久任务服务'
|
: '任务会根据文件内容自动识别,关闭页面后仍可从任务中心恢复'
|
"
|
>
|
<a-button
|
:disabled="!durableTasksEnabled || !newFiles.length"
|
:loading="creating"
|
@click="startBackgroundAnalysis"
|
>
|
后台分析
|
</a-button>
|
</a-tooltip>
|
<a-button
|
type="primary"
|
:loading="creating"
|
@click="createConversation"
|
>
|
直接开始补录
|
</a-button>
|
</div>
|
</template>
|
</a-modal>
|
</div>
|
</Page>
|
</template>
|