Merge branch 'dev' into snow

# Conflicts:
#	backend/app/api/chat.py
#	backend/app/services/admin/permission_service.py
#	backend/app/services/knowledge_cleaning/dify_sync_service.py
#	backend/app/services/knowledge_cleaning/settings_service.py
#	backend/tests/test_dify_sync_process_rule.py
#	docker-compose.yml
#	docs/funclist.md
#	frontend/package-lock.json
#	frontend/src/config.ts
#	frontend/src/features/admin/components/AdminNav.vue
#	frontend/src/features/admin/constants/modules.ts
#	frontend/src/features/admin/stores/admin-nav.store.ts
#	frontend/src/features/chat/components/messages/ChatMessageBubble.vue
#	frontend/src/features/user/views/UserProfilePage.vue
#	frontend/src/locales/en/admin.json
#	frontend/src/locales/en/auth.json
#	frontend/src/locales/en/errors.json
#	frontend/src/locales/th/admin.json
#	frontend/src/locales/th/auth.json
#	frontend/src/locales/th/errors.json
#	frontend/src/locales/zh-CN/admin.json
#	frontend/src/locales/zh-CN/auth.json
#	frontend/src/locales/zh-CN/errors.json
#	frontend/src/locales/zh-TW/admin.json
#	frontend/src/locales/zh-TW/auth.json
#	frontend/src/locales/zh-TW/errors.json
This commit is contained in:
HTEWJ\26070045 committed 2026-09-11 14:55:20 +08:00
commit ca9c174f29
2050 files changed
+511839 -42320

No files matched your search

@@ -0,0 +1,34 @@
/**
* features/chat/composables/transferLocales.spec.ts
* 用途:四语言 transfer 文案 key 一致性校验(zh-CN/zh-TW/en/th)。
* 依赖:locales 四语言 chat.json。
* 逻辑:四个语言包的 chat.transfer 键集合必须完全一致(防止漏翻译)。
*/
import { describe, expect, it } from 'vitest';
import zhCN from '@/locales/zh-CN/chat.json';
import zhTW from '@/locales/zh-TW/chat.json';
import en from '@/locales/en/chat.json';
import th from '@/locales/th/chat.json';
const packages: Record<string, Record<string, unknown>> = { zhCN, zhTW, en, th };
describe('transfer i18n four-language consistency', () => {
it('四个语言包拥有相同的 transfer 键集合', () => {
const keys = Object.keys(zhCN.transfer as Record<string, unknown>).sort();
expect(keys.length).toBeGreaterThan(30);
for (const [name, pack] of Object.entries(packages)) {
const transfer = (pack as Record<string, { transfer: Record<string, unknown> }>).transfer;
expect(transfer).toBeTruthy();
expect(Object.keys(transfer).sort()).toEqual(keys);
}
});
it('每个 transfer 文案值非空', () => {
for (const [name, pack] of Object.entries(packages)) {
const transfer = (pack as Record<string, { transfer: Record<string, unknown> }>).transfer;
for (const [key, value] of Object.entries(transfer)) {
expect(String(value).trim().length, `${name}.transfer.${key}`).toBeGreaterThan(0);
}
}
});
});
@@ -1,30 +1,53 @@
/**
* features/chat/composables/useChat.spec.ts
* 用途:验证聊天流对发货通知 UI State SSE 事件的消息级回写行为。
* 依赖:vitest、useChat 导出的纯函数、chat.types。
* 逻辑:覆盖 batch_ui_state 到 focus_task_ui_state 的投影、focus 切换时按钮跟随更新,以及已消费按钮消息的防回挂保护。
* 用途:验证聊天流对发货通知 UI State 与订单识别生命周期 SSE 的消息级回写行为。
* 依赖:vitest、useChat/chat.api 导出的纯函数、chat.types。
* 逻辑:覆盖任务状态投影、订单识别终态保护、terminal 后事件放行及历史 payload 恢复。
*/
import { describe, expect, it } from 'vitest';
import { applyShippingUiStateToMessage } from './useChat';
import {
applyShippingOrderExtractionStateToMessage,
applyShippingUiStateToMessage,
createUserChatMessage,
isAllowedAfterStreamTerminal,
} from './useChat';
import { hydrateShippingOrderExtractionState } from '../api/chat.api';
import type { ChatMessage } from '../types/chat.types';
const buildBatchUiStateEvent = (
describe('useChat user attachment snapshots', () => {
it('copies sent attachments onto the user message without inheriting them for text-only messages', () => {
const attachments = [{
name: 'purchase-order.pdf',
size: 144_456,
extension: 'pdf',
type: 'document' as const,
source: 'local' as const,
}];
const message = createUserChatMessage('总结附件', attachments);
attachments[0]!.name = 'changed.pdf';
expect(message).toMatchObject({
role: 'user',
content: '总结附件',
attachments: [{ name: 'purchase-order.pdf', size: 144_456 }],
});
expect(message.attachments).not.toBe(attachments);
expect(createUserChatMessage('仅重发文字')).toEqual({ role: 'user', content: '仅重发文字' });
});
});
const buildTaskUiStateEvent = (
taskNo: string,
batchNo: string,
actionId: string,
checkpoint = 'ready_export',
position = 'ready_export',
) => ({
event: 'shipping_ui_state',
batch_no: batchNo,
batch_ui_state: {
batch_no: batchNo,
current_focus_task_no: taskNo,
tasks: [],
focus_task_ui_state: {
task_no: taskNo,
ui_state: {
task_no: taskNo,
batch_no: batchNo,
checkpoint,
process_status: 'matched',
position,
match_status: 'matched',
review_status: null,
pending_human_reason: null,
match_status: 'fulfillable',
@@ -44,56 +67,179 @@ const buildBatchUiStateEvent = (
},
],
updated_at: '2026-07-01T10:00:00+08:00',
},
},
});
describe('useChat shipping_ui_state SSE', () => {
it('hydrates focus task ui state from batch payload and does not reattach used actions', () => {
it('hydrates ui_state for notifications and never attaches chat fulfillment actions', () => {
const message: ChatMessage = {
role: 'assistant',
content: '当前正在处理批次任务',
content: '当前正在处理任务',
type: 'shipping-match-result',
payload: { action_buttons: [] },
payload: { action_buttons: [{ id: 'legacy' }] },
};
const batchEvent = buildBatchUiStateEvent('SN-UNIT-001', 'SB-UNIT-001', 'generate_excel');
const taskEvent = buildTaskUiStateEvent('SN-UNIT-001', 'generate_excel');
applyShippingUiStateToMessage(message, batchEvent);
applyShippingUiStateToMessage(message, taskEvent);
expect(message.shipping_ui_state?.task_no).toBe('SN-UNIT-001');
expect(message.shipping_actions?.map((item) => item.id)).toEqual(['generate_excel']);
expect((message.payload as { action_buttons?: unknown[] }).action_buttons).toHaveLength(1);
expect((message.payload as { shipping_batch_ui_state?: { batch_no?: string } }).shipping_batch_ui_state?.batch_no).toBe('SB-UNIT-001');
message.shipping_actions_used = true;
message.shipping_actions = undefined;
(message.payload as { action_buttons?: unknown[] }).action_buttons = [];
applyShippingUiStateToMessage(message, batchEvent);
expect(message.shipping_ui_state?.checkpoint).toBe('ready_export');
expect(message.shipping_actions).toBeUndefined();
expect((message.payload as { action_buttons?: unknown[] }).action_buttons).toEqual([]);
expect((message.payload as { action_buttons?: unknown[] }).action_buttons).toBeUndefined();
expect((message.payload as { shipping_ui_state?: { task_no?: string } }).shipping_ui_state?.task_no).toBe('SN-UNIT-001');
});
it('switches buttons when batch focus task changes from A to B', () => {
it('updates ui_state when task changes without remounting action buttons', () => {
const message: ChatMessage = {
role: 'assistant',
content: '请继续处理当前批次',
content: '请继续处理当前任务',
payload: { action_buttons: [] },
};
applyShippingUiStateToMessage(message, buildBatchUiStateEvent('SN-FOCUS-A', 'SB-FOCUS-001', 'generate_excel'));
applyShippingUiStateToMessage(message, buildTaskUiStateEvent('SN-FOCUS-A', 'generate_excel'));
expect(message.shipping_ui_state?.task_no).toBe('SN-FOCUS-A');
expect(message.shipping_actions?.map((item) => item.id)).toEqual(['generate_excel']);
expect(message.shipping_actions).toBeUndefined();
applyShippingUiStateToMessage(message, buildBatchUiStateEvent('SN-FOCUS-B', 'SB-FOCUS-001', 'retry_upload'));
applyShippingUiStateToMessage(message, buildTaskUiStateEvent('SN-FOCUS-B', 'retry_upload'));
expect(message.shipping_ui_state?.task_no).toBe('SN-FOCUS-B');
expect(message.shipping_actions?.map((item) => item.id)).toEqual(['retry_upload']);
expect((message.payload as { shipping_batch_ui_state?: { current_focus_task_no?: string } }).shipping_batch_ui_state?.current_focus_task_no)
expect(message.shipping_actions).toBeUndefined();
expect((message.payload as { shipping_ui_state?: { task_no?: string } }).shipping_ui_state?.task_no)
.toBe('SN-FOCUS-B');
});
});
describe('useChat shipping_order_extraction_state SSE', () => {
it('replaces extracting with persisted facts without overwriting Dify content', () => {
const message: ChatMessage = {
role: 'assistant',
content: 'Dify 最终正文保持不变',
payload: { existing_key: 'kept' },
};
applyShippingOrderExtractionStateToMessage(message, {
event: 'shipping_order_extraction_state',
status: 'processing',
summary: {
totalDocuments: 3,
pendingDocuments: 0,
processingDocuments: 2,
completedDocuments: 1,
reviewRequiredDocuments: 0,
failedDocuments: 0,
candidateCount: 1,
},
currentActivity: {
unitId: 12,
fileName: 'PO-450001.pdf',
eventCode: 'profile_matching',
},
selectionPlan: {
maxInitialAttachments: 2,
pendingExpansionAttachmentCount: 1,
},
unitSummary: {
reviewRequiredReasonCodes: ['required_field_missing'],
expansionTriggerReasonCodes: ['missing_reservation_id'],
technicalFailureReasonCodes: ['SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT'],
},
availableActions: ['view_details'],
terminal: false,
});
expect(message.shipping_order_extraction_state?.status).toBe('processing');
expect(message.shipping_order_extraction_state?.summary.processingDocuments).toBe(2);
expect(message.shipping_order_extraction_state?.selectionPlan?.pendingExpansionAttachmentCount).toBe(1);
expect(message.shipping_order_extraction_state?.unitSummary?.reviewRequiredReasonCodes).toEqual(['required_field_missing']);
applyShippingOrderExtractionStateToMessage(message, {
event: 'shipping_order_extraction_state',
status: 'completed',
summary: {
totalDocuments: 3,
pendingDocuments: 0,
processingDocuments: 0,
completedDocuments: 3,
reviewRequiredDocuments: 0,
failedDocuments: 0,
candidateCount: 3,
},
currentActivity: null,
availableActions: ['view_details'],
terminal: true,
});
expect(message.content).toBe('Dify 最终正文保持不变');
expect(message.shipping_order_extraction_state).toMatchObject({
status: 'completed',
summary: {
completedDocuments: 3,
candidateCount: 3,
},
terminal: true,
});
expect((message.payload as Record<string, unknown>).existing_key).toBe('kept');
expect((message.payload as { shipping_order_extraction_state?: { summary?: { candidateCount?: number } } })
.shipping_order_extraction_state?.summary?.candidateCount).toBe(3);
// 关键断言:网络重排导致的迟到进行态不能覆盖已经展示的终态。
applyShippingOrderExtractionStateToMessage(message, {
status: 'processing',
summary: {
totalDocuments: 3,
pendingDocuments: 0,
processingDocuments: 1,
completedDocuments: 2,
reviewRequiredDocuments: 0,
failedDocuments: 0,
candidateCount: 2,
},
availableActions: ['view_details'],
terminal: false,
});
expect(message.shipping_order_extraction_state?.status).toBe('completed');
});
it('allows HXOPS domain states after the upstream terminal event', () => {
expect(isAllowedAfterStreamTerminal('shipping_order_extraction_state')).toBe(true);
expect(isAllowedAfterStreamTerminal('shipping_ui_state')).toBe(true);
expect(isAllowedAfterStreamTerminal('agent_message')).toBe(false);
});
it('hydrates persisted terminal state from ChatLog payload', () => {
const message: ChatMessage = {
role: 'assistant',
content: '订单识别完成',
payload: {
shipping_order_extraction_state: {
status: 'partially_completed',
summary: {
totalDocuments: 3,
pendingDocuments: 0,
processingDocuments: 0,
completedDocuments: 2,
reviewRequiredDocuments: 1,
failedDocuments: 0,
candidateCount: 2,
},
selectionPlan: {
pendingExpansionAttachmentCount: 2,
},
unitSummary: {
reviewRequiredReasonCodes: ['multiple_po_detected'],
},
availableActions: ['view_details', 'enter_manual_review'],
terminal: true,
},
},
};
hydrateShippingOrderExtractionState(message);
expect(message.shipping_order_extraction_state?.status).toBe('partially_completed');
expect(message.shipping_order_extraction_state?.summary.reviewRequiredDocuments).toBe(1);
expect(message.shipping_order_extraction_state?.selectionPlan?.pendingExpansionAttachmentCount).toBe(2);
expect(message.shipping_order_extraction_state?.unitSummary?.reviewRequiredReasonCodes).toEqual(['multiple_po_detected']);
expect(message.shipping_order_extraction_state?.availableActions).toEqual(['view_details', 'enter_manual_review']);
});
});
+225 -37
View File
@@ -1,19 +1,49 @@
/**
* features/chat/composables/useChat.ts
* SSE 流式对话核心:消息列表、runs、发送与接收。
* 用途:维护聊天消息、并行 run 与 legacy SSE 流式收发,并投影普通货代 UI 状态。
* 依赖:Vue、vue-i18n、useChatTurn、streamErrorMessage、chat/shipping 类型。
* 逻辑:页面调用 useChat 发起消息;Dify/HXOPS SSE 被归并到当前助手消息,订单抽取状态由独立 Run API 维护。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { getAuthHeaders } from '@/shared/utils/auth';
import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
import type { ChatMessage, ChatRun, RetrieverResource } from '../types/chat.types';
import type { ShippingBatchUiState, ShippingTaskUiState } from '../types/shipping.api.types';
import type {
ChatMessage,
ChatMessageAttachment,
ChatRun,
RetrieverResource,
ShippingOrderExtractionState,
} from '../types/chat.types';
import type { ShippingTaskUiState } from '../types/shipping.api.types';
import type { ChatMessageSendResult } from '../types/chat-turn.types';
import { createStartChatTurn } from './useChatTurn';
export interface SendMessageLifecycleHooks {
/** 当前轮用户消息的已发送附件快照;仅用于界面展示与后续持久化。 */
userAttachments?: ChatMessageAttachment[];
onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void>;
}
/**
* 创建当前轮乐观用户消息,并复制附件快照避免调用方后续修改污染消息历史。
* @param content - 用户可见问题文本
* @param attachments - 已上传并固化的附件快照
* @returns 可直接推入消息列表的用户消息
*/
export function createUserChatMessage(
content: string,
attachments?: ChatMessageAttachment[],
): ChatMessage {
return {
role: 'user',
content,
...(attachments?.length
? { attachments: attachments.map((attachment) => ({ ...attachment })) }
: {}),
};
}
const normalizeResources = (resources: unknown) => {
if (!resources) return [];
if (Array.isArray(resources)) return resources;
@@ -82,57 +112,182 @@ const addAttributionParts = (msg: ChatMessage, value: unknown) => {
/**
* 解析发货通知 SSE 事件中的统一 UI State 载荷。
*
* 核心逻辑:优先读取单票 `ui_state`,批次事件则下钻 `batch_ui_state.focus_task_ui_state`;
* 同时保留批次态原文,供右侧工作台和后续兼容逻辑继续消费。
* 核心逻辑:只读取正式任务 `ui_state`;已删除的 shipping_batches 不再参与事件恢复。
* @param data - SSE 事件 JSON
* @returns 提炼后的单票 UI State 与原始批次 UI State
* @returns 提炼后的单票 UI State
*/
export const resolveShippingUiStatePayload = (data: Record<string, unknown>): {
uiState?: ShippingTaskUiState;
batchUiState?: ShippingBatchUiState;
} => {
const rawUiState = data.ui_state;
const uiState = rawUiState && typeof rawUiState === 'object'
? rawUiState as ShippingTaskUiState
: undefined;
const rawBatchUiState = data.batch_ui_state;
const batchUiState = rawBatchUiState && typeof rawBatchUiState === 'object'
? rawBatchUiState as ShippingBatchUiState
: undefined;
const focusTaskUiState = batchUiState?.focus_task_ui_state && typeof batchUiState.focus_task_ui_state === 'object'
? batchUiState.focus_task_ui_state
: undefined;
return {
uiState: uiState || focusTaskUiState,
batchUiState,
uiState,
};
};
/**
* 将发货通知状态机事件同步到当前助手消息。
*
* 说明:shipping_ui_state 是 HXOPS 自有 SSE 事件,不依赖 Dify 正文;收到后立即挂按钮,
* 让用户无需等待 `message_end` 才拿到状态机结果。若该消息按钮已被消费,则只更新状态快照,
* 不重新挂出可点击按钮,避免首帧旧状态覆盖。
* 说明:shipping_ui_state 是 HXOPS 自有 SSE 事件;收到后写入状态快照供会话摘要/通知展示,
* 不再把 action_buttons 挂到聊天消息(履约写操作改由任务处理工作台承接)。
*/
export const applyShippingUiStateToMessage = (msg: ChatMessage, data: Record<string, unknown>) => {
const { uiState, batchUiState } = resolveShippingUiStatePayload(data);
const { uiState } = resolveShippingUiStatePayload(data);
if (!uiState) return;
const nextActions = Array.isArray(uiState.action_buttons) && uiState.action_buttons.length
? uiState.action_buttons
: undefined;
msg.shipping_ui_state = uiState;
if (!msg.shipping_actions_used) {
msg.shipping_actions = nextActions;
}
if (msg.type === 'shipping-match-result' && msg.payload && typeof msg.payload === 'object' && !msg.shipping_actions_used) {
(msg.payload as { action_buttons?: ChatMessage['shipping_actions'] }).action_buttons = nextActions;
msg.shipping_actions = undefined;
if (msg.type === 'shipping-match-result' && msg.payload && typeof msg.payload === 'object') {
delete (msg.payload as { action_buttons?: ChatMessage['shipping_actions'] }).action_buttons;
}
msg.payload = {
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
shipping_ui_state: uiState,
...(batchUiState ? { shipping_batch_ui_state: batchUiState } : {}),
};
};
export const isAllowedAfterStreamTerminal = (eventName: string): boolean => (
eventName === 'shipping_ui_state' || eventName === 'shipping_order_extraction_state'
);
const normalizeShippingOrderExtractionState = (
data: Record<string, unknown>,
): ShippingOrderExtractionState | null => {
const status = String(data.status || '').trim();
if (!['queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'].includes(status)) {
return null;
}
const rawSummary = data.summary && typeof data.summary === 'object'
? data.summary as Record<string, unknown>
: {};
const rawActivity = data.currentActivity && typeof data.currentActivity === 'object'
? data.currentActivity as Record<string, unknown>
: null;
const rawSelectionPlan = data.selectionPlan && typeof data.selectionPlan === 'object'
? data.selectionPlan as Record<string, unknown>
: null;
const rawUnitSummary = data.unitSummary && typeof data.unitSummary === 'object'
? data.unitSummary as Record<string, unknown>
: null;
return {
status: status as ShippingOrderExtractionState['status'],
uploadBatchId: String(data.uploadBatchId || '').trim() || null,
summary: {
totalDocuments: Math.max(0, Number(rawSummary.totalDocuments || 0)),
pendingDocuments: Math.max(0, Number(rawSummary.pendingDocuments || 0)),
processingDocuments: Math.max(0, Number(rawSummary.processingDocuments || 0)),
completedDocuments: Math.max(0, Number(rawSummary.completedDocuments || 0)),
reviewRequiredDocuments: Math.max(0, Number(rawSummary.reviewRequiredDocuments || 0)),
failedDocuments: Math.max(0, Number(rawSummary.failedDocuments || 0)),
candidateCount: Math.max(0, Number(rawSummary.candidateCount || 0)),
},
currentActivity: rawActivity
? {
unitId: Math.max(0, Number(rawActivity.unitId || 0)),
fileName: String(rawActivity.fileName || '').trim() || null,
eventCode: String(rawActivity.eventCode || '').trim(),
selectionBatch: rawActivity.selectionBatch != null
? Math.max(0, Number(rawActivity.selectionBatch || 0)) || null
: null,
reasonCodes: Array.isArray(rawActivity.reasonCodes)
? rawActivity.reasonCodes.map((item) => String(item || '').trim()).filter(Boolean)
: [],
}
: null,
documents: Array.isArray(data.documents)
? data.documents.map((item) => {
const row = item && typeof item === 'object' ? item as Record<string, unknown> : {};
return {
unitId: Math.max(0, Number(row.unitId || 0)),
documentId: Math.max(0, Number(row.documentId || 0)),
intakeId: row.intakeId != null ? Math.max(0, Number(row.intakeId || 0)) || null : null,
documentType: String(row.documentType || '').trim() || null,
fileName: String(row.fileName || '').trim() || null,
status: String(row.status || '').trim(),
userVisibleStage: String(row.userVisibleStage || '').trim() || null,
reasonCode: String(row.reasonCode || '').trim() || null,
explainability: row.explainability && typeof row.explainability === 'object'
? row.explainability as { message?: string | null }
: null,
emailSupplement: row.emailSupplement && typeof row.emailSupplement === 'object'
? row.emailSupplement as { status?: string | null }
: null,
};
})
: [],
selectionPlan: rawSelectionPlan
? {
selectionVersion: String(rawSelectionPlan.selectionVersion || '').trim() || null,
maxInitialAttachments: Math.max(0, Number(rawSelectionPlan.maxInitialAttachments || 0)),
maxInitialConcurrency: Math.max(0, Number(rawSelectionPlan.maxInitialConcurrency || 0)),
expansionBatchSize: Math.max(0, Number(rawSelectionPlan.expansionBatchSize || 0)),
maxTotalAttachments: Math.max(0, Number(rawSelectionPlan.maxTotalAttachments || 0)),
totalAttachmentCount: Math.max(0, Number(rawSelectionPlan.totalAttachmentCount || 0)),
eligibleAttachmentCount: Math.max(0, Number(rawSelectionPlan.eligibleAttachmentCount || 0)),
selectedAttachmentCount: Math.max(0, Number(rawSelectionPlan.selectedAttachmentCount || 0)),
plannedAttachmentCount: Math.max(0, Number(rawSelectionPlan.plannedAttachmentCount || 0)),
pendingExpansionAttachmentCount: Math.max(0, Number(rawSelectionPlan.pendingExpansionAttachmentCount || 0)),
pendingExpansionBatches: rawSelectionPlan.pendingExpansionBatches && typeof rawSelectionPlan.pendingExpansionBatches === 'object'
? rawSelectionPlan.pendingExpansionBatches as Record<string, number>
: {},
skippedAttachmentCount: Math.max(0, Number(rawSelectionPlan.skippedAttachmentCount || 0)),
duplicateAttachmentCount: Math.max(0, Number(rawSelectionPlan.duplicateAttachmentCount || 0)),
budgetLimitedAttachmentCount: Math.max(0, Number(rawSelectionPlan.budgetLimitedAttachmentCount || 0)),
groupCount: Math.max(0, Number(rawSelectionPlan.groupCount || 0)),
}
: null,
unitSummary: rawUnitSummary
? {
totalUnits: Math.max(0, Number(rawUnitSummary.totalUnits || 0)),
selectedUnits: Math.max(0, Number(rawUnitSummary.selectedUnits || 0)),
retryingUnits: Math.max(0, Number(rawUnitSummary.retryingUnits || 0)),
pendingRetryUnits: Math.max(0, Number(rawUnitSummary.pendingRetryUnits || 0)),
failedUnits: Math.max(0, Number(rawUnitSummary.failedUnits || 0)),
reviewRequiredUnits: Math.max(0, Number(rawUnitSummary.reviewRequiredUnits || 0)),
succeededUnits: Math.max(0, Number(rawUnitSummary.succeededUnits || 0)),
selectionBatches: rawUnitSummary.selectionBatches && typeof rawUnitSummary.selectionBatches === 'object'
? rawUnitSummary.selectionBatches as Record<string, number>
: {},
reviewRequiredReasonCodes: Array.isArray(rawUnitSummary.reviewRequiredReasonCodes)
? rawUnitSummary.reviewRequiredReasonCodes.map((item) => String(item || '').trim()).filter(Boolean)
: [],
expansionTriggerReasonCodes: Array.isArray(rawUnitSummary.expansionTriggerReasonCodes)
? rawUnitSummary.expansionTriggerReasonCodes.map((item) => String(item || '').trim()).filter(Boolean)
: [],
technicalFailureReasonCodes: Array.isArray(rawUnitSummary.technicalFailureReasonCodes)
? rawUnitSummary.technicalFailureReasonCodes.map((item) => String(item || '').trim()).filter(Boolean)
: [],
}
: null,
availableActions: Array.isArray(data.availableActions)
? data.availableActions.map((item) => String(item || '').trim()).filter(Boolean)
: [],
terminal: Boolean(data.terminal),
refreshFailed: Boolean(data.refreshFailed),
errorCode: String(data.errorCode || '').trim() || null,
startedAt: String(data.startedAt || '').trim() || null,
finishedAt: String(data.finishedAt || '').trim() || null,
};
};
/**
* 将订单抽取状态消息同步到当前助手消息。
*
* 说明:订单抽取已经迁移为 HXOPS 自有 Run 事实;即使流式正文已完成,
* 服务端后续补发的领域状态也允许继续覆盖当前卡片,但迟到的非终态不得回退终态展示。
*/
export const applyShippingOrderExtractionStateToMessage = (msg: ChatMessage, data: Record<string, unknown>) => {
const next = normalizeShippingOrderExtractionState(data);
if (!next) return;
const previous = msg.shipping_order_extraction_state;
if (previous?.terminal && !next.terminal) return;
msg.shipping_order_extraction_state = next;
msg.payload = {
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
shipping_order_extraction_state: next,
};
};
@@ -436,10 +591,14 @@ export function useChat() {
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'local_file'; upload_file_id: string }
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'remote_url'; url: string }
>,
context?: { task_id?: string; batch_no?: string; display_query?: string },
context?: { task_id?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
hooks?: SendMessageLifecycleHooks,
) => {
const displayQuery = String(context?.display_query || query || '').trim();
): Promise<ChatMessageSendResult> => {
const displayQuery = String(
context && Object.prototype.hasOwnProperty.call(context, 'display_query')
? context.display_query ?? ''
: query || '',
).trim();
clearLikelyCompletedStreamTimer();
const shouldDetachPreviousStream = Boolean(activeStreamController.value) && hasVisibleCompletedAssistantReply(messages.value);
if (shouldDetachPreviousStream) {
@@ -466,10 +625,12 @@ export function useChat() {
if (runs.value.length > 30) runs.value = runs.value.slice(0, 30);
activeRunId.value = run.runId;
runMessages.push({ role: 'user', content: displayQuery });
const userMessageIndex = runMessages.push(createUserChatMessage(displayQuery, hooks?.userAttachments)) - 1;
let botMsgIndex: number | null = null;
let hasAssistantContent = false;
let hasTerminalEvent = false;
let requestAccepted = false;
let chatLogId: number | undefined;
let ignoreFurtherStreamEvents = false;
const ensureBotMessage = () => {
if (botMsgIndex === null) {
@@ -497,8 +658,12 @@ export function useChat() {
kb_type: kbType,
files: files && files.length > 0 ? files : undefined,
task_id: context?.task_id || undefined,
batch_no: context?.batch_no || undefined,
display_query: context?.display_query || undefined,
shipping_temporary_inventory_asset_no: context?.shipping_temporary_inventory_asset_no || undefined,
shipping_temporary_inventory_session_no: context?.shipping_temporary_inventory_session_no || undefined,
display_query: context && Object.prototype.hasOwnProperty.call(context, 'display_query')
? context.display_query
: undefined,
user_attachments: hooks?.userAttachments?.length ? hooks.userAttachments : undefined,
}),
});
@@ -506,6 +671,7 @@ export function useChat() {
const err = await response.json().catch(() => ({}));
throw new Error((err as { error?: string }).error || `Request failed with status ${response.status}`);
}
requestAccepted = true;
const reader = response.body?.getReader();
const decoder = new TextDecoder();
@@ -552,13 +718,21 @@ export function useChat() {
}
const eventName = String(data.event || '');
if (ignoreFurtherStreamEvents && eventName !== 'shipping_ui_state') {
const eventChatLogId = Number(data.chat_log_id || 0);
if (Number.isInteger(eventChatLogId) && eventChatLogId > 0) {
chatLogId = eventChatLogId;
}
if (ignoreFurtherStreamEvents && !isAllowedAfterStreamTerminal(eventName)) {
continue;
}
if (eventName === 'shipping_ui_state') {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
applyShippingUiStateToMessage(botMsg, data);
} else if (eventName === 'shipping_order_extraction_state') {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
applyShippingOrderExtractionStateToMessage(botMsg, data);
} else if (eventName === 'message' || eventName === 'agent_message') {
if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
@@ -684,10 +858,24 @@ export function useChat() {
if (run.status === 'done' && botMsgIndex !== null) {
const botMsg = runMessages[botMsgIndex];
if (botMsg) {
await hooks?.onAssistantMessageFinished?.(botMsg, runMessages);
try {
await hooks?.onAssistantMessageFinished?.(botMsg, runMessages);
} catch (error) {
// 助手完成后的领域刷新属于附加动作,失败不能反向改变已被服务端接受的消息结果。
console.error('[chat] onAssistantMessageFinished failed', error);
}
}
}
if (!requestAccepted) {
const removeCount = botMsgIndex === null ? 1 : Math.max(botMsgIndex - userMessageIndex + 1, 1);
runMessages.splice(userMessageIndex, removeCount);
}
}
return {
accepted: requestAccepted,
completed: requestAccepted && run.status === 'done',
...(chatLogId ? { chatLogId } : {}),
};
};
return {
@@ -1,15 +1,16 @@
/**
* features/chat/composables/useChatAgent.ts
* 当前 Agent 元数据、发送时默认知识库类型、推荐问题与用户可切换 Agent 列表。
* 依赖:user API、agent-registry / agent-category utils、training 题库工具、ChatDeps。
* 逻辑:Chat 页面通过 useChatPage 调用;selectedKb 固定为企业知识库供发消息透传,输入栏不再展示知识库下拉。
* 当前 Agent 元数据、知识库选项、推荐问题与用户可切换 Agent 列表。
*/
import { computed, ref, type ComputedRef } from 'vue';
import { computed, ref, watch, type ComputedRef } from 'vue';
import { BusinessError } from '@/shared/api/client';
import { getUserAgent, listUserAgents } from '@/features/user';
import { getUserAgent, listUserAgents } from '@/features/auth/api/user.api';
import { setLastChatAgentId } from '@/shared/utils/lastChatAgent';
import { sortAgentsByCategory } from '@/shared/utils/agent-category.utils';
import type { AgentRegistryFields } from '@/shared/utils/agent-registry.utils';
import {
agentHasErpKb,
type AgentRegistryFields,
} from '@/shared/utils/agent-registry.utils';
import { matchesTrainingAgent } from '../training/trainingWorkspace.utils';
import { resolveTrainingRoleChatQuestions } from '../training/trainingChatQuestions';
import type { ChatDeps } from './chat.deps';
@@ -20,8 +21,11 @@ export type AgentSuggestedQuestionItem = {
group: string;
};
/** 发消息时透传给后端的默认 kb_type;聊天输入栏已不再提供切换入口 */
const DEFAULT_KB = '企业知识库';
const ERP_KB = 'ERP知识库';
const TRAINING_AGENT_DESCRIPTION =
'我是你的新人培训助手,会在同一个聊天页面内带你完成视频学习、知识点复盘、逐题考试和结果复盘。';
const normalizeAgentSuggestedQuestions = (value: unknown): AgentSuggestedQuestionItem[] => {
if (!Array.isArray(value)) return [];
@@ -47,45 +51,68 @@ export interface UseChatAgentOptions {
chatGuides: Pick<UseChatGuidesReturn, 'loadGuides' | 'clearGuides'>;
}
type ChatAgentOption = AgentRegistryFields & {
id: number;
name: string;
description: string;
icon_url?: string;
dify_app_type?: 'chatflow' | 'workflow';
category?: string | null;
sub_category?: string | null;
sort_order?: number;
is_aggregate?: boolean;
directory_members?: Array<AgentRegistryFields & {
id: number;
name: string;
description?: string | null;
icon_url?: string;
category?: string | null;
sub_category?: string | null;
sort_order?: number;
}>;
};
export function useChatAgent(options: UseChatAgentOptions) {
const { deps, currentAgentId, currentUser, chatGuides } = options;
const { t, msg, router } = deps;
const currentAgent = ref<AgentRegistryFields | null>(null);
const userAgents = ref<ChatAgentOption[]>([]);
const userAgents = ref<Array<AgentRegistryFields & {
id: number;
name: string;
description: string;
icon_url?: string;
dify_app_type?: 'chatflow' | 'workflow';
category?: string | null;
sub_category?: string | null;
sort_order?: number;
is_aggregate?: boolean;
directory_members?: Array<AgentRegistryFields & {
id: number;
name: string;
description?: string | null;
icon_url?: string;
category?: string | null;
sub_category?: string | null;
sort_order?: number;
}>;
}>>([]);
const showAgentPanel = ref(true);
const selectedKb = ref(DEFAULT_KB);
const kbOptions = [DEFAULT_KB, ERP_KB];
const getKbLabel = (kb: string) => {
if (kb === DEFAULT_KB) return t('chat.kb.enterprise');
if (kb === ERP_KB) return t('chat.kb.erp');
return kb;
};
const canSelectErpKnowledgeBase = computed(() => agentHasErpKb(currentAgent.value));
const availableKbOptions = computed(() => (
canSelectErpKnowledgeBase.value
? kbOptions
: kbOptions.filter((option) => option !== ERP_KB)
));
const kbDropdownDisabled = computed(() => availableKbOptions.value.length <= 1);
const isTrainingAdminViewer = computed(() => Boolean(
(currentUser.value as { feature_permissions?: { training_hr_manage?: boolean } } | null)
?.feature_permissions?.training_hr_manage,
));
watch(canSelectErpKnowledgeBase, (allowed) => {
if (allowed) {
selectedKb.value = DEFAULT_KB;
return;
}
if (selectedKb.value === ERP_KB) {
selectedKb.value = DEFAULT_KB;
}
}, { immediate: true });
const agentDescription = computed(() => {
const welcome = String(currentAgent.value?.welcome_message || '').trim();
if (welcome) return welcome;
const text = String(currentAgent.value?.description || '').trim();
if (!text && matchesTrainingAgent(currentAgent.value)) return t('chat.training.agentDescription');
if (!text && matchesTrainingAgent(currentAgent.value)) return TRAINING_AGENT_DESCRIPTION;
return text;
});
@@ -119,7 +146,7 @@ export function useChatAgent(options: UseChatAgentOptions) {
const styledSuggestedQuestionSections = computed(() => {
const groups = new Map<string, AgentSuggestedQuestionItem[]>();
for (const item of agentSuggestedQuestions.value) {
const groupName = String(item.group || '').trim() || t('chat.faqGroup');
const groupName = String(item.group || '').trim() || '常见问题';
if (!groups.has(groupName)) {
groups.set(groupName, []);
}
@@ -135,7 +162,7 @@ export function useChatAgent(options: UseChatAgentOptions) {
const loadAgent = async () => {
try {
currentAgent.value = await getUserAgent<AgentRegistryFields>(currentAgentId.value);
currentAgent.value = await getUserAgent(currentAgentId.value);
await chatGuides.loadGuides();
} catch (e) {
if (e instanceof BusinessError && e.status === 403) {
@@ -151,9 +178,9 @@ export function useChatAgent(options: UseChatAgentOptions) {
const loadUserAgents = async () => {
try {
const agents = await listUserAgents<ChatAgentOption>();
const agents = await listUserAgents();
const filtered = Array.isArray(agents)
? agents.filter((agent) => (agent.dify_app_type || 'chatflow') === 'chatflow')
? agents.filter((a: any) => (a.dify_app_type || 'chatflow') === 'chatflow')
: [];
userAgents.value = sortAgentsByCategory(filtered);
showAgentPanel.value = userAgents.value.length > 0;
@@ -174,6 +201,9 @@ export function useChatAgent(options: UseChatAgentOptions) {
userAgents,
showAgentPanel,
selectedKb,
getKbLabel,
availableKbOptions,
kbDropdownDisabled,
agentDescription,
suggestedQuestionsStyle,
agentSuggestedQuestions,
@@ -1,42 +1,40 @@
/**
* features/chat/composables/useChatAssetHistory.ts
* 用途:管理固定资产履历检索、友好提示与文件预览跳转。
* 依赖:chat.api、vue-i18n、useChatSourceFiles 暴露的 openPreview、聊天提示消息。
* 依赖:chat.api、useChatSourceFiles 暴露的 openPreview、聊天提示消息。
* 逻辑:页面层统一持有“打开履历”动作,消息气泡/查询预览弹窗复用该入口;
* 点击资产编号后先进入“检索中”状态,命中履历文件则直接打开最佳候选预览,未命中时仅提示用户。
*/
import { ref } from 'vue';
import type { ComputedRef } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
import { searchAssetHistoryFiles } from '../api/chat.api';
import type { AssetHistoryFileItem, SourceFileLink } from '../types/chat.types';
import type { ComputedRef } from 'vue';
interface UseChatAssetHistoryOptions {
agentId: ComputedRef<number>;
openPreview: (file: SourceFileLink) => Promise<void>;
warn: (message: string) => void;
t: ComposerTranslation;
}
/**
* 把后端返回的技术性错误翻译成用户可理解的提示。
* AI 触发时机:当资产履历查询失败,但原始错误包含英文配置名、共享盘术语等技术细节时调用。
* 核心逻辑:优先识别已知的履历共享盘配置异常,返回面向业务用户的本地化说明;其他错误保持原文。
* 核心逻辑:优先识别已知的履历共享盘配置异常,返回面向业务用户的中文说明;其他错误保持原文,避免吞掉真实上下文。
* 参数约束:仅处理展示文案,不改变错误对象本身;返回值必须适合作为 toast/警告弹窗直接展示。
*/
function normalizeAssetHistoryErrorMessage(message: string, t: ComposerTranslation): string {
function normalizeAssetHistoryErrorMessage(message: string): string {
const normalizedMessage = String(message || '').trim();
const lowerCaseMessage = normalizedMessage.toLowerCase();
if (lowerCaseMessage.includes('asset history share is not configured')) {
return String(t('chat.assetHistory.shareNotConfigured'));
return '当前系统暂未配置资产履历文件目录,暂时无法查看履历,请联系管理员处理。';
}
if (lowerCaseMessage.includes('asset history share is unreachable')) {
return String(t('chat.assetHistory.shareUnreachable'));
return '当前环境暂时无法访问资产履历共享盘,请联系管理员检查测试环境共享盘挂载或访问权限。';
}
if (lowerCaseMessage.includes('asset history share is invalid')) {
return String(t('chat.assetHistory.shareInvalid'));
return '当前环境的资产履历目录配置无效,请联系管理员检查共享盘目录配置。';
}
return normalizedMessage || String(t('chat.assetHistory.searchFailed'));
return normalizedMessage || '检索资产履历失败';
}
export function useChatAssetHistory(options: UseChatAssetHistoryOptions) {
@@ -46,7 +44,6 @@ export function useChatAssetHistory(options: UseChatAssetHistoryOptions) {
const assetId = ref('');
const assetName = ref('');
const items = ref<AssetHistoryFileItem[]>([]);
const { t } = options;
const close = () => {
open.value = false;
@@ -69,7 +66,7 @@ export function useChatAssetHistory(options: UseChatAssetHistoryOptions) {
return;
}
if (!normalizedAssetId && !normalizedAssetName) {
options.warn(String(t('chat.assetHistory.missingIdentifier')));
options.warn('当前资产缺少可用于检索履历的编号或名称');
return;
}
@@ -88,15 +85,15 @@ export function useChatAssetHistory(options: UseChatAssetHistoryOptions) {
const bestMatch = items.value[0];
if (!bestMatch) {
const displayName = normalizedAssetId || normalizedAssetName;
options.warn(String(t('chat.assetHistory.notFound', { name: displayName })));
options.warn(`未找到资产 ${displayName} 的履历文件,如确认应有履历,请联系管理员补充。`);
return;
}
await openHistoryFilePreview(bestMatch);
} catch (err: unknown) {
const rawMessage = err instanceof Error ? err.message : String(t('chat.assetHistory.searchFailed'));
const message = normalizeAssetHistoryErrorMessage(rawMessage, t);
const rawMessage = err instanceof Error ? err.message : '检索资产履历失败';
const message = normalizeAssetHistoryErrorMessage(rawMessage);
error.value = message;
options.warn(String(t('chat.assetHistory.queryFailed', { message })));
options.warn(`履历查询失败:${message}`);
} finally {
loading.value = false;
}
@@ -1,12 +1,11 @@
/**
* features/chat/composables/useChatAssetImage.ts
* 用途:管理固定资产图片检索、友好提示与预览跳转。
* 依赖:chat.api、vue-i18n、useChatSourceFiles 暴露的 openPreview、聊天提示消息。
* 依赖:chat.api、useChatSourceFiles 暴露的 openPreview、聊天提示消息。
* 逻辑:用户点击“图片 -> 查看”后,本 composable 统一向后端索要最佳图片,再复用现有文件预览弹窗在站内展示。
*/
import { ref } from 'vue';
import type { ComputedRef } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
import { resolveAssetImagePreview } from '../api/chat.api';
import type { SourceFileLink } from '../types/chat.types';
@@ -14,39 +13,37 @@ interface UseChatAssetImageOptions {
agentId: ComputedRef<number>;
openPreviewGallery: (files: SourceFileLink[], initialIndex?: number) => Promise<void>;
warn: (message: string) => void;
t: ComposerTranslation;
}
/**
* 把后端返回的图片检索错误翻译成业务用户能看懂的提示。
* AI 触发时机:当用户点击“图片 -> 查看”失败,但原始报错包含接口路径、外部系统术语等技术细节时调用。
* 核心逻辑:优先识别已知的配置/检索异常并转成本地化说明;未知错误保留原始文本,方便排查。
* 核心逻辑:优先识别已知的配置/检索异常并转成中文说明;未知错误保留原始文本,方便排查。
* 参数与输出约束:只负责展示文案,不吞掉真实错误对象;返回值必须适合作为 toast 直接展示。
*/
function normalizeAssetImageErrorMessage(message: string, t: ComposerTranslation): string {
function normalizeAssetImageErrorMessage(message: string): string {
const normalizedMessage = String(message || '').trim();
const lowerCaseMessage = normalizedMessage.toLowerCase();
if (lowerCaseMessage.includes('固定资产图片文档库未配置')) {
return String(t('chat.assetImage.libraryNotConfigured'));
return '当前系统暂未配置固定资产图片文档库,暂时无法查看图片,请联系管理员处理。';
}
if (lowerCaseMessage.includes('请求的资源不存在')) {
return String(t('chat.assetImage.noPhotoUploaded'));
return '设备管理员还未上传照片~';
}
if (lowerCaseMessage.includes('未找到资产')) {
return normalizedMessage;
}
return normalizedMessage || String(t('chat.assetImage.searchFailed'));
return normalizedMessage || '检索固定资产图片失败';
}
export function useChatAssetImage(options: UseChatAssetImageOptions) {
const loading = ref(false);
const { t } = options;
/**
* 检索固定资产图片并直接打开预览。
* AI 触发时机:当用户点击聊天表格或 CSV 预览里的“图片 -> 查看”时调用。
* 核心逻辑:先向后端请求全部命中的图片文件,再把图片组交给通用 FilePreviewModal 预览。
* 核心逻辑:先向后端请求全部命中的图片文件,再把图片组交给通用 FilePreviewModal 预览。
* 参数约束:至少要提供资产编号或资产名称之一;后端负责登录外部文档库和挑选最佳图片。
*/
const openImage = async (nextAssetId: string, nextAssetName = '') => {
@@ -54,7 +51,7 @@ export function useChatAssetImage(options: UseChatAssetImageOptions) {
const normalizedAssetName = String(nextAssetName || '').trim();
if (loading.value) return;
if (!normalizedAssetId && !normalizedAssetName) {
options.warn(String(t('chat.assetImage.missingIdentifier')));
options.warn('当前资产缺少可用于检索图片的编号或名称');
return;
}
@@ -69,7 +66,7 @@ export function useChatAssetImage(options: UseChatAssetImageOptions) {
: (result?.item ? [result.item] : []);
if (!items.length) {
const displayName = normalizedAssetId || normalizedAssetName;
options.warn(String(t('chat.assetImage.notFound', { name: displayName })));
options.warn(`未找到资产 ${displayName} 的图片文件,请联系管理员补充。`);
return;
}
await options.openPreviewGallery(
@@ -81,12 +78,12 @@ export function useChatAssetImage(options: UseChatAssetImageOptions) {
0,
);
} catch (err: unknown) {
const rawMessage = err instanceof Error ? err.message : String(t('chat.assetImage.searchFailed'));
const message = normalizeAssetImageErrorMessage(rawMessage, t);
if (message === String(t('chat.assetImage.noPhotoUploaded'))) {
const rawMessage = err instanceof Error ? err.message : '检索固定资产图片失败';
const message = normalizeAssetImageErrorMessage(rawMessage);
if (message === '设备管理员还未上传照片~') {
options.warn(message);
} else {
options.warn(String(t('chat.assetImage.queryFailed', { message })));
options.warn(`图片查询失败:${message}`);
}
} finally {
loading.value = false;
@@ -0,0 +1,168 @@
/**
* features/chat/composables/useChatAttachments.spec.ts
* 用途:验证普通聊天附件的逐文件上传状态、成功缓存、失败重试与删除保护。
* 依赖:Vitest、Vue 响应式 API、mock 后的 chat.api。
* 逻辑:直接调用 useChatAttachments,断言附件状态与生成的 Dify 文件参数保持一致。
*/
import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { uploadChatFile } from '../api/chat.api';
import { useChatAttachments } from './useChatAttachments';
import type { ChatDeps } from './chat.deps';
vi.mock('../api/chat.api', () => ({
uploadChatFile: vi.fn(),
}));
const uploadChatFileMock = vi.mocked(uploadChatFile);
/** 创建满足 composable 依赖的最小测试上下文。 */
function createAttachments() {
return useChatAttachments({
deps: {
t: ((key: string, params?: Record<string, unknown>) => `${key}${params ? JSON.stringify(params) : ''}`),
msg: { warning: vi.fn() },
} as unknown as ChatDeps,
currentAgentId: computed(() => 7),
currentAgent: ref({
capabilities: { file_upload: true },
dify_parameters: {
file_upload: {
document: { enabled: true, transfer_methods: ['local_file'] },
},
},
}),
});
}
/** 向附件状态中加入一个普通本地文件。 */
function selectLocalFile(api: ReturnType<typeof createAttachments>, name = 'order.pdf') {
const file = new File(['content'], name, { type: 'application/pdf' });
api.handleLocalFilesSelected({ target: { files: [file], value: 'selected' } } as unknown as Event);
return api.attachments.value.at(-1);
}
describe('useChatAttachments upload states', () => {
beforeEach(() => {
uploadChatFileMock.mockReset();
});
it('marks a successful local upload ready and reuses its upload id', async () => {
const api = createAttachments();
const attachment = selectLocalFile(api);
uploadChatFileMock.mockResolvedValue({ id: 'upload-1' });
const firstSpecs = await api.buildFileSpecsForSend();
const secondSpecs = await api.buildFileSpecsForSend();
expect(attachment).toMatchObject({
kind: 'local',
uploadStatus: 'uploaded',
uploadProgress: 100,
uploadFileId: 'upload-1',
});
expect(firstSpecs).toEqual([{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-1' }]);
expect(secondSpecs).toEqual(firstSpecs);
expect(uploadChatFileMock).toHaveBeenCalledTimes(1);
});
it('keeps a failed attachment and retries it on the next send', async () => {
const api = createAttachments();
const attachment = selectLocalFile(api);
uploadChatFileMock
.mockRejectedValueOnce(new Error('network unavailable'))
.mockResolvedValueOnce({ id: 'upload-retry' });
await expect(api.buildFileSpecsForSend()).rejects.toThrow('network unavailable');
expect(attachment).toMatchObject({
uploadStatus: 'failed',
uploadProgress: 0,
errorMessage: 'network unavailable',
});
await expect(api.buildFileSpecsForSend()).resolves.toEqual([
{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-retry' },
]);
expect(attachment).toMatchObject({ uploadStatus: 'uploaded', uploadFileId: 'upload-retry' });
expect(attachment && 'errorMessage' in attachment ? attachment.errorMessage : undefined).toBeUndefined();
});
it('explicitly retries only the selected failed attachment', async () => {
const api = createAttachments();
const first = selectLocalFile(api, 'first.pdf');
const second = selectLocalFile(api, 'second.pdf');
if (first?.kind === 'local') first.uploadStatus = 'failed';
if (second?.kind === 'local') {
second.uploadStatus = 'uploaded';
second.uploadFileId = 'upload-second';
}
uploadChatFileMock.mockResolvedValueOnce({ id: 'upload-first-retry' });
await expect(api.retryAttachment(first?.id || '')).resolves.toBe(true);
expect(uploadChatFileMock).toHaveBeenCalledOnce();
expect(uploadChatFileMock).toHaveBeenCalledWith(7, first && 'file' in first ? first.file : undefined);
expect(first).toMatchObject({ uploadStatus: 'uploaded', uploadFileId: 'upload-first-retry' });
expect(second).toMatchObject({ uploadStatus: 'uploaded', uploadFileId: 'upload-second' });
});
it('keeps explicit retry failures available for another retry', async () => {
const api = createAttachments();
const attachment = selectLocalFile(api);
if (attachment?.kind === 'local') attachment.uploadStatus = 'failed';
uploadChatFileMock.mockRejectedValueOnce(new Error('still unavailable'));
await expect(api.retryAttachment(attachment?.id || '')).resolves.toBe(false);
expect(attachment).toMatchObject({
uploadStatus: 'failed',
uploadProgress: 0,
errorMessage: 'still unavailable',
});
expect(api.attachments.value).toHaveLength(1);
});
it('reuses earlier successful files when a later file failed', async () => {
const api = createAttachments();
selectLocalFile(api, 'first.pdf');
selectLocalFile(api, 'second.pdf');
uploadChatFileMock
.mockResolvedValueOnce({ id: 'upload-first' })
.mockRejectedValueOnce(new Error('second failed'))
.mockResolvedValueOnce({ id: 'upload-second' });
await expect(api.buildFileSpecsForSend()).rejects.toThrow('second failed');
expect(api.attachments.value[0]).toMatchObject({
uploadStatus: 'uploaded',
uploadFileId: 'upload-first',
});
expect(api.attachments.value[1]).toMatchObject({ uploadStatus: 'failed' });
await expect(api.buildFileSpecsForSend()).resolves.toEqual([
{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-first' },
{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-second' },
]);
expect(uploadChatFileMock).toHaveBeenCalledTimes(3);
});
it('does not remove a local attachment while its request is uploading', async () => {
const api = createAttachments();
const attachment = selectLocalFile(api);
let resolveUpload: ((value: { id: string }) => void) | undefined;
uploadChatFileMock.mockImplementation(() => new Promise((resolve) => {
resolveUpload = resolve;
}));
const buildPromise = api.buildFileSpecsForSend();
await Promise.resolve();
expect(attachment && 'uploadStatus' in attachment ? attachment.uploadStatus : undefined).toBe('uploading');
api.removeAttachment(attachment?.id || '');
expect(api.attachments.value).toHaveLength(1);
resolveUpload?.({ id: 'upload-finished' });
await buildPromise;
api.removeAttachment(attachment?.id || '');
expect(api.attachments.value).toHaveLength(0);
});
});
@@ -1,9 +1,12 @@
/**
* features/chat/composables/useChatAttachments.ts
* Dify 附件策略解析、本地/URL 附件管理与发送前上传。
* 用途:解析 Dify 附件策略,管理本地/URL 附件,并在发送前逐文件上传。
* 依赖:chat.api 的附件上传接口、chat.deps 的消息提示能力。
* 逻辑:Chat 页面通过本 composable 维护附件状态;发送流程调用 buildFileSpecsForSend 生成 Dify 文件参数。
*/
import { computed, ref, type ComputedRef, type Ref } from 'vue';
import { uploadChatFile } from '../api/chat.api';
import { createChatMessageAttachmentSnapshots } from '../utils/attachmentCard.utils';
import type { PendingAttachment } from '../types/shipping.types';
import type { ChatDeps } from './chat.deps';
import { isProcurementContractAgent as resolveProcurementContractAgent } from '@/shared/utils/agent-registry.utils';
@@ -256,7 +259,13 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
return resolveDifyType(ext, file.type || '');
};
/**
* 删除未在上传中的附件,避免界面移除后网络请求仍继续造成状态失配。
* @param id - 待删除附件的本地唯一标识
*/
const removeAttachment = (id: string) => {
const target = attachments.value.find((attachment) => attachment.id === id);
if (target?.kind === 'local' && target.uploadStatus === 'uploading') return;
attachments.value = attachments.value.filter((a) => a.id !== id);
};
@@ -299,7 +308,14 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
msg.warning(t('chat.attachmentsUi.typeLimitReached', { limit: caps.limit }));
continue;
}
attachments.value.push({ id: `${Date.now()}_${Math.random()}`, kind: 'local', file: f, type });
attachments.value.push({
id: `${Date.now()}_${Math.random()}`,
kind: 'local',
file: f,
type,
uploadStatus: 'waiting',
uploadProgress: 0,
});
}
if (inputEl) inputEl.value = '';
};
@@ -347,6 +363,59 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
attachments.value.push({ id: `${Date.now()}_${Math.random()}`, kind: 'remote', url, type });
};
/**
* 上传单个普通本地附件;成功上传 ID 可被发送流程复用。
* @param item - 必须是仍存在于输入区的本地附件
* @returns Dify 本地文件参数
*/
const uploadLocalAttachment = async (
item: Extract<PendingAttachment, { kind: 'local' }>,
): Promise<ChatUploadFileSpec> => {
if (item.uploadStatus === 'uploaded' && item.uploadFileId) {
return { type: item.type, transfer_method: 'local_file', upload_file_id: item.uploadFileId };
}
item.uploadStatus = 'uploading';
item.uploadProgress = 0;
item.errorMessage = undefined;
try {
const uploaded = await uploadChatFile(currentAgentId.value, item.file);
if (!uploaded?.id) throw new Error(t('chat.attachment.missingUploadId'));
item.uploadStatus = 'uploaded';
item.uploadProgress = 100;
item.uploadFileId = uploaded.id;
return { type: item.type, transfer_method: 'local_file', upload_file_id: uploaded.id };
} catch (error: unknown) {
item.uploadStatus = 'failed';
item.uploadProgress = 0;
item.uploadFileId = undefined;
item.errorMessage = error instanceof Error ? error.message : t('chat.attachment.uploadFailed');
throw error;
}
};
/** 用户从失败卡片显式重试单个普通附件,不触发整条消息发送。 */
const retryAttachment = async (id: string): Promise<boolean> => {
const target = attachments.value.find(
(item): item is Extract<PendingAttachment, { kind: 'local' }> => item.id === id && item.kind === 'local',
);
if (!target || target.uploadStatus !== 'failed' || isUploadingAttachments.value) return false;
isUploadingAttachments.value = true;
try {
await uploadLocalAttachment(target);
return true;
} catch {
return false;
} finally {
isUploadingAttachments.value = false;
}
};
/**
* 将待发送附件转换为 Dify 文件参数,并逐个更新本地文件的真实上传状态。
* 核心逻辑:复用已成功上传的 uploadFileId;失败附件保留并在下次发送时重试。
* @returns 可直接传给聊天接口的文件参数列表
* @throws 任一本地附件上传失败时抛出原始错误,中止本次消息发送
*/
const buildFileSpecsForSend = async (): Promise<ChatUploadFileSpec[]> => {
if (!attachmentPolicy.value.anyEnabled) return [];
if (attachments.value.length === 0) return [];
@@ -359,11 +428,7 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
isUploadingAttachments.value = true;
try {
for (const item of locals) {
const uploaded = await uploadChatFile(currentAgentId.value, item.file);
if (!uploaded?.id) {
throw new Error('Missing upload id');
}
specs.push({ type: item.type, transfer_method: 'local_file', upload_file_id: uploaded.id });
specs.push(await uploadLocalAttachment(item));
}
} finally {
isUploadingAttachments.value = false;
@@ -381,14 +446,24 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
attachments.value = [];
};
/**
* 固化当前待发送附件,供发送成功后的用户消息展示。
* @returns 与当前附件顺序一致、可 JSON 序列化的安全快照
*/
const createMessageAttachmentSnapshots = () => (
createChatMessageAttachmentSnapshots(attachments.value)
);
return {
attachments,
isUploadingAttachments,
attachmentPolicy,
removeAttachment,
retryAttachment,
handleLocalFilesSelected,
addRemoteUrlAttachment,
buildFileSpecsForSend,
createMessageAttachmentSnapshots,
clearAttachments,
};
}
@@ -3,7 +3,7 @@
* Agent 学习之窗:指南列表加载与弹窗状态。
*/
import { computed, ref, type ComputedRef } from 'vue';
import { listAgentGuides } from '@/features/user';
import { listAgentGuides } from '@/features/auth/api/user.api';
export interface AgentGuide {
id: number;
@@ -8,7 +8,7 @@
* - leave-result:OA 提交结果
*/
import { computed, type ComputedRef, type Ref } from 'vue';
import { getUserProfile } from '@/features/user';
import { getUserProfile } from '@/features/auth/api/user.api';
import { canUseLeaveFeature as resolveLeaveFeatureEnabled } from '@/shared/utils/agent-registry.utils';
import type { AgentRegistryFields } from '@/shared/utils/agent-registry.utils';
import { LEAVE_TYPES } from '../constants/leave';
@@ -120,9 +120,9 @@ export function useChatLeave(options: UseChatLeaveOptions) {
canUseLeaveFeature,
...oaLogin,
...agentPicker,
getLeaveTypeLabel: (val: string) => getLeaveTypeLabel(val, t),
getLeaveTypeLabel,
formatDurationLabel: (hours: number, leaveType?: string) => formatDurationLabel(hours, leaveType, t),
formatYesNoLabel: (value: 0 | 1 | null) => formatYesNoLabel(value, t),
formatYesNoLabel,
syncLeaveDuration,
getLeaveFormPayload,
getLeaveConfirmationPayload,
@@ -1,6 +1,9 @@
/**
* features/chat/composables/useChatPage.ts
* 对话页主编排:组合 SSE、Agent、附件、请假/出货/采购合同、路由同步与 page/* 子模块。
* 用途:对话页主编排;组合 SSE、Agent、附件、请假/出货、路由同步与 page/* 子模块。
* 依赖:useChat* composables、shipping(含 openShippingCustomerDialog)、chat.api。
* 逻辑:ChatView provide(CHAT_PAGE_KEY);子树经 inject 打开客户确认等叠层。
* 兼容:同时编排采购合同审查与货代客户确认能力。
*/
import { computed, markRaw, nextTick, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
@@ -32,14 +35,13 @@ import { useChatStore } from '../stores/chat.store';
import { useTrainingWorkspace } from './useTrainingWorkspace';
import { matchesTrainingAgent } from '../training/trainingWorkspace.utils';
import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy';
import { clearPendingNoticeBatchRetry } from '../shipping/useChatShippingUploadHandler';
import {
createChatPageConversationApi,
createChatPageLocalMessageApi,
createChatPageMarkdownApi,
createChatPageSendApi,
createLeaveMessageHandlers,
createShippingMappingHandlers,
createShippingMessageHandlers,
createShippingPickerRefHolder,
createTrainingHandlers,
useChatPageDialogs,
@@ -180,13 +182,11 @@ export function useChatPage() {
agentId: currentAgentId,
openPreview,
warn: (text) => msg.warning(text),
t,
});
const assetImage = useChatAssetImage({
agentId: currentAgentId,
openPreviewGallery,
warn: (text) => msg.warning(text),
t,
});
watch(currentAgentId, (id) => {
@@ -194,7 +194,7 @@ export function useChatPage() {
}, { immediate: true });
const dialogs = useChatPageDialogs(messages);
const { openDeleteConfirmDialog, openRetryFailedConfirm, showShippingToast } = dialogs;
const { openDeleteConfirmDialog } = dialogs;
let loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
let startNewChat: () => void;
@@ -292,7 +292,6 @@ export function useChatPage() {
history,
loadHistory,
input,
chatScrollContainer,
attachments: attachmentApi.attachments,
selectedKb: agent.selectedKb,
isUploadingAttachments: attachmentApi.isUploadingAttachments,
@@ -318,7 +317,7 @@ export function useChatPage() {
isUploadingAttachments: attachmentApi.isUploadingAttachments,
input,
clearAttachments: attachmentApi.clearAttachments,
saveLocalMessageToBackend,
saveLocalMessageToBackend: async (msg, userQuery) => { await saveLocalMessageToBackend(msg, userQuery); },
loadHistory,
msg,
t,
@@ -330,29 +329,6 @@ export function useChatPage() {
|| procurement.allowsSendWithAttachmentsOnly.value,
);
/**
* Drawer「重试所有失败」点击:仅打开确认弹窗,不立刻发请求。
*/
const openRetryFailedConfirmDialog = () => {
if (shipping.retryingShippingPendingTasks.value) return;
openRetryFailedConfirm(() => confirmRetryFailedTasks());
};
/**
* 确认后执行批次失败任务重试,并以非阻塞 toast 反馈结果。
* 核心逻辑:调用 useChatShipping.retryCurrentShippingBatchPendingTasks,成功后刷新已内置;仅补 toast。
*/
const confirmRetryFailedTasks = async () => {
const result = await shipping.retryCurrentShippingBatchPendingTasks();
if (!result) return;
showShippingToast(
t('chat.shippingNoticeUi.retryFailedStarted', {
started: result.started,
skipped: result.skipped,
}),
);
};
const conversationApi = createChatPageConversationApi({
deps,
route,
@@ -364,13 +340,11 @@ export function useChatPage() {
isThinking,
loadConversationState,
createNewChatView,
clearPendingNoticeBatchRetry,
onConversationIdChanging: shipping.onConversationIdChanging,
onConversationLoadedEmpty: shipping.onConversationLoadedEmpty,
onConversationLoadFailed: shipping.onConversationLoadFailed,
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
shippingTaskIdFromQuery: shipping.shippingTaskIdFromQuery,
shippingBatchNoFromQuery: shipping.shippingBatchNoFromQuery,
clearHistory,
clearAttachments: attachmentApi.clearAttachments,
input,
@@ -421,13 +395,10 @@ export function useChatPage() {
getSourceTitle,
getSourceMeta,
getSourceBrief,
getShippingInventoryMappingPayload: shipping.getShippingInventoryMappingPayload,
getShippingMatchResultPayload: shipping.getShippingMatchResultPayload,
canOpenQueryPreview: queryPreview.canOpen,
getQueryPreviewSummary: queryPreview.getSummary,
openQueryPreviewDialog: queryPreview.openDialog,
shippingActionButtonClass: shipping.shippingActionButtonClass,
onShippingActionClick: shipping.handleShippingActionClick,
});
const sendApi = createChatPageSendApi({
@@ -441,6 +412,7 @@ export function useChatPage() {
attachments: attachmentApi.attachments,
allowsSendWithAttachmentsOnly,
buildFileSpecsForSend: attachmentApi.buildFileSpecsForSend,
createMessageAttachmentSnapshots: attachmentApi.createMessageAttachmentSnapshots,
clearAttachments: attachmentApi.clearAttachments,
sendMessage,
getChatContext: shipping.isShippingNoticeAgent ? shipping.getCurrentShippingChatContext : undefined,
@@ -482,7 +454,7 @@ export function useChatPage() {
shipping.shippingBindSend(() => sendApi.handleSend());
const leaveMessageHandlers = createLeaveMessageHandlers(leave);
const shippingMappingHandlers = createShippingMappingHandlers(shipping);
const shippingMessageHandlers = createShippingMessageHandlers(shipping);
const trainingHandlers = createTrainingHandlers(training);
const shippingPickerRefHolder = markRaw(createShippingPickerRefHolder(shipping.shippingInventoryPickerRef));
const shippingNoticePickerRefHolder = markRaw(createShippingPickerRefHolder(shipping.shippingNoticePickerRef));
@@ -494,7 +466,6 @@ export function useChatPage() {
currentAgentId,
presetQuestion,
shippingTaskIdFromQuery: shipping.shippingTaskIdFromQuery,
shippingBatchNoFromQuery: shipping.shippingBatchNoFromQuery,
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
resetChatStateForAgentChange,
cancelVoiceInput: voice.cancelVoiceInput,
@@ -578,6 +549,8 @@ export function useChatPage() {
attachmentApi.removeAttachment(id);
},
retryShippingNoticeAttachment: shipping.retryShippingNoticeAttachment,
setShippingCandidateSelected: shipping.setShippingCandidateSelected,
resolveShippingCandidateDuplicate: shipping.resolveShippingCandidateDuplicate,
showShippingDuplicateDialog: shipping.showShippingDuplicateDialog,
shippingDuplicateAttachment: shipping.shippingDuplicateAttachment,
canForceCreateShippingDuplicate: shipping.canForceCreateShippingDuplicate,
@@ -585,6 +558,13 @@ export function useChatPage() {
resolveShippingDuplicateDialog: shipping.resolveShippingDuplicateDialog,
removeShippingDuplicateDialogAttachment: shipping.removeShippingDuplicateDialogAttachment,
closeShippingDuplicateDialog: shipping.closeShippingDuplicateDialog,
showShippingCustomerDialog: shipping.showShippingCustomerDialog,
shippingCustomerOptions: shipping.shippingCustomerOptions,
shippingCustomerLoading: shipping.shippingCustomerLoading,
openShippingCustomerDialog: shipping.openShippingCustomerDialog,
searchShippingCustomers: shipping.searchShippingCustomers,
confirmShippingCustomer: shipping.confirmShippingCustomer,
closeShippingCustomerDialog: shipping.closeShippingCustomerDialog,
filePreviewVisible,
previewFile,
previewFiles,
@@ -605,7 +585,7 @@ export function useChatPage() {
training,
...leave,
leaveMessageHandlers,
shippingMappingHandlers,
shippingMessageHandlers,
trainingHandlers,
shippingPickerRefHolder,
shippingNoticePickerRefHolder,
@@ -626,10 +606,6 @@ export function useChatPage() {
deleteConfirmMessage: dialogs.deleteConfirmMessage,
closeDeleteConfirmDialog: dialogs.closeDeleteConfirmDialog,
handleDeleteConfirm: dialogs.handleDeleteConfirm,
showRetryFailedConfirmDialog: dialogs.showRetryFailedConfirmDialog,
closeRetryFailedConfirm: dialogs.closeRetryFailedConfirm,
handleRetryFailedConfirm: dialogs.handleRetryFailedConfirm,
openRetryFailedConfirm: openRetryFailedConfirmDialog,
shippingToastMessage: dialogs.shippingToastMessage,
clearShippingToast: dialogs.clearShippingToast,
showChatRating,
@@ -640,22 +616,15 @@ export function useChatPage() {
handleProcurementOriginalContractSelected: procurement.handleOriginalContractSelected,
clearProcurementOriginalContract: procurement.clearOriginalContract,
showShippingProgressWorkspace: shipping.showShippingProgressWorkspace,
shippingBatchSummary: shipping.shippingBatchSummary,
shippingConversationWorkspace: shipping.shippingConversationWorkspace,
activeShippingBatchNo: shipping.activeShippingBatchNo,
focusedShippingTaskNo: shipping.focusedShippingTaskNo,
shippingFocusReason: shipping.shippingFocusReason,
shippingBatchTasks: shipping.shippingBatchTasks,
clearShippingFocus: shipping.clearShippingFocus,
activeShippingTaskDetail: shipping.activeShippingTaskDetail,
shippingWorkspaceOpen: shipping.shippingWorkspaceOpen,
retryingShippingPendingTasks: shipping.retryingShippingPendingTasks,
getActiveOrderExtractionRunNo: shipping.getActiveOrderExtractionRunNo,
workflowRefreshTrigger: shipping.workflowRefreshTrigger,
bumpWorkflowRefresh: shipping.bumpWorkflowRefresh,
focusedConversationTaskNo: shipping.focusedConversationTaskNo,
setFocusedConversationTaskNo: shipping.setFocusedConversationTaskNo,
shippingInventorySelectionActive: shipping.shippingInventorySelectionActive,
shippingInventorySelectionTaskId: shipping.shippingInventorySelectionTaskId,
switchShippingBatch: shipping.switchShippingBatch,
switchShippingFocusTask: shipping.switchShippingFocusTask,
clearShippingFocus: shipping.clearShippingFocus,
handleShippingWorkspaceAction: shipping.handleShippingWorkspaceAction,
retryCurrentShippingBatchPendingTasks: shipping.retryCurrentShippingBatchPendingTasks,
queryShippingShortageDetails: shipping.queryShippingShortageDetails,
selectShippingInventoryUploadTask: shipping.selectShippingInventoryUploadTask,
cancelShippingInventoryTaskSelection: shipping.cancelShippingInventoryTaskSelection,
@@ -1,11 +1,8 @@
/**
* features/chat/composables/useChatQueryPreview.ts
* 用途:Text2SQL 查询结果全量预览弹窗:分页加载与消息 payload 解析。
* 依赖:vue-i18n、chat.api.getChatQueryPreviewPage、chat.types.ChatMessage。
* 逻辑:Chat 消息气泡触发 openDialog;文案走 chat.queryPreview.*。
* Text2SQL 查询结果全量预览弹窗:分页加载与消息 payload 解析。
*/
import { ref, type ComputedRef } from 'vue';
import { useI18n } from 'vue-i18n';
import { getChatQueryPreviewPage } from '../api/chat.api';
import type { ChatMessage } from '../types/chat.types';
@@ -32,15 +29,8 @@ export interface UseChatQueryPreviewOptions {
currentAgentId: ComputedRef<number>;
}
/**
* 组装查询结果全量预览弹窗状态与分页加载逻辑。
* 核心逻辑:从消息 payload 判断可预览;调用 getChatQueryPreviewPage 拉取分页数据。
* @param options.currentAgentId - 当前 Agent ID(请求预览接口必填)
* @returns 弹窗状态、摘要文案与 open/close/changePage 操作
*/
export function useChatQueryPreview(options: UseChatQueryPreviewOptions) {
const { currentAgentId } = options;
const { t } = useI18n();
const show = ref(false);
const loading = ref(false);
@@ -56,11 +46,6 @@ export function useChatQueryPreview(options: UseChatQueryPreviewOptions) {
total: 0,
});
/**
* 从消息中提取 text2sql 预览 payload。
* @param msg - 聊天消息
* @returns 预览 payload;非目标 kind 时返回 null
*/
const getPayload = (msg: ChatMessage): QueryPreviewPayload | null => {
const payload = msg?.payload;
if (!payload || typeof payload !== 'object') return null;
@@ -68,52 +53,29 @@ export function useChatQueryPreview(options: UseChatQueryPreviewOptions) {
return payload as QueryPreviewPayload;
};
/**
* 判断消息是否可打开全量预览。
* @param msg - 聊天消息
* @returns 是否可预览
*/
const canOpen = (msg: ChatMessage) => {
const payload = getPayload(msg);
return !!(payload?.previewable && Number(msg?.chat_log_id) > 0);
};
/**
* 生成“查看全部预览”摘要文案(含可选总条数)。
* @param msg - 聊天消息
* @returns 本地化摘要
*/
const getSummary = (msg: ChatMessage) => {
const payload = getPayload(msg);
const total = Number(payload?.total_count || 0);
if (total > 0) return t('chat.queryPreview.viewAllWithTotal', { total });
return t('chat.queryPreview.viewAll');
if (total > 0) return `查看全部预览(共 ${total} 条)`;
return '查看全部预览';
};
/**
* 按当前 pageSize 计算总页数。
* @returns 至少为 1 的页数
*/
const totalPages = () =>
Math.max(1, Math.ceil((state.value.total || 0) / (state.value.pageSize || 100)));
/**
* 关闭预览弹窗并清空错误。
*/
const close = () => {
show.value = false;
error.value = '';
};
/**
* 拉取指定 chat_log 的分页预览数据。
* 核心逻辑:Agent 未就绪时写本地化错误;成功后合并 state;失败回落 loadFailed。
* @param chatLogId - 聊天日志 ID
* @param page - 页码,默认 1
*/
const loadPage = async (chatLogId: number, page = 1) => {
if (!currentAgentId.value) {
error.value = t('chat.queryPreview.agentNotReady');
error.value = '当前 Agent 未就绪,请稍后重试';
return;
}
loading.value = true;
@@ -123,11 +85,10 @@ export function useChatQueryPreview(options: UseChatQueryPreviewOptions) {
page,
page_size: state.value.pageSize,
});
const fallbackTitle = t('chat.queryPreview.title');
state.value = {
...state.value,
chatLogId,
title: String(result.query || state.value.title || fallbackTitle).trim() || fallbackTitle,
title: String(result.query || state.value.title || '查询结果全量预览').trim() || '查询结果全量预览',
query: String(result.query || '').trim(),
columns: Array.isArray(result.columns) ? result.columns : [],
rows: Array.isArray(result.rows) ? result.rows : [],
@@ -136,25 +97,20 @@ export function useChatQueryPreview(options: UseChatQueryPreviewOptions) {
total: Number(result.total || 0),
};
} catch (err: unknown) {
error.value = (err as { message?: string })?.message || t('chat.queryPreview.loadFailed');
error.value = (err as { message?: string })?.message || '加载全量预览失败';
} finally {
loading.value = false;
}
};
/**
* 打开预览弹窗并加载第一页。
* @param msg - 触发预览的聊天消息
*/
const openDialog = async (msg: ChatMessage) => {
const chatLogId = Number(msg?.chat_log_id || 0);
if (!chatLogId) return;
const payload = getPayload(msg);
const fallbackTitle = t('chat.queryPreview.title');
state.value = {
...state.value,
chatLogId,
title: String(payload?.query || msg?.content || fallbackTitle).trim() || fallbackTitle,
title: String(payload?.query || msg?.content || '查询结果全量预览').trim() || '查询结果全量预览',
query: String(payload?.query || '').trim(),
page: 1,
total: Number(payload?.total_count || 0),
@@ -163,10 +119,6 @@ export function useChatQueryPreview(options: UseChatQueryPreviewOptions) {
await loadPage(chatLogId, 1);
};
/**
* 相对当前页翻页并重新加载。
* @param delta - 页码增量(通常 ±1)
*/
const changePage = async (delta: number) => {
const nextPage = state.value.page + delta;
if (nextPage < 1 || nextPage > totalPages()) return;
@@ -0,0 +1,63 @@
/**
* features/chat/composables/useChatRouteSync.spec.ts
* 用途:验证聊天路由初始化的关键首屏请求调度。
* 依赖:vitest、useChatRouteSync。
* 逻辑:历史会话列表属于后台辅助数据,不能阻塞指定 conversation 的消息与进度加载。
*/
import { describe, expect, it, vi } from 'vitest';
vi.mock('vue', () => ({
onBeforeUnmount: vi.fn(),
onMounted: vi.fn(),
watch: vi.fn(),
}));
import { useChatRouteSync } from './useChatRouteSync';
describe('useChatRouteSync', () => {
it('starts the requested conversation before the history list resolves', async () => {
let resolveHistory!: () => void;
const loadHistory = vi.fn(() => new Promise<void>((resolve) => {
resolveHistory = resolve;
}));
const loadConversation = vi.fn(async () => undefined);
const routeSync = useChatRouteSync({
deps: {
route: {
params: { agentId: '24' },
query: { conversation_id: 'conversation-b' },
},
router: { push: vi.fn() },
} as never,
currentAgentId: { value: 24 } as never,
presetQuestion: { value: '' } as never,
shippingTaskIdFromQuery: { value: null } as never,
isShippingNoticeAgent: { value: true } as never,
resetChatStateForAgentChange: vi.fn(),
cancelVoiceInput: vi.fn(),
syncCurrentUserProfile: vi.fn(async () => undefined),
loadAgent: vi.fn(async () => undefined),
loadUserAgents: vi.fn(async () => undefined),
loadHistory,
loadConversation,
resumeShippingTaskFromQuery: vi.fn(async () => undefined),
handleSend: vi.fn(async () => undefined),
createNewChatView: vi.fn(),
onAuthLogout: vi.fn(),
onViewportResize: vi.fn(),
disposePeripherals: vi.fn(),
scheduleScrollToBottom: vi.fn(),
input: { value: '' } as never,
});
const pending = routeSync.syncChatStateForRoute();
await vi.waitFor(() => {
expect(loadHistory).toHaveBeenCalledTimes(1);
expect(loadConversation).toHaveBeenCalledWith('conversation-b', { force: true });
});
resolveHistory();
await pending;
});
});
@@ -13,7 +13,6 @@ export interface UseChatRouteSyncOptions {
currentAgentId: ComputedRef<number>;
presetQuestion: ComputedRef<string>;
shippingTaskIdFromQuery: ComputedRef<string | null>;
shippingBatchNoFromQuery?: ComputedRef<string | null>;
isShippingNoticeAgent: ComputedRef<boolean>;
resetChatStateForAgentChange: () => void;
cancelVoiceInput: () => void;
@@ -39,7 +38,6 @@ export function useChatRouteSync(options: UseChatRouteSyncOptions) {
currentAgentId,
presetQuestion,
shippingTaskIdFromQuery,
shippingBatchNoFromQuery,
resetChatStateForAgentChange,
cancelVoiceInput,
syncCurrentUserProfile,
@@ -94,16 +92,23 @@ export function useChatRouteSync(options: UseChatRouteSyncOptions) {
await loadUserAgents();
if (syncToken !== routeSyncToken) return;
await loadHistory();
if (syncToken !== routeSyncToken) return;
const convId = route.query.conversation_id as string;
// 历史列表是辅助内容;直达会话时不能阻塞消息/货代 Projection 的首屏读取。
const historyPromise = loadHistory();
if (convId) {
await loadConversation(convId, { force: true });
await Promise.all([
historyPromise,
loadConversation(convId, { force: true }),
]);
if (syncToken !== routeSyncToken) return;
} else if (shippingTaskIdFromQuery.value) {
await historyPromise;
if (syncToken !== routeSyncToken) return;
} else if (shippingTaskIdFromQuery.value || shippingBatchNoFromQuery?.value) {
await resumeShippingTaskFromQuery();
if (syncToken !== routeSyncToken) return;
} else {
await historyPromise;
if (syncToken !== routeSyncToken) return;
}
if (presetQuestion.value) {
@@ -122,17 +127,16 @@ export function useChatRouteSync(options: UseChatRouteSyncOptions) {
});
watch(
() => [route.params.agentId, route.query.conversation_id, route.query.preset, route.query.task_id, route.query.batch_no],
() => [route.params.agentId, route.query.conversation_id, route.query.preset, route.query.task_id],
async (
[nextAgentId, nextConversationId, nextPreset, nextTaskId, nextBatchNo],
[prevAgentId, prevConversationId, prevPreset, prevTaskId, prevBatchNo],
[nextAgentId, nextConversationId, nextPreset, nextTaskId],
[prevAgentId, prevConversationId, prevPreset, prevTaskId],
) => {
if (
nextAgentId === prevAgentId
&& nextConversationId === prevConversationId
&& nextPreset === prevPreset
&& nextTaskId === prevTaskId
&& nextBatchNo === prevBatchNo
) {
return;
}
@@ -141,7 +145,6 @@ export function useChatRouteSync(options: UseChatRouteSyncOptions) {
nextAgentId === prevAgentId
&& nextPreset === prevPreset
&& nextTaskId === prevTaskId
&& nextBatchNo === prevBatchNo
&& nextConversationId !== prevConversationId
) {
if (typeof nextConversationId === 'string' && nextConversationId) {
@@ -13,6 +13,7 @@ const { deleteAllChatSessions, deleteChatSession, listChatSessions } = vi.hoiste
deleteChatSession: vi.fn(),
listChatSessions: vi.fn(),
}));
const listWorkspaceShippingOrderExtractionRuns = vi.hoisted(() => vi.fn());
const {
getSessionHistory,
@@ -29,6 +30,7 @@ vi.mock('../api/chat.api', () => ({
deleteChatSession,
listChatSessions,
}));
vi.mock('../api/shipping.api', () => ({ listWorkspaceShippingOrderExtractionRuns }));
vi.mock('../stores/chat.store', () => ({
useChatStore: () => ({
@@ -43,6 +45,7 @@ describe('useChatSessions', () => {
deleteAllChatSessions.mockReset();
deleteChatSession.mockReset();
listChatSessions.mockReset();
listWorkspaceShippingOrderExtractionRuns.mockReset();
getSessionHistory.mockReset();
setSessionHistory.mockReset();
patchSessionHistory.mockReset();
@@ -91,4 +94,41 @@ describe('useChatSessions', () => {
expect(runs.value).toEqual([]);
expect(startNewChat).toHaveBeenCalledTimes(1);
});
it('rebuilds order-review query from the selected conversation', async () => {
const replace = vi.fn();
listWorkspaceShippingOrderExtractionRuns.mockResolvedValue({
items: [{ run_no: 'RUN-NEW', status: 'review_required' }],
});
const sessions = useChatSessions({
deps: {
t: (key: string) => key,
router: { replace },
route: {
path: '/chat/7',
query: {
conversation_id: 'conv-old', mode: 'order-review', run_no: 'RUN-OLD',
case_no: 'CASE-OLD', document_id: '91', focus: 'evidence',
},
},
} as never,
currentAgentId: computed(() => 7),
conversationId: ref('conv-old'),
activeRunId: ref(null),
runs: ref([]),
activateRun: vi.fn(),
loadConversation: vi.fn(async () => {}),
isSidebarOpen: ref(true),
onConfirmDelete: vi.fn(),
startNewChat: vi.fn(),
});
await sessions.handleHistorySelect({ id: 2, conversation_id: 'conv-new' } as never);
expect(listWorkspaceShippingOrderExtractionRuns).toHaveBeenCalledWith('conv-new', 20);
expect(replace).toHaveBeenCalledWith({
path: '/chat/7',
query: { conversation_id: 'conv-new', mode: 'order-review', run_no: 'RUN-NEW' },
});
});
});
@@ -8,6 +8,7 @@ import {
deleteChatSession,
listChatSessions,
} from '../api/chat.api';
import { listWorkspaceShippingOrderExtractionRuns } from '../api/shipping.api';
import type { ChatRun, ChatSessionItem, DisplayHistoryItem } from '../types/chat.types';
import type { ChatDeps } from './chat.deps';
import { useChatStore } from '../stores/chat.store';
@@ -133,6 +134,22 @@ export function useChatSessions(options: UseChatSessionsOptions) {
return;
}
const isOrderReview = route.query.mode === 'order-review';
if (isOrderReview) {
// 复核工作台的 Run/Case/文档上下文属于旧会话,切换时必须整体重建,不能只替换 conversation_id。
const restored = await listWorkspaceShippingOrderExtractionRuns(item.conversation_id, 20);
const nextRun = (restored.items || []).find((candidate) =>
['review_required', 'partially_completed'].includes(String(candidate.status || '')),
);
const nextQuery: Record<string, string> = { conversation_id: item.conversation_id };
if (nextRun?.run_no) {
nextQuery.mode = 'order-review';
nextQuery.run_no = String(nextRun.run_no);
}
await router.replace({ path: route.path, query: nextQuery });
return;
}
const nextQuery: Record<string, string | string[]> = { ...route.query, conversation_id: item.conversation_id };
delete nextQuery.task_id;
delete nextQuery.preset;
@@ -1,64 +1,36 @@
/**
* features/chat/composables/useChatShipping.spec.ts
* 用途:验证发货批次切换后的默认焦点解析,避免右侧工作台沿用旧批次的 focused task。
* 用途:验证聊天恢复只使用单票任务锚点。
* 依赖:vitest、useChatShipping 纯函数导出。
* 逻辑:覆盖 current focus、process summary 回退、首票回退与无任务时清空焦点原因四种路径。
* 逻辑:历史回放只接受 task_no / shipping_ui_state,不恢复已下线批次快照。
*/
import { describe, expect, it } from 'vitest';
import { resolveShippingBatchFocusState } from './useChatShipping';
import { resolveLatestShippingMessageRecoveryPayload } from './useChatShipping';
describe('useChatShipping batch focus sync', () => {
it('prefers batch current focus task and keeps default reason', () => {
expect(resolveShippingBatchFocusState(
describe('useChatShipping message recovery payload', () => {
it('recovers a task anchor and read-only UI state', () => {
const payload = resolveLatestShippingMessageRecoveryPayload([
{
current_focus_task_no: 'SN-BATCH-B2',
process_summary: { current_task_no: 'SN-BATCH-B1' },
role: 'assistant',
content: '已打开已有任务',
payload: {
task_no: 'SN-OPEN-EXISTING',
shipping_ui_state: {
task_no: 'SN-OPEN-EXISTING',
steps: [],
summary: {},
},
},
},
[{ task_no: 'SN-BATCH-B0' }],
'当前聚焦任务',
)).toEqual({
taskNo: 'SN-BATCH-B2',
focusReason: '当前聚焦任务',
});
]);
expect(payload?.task_no).toBe('SN-OPEN-EXISTING');
expect(payload?.shipping_ui_state?.task_no).toBe('SN-OPEN-EXISTING');
});
it('falls back to process summary and first task when current focus is absent', () => {
expect(resolveShippingBatchFocusState(
{
current_focus_task_no: '',
process_summary: { current_task_no: 'SN-BATCH-C1' },
},
[{ task_no: 'SN-BATCH-C0' }],
'当前聚焦任务',
)).toEqual({
taskNo: 'SN-BATCH-C1',
focusReason: '当前聚焦任务',
});
expect(resolveShippingBatchFocusState(
{
current_focus_task_no: '',
process_summary: { current_task_no: '' },
},
[{ task_no: 'SN-BATCH-D0' }],
'当前聚焦任务',
)).toEqual({
taskNo: 'SN-BATCH-D0',
focusReason: '当前聚焦任务',
});
});
it('clears focus state when the new batch has no resolvable task', () => {
expect(resolveShippingBatchFocusState(
{
current_focus_task_no: '',
process_summary: { current_task_no: '' },
},
[],
'当前聚焦任务',
)).toEqual({
taskNo: '',
focusReason: '',
});
it('ignores a legacy batch-only payload', () => {
expect(resolveLatestShippingMessageRecoveryPayload([
{ role: 'assistant', content: '', payload: { shipping_batch_ui_state: { tasks: [] } } },
])).toBeNull();
});
});
File diff suppressed because it is too large. Load diff
@@ -1,8 +1,6 @@
/**
* features/chat/composables/useChatSourceFiles.ts
* 用途:检索来源 / 源文件链接解析与预览。
* 依赖:vue-i18n(t)、chat.api.resolveChatSourceFile、useMessage。
* 逻辑:消息气泡源文件按钮调用 openPreview;缺链时抛 chat.sourcePreviewLinkMissing。
* 检索来源 / 源文件链接解析与预览。
*/
import { ref, type ComputedRef, type Ref } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
@@ -391,7 +389,7 @@ export function useChatSourceFiles({ agentId, t, msg, isMobile }: UseChatSourceF
};
}
}
if (!file.url) throw new Error(t('chat.sourcePreviewLinkMissing'));
if (!file.url) throw new Error('当前源文件暂未返回可预览链接');
return { name: file.name, url: file.url, actualExt: file.actualExt };
};
@@ -0,0 +1,113 @@
/**
* features/chat/composables/useChatTransfer.spec.ts
* 用途:验证预检创建/恢复、选择范围、直接生成执行 Run、结果恢复与防重复。
* 依赖:vi.mock(transfer.api)、useChatTransfer。
* 逻辑:用 Mock API 驱动组合式函数,断言状态流转与调用参数。
*/
import { describe, expect, it, vi, beforeEach } from 'vitest';
const api = vi.hoisted(() => ({
createTransferPrecheck: vi.fn(),
getTransferPrecheck: vi.fn(),
executeTransferPrecheck: vi.fn(),
getTransferRun: vi.fn(),
cancelTransferRun: vi.fn(),
retryTransferItem: vi.fn(),
manualCloseTransferItem: vi.fn(),
downloadTransferReceiptFiles: vi.fn(),
downloadTransferErpInventory: vi.fn(),
downloadTransferExceptions: vi.fn(),
}));
vi.mock('../api/transfer.api', () => api);
import { useChatTransfer } from './useChatTransfer';
const summary = {
precheck_id: 'TPC-20260806-001',
status: 'ready_to_execute',
business_date: '2026-08-06',
eligible_receipt_date_to: '2026-08-05',
expires_at: '',
counts: { file_invoice_count: 2, not_matured_count: 0, prechecked_count: 2, executable_count: 2, blocked_count: 0 },
estimated_transfer_quantity: '2400',
estimated_erp_write_count: 2,
precheck_hash: 'sha256:abc',
};
const detail = {
summary,
sources: [{ source_code: 'DBS-AWSBI', stage: 'file_ready', file_no: 'REC-1' }],
items: [
{ source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: 'x', specification: 'y', invoice_no: 'INV-001', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200', to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable' },
{ source_code: 'DBS-AWSBI', material_no: 'MAT-2', material_name: 'x', specification: 'y', invoice_no: 'INV-002', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200', to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable' },
{ source_code: 'DBS-AWSBI', material_no: 'MAT-3', material_name: 'x', specification: 'y', invoice_no: 'INV-041', from_warehouse: '', from_quantity: null, to_warehouse: '', to_quantity: '400', result: 'not_matured' },
],
};
describe('useChatTransfer', () => {
beforeEach(() => {
vi.clearAllMocks();
api.createTransferPrecheck.mockResolvedValue(summary);
api.getTransferPrecheck.mockResolvedValue(detail);
api.executeTransferPrecheck.mockResolvedValue({ run_no: 'RUN-20260806-1', status: 'success' });
api.getTransferRun.mockResolvedValue({
run_no: 'RUN-20260806-1',
status: 'success',
result: { erp_documents: [], exceptions: [] },
});
});
it('创建预检后默认勾选全部可执行项,未成熟项不可勾选', async () => {
const transfer = useChatTransfer();
await transfer.createPrecheck(['DBS-AWSBI'], '2026-08-06');
expect(transfer.precheckId.value).toBe('TPC-20260806-001');
expect(transfer.executableInvoices.value).toEqual(['INV-001', 'INV-002']);
expect(transfer.selected.value.has('INV-001')).toBe(true);
expect(transfer.selected.value.has('INV-041')).toBe(false);
});
it('执行时提交勾选范围并恢复 Run', async () => {
const transfer = useChatTransfer();
await transfer.createPrecheck(['DBS-AWSBI']);
transfer.toggleSelect('INV-001', false);
await transfer.execute();
expect(api.executeTransferPrecheck).toHaveBeenCalledWith('TPC-20260806-001', ['INV-002']);
expect(transfer.runNo.value).toBe('RUN-20260806-1');
expect(api.getTransferRun).toHaveBeenCalledWith('RUN-20260806-1');
});
it('无选择时执行被拦截(不调用 API)', async () => {
const transfer = useChatTransfer();
await transfer.createPrecheck(['DBS-AWSBI']);
transfer.selected.value = new Set();
const result = await transfer.execute().catch(() => null);
expect(result).toBeNull();
expect(api.executeTransferPrecheck).not.toHaveBeenCalled();
});
it('busy 在请求期间置位,完成后复位(防重复点击)', async () => {
let resolvePrecheck!: (value: unknown) => void;
api.getTransferPrecheck.mockImplementation(
() => new Promise((resolve) => { resolvePrecheck = resolve; }),
);
const transfer = useChatTransfer();
const promise = transfer.createPrecheck(['DBS-AWSBI']);
// 推进微任务链:createTransferPrecheck → getTransferPrecheck(mock 已执行)
await Promise.resolve();
await Promise.resolve();
expect(transfer.busy.value).toBe(true);
resolvePrecheck(detail);
await promise;
expect(transfer.busy.value).toBe(false);
});
it('reset 清空全部状态', async () => {
const transfer = useChatTransfer();
await transfer.createPrecheck(['DBS-AWSBI']);
transfer.reset();
expect(transfer.precheckId.value).toBeNull();
expect(transfer.items.value).toHaveLength(0);
expect(transfer.run.value).toBeNull();
});
});
@@ -0,0 +1,259 @@
/**
* features/chat/composables/useChatTransfer.ts
* 用途:在途仓自动调拨聊天编排入口——预检创建/恢复、选择范围、直接生成执行 Run、
* Run 进度与结果恢复、人工重试/关闭、下载。
* 依赖:transfer.api、transfer.types、useMessage、Vue refs/computed。
* 逻辑:前端只消费稳定 DTO;Run 是异步真相源,刷新/重进由 GET 恢复;
* 防重复点击(busy);错误统一 useMessage 展示 BusinessError。
*/
import { computed, ref, type Ref } from 'vue';
import { useMessage } from '@/shared/composables/useMessage';
import {
cancelTransferRun,
createTransferPrecheck,
downloadTransferErpInventory,
downloadTransferExceptions,
downloadTransferReceiptFiles,
executeTransferPrecheck,
getTransferBacklogSummary,
getTransferPrecheck,
getTransferRun,
listTransferBacklog,
listTransferSources,
manualCloseTransferItem,
retryTransferItem,
retryTransferSourceRpa,
} from '../api/transfer.api';
import type {
TransferBacklogItem,
TransferBacklogSummary,
TransferPrecheckDetail,
TransferPrecheckItem,
TransferPrecheckSummary,
TransferRunResult,
TransferSourceOption,
TransferSourceProgress,
} from '../types/transfer.types';
export function useChatTransfer() {
const { error: notifyError } = useMessage();
const precheckId = ref<string | null>(null);
const precheck = ref<TransferPrecheckSummary | null>(null);
const items = ref<TransferPrecheckItem[]>([]);
const sources = ref<TransferSourceProgress[]>([]);
const runNo = ref<string | null>(null);
const run = ref<TransferRunResult | null>(null);
const backlog = ref<TransferBacklogItem[]>([]);
const backlogSummary = ref<TransferBacklogSummary | null>(null);
const sourceOptions = ref<TransferSourceOption[]>([]);
const selected = ref<Set<string>>(new Set());
const busy = ref(false);
const error = ref('');
/** 全部可执行 Invoice(阻断/未成熟不可勾选) */
const executableInvoices = computed(() =>
items.value.filter((item) => item.result === 'executable').map((item) => item.invoice_no),
);
const selectedCount = computed(() => selected.value.size);
const estimatedQuantity = computed(() => precheck.value?.estimated_transfer_quantity ?? '0');
/** 创建预检(缺文件时来源级阶段展示等待/失败) */
async function createPrecheck(sourceCodes: string[], businessDate?: string) {
busy.value = true;
error.value = '';
try {
const summary = await createTransferPrecheck({ source_codes: sourceCodes, business_date: businessDate });
precheckId.value = summary.precheck_id;
await refreshPrecheck();
return summary;
} catch (e) {
error.value = String(e);
throw e;
} finally {
busy.value = false;
}
}
/** 恢复预检进度(页面刷新/会话恢复) */
async function refreshPrecheck() {
if (!precheckId.value) return null;
const detail = await getTransferPrecheck(precheckId.value);
applyDetail(detail);
return detail;
}
function applyDetail(detail: TransferPrecheckDetail) {
precheck.value = detail.summary;
items.value = detail.items;
sources.value = detail.sources;
// 默认勾选全部可执行项;阻断/未成熟不可选
selected.value = new Set(
detail.items.filter((item) => item.result === 'executable').map((item) => item.invoice_no),
);
}
function toggleSelect(invoiceNo: string, checked: boolean) {
const next = new Set(selected.value);
if (checked) next.add(invoiceNo);
else next.delete(invoiceNo);
selected.value = next;
}
/** 直接生成调拨单(决策 4/5:无独立确认页) */
async function execute() {
if (!precheckId.value) throw new Error('precheck not created');
if (selected.value.size === 0) {
notifyError('请至少选择一个可执行 Invoice');
return null;
}
busy.value = true;
error.value = '';
try {
const result = await executeTransferPrecheck(precheckId.value, [...selected.value]);
runNo.value = result.run_no;
await refreshRun();
return result;
} catch (e) {
error.value = String(e);
throw e;
} finally {
busy.value = false;
}
}
/** 恢复 Run 最终结果 */
async function refreshRun() {
if (!runNo.value) return null;
const data = await getTransferRun(runNo.value);
run.value = data;
return data;
}
/** 请求停止剩余任务 */
async function cancelRun(reason: string) {
if (!runNo.value) return null;
const result = await cancelTransferRun(runNo.value, reason);
await refreshRun();
return result;
}
/** 人工重试异常项 */
async function retry(itemId: number) {
const result = await retryTransferItem(itemId);
await refreshPrecheck();
return result;
}
/** 人工关闭异常项 */
async function manualClose(itemId: number, reason: string) {
const result = await manualCloseTransferItem(itemId, reason);
await refreshPrecheck();
return result;
}
/** 下载收料来源文件(zip) */
async function downloadReceiptFiles() {
if (!runNo.value) return null;
const result = await downloadTransferReceiptFiles(runNo.value);
saveBlob(result.blob, result.filename ?? `receipt-files-${runNo.value}.zip`);
return result;
}
/** 下载预检冻结的 ERP 库存表(csv) */
async function downloadErpInventory() {
if (!runNo.value) return null;
const result = await downloadTransferErpInventory(runNo.value);
saveBlob(result.blob, result.filename ?? `erp-inventory-${runNo.value}.csv`);
return result;
}
/** 下载七 Sheet 异常 Excel */
async function downloadExceptions() {
if (!runNo.value) return null;
const result = await downloadTransferExceptions(runNo.value);
saveBlob(result.blob, result.filename ?? `transfer-exceptions-${runNo.value}.xlsx`);
return result;
}
/** 加载来源实例列表(决策 3:平台仅分组,每来源附收料文件状态) */
async function loadSources() {
sourceOptions.value = await listTransferSources();
return sourceOptions.value;
}
/** 对指定来源重新触发收料 RPA 抓取,并刷新来源状态 */
async function retrySourceRpa(sourceCode: string) {
const status = await retryTransferSourceRpa(sourceCode);
await loadSources();
return status;
}
/** 加载待处理异常列表与汇总 */
async function loadBacklog() {
const [items, summary] = await Promise.all([listTransferBacklog(), getTransferBacklogSummary()]);
backlog.value = items;
backlogSummary.value = summary;
return { items, summary };
}
function saveBlob(blob: Blob, filename: string) {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.click();
URL.revokeObjectURL(url);
}
function reset() {
precheckId.value = null;
precheck.value = null;
items.value = [];
sources.value = [];
runNo.value = null;
run.value = null;
backlog.value = [];
backlogSummary.value = null;
sourceOptions.value = [];
selected.value = new Set();
error.value = '';
}
return {
precheckId,
precheck,
items,
sources,
runNo,
run,
backlog,
backlogSummary,
sourceOptions,
selected,
selectedCount,
executableInvoices,
estimatedQuantity,
busy,
error,
createPrecheck,
refreshPrecheck,
toggleSelect,
execute,
refreshRun,
cancelRun,
retry,
manualClose,
loadSources,
retrySourceRpa,
loadBacklog,
downloadReceiptFiles,
downloadErpInventory,
downloadExceptions,
reset,
};
}
export type ChatTransfer = ReturnType<typeof useChatTransfer>;
export type { Ref };
@@ -169,6 +169,7 @@ export function createStartChatTurn(options: CreateStartChatTurnOptions) {
if (eventName === 'shipping_ui_state' || eventName === 'ui_state.updated') {
const botMsg = ensureBotMessage();
if (botMsg) applyShippingUiStateToMessage(botMsg, data);
} else if (
eventName === 'message'
|| eventName === 'agent_message'
@@ -0,0 +1,50 @@
/**
* features/chat/composables/useProcurementContractChat.spec.ts
* 用途:验证采购合同双文件选择后的即时可见状态。
* 依赖:Vitest、Vue refs、useProcurementContractChat。
* 逻辑:我方原合同选择后即展示本地文件名,FileAsset 上传仅补充可提交的资产编号。
*/
import { computed, ref } from 'vue';
import { describe, expect, it, vi } from 'vitest';
import { useProcurementContractChat } from './useProcurementContractChat';
const { uploadFileAsset } = vi.hoisted(() => ({ uploadFileAsset: vi.fn() }));
vi.mock('@/shared/api/file-assets.api', () => ({ uploadFileAsset }));
/** 构建只覆盖原合同选择流程的最小上下文。 */
function createProcurementChat() {
return useProcurementContractChat({
currentAgent: ref({ agent_code: 'procurement_contract_review' }),
currentAgentId: computed(() => 1),
attachments: ref([]),
messages: ref([]),
isThinking: ref(false),
isUploadingAttachments: ref(false),
input: ref(''),
clearAttachments: vi.fn(),
saveLocalMessageToBackend: vi.fn(async () => undefined),
loadHistory: vi.fn(async () => undefined),
msg: { warning: vi.fn(), success: vi.fn(), info: vi.fn() },
t: (key: string) => key,
});
}
describe('useProcurementContractChat original contract selection', () => {
it('shows the selected original contract before its FileAsset upload finishes', async () => {
let resolveUpload: ((value: { asset_no: string; original_filename: string }) => void) | undefined;
uploadFileAsset.mockImplementation(() => new Promise((resolve) => { resolveUpload = resolve; }));
const chat = createProcurementChat();
const file = new File(['original'], '我方原合同.md', { type: 'text/markdown' });
const selecting = chat.handleOriginalContractSelected({ target: { files: [file], value: 'selected' } } as unknown as Event);
// 断言上传尚未完成时 UI 仍能立刻渲染已选择的我方原合同。
expect(chat.originalContractName.value).toBe('我方原合同.md');
expect(chat.originalContractAssetNo.value).toBeNull();
resolveUpload?.({ asset_no: 'FA-ORIGINAL-1', original_filename: '我方原合同.md' });
await selecting;
expect(chat.originalContractAssetNo.value).toBe('FA-ORIGINAL-1');
});
});
@@ -131,12 +131,18 @@ export function useProcurementContractChat(options: ProcurementContractChatOptio
const file = input.files?.[0];
input.value = '';
if (!file) return;
// [STEP 1] 选择即展示,避免 FileAsset 网络上传期间输入栏看起来没有响应。
originalContractAssetNo.value = null;
originalContractName.value = file.name;
options.isUploadingAttachments.value = true;
try {
const asset = await uploadFileAsset(file);
// [STEP 2] 上传完成后才允许作为正式比对基准提交。
originalContractAssetNo.value = asset.asset_no;
originalContractName.value = asset.original_filename || file.name;
} catch (e: unknown) {
// 上传失败的临时卡片不可作为基准,必须移除,避免显示与提交状态不一致。
clearOriginalContract();
options.msg.warning(e instanceof Error ? e.message : options.t('chat.procurementContract.uploadFailed'));
} finally {
options.isUploadingAttachments.value = false;
@@ -1,11 +1,4 @@
/**
* features/chat/composables/useToolRunProgress.ts
* 用途:轮询 Tool/文件检核任务进度,并在执行中锁定输入。
* 依赖:vue-i18n、toolRunProgress.api、toolRunProgressConfig。
* 逻辑:Chat 页 progress 卡片消费;lockMessage / queryFailed 走 chat.toolRun.*。
*/
import { computed, onBeforeUnmount, ref, type Ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { buildFileCheckLogProgressUrl } from '../utils/toolRunProgressConfig';
import { getToolRunProgress, type ToolRunProgress } from '../api/toolRunProgress.api';
import type { ToolRunProgressMatchSource } from '../types/tool-run-progress.types';
@@ -50,15 +43,11 @@ const isTerminalStatus = (status?: string | null) => TERMINAL_STATUSES.has(Strin
/**
* 轮询任务进度:有 run_id 时走 detail;或走 for-log / active。
* 核心逻辑:按 config 选择 detail/session/active URL;running 时定时刷新;终态停表。
* @param configRef - 进度轮询配置
* @param options.allowEmptySessionPolls - 允许 for-session 空结果继续重试
*/
export function useToolRunProgress(
configRef: Ref<ToolRunProgressConfig | null>,
options: UseToolRunProgressOptions = {},
) {
const { t } = useI18n();
const run = ref<ToolRunProgress | null>(null);
const matchSource = ref<ToolRunProgressMatchSource | null>(null);
const loading = ref(false);
@@ -79,7 +68,7 @@ export function useToolRunProgress(
const isRunning = computed(() => run.value?.status === 'running');
const shouldLockInput = computed(() => Boolean(configRef.value?.lock_input_when_running) && isRunning.value);
const lockMessage = computed(() => configRef.value?.lock_message || t('chat.toolRun.lockWaiting'));
const lockMessage = computed(() => configRef.value?.lock_message || '当前任务执行中,请等待完成');
const clearTimer = () => {
if (timer !== undefined) {
@@ -111,7 +100,7 @@ export function useToolRunProgress(
matchSource.value = payload.match_source ?? null;
return payload.run ?? null;
} catch (e: unknown) {
const message = e instanceof Error ? e.message : t('chat.toolRun.queryFailed');
const message = e instanceof Error ? e.message : '任务进度查询失败';
error.value = message;
matchSource.value = null;
clearTimer();
@@ -1,8 +1,9 @@
/**
* features/chat/composables/useTrainingWorkspace.ts
* 用途:封装员工培训 Agent 的工作区状态,包括学员考试流、进度持久化与 HR 真实统计导出。
* 用途:封装员工培训 Agent 的工作区状态,包括学员考试流、进度持久化、HR 真实统计导出与精益定向提醒。
* 依赖:Vue reactivity、vue-i18n、training.api,以及 training.types。
* 逻辑:仅在培训 Agent 下启用;学员端按“视频 -> 知识点 -> 一题一答 -> 结算”推进,并把进度同步到后端,聊天区只保留问答能力。
* 逻辑:仅在培训 Agent 下启用;学员端按“视频 -> 知识点 -> 一题一答 -> 结算”推进,并把进度同步到后端;
* 非安全培训页额外按后台配置动态渲染进度项与步骤说明文案;精益管理面板通过独立状态提交未完成人员提醒。
*/
import { computed, ref, watch, type ComputedRef } from 'vue';
import { useI18n } from 'vue-i18n';
@@ -10,33 +11,52 @@ import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
exportTrainingRecords,
getMyTrainingConfig,
getMyTrainingProgress,
getMyTrainingTypes,
getTrainingStats,
getMyLeanTrainingTasks,
getLeanTrainingDashboard,
sendLeanTrainingReminders,
listTrainingRecords,
markMyLeanVideoWatched,
saveMyTrainingProgress,
saveMyLeanTrainingCompletion,
} from '@/features/chat/api/training.api';
import type {
SafetyProgressState,
TrainingAnswerRecord,
TrainingContentConfig,
TrainingExamMode,
TrainingExamTransitionFeedback,
TrainingQuestion,
TrainingQuestionOption,
TrainingProgressRecord,
TrainingPublishedConfig,
TrainingRecord,
TrainingRecordStatus,
SafetyStage,
TrainingStage,
TrainingStats,
TrainingType,
TrainingTypeOption,
TrainingWorkspaceView,
LeanTrainingDashboard,
LeanTrainingDashboardRow,
LeanTrainingMyTask,
} from '@/features/chat/training/training.types';
import {
SAFETY_STAGE_GUIDE_USAGE_MAP,
matchesTrainingAgent,
resolveLearnerCopyText,
resolveLearnerProgressItems,
resolveTrainingContentConfig,
resolveTrainingVideoGuide,
resolveTrainingVideoUrl,
resolveSafetyTrainingVideoGuide,
type TrainingGuideLike,
} from '@/features/chat/training/trainingWorkspace.utils';
type TrainingAgentLike = {
id?: number | null;
name?: string | null;
extra_config?: Record<string, unknown> | null;
} | null | undefined;
@@ -52,14 +72,16 @@ type TrainingUserLike = {
} | null;
} | null | undefined;
type SafetyLearningStage = Exclude<SafetyStage, 'exam' | 'result'>;
export interface UseTrainingWorkspaceOptions {
currentAgent: ComputedRef<TrainingAgentLike>;
currentUser: ComputedRef<TrainingUserLike>;
currentGuides: ComputedRef<TrainingGuideLike[]>;
}
const DEFAULT_TRAINING_VIDEO_URL = 'https://www.w3schools.com/html/mov_bbb.mp4';
const DEFAULT_PASS_SCORE = 90;
const DEFAULT_TRAINING_VERSION = 'v1.0';
const formatDate = (value: Date) => value.toISOString().slice(0, 10);
@@ -72,22 +94,64 @@ const calculateTrainingScore = (correctAnswerCount: number, totalQuestionCount:
return Math.round((correctAnswerCount / totalQuestionCount) * 100);
};
/**
* 规范填空题文本以便与题库标准答案进行即时比对。
* 用途:忽略作答中的空格和大小写,避免 PDF 文本换行或录入格式导致本应正确的填空题被误判。
*/
const normalizeTextAnswer = (value: string) => value
.normalize('NFKC')
.replace(/[\s\u3000、,,;;。..!!??::()()【】\[\]{}"'“”‘’\-—_]+/g, '')
.toLocaleLowerCase();
export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
const { currentAgent, currentUser, currentGuides } = options;
const { t, tm } = useI18n();
const msg = useMessage();
const isTrainingAgent = computed(() => matchesTrainingAgent(currentAgent.value));
const currentTrainingAgentId = computed<number | null>(() => {
const parsed = Number(currentAgent.value?.id);
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
});
const hasAuthenticatedUser = computed(() => Boolean(String(currentUser.value?.username || '').trim()));
const isAdminViewer = computed(() => Boolean(currentUser.value?.feature_permissions?.training_hr_manage));
const defaultActiveView = computed<TrainingWorkspaceView>(() => (isAdminViewer.value ? 'admin' : 'learner'));
const canViewLeanDashboard = computed(() => isAdminViewer.value);
const canManageTrainingWorkspace = computed(() => isAdminViewer.value);
/** 学员端精益周任务列表(后端按发布周期倒序,最新在前),并附每期任务状态与完成信息。 */
const leanMyTasks = ref<LeanTrainingMyTask[]>([]);
const leanDashboard = ref<LeanTrainingDashboard>({ task: null, completed: [], incomplete: [], periods: [] });
/** 管理端内容页签:all=全部培训(现有统计/筛选/主表);lean=精益管理(精益看板单任务,按状态列区分三态)。 */
const hrTrainingTab = ref<'all' | 'lean'>('all');
/** 管理端精益看板当前选中的期次任务 ID;为空表示最新一期,切换后重新拉取对应期看板。 */
const leanDashboardTaskId = ref<number | null>(null);
const leanReminderLoading = ref<Record<number, boolean>>({});
/** 按任务 ID 分组的感悟草稿,支持时间树上多期任务并行编辑。 */
const leanSummaryByTask = ref<Record<number, string>>({});
/** 按任务 ID 分组的观看记录(资源 ID -> 观看时间),提交时随感悟一并交由服务端校验。 */
const leanWatchedByTask = ref<Record<number, Record<string, string>>>({});
const defaultActiveView = computed<TrainingWorkspaceView>(() => (canManageTrainingWorkspace.value ? 'admin' : 'learner'));
const activeView = ref<TrainingWorkspaceView>('learner');
const learnerTab = ref<TrainingType>('onboarding');
const trainingTypes = ref<TrainingTypeOption[]>([
{ code: 'onboarding', name: t('chat.training.safety.tabs.onboarding') },
{ code: 'safety', name: t('chat.training.safety.tabs.safety') },
]);
const trainingVersion = ref<string>(DEFAULT_TRAINING_VERSION);
const examMode = ref<TrainingExamMode>('unified');
const safetyStage = ref<SafetyStage>('company');
const safetyViewStage = ref<SafetyStage>('company');
const safetyProgress = ref<SafetyProgressState>({
company: 'active',
department: 'pending',
team: 'pending',
});
const stage = ref<TrainingStage>('video');
const currentQuestionIndex = ref(0);
const score = ref(0);
const attemptCount = ref(0);
const selectedOptionId = ref('');
const answerText = ref('');
const answerLocked = ref(false);
const currentFeedbackCorrect = ref(false);
const latestExamFeedback = ref<TrainingExamTransitionFeedback | null>(null);
@@ -103,10 +167,13 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
const isHydrated = ref(false);
const hasWarnedPersistFailure = ref(false);
const hasWarnedLoadFailure = ref(false);
const publishedConfig = ref<TrainingPublishedConfig | null>(null);
const trainingConfigLoading = ref(false);
const hrKeyword = ref('');
const hrStatusFilter = ref<'all' | TrainingRecordStatus>('all');
const hrDepartmentFilter = ref('all');
const hrTypeFilter = ref('all');
const records = ref<TrainingRecord[]>([]);
const departmentOptions = ref<string[]>([]);
const stats = ref<TrainingStats>({
@@ -117,6 +184,28 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
passRate: 0,
averageScore: 0,
});
/** 精益看板合并行:已完成+未完成名单合为单表遍历,状态列区分已完成/已延期/进行中三态。 */
const leanRows = computed<LeanTrainingDashboardRow[]>(() => [...leanDashboard.value.completed, ...leanDashboard.value.incomplete]);
/**
* 精益管理页签统计:按看板行三态(completed/in_progress/overdue)实际计数,供统计卡片随页签切换数据源。
* total=参训人数(已完成+未完成名单行数);passed=已完成;failed=已延期;inProgress=进行中;passRate=完成率。
*/
const leanStats = computed<TrainingStats>(() => {
// [STEP 1] 合并已完成/未完成两组行后按后端归一的三态计数,避免只扫 incomplete 组漏算已延期。
const rows = [...leanDashboard.value.completed, ...leanDashboard.value.incomplete];
const total = rows.length;
const completedCount = rows.filter((row) => row.status === 'completed').length;
const overdueCount = rows.filter((row) => row.status === 'overdue').length;
const inProgressCount = rows.filter((row) => row.status === 'in_progress').length;
return {
total,
passed: completedCount,
failed: overdueCount,
inProgress: inProgressCount,
passRate: total > 0 ? Math.round((completedCount / total) * 100) : 0,
averageScore: 0,
};
});
let persistQueue: Promise<void> = Promise.resolve();
watch(isTrainingAgent, (enabled) => {
@@ -127,7 +216,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
});
watch(
[isTrainingAgent, isAdminViewer],
[isTrainingAgent, canManageTrainingWorkspace],
([enabled]) => {
if (!enabled) return;
activeView.value = defaultActiveView.value;
@@ -174,6 +263,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
type,
prompt: String(item.prompt || ''),
answer: String(item.answer || ''),
scoreRatio: Number(item.score_ratio || item.scoreRatio || 1),
explanation: String(item.explanation || ''),
options,
};
@@ -190,12 +280,45 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
questionBank: defaultQuestionBank.value,
},
booleanOptions.value,
publishedConfig.value,
));
const summaryPoints = computed(() => trainingContent.value.summaryPoints);
const summaryChecklist = computed(() => trainingContent.value.summaryChecklist);
const questionBank = computed<TrainingQuestion[]>(() => trainingContent.value.questionBank);
const passScore = computed(() => trainingContent.value.passScore);
const hasPublishedTrainingConfig = computed(() => publishedConfig.value !== null);
const activeSafetyLearningStage = computed<SafetyLearningStage | null>(() => (
['company', 'department', 'team'].includes(safetyStage.value)
? safetyStage.value as SafetyLearningStage
: null
));
const visibleSafetyLearningStage = computed<SafetyLearningStage | null>(() => (
['company', 'department', 'team'].includes(safetyViewStage.value)
? safetyViewStage.value as SafetyLearningStage
: null
));
const resolveSafetyStageMaterials = (targetStage: SafetyLearningStage | null) => [...(publishedConfig.value?.resources || [])]
.filter((resource) => resource.resourceType !== 'inline_questions')
.filter((resource) => !targetStage || resource.trainingLevel === targetStage)
.sort((left, right) => Number(left.sortOrder || 0) - Number(right.sortOrder || 0));
/**
* 按当前安全培训阶段筛选已发布资料。
* AI 触发时机:员工进入公司级、部门级或班组级页面时,只展示后台绑定到当前级别的资料;入职培训仍展示全部非题库资料。
*/
const publishedTrainingMaterials = computed(() => [...(publishedConfig.value?.resources || [])]
.filter((resource) => resource.resourceType !== 'inline_questions')
.filter((resource) => learnerTab.value !== 'safety' || resource.trainingLevel === visibleSafetyLearningStage.value)
.sort((left, right) => Number(left.sortOrder || 0) - Number(right.sortOrder || 0)));
const publishedSafetySummary = computed(() => {
const summaries = publishedConfig.value?.settings?.summaryByStage;
if (!summaries || typeof summaries !== 'object') return [];
const value = (summaries as Record<string, unknown>)[safetyViewStage.value];
return Array.isArray(value) ? value.map((item) => String(item)) : [];
});
const learnerProgressItems = computed(() => resolveLearnerProgressItems(publishedConfig.value));
const learnerProgressHintText = computed(() => resolveLearnerCopyText(publishedConfig.value, 'progress_hint_text'));
const learnerStepIntroText = computed(() => resolveLearnerCopyText(publishedConfig.value, 'step_intro_text'));
const currentQuestion = computed(() => questionBank.value[currentQuestionIndex.value] || null);
const totalQuestionCount = computed(() => questionBank.value.length);
@@ -213,8 +336,73 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
&& answeredCount.value >= totalQuestionCount.value
));
const canEnterResultStage = computed(() => stage.value === 'result');
const safetyProgressPercent = computed(() => {
if (safetyStage.value === 'exam') return 90;
if (safetyStage.value === 'result') return 100;
let completedCount = 0;
if (isStageCompleted('company')) completedCount++;
if (isStageCompleted('department')) completedCount++;
if (isStageCompleted('team')) completedCount++;
return Math.round((completedCount / 3) * 75) || 10; // Start at 10% or just based on completed
});
const isStageCompleted = (stageKey: SafetyLearningStage) => {
const materials = resolveSafetyStageMaterials(stageKey);
if (!materials.length) return true;
return materials.every(m => {
if (m.id == null) return true;
const progress = safetyProgress.value.resource_progress?.[String(m.id)];
return progress?.completed;
});
};
/**
* 校验三级安全培训资料是否已全部完成。
* 用途:在员工端进入或提交安全考试前提供即时拦截;服务端仍会使用同一资源完成事实做最终校验。
*/
const isSafetyLearningComplete = () => (
isStageCompleted('company') && isStageCompleted('department') && isStageCompleted('team')
);
const safetyStepItems = computed(() => {
const base: Array<{ id: SafetyStage extends infer U ? U : never; labelKey: string }> = [
{ id: 'company', labelKey: 'chat.training.safety.steps.company' },
{ id: 'department', labelKey: 'chat.training.safety.steps.department' },
{ id: 'team', labelKey: 'chat.training.safety.steps.team' },
{ id: 'exam', labelKey: 'chat.training.safety.steps.exam' },
];
return base.map((item) => {
let status: 'completed' | 'active' | 'pending' | 'locked' = 'pending';
if (item.id === 'company' || item.id === 'department' || item.id === 'team') {
const completed = isStageCompleted(item.id);
if (safetyViewStage.value === item.id) {
status = 'active';
} else if (completed) {
status = 'completed';
} else {
status = 'pending';
}
} else if (item.id === 'exam') {
const allCompleted = isStageCompleted('company') && isStageCompleted('department') && isStageCompleted('team');
if (['exam', 'result'].includes(safetyStage.value)) {
status = safetyStage.value === 'exam' ? 'active' : 'completed';
} else {
status = allCompleted ? 'pending' : 'locked';
}
}
return {
id: item.id,
label: t(item.labelKey),
status,
};
});
});
const learnerProgressPercent = computed(() => {
if (learnerTab.value === 'safety') {
return safetyProgressPercent.value;
}
if (stage.value === 'video') return 25;
if (stage.value === 'summary') return 50;
if (stage.value === 'result') return 100;
@@ -234,6 +422,37 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
const currentUserDepartment = computed(() => String(currentUser.value?.department || '').trim() || t('chat.training.unknownDepartment'));
const filteredRecords = computed(() => records.value);
/**
* 解析培训类型的展示名称,优先使用后端已发布配置名称,并兼容历史内置类型。
* AI 触发时机:Tabs、HR 筛选、记录和报告展示培训类型时调用,禁止直接将类型 code 暴露给用户。
*/
const resolveTrainingTypeName = (code?: string | null) => {
const normalizedCode = String(code || '').trim();
return trainingTypes.value.find((item) => item.code === normalizedCode)?.name
|| (normalizedCode === 'onboarding' ? t('chat.training.hr.filters.typeOnboarding') : '')
|| (normalizedCode === 'safety' ? t('chat.training.hr.filters.typeSafety') : '')
|| normalizedCode
|| '--';
};
/**
* 读取员工可见的已发布培训类型,作为动态 Tabs 与 HR 类型筛选的统一数据源。
* AI 触发时机:进入培训 Agent 或登录状态变更后调用;无已发布配置时保留内置类型以兼容历史数据。
*/
const loadTrainingTypes = async () => {
if (!isTrainingAgent.value || !hasAuthenticatedUser.value) return;
try {
const items = await getMyTrainingTypes();
if (!items.length) return;
trainingTypes.value = items;
if (!items.some((item) => item.code === learnerTab.value)) {
learnerTab.value = items[0]?.code || learnerTab.value;
}
} catch {
// 无法读取目录时保留内置兼容项,后续仍可按 code 请求配置。
}
};
/**
* 重置考试状态,为首次开考或再次补考共用。
* AI 触发时机:当前端需要严格模拟“未通过必须重考”的培训流程时使用,确保上一轮答题状态不会污染下一轮。
@@ -242,6 +461,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
currentQuestionIndex.value = 0;
score.value = 0;
selectedOptionId.value = '';
answerText.value = '';
answerLocked.value = false;
currentFeedbackCorrect.value = false;
latestExamFeedback.value = null;
@@ -334,8 +554,11 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
? answerRecords.value.find((item) => item.questionId === questionId)
: null;
selectedOptionId.value = currentAnswer?.selectedOptionId || '';
answerText.value = currentAnswer?.answerText || '';
answerLocked.value = Boolean(currentAnswer);
currentFeedbackCorrect.value = Boolean(currentAnswer?.correct);
currentFeedbackCorrect.value = currentQuestion.value?.type === 'fill' && currentQuestion.value.answer && currentAnswer?.answerText
? normalizeTextAnswer(currentAnswer.answerText) === normalizeTextAnswer(currentQuestion.value.answer)
: Boolean(currentAnswer?.correct);
};
/**
@@ -353,14 +576,95 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
syncAnswerStateForCurrentQuestion();
};
/**
* 按安全培训目标阶段重置三级学习进度。
* AI 触发时机:当员工完成上一级学习、切换安全培训阶段,或后端恢复安全培训初始态时,需要一次性得到完整的三级状态快照。
*/
const resetSafetyProgress = (nextStage: SafetyStage = 'company') => {
const resourceProgressSnapshot = safetyProgress.value.resource_progress
? { ...safetyProgress.value.resource_progress }
: undefined;
safetyStage.value = nextStage;
safetyViewStage.value = nextStage;
if (nextStage === 'company') {
safetyProgress.value = { company: 'active', department: 'pending', team: 'pending', resource_progress: resourceProgressSnapshot };
return;
}
if (nextStage === 'department') {
safetyProgress.value = { company: 'completed', department: 'active', team: 'pending', resource_progress: resourceProgressSnapshot };
return;
}
if (nextStage === 'team') {
safetyProgress.value = { company: 'completed', department: 'completed', team: 'active', resource_progress: resourceProgressSnapshot };
return;
}
safetyProgress.value = { company: 'completed', department: 'completed', team: 'completed', resource_progress: resourceProgressSnapshot };
};
/**
* 进入安全培训考试阶段并初始化本轮考试状态。
* AI 触发时机:当三级学习全部完成,或员工在安全培训中点击“开始考试/重新考试”时调用。
*/
const enterSafetyExam = () => {
if (!isSafetyLearningComplete()) {
msg.warning(t('chat.training.errors.safetyLearningIncomplete'));
return;
}
if (totalQuestionCount.value <= 0) {
msg.warning(t('chat.training.errors.questionBankEmpty'));
return;
}
safetyStage.value = 'exam';
safetyViewStage.value = 'exam';
stage.value = 'exam';
attemptCount.value += 1;
resetExamState();
};
/**
* 把后端培训记录回填到当前工作区状态。
* AI 触发时机:页面刷新、重新进入聊天页或切换培训类型后,需要把服务端快照完整恢复到本地状态机。
*/
const applyProgressRecord = (record: TrainingProgressRecord | null) => {
if (!record) {
trainingVersion.value = DEFAULT_TRAINING_VERSION;
examMode.value = 'unified';
resetSafetyProgress('company');
stage.value = 'video';
resetExamState();
currentJoinDate.value = null;
latestSettledResult.value = null;
return;
}
trainingVersion.value = record.trainingVersion || publishedConfig.value?.version || DEFAULT_TRAINING_VERSION;
examMode.value = record.examMode || 'unified';
if (learnerTab.value === 'safety') {
safetyStage.value = record.safetyStage || 'company';
// Ensure resource_progress is preserved when merging from backend
safetyProgress.value = {
...record.safetyProgress,
resource_progress: record.safetyProgress?.resource_progress || safetyProgress.value.resource_progress || {}
};
// Sync legacy fields with actual resource completion
safetyProgress.value.company = isStageCompleted('company') ? 'completed' : 'active';
safetyProgress.value.department = isStageCompleted('department') ? 'completed' : 'active';
safetyProgress.value.team = isStageCompleted('team') ? 'completed' : 'active';
if (safetyStage.value !== 'exam' && safetyStage.value !== 'result') {
if (!isStageCompleted('company')) {
safetyViewStage.value = 'company';
} else if (!isStageCompleted('department')) {
safetyViewStage.value = 'department';
} else if (!isStageCompleted('team')) {
safetyViewStage.value = 'team';
} else {
safetyViewStage.value = 'company';
}
} else {
safetyViewStage.value = record.safetyStage || 'company';
}
}
stage.value = record.stage;
syncExamQuestionIndex(record.currentQuestionIndex);
score.value = Number(record.score || 0);
@@ -387,8 +691,19 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
syncAnswerStateForCurrentQuestion();
};
/**
* 组装当前培训工作区的持久化载荷。
* AI 触发时机:每次阶段推进、答题、结算或安全培训切级后,都要把统一格式的快照发送给后端保存。
*/
const buildProgressPayload = () => ({
stage: stage.value,
agentId: currentTrainingAgentId.value,
stage: learnerTab.value === 'safety'
? (safetyStage.value === 'exam' ? 'exam' : safetyStage.value === 'result' ? 'result' : 'summary')
: stage.value,
trainingVersion: trainingVersion.value,
examMode: examMode.value,
safetyStage: learnerTab.value === 'safety' ? safetyStage.value : null,
safetyProgress: learnerTab.value === 'safety' ? safetyProgress.value : null,
currentQuestionIndex: currentQuestionIndex.value,
score: score.value,
passed: isPassed.value,
@@ -401,10 +716,12 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
if (!isTrainingAgent.value) return;
persistQueue = persistQueue.catch(() => undefined).then(async () => {
try {
const saved = await saveMyTrainingProgress(buildProgressPayload());
const saved = await saveMyTrainingProgress(buildProgressPayload(), learnerTab.value);
hasWarnedPersistFailure.value = false;
currentJoinDate.value = saved.joinDate || currentJoinDate.value;
completionDate.value = saved.completionDate;
score.value = Number(saved.score || 0);
answerRecords.value = saved.answerDetails;
if (isAdminViewer.value) {
void loadAdminRecords();
}
@@ -433,7 +750,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
return;
}
try {
const record = await getMyTrainingProgress();
const record = await getMyTrainingProgress(learnerTab.value);
hasWarnedLoadFailure.value = false;
applyProgressRecord(record);
} catch (error) {
@@ -459,6 +776,24 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
}
};
const loadTrainingConfig = async () => {
if (!isTrainingAgent.value || !hasAuthenticatedUser.value) {
publishedConfig.value = null;
trainingConfigLoading.value = false;
return;
}
trainingConfigLoading.value = true;
try {
publishedConfig.value = await getMyTrainingConfig(learnerTab.value);
} catch (error) {
if (!(error instanceof BusinessError && error.status === 401)) {
publishedConfig.value = null;
}
} finally {
trainingConfigLoading.value = false;
}
};
const loadAdminRecords = async () => {
if (!isTrainingAgent.value || !isAdminViewer.value) return;
try {
@@ -466,6 +801,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
keyword: hrKeyword.value || undefined,
department: hrDepartmentFilter.value === 'all' ? undefined : hrDepartmentFilter.value,
status: hrStatusFilter.value,
type: hrTypeFilter.value === 'all' ? undefined : hrTypeFilter.value,
};
const [recordData, statsData] = await Promise.all([
listTrainingRecords(query),
@@ -488,12 +824,99 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
}
};
/** 拉取管理端精益看板(按 leanDashboardTaskId 指定期次,空则最新一期),失败时清空兜底。 */
const loadLeanDashboard = async () => {
if (!canViewLeanDashboard.value) return;
try {
leanDashboard.value = await getLeanTrainingDashboard(leanDashboardTaskId.value ?? undefined);
} catch {
leanDashboard.value = { task: null, completed: [], incomplete: [], periods: [] };
}
};
/** 切换精益看板期次:记录任务 ID 后仅重拉看板与精益统计,不动学员任务列表。 */
const selectLeanDashboardPeriod = async (taskId: number) => {
if (leanDashboardTaskId.value === taskId) return;
leanDashboardTaskId.value = taskId;
await loadLeanDashboard();
};
/** 读取学员端全部已发布精益周任务(含状态与播放地址),并以服务端完成记录回填各任务的感悟/观看草稿。 */
const loadLeanTraining = async () => {
if (!isTrainingAgent.value || !hasAuthenticatedUser.value) return;
try {
leanMyTasks.value = await getMyLeanTrainingTasks();
// [STEP 1] 回填草稿:已完成任务还原当时提交的感悟与观看时间;进行中/已延期任务保留已有观看记录,避免刷新后丢失。
const summaries: Record<number, string> = {};
const watched: Record<number, Record<string, string>> = {};
leanMyTasks.value.forEach((task) => {
summaries[task.id] = task.completion?.summaryText || '';
watched[task.id] = { ...(task.completion?.watchedAt || {}) };
});
leanSummaryByTask.value = summaries;
leanWatchedByTask.value = watched;
await loadLeanDashboard();
} catch {
leanMyTasks.value = [];
leanDashboard.value = { task: null, completed: [], incomplete: [], periods: [] };
}
};
/**
* 记录某期任务的指定视频已完成观看:本地即时生效,并异步持久化到服务端(刷新后仍保留)。
* AI 触发时机:学员在精益管理时间树上点击任务视频并完整播放到结尾时调用;已有观看记录的资源保留首次时间不覆盖。
*/
const markLeanVideoWatched = (taskId: number, resourceId: number) => {
const taskWatched = leanWatchedByTask.value[taskId] || {};
if (taskWatched[String(resourceId)]) return;
leanWatchedByTask.value = { ...leanWatchedByTask.value, [taskId]: { ...taskWatched, [String(resourceId)]: new Date().toISOString() } };
// 持久化失败不阻塞本地状态;下次刷新列表会以服务端记录为准,未持久化的视频需重新完整观看
void markMyLeanVideoWatched(taskId, resourceId).catch(() => {});
};
/**
* 提交指定周任务的学习感悟;服务端校验该任务已推送视频全部完成且达到最少字数,成功后刷新任务列表与看板。
*/
const submitLeanTrainingCompletion = async (taskId: number) => {
await saveMyLeanTrainingCompletion({ weeklyTaskId: taskId, watchedAt: leanWatchedByTask.value[taskId] || {}, summaryText: leanSummaryByTask.value[taskId] || '' });
await loadLeanTraining();
};
/**
* HR 对看板中未完成成员发起定向提醒,并按服务端实发统计如实提示。
* AI 触发时机:HR 在精益培训完成名单点击行内【提醒】按钮时调用。
* 核心逻辑:后端 created 计数包含"企微发送失败"的提醒(仅代表已尝试),
* 成功提示必须以 sent(企微受理成功)为准,failed>0 时明确告知失败,避免误报已送达。
*/
const remindLeanTrainingMember = async (userId: number) => {
if (!leanDashboard.value.task || leanReminderLoading.value[userId]) return;
leanReminderLoading.value[userId] = true;
try {
const result = await sendLeanTrainingReminders(leanDashboard.value.task.id, [userId]);
if (result.sent > 0 && result.failed > 0) {
msg.warning(t('chat.training.lean.reminder.partial', { sent: result.sent, failed: result.failed }));
} else if (result.sent > 0) {
msg.success(t('chat.training.lean.reminder.success', { count: result.sent }));
} else if (result.failed > 0) {
msg.error(t('chat.training.lean.reminder.sendFailed', { count: result.failed }));
} else {
msg.warning(t('chat.training.lean.reminder.notSent'));
}
await loadLeanTraining();
} catch (error) {
msg.error(error instanceof BusinessError ? error.message : t('chat.training.lean.reminder.failed'));
} finally {
leanReminderLoading.value[userId] = false;
}
};
watch(
[
currentAgent,
hasAuthenticatedUser,
() => String(currentUser.value?.username || '').trim(),
() => String(currentUser.value?.role || '').trim(),
learnerTab,
],
([agent, loggedIn]) => {
if (!matchesTrainingAgent(agent)) {
@@ -516,7 +939,10 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
return;
}
isHydrated.value = false;
void loadTrainingTypes();
void loadTrainingConfig();
void loadTrainingProgress();
void loadLeanTraining();
},
{ immediate: true },
);
@@ -528,6 +954,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
hrKeyword,
hrStatusFilter,
hrDepartmentFilter,
hrTypeFilter,
() => String(currentUser.value?.username || '').trim(),
() => String(currentUser.value?.role || '').trim(),
],
@@ -539,11 +966,22 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
);
const markVideoCompleted = () => {
if (!hasPublishedTrainingConfig.value || !videoUrl.value) return;
if (learnerTab.value === 'safety') {
checkAndAdvanceStage();
return;
}
stage.value = 'summary';
void persistProgress();
};
const startExam = () => {
if (!hasPublishedTrainingConfig.value) return;
if (learnerTab.value === 'safety') {
enterSafetyExam();
void persistProgress();
return;
}
if (totalQuestionCount.value <= 0) {
msg.warning(t('chat.training.errors.questionBankEmpty'));
return;
@@ -559,7 +997,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
* AI 触发时机:当员工在逐题考试阶段点击右侧题号返回某题时,需要允许直接改答且不破坏“提交答卷后才结算”的流程。
*/
const selectAnswer = (optionId: string) => {
if (!currentQuestion.value) return;
if (!currentQuestion.value || currentQuestion.value.type === 'fill' || currentQuestion.value.type === 'essay') return;
const answeredQuestion = currentQuestion.value;
const hadExistingAnswer = answerRecords.value.some((item) => item.questionId === answeredQuestion.id);
selectedOptionId.value = optionId;
@@ -593,6 +1031,40 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
void persistProgress();
};
/**
* 提交填空或问答题的文本作答。
* 核心逻辑:文本题由服务端以题库标准答案或无标准答案的字数规则最终判卷;前端仅保存非空文本并推进。
* @returns 无有效文本时不记录,否则更新当前题作答并保持既有逐题推进行为。
*/
const submitTextAnswer = () => {
if (!currentQuestion.value || !['fill', 'essay'].includes(currentQuestion.value.type)) return;
const answeredQuestion = currentQuestion.value;
const text = answerText.value.trim();
if (!text) return;
const hadExistingAnswer = answerRecords.value.some((item) => item.questionId === answeredQuestion.id);
const answerRecord: TrainingAnswerRecord = {
questionId: answeredQuestion.id,
selectedOptionId: '',
answerText: text,
correct: answeredQuestion.type === 'fill' && answeredQuestion.answer
? normalizeTextAnswer(text) === normalizeTextAnswer(answeredQuestion.answer)
: false,
scoreRatio: 0,
};
answerLocked.value = true;
upsertAnswerRecord(answerRecord);
const nextScore = recalculateScoreFromAnswers(answerRecords.value);
score.value = nextScore;
currentFeedbackCorrect.value = answerRecord.correct;
latestExamFeedback.value = buildExamFeedback(answeredQuestion, answerRecord, nextScore);
if (hadExistingAnswer || currentQuestionIndex.value >= totalQuestionCount.value - 1) {
void persistProgress();
return;
}
syncExamQuestionIndex(currentQuestionIndex.value + 1);
void persistProgress();
};
/**
* 进入下一题或结束考试。
* AI 触发时机:当用户答完一题后,前端必须只推进一题并即时结算,保证“一题一答一反馈”的 HR 规则被严格执行。
@@ -613,7 +1085,15 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
*/
const submitExam = () => {
if (!examReadyToSubmit.value) return;
if (learnerTab.value === 'safety' && !isSafetyLearningComplete()) {
msg.warning(t('chat.training.errors.safetyLearningIncomplete'));
return;
}
stage.value = 'result';
if (learnerTab.value === 'safety') {
safetyStage.value = 'result';
safetyViewStage.value = 'result';
}
completionDate.value = formatDate(new Date());
latestSettledResult.value = {
score: score.value,
@@ -625,16 +1105,40 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
};
const restartExam = () => {
if (learnerTab.value === 'safety') {
enterSafetyExam();
void persistProgress();
return;
}
stage.value = 'video';
resetExamState();
// 不立即覆盖后端已结算成绩,避免刷新页面或重新进入历史对话时丢失上一轮考试结果与 HR 统计事实。
};
/**
* 按右侧步骤面板切换安全培训阶段。
* AI 触发时机:当员工点击安全培训流程步骤时,只允许查看当前可达阶段,
* 但绝不能因为“返回查看已完成阶段”而重置已保存的完成状态或学习记录。
*/
const setSafetyStage = (nextStage: SafetyStage) => {
if (!hasPublishedTrainingConfig.value) return;
const target = safetyStepItems.value.find((item) => item.id === nextStage);
if (!target || target.status === 'locked') return;
if (nextStage === 'exam' && safetyStage.value !== 'exam' && safetyStage.value !== 'result') {
enterSafetyExam();
void persistProgress();
} else {
safetyViewStage.value = nextStage;
}
};
const exportRecords = async () => {
await exportTrainingRecords({
keyword: hrKeyword.value || undefined,
department: hrDepartmentFilter.value === 'all' ? undefined : hrDepartmentFilter.value,
status: hrStatusFilter.value,
type: hrTypeFilter.value === 'all' ? undefined : hrTypeFilter.value,
});
};
@@ -642,6 +1146,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
const parts = [
t('chat.training.chatPrompts.hrSummaryPrefix'),
`${t('chat.training.hr.filters.keywordLabel')}: ${hrKeyword.value || t('chat.training.hr.filters.noLimit')}`,
`${t('chat.training.hr.filters.typeLabel')}: ${hrTypeFilter.value === 'all' ? t('chat.training.hr.filters.allTypes') : resolveTrainingTypeName(hrTypeFilter.value)}`,
`${t('chat.training.hr.filters.statusLabel')}: ${hrStatusFilter.value === 'all' ? t('chat.training.hr.filters.allStatuses') : t(`chat.training.hr.status.${hrStatusFilter.value}`)}`,
`${t('chat.training.hr.filters.departmentLabel')}: ${hrDepartmentFilter.value === 'all' ? t('chat.training.hr.filters.allDepartments') : hrDepartmentFilter.value}`,
`${t('chat.training.hr.stats.passRate')}: ${stats.value.passRate}%`,
@@ -691,17 +1196,127 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
});
const showVideoModal = ref(false);
const currentViewingMaterialId = ref<number | null>(null);
const materialStartTime = ref<number>(0);
const currentViewingMaterialRequiredDuration = computed(() => {
if (!currentViewingMaterialId.value) return 0;
const resource = (publishedConfig.value?.resources || []).find((item) => String(item.id) === String(currentViewingMaterialId.value));
return resource?.requiredDuration || 0;
});
const startMaterialTimer = (materialId: number) => {
currentViewingMaterialId.value = materialId;
materialStartTime.value = Date.now();
};
const stopMaterialTimer = () => {
if (!currentViewingMaterialId.value || !materialStartTime.value) return;
const materialId = String(currentViewingMaterialId.value);
// 累计观看时长(秒)
const durationSeconds = Math.round((Date.now() - materialStartTime.value) / 1000);
const resource = (publishedConfig.value?.resources || []).find((item) => String(item.id) === materialId);
if (resource) {
if (!safetyProgress.value.resource_progress) {
safetyProgress.value.resource_progress = {};
}
const existing = safetyProgress.value.resource_progress[materialId] || { duration: 0, completed: false };
existing.duration += durationSeconds;
const reqDurationMinutes = resource.requiredDuration || 0;
if (existing.duration >= reqDurationMinutes * 60) {
existing.completed = true;
}
safetyProgress.value.resource_progress[materialId] = existing;
checkAndAdvanceStage();
}
currentViewingMaterialId.value = null;
materialStartTime.value = 0;
};
const checkAndAdvanceStage = () => {
// Update legacy string fields to reflect real status based on resources
safetyProgress.value.company = isStageCompleted('company') ? 'completed' : 'active';
safetyProgress.value.department = isStageCompleted('department') ? 'completed' : 'active';
safetyProgress.value.team = isStageCompleted('team') ? 'completed' : 'active';
if (learnerTab.value === 'safety') {
const allSafetyCompleted = isStageCompleted('company') && isStageCompleted('department') && isStageCompleted('team');
if (allSafetyCompleted && safetyStage.value !== 'exam' && safetyStage.value !== 'result') {
safetyStage.value = 'exam';
enterSafetyExam();
}
void persistProgress();
} else {
const activeStageMaterials = publishedTrainingMaterials.value;
if (!activeStageMaterials.length) return;
const allCompleted = activeStageMaterials.every(m => {
if (m.id == null) return true;
const progress = safetyProgress.value.resource_progress?.[String(m.id)];
return progress?.completed;
});
if (allCompleted) {
stage.value = 'summary';
}
void persistProgress();
}
};
const videoUrl = computed(() => {
const uploadedGuide = resolveTrainingVideoGuide(currentGuides.value);
if (!publishedConfig.value) return '';
const visibleGuideStage = visibleSafetyLearningStage.value || activeSafetyLearningStage.value;
const preferredGuideIds = publishedTrainingMaterials.value
.filter((resource) => resource.resourceType === 'agent_guide' && resource.agentGuideId != null)
.map((resource) => Number(resource.agentGuideId));
const uploadedGuide = learnerTab.value === 'safety'
? resolveSafetyTrainingVideoGuide(currentGuides.value, visibleGuideStage || 'company', preferredGuideIds)
: currentGuides.value.find((guide) => guide?.id != null && preferredGuideIds.includes(Number(guide.id)) && guide?.file_type === 'video');
const uploadedGuideUrl = String(uploadedGuide?.file_url || uploadedGuide?.file_path || '').trim();
return uploadedGuideUrl || resolveTrainingVideoUrl(currentAgent.value, DEFAULT_TRAINING_VIDEO_URL);
const configuredGuide = publishedTrainingMaterials.value
.find((resource) => resource.resourceType === 'agent_guide'
&& resource.resource?.fileType === 'video'
&& (learnerTab.value !== 'safety'
|| !visibleGuideStage
|| !SAFETY_STAGE_GUIDE_USAGE_MAP[visibleGuideStage as keyof typeof SAFETY_STAGE_GUIDE_USAGE_MAP]
|| resource.resource.guideUsage === SAFETY_STAGE_GUIDE_USAGE_MAP[visibleGuideStage as keyof typeof SAFETY_STAGE_GUIDE_USAGE_MAP]));
return String(configuredGuide?.resource?.fileUrl || '').trim()
|| uploadedGuideUrl;
});
return {
isTrainingAgent,
isAdminViewer,
canViewLeanDashboard,
canManageTrainingWorkspace,
leanDashboard,
leanReminderLoading,
leanSummaryByTask,
leanWatchedByTask,
leanMyTasks,
isHydrated,
trainingConfigLoading,
hasPublishedTrainingConfig,
publishedTrainingMaterials,
publishedSafetySummary,
learnerProgressItems,
learnerProgressHintText,
learnerStepIntroText,
activeView,
learnerTab,
trainingTypes,
resolveTrainingTypeName,
trainingVersion,
examMode,
safetyStage,
safetyViewStage,
safetyProgress,
safetyProgressPercent,
safetyStepItems,
stage,
currentQuestionIndex,
currentQuestionNumber,
@@ -713,6 +1328,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
score,
attemptCount,
selectedOptionId,
answerText,
answerLocked,
currentFeedbackCorrect,
examReadyToSubmit,
@@ -731,11 +1347,17 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
currentUserEmployeeId,
currentUserDepartment,
hrKeyword,
hrStatusFilter,
hrDepartmentFilter,
hrStatusFilter,
hrTypeFilter,
departmentOptions,
filteredRecords,
stats,
hrTrainingTab,
leanStats,
leanRows,
leanDashboardTaskId,
selectLeanDashboardPeriod,
learnerChatPrompt,
newSessionReminderMessage,
shouldShowNewSessionReminder,
@@ -744,12 +1366,23 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
markVideoCompleted,
startExam,
selectAnswer,
submitTextAnswer,
syncExamQuestionIndex,
moveToNextQuestion,
submitExam,
restartExam,
setSafetyStage,
exportRecords,
loadLeanTraining,
markLeanVideoWatched,
submitLeanTrainingCompletion,
remindLeanTrainingMember,
showVideoModal,
videoUrl,
startMaterialTimer,
stopMaterialTimer,
currentViewingMaterialId,
currentViewingMaterialRequiredDuration,
currentTrainingAgentId,
};
}