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:
commit
ca9c174f29
2050 files changed
+511839
-42320
No files matched your search
@@ -1,6 +1,8 @@
|
||||
/**
|
||||
* features/chat/api/chat.api.ts
|
||||
* 聊天域 HTTP API:会话、消息、源文件、附件上传。
|
||||
* 用途:封装聊天会话、消息、源文件与附件上传 HTTP API,并恢复结构化历史消息状态。
|
||||
* 依赖:shared/api/client、鉴权工具、chat.types。
|
||||
* 逻辑:页面 composable 调用本模块;历史消息响应在返回前将 ChatLog.payload 中的领域状态投影到 ChatMessage。
|
||||
*/
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
@@ -14,6 +16,7 @@ import type {
|
||||
ChatSourceFileResult,
|
||||
ChatUploadResult,
|
||||
OaEmployeesResponse,
|
||||
ShippingOrderExtractionState,
|
||||
} from '../types/chat.types';
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
@@ -28,10 +31,35 @@ export const deleteAllChatSessions = (agentId: number) =>
|
||||
export const deleteChatSession = (conversationId: string, agentId: number) =>
|
||||
requestJson(`/api/chat/sessions/${conversationId}?agent_id=${agentId}`, { method: 'DELETE', ...auth() });
|
||||
|
||||
/**
|
||||
* 从 ChatLog.payload 恢复订单识别终态,保证刷新会话后与实时 SSE 消息形状一致。
|
||||
* 核心逻辑:仅接受带合法 status 的对象;服务端仍是终态事实源,本函数不推导或改写计数。
|
||||
* @param message - 历史接口返回的单条消息。
|
||||
* @returns 原消息或已补充 shipping_order_extraction_state 的消息。
|
||||
*/
|
||||
export const hydrateShippingOrderExtractionState = (message: ChatMessage): ChatMessage => {
|
||||
const payload = message.payload && typeof message.payload === 'object'
|
||||
? message.payload as Record<string, unknown>
|
||||
: {};
|
||||
const state = payload.shipping_order_extraction_state;
|
||||
if (!state || typeof state !== 'object') return message;
|
||||
const status = String((state as Record<string, unknown>).status || '');
|
||||
if (!['queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'].includes(status)) return message;
|
||||
const normalized = state as ShippingOrderExtractionState;
|
||||
if (normalized.supersedingRunNo) {
|
||||
normalized.isCurrent = false;
|
||||
normalized.readOnlyReason = normalized.readOnlyReason || 'superseded_by_newer_run';
|
||||
}
|
||||
message.shipping_order_extraction_state = normalized;
|
||||
return message;
|
||||
};
|
||||
|
||||
export const listChatMessages = async (conversationId: string, agentId: number) => {
|
||||
const messages = await requestJson<ChatMessage[]>(`/api/chat/messages?conversation_id=${conversationId}&agent_id=${agentId}`, auth());
|
||||
return Array.isArray(messages)
|
||||
? messages.filter((message) => message?.type !== 'shipping-parse-review')
|
||||
? messages
|
||||
.filter((message) => message?.type !== 'shipping-parse-review')
|
||||
.map(hydrateShippingOrderExtractionState)
|
||||
: messages;
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* features/chat/api/shipping.api.legacy-entrypoints.spec.ts
|
||||
* 用途:锁定 Shipping 前端 API 不再暴露直接匹配/导出业务入口。
|
||||
* 依赖:shipping.api 的模块导出。
|
||||
* 逻辑:正式业务动作只能由 Projection + Process Gate Action 驱动;旧函数名不得重新被页面调用。
|
||||
*/
|
||||
import * as shippingApi from './shipping.api';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
describe('shipping API runtime entrypoints', () => {
|
||||
it('does not expose direct inventory match or Excel generation actions', () => {
|
||||
expect(Object.prototype.hasOwnProperty.call(shippingApi, 'matchWorkspaceShippingInventory')).toBe(false);
|
||||
expect(Object.prototype.hasOwnProperty.call(shippingApi, 'generateWorkspaceShippingExcel')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* features/chat/api/shipping.api.request-dedupe.spec.ts
|
||||
* 用途:锁定重型订单抽取 Run 读取的同 key 在途请求合并契约。
|
||||
* 依赖:Vitest、shipping.api、统一 requestJson。
|
||||
* 逻辑:两个消费者同时读取同一 Run 时必须复用一个 HTTP 请求;请求结束后才允许下一次读取。
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const requestJson = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('@/shared/api/client', () => ({
|
||||
BusinessError: class BusinessError extends Error {},
|
||||
requestJson,
|
||||
}));
|
||||
|
||||
import {
|
||||
getWorkspaceShippingOrderExtractionRun,
|
||||
getWorkspaceShippingProcessing,
|
||||
getWorkspaceShippingTask,
|
||||
} from './shipping.api';
|
||||
|
||||
describe('getWorkspaceShippingTask', () => {
|
||||
beforeEach(() => {
|
||||
requestJson.mockReset();
|
||||
});
|
||||
|
||||
it('coalesces concurrent reads of the same task detail into one HTTP request', async () => {
|
||||
let resolveRequest!: (value: { task_no: string }) => void;
|
||||
requestJson.mockImplementationOnce(() => new Promise((resolve) => {
|
||||
resolveRequest = resolve;
|
||||
}));
|
||||
|
||||
const first = getWorkspaceShippingTask('SN-DEDUPE-1');
|
||||
const second = getWorkspaceShippingTask('SN-DEDUPE-1');
|
||||
|
||||
// 关键断言:重型任务详情在途时,同 task_no 的并行消费者(工作台 loadFormalTaskDetail
|
||||
// 与对话侧 syncActiveShippingTaskDetail)必须复用一个网络请求,禁止重复拉取。
|
||||
expect(requestJson).toHaveBeenCalledTimes(1);
|
||||
resolveRequest({ task_no: 'SN-DEDUPE-1' });
|
||||
await expect(Promise.all([first, second])).resolves.toEqual([
|
||||
{ task_no: 'SN-DEDUPE-1' },
|
||||
{ task_no: 'SN-DEDUPE-1' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('does not cache a completed task detail across a later read', async () => {
|
||||
requestJson.mockResolvedValueOnce({ task_no: 'SN-FRESH-1' });
|
||||
requestJson.mockResolvedValueOnce({ task_no: 'SN-FRESH-1' });
|
||||
|
||||
// 单飞去重只合并「在途」请求;完成后不得返回过期快照,保证 Gate 动作后的新鲜重读。
|
||||
await getWorkspaceShippingTask('SN-FRESH-1');
|
||||
await getWorkspaceShippingTask('SN-FRESH-1');
|
||||
|
||||
expect(requestJson).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('keys dedup by view so workbench and full projections do not merge', async () => {
|
||||
requestJson.mockResolvedValue({ task_no: 'SN-VIEW-1' });
|
||||
// 关键断言:workbench(裁剪)与 full 是两个不同响应体,缺省 view 与 view=workbench
|
||||
// 共享同一个 task_no 时不能合并成一个请求,否则会把裁剪版响应交给 full 消费者。
|
||||
const full = getWorkspaceShippingTask('SN-VIEW-1');
|
||||
const wb = getWorkspaceShippingTask('SN-VIEW-1', { view: 'workbench' });
|
||||
const wbAgain = getWorkspaceShippingTask('SN-VIEW-1', { view: 'workbench' });
|
||||
|
||||
// 两个视图各一次、workbench 同视图合并:共 2 次底层请求。
|
||||
expect(requestJson).toHaveBeenCalledTimes(2);
|
||||
expect(requestJson).toHaveBeenNthCalledWith(1, '/api/workspace/shipping-tasks/SN-VIEW-1');
|
||||
expect(requestJson).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
'/api/workspace/shipping-tasks/SN-VIEW-1?view=workbench',
|
||||
);
|
||||
await Promise.allSettled([full, wb, wbAgain]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getWorkspaceShippingOrderExtractionRun', () => {
|
||||
beforeEach(() => {
|
||||
requestJson.mockReset();
|
||||
// 模块级短缓存会跨用例保留;本文件的会话 ID 均唯一,避免上一用例污染下一用例。
|
||||
});
|
||||
|
||||
it('coalesces concurrent reads of the same Run into one HTTP request', async () => {
|
||||
let resolveRequest!: (value: { run_no: string }) => void;
|
||||
requestJson.mockImplementationOnce(() => new Promise((resolve) => {
|
||||
resolveRequest = resolve;
|
||||
}));
|
||||
|
||||
const first = getWorkspaceShippingOrderExtractionRun('SNER-SAME');
|
||||
const second = getWorkspaceShippingOrderExtractionRun('SNER-SAME');
|
||||
|
||||
// 关键断言:慢 Run 投影在途时,同一文件的第二个消费者不得再创建独立网络请求。
|
||||
expect(requestJson).toHaveBeenCalledTimes(1);
|
||||
resolveRequest({ run_no: 'SNER-SAME' });
|
||||
await expect(Promise.all([first, second])).resolves.toEqual([
|
||||
{ run_no: 'SNER-SAME' },
|
||||
{ run_no: 'SNER-SAME' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('lets one caller stop waiting without aborting a shared Run request', async () => {
|
||||
let resolveRequest!: (value: { run_no: string }) => void;
|
||||
requestJson.mockImplementationOnce(() => new Promise((resolve) => {
|
||||
resolveRequest = resolve;
|
||||
}));
|
||||
const controller = new AbortController();
|
||||
|
||||
const cancelledCaller = getWorkspaceShippingOrderExtractionRun('SNER-SHARED', controller.signal);
|
||||
const activeCaller = getWorkspaceShippingOrderExtractionRun('SNER-SHARED');
|
||||
controller.abort();
|
||||
|
||||
// 关键断言:路由离开只结束当前消费者等待,不能中止其他组件复用的重型读取。
|
||||
await expect(cancelledCaller).rejects.toMatchObject({ name: 'AbortError' });
|
||||
expect(requestJson).toHaveBeenCalledTimes(1);
|
||||
resolveRequest({ run_no: 'SNER-SHARED' });
|
||||
await expect(activeCaller).resolves.toEqual({ run_no: 'SNER-SHARED' });
|
||||
});
|
||||
|
||||
it('reuses a successful conversation summary during the short refresh burst', async () => {
|
||||
requestJson.mockResolvedValue({
|
||||
conversation_id: 'conversation-summary-cache',
|
||||
work_items: [],
|
||||
conversation_processing: null,
|
||||
});
|
||||
|
||||
await getWorkspaceShippingProcessing('conversation-summary-cache');
|
||||
await getWorkspaceShippingProcessing('conversation-summary-cache');
|
||||
|
||||
// 关键断言:首屏 watcher 连续触发时必须复用刚完成的摘要,避免重复慢查询。
|
||||
expect(requestJson).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('binds every summary leaf to its status-group task for batch rendering', async () => {
|
||||
requestJson.mockResolvedValue({
|
||||
conversation_id: 'conversation-leaf-binding-20260822',
|
||||
conversation_processing: {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
status_groups: {
|
||||
failed: [],
|
||||
waiting_human: [{
|
||||
user_task_no: 'INTAKE:SNI-1', group: 'needs_action', status_label: 'waiting_human',
|
||||
file_count: 1, can_append: false,
|
||||
aggregate_children: [{
|
||||
work_item_type: 'order_task', work_item_no: 'DOCUMENT:1', source_type: 'eml',
|
||||
conversation_id: 'conversation-leaf-binding-20260822', intake_no: 'SNI-1', submission_no: 'SUB-1',
|
||||
// 同一邮件内另一 Candidate 的原始 OT 不能用作父卡关联键。
|
||||
root_order_task_no: 'OT-OTHER-CANDIDATE',
|
||||
status: 'waiting_human', stage: 'candidate_creating', progress_version: 1,
|
||||
source_summary: { document_id: 1, filename: 'order.pdf' },
|
||||
}],
|
||||
}],
|
||||
processing: [], completed: [], cancelled: [], archived: [],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const response = await getWorkspaceShippingProcessing('conversation-leaf-binding-20260822');
|
||||
|
||||
// 关键断言:批次卡按父任务查实时叶子时,必须能找到本摘要组的文件。
|
||||
expect(response.conversation_processing?.status_groups?.waiting_human[0]?.aggregateChildren?.[0]).toMatchObject({
|
||||
workItemNo: 'DOCUMENT:1',
|
||||
});
|
||||
expect(response.conversation_processing?.status_groups?.waiting_human[0]?.aggregateChildren).toHaveLength(1);
|
||||
expect(response.work_items).toHaveLength(1);
|
||||
expect(response.work_items[0]?.rootOrderTaskNo).toBe('INTAKE:SNI-1');
|
||||
expect(response.work_items[0]?.sourceSummary.documentId).toBe(1);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,16 +1,82 @@
|
||||
/**
|
||||
* features/chat/api/training.api.ts
|
||||
* 用途:培训工作区专用 HTTP API,负责员工进度读取/保存、HR 记录查询、统计和导出。
|
||||
* 用途:培训工作区专用 HTTP API,负责员工进度读取/保存、HR 记录查询、统计导出和精益任务提醒。
|
||||
* 依赖:shared/api/client、auth headers、training.types。
|
||||
* 逻辑:把后端 training 领域的 snake_case 返回值统一映射成前端工作区需要的 camelCase 结构。
|
||||
* 逻辑:把后端 training 领域的 snake_case 返回值统一映射成前端工作区需要的 camelCase 结构,并提交精益未完成人员提醒请求。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type { TrainingAnswerRecord, TrainingProgressRecord, TrainingRecord, TrainingStage, TrainingStats } from '../training/training.types';
|
||||
import type {
|
||||
SafetyProgressState,
|
||||
TrainingAnswerRecord,
|
||||
TrainingExamMode,
|
||||
TrainingProgressRecord,
|
||||
TrainingPublishedConfig,
|
||||
TrainingRecord,
|
||||
TrainingStage,
|
||||
TrainingStats,
|
||||
LeanTrainingDashboard,
|
||||
LeanTrainingDashboardRow,
|
||||
LeanTrainingMyTask,
|
||||
LeanTrainingTaskStatus,
|
||||
LeanTrainingWeeklyTask,
|
||||
TrainingType,
|
||||
TrainingTypeOption,
|
||||
} from '../training/training.types';
|
||||
|
||||
type LeanTrainingTaskApi = {
|
||||
id: number; week_key: string; due_at: string; video_resource_ids: number[];
|
||||
target_roles: string[]; target_user_ids: number[];
|
||||
videos: Array<{ id: number; name: string; file_url?: string | null }>; status: string; min_summary_length: number;
|
||||
weekly_count?: number; pushed_video_count?: number;
|
||||
week_end?: string | null; week_index?: number;
|
||||
};
|
||||
|
||||
type LeanTrainingMyTaskApi = LeanTrainingTaskApi & {
|
||||
task_status: LeanTrainingTaskStatus;
|
||||
completion: { summary_text: string; watched_at: Record<string, string>; completed_at?: string | null } | null;
|
||||
};
|
||||
|
||||
type LeanTrainingDashboardRowApi = {
|
||||
id?: number; user_id: number; employee_id?: string | null; name: string; department?: string | null;
|
||||
videos: Array<{ name: string; watched_at?: string | null }>;
|
||||
// 后端序列化层三态归一:completed=已提交感悟;overdue=过截止未完成;in_progress=进行中
|
||||
summary_text?: string | null; status: 'completed' | 'in_progress' | 'overdue'; completed_at?: string | null;
|
||||
};
|
||||
|
||||
const mapLeanTask = (data: LeanTrainingTaskApi): LeanTrainingWeeklyTask => ({
|
||||
id: data.id, weekKey: data.week_key, dueAt: data.due_at, videoResourceIds: data.video_resource_ids || [],
|
||||
targetRoles: data.target_roles || [], targetUserIds: data.target_user_ids || [],
|
||||
videos: (data.videos || []).map((video) => ({ id: video.id, name: video.name, fileUrl: video.file_url || null })),
|
||||
status: data.status, minSummaryLength: data.min_summary_length,
|
||||
weeklyCount: data.weekly_count, pushedVideoCount: data.pushed_video_count,
|
||||
weekEnd: data.week_end ?? null, weekIndex: data.week_index,
|
||||
});
|
||||
|
||||
const mapLeanMyTask = (data: LeanTrainingMyTaskApi): LeanTrainingMyTask => ({
|
||||
...mapLeanTask(data),
|
||||
taskStatus: data.task_status,
|
||||
completion: data.completion ? {
|
||||
summaryText: data.completion.summary_text,
|
||||
watchedAt: data.completion.watched_at || {},
|
||||
completedAt: data.completion.completed_at || null,
|
||||
} : null,
|
||||
});
|
||||
|
||||
const mapLeanDashboardRow = (data: LeanTrainingDashboardRowApi): LeanTrainingDashboardRow => ({
|
||||
id: data.id, userId: data.user_id, employeeId: data.employee_id, name: data.name, department: data.department,
|
||||
videos: (data.videos || []).map((item) => ({ name: item.name, watchedAt: item.watched_at })),
|
||||
summaryText: data.summary_text, status: data.status, completedAt: data.completed_at,
|
||||
});
|
||||
|
||||
type TrainingRecordApi = {
|
||||
id: number;
|
||||
user_id?: number;
|
||||
training_type?: TrainingType;
|
||||
training_version?: string | null;
|
||||
exam_mode?: TrainingExamMode;
|
||||
safety_stage?: string | null;
|
||||
safety_progress?: Partial<SafetyProgressState> | null;
|
||||
employee_id?: string | null;
|
||||
name?: string | null;
|
||||
department?: string | null;
|
||||
@@ -23,7 +89,9 @@ type TrainingRecordApi = {
|
||||
answer_details?: Array<{
|
||||
question_id?: string;
|
||||
selected_option_id?: string;
|
||||
answer_text?: string;
|
||||
correct?: boolean;
|
||||
score_ratio?: number;
|
||||
}>;
|
||||
completion_time?: string | null;
|
||||
updated_at?: string | null;
|
||||
@@ -31,6 +99,32 @@ type TrainingRecordApi = {
|
||||
status?: TrainingRecord['status'];
|
||||
};
|
||||
|
||||
type TrainingConfigApi = {
|
||||
id: number;
|
||||
training_type?: TrainingType;
|
||||
version?: string | null;
|
||||
pass_score?: number | null;
|
||||
settings?: Record<string, unknown> | null;
|
||||
resources?: Array<{
|
||||
id?: number | null;
|
||||
resource_type?: string | null;
|
||||
training_level?: 'company' | 'department' | 'team' | null;
|
||||
agent_guide_id?: number | null;
|
||||
inline_questions?: unknown[];
|
||||
title?: string | null;
|
||||
sort_order?: number;
|
||||
required_duration?: number;
|
||||
resource?: {
|
||||
id?: number;
|
||||
file_name?: string;
|
||||
file_type?: string;
|
||||
file_url?: string;
|
||||
guide_usage?: string;
|
||||
source_file_name?: string;
|
||||
} | null;
|
||||
}>;
|
||||
};
|
||||
|
||||
type TrainingListApi = {
|
||||
items: TrainingRecordApi[];
|
||||
total: number;
|
||||
@@ -52,13 +146,19 @@ type TrainingStatsApi = {
|
||||
export interface TrainingRecordQuery {
|
||||
keyword?: string;
|
||||
department?: string;
|
||||
status?: 'all' | 'passed' | 'failed' | 'in_progress';
|
||||
status?: string;
|
||||
type?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface SaveTrainingProgressPayload {
|
||||
stage: TrainingStage;
|
||||
agentId?: number | null;
|
||||
trainingVersion?: string | null;
|
||||
examMode?: TrainingExamMode;
|
||||
safetyStage?: string | null;
|
||||
safetyProgress?: Partial<SafetyProgressState> | null;
|
||||
currentQuestionIndex: number;
|
||||
score: number;
|
||||
passed: boolean;
|
||||
@@ -75,14 +175,27 @@ function mapAnswerDetails(items?: TrainingRecordApi['answer_details']): Training
|
||||
? items.map((item) => ({
|
||||
questionId: String(item.question_id || ''),
|
||||
selectedOptionId: String(item.selected_option_id || ''),
|
||||
answerText: String(item.answer_text || ''),
|
||||
correct: Boolean(item.correct),
|
||||
scoreRatio: Number(item.score_ratio || 0),
|
||||
}))
|
||||
: [];
|
||||
}
|
||||
|
||||
function mapSafetyProgressState(items?: TrainingRecordApi['safety_progress']): SafetyProgressState {
|
||||
return {
|
||||
company: String(items?.company || 'pending'),
|
||||
department: String(items?.department || 'pending'),
|
||||
team: String(items?.team || 'pending'),
|
||||
resource_progress: (items as any)?.resource_progress || {},
|
||||
};
|
||||
}
|
||||
|
||||
function mapTrainingProgressRecord(data: TrainingRecordApi): TrainingProgressRecord {
|
||||
return {
|
||||
id: data.id,
|
||||
trainingType: data.training_type || 'onboarding',
|
||||
trainingVersion: data.training_version || undefined,
|
||||
name: String(data.name || ''),
|
||||
employeeId: String(data.employee_id || ''),
|
||||
department: String(data.department || ''),
|
||||
@@ -92,6 +205,9 @@ function mapTrainingProgressRecord(data: TrainingRecordApi): TrainingProgressRec
|
||||
attempts: Number(data.attempt_count || 0),
|
||||
status: data.status || 'in_progress',
|
||||
stage: (data.stage || 'video') as TrainingStage,
|
||||
examMode: (data.exam_mode || 'unified') as TrainingExamMode,
|
||||
safetyStage: data.safety_stage ? String(data.safety_stage) as TrainingProgressRecord['safetyStage'] : null,
|
||||
safetyProgress: mapSafetyProgressState(data.safety_progress),
|
||||
currentQuestionIndex: Number(data.current_question_index || 0),
|
||||
passed: Boolean(data.passed),
|
||||
answerDetails: mapAnswerDetails(data.answer_details),
|
||||
@@ -101,10 +217,41 @@ function mapTrainingProgressRecord(data: TrainingRecordApi): TrainingProgressRec
|
||||
};
|
||||
}
|
||||
|
||||
function mapTrainingConfig(data: TrainingConfigApi): TrainingPublishedConfig {
|
||||
return {
|
||||
id: data.id,
|
||||
trainingType: data.training_type || 'onboarding',
|
||||
version: String(data.version || ''),
|
||||
passScore: Number(data.pass_score || 0),
|
||||
settings: data.settings || {},
|
||||
resources: Array.isArray(data.resources)
|
||||
? data.resources.map((resource) => ({
|
||||
id: resource.id,
|
||||
resourceType: resource.resource_type,
|
||||
trainingLevel: resource.training_level,
|
||||
agentGuideId: resource.agent_guide_id,
|
||||
inlineQuestions: resource.inline_questions,
|
||||
title: resource.title,
|
||||
sortOrder: Number(resource.sort_order || 0),
|
||||
requiredDuration: Number(resource.required_duration || 0),
|
||||
resource: resource.resource ? {
|
||||
id: resource.resource.id,
|
||||
fileName: resource.resource.file_name || resource.resource.source_file_name,
|
||||
fileType: resource.resource.file_type,
|
||||
fileUrl: resource.resource.file_url,
|
||||
guideUsage: resource.resource.guide_usage,
|
||||
} : null,
|
||||
}))
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
function mapTrainingRecord(data: TrainingRecordApi): TrainingRecord {
|
||||
const progress = mapTrainingProgressRecord(data);
|
||||
return {
|
||||
id: progress.id,
|
||||
trainingType: progress.trainingType,
|
||||
trainingVersion: progress.trainingVersion,
|
||||
name: progress.name,
|
||||
employeeId: progress.employeeId,
|
||||
department: progress.department,
|
||||
@@ -113,6 +260,7 @@ function mapTrainingRecord(data: TrainingRecordApi): TrainingRecord {
|
||||
score: progress.score,
|
||||
attempts: progress.attempts,
|
||||
status: progress.status,
|
||||
answerDetails: progress.answerDetails,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -121,30 +269,89 @@ function buildQueryString(query: TrainingRecordQuery = {}) {
|
||||
if (query.keyword) params.set('keyword', query.keyword);
|
||||
if (query.department) params.set('department', query.department);
|
||||
if (query.status) params.set('status', query.status);
|
||||
if (query.type) params.set('type', query.type);
|
||||
if (query.page) params.set('page', String(query.page));
|
||||
if (query.page_size) params.set('page_size', String(query.page_size));
|
||||
return params.toString();
|
||||
}
|
||||
|
||||
export async function getMyTrainingProgress(): Promise<TrainingProgressRecord | null> {
|
||||
const data = await requestJson<TrainingRecordApi | null>('/api/user/training-record', authHeaders());
|
||||
export async function getMyTrainingTypes(): Promise<TrainingTypeOption[]> {
|
||||
return requestJson<TrainingTypeOption[]>('/api/user/training-types', authHeaders());
|
||||
}
|
||||
|
||||
export async function getMyLeanTrainingTasks(): Promise<LeanTrainingMyTask[]> {
|
||||
const response = await requestJson<LeanTrainingMyTaskApi[]>('/api/user/lean-training/my-tasks', authHeaders());
|
||||
return (response || []).map(mapLeanMyTask);
|
||||
}
|
||||
|
||||
export async function markMyLeanVideoWatched(weeklyTaskId: number, resourceId: number): Promise<void> {
|
||||
await requestJson<{ watched_at: Record<string, string> }>('/api/user/lean-training/my-tasks/watched', {
|
||||
method: 'POST',
|
||||
...jsonAuthHeaders(),
|
||||
body: JSON.stringify({ weekly_task_id: weeklyTaskId, resource_id: resourceId }),
|
||||
});
|
||||
}
|
||||
|
||||
export async function saveMyLeanTrainingCompletion(payload: { weeklyTaskId: number; watchedAt: Record<string, string>; summaryText: string }): Promise<LeanTrainingDashboardRow> {
|
||||
const response = await requestJson<LeanTrainingDashboardRowApi>('/api/user/lean-training/completions', {
|
||||
method: 'PUT', ...jsonAuthHeaders(), body: JSON.stringify({ weekly_task_id: payload.weeklyTaskId, watched_at: payload.watchedAt, summary_text: payload.summaryText }),
|
||||
});
|
||||
return mapLeanDashboardRow(response);
|
||||
}
|
||||
|
||||
export async function getLeanTrainingDashboard(taskId?: number): Promise<LeanTrainingDashboard> {
|
||||
// task_id 为空时后端返回最新一期;periods 为全部期次摘要(期号按周次升序),供管理端下拉切换第几期。
|
||||
const query = taskId ? `?task_id=${taskId}` : '';
|
||||
const response = await requestJson<{ task: LeanTrainingTaskApi | null; completed: LeanTrainingDashboardRowApi[]; incomplete: LeanTrainingDashboardRowApi[]; periods?: Array<{ id: number; week_key: string; index: number }> }>(`/api/admin/lean-training/dashboard${query}`, authHeaders());
|
||||
return {
|
||||
task: response.task ? mapLeanTask(response.task) : null,
|
||||
completed: (response.completed || []).map(mapLeanDashboardRow),
|
||||
incomplete: (response.incomplete || []).map(mapLeanDashboardRow),
|
||||
periods: (response.periods || []).map((period) => ({ id: period.id, weekKey: period.week_key, index: period.index })),
|
||||
};
|
||||
}
|
||||
|
||||
/** HR 对指定成员发起精益培训定向提醒;返回后端实发统计(sent/failed 才是真实送达情况,created 含发送失败)。 */
|
||||
export async function sendLeanTrainingReminders(weeklyTaskId: number, userIds: number[]): Promise<{ created: number; sent: number; skipped: number; failed: number }> {
|
||||
return requestJson<{ created: number; sent: number; skipped: number; failed: number }>(`/api/admin/lean-training/weekly-tasks/${weeklyTaskId}/reminders`, {
|
||||
method: 'POST',
|
||||
...jsonAuthHeaders(),
|
||||
body: JSON.stringify({ user_ids: userIds }),
|
||||
});
|
||||
}
|
||||
|
||||
export async function getMyTrainingProgress(type: string = 'onboarding'): Promise<TrainingProgressRecord | null> {
|
||||
const data = await requestJson<TrainingRecordApi | null>(`/api/user/training-record?type=${encodeURIComponent(type)}`, authHeaders());
|
||||
return data ? mapTrainingProgressRecord(data) : null;
|
||||
}
|
||||
|
||||
export async function saveMyTrainingProgress(payload: SaveTrainingProgressPayload): Promise<TrainingProgressRecord> {
|
||||
export async function getMyTrainingConfig(type: string = 'onboarding'): Promise<TrainingPublishedConfig | null> {
|
||||
const data = await requestJson<TrainingConfigApi | null>(`/api/user/training-config?type=${encodeURIComponent(type)}`, authHeaders());
|
||||
return data ? mapTrainingConfig(data) : null;
|
||||
}
|
||||
|
||||
export async function saveMyTrainingProgress(payload: SaveTrainingProgressPayload, type: string = 'onboarding'): Promise<TrainingProgressRecord> {
|
||||
const data = await requestJson<TrainingRecordApi>('/api/user/training-record/progress', {
|
||||
method: 'PUT',
|
||||
...jsonAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
agent_id: payload.agentId || undefined,
|
||||
stage: payload.stage,
|
||||
training_version: payload.trainingVersion || undefined,
|
||||
exam_mode: payload.examMode || undefined,
|
||||
safety_stage: payload.safetyStage || undefined,
|
||||
safety_progress: payload.safetyProgress || undefined,
|
||||
current_question_index: payload.currentQuestionIndex,
|
||||
score: payload.score,
|
||||
passed: payload.passed,
|
||||
attempt_count: payload.attemptCount,
|
||||
type: type,
|
||||
answer_details: payload.answerDetails.map((item) => ({
|
||||
question_id: item.questionId,
|
||||
selected_option_id: item.selectedOptionId,
|
||||
answer_text: item.answerText || '',
|
||||
correct: item.correct,
|
||||
score_ratio: item.scoreRatio || 0,
|
||||
})),
|
||||
join_date: payload.joinDate || undefined,
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* features/chat/api/transfer.api.spec.ts
|
||||
* 用途:锁定在途仓自动调拨 JSON POST 请求头契约——必须携带 Content-Type: application/json,
|
||||
* 否则后端 Flask request.get_json 解析不到 body,导致默认 source_codes=[] 返回 400。
|
||||
* 依赖:Vitest、vi.mock(@/shared/api/client)、transfer.api、getAuthHeaders。
|
||||
* 逻辑:POST(create/execute/cancel/retry/manual-close)断言 headers 含 application/json,
|
||||
* 且 body 序列化正确;GET/blob 端点不强制 Content-Type。
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const requestJson = vi.hoisted(() => vi.fn());
|
||||
const requestBlob = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('@/shared/api/client', () => ({
|
||||
BusinessError: class BusinessError extends Error {},
|
||||
requestJson,
|
||||
requestBlob,
|
||||
}));
|
||||
|
||||
vi.mock('@/shared/utils/auth', () => ({
|
||||
getAuthHeaders: () => ({ Authorization: 'Bearer TEST-TOKEN' }),
|
||||
}));
|
||||
|
||||
import {
|
||||
cancelTransferRun,
|
||||
createTransferPrecheck,
|
||||
executeTransferPrecheck,
|
||||
getTransferBacklogSummary,
|
||||
getTransferPrecheck,
|
||||
getTransferRun,
|
||||
listTransferSources,
|
||||
manualCloseTransferItem,
|
||||
retryTransferItem,
|
||||
} from './transfer.api';
|
||||
|
||||
describe('transfer.api JSON request contract', () => {
|
||||
beforeEach(() => {
|
||||
requestJson.mockReset();
|
||||
requestBlob.mockReset();
|
||||
});
|
||||
|
||||
it('创建预检 POST 带 Content-Type: application/json 与序列化 source_codes', () => {
|
||||
createTransferPrecheck({ source_codes: ['DBS-AWSBI'], business_date: '2026-08-18' });
|
||||
const [url, init] = requestJson.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/in-transit-transfer/prechecks');
|
||||
expect(init.method).toBe('POST');
|
||||
expect((init.headers as Record<string, string>)['Content-Type']).toBe('application/json');
|
||||
expect(init.body).toBe(JSON.stringify({ source_codes: ['DBS-AWSBI'], business_date: '2026-08-18' }));
|
||||
});
|
||||
|
||||
it('直接生成调拨单 POST 带 application/json', () => {
|
||||
executeTransferPrecheck('TPC-1', ['INV-001']);
|
||||
const [, init] = requestJson.mock.calls[0] as [string, RequestInit];
|
||||
expect(init.method).toBe('POST');
|
||||
expect((init.headers as Record<string, string>)['Content-Type']).toBe('application/json');
|
||||
expect(init.body).toBe(JSON.stringify({ invoice_nos: ['INV-001'] }));
|
||||
});
|
||||
|
||||
it('重试/关闭/取消 POST 带 application/json', () => {
|
||||
retryTransferItem(7);
|
||||
manualCloseTransferItem(7, '线下已处理');
|
||||
cancelTransferRun('RUN-1', '紧急');
|
||||
for (const [, init] of requestJson.mock.calls as [string, RequestInit][]) {
|
||||
expect(init.method).toBe('POST');
|
||||
expect((init.headers as Record<string, string>)['Content-Type']).toBe('application/json');
|
||||
}
|
||||
});
|
||||
|
||||
it('GET 端点只需鉴权头,不需要强制 Content-Type', () => {
|
||||
getTransferPrecheck('TPC-1');
|
||||
getTransferRun('RUN-1');
|
||||
getTransferBacklogSummary();
|
||||
listTransferSources();
|
||||
for (const [, init] of requestJson.mock.calls as [string, RequestInit][]) {
|
||||
expect(init.headers).toBeDefined();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* features/chat/api/transfer.api.ts
|
||||
* 用途:在途仓自动调拨 API 客户端(统一 requestJson / requestBlob,不重复造客户端)。
|
||||
* 依赖:@/shared/api/client(requestJson / requestBlob / BusinessError)、getAuthHeaders。
|
||||
* 逻辑:薄封装后端 /api/in-transit-transfer 全部端点;二进制下载走 requestBlob。
|
||||
*/
|
||||
import { requestBlob, requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type {
|
||||
TransferActionResult,
|
||||
TransferBacklogItem,
|
||||
TransferBacklogSummary,
|
||||
TransferExecuteResponse,
|
||||
TransferPrecheckDetail,
|
||||
TransferPrecheckSummary,
|
||||
TransferRunResult,
|
||||
TransferSourceFileStatus,
|
||||
TransferSourceOption,
|
||||
} from '../types/transfer.types';
|
||||
|
||||
const BASE = '/api/in-transit-transfer';
|
||||
|
||||
/** JSON 请求头:除鉴权外必须带 Content-Type: application/json,否则 Flask request.get_json 解析不到 body。 */
|
||||
const jsonHeaders = () => ({ 'Content-Type': 'application/json', ...getAuthHeaders() });
|
||||
|
||||
export interface CreatePrecheckPayload {
|
||||
source_codes: string[];
|
||||
business_date?: string;
|
||||
}
|
||||
|
||||
/** 创建预检(只读) */
|
||||
export const createTransferPrecheck = (payload: CreatePrecheckPayload) =>
|
||||
requestJson<TransferPrecheckSummary>(BASE + '/prechecks', {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
/** 恢复预检进度与明细 */
|
||||
export const getTransferPrecheck = (precheckId: string) =>
|
||||
requestJson<TransferPrecheckDetail>(`${BASE}/prechecks/${precheckId}`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
|
||||
/** 确认选择范围并直接生成执行 Run */
|
||||
export const executeTransferPrecheck = (precheckId: string, invoiceNos: string[]) =>
|
||||
requestJson<TransferExecuteResponse>(`${BASE}/prechecks/${precheckId}/execute`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(),
|
||||
body: JSON.stringify({ invoice_nos: invoiceNos }),
|
||||
});
|
||||
|
||||
/** 恢复 Run 最终结果 */
|
||||
export const getTransferRun = (runNo: string) =>
|
||||
requestJson<TransferRunResult>(`${BASE}/runs/${runNo}`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
|
||||
/** 请求停止剩余任务 */
|
||||
export const cancelTransferRun = (runNo: string, reason: string) =>
|
||||
requestJson<TransferActionResult>(`${BASE}/runs/${runNo}/cancel`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(),
|
||||
body: JSON.stringify({ reason }),
|
||||
});
|
||||
|
||||
/** 人工重试异常项(仅重新查询 ERP,新 Attempt) */
|
||||
export const retryTransferItem = (itemId: number) =>
|
||||
requestJson<TransferActionResult>(`${BASE}/items/${itemId}/retry`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(),
|
||||
body: JSON.stringify({ kind: 'erp_recheck' }),
|
||||
});
|
||||
|
||||
/** 人工关闭异常项 */
|
||||
export const manualCloseTransferItem = (itemId: number, reason: string) =>
|
||||
requestJson<TransferActionResult>(`${BASE}/items/${itemId}/manual-close`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(),
|
||||
body: JSON.stringify({ reason }),
|
||||
});
|
||||
|
||||
/** 下载收料来源文件(zip) */
|
||||
export const downloadTransferReceiptFiles = (runNo: string) =>
|
||||
requestBlob(`${BASE}/runs/${runNo}/receipt-files`, { headers: getAuthHeaders() });
|
||||
|
||||
/** 下载预检冻结的 ERP 库存表(csv) */
|
||||
export const downloadTransferErpInventory = (runNo: string) =>
|
||||
requestBlob(`${BASE}/runs/${runNo}/erp-inventory`, { headers: getAuthHeaders() });
|
||||
|
||||
/** 下载七 Sheet 异常 Excel */
|
||||
export const downloadTransferExceptions = (runNo: string) =>
|
||||
requestBlob(`${BASE}/runs/${runNo}/exceptions.xlsx`, { headers: getAuthHeaders() });
|
||||
|
||||
/** 待处理异常列表(可恢复/已关闭/结果未知 + 老化等级) */
|
||||
export const listTransferBacklog = () =>
|
||||
requestJson<TransferBacklogItem[]>(`${BASE}/backlog`, { headers: getAuthHeaders() });
|
||||
|
||||
/** 待处理异常汇总(含 3/5/7 天老化分级) */
|
||||
export const getTransferBacklogSummary = () =>
|
||||
requestJson<TransferBacklogSummary>(`${BASE}/backlog/summary`, { headers: getAuthHeaders() });
|
||||
|
||||
/** 来源实例列表(平台 DBS/Crane 仅分组,每来源附收料文件状态) */
|
||||
export const listTransferSources = () =>
|
||||
requestJson<TransferSourceOption[]>(`${BASE}/sources`, { headers: getAuthHeaders() });
|
||||
|
||||
/** 对指定来源重新触发一次收料 RPA 抓取 */
|
||||
export const retryTransferSourceRpa = (sourceCode: string) =>
|
||||
requestJson<TransferSourceFileStatus>(`${BASE}/sources/${encodeURIComponent(sourceCode)}/retry-rpa`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(),
|
||||
});
|
||||
@@ -2,11 +2,10 @@
|
||||
/**
|
||||
* features/chat/components/ChatAssetHistoryDialog.vue
|
||||
* 用途:展示固定资产履历候选文件列表,并复用既有文件预览弹窗打开具体履历。
|
||||
* 依赖:vue-i18n、聊天页 useChatPage 提供的查询状态与打开预览回调。
|
||||
* 依赖:聊天页 useChatPage 提供的查询状态与打开预览回调。
|
||||
* 逻辑:用户点击资产编号后打开;先显示检索状态,再列出共享盘匹配文件,点击单条文件进入预览。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ExternalLink, FileText, Loader2, X } from 'lucide-vue-next';
|
||||
import type { AssetHistoryFileItem } from '../types/chat.types';
|
||||
|
||||
@@ -25,8 +24,7 @@ const emit = defineEmits<{
|
||||
openPreview: [item: AssetHistoryFileItem];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const titleText = computed(() => props.assetId || props.assetName || t('chat.assetHistory.title'));
|
||||
const titleText = computed(() => props.assetId || props.assetName || '资产履历');
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -38,17 +36,17 @@ const titleText = computed(() => props.assetId || props.assetName || t('chat.ass
|
||||
<div class="dialog-panel flex max-h-[88vh] w-[min(96vw,900px)] max-w-[900px] flex-col">
|
||||
<div class="dialog-header">
|
||||
<div>
|
||||
<h3 class="section-title">{{ $t('chat.assetHistory.title') }}</h3>
|
||||
<p class="section-desc mt-1">{{ $t('chat.assetHistory.currentAsset', { name: titleText }) }}</p>
|
||||
<h3 class="section-title">资产履历</h3>
|
||||
<p class="section-desc mt-1">当前资产:{{ titleText }}</p>
|
||||
</div>
|
||||
<button type="button" class="btn-icon-ds" :aria-label="$t('common.close')" @click="emit('close')">
|
||||
<button type="button" class="btn-icon-ds" aria-label="关闭" @click="emit('close')">
|
||||
<X class="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="dialog-body flex min-h-0 flex-1 flex-col gap-4 border-t-0 pt-4">
|
||||
<div v-if="loading" class="flex h-56 items-center justify-center text-sm text-muted">
|
||||
<Loader2 class="mr-2 h-5 w-5 animate-spin text-brand-500" />
|
||||
{{ $t('chat.assetHistory.searching') }}
|
||||
正在检索共享盘履历文件...
|
||||
</div>
|
||||
<div v-else-if="error" class="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
|
||||
{{ error }}
|
||||
@@ -57,7 +55,7 @@ const titleText = computed(() => props.assetId || props.assetName || t('chat.ass
|
||||
v-else-if="items.length === 0"
|
||||
class="flex h-56 items-center justify-center rounded-2xl border border-dashed border-default bg-surface-soft text-sm text-muted"
|
||||
>
|
||||
{{ $t('chat.assetHistory.empty') }}
|
||||
未找到匹配的履历文件
|
||||
</div>
|
||||
<div v-else class="min-h-0 flex-1 overflow-auto rounded-2xl border border-default bg-surface">
|
||||
<div
|
||||
@@ -72,9 +70,9 @@ const titleText = computed(() => props.assetId || props.assetName || t('chat.ass
|
||||
</div>
|
||||
<div class="mt-1 break-all text-xs text-secondary">{{ item.relative_path }}</div>
|
||||
<div class="mt-2 flex flex-wrap gap-3 text-xs text-muted">
|
||||
<span v-if="item.modified_at">{{ $t('chat.assetHistory.modifiedAt', { time: item.modified_at }) }}</span>
|
||||
<span v-if="item.size_bytes">{{ $t('chat.assetHistory.sizeKb', { size: Math.max(1, Math.round(item.size_bytes / 1024)) }) }}</span>
|
||||
<span v-if="item.match_reason">{{ $t('chat.assetHistory.matchReason', { reason: item.match_reason }) }}</span>
|
||||
<span v-if="item.modified_at">修改时间:{{ item.modified_at }}</span>
|
||||
<span v-if="item.size_bytes">大小:{{ Math.max(1, Math.round(item.size_bytes / 1024)) }} KB</span>
|
||||
<span v-if="item.match_reason">匹配方式:{{ item.match_reason }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
@@ -83,7 +81,7 @@ const titleText = computed(() => props.assetId || props.assetName || t('chat.ass
|
||||
@click="emit('openPreview', item)"
|
||||
>
|
||||
<ExternalLink class="h-4 w-4" />
|
||||
{{ $t('chat.assetHistory.viewFile') }}
|
||||
查看履历
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -38,7 +38,7 @@ const emit = defineEmits<{
|
||||
>
|
||||
<div
|
||||
class="absolute inset-y-0 left-1/2 w-px -translate-x-1/2 transition-colors"
|
||||
:class="isResizing ? 'bg-brand-500' : 'bg-slate-200'"
|
||||
:class="isResizing ? 'bg-brand-500' : 'bg-surface-strong'"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -94,7 +94,7 @@ const emit = defineEmits<{
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="min-h-0 flex-1 bg-slate-100">
|
||||
<div class="min-h-0 flex-1 bg-surface-strong">
|
||||
<div
|
||||
v-if="!currentUrl"
|
||||
class="flex h-full flex-col items-center justify-center gap-3 px-8 text-center text-sm text-muted"
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
/**
|
||||
* features/chat/components/ChatGuideModal.vue
|
||||
* 用途:Agent 学习之窗弹窗,展示指南目录与视频 / PDF / 图片预览。
|
||||
* 依赖:lucide-vue-next、useChatGuides.AgentGuide、vue-i18n($t)。
|
||||
* 逻辑:由 Chat 页打开;目录折叠/展开与空态文案走 chat.guide.* / chat.learningWindow。
|
||||
* Agent 学习之窗:指南目录与视频 / PDF / 图片预览。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { BookOpen, FileText, Image as ImageIcon, PanelLeftClose, PanelLeftOpen, Play, X } from 'lucide-vue-next';
|
||||
@@ -29,7 +27,7 @@ defineProps<{
|
||||
<div class="flex shrink-0 items-center justify-between border-b border-default bg-surface px-6 py-4">
|
||||
<h3 class="flex items-center gap-2 text-lg font-bold text-primary">
|
||||
<BookOpen class="h-5 w-5 text-brand-600" />
|
||||
{{ agentName }} - {{ $t('chat.learningWindow') }}
|
||||
{{ agentName }} - 学习之窗
|
||||
</h3>
|
||||
<div class="flex items-center gap-3">
|
||||
<button
|
||||
@@ -38,7 +36,7 @@ defineProps<{
|
||||
@click="showSidebar = !showSidebar"
|
||||
>
|
||||
<component :is="showSidebar ? PanelLeftClose : PanelLeftOpen" class="h-4 w-4" />
|
||||
{{ showSidebar ? $t('chat.guide.collapseToc') : $t('chat.guide.expandToc') }}
|
||||
{{ showSidebar ? '收起目录' : '展开目录' }}
|
||||
</button>
|
||||
<div class="h-5 w-px bg-default" />
|
||||
<button
|
||||
@@ -95,7 +93,7 @@ defineProps<{
|
||||
v-else-if="activeGuide.file_type === 'pdf'"
|
||||
:key="'pdf-' + activeGuide.id"
|
||||
:src="activeGuide.file_url || activeGuide.file_path"
|
||||
class="h-full w-full border-none bg-white"
|
||||
class="h-full w-full border-none bg-surface"
|
||||
/>
|
||||
<img
|
||||
v-else
|
||||
@@ -106,7 +104,7 @@ defineProps<{
|
||||
</template>
|
||||
<div v-else class="flex flex-col items-center gap-3 text-muted">
|
||||
<BookOpen class="h-12 w-12 opacity-20" />
|
||||
<p class="text-sm">{{ $t('chat.guide.selectHint') }}</p>
|
||||
<p class="text-sm">请选择左侧指南进行查阅</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* features/chat/components/ChatInputBar.spec.ts
|
||||
* 用途:验证采购合同双文件在聊天输入栏中的统一卡片展示与删除交互。
|
||||
* 依赖:Vue Test Utils、Vue I18n、ChatInputBar。
|
||||
* 逻辑:我方原合同和卖方回传合同均以附件卡片展示;删除我方原合同必须通知上层清除对应资产状态。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { ref } from 'vue';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import ChatInputBar from './ChatInputBar.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: { 'zh-CN': {} },
|
||||
});
|
||||
|
||||
/** 创建采购合同双文件输入栏所需的最小属性。 */
|
||||
function mountProcurementInputBar() {
|
||||
return mount(ChatInputBar, {
|
||||
props: {
|
||||
modelValue: '',
|
||||
procurementReviewMode: 'compare',
|
||||
attachments: [{
|
||||
id: 'seller-contract',
|
||||
kind: 'local',
|
||||
file: new File(['seller'], '卖方回传合同.md', { type: 'text/markdown' }),
|
||||
type: 'document',
|
||||
uploadStatus: 'waiting',
|
||||
uploadProgress: 0,
|
||||
}],
|
||||
attachmentPolicy: { anyEnabled: true, canLocal: true, canRemote: false, accept: '.md' },
|
||||
isThinking: false,
|
||||
isVoiceRecording: false,
|
||||
isVoiceTranscribing: false,
|
||||
isUploadingAttachments: false,
|
||||
canSendMessage: true,
|
||||
isShippingNoticeAgent: false,
|
||||
isProcurementContractAgent: true,
|
||||
procurementOriginalContractName: '我方原合同.md',
|
||||
isMaintenanceAgent: false,
|
||||
canManageMaintenance: false,
|
||||
canForceCreateShippingDuplicate: false,
|
||||
shippingSuggestedPrompt: '',
|
||||
shippingPickerRefHolder: { pickerRef: ref(null) },
|
||||
shippingNoticePickerRefHolder: { pickerRef: ref(null) },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
/** 创建仅选择我方原合同、尚未选择卖方回传合同的输入栏。 */
|
||||
function mountOriginalContractOnlyInputBar() {
|
||||
return mount(ChatInputBar, {
|
||||
props: {
|
||||
modelValue: '',
|
||||
procurementReviewMode: 'compare',
|
||||
attachments: [],
|
||||
attachmentPolicy: { anyEnabled: true, canLocal: true, canRemote: false, accept: '.md' },
|
||||
isThinking: false,
|
||||
isVoiceRecording: false,
|
||||
isVoiceTranscribing: false,
|
||||
isUploadingAttachments: true,
|
||||
canSendMessage: false,
|
||||
isShippingNoticeAgent: false,
|
||||
isProcurementContractAgent: true,
|
||||
procurementOriginalContractName: '我方原合同.md',
|
||||
isMaintenanceAgent: false,
|
||||
canManageMaintenance: false,
|
||||
canForceCreateShippingDuplicate: false,
|
||||
shippingSuggestedPrompt: '',
|
||||
shippingPickerRefHolder: { pickerRef: ref(null) },
|
||||
shippingNoticePickerRefHolder: { pickerRef: ref(null) },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('ChatInputBar procurement contract attachments', () => {
|
||||
it('shows the original contract immediately even before a seller contract is selected', () => {
|
||||
const wrapper = mountOriginalContractOnlyInputBar();
|
||||
|
||||
// 原合同上传中时卖方附件数组为空,仍必须显示原合同卡片提供明确反馈。
|
||||
expect(wrapper.get('[data-testid="chat-attachment-list"]')).toBeTruthy();
|
||||
expect(wrapper.get('[data-testid="procurement-original-contract-card"]')).toBeTruthy();
|
||||
expect(wrapper.findAll('[data-testid="chat-attachment-card"]')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('renders the original contract as a standard attachment card and clears it on delete', async () => {
|
||||
const wrapper = mountProcurementInputBar();
|
||||
|
||||
// 断言两份合同使用同一附件卡片结构,防止我方原合同退化回独立小标签。
|
||||
expect(wrapper.get('[data-testid="procurement-original-contract-card"]')).toBeTruthy();
|
||||
expect(wrapper.findAll('[data-testid="chat-attachment-card"], [data-testid="procurement-original-contract-card"]')).toHaveLength(2);
|
||||
|
||||
await wrapper.get('[data-testid="remove-procurement-original-contract"]').trigger('click');
|
||||
|
||||
// 删除操作必须交由父级清空 originalContractAssetNo 与名称,避免残留无形基准文件。
|
||||
expect(wrapper.emitted('clear-procurement-original-contract')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('keeps original-contract delete pointer events out of the attachment drag surface', async () => {
|
||||
const wrapper = mountProcurementInputBar();
|
||||
let dragSurfaceReceivedPointerDown = false;
|
||||
wrapper.get('[data-testid="chat-attachment-list"]').element.addEventListener('pointerdown', () => {
|
||||
dragSurfaceReceivedPointerDown = true;
|
||||
});
|
||||
|
||||
// 删除按钮不能触发横向拖拽容器,否则指针捕获会干扰实际 click 事件。
|
||||
await wrapper.get('[data-testid="remove-procurement-original-contract"]').trigger('pointerdown');
|
||||
|
||||
expect(dragSurfaceReceivedPointerDown).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,9 @@
|
||||
/**
|
||||
* features/chat/components/ChatInputBar.vue
|
||||
* 聊天输入栏:文本框、附件、语音与采购合同双文件输入控件。
|
||||
* 逻辑:底部左区放附件/合同等工具;右区语音与发送并排。采购合同审查用专用上传按钮,不展示通用回形针附件入口。
|
||||
* 用途:承载聊天文本输入、附件预览、语音、知识库选择与发送操作。
|
||||
* 依赖:lucide 图标、附件完整性判断工具。
|
||||
* 逻辑:附件卡片位于文本框上方;订单审核结果随对应聊天消息展示,输入区只保留附件处理状态。
|
||||
* 同时支持采购合同双文件输入控件:底部左区放附件/合同等工具,右区语音与发送并排;采购合同审查用专用上传按钮,不展示通用回形针附件入口。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
@@ -9,7 +11,12 @@ import { useI18n } from 'vue-i18n';
|
||||
import type { Ref } from 'vue';
|
||||
import {
|
||||
Check,
|
||||
CircleAlert,
|
||||
CircleCheck,
|
||||
FileAudio,
|
||||
FileImage,
|
||||
FileText,
|
||||
FileVideo,
|
||||
Link2,
|
||||
Loader2,
|
||||
Mic,
|
||||
@@ -26,6 +33,13 @@ import {
|
||||
isBlockingWarning,
|
||||
isShippingNoticeAttachmentParseIncomplete,
|
||||
} from '../shipping/shippingNoticeAttachmentIntegrity';
|
||||
import {
|
||||
getAttachmentCardStatus,
|
||||
getAttachmentExtension,
|
||||
getAttachmentName,
|
||||
getAttachmentSize,
|
||||
isAttachmentRemoveDisabled,
|
||||
} from '../utils/attachmentCard.utils';
|
||||
|
||||
export interface ChatInputAttachmentPolicy {
|
||||
anyEnabled: boolean;
|
||||
@@ -50,6 +64,7 @@ const props = defineProps<{
|
||||
procurementOriginalContractName?: string | null;
|
||||
isMaintenanceAgent?: boolean;
|
||||
canManageMaintenance?: boolean;
|
||||
canForceCreateShippingDuplicate?: boolean;
|
||||
shippingSuggestedPrompt: string;
|
||||
shippingFocusTaskNo?: string;
|
||||
shippingFocusReason?: string;
|
||||
@@ -63,8 +78,11 @@ const emit = defineEmits<{
|
||||
stop: [];
|
||||
'voice-click': [];
|
||||
'remove-attachment': [id: string];
|
||||
'retry-attachment': [id: string];
|
||||
'retry-shipping-notice-attachment': [id: string];
|
||||
'resolve-shipping-notice-duplicate': [id: string];
|
||||
'select-shipping-candidate': [candidateNo: string, selected: boolean];
|
||||
'resolve-shipping-candidate-duplicate': [candidateNo: string, action: import('../types/shipping.types').ShippingDuplicateAction, targetTaskNo: string | undefined, reason: string | undefined, done: (success: boolean) => void];
|
||||
'local-files-selected': [event: Event];
|
||||
'add-remote-url': [url: string];
|
||||
'shipping-inventory-selected': [event: Event];
|
||||
@@ -85,12 +103,68 @@ const attachmentUrlInputRef = ref<HTMLInputElement | null>(null);
|
||||
const showAttachmentMenu = ref(false);
|
||||
const showAttachmentUrlPanel = ref(false);
|
||||
const attachmentUrlInput = ref('');
|
||||
const attachmentScrollerRef = ref<HTMLElement | null>(null);
|
||||
const attachmentCanScrollLeft = ref(false);
|
||||
const attachmentCanScrollRight = ref(false);
|
||||
let attachmentDragStartX = 0;
|
||||
let attachmentDragScrollLeft = 0;
|
||||
let attachmentDragging = false;
|
||||
|
||||
/** 同步附件横向带的左右可滚动状态,供箭头按钮和无障碍状态使用。 */
|
||||
function updateAttachmentScrollState() {
|
||||
const element = attachmentScrollerRef.value;
|
||||
if (!element) return;
|
||||
attachmentCanScrollLeft.value = element.scrollLeft > 1;
|
||||
attachmentCanScrollRight.value = element.scrollLeft + element.clientWidth < element.scrollWidth - 1;
|
||||
}
|
||||
|
||||
/** 按固定步长移动附件横向带,避免大量附件撑高输入区。 */
|
||||
function scrollAttachments(direction: 'left' | 'right') {
|
||||
attachmentScrollerRef.value?.scrollBy({ left: direction === 'left' ? -320 : 320, behavior: 'smooth' });
|
||||
}
|
||||
|
||||
/** 开始桌面端指针拖拽;触摸端交给原生横向滚动,避免手势冲突。 */
|
||||
function startAttachmentDrag(event: PointerEvent) {
|
||||
const element = attachmentScrollerRef.value;
|
||||
if (!element || event.pointerType === 'touch') return;
|
||||
attachmentDragging = true;
|
||||
attachmentDragStartX = event.clientX;
|
||||
attachmentDragScrollLeft = element.scrollLeft;
|
||||
element.setPointerCapture?.(event.pointerId);
|
||||
}
|
||||
|
||||
/** 根据指针位移更新附件横向滚动位置。 */
|
||||
function moveAttachmentDrag(event: PointerEvent) {
|
||||
if (!attachmentDragging || !attachmentScrollerRef.value) return;
|
||||
attachmentScrollerRef.value.scrollLeft = attachmentDragScrollLeft - (event.clientX - attachmentDragStartX);
|
||||
}
|
||||
|
||||
/** 结束附件横向拖拽并恢复普通指针状态。 */
|
||||
function stopAttachmentDrag() {
|
||||
attachmentDragging = false;
|
||||
}
|
||||
|
||||
/** 当前发货通知是否仍在上传或预解析,决定输入框下方的操作提示。 */
|
||||
const hasShippingNoticeInProgress = computed(() => props.attachments.some(
|
||||
(attachment) => attachment.kind === 'shipping_notice'
|
||||
&& (
|
||||
attachment.uploadStatus === 'waiting'
|
||||
|| attachment.uploadStatus === 'uploading'
|
||||
|| ['waiting', 'queued', 'parsing'].includes(attachment.parseStatus)
|
||||
),
|
||||
));
|
||||
|
||||
const hasProcurementContractAttachment = computed(() =>
|
||||
Boolean(props.isProcurementContractAgent)
|
||||
&& props.attachments.some((item) => item.kind === 'local'),
|
||||
);
|
||||
|
||||
/** 显示我方原合同卡片的文件扩展名;没有扩展名时使用通用文档标识。 */
|
||||
function getProcurementOriginalContractExtension(name: string): string {
|
||||
const extension = name.split('.').pop()?.trim();
|
||||
return extension ? extension.toUpperCase().slice(0, 4) : 'DOC';
|
||||
}
|
||||
|
||||
const procurementQuickActions = computed(() => {
|
||||
const actions = [
|
||||
{
|
||||
@@ -117,24 +191,47 @@ const procurementQuickActions = computed(() => {
|
||||
|
||||
/**
|
||||
* 汇总 EML 附件解析进度,供输入栏徽标展示。
|
||||
* 核心逻辑:failed/empty/skipped/超限/文本预算耗尽计为问题;duplicate 单独提示,不记为失败。
|
||||
* 核心逻辑:阶段 1 仅展示快览结果;优先说明发现了多少附件,技术失败/目录不完整再退化为问题提示。
|
||||
*/
|
||||
function shippingNoticeAttachmentHint(attachment: ShippingNoticePendingAttachment): string {
|
||||
const summary = attachment.parseSummary;
|
||||
const total = Number(summary?.attachment_count || 0);
|
||||
const rows = summary?.attachments || [];
|
||||
// 兼容旧摘要:早期快览未标记签名图,按内嵌标记、目录原因和图片 MIME 一并排除。
|
||||
const businessRows = rows.filter((item) => {
|
||||
const mimeType = String(item.mime_type || '').toLowerCase();
|
||||
const catalogReason = String(item.catalog_reason || '').toLowerCase();
|
||||
return !item.is_inline_resource
|
||||
&& !mimeType.startsWith('image/')
|
||||
&& catalogReason !== 'signature_or_logo'
|
||||
&& catalogReason !== 'inline_resource';
|
||||
});
|
||||
const inlineCount = rows.length - businessRows.length;
|
||||
const total = Math.max(0, Number(summary?.attachment_count || 0) - inlineCount);
|
||||
const warnings = summary?.warnings || [];
|
||||
const hasBlockingWarning = warnings.some((w) => isBlockingWarning(String(w || '')));
|
||||
if (!total && !hasBlockingWarning && !rows.length) return '';
|
||||
if (!total && !hasBlockingWarning && !businessRows.length) return '';
|
||||
|
||||
const effectiveTotal = total || rows.length;
|
||||
const ok = rows.filter((item) => item.parse_status === 'parsed').length;
|
||||
const problematic = rows.filter((item) =>
|
||||
const effectiveTotal = total || businessRows.length;
|
||||
const ok = Number(summary?.ready_attachment_count || businessRows.filter((item) => item.ready_for_extraction).length);
|
||||
const problematic = businessRows.filter((item) =>
|
||||
['failed', 'empty', 'skipped'].includes(String(item.parse_status || '')),
|
||||
).length;
|
||||
const duplicates = rows.filter((item) => item.parse_status === 'duplicate').length;
|
||||
const overflow = Math.max(0, effectiveTotal - rows.length);
|
||||
const issues = problematic + overflow + (hasBlockingWarning && problematic === 0 && overflow === 0 ? 1 : 0);
|
||||
const duplicates = Number(
|
||||
summary?.duplicate_attachment_count
|
||||
|| businessRows.filter((item) => item.parse_status === 'duplicate').length,
|
||||
);
|
||||
const overflow = Math.max(0, effectiveTotal - businessRows.length);
|
||||
const previewStatus = String(summary?.preview_status || '').trim().toLowerCase();
|
||||
const issues = problematic
|
||||
+ overflow
|
||||
+ (hasBlockingWarning && problematic === 0 && overflow === 0 ? 1 : 0)
|
||||
+ (
|
||||
(summary?.technical_failure || previewStatus === 'technical_failed' || previewStatus === 'directory_incomplete')
|
||||
&& problematic === 0
|
||||
&& overflow === 0
|
||||
? 1
|
||||
: 0
|
||||
);
|
||||
|
||||
if (issues > 0) {
|
||||
return t('chat.shippingNoticeAttachmentHintPartial', {
|
||||
@@ -144,10 +241,10 @@ function shippingNoticeAttachmentHint(attachment: ShippingNoticePendingAttachmen
|
||||
});
|
||||
}
|
||||
if (duplicates > 0) {
|
||||
return t('chat.shippingNoticeAttachmentHintWithDup', { ok, total: effectiveTotal, duplicates });
|
||||
return t('chat.shippingNoticeAttachmentHintDiscoveredWithDup', { total: effectiveTotal, duplicates });
|
||||
}
|
||||
if (!effectiveTotal) return '';
|
||||
return t('chat.shippingNoticeAttachmentHint', { ok, total: effectiveTotal });
|
||||
return t('chat.shippingNoticeAttachmentHintDiscovered', { total: effectiveTotal });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -181,6 +278,15 @@ function shippingNoticeAttachmentTitle(attachment: ShippingNoticePendingAttachme
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/** 根据附件业务类型选择文件图标,帮助用户快速区分媒体与文档。 */
|
||||
function attachmentIcon(attachment: PendingAttachment) {
|
||||
if (attachment.kind === 'remote') return Link2;
|
||||
if (attachment.type === 'image') return FileImage;
|
||||
if (attachment.type === 'audio') return FileAudio;
|
||||
if (attachment.type === 'video') return FileVideo;
|
||||
return FileText;
|
||||
}
|
||||
|
||||
const closeAttachmentMenu = () => {
|
||||
showAttachmentMenu.value = false;
|
||||
showAttachmentUrlPanel.value = false;
|
||||
@@ -261,11 +367,14 @@ const handleDocumentPointerDown = (event: MouseEvent | TouchEvent) => {
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
nextTick(updateAttachmentScrollState);
|
||||
window.addEventListener('resize', updateAttachmentScrollState);
|
||||
document.addEventListener('mousedown', handleDocumentPointerDown);
|
||||
document.addEventListener('touchstart', handleDocumentPointerDown, { passive: true });
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('resize', updateAttachmentScrollState);
|
||||
document.removeEventListener('mousedown', handleDocumentPointerDown);
|
||||
document.removeEventListener('touchstart', handleDocumentPointerDown);
|
||||
});
|
||||
@@ -308,7 +417,7 @@ watch(
|
||||
role="tab"
|
||||
class="rounded-full px-3 py-1.5 text-xs font-bold transition-all"
|
||||
:class="procurementReviewMode === 'compare'
|
||||
? 'bg-white text-[#2f80d1] shadow-[0_1px_4px_rgba(23,32,51,0.08)]'
|
||||
? 'bg-surface text-[#2f80d1] shadow-[0_1px_4px_rgba(23,32,51,0.08)]'
|
||||
: 'bg-transparent text-[#667792] hover:text-[#172033]'"
|
||||
:aria-selected="procurementReviewMode === 'compare'"
|
||||
@click="procurementReviewMode = 'compare'"
|
||||
@@ -320,7 +429,7 @@ watch(
|
||||
role="tab"
|
||||
class="rounded-full px-3 py-1.5 text-xs font-bold transition-all"
|
||||
:class="procurementReviewMode === 'solo'
|
||||
? 'bg-white text-[#2f80d1] shadow-[0_1px_4px_rgba(23,32,51,0.08)]'
|
||||
? 'bg-surface text-[#2f80d1] shadow-[0_1px_4px_rgba(23,32,51,0.08)]'
|
||||
: 'bg-transparent text-[#667792] hover:text-[#172033]'"
|
||||
:aria-selected="procurementReviewMode === 'solo'"
|
||||
@click="procurementReviewMode = 'solo'"
|
||||
@@ -352,11 +461,173 @@ watch(
|
||||
<X class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="attachments.length > 0 || (isProcurementContractAgent && procurementReviewMode === 'compare' && procurementOriginalContractName)"
|
||||
data-testid="chat-attachment-list"
|
||||
class="relative flex items-center gap-1 px-2.5 pb-2 pt-1"
|
||||
>
|
||||
<button v-if="attachmentCanScrollLeft" type="button" class="z-10 shrink-0 rounded-full border border-default bg-surface p-1 text-muted shadow-sm" aria-label="向左查看附件" @click="scrollAttachments('left')">‹</button>
|
||||
<div
|
||||
ref="attachmentScrollerRef"
|
||||
class="flex min-w-0 flex-1 flex-nowrap gap-2 overflow-x-auto pb-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
|
||||
:class="attachmentDragging ? 'cursor-grabbing select-none' : 'cursor-grab'"
|
||||
@scroll="updateAttachmentScrollState"
|
||||
@pointerdown="startAttachmentDrag"
|
||||
@pointermove="moveAttachmentDrag"
|
||||
@pointerup="stopAttachmentDrag"
|
||||
@pointercancel="stopAttachmentDrag"
|
||||
@pointerleave="stopAttachmentDrag"
|
||||
>
|
||||
<article
|
||||
v-if="isProcurementContractAgent && procurementReviewMode === 'compare' && procurementOriginalContractName"
|
||||
data-testid="procurement-original-contract-card"
|
||||
class="group relative flex h-[68px] w-[250px] shrink-0 items-center gap-3 rounded-xl border border-[#9cc7f2] bg-[#eef6ff] px-3 py-2.5 transition-colors"
|
||||
:title="procurementOriginalContractName"
|
||||
>
|
||||
<div
|
||||
class="flex h-11 w-10 shrink-0 flex-col items-center justify-center rounded-lg bg-brand-50 text-brand-700 dark:bg-brand-900/30 dark:text-brand-300"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<FileText class="h-4.5 w-4.5" />
|
||||
<span class="mt-0.5 max-w-9 truncate text-[9px] font-bold leading-none">{{ getProcurementOriginalContractExtension(procurementOriginalContractName) }}</span>
|
||||
</div>
|
||||
<div class="min-w-0 flex-1 pr-5">
|
||||
<p class="truncate text-sm font-medium text-primary">
|
||||
<span class="mr-1 text-[#2f80d1]">{{ $t('chat.procurementContract.originalContractChip', { name: '' }) }}</span>
|
||||
{{ procurementOriginalContractName }}
|
||||
</p>
|
||||
<div class="mt-1 flex min-w-0 items-center gap-1.5 text-[11px] leading-none text-muted">
|
||||
<span>{{ $t('chat.attachment.pending') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="remove-procurement-original-contract"
|
||||
class="absolute right-1.5 top-1.5 flex h-6 w-6 items-center justify-center rounded-full text-muted opacity-80 transition hover:bg-surface hover:text-red-500 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-400"
|
||||
:title="t('chat.attachment.remove')"
|
||||
:aria-label="t('chat.attachment.removeNamed', { name: procurementOriginalContractName })"
|
||||
@pointerdown.stop
|
||||
@click.stop="emit('clear-procurement-original-contract')"
|
||||
>
|
||||
<X class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</article>
|
||||
<article
|
||||
v-for="a in attachments"
|
||||
:key="a.id"
|
||||
data-testid="chat-attachment-card"
|
||||
class="group relative flex h-[68px] w-[250px] shrink-0 items-center gap-3 rounded-xl px-3 py-2.5 transition-colors"
|
||||
:class="isProcurementContractAgent && a.kind === 'local'
|
||||
? 'border border-[#9cc7f2] bg-[#eef6ff]'
|
||||
: 'border border-default bg-surface-soft'"
|
||||
:title="a.kind === 'shipping_notice' ? shippingNoticeAttachmentTitle(a) : getAttachmentName(a)"
|
||||
>
|
||||
<div
|
||||
class="flex h-11 w-10 shrink-0 flex-col items-center justify-center rounded-lg bg-brand-50 text-brand-700 dark:bg-brand-900/30 dark:text-brand-300"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<component :is="attachmentIcon(a)" class="h-4.5 w-4.5" />
|
||||
<span class="mt-0.5 max-w-9 truncate text-[9px] font-bold leading-none">{{ getAttachmentExtension(a) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="min-w-0 flex-1 pr-5">
|
||||
<p class="truncate text-sm font-medium text-primary">
|
||||
<span v-if="isProcurementContractAgent" class="mr-1 text-[#2f80d1]">
|
||||
{{ $t(procurementReviewMode === 'compare'
|
||||
? 'chat.procurementContract.sellerReturnedContractLabel'
|
||||
: 'chat.procurementContract.contractToReviewLabel') }}:
|
||||
</span>
|
||||
{{ getAttachmentName(a) }}
|
||||
</p>
|
||||
<div class="mt-1 flex min-w-0 items-center gap-1.5 text-[11px] leading-none">
|
||||
<span v-if="getAttachmentSize(a)" class="shrink-0 text-muted">{{ getAttachmentSize(a) }}</span>
|
||||
<span v-if="getAttachmentSize(a)" class="text-muted">·</span>
|
||||
<span
|
||||
class="flex min-w-0 items-center gap-1 truncate"
|
||||
:class="{
|
||||
'text-muted': getAttachmentCardStatus(a).state === 'pending',
|
||||
'text-brand-600': ['uploading', 'processing'].includes(getAttachmentCardStatus(a).state),
|
||||
'text-amber-700': getAttachmentCardStatus(a).state === 'attention',
|
||||
'text-emerald-600': getAttachmentCardStatus(a).state === 'ready',
|
||||
'text-red-500': getAttachmentCardStatus(a).state === 'failed',
|
||||
}"
|
||||
>
|
||||
<Loader2
|
||||
v-if="['uploading', 'processing'].includes(getAttachmentCardStatus(a).state)"
|
||||
class="h-3 w-3 shrink-0 animate-spin"
|
||||
/>
|
||||
<CircleCheck v-else-if="getAttachmentCardStatus(a).state === 'ready'" class="h-3 w-3 shrink-0" />
|
||||
<CircleAlert v-else-if="['attention', 'failed'].includes(getAttachmentCardStatus(a).state)" class="h-3 w-3 shrink-0" />
|
||||
<span class="truncate">{{ t(getAttachmentCardStatus(a).labelKey) }}</span>
|
||||
<template v-if="a.kind === 'shipping_notice' && shippingNoticeAttachmentHint(a)">
|
||||
<span class="truncate">· {{ shippingNoticeAttachmentHint(a) }}</span>
|
||||
</template>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="a.kind === 'local' && a.uploadStatus === 'failed'"
|
||||
class="absolute bottom-1.5 right-2 flex items-center gap-1"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded p-1 text-red-500 hover:bg-red-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-400 disabled:cursor-not-allowed disabled:opacity-30 dark:hover:bg-red-950/30"
|
||||
:disabled="isUploadingAttachments"
|
||||
:title="t('chat.attachment.retry')"
|
||||
:aria-label="t('chat.attachment.retryNamed', { name: getAttachmentName(a) })"
|
||||
@click="emit('retry-attachment', a.id)"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="a.kind === 'shipping_notice' && (canRetryShippingNoticeParse(a) || (!a.candidates?.length && a.duplicate?.blocking && !a.duplicateResolution?.action))"
|
||||
class="absolute bottom-1.5 right-2 flex items-center gap-1"
|
||||
>
|
||||
<button
|
||||
v-if="!a.candidates?.length && a.duplicate?.blocking && !a.duplicateResolution?.action"
|
||||
type="button"
|
||||
class="rounded px-1.5 py-1 text-[10px] font-medium text-amber-700 hover:bg-amber-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-400"
|
||||
:title="t('chat.shippingNoticeDuplicateHandle')"
|
||||
@click="emit('resolve-shipping-notice-duplicate', a.id)"
|
||||
>
|
||||
{{ t('chat.shippingNoticeDuplicateHandle') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canRetryShippingNoticeParse(a)"
|
||||
type="button"
|
||||
class="rounded p-1 text-muted hover:bg-surface hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-400"
|
||||
:title="t('chat.shippingNoticeRetryParse')"
|
||||
@click="emit('retry-shipping-notice-attachment', a.id)"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="absolute right-1.5 top-1.5 flex h-6 w-6 items-center justify-center rounded-full text-muted opacity-80 transition hover:bg-surface hover:text-red-500 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-400 disabled:cursor-not-allowed disabled:opacity-30"
|
||||
:disabled="isAttachmentRemoveDisabled(a)"
|
||||
:title="t('chat.attachment.remove')"
|
||||
:aria-label="t('chat.attachment.removeNamed', { name: getAttachmentName(a) })"
|
||||
@pointerdown.stop
|
||||
@click.stop="emit('remove-attachment', a.id)"
|
||||
>
|
||||
<X class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</article>
|
||||
</div>
|
||||
<button v-if="attachmentCanScrollRight" type="button" class="z-10 shrink-0 rounded-full border border-default bg-surface p-1 text-muted shadow-sm" aria-label="向右查看附件" @click="scrollAttachments('right')">›</button>
|
||||
</div>
|
||||
|
||||
<input
|
||||
:ref="bindShippingPickerRef"
|
||||
type="file"
|
||||
class="hidden"
|
||||
accept=".xlsx,.csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,text/csv"
|
||||
accept=".xls,.xlsx,.csv,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,text/csv"
|
||||
@change="emit('shipping-inventory-selected', $event)"
|
||||
/>
|
||||
|
||||
@@ -377,102 +648,6 @@ watch(
|
||||
@change="emit('procurement-original-contract-selected', $event)"
|
||||
/>
|
||||
|
||||
<div
|
||||
v-if="isProcurementContractAgent && procurementReviewMode === 'compare' && procurementOriginalContractName"
|
||||
class="flex flex-wrap gap-2 px-3 pb-1"
|
||||
>
|
||||
<div class="flex items-center gap-2 rounded-lg border border-dashed border-[#8db8e6] bg-[#eef6ff] px-2 py-1 text-xs font-semibold text-[#1f5f99]">
|
||||
<FileText class="h-3.5 w-3.5" />
|
||||
<span class="max-w-[260px] truncate">{{ $t('chat.procurementContract.originalContractChip', { name: procurementOriginalContractName }) }}</span>
|
||||
<button type="button" class="text-[#1f5f99] hover:opacity-80" @click="emit('clear-procurement-original-contract')">
|
||||
<X class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="attachments.length > 0" class="flex flex-wrap gap-2 px-3 pb-1">
|
||||
<div
|
||||
v-for="a in attachments"
|
||||
:key="a.id"
|
||||
class="flex items-center gap-2 rounded-lg border px-2 py-1 text-xs"
|
||||
:class="isProcurementContractAgent && a.kind === 'local'
|
||||
? 'border-[#9cc7f2] bg-[#eef6ff] font-semibold text-[#1f5f99]'
|
||||
: 'border-default bg-surface-soft text-secondary'"
|
||||
>
|
||||
<FileText
|
||||
v-if="isProcurementContractAgent && a.kind === 'local'"
|
||||
class="h-3.5 w-3.5 shrink-0 text-[#2f80d1]"
|
||||
/>
|
||||
<span class="max-w-[220px] truncate">
|
||||
<template v-if="a.kind === 'shipping_notice'">
|
||||
{{ a.originalFilename }}
|
||||
<span v-if="a.uploadStatus === 'uploading'" class="text-muted"> · {{ t('chat.shippingNoticeUploading') }}</span>
|
||||
<span v-else-if="a.parseStatus === 'queued' || a.parseStatus === 'parsing'" class="text-muted"> · {{ t('chat.shippingNoticeParsing') }}</span>
|
||||
<span
|
||||
v-else-if="a.parseStatus === 'parsed' && a.duplicate?.status === 'possible_duplicate' && !a.duplicateResolution?.action"
|
||||
class="font-medium text-amber-700"
|
||||
> · {{ t('chat.shippingNoticeDuplicatePossibleBadge') }}</span>
|
||||
<span
|
||||
v-else-if="a.parseStatus === 'parsed' && a.duplicate?.blocking && !a.duplicateResolution?.action"
|
||||
class="font-medium text-amber-700"
|
||||
> · {{ t('chat.shippingNoticeDuplicateBlockingBadge') }}</span>
|
||||
<span
|
||||
v-else-if="a.parseStatus === 'parsed' && a.duplicateResolution?.action === 'create_revision'"
|
||||
class="text-brand-700"
|
||||
> · {{ t('chat.shippingNoticeDuplicateRevisionChosen') }}</span>
|
||||
<span
|
||||
v-else-if="a.parseStatus === 'parsed' && a.duplicateResolution?.action === 'force_create'"
|
||||
class="text-amber-700"
|
||||
> · {{ t('chat.shippingNoticeDuplicateForceChosen') }}</span>
|
||||
<span
|
||||
v-else-if="a.parseStatus === 'parsed' && a.duplicateResolution?.action === 'open_existing'"
|
||||
class="text-muted"
|
||||
> · {{ t('chat.shippingNoticeDuplicateOpenChosen') }}</span>
|
||||
<span
|
||||
v-else-if="a.parseStatus === 'parsed'"
|
||||
class="text-muted"
|
||||
:title="shippingNoticeAttachmentTitle(a)"
|
||||
>
|
||||
· {{ t('chat.shippingNoticeParsed') }}
|
||||
<template v-if="shippingNoticeAttachmentHint(a)">
|
||||
· {{ shippingNoticeAttachmentHint(a) }}
|
||||
</template>
|
||||
</span>
|
||||
<span v-else-if="a.parseStatus === 'failed'" class="text-muted"> · {{ t('chat.shippingNoticeParseFailed') }}</span>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span v-if="isProcurementContractAgent" class="mr-1 text-[#2f80d1]">
|
||||
{{ $t(procurementReviewMode === 'compare'
|
||||
? 'chat.procurementContract.sellerReturnedContractLabel'
|
||||
: 'chat.procurementContract.contractToReviewLabel') }}:
|
||||
</span>
|
||||
{{ a.kind === 'local' ? a.file.name : a.url }}
|
||||
</template>
|
||||
</span>
|
||||
<button
|
||||
v-if="a.kind === 'shipping_notice' && a.duplicate?.blocking && !a.duplicateResolution?.action"
|
||||
type="button"
|
||||
class="text-amber-700 hover:text-amber-800"
|
||||
:title="t('chat.shippingNoticeDuplicateHandle')"
|
||||
@click="emit('resolve-shipping-notice-duplicate', a.id)"
|
||||
>
|
||||
{{ t('chat.shippingNoticeDuplicateHandle') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="a.kind === 'shipping_notice' && canRetryShippingNoticeParse(a)"
|
||||
type="button"
|
||||
class="text-muted hover:text-primary"
|
||||
:title="t('chat.shippingNoticeRetryParse')"
|
||||
@click="emit('retry-shipping-notice-attachment', a.id)"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<button type="button" class="text-muted hover:text-red-500" @click="emit('remove-attachment', a.id)">
|
||||
<X class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="hasProcurementContractAttachment"
|
||||
class="flex flex-wrap items-center gap-2 px-3 pb-1"
|
||||
@@ -481,7 +656,7 @@ watch(
|
||||
v-for="action in procurementQuickActions"
|
||||
:key="action.label"
|
||||
type="button"
|
||||
class="rounded-full border border-[#d8e0ec] bg-white px-3 py-1.5 text-xs font-semibold text-[#31445f] transition-colors hover:border-[#2f80d1] hover:bg-[#eef6ff] hover:text-[#1f5f99] disabled:cursor-not-allowed disabled:opacity-50"
|
||||
class="rounded-full border border-[#d8e0ec] bg-surface px-3 py-1.5 text-xs font-semibold text-[#31445f] transition-colors hover:border-[#2f80d1] hover:bg-[#eef6ff] hover:text-[#1f5f99] disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:disabled="isThinking || isUploadingAttachments"
|
||||
@click="runProcurementQuickAction(action.prompt)"
|
||||
>
|
||||
@@ -500,7 +675,7 @@ watch(
|
||||
>
|
||||
{{ shippingSuggestedPrompt || $t('chat.recommendedQuestion') }}
|
||||
</button>
|
||||
<span>{{ t('chat.shippingNoticeConfirmBatchHint') }}</span>
|
||||
<span>{{ hasShippingNoticeInProgress ? t('chat.shippingNoticeWaitingForParse') : t('chat.shippingNoticeConfirmBatchHint') }}</span>
|
||||
</div>
|
||||
|
||||
<textarea
|
||||
@@ -683,7 +858,7 @@ watch(
|
||||
:disabled="!canSendMessage"
|
||||
class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full border shadow-sm transition-all duration-200 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:class="!canSendMessage
|
||||
? 'border-default bg-slate-100 text-muted'
|
||||
? 'border-default bg-surface-strong text-muted'
|
||||
: 'border-brand-500 bg-brand-500 text-white shadow-[0_0_0_4px_rgba(59,130,246,0.18)] hover:scale-105 hover:bg-brand-600 hover:shadow-[0_0_0_6px_rgba(59,130,246,0.24)] active:scale-95'"
|
||||
@click="emit('send')"
|
||||
>
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
/**
|
||||
* features/chat/components/ChatMessageList.vue
|
||||
* 消息列表主区域:滚动容器、欢迎页、消息气泡与思考中占位。
|
||||
* 用途:消息列表主区域(滚动容器、欢迎页、气泡与思考中占位)。
|
||||
* 依赖:ChatMessageBubble、各类进度卡、chat.types。
|
||||
* 逻辑:按 shouldRenderMessage 过滤;货代抽取卡按 run / upload_batch / client_submission 去重只留最后一张;
|
||||
* 用户气泡在下方已有抽取进度卡时对附件启用 summaryOnly,避免与进度卡重复堆文件明细。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import type { Ref } from 'vue';
|
||||
import ChatWelcomePanel, { type WelcomeQuestionItem, type WelcomeQuestionSection } from './ChatWelcomePanel.vue';
|
||||
import ChatThinkingBubble from './ChatThinkingBubble.vue';
|
||||
import ChatMessageBubble, { type ChatMessageBubbleHandlers } from './messages/ChatMessageBubble.vue';
|
||||
import TransferHomePanel from './messages/TransferHomePanel.vue';
|
||||
import ToolRunProgressCard from './ToolRunProgressCard.vue';
|
||||
import type { LeaveMessageHandlers } from './messages/LeaveMessageBlock.vue';
|
||||
import type { ShippingMappingHandlers } from './messages/ShippingInventoryMappingMessage.vue';
|
||||
import type { ShippingMessageHandlers } from './messages/shippingMessageHandlers';
|
||||
import type { TrainingHandlers } from './messages/TrainingExamQuestionMessage.vue';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ToolRunProgress } from '../api/toolRunProgress.api';
|
||||
@@ -34,7 +38,7 @@ const {
|
||||
isShippingNoticeAgent: boolean;
|
||||
handlers: ChatMessageBubbleHandlers;
|
||||
leaveHandlers: LeaveMessageHandlers;
|
||||
shippingHandlers: ShippingMappingHandlers;
|
||||
shippingHandlers: ShippingMessageHandlers;
|
||||
trainingHandlers: TrainingHandlers;
|
||||
shouldRenderMessage: (msg: ChatMessage) => boolean;
|
||||
shouldShowToolRunProgressAfterMessage: (msg: ChatMessage, index: number) => boolean;
|
||||
@@ -45,9 +49,12 @@ const {
|
||||
toolRunProgressTitle: string;
|
||||
showScrollToBottom: boolean;
|
||||
hideWelcomePanel?: boolean;
|
||||
/** 在途仓自动调拨 Agent:无消息时渲染专属首页入口区(替代通用欢迎面板)。 */
|
||||
isInTransitTransferAgent?: boolean;
|
||||
pinMessagesToBottom?: boolean;
|
||||
/** 供父级滚动逻辑绑定 main 元素 */
|
||||
scrollContainerHolder: { el: Ref<HTMLElement | null> };
|
||||
compactShippingProgress?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -61,6 +68,9 @@ const emit = defineEmits<{
|
||||
'maintenance-edit-record': [record: MaintenanceRecord];
|
||||
'maintenance-view-record-history': [device: MaintenanceDevice];
|
||||
'maintenance-create-record-for-device': [device: MaintenanceDevice];
|
||||
'open-batch-workbench': [];
|
||||
/** 在途仓自动调拨:业务流激活时向上冒泡,父级据此隐藏聊天输入框。 */
|
||||
'transfer-flow-active': [active: boolean];
|
||||
}>();
|
||||
|
||||
const bindScrollContainer = (node: unknown) => {
|
||||
@@ -77,6 +87,59 @@ const getMessageKey = (msg: ChatMessage, index: number) => (
|
||||
|| `${msg.role}:${msg.run_id || 'none'}:${String(msg.content || '').slice(0, 40)}:${index}`
|
||||
);
|
||||
|
||||
/** 同一 Run / 上传批次 / 提交幂等键只展示最后一张状态卡,避免历史恢复造成重复窗口。 */
|
||||
const isDuplicateShippingExtractionMessage = (items: ChatMessage[], index: number): boolean => {
|
||||
const current = items[index];
|
||||
if (!current?.shipping_order_extraction_state) return false;
|
||||
const payload = current.payload && typeof current.payload === 'object'
|
||||
? current.payload as Record<string, unknown>
|
||||
: {};
|
||||
const runIdentity = String(
|
||||
payload.order_extraction_run_no
|
||||
|| payload.formId
|
||||
|| current.shipping_order_extraction_state.runNo
|
||||
|| '',
|
||||
).trim();
|
||||
const batchIdentity = String(
|
||||
payload.shipping_order_extraction_upload_batch_id
|
||||
|| current.shipping_order_extraction_state.uploadBatchId
|
||||
|| '',
|
||||
).trim();
|
||||
const submissionIdentity = String(
|
||||
payload.shipping_order_extraction_client_submission_id
|
||||
|| current.shipping_order_extraction_state.clientSubmissionId
|
||||
|| '',
|
||||
).trim();
|
||||
if (!runIdentity && !batchIdentity && !submissionIdentity) return false;
|
||||
return items.slice(index + 1).some((candidate) => {
|
||||
if (!candidate?.shipping_order_extraction_state) return false;
|
||||
const candidatePayload = candidate.payload && typeof candidate.payload === 'object'
|
||||
? candidate.payload as Record<string, unknown>
|
||||
: {};
|
||||
const candidateRunIdentity = String(
|
||||
candidatePayload.order_extraction_run_no
|
||||
|| candidatePayload.formId
|
||||
|| candidate.shipping_order_extraction_state.runNo
|
||||
|| '',
|
||||
).trim();
|
||||
const candidateBatchIdentity = String(
|
||||
candidatePayload.shipping_order_extraction_upload_batch_id
|
||||
|| candidate.shipping_order_extraction_state.uploadBatchId
|
||||
|| '',
|
||||
).trim();
|
||||
const candidateSubmissionIdentity = String(
|
||||
candidatePayload.shipping_order_extraction_client_submission_id
|
||||
|| candidate.shipping_order_extraction_state.clientSubmissionId
|
||||
|| '',
|
||||
).trim();
|
||||
return Boolean(
|
||||
(batchIdentity && candidateBatchIdentity === batchIdentity)
|
||||
|| (submissionIdentity && candidateSubmissionIdentity === submissionIdentity)
|
||||
|| (runIdentity && candidateRunIdentity === runIdentity),
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 标记“当前消息后面是否还存在新的 assistant 消息”。
|
||||
* 核心逻辑:培训题卡属于“最新一张 assistant 题卡”才能继续交互;
|
||||
@@ -90,6 +153,20 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 用户消息与下一轮用户输入之间,是否已有货代订单抽取进度卡。
|
||||
* 核心逻辑:有进度卡时附件区只留摘要,文件明细交给进度卡展示。
|
||||
*/
|
||||
const hasFollowingShippingProgressCard = (items: ChatMessage[], index: number): boolean => {
|
||||
for (let i = index + 1; i < items.length; i += 1) {
|
||||
const candidate = items[i];
|
||||
if (!candidate) continue;
|
||||
if (candidate.role === 'user') break;
|
||||
if (candidate.shipping_order_extraction_state) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -100,7 +177,7 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
|
||||
>
|
||||
<div :class="messages.length === 0 ? 'h-full' : pinMessagesToBottom === false ? 'min-h-full' : 'flex min-h-full flex-col justify-end'">
|
||||
<ChatWelcomePanel
|
||||
v-if="messages.length === 0 && !hideWelcomePanel"
|
||||
v-if="messages.length === 0 && !hideWelcomePanel && !isInTransitTransferAgent"
|
||||
:agent-name="agentName"
|
||||
:suggested-questions-style="suggestedQuestionsStyle"
|
||||
:styled-sections="styledSections"
|
||||
@@ -109,9 +186,15 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
|
||||
@select-question="emit('select-question', $event)"
|
||||
/>
|
||||
|
||||
<TransferHomePanel
|
||||
v-if="messages.length === 0 && !hideWelcomePanel && isInTransitTransferAgent"
|
||||
:agent-name="agentName"
|
||||
@flow-active="emit('transfer-flow-active', $event)"
|
||||
/>
|
||||
|
||||
<template v-for="(msg, index) in messages" :key="getMessageKey(msg, index)">
|
||||
<ChatMessageBubble
|
||||
v-if="shouldRenderMessage(msg)"
|
||||
v-if="shouldRenderMessage(msg) && !isDuplicateShippingExtractionMessage(messages, index)"
|
||||
:message="msg"
|
||||
:index="index"
|
||||
:message-count="messages.length"
|
||||
@@ -124,6 +207,8 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
|
||||
:leave-handlers="leaveHandlers"
|
||||
:shipping-handlers="shippingHandlers"
|
||||
:training-handlers="trainingHandlers"
|
||||
:compact-shipping-progress="compactShippingProgress"
|
||||
:attachment-summary-only="hasFollowingShippingProgressCard(messages, index)"
|
||||
@copy="emit('copy', { message: msg, index })"
|
||||
@edit="emit('edit', $event)"
|
||||
@resend="emit('resend', $event)"
|
||||
@@ -132,6 +217,7 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
|
||||
@maintenance-edit-record="emit('maintenance-edit-record', $event)"
|
||||
@maintenance-view-record-history="emit('maintenance-view-record-history', $event)"
|
||||
@maintenance-create-record-for-device="emit('maintenance-create-record-for-device', $event)"
|
||||
@open-batch-workbench="emit('open-batch-workbench')"
|
||||
/>
|
||||
<ToolRunProgressCard
|
||||
v-if="shouldRenderMessage(msg) && shouldShowToolRunProgressAfterMessage(msg, index)"
|
||||
@@ -150,7 +236,7 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
|
||||
<button
|
||||
v-if="showScrollToBottom"
|
||||
type="button"
|
||||
class="sticky bottom-4 left-1/2 z-30 flex h-10 w-10 -translate-x-1/2 items-center justify-center rounded-full border border-slate-100 bg-white text-[28px] font-light leading-none text-slate-500 shadow-[0_10px_28px_rgba(15,23,42,0.16)] transition hover:-translate-y-0.5 hover:border-slate-200 hover:text-slate-700 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-300 dark:shadow-black/30 md:bottom-6"
|
||||
class="sticky bottom-4 left-1/2 z-30 flex h-10 w-10 -translate-x-1/2 items-center justify-center rounded-full border border-subtle bg-surface text-[28px] font-light leading-none text-muted shadow-[0_10px_28px_rgba(15,23,42,0.16)] transition hover:-translate-y-0.5 hover:border-slate-200 hover:text-slate-700 dark:shadow-black/30 md:bottom-6"
|
||||
:title="$t('chat.scrollToLatest')"
|
||||
@click="emit('scroll-to-bottom')"
|
||||
>
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
/**
|
||||
* features/chat/components/ChatMobileHeader.vue
|
||||
* 移动端顶栏:Agent 名称、学习之窗、关联服务入口与 Agent 切换弹层。
|
||||
* 依赖:AgentCategoryList、ExternalSystemLinks。
|
||||
* 逻辑:关联服务 compact 按钮与右侧 Agent/历史按钮同为 h-9 圆形图标。
|
||||
* 移动端顶栏:Agent 名称、学习之窗与 Agent 切换弹层。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
import { BookOpen, History, LayoutGrid } from 'lucide-vue-next';
|
||||
import AgentCategoryList from '@/shared/components/AgentCategoryList.vue';
|
||||
import { ExternalSystemLinks } from '@/features/sso';
|
||||
import type { AgentWithCategory } from '@/shared/utils/agent-category.utils';
|
||||
|
||||
export interface ChatMobileHeaderAgent extends AgentWithCategory {}
|
||||
@@ -75,16 +72,10 @@ onBeforeUnmount(() => {
|
||||
@click="emit('open-guide')"
|
||||
>
|
||||
<BookOpen class="h-4 w-4" />
|
||||
{{ $t('chat.learningWindow') }}
|
||||
学习之窗
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex items-center gap-1">
|
||||
<ExternalSystemLinks
|
||||
compact
|
||||
:show-label="false"
|
||||
button-class="flex h-9 w-9 items-center justify-center rounded-full text-muted transition-colors hover-surface-soft"
|
||||
icon-class="h-4 w-4 shrink-0"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-9 w-9 items-center justify-center rounded-full text-muted transition-colors hover-surface-soft"
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
/**
|
||||
* features/chat/components/ChatQueryPreviewDialog.vue
|
||||
* Text2SQL 查询结果全量预览弹窗 UI。
|
||||
* 依赖:vue-i18n、useChatQueryPreview 状态。
|
||||
* 逻辑:列名匹配仍兼容服务端中文表头与本地化后的展示标签,避免切语言后丢失资产编号/图片交互。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Loader2, X } from 'lucide-vue-next';
|
||||
import type { QueryPreviewState } from '../composables/useChatQueryPreview';
|
||||
|
||||
@@ -25,32 +22,15 @@ const emit = defineEmits<{
|
||||
'open-asset-image': [payload: { assetId: string; assetName: string }];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
/** 判断列是否命中资产编号(服务端中文表头或本地化标签)。 */
|
||||
function matchesAssetIdColumn(column: string): boolean {
|
||||
return column === '资产编号' || column === t('chat.assetColumns.assetId');
|
||||
}
|
||||
|
||||
/** 判断列是否命中资产名称。 */
|
||||
function matchesAssetNameColumn(column: string): boolean {
|
||||
return column === '资产名称' || column === t('chat.assetColumns.assetName');
|
||||
}
|
||||
|
||||
/** 判断列是否命中图片。 */
|
||||
function matchesImageColumn(column: string): boolean {
|
||||
return column === '图片' || column === t('chat.assetColumns.image');
|
||||
}
|
||||
|
||||
const totalPages = computed(() =>
|
||||
Math.max(1, Math.ceil((props.state.total || 0) / (props.state.pageSize || 100))),
|
||||
);
|
||||
const assetIdColumnIndex = computed(() => props.state.columns.findIndex((column) => matchesAssetIdColumn(column)));
|
||||
const assetNameColumnIndex = computed(() => props.state.columns.findIndex((column) => matchesAssetNameColumn(column)));
|
||||
const imageColumnIndex = computed(() => props.state.columns.findIndex((column) => matchesImageColumn(column)));
|
||||
const assetIdColumnIndex = computed(() => props.state.columns.findIndex((column) => column === '资产编号'));
|
||||
const assetNameColumnIndex = computed(() => props.state.columns.findIndex((column) => column === '资产名称'));
|
||||
const imageColumnIndex = computed(() => props.state.columns.findIndex((column) => column === '图片'));
|
||||
|
||||
function isHighlightColumn(column: string): boolean {
|
||||
return matchesAssetIdColumn(column) || matchesImageColumn(column);
|
||||
return column === '资产编号' || column === '图片';
|
||||
}
|
||||
|
||||
function normalizeCellText(cell: unknown): string {
|
||||
@@ -88,16 +68,16 @@ function emitAssetAction(row: unknown[], cellIndex: number): void {
|
||||
<div class="dialog-panel flex max-h-[88vh] w-[min(96vw,1280px)] max-w-[1280px] flex-col">
|
||||
<div class="dialog-header">
|
||||
<div>
|
||||
<h3 class="section-title">{{ $t('chat.queryPreview.title') }}</h3>
|
||||
<h3 class="section-title">查询结果全量预览</h3>
|
||||
<p class="section-desc mt-1">{{ state.query || state.title }}</p>
|
||||
</div>
|
||||
<button type="button" class="btn-icon-ds" :aria-label="$t('common.close')" @click="emit('close')">
|
||||
<button type="button" class="btn-icon-ds" aria-label="关闭" @click="emit('close')">
|
||||
<X class="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="dialog-body flex min-h-0 flex-1 flex-col gap-4 border-t-0 pt-4">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-default bg-surface-soft px-4 py-3 text-sm text-secondary">
|
||||
<div>{{ $t('chat.queryPreview.summary', { total: state.total || 0, page: state.page, pages: totalPages }) }}</div>
|
||||
<div>共 {{ state.total || 0 }} 条,当前第 {{ state.page }} / {{ totalPages }} 页</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
@@ -105,7 +85,7 @@ function emitAssetAction(row: unknown[], cellIndex: number): void {
|
||||
:disabled="loading || state.page <= 1"
|
||||
@click="emit('change-page', -1)"
|
||||
>
|
||||
{{ $t('chat.queryPreview.prev') }}
|
||||
上一页
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@@ -113,7 +93,7 @@ function emitAssetAction(row: unknown[], cellIndex: number): void {
|
||||
:disabled="loading || state.page >= totalPages"
|
||||
@click="emit('change-page', 1)"
|
||||
>
|
||||
{{ $t('chat.queryPreview.next') }}
|
||||
下一页
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -125,7 +105,7 @@ function emitAssetAction(row: unknown[], cellIndex: number): void {
|
||||
<Loader2 class="h-6 w-6 animate-spin text-brand-500" />
|
||||
</div>
|
||||
<div v-else-if="!state.columns.length" class="flex h-56 items-center justify-center text-sm text-muted">
|
||||
{{ $t('chat.queryPreview.empty') }}
|
||||
暂无可预览数据
|
||||
</div>
|
||||
<table v-else class="min-w-full border-collapse text-sm">
|
||||
<thead class="sticky top-0 z-10 bg-slate-50">
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* features/chat/components/ChatSidebar.vue
|
||||
* 用途:桌面端聊天侧栏,承载 Agent 信息、会话历史、Agent 切换面板与底部用户菜单。
|
||||
* 依赖:lucide-vue-next、LocaleToggleButton、ExternalSystemLinks、AgentCategoryList、chat.types。
|
||||
@@ -105,6 +105,15 @@ const userInitial = (fallback: string) => {
|
||||
const name = String(props.currentUser?.username ?? '').trim();
|
||||
return (name || fallback).charAt(0).toUpperCase();
|
||||
};
|
||||
|
||||
/** 会话待查看采用点状提醒,颜色只表达业务处理优先级,不泄露订单或错误细节。 */
|
||||
const orderExtractionAttentionClass = (item: DisplayHistoryItem) => {
|
||||
switch (item.unseen_order_extraction_severity) {
|
||||
case 'error': return 'bg-rose-500';
|
||||
case 'warning': return 'bg-amber-500';
|
||||
default: return 'bg-sky-500';
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -196,11 +205,11 @@ const userInitial = (fallback: string) => {
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between px-4 py-2">
|
||||
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">{{ $t('chat.history') }}</span>
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.history') }}</span>
|
||||
<button
|
||||
v-if="displayHistory.length > 0"
|
||||
type="button"
|
||||
class="text-xs text-slate-400 transition-colors hover:text-slate-600 dark:hover:text-slate-200"
|
||||
class="text-xs text-muted transition-colors hover:text-slate-600 dark:hover:text-slate-200"
|
||||
@click="emit('clear-all-history')"
|
||||
>
|
||||
{{ $t('chat.clearAll') }}
|
||||
@@ -208,7 +217,7 @@ const userInitial = (fallback: string) => {
|
||||
</div>
|
||||
|
||||
<div class="scrollbar-thin flex-1 overflow-y-auto px-2">
|
||||
<div v-if="displayHistory.length === 0" class="py-8 text-center text-sm italic text-slate-400">
|
||||
<div v-if="displayHistory.length === 0" class="py-8 text-center text-sm italic text-muted">
|
||||
{{ $t('chat.noHistory') }}
|
||||
</div>
|
||||
<div v-else class="space-y-0.5">
|
||||
@@ -216,18 +225,25 @@ const userInitial = (fallback: string) => {
|
||||
v-for="item in displayHistory"
|
||||
:key="item.conversation_id"
|
||||
class="group relative flex w-full items-center justify-between rounded-lg transition-colors"
|
||||
:class="activeHistoryKey === item.conversation_id ? 'bg-brand-50 dark:bg-brand-900/20' : 'hover:bg-slate-50 dark:hover:bg-slate-800/50'"
|
||||
:class="activeHistoryKey === item.conversation_id ? 'bg-brand-50 dark:bg-brand-900/20' : 'hover-surface-soft dark:hover:bg-slate-800/50'"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="flex-1 truncate px-3 py-2.5 pr-8 text-left text-sm"
|
||||
:class="activeHistoryKey === item.conversation_id
|
||||
? 'font-medium text-brand-700 dark:text-brand-300'
|
||||
: 'text-slate-600 dark:text-slate-300'"
|
||||
: 'text-secondary '"
|
||||
@click="emit('history-select', item)"
|
||||
>
|
||||
{{ item.title || $t('chat.newChat') }}
|
||||
</button>
|
||||
<span
|
||||
v-if="item.unseen_order_extraction_count"
|
||||
class="absolute right-8 h-2 w-2 rounded-full"
|
||||
:class="orderExtractionAttentionClass(item)"
|
||||
:title="$t('chat.shippingOrderExtractionUnread', { count: item.unseen_order_extraction_count })"
|
||||
:aria-label="$t('chat.shippingOrderExtractionUnread', { count: item.unseen_order_extraction_count })"
|
||||
/>
|
||||
<button
|
||||
v-if="!item.__runId"
|
||||
type="button"
|
||||
|
||||
@@ -1,392 +1,834 @@
|
||||
/**
|
||||
|
||||
* features/chat/components/ChatViewContent.vue
|
||||
* 用途:对话页主区域,组合侧栏、发货批次进度区、消息列表、输入栏与内置浏览器。
|
||||
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingBatchProgressPanel、ShippingBatchWorkspaceDrawer、chat.context。
|
||||
* 逻辑:本文件只做页面结构编排;发货批次进度样式与任务续办交互下沉到独立面板组件。
|
||||
|
||||
* 用途:对话页主区域,组合侧栏、消息列表、输入栏、货代会话 Workflow 时间线与内置浏览器。
|
||||
|
||||
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingWorkflowTimeline、chat.context。
|
||||
|
||||
* 逻辑:本文件只做页面结构编排;货代 Chat 仅上传/进度通知,履约写操作不在本页;
|
||||
* 右侧「本次处理」由 conversationId 驱动 Workflow projection,extractionRunNo 仅作进度装饰;
|
||||
* 订单复核工作台异步分包,避免普通对话首屏拉取 PDF.js。
|
||||
|
||||
*/
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
|
||||
import { computed, defineAsyncComponent, provide, ref, watch } from 'vue';
|
||||
|
||||
import { useRoute } from 'vue-router';
|
||||
|
||||
import { Maximize2, Minimize2, Loader2 } from 'lucide-vue-next';
|
||||
|
||||
import ChatShell from '@/shared/layouts/ChatShell.vue';
|
||||
|
||||
import ChatSidebar from '@/features/chat/components/ChatSidebar.vue';
|
||||
|
||||
import ChatInputBar from '@/features/chat/components/ChatInputBar.vue';
|
||||
|
||||
import ChatMessageList from '@/features/chat/components/ChatMessageList.vue';
|
||||
|
||||
import ChatMobileHeader from '@/features/chat/components/ChatMobileHeader.vue';
|
||||
|
||||
import ChatBrowserPanel from '@/features/chat/components/ChatBrowserPanel.vue';
|
||||
import ShippingBatchProgressPanel from '@/features/chat/components/ShippingBatchProgressPanel.vue';
|
||||
import ShippingBatchWorkspaceDrawer from '@/features/chat/components/ShippingBatchWorkspaceDrawer.vue';
|
||||
|
||||
import ShippingWorkflowTimeline from '@/features/chat/components/shipping/ShippingWorkflowTimeline.vue';
|
||||
|
||||
import TrainingWorkspacePanel from '@/features/chat/components/TrainingWorkspacePanel.vue';
|
||||
|
||||
import LedgerConfigPanel from '@/features/maintenance/components/LedgerConfigPanel.vue';
|
||||
|
||||
import MaintenanceRecordManagerPanel from '@/features/maintenance/components/MaintenanceRecordManagerPanel.vue';
|
||||
|
||||
import { useChatPageContext } from '@/features/chat/composables/chat.context';
|
||||
|
||||
import { matchesTrainingAgent } from '@/features/chat/training/trainingWorkspace.utils';
|
||||
import { agentHasIntentUiProfile } from '@/shared/utils/agent-registry.utils';
|
||||
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
|
||||
import type { MaintenanceRecord } from '@/features/maintenance/types/record.types';
|
||||
|
||||
import { agentHasIntentUiProfile, resolveAgentCode, AGENT_CODE_IN_TRANSIT_TRANSFER } from '@/shared/utils/agent-registry.utils';
|
||||
|
||||
import {
|
||||
SHIPPING_WORKFLOW_KEY,
|
||||
useShippingNoticeWorkflow,
|
||||
} from '@/features/chat/shipping/useShippingNoticeWorkflow';
|
||||
|
||||
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
|
||||
|
||||
import type { MaintenanceRecord } from '@/features/maintenance/types/record.types';
|
||||
|
||||
import {
|
||||
|
||||
MAINTENANCE_PANEL_DEFAULT_WIDTH,
|
||||
|
||||
buildMaintenancePanelWidthStyle,
|
||||
|
||||
clampMaintenancePanelWidth,
|
||||
|
||||
} from '@/features/maintenance/utils/maintenance-panel-layout.utils';
|
||||
|
||||
/** 复核工作台按需分包:仅 order-review 模式加载,避免 Chat 首屏带上 PDF.js。 */
|
||||
const ShippingOrderReviewView = defineAsyncComponent(
|
||||
() => import('@/features/chat/views/ShippingOrderReviewView.vue'),
|
||||
);
|
||||
|
||||
type MaintenanceRecordPanelCommand = {
|
||||
|
||||
mode: 'list' | 'create';
|
||||
|
||||
device: MaintenanceDevice;
|
||||
|
||||
nonce: number;
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
const page = useChatPageContext();
|
||||
|
||||
const route = useRoute();
|
||||
|
||||
const shippingProcessing = useShippingNoticeWorkflow({
|
||||
// 历史会话首屏直接使用路由 ID,与聊天消息并行拉取统一进度。
|
||||
// 路由切换先于 page 历史消息回填;必须先切换 Projection,禁止短暂复用旧会话卡片。
|
||||
conversationId: () => String(route.query.conversation_id || page.conversationId || ''),
|
||||
refreshTrigger: () => page.workflowRefreshTrigger,
|
||||
});
|
||||
provide(SHIPPING_WORKFLOW_KEY, shippingProcessing);
|
||||
|
||||
/**
|
||||
* 当前货代工作台的会话身份。
|
||||
*
|
||||
* 核心逻辑:历史会话首帧时 page.conversationId 尚未由消息恢复链路回填,
|
||||
* 但 route.query.conversation_id 已是用户明确打开的会话。所有批次中心
|
||||
* 显隐、传参和会话切换边界必须使用同一个优先级,避免中心带空 ID 初始化。
|
||||
*/
|
||||
const activeShippingConversationId = computed(() => (
|
||||
String(route.query.conversation_id || page.conversationId || '').trim()
|
||||
));
|
||||
|
||||
const isOrderReviewMode = computed(() => route.query.mode === 'order-review' && typeof route.query.run_no === 'string' && route.query.run_no.length > 0);
|
||||
|
||||
const isTrainingAgentPage = computed(() => matchesTrainingAgent(page.currentAgent));
|
||||
|
||||
const isMaintenanceAgentPage = computed(() => agentHasIntentUiProfile(page.currentAgent, 'maintenance'));
|
||||
|
||||
/** 在途仓自动调拨 Agent:无消息时展示专属首页入口区(决策:补 Chat 首页入口 A 方案)。 */
|
||||
const isInTransitTransferAgent = computed(() => resolveAgentCode(page.currentAgent) === AGENT_CODE_IN_TRANSIT_TRANSFER);
|
||||
|
||||
/** 在途仓自动调拨业务流激活(来源选择/待处理等子视图)时隐藏聊天输入框,模拟业务页。 */
|
||||
const transferFlowActive = ref(false);
|
||||
watch(isInTransitTransferAgent, (isTransfer) => { if (!isTransfer) transferFlowActive.value = false; });
|
||||
|
||||
/** 批次进度工作台按需打开;关闭时不占用对话区右侧布局。 */
|
||||
const batchWorkbenchOpen = ref(false);
|
||||
|
||||
|
||||
|
||||
const showShippingWorkflowTimeline = computed(() => (
|
||||
page.isShippingNoticeAgent
|
||||
&& batchWorkbenchOpen.value
|
||||
&& Boolean(activeShippingConversationId.value)
|
||||
));
|
||||
|
||||
const compactShippingProgress = computed(() => batchWorkbenchOpen.value);
|
||||
|
||||
function openBatchWorkbench() {
|
||||
batchWorkbenchOpen.value = true;
|
||||
}
|
||||
|
||||
function closeBatchWorkbench() {
|
||||
batchWorkbenchOpen.value = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批次中心只服务于用户主动打开时所在的会话。切换历史会话或 Agent 后必须关闭,
|
||||
* 否则旧会话的右侧投影会短暂占用新会话的对话区并造成“本次处理”串批错觉。
|
||||
*/
|
||||
watch(
|
||||
() => [activeShippingConversationId.value, Number(page.currentAgentId || 0)] as const,
|
||||
(next, previous) => {
|
||||
if (!previous || next[0] === previous[0] && next[1] === previous[1]) return;
|
||||
batchWorkbenchOpen.value = false;
|
||||
},
|
||||
);
|
||||
|
||||
const embeddedIframeSrc = computed(() => {
|
||||
|
||||
const agent = page.currentAgent;
|
||||
|
||||
if (!agent) return undefined;
|
||||
|
||||
const url = agent.iframe_url;
|
||||
|
||||
return url ? String(url) : undefined;
|
||||
|
||||
});
|
||||
|
||||
const canManageMaintenance = computed(() => ['admin', 'maintenance_manager'].includes(String(page.currentUser?.role || '')));
|
||||
|
||||
const hideWelcomePanel = computed(() => false);
|
||||
|
||||
const hideWelcomeTitle = computed(() => isTrainingAgentPage.value);
|
||||
|
||||
const isTrainingWorkspaceExpanded = ref(false);
|
||||
|
||||
const maintenancePanel = ref<'ledger' | 'record' | null>(null);
|
||||
|
||||
const maintenanceEditRecord = ref<MaintenanceRecord | null>(null);
|
||||
|
||||
const maintenanceRecordPanelCommand = ref<MaintenanceRecordPanelCommand | null>(null);
|
||||
|
||||
const maintenancePanelWidth = ref(MAINTENANCE_PANEL_DEFAULT_WIDTH);
|
||||
|
||||
const isMaintenancePanelFullscreen = ref(false);
|
||||
|
||||
const isMaintenancePanelResizing = ref(false);
|
||||
|
||||
const maintenancePanelStyle = computed(() => {
|
||||
|
||||
if (isMaintenancePanelFullscreen.value) {
|
||||
|
||||
return { width: '100%', minWidth: '100%', maxWidth: '100%' };
|
||||
|
||||
}
|
||||
|
||||
return buildMaintenancePanelWidthStyle(maintenancePanelWidth.value);
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 开始拖拽设备维保右侧面板左边缘,允许管理员按表格内容临时调宽。
|
||||
|
||||
* @param event - 鼠标按下事件。
|
||||
|
||||
*/
|
||||
|
||||
const startMaintenancePanelResize = (event: MouseEvent): void => {
|
||||
|
||||
if (isMaintenancePanelFullscreen.value) return;
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
isMaintenancePanelResizing.value = true;
|
||||
|
||||
const startX = event.clientX;
|
||||
|
||||
const startWidth = maintenancePanelWidth.value;
|
||||
|
||||
const handleMove = (moveEvent: MouseEvent) => {
|
||||
|
||||
const nextWidth = startWidth + (startX - moveEvent.clientX);
|
||||
|
||||
maintenancePanelWidth.value = clampMaintenancePanelWidth(nextWidth, window.innerWidth);
|
||||
|
||||
};
|
||||
|
||||
const stopResize = () => {
|
||||
|
||||
isMaintenancePanelResizing.value = false;
|
||||
|
||||
window.removeEventListener('mousemove', handleMove);
|
||||
|
||||
window.removeEventListener('mouseup', stopResize);
|
||||
|
||||
};
|
||||
|
||||
window.addEventListener('mousemove', handleMove);
|
||||
|
||||
window.addEventListener('mouseup', stopResize);
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 打开右侧维修记录面板并进入指定记录的编辑表单。
|
||||
|
||||
* @param record - 会话结果表格中选中的维修记录。
|
||||
|
||||
*/
|
||||
|
||||
const openMaintenanceRecordEdit = (record: MaintenanceRecord): void => {
|
||||
|
||||
maintenanceEditRecord.value = record;
|
||||
|
||||
maintenanceRecordPanelCommand.value = null;
|
||||
|
||||
maintenancePanel.value = 'record';
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 鎵撳紑鍙充晶缁翠慨璁板綍鍒楄〃锛屽苟鎸夊綋鍓嶈澶囩紪鍙风瓫閫夊巻鍙茶褰曘€?
|
||||
* @param device - 浼氳瘽缁撴灉涓懡涓殑璁惧銆?
|
||||
|
||||
* 打开右侧维修记录列表,并按当前设备编号筛选历史记录。
|
||||
|
||||
* @param device - 会话结果中命中的设备。
|
||||
|
||||
*/
|
||||
|
||||
const openMaintenanceRecordHistory = (device: MaintenanceDevice): void => {
|
||||
|
||||
maintenanceEditRecord.value = null;
|
||||
|
||||
maintenanceRecordPanelCommand.value = { mode: 'list', device, nonce: Date.now() };
|
||||
|
||||
maintenancePanel.value = 'record';
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 鎵撳紑鍙充晶缁翠慨璁板綍鏂板琛ㄥ崟锛屽苟棰勫~褰撳墠璁惧缂栧彿銆?
|
||||
* @param device - 浼氳瘽缁撴灉涓懡涓殑璁惧銆?
|
||||
|
||||
* 打开右侧维修记录新增表单,并预填当前设备编号。
|
||||
|
||||
* @param device - 会话结果中命中的设备。
|
||||
|
||||
*/
|
||||
|
||||
const openMaintenanceRecordCreate = (device: MaintenanceDevice): void => {
|
||||
|
||||
maintenanceEditRecord.value = null;
|
||||
|
||||
maintenanceRecordPanelCommand.value = { mode: 'create', device, nonce: Date.now() };
|
||||
|
||||
maintenancePanel.value = 'record';
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 打开空白维修记录新增表单(不预填设备)。
|
||||
|
||||
*/
|
||||
|
||||
const openBlankMaintenanceRecordCreate = (): void => {
|
||||
|
||||
maintenanceEditRecord.value = null;
|
||||
|
||||
maintenanceRecordPanelCommand.value = null;
|
||||
|
||||
maintenancePanel.value = 'record';
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
// 切换非培训 Agent 时,重置工作区展开状态;培训 Agent 的默认展开策略交给 TrainingWorkspacePanel 按角色决定。
|
||||
|
||||
watch(() => page.currentAgentId, () => {
|
||||
|
||||
if (!isTrainingAgentPage.value) {
|
||||
|
||||
isTrainingWorkspaceExpanded.value = false;
|
||||
|
||||
}
|
||||
|
||||
maintenancePanel.value = null;
|
||||
|
||||
isMaintenancePanelFullscreen.value = false;
|
||||
|
||||
});
|
||||
|
||||
</script>
|
||||
|
||||
|
||||
|
||||
<template>
|
||||
|
||||
<ChatShell>
|
||||
|
||||
<template #overlay>
|
||||
|
||||
<div
|
||||
|
||||
v-if="page.isSidebarOpen && !page.isMobile"
|
||||
|
||||
class="fixed inset-0 z-40 bg-overlay backdrop-blur-sm transition-opacity md:hidden"
|
||||
|
||||
@click="page.isSidebarOpen = false"
|
||||
|
||||
/>
|
||||
|
||||
</template>
|
||||
|
||||
|
||||
|
||||
<template #sidebar>
|
||||
|
||||
<ChatSidebar
|
||||
|
||||
v-if="!page.isMobile"
|
||||
|
||||
v-model:collapsed="page.sidebarCollapsed"
|
||||
|
||||
v-model:agent-panel-open="page.showAgentPanel"
|
||||
|
||||
:is-open="page.isSidebarOpen"
|
||||
|
||||
:current-agent="page.currentAgent"
|
||||
|
||||
:current-agent-id="page.currentAgentId"
|
||||
|
||||
:agent-description="page.agentDescription"
|
||||
|
||||
:has-agent-guides="page.agentGuides.length > 0"
|
||||
|
||||
:display-history="page.displayHistory"
|
||||
|
||||
:active-history-key="page.activeHistoryKey"
|
||||
|
||||
:user-agents="page.userAgents"
|
||||
|
||||
:current-user="page.currentUser"
|
||||
|
||||
:applied-theme="page.appliedTheme"
|
||||
|
||||
@new-chat="page.handleSidebarNewChat"
|
||||
|
||||
@open-guide="page.openGuideModal"
|
||||
|
||||
@history-select="page.handleHistorySelect"
|
||||
|
||||
@clear-all-history="page.clearAllHistory"
|
||||
|
||||
@delete-history-item="page.deleteHistoryItem"
|
||||
|
||||
@switch-agent="page.switchToAgent"
|
||||
|
||||
@toggle-theme="page.toggleLightDark"
|
||||
|
||||
@open-feedback="page.showGeneralFeedbackDialog = true"
|
||||
|
||||
@go-workspace="page.goToWorkspace()"
|
||||
|
||||
@go-admin="page.goToAdmin"
|
||||
|
||||
@logout="page.handleLogout"
|
||||
|
||||
/>
|
||||
|
||||
</template>
|
||||
|
||||
|
||||
|
||||
<ChatMobileHeader
|
||||
|
||||
v-if="page.isMobile && page.currentAgent"
|
||||
|
||||
:agent-name="page.currentAgent?.name || 'AI'"
|
||||
|
||||
:active-agent-id="page.currentAgentId"
|
||||
|
||||
:has-agent-guides="page.agentGuides.length > 0"
|
||||
|
||||
:user-agents="page.userAgents"
|
||||
|
||||
@open-guide="page.openGuideModal"
|
||||
|
||||
@go-history="page.goToWorkspace('history')"
|
||||
|
||||
@open-agent-popover="page.loadUserAgents"
|
||||
|
||||
@switch-agent="page.switchToAgent"
|
||||
|
||||
/>
|
||||
|
||||
|
||||
|
||||
<div v-if="!page.currentAgent" class="flex flex-1 flex-col items-center justify-center space-y-4">
|
||||
|
||||
<Loader2 class="h-10 w-10 animate-spin text-brand-500" />
|
||||
|
||||
<p class="text-sm animate-pulse text-muted">{{ $t('chat.loadingAgent') }}</p>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<div v-else-if="page.currentAgent.runtime_provider === 'iframe' || page.currentAgent.conversation_mode === 'embedded'" class="relative h-full w-full flex-1">
|
||||
|
||||
<iframe
|
||||
|
||||
:src="embeddedIframeSrc"
|
||||
|
||||
class="h-full w-full border-0 bg-surface"
|
||||
|
||||
allow="microphone; camera; clipboard-read; clipboard-write"
|
||||
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<template v-else>
|
||||
<div class="flex min-h-0 min-w-0 flex-1">
|
||||
<div class="flex min-h-0 min-w-0 flex-1 flex-col">
|
||||
|
||||
<ShippingOrderReviewView v-if="isOrderReviewMode" />
|
||||
|
||||
<div v-else class="flex min-h-0 min-w-0 flex-1" :class="showShippingWorkflowTimeline ? 'shipping-workbench-layout' : ''">
|
||||
|
||||
<div class="flex min-h-0 min-w-0 flex-1 flex-col" :class="showShippingWorkflowTimeline ? 'shipping-chat-column' : ''">
|
||||
|
||||
<TrainingWorkspacePanel
|
||||
|
||||
:current-agent="page.currentAgent"
|
||||
|
||||
:current-user="page.currentUser"
|
||||
|
||||
:agent-guides="page.agentGuides"
|
||||
|
||||
:new-session-tick="page.viewId"
|
||||
|
||||
:training="page.training"
|
||||
|
||||
@open-guide="page.openGuideModal"
|
||||
|
||||
@update:expanded="isTrainingWorkspaceExpanded = $event"
|
||||
|
||||
/>
|
||||
|
||||
<ShippingBatchProgressPanel
|
||||
v-if="page.showShippingProgressWorkspace && (page.shippingBatchSummary || page.activeShippingTaskDetail)"
|
||||
:conversation-workspace="page.shippingConversationWorkspace"
|
||||
:active-batch-no="page.activeShippingBatchNo"
|
||||
:batch-summary="page.shippingBatchSummary"
|
||||
:batch-tasks="page.shippingBatchTasks"
|
||||
:active-task-detail="page.activeShippingTaskDetail"
|
||||
:workspace-open="page.shippingWorkspaceOpen"
|
||||
@switch-batch="page.switchShippingBatch"
|
||||
@toggle-workspace="page.shippingWorkspaceOpen = !page.shippingWorkspaceOpen"
|
||||
/>
|
||||
|
||||
|
||||
<ChatMessageList
|
||||
|
||||
v-show="!isTrainingWorkspaceExpanded"
|
||||
|
||||
:messages="page.messages"
|
||||
|
||||
:agent-name="page.currentAgent?.name || 'AI'"
|
||||
|
||||
:suggested-questions-style="page.suggestedQuestionsStyle"
|
||||
|
||||
:styled-sections="page.styledSuggestedQuestionSections"
|
||||
|
||||
:suggested-questions="page.agentSuggestedQuestions"
|
||||
|
||||
:show-thinking-bubble="page.shouldShowThinkingBubble"
|
||||
|
||||
:is-thinking="page.isThinking"
|
||||
|
||||
:show-chat-rating="page.showChatRating"
|
||||
|
||||
:copied-index="page.copiedIndex"
|
||||
|
||||
:is-shipping-notice-agent="page.isShippingNoticeAgent"
|
||||
|
||||
:handlers="page.messageBubbleHandlers"
|
||||
|
||||
:leave-handlers="page.leaveMessageHandlers"
|
||||
:shipping-handlers="page.shippingMappingHandlers"
|
||||
|
||||
:shipping-handlers="page.shippingMessageHandlers"
|
||||
|
||||
:training-handlers="page.trainingHandlers"
|
||||
|
||||
:should-render-message="page.shouldRenderMessage"
|
||||
|
||||
:should-show-tool-run-progress-after-message="page.shouldShowToolRunProgressAfterMessage"
|
||||
|
||||
:get-message-run-progress="page.getMessageRunProgress"
|
||||
|
||||
:get-message-run-progress-error="page.getMessageRunProgressError"
|
||||
|
||||
:is-message-run-progress-loading="page.isMessageRunProgressLoading"
|
||||
|
||||
:tool-run-progress="page.toolRunProgress"
|
||||
|
||||
:tool-run-progress-title="page.toolRunProgressTitle"
|
||||
|
||||
:show-scroll-to-bottom="page.showScrollToBottom"
|
||||
|
||||
:hide-welcome-panel="hideWelcomePanel"
|
||||
|
||||
:hide-welcome-title="hideWelcomeTitle"
|
||||
|
||||
:is-in-transit-transfer-agent="isInTransitTransferAgent"
|
||||
|
||||
:pin-messages-to-bottom="!isTrainingAgentPage"
|
||||
|
||||
:scroll-container-holder="page.scrollContainerHolder"
|
||||
|
||||
:compact-shipping-progress="compactShippingProgress"
|
||||
|
||||
@copy="page.copyToClipboard($event.message, $event.index)"
|
||||
|
||||
@edit="page.input = $event"
|
||||
|
||||
@resend="page.handleSend($event)"
|
||||
|
||||
@regenerate="page.regenerate"
|
||||
|
||||
@open-feedback="page.handleOpenFeedback($event)"
|
||||
|
||||
@select-question="page.handleSend"
|
||||
|
||||
@scroll-to-bottom="page.scrollToBottom"
|
||||
|
||||
@maintenance-edit-record="openMaintenanceRecordEdit"
|
||||
|
||||
@maintenance-view-record-history="openMaintenanceRecordHistory"
|
||||
|
||||
@maintenance-create-record-for-device="openMaintenanceRecordCreate"
|
||||
|
||||
@open-batch-workbench="openBatchWorkbench"
|
||||
|
||||
@transfer-flow-active="transferFlowActive = $event"
|
||||
|
||||
/>
|
||||
|
||||
|
||||
|
||||
<ChatInputBar
|
||||
v-show="!isTrainingWorkspaceExpanded"
|
||||
|
||||
v-show="!isTrainingWorkspaceExpanded && !transferFlowActive"
|
||||
|
||||
:key="`${page.currentAgentId}-${page.conversationId || 'draft'}-${page.messages.length}`"
|
||||
|
||||
v-model="page.input"
|
||||
v-model:selected-kb="page.selectedKb"
|
||||
v-model:procurement-review-mode="page.procurementReviewMode"
|
||||
:attachments="page.attachments"
|
||||
|
||||
:attachment-policy="page.attachmentPolicy"
|
||||
:available-kb-options="page.availableKbOptions"
|
||||
:kb-dropdown-disabled="page.kbDropdownDisabled"
|
||||
:is-thinking="page.isThinking"
|
||||
|
||||
:is-voice-recording="page.isVoiceRecording"
|
||||
|
||||
:is-voice-transcribing="page.isVoiceTranscribing"
|
||||
|
||||
:is-uploading-attachments="page.isUploadingAttachments"
|
||||
|
||||
:can-send-message="page.canSendMessage"
|
||||
|
||||
:is-shipping-notice-agent="page.isShippingNoticeAgent"
|
||||
:is-procurement-contract-agent="page.isProcurementContractAgent"
|
||||
:procurement-original-contract-name="page.procurementOriginalContractName"
|
||||
:is-maintenance-agent="isMaintenanceAgentPage"
|
||||
|
||||
:can-manage-maintenance="canManageMaintenance"
|
||||
|
||||
:can-force-create-shipping-duplicate="page.canForceCreateShippingDuplicate"
|
||||
|
||||
:shipping-suggested-prompt="page.shippingSuggestedPrompt"
|
||||
:shipping-focus-task-no="page.focusedShippingTaskNo"
|
||||
:shipping-focus-reason="page.shippingFocusReason"
|
||||
|
||||
:shipping-picker-ref-holder="page.shippingPickerRefHolder"
|
||||
|
||||
:shipping-notice-picker-ref-holder="page.shippingNoticePickerRefHolder"
|
||||
:get-kb-label="page.getKbLabel"
|
||||
@send="page.handleSend()"
|
||||
|
||||
@stop="page.stopActiveGeneration()"
|
||||
|
||||
@voice-click="page.handleVoiceFeatureClick"
|
||||
|
||||
@remove-attachment="page.removeAttachment"
|
||||
|
||||
@retry-attachment="page.retryAttachment"
|
||||
|
||||
@retry-shipping-notice-attachment="page.retryShippingNoticeAttachment"
|
||||
|
||||
@resolve-shipping-notice-duplicate="page.openShippingDuplicateDialog"
|
||||
|
||||
@select-shipping-candidate="page.setShippingCandidateSelected"
|
||||
|
||||
@resolve-shipping-candidate-duplicate="page.resolveShippingCandidateDuplicate"
|
||||
|
||||
@local-files-selected="page.handleLocalFilesSelected"
|
||||
|
||||
@add-remote-url="page.addRemoteUrlAttachment"
|
||||
|
||||
@shipping-inventory-selected="page.handleShippingInventorySelected"
|
||||
|
||||
@use-shipping-suggested-prompt="page.useShippingSuggestedPrompt"
|
||||
|
||||
@maintenance-ledger-config="maintenancePanel = 'ledger'"
|
||||
|
||||
@maintenance-create-record="openBlankMaintenanceRecordCreate"
|
||||
@clear-shipping-focus="page.clearShippingFocus"
|
||||
@procurement-original-contract-selected="page.handleProcurementOriginalContractSelected"
|
||||
@clear-procurement-original-contract="page.clearProcurementOriginalContract"
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<ShippingWorkflowTimeline
|
||||
v-if="showShippingWorkflowTimeline"
|
||||
:conversation-id="activeShippingConversationId"
|
||||
:refresh-trigger="page.workflowRefreshTrigger"
|
||||
:controller="shippingProcessing"
|
||||
|
||||
@close="closeBatchWorkbench"
|
||||
/>
|
||||
|
||||
|
||||
|
||||
<aside
|
||||
|
||||
v-if="isMaintenanceAgentPage && canManageMaintenance && maintenancePanel"
|
||||
|
||||
class="relative flex flex-col border-l border-default bg-surface shadow-[-8px_0_24px_rgba(15,23,42,0.06)]"
|
||||
|
||||
:class="[
|
||||
|
||||
isMaintenancePanelFullscreen ? 'absolute inset-y-0 right-0 z-30' : '',
|
||||
|
||||
isMaintenancePanelResizing ? 'select-none' : '',
|
||||
|
||||
]"
|
||||
|
||||
:style="maintenancePanelStyle"
|
||||
|
||||
>
|
||||
|
||||
<button
|
||||
|
||||
v-if="!isMaintenancePanelFullscreen"
|
||||
|
||||
type="button"
|
||||
|
||||
class="absolute inset-y-0 left-[-4px] z-10 w-2 cursor-col-resize bg-transparent hover:bg-brand-200/60"
|
||||
|
||||
:title="$t('maintenance.panel.resizeTitle')"
|
||||
|
||||
@mousedown="startMaintenancePanelResize"
|
||||
|
||||
/>
|
||||
|
||||
<div class="flex items-start justify-between gap-3 border-b border-default px-4 py-3">
|
||||
|
||||
<div>
|
||||
|
||||
<h2 class="text-base font-semibold text-primary">
|
||||
|
||||
{{ maintenancePanel === 'ledger' ? $t('maintenance.panel.ledgerTitle') : $t('maintenance.panel.recordTitle') }}
|
||||
|
||||
</h2>
|
||||
|
||||
<p class="mt-1 text-xs text-secondary">
|
||||
|
||||
{{ maintenancePanel === 'ledger' ? $t('maintenance.panel.ledgerSubtitle') : $t('maintenance.panel.recordSubtitle') }}
|
||||
|
||||
</p>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
|
||||
<button
|
||||
|
||||
type="button"
|
||||
|
||||
class="inline-flex h-8 w-8 items-center justify-center rounded-lg border border-default text-secondary hover:bg-surface-soft"
|
||||
|
||||
:title="isMaintenancePanelFullscreen ? $t('maintenance.panel.exitFullscreen') : $t('maintenance.panel.fullscreen')"
|
||||
|
||||
@click="isMaintenancePanelFullscreen = !isMaintenancePanelFullscreen"
|
||||
|
||||
>
|
||||
|
||||
<Minimize2 v-if="isMaintenancePanelFullscreen" class="h-4 w-4" />
|
||||
|
||||
<Maximize2 v-else class="h-4 w-4" />
|
||||
|
||||
</button>
|
||||
|
||||
<button
|
||||
|
||||
type="button"
|
||||
|
||||
class="inline-flex h-8 w-8 items-center justify-center rounded-lg border border-default text-sm text-secondary hover:bg-surface-soft"
|
||||
|
||||
:title="$t('maintenance.panel.close')"
|
||||
|
||||
@click="maintenancePanel = null"
|
||||
|
||||
>
|
||||
|
||||
×
|
||||
|
||||
</button>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="min-h-0 flex-1 overflow-auto p-4">
|
||||
|
||||
<LedgerConfigPanel v-if="maintenancePanel === 'ledger'" />
|
||||
|
||||
<MaintenanceRecordManagerPanel
|
||||
|
||||
v-else
|
||||
|
||||
:edit-record="maintenanceEditRecord"
|
||||
|
||||
:command="maintenanceRecordPanelCommand"
|
||||
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
</aside>
|
||||
|
||||
|
||||
|
||||
<ChatBrowserPanel
|
||||
|
||||
v-model:open="page.browserPanelOpen"
|
||||
|
||||
v-model:draft-url="page.browserDraftUrl"
|
||||
|
||||
:current-url="page.browserCurrentUrl"
|
||||
|
||||
:frame-key="page.browserFrameKey"
|
||||
|
||||
:panel-style="page.browserPanelStyle"
|
||||
|
||||
:is-resizing="page.isBrowserResizing"
|
||||
|
||||
@load="page.browser.loadPage"
|
||||
|
||||
@refresh="page.browser.refreshPage"
|
||||
|
||||
@open-new-tab="page.browser.openInNewTab"
|
||||
|
||||
@url-enter="page.browser.onUrlEnter"
|
||||
|
||||
@start-resize="page.browser.startResize"
|
||||
|
||||
@close="page.browser.close"
|
||||
|
||||
/>
|
||||
|
||||
<ShippingBatchWorkspaceDrawer
|
||||
v-if="page.showShippingProgressWorkspace && (page.shippingConversationWorkspace || page.shippingBatchSummary)"
|
||||
v-model:open="page.shippingWorkspaceOpen"
|
||||
:conversation-workspace="page.shippingConversationWorkspace"
|
||||
:active-batch-no="page.activeShippingBatchNo"
|
||||
:focused-task-no="page.focusedShippingTaskNo"
|
||||
:batch-summary="page.shippingBatchSummary"
|
||||
:batch-tasks="page.shippingBatchTasks"
|
||||
:active-task-detail="page.activeShippingTaskDetail"
|
||||
:retrying-pending="page.retryingShippingPendingTasks"
|
||||
:action-busy="page.shippingActionBusy"
|
||||
@switch-batch="page.switchShippingBatch"
|
||||
@focus-task="page.switchShippingFocusTask"
|
||||
@workspace-action="page.handleShippingWorkspaceAction"
|
||||
@query-shortage="page.queryShippingShortageDetails"
|
||||
@retry-pending="page.openRetryFailedConfirm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
</template>
|
||||
|
||||
</ChatShell>
|
||||
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/** 打开批次工作台后,左侧对话保留为压缩入口,右侧取得主工作区宽度。 */
|
||||
@media (min-width: 1024px) {
|
||||
.shipping-workbench-layout {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.shipping-chat-column {
|
||||
flex: 0 0 clamp(360px, 32vw, 520px);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -11,6 +11,7 @@ import ChatLeaveAgentDialog from '@/features/chat/components/ChatLeaveAgentDialo
|
||||
import ChatOALoginDialog from '@/features/chat/components/ChatOALoginDialog.vue';
|
||||
import ChatGuideModal from '@/features/chat/components/ChatGuideModal.vue';
|
||||
import ShippingNoticeDuplicateDialog from '@/features/chat/components/ShippingNoticeDuplicateDialog.vue';
|
||||
import ShippingCustomerConfirmDialog from '@/features/chat/components/ShippingCustomerConfirmDialog.vue';
|
||||
import { Check, Loader2, X } from 'lucide-vue-next';
|
||||
import { nextTick } from 'vue';
|
||||
import { useChatPageContext } from '@/features/chat/composables/chat.context';
|
||||
@@ -111,16 +112,6 @@ async function handleQueryPreviewAssetImage(assetId: string, assetName: string)
|
||||
@confirm="page.handleDeleteConfirm"
|
||||
@cancel="page.closeDeleteConfirmDialog"
|
||||
/>
|
||||
<DeleteConfirmDialog
|
||||
v-model="page.showRetryFailedConfirmDialog"
|
||||
:title="page.t('chat.shippingNoticeUi.retryFailedConfirmTitle')"
|
||||
:message="page.t('chat.shippingNoticeUi.retryFailedConfirmMessage')"
|
||||
:confirm-text="page.t('chat.shippingNoticeUi.retryFailedConfirmAction')"
|
||||
:confirm-loading="page.retryingShippingPendingTasks"
|
||||
confirm-tone="primary"
|
||||
@confirm="page.handleRetryFailedConfirm"
|
||||
@cancel="page.closeRetryFailedConfirm"
|
||||
/>
|
||||
<div
|
||||
v-if="page.shippingToastMessage"
|
||||
class="pointer-events-none fixed inset-x-0 top-20 z-[145] flex justify-center px-4"
|
||||
@@ -155,4 +146,12 @@ async function handleQueryPreviewAssetImage(assetId: string, assetName: string)
|
||||
@remove="() => void page.removeShippingDuplicateDialogAttachment?.()"
|
||||
@cancel="page.closeShippingDuplicateDialog?.()"
|
||||
/>
|
||||
<ShippingCustomerConfirmDialog
|
||||
:open="!!page.showShippingCustomerDialog"
|
||||
:options="page.shippingCustomerOptions || []"
|
||||
:loading="!!page.shippingCustomerLoading"
|
||||
@close="page.closeShippingCustomerDialog?.()"
|
||||
@search="(query) => void page.searchShippingCustomers?.(query)"
|
||||
@confirm="(customerId) => void page.confirmShippingCustomer?.(customerId)"
|
||||
/>
|
||||
</template>
|
||||
@@ -1,239 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/chat/components/ShippingBatchProgressPanel.vue
|
||||
* 用途:发货通知聊天顶部轻量批次状态条,展示当前批次进度与工作台入口。
|
||||
* 依赖:shipping.api.types、vue-i18n、批次 retry API。
|
||||
* 逻辑:生成式执行摘要由聊天消息流承载;本组件只提供固定状态 chrome 和明确范围的批次操作。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { AlertTriangle, List, RefreshCw } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { retryWorkspaceShippingBatchPending } from '@/features/chat/api/shipping.api';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { resolveShippingWorkflowSteps } from '@/features/chat/shipping';
|
||||
import type {
|
||||
ShippingBatchSummary,
|
||||
ShippingConversationWorkspace,
|
||||
ShippingTaskDetail,
|
||||
ShippingTaskSummary,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
|
||||
const props = defineProps<{
|
||||
conversationWorkspace: ShippingConversationWorkspace | null;
|
||||
activeBatchNo: string;
|
||||
batchSummary: ShippingBatchSummary | null;
|
||||
batchTasks: ShippingTaskSummary[];
|
||||
activeTaskDetail: ShippingTaskDetail | null;
|
||||
workspaceOpen: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'switch-batch': [batchNo: string];
|
||||
'toggle-workspace': [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
const retryingPending = ref(false);
|
||||
|
||||
const COMPLETED_PROCESS_STATUSES = new Set(['uploaded', 'completed', 'closed']);
|
||||
const FAILED_PROCESS_STATUSES = new Set(['rejected', 'upload_failed']);
|
||||
const workspaceBatches = computed(() => props.conversationWorkspace?.batches || []);
|
||||
const activeBatchNo = computed(() =>
|
||||
String(props.activeBatchNo || props.batchSummary?.batch_no || workspaceBatches.value[0]?.batch_no || '').trim(),
|
||||
);
|
||||
const focusedTaskNo = computed(() =>
|
||||
String(
|
||||
props.activeTaskDetail?.task_no
|
||||
|| props.batchSummary?.current_focus_task_no
|
||||
|| props.batchSummary?.process_summary?.current_task_no
|
||||
|| '',
|
||||
).trim(),
|
||||
);
|
||||
|
||||
const processSummary = computed(() => {
|
||||
const summary = props.batchSummary?.process_summary || null;
|
||||
const total = Number(summary?.total || props.batchSummary?.file_count || props.batchTasks.length || 0);
|
||||
const completed = Number(
|
||||
summary?.completed
|
||||
|| props.batchTasks.filter((task) => COMPLETED_PROCESS_STATUSES.has(String(task.process_status || '').trim())).length
|
||||
|| 0,
|
||||
);
|
||||
const runningFallback = props.batchTasks.some(
|
||||
(task) => !COMPLETED_PROCESS_STATUSES.has(String(task.process_status || '').trim()),
|
||||
) ? 1 : 0;
|
||||
const running = Number(summary?.running || runningFallback || 0);
|
||||
const taskAbnormal = props.batchTasks.filter((task) => {
|
||||
const status = String(task.process_status || '').trim();
|
||||
return FAILED_PROCESS_STATUSES.has(status)
|
||||
|| task.upload_status === 'failed'
|
||||
|| Boolean(task.review_status || task.pending_human_reason);
|
||||
}).length;
|
||||
const summaryAbnormal = Number(summary?.failed || 0) + Number((summary as { needs_human?: number })?.needs_human || 0);
|
||||
const abnormal = Math.max(taskAbnormal, summaryAbnormal);
|
||||
const pending = Math.max(0, Number(summary?.pending ?? (total - completed - running - abnormal)));
|
||||
return { total, completed, running, pending, abnormal };
|
||||
});
|
||||
|
||||
const abnormalCount = computed(() => processSummary.value.abnormal);
|
||||
|
||||
const progressPercent = computed(() =>
|
||||
processSummary.value.total
|
||||
? Math.round((processSummary.value.completed / processSummary.value.total) * 100)
|
||||
: 0,
|
||||
);
|
||||
|
||||
const executionStateMeta = computed(() => {
|
||||
if (abnormalCount.value > 0) {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.needsIntervention'),
|
||||
className: 'border-amber-100 bg-amber-50 text-amber-700',
|
||||
};
|
||||
}
|
||||
if (processSummary.value.running > 0 || processSummary.value.pending > 0) {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.runningState'),
|
||||
className: 'border-sky-100 bg-sky-50 text-brand-700',
|
||||
};
|
||||
}
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.completedState'),
|
||||
className: 'border-emerald-100 bg-emerald-50 text-emerald-700',
|
||||
};
|
||||
});
|
||||
|
||||
const activeTaskSteps = computed(() => (
|
||||
resolveShippingWorkflowSteps(props.activeTaskDetail)
|
||||
));
|
||||
const activeStepIndex = computed(() => {
|
||||
const index = activeTaskSteps.value.findIndex((step) => step.status === 'current' || step.status === 'blocked');
|
||||
return index >= 0 ? index : Math.max(0, activeTaskSteps.value.length - 1);
|
||||
});
|
||||
const activeStepLabel = computed(() => {
|
||||
const step = activeTaskSteps.value[activeStepIndex.value];
|
||||
return step ? t('chat.shippingNoticeUi.stepHeadline', {
|
||||
current: activeStepIndex.value + 1,
|
||||
total: activeTaskSteps.value.length,
|
||||
label: step.label.startsWith('chat.') ? t(step.label) : step.label,
|
||||
}) : '--';
|
||||
});
|
||||
|
||||
const blockingMeta = computed(() => {
|
||||
const task = props.activeTaskDetail;
|
||||
if (!task) return null;
|
||||
const reason = String(task.pending_human_reason || '').trim();
|
||||
const reviewStatus = String(task.review_status || '').trim();
|
||||
const processStatus = String(task.process_status || '').trim();
|
||||
if (processStatus === 'upload_failed' || task.upload_status === 'failed') {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.blockedUploadRetryable'),
|
||||
className: 'border-rose-200 bg-rose-50 text-rose-700',
|
||||
};
|
||||
}
|
||||
if (reason === 'shortage' || reason === 'shortage_review' || reviewStatus === 'shortage_review') {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.blockedShortage'),
|
||||
className: 'border-amber-200 bg-amber-50 text-amber-700',
|
||||
};
|
||||
}
|
||||
if (reason === 'low_confidence' || reviewStatus === 'parse_review') {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.blockedParseReview'),
|
||||
className: 'border-amber-200 bg-amber-50 text-amber-700',
|
||||
};
|
||||
}
|
||||
if (reason || reviewStatus) {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.blockedWaitingHuman'),
|
||||
className: 'border-amber-200 bg-amber-50 text-amber-700',
|
||||
};
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const handleRetryPending = async () => {
|
||||
const batchNo = String(props.batchSummary?.batch_no || '').trim();
|
||||
if (!batchNo || retryingPending.value) return;
|
||||
retryingPending.value = true;
|
||||
try {
|
||||
const result = await retryWorkspaceShippingBatchPending(batchNo);
|
||||
msg.success(result.message || t('chat.shippingNoticeUi.retryPendingDone'));
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('chat.shippingNoticeUi.retryFailed'));
|
||||
} finally {
|
||||
retryingPending.value = false;
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="w-full px-3 pt-3 md:px-8 md:pr-10">
|
||||
<div
|
||||
class="mx-auto w-full max-w-4xl rounded-2xl border border-default bg-gradient-to-r from-sky-50 via-white to-emerald-50 px-6 py-4 shadow-sm"
|
||||
>
|
||||
<div class="flex flex-wrap items-start justify-between gap-3">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex flex-wrap items-center gap-2 text-xs text-slate-500">
|
||||
<span class="font-mono font-semibold text-brand-700">{{ activeBatchNo || '--' }}</span>
|
||||
<span>{{ t('chat.shippingNoticeUi.fileCount') }} {{ processSummary.total }}</span>
|
||||
<span>{{ t('chat.shippingNoticeUi.completedCount') }} {{ processSummary.completed }}</span>
|
||||
<span>{{ t('chat.shippingNoticeUi.runningCount') }} {{ processSummary.running }}</span>
|
||||
<span>{{ t('chat.shippingNoticeUi.pendingCount') }} {{ processSummary.pending }}</span>
|
||||
<span>{{ t('chat.shippingNoticeUi.needsIntervention') }} {{ abnormalCount }}</span>
|
||||
<span
|
||||
class="rounded-full border px-2 py-0.5 text-[11px] font-semibold"
|
||||
:class="executionStateMeta.className"
|
||||
>
|
||||
{{ executionStateMeta.text }}
|
||||
</span>
|
||||
<span
|
||||
v-if="blockingMeta"
|
||||
class="inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-semibold"
|
||||
:class="blockingMeta.className"
|
||||
>
|
||||
<AlertTriangle class="h-3 w-3" />
|
||||
{{ blockingMeta.text }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-secondary">
|
||||
<span>
|
||||
<span class="text-muted">{{ t('chat.shippingNoticeUi.currentFocus') }}</span>
|
||||
<span class="font-mono font-semibold text-primary">{{ focusedTaskNo || '--' }}</span>
|
||||
</span>
|
||||
<span>
|
||||
<span class="text-muted">{{ t('chat.shippingNoticeUi.currentStepLabel') }}:</span>
|
||||
<span class="font-medium text-primary">{{ activeStepLabel }}</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-2 h-1.5 max-w-md overflow-hidden rounded-full bg-slate-200">
|
||||
<div
|
||||
class="h-full rounded-full bg-brand-500 transition-all"
|
||||
:style="{ width: `${progressPercent}%` }"
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
<button
|
||||
v-if="batchSummary?.batch_no"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-lg border border-default bg-white/80 px-2.5 py-1 text-xs font-medium text-secondary transition hover:border-brand-300 hover:bg-brand-50 hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
:disabled="retryingPending"
|
||||
@click="handleRetryPending"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" :class="retryingPending ? 'animate-spin' : ''" />
|
||||
{{ retryingPending ? t('chat.shippingNoticeUi.retrying') : t('chat.shippingNoticeUi.retryPendingTasks') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-lg border border-default bg-white/80 px-2.5 py-1 text-xs font-medium text-secondary transition hover:border-brand-300 hover:bg-brand-50 hover:text-brand-700"
|
||||
@click="emit('toggle-workspace')"
|
||||
>
|
||||
<List class="h-3.5 w-3.5" />
|
||||
{{ workspaceOpen ? t('chat.shippingNoticeUi.collapseTaskList') : t('chat.shippingNoticeUi.expandTaskList') }}
|
||||
<span class="text-brand-600">{{ workspaceOpen ? '▲' : '▼' }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -1,783 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/chat/components/ShippingBatchWorkspaceDrawer.vue
|
||||
* 用途:发货通知 Agent 的右侧批次工作台抽屉,承载多批次切换、任务筛选、步骤诊断与统一动作入口。
|
||||
* 依赖:shippingStepper、shippingMenu、shipping.api.types、vue-i18n、lucide-vue-next。
|
||||
* 逻辑:上游传入会话级 workspace 与当前批次任务;本组件只渲染后端 `ui_state.action_buttons` 和查看类辅助入口。
|
||||
* 解析阶段诊断优先展示 `ui_state.summary.issues` 完整问题列表;「重试所有失败」仅 emit `retry-pending`,由父级打开确认弹窗后再调用 useChatShipping 执行。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { RefreshCw, Target, X } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
resolveShippingWorkflowSteps,
|
||||
type ShippingWorkflowStepItem,
|
||||
} from '@/features/chat/shipping';
|
||||
import { sanitizeShippingRuntimeStatusText } from '@/features/chat/shipping/shippingText';
|
||||
import { reportShippingDebugEvent } from '@/features/chat/shipping/shippingDebugReporter';
|
||||
import {
|
||||
isShippingWorkspaceTerminalTask,
|
||||
resolveShippingWorkspaceActionButtons,
|
||||
} from '@/features/chat/shipping/shippingWorkspaceActions';
|
||||
import { hasShortageLines } from '@/features/chat/shipping/shippingShortageDetails';
|
||||
import type {
|
||||
ShippingBatchSummary,
|
||||
ShippingConversationWorkspace,
|
||||
ShippingChatAction,
|
||||
ShippingTaskDetail,
|
||||
ShippingTaskSummary,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
conversationWorkspace: ShippingConversationWorkspace | null;
|
||||
activeBatchNo: string;
|
||||
focusedTaskNo: string;
|
||||
batchSummary: ShippingBatchSummary | null;
|
||||
batchTasks: ShippingTaskSummary[];
|
||||
activeTaskDetail: ShippingTaskDetail | null;
|
||||
retryingPending?: boolean;
|
||||
actionBusy?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean];
|
||||
'switch-batch': [batchNo: string];
|
||||
'focus-task': [taskNo: string];
|
||||
'workspace-action': [taskNo: string, action: ShippingChatAction];
|
||||
'query-shortage': [taskNo: string];
|
||||
'retry-pending': [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const activeFilter = ref<'all' | 'abnormal' | 'waitingHuman' | 'resumable' | 'completed'>('all');
|
||||
|
||||
// #region debug-point A:workspace-click
|
||||
const reportRetryRpaDebug = (hypothesisId: string, msg: string, data: Record<string, unknown>) =>
|
||||
reportShippingDebugEvent('ShippingBatchWorkspaceDrawer.vue', hypothesisId, msg, data);
|
||||
// #endregion
|
||||
|
||||
const workspaceBatches = computed(() => props.conversationWorkspace?.batches || []);
|
||||
const activeBatchNo = computed(() =>
|
||||
String(props.activeBatchNo || props.batchSummary?.batch_no || workspaceBatches.value[0]?.batch_no || '').trim(),
|
||||
);
|
||||
|
||||
const isFailedTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
task.upload_status === 'failed' || String(task.process_status || '').trim() === 'upload_failed';
|
||||
|
||||
const isCompletedTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
isShippingWorkspaceTerminalTask(task);
|
||||
|
||||
const isAbnormalTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
!isCompletedTask(task)
|
||||
&& (isFailedTask(task)
|
||||
|| Boolean(task.review_status || task.pending_human_reason)
|
||||
|| String(task.process_status || '').trim() === 'waiting_inventory');
|
||||
|
||||
const isWaitingHumanTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
!isCompletedTask(task) && !isFailedTask(task) && Boolean(task.review_status || task.pending_human_reason);
|
||||
|
||||
const isResumableTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
!isCompletedTask(task) && !isWaitingHumanTask(task) && (
|
||||
isFailedTask(task)
|
||||
|| ['created', 'parsed', 'inventory_ready', 'matched', 'waiting_upload'].includes(String(task.process_status || '').trim())
|
||||
);
|
||||
|
||||
const resolveWorkspaceActionButtons = (task: ShippingTaskSummary | ShippingTaskDetail): ShippingChatAction[] =>
|
||||
resolveShippingWorkspaceActionButtons(task);
|
||||
|
||||
const rpaRuntimeMode = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
String(task.rpa_runtime?.mode || '').trim().toLowerCase();
|
||||
|
||||
const rpaRuntimeLabel = (task: ShippingTaskSummary | ShippingTaskDetail) => {
|
||||
const mode = rpaRuntimeMode(task);
|
||||
if (mode === 'mock') return t('chat.shippingNoticeUi.rpaModeMock');
|
||||
if (mode === 'browser') return t('chat.shippingNoticeUi.rpaModeBrowser');
|
||||
return String(task.rpa_runtime?.label || '').trim() || t('chat.shippingNoticeUi.rpaModeUnknown');
|
||||
};
|
||||
|
||||
const rpaRuntimeBadgeClass = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
rpaRuntimeMode(task) === 'mock'
|
||||
? 'border-amber-200 bg-amber-50 text-amber-700'
|
||||
: 'border-emerald-200 bg-emerald-50 text-emerald-700';
|
||||
|
||||
/**
|
||||
* 渲染工作台任务卡中的辅助动作按钮样式。
|
||||
* 核心逻辑:把“聚焦当前任务 / 查询缺口明细”降级成轻量辅助入口,避免与后端主业务动作抢视觉权重。
|
||||
* @param kind - 当前辅助动作的视觉类型
|
||||
* @returns 对应的 Tailwind class 字符串
|
||||
*/
|
||||
const resolveWorkspaceAssistButtonClass = (kind: 'focus' | 'shortage') => {
|
||||
if (kind === 'shortage') {
|
||||
return 'inline-flex min-h-[32px] items-center justify-center gap-1.5 rounded-lg border border-amber-200 bg-amber-50/90 px-2.5 py-1.5 text-xs font-semibold text-amber-700 transition-all hover:border-amber-300 hover:bg-amber-100 disabled:cursor-not-allowed disabled:opacity-60';
|
||||
}
|
||||
return 'inline-flex min-h-[32px] items-center justify-center gap-1.5 rounded-lg border border-slate-200 bg-slate-50/90 px-2.5 py-1.5 text-xs font-semibold text-slate-700 transition-all hover:border-brand-200 hover:bg-white hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-60';
|
||||
};
|
||||
|
||||
/**
|
||||
* 渲染工作台任务卡中的业务动作按钮样式。
|
||||
* 核心逻辑:主动作在右侧工作台里使用更强的卡片式按钮承载,优先突出 primary,secondary/danger 维持次级密度。
|
||||
* @param action - 后端返回的结构化动作按钮
|
||||
* @param total - 当前任务业务动作总数,用于控制按钮跨列布局
|
||||
* @returns 对应的 Tailwind class 字符串
|
||||
*/
|
||||
const resolveWorkspaceTaskActionClass = (action: ShippingChatAction, total: number) => {
|
||||
const spanClass = action.variant === 'primary' || total === 1 ? 'col-span-2' : 'col-span-1';
|
||||
if (action.variant === 'primary') {
|
||||
return `${spanClass} inline-flex min-h-[36px] items-center justify-center rounded-lg bg-gradient-to-r from-brand-600 to-sky-500 px-3 py-1.5 text-sm font-semibold text-white shadow-sm transition-all hover:-translate-y-[1px] hover:from-brand-700 hover:to-sky-600 disabled:cursor-not-allowed disabled:opacity-60`;
|
||||
}
|
||||
if (action.variant === 'danger') {
|
||||
return `${spanClass} inline-flex min-h-[36px] items-center justify-center rounded-lg border border-rose-200 bg-rose-50 px-3 py-1.5 text-sm font-semibold text-rose-700 transition-all hover:border-rose-300 hover:bg-rose-100 disabled:cursor-not-allowed disabled:opacity-60`;
|
||||
}
|
||||
return `${spanClass} inline-flex min-h-[36px] items-center justify-center rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-sm font-semibold text-slate-700 shadow-sm transition-all hover:border-brand-200 hover:bg-brand-50 hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-60`;
|
||||
};
|
||||
|
||||
// #region debug-point A:workspace-action
|
||||
const emitWorkspaceAction = (
|
||||
task: ShippingTaskSummary | ShippingTaskDetail,
|
||||
action: ShippingChatAction,
|
||||
) => {
|
||||
void reportRetryRpaDebug('A', 'workspace action clicked', {
|
||||
actionId: String(action.id || ''),
|
||||
actionBusy: Boolean(props.actionBusy),
|
||||
taskNo: String(task.task_no || '').trim().toUpperCase(),
|
||||
processStatus: String(task.process_status || ''),
|
||||
pendingHumanReason: String(task.pending_human_reason || ''),
|
||||
focusedTaskNo: String(props.focusedTaskNo || props.activeTaskDetail?.task_no || '').trim().toUpperCase(),
|
||||
});
|
||||
emit('workspace-action', task.task_no, action);
|
||||
};
|
||||
// #endregion
|
||||
|
||||
// #region debug-point A:workspace-busy-state
|
||||
watch(
|
||||
() => [Boolean(props.actionBusy), String(props.focusedTaskNo || ''), String(props.activeTaskDetail?.task_no || '')].join('|'),
|
||||
() => {
|
||||
void reportRetryRpaDebug('A', 'workspace busy state snapshot', {
|
||||
actionBusy: Boolean(props.actionBusy),
|
||||
focusedTaskNo: String(props.focusedTaskNo || '').trim().toUpperCase(),
|
||||
activeDetailTaskNo: String(props.activeTaskDetail?.task_no || '').trim().toUpperCase(),
|
||||
activeDetailStatus: String(props.activeTaskDetail?.process_status || ''),
|
||||
activeDetailPendingReason: String(props.activeTaskDetail?.pending_human_reason || ''),
|
||||
open: props.open,
|
||||
});
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
// #endregion
|
||||
|
||||
const batchAbnormalCount = (batch: ShippingBatchSummary) => {
|
||||
const summary = batch.process_summary || {};
|
||||
return Number(summary.failed || 0) + Number((summary as { needs_human?: number }).needs_human || 0);
|
||||
};
|
||||
|
||||
const batchCompletedCount = (batch: ShippingBatchSummary) =>
|
||||
Number(batch.process_summary?.completed || 0);
|
||||
|
||||
const batchTotalCount = (batch: ShippingBatchSummary) =>
|
||||
Number(batch.process_summary?.total || batch.file_count || 0);
|
||||
|
||||
const taskCounts = computed(() => {
|
||||
const tasks = props.batchTasks || [];
|
||||
const completed = tasks.filter(isCompletedTask).length;
|
||||
const abnormal = tasks.filter(isAbnormalTask).length;
|
||||
const waitingHuman = tasks.filter(isWaitingHumanTask).length;
|
||||
const resumable = tasks.filter(isResumableTask).length;
|
||||
return {
|
||||
total: tasks.length,
|
||||
abnormal,
|
||||
waitingHuman,
|
||||
resumable,
|
||||
completed,
|
||||
};
|
||||
});
|
||||
|
||||
const filteredTasks = computed(() => {
|
||||
const tasks = props.batchTasks || [];
|
||||
if (activeFilter.value === 'abnormal') return tasks.filter(isAbnormalTask);
|
||||
if (activeFilter.value === 'waitingHuman') return tasks.filter(isWaitingHumanTask);
|
||||
if (activeFilter.value === 'resumable') return tasks.filter(isResumableTask);
|
||||
if (activeFilter.value === 'completed') return tasks.filter(isCompletedTask);
|
||||
return tasks;
|
||||
});
|
||||
|
||||
const isCurrentTask = (taskNo?: string | null) =>
|
||||
String(taskNo || '').trim().toUpperCase() === String(props.focusedTaskNo || props.activeTaskDetail?.task_no || '').trim().toUpperCase();
|
||||
|
||||
const resolveTaskStateMeta = (task: ShippingTaskSummary | ShippingTaskDetail) => {
|
||||
if (isCompletedTask(task)) {
|
||||
return { text: t('chat.shippingNoticeUi.completedState'), className: 'border-emerald-100 bg-emerald-50 text-emerald-700' };
|
||||
}
|
||||
if (isFailedTask(task)) {
|
||||
return { text: t('chat.shippingNoticeUi.status.uploadFailed'), className: 'border-rose-100 bg-rose-50 text-rose-700' };
|
||||
}
|
||||
if (isAbnormalTask(task)) {
|
||||
return { text: t('chat.shippingNoticeUi.pendingState'), className: 'border-amber-100 bg-amber-50 text-amber-700' };
|
||||
}
|
||||
return { text: t('chat.shippingNoticeUi.runningState'), className: 'border-sky-100 bg-sky-50 text-brand-700' };
|
||||
};
|
||||
|
||||
const taskWorkflowSteps = (task: ShippingTaskSummary | ShippingTaskDetail) => (
|
||||
resolveShippingWorkflowSteps(task)
|
||||
);
|
||||
|
||||
const taskStepNumber = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
resolveActiveStep(taskWorkflowSteps(task)) + 1;
|
||||
|
||||
const taskStepHeadline = (task: ShippingTaskSummary | ShippingTaskDetail) => {
|
||||
const steps = taskWorkflowSteps(task);
|
||||
const index = resolveActiveStep(steps);
|
||||
const step = steps[index];
|
||||
return step ? t('chat.shippingNoticeUi.stepHeadline', {
|
||||
current: index + 1,
|
||||
total: steps.length,
|
||||
label: step.label.startsWith('chat.') ? t(step.label) : step.label,
|
||||
}) : t('chat.shippingNoticeUi.stepFraction', { current: index + 1, total: steps.length });
|
||||
};
|
||||
|
||||
const currentStepProgress = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
task.step_payload?.current_step_progress || null;
|
||||
|
||||
/**
|
||||
* 规范化工作台中的运行态诊断文案。
|
||||
* 核心逻辑:右侧工作台属于业务操作面,不展示“第几次重试”这类过程计数,只保留状态与建议。
|
||||
* @param text - 后端返回的 summary / progress / error 文本
|
||||
* @returns 面向业务用户的净化后文案
|
||||
*/
|
||||
const sanitizeDiagnosisCopy = (text: string | null | undefined) =>
|
||||
sanitizeShippingRuntimeStatusText(String(text || '').trim());
|
||||
|
||||
/**
|
||||
* 读取任务诊断卡要展示的全部问题列表。
|
||||
* 核心逻辑:优先消费后端 `ui_state.summary.issues`(解析阶段已汇总库存源+warnings);
|
||||
* 若缺失则回退到单一 error_message,保证旧数据仍有可读文案。
|
||||
*/
|
||||
const resolveTaskDiagnosisIssues = (task: ShippingTaskSummary | ShippingTaskDetail): string[] => {
|
||||
const uiIssues = task.ui_state?.summary?.issues;
|
||||
if (Array.isArray(uiIssues) && uiIssues.length) {
|
||||
return uiIssues
|
||||
.map((item) => sanitizeDiagnosisCopy(item))
|
||||
.filter(Boolean);
|
||||
}
|
||||
const fallback = sanitizeDiagnosisCopy(task.ui_state?.summary?.error_message || task.error_message);
|
||||
return fallback ? [fallback] : [];
|
||||
};
|
||||
|
||||
/**
|
||||
* 解析右侧工作台诊断标题/建议/问题列表。
|
||||
* 核心逻辑:解析阶段若 issues 多于 1 条,使用「发现问题」标题并列出全部条目,避免只显示库存源一条。
|
||||
*/
|
||||
const resolveTaskDiagnosis = (task: ShippingTaskSummary | ShippingTaskDetail) => {
|
||||
const uiSummary = task.ui_state?.summary;
|
||||
const issues = resolveTaskDiagnosisIssues(task);
|
||||
if (uiSummary?.title || uiSummary?.message || uiSummary?.error_message || issues.length) {
|
||||
const multiIssue = issues.length > 1;
|
||||
return {
|
||||
title: multiIssue
|
||||
? t('chat.shippingNoticeUi.diagnosisIssuesTitle', { count: issues.length })
|
||||
: (
|
||||
sanitizeDiagnosisCopy(issues[0] || uiSummary?.error_message || uiSummary?.title)
|
||||
|| t('chat.shippingNoticeUi.diagnosisStepWaitingTitle', { step: taskStepNumber(task) })
|
||||
),
|
||||
advice: multiIssue
|
||||
? t('chat.shippingNoticeUi.diagnosisIssuesAdvice')
|
||||
: (sanitizeDiagnosisCopy(uiSummary?.message) || t('chat.shippingNoticeUi.diagnosisStepWaitingAdvice')),
|
||||
issues: multiIssue ? issues : [],
|
||||
};
|
||||
}
|
||||
const reason = String(task.pending_human_reason || '').trim();
|
||||
const reviewStatus = String(task.review_status || '').trim();
|
||||
const processStatus = String(task.process_status || '').trim();
|
||||
const explicitError = String(task.error_message || '').trim();
|
||||
const progress = currentStepProgress(task);
|
||||
const progressMessage = String(progress?.message || '').trim();
|
||||
const progressDetail = String(progress?.detail || '').trim();
|
||||
const step = taskStepNumber(task);
|
||||
|
||||
if (isCompletedTask(task)) {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisCompletedTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisCompletedAdvice'),
|
||||
};
|
||||
}
|
||||
if (progressMessage && reason === 'rpa_pending') {
|
||||
return {
|
||||
title: sanitizeDiagnosisCopy(progressMessage),
|
||||
advice: sanitizeDiagnosisCopy(progressDetail) || t('chat.shippingNoticeUi.diagnosisInventoryRpaAdvice'),
|
||||
};
|
||||
}
|
||||
if (explicitError) {
|
||||
return {
|
||||
title: sanitizeDiagnosisCopy(explicitError),
|
||||
advice: sanitizeDiagnosisCopy(progressDetail) || t('chat.shippingNoticeUi.diagnosisAdviceRetryOrFocus'),
|
||||
};
|
||||
}
|
||||
if (progressMessage && (isAbnormalTask(task) || progress?.status === 'needs_human')) {
|
||||
return {
|
||||
title: sanitizeDiagnosisCopy(progressMessage),
|
||||
advice: sanitizeDiagnosisCopy(progressDetail) || t('chat.shippingNoticeUi.diagnosisStepWaitingAdvice'),
|
||||
};
|
||||
}
|
||||
if (isFailedTask(task) || reason === 'upload_rpa_failed') {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisUploadFailedTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisUploadFailedAdvice'),
|
||||
};
|
||||
}
|
||||
if (reason === 'shortage' || reason === 'shortage_review' || reviewStatus === 'shortage_review') {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisShortageTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisShortageAdvice'),
|
||||
};
|
||||
}
|
||||
if (reason === 'rpa_exhausted' || reason === 'rpa_pending' || reason === 'inv_unavail') {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisInventoryRpaTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisInventoryRpaAdvice'),
|
||||
};
|
||||
}
|
||||
if (reason === 'align_review' || reviewStatus === 'align_review') {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisAlignReviewTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisAlignReviewAdvice'),
|
||||
};
|
||||
}
|
||||
if (reason === 'low_confidence' || reviewStatus === 'parse_review') {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisParseReviewTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisParseReviewAdvice'),
|
||||
};
|
||||
}
|
||||
if (reason === 'rsv_required' || reviewStatus === 'rsv_required') {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisReservationRequiredTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisReservationRequiredAdvice'),
|
||||
};
|
||||
}
|
||||
if (reason === 'inventory_source_unresolved') {
|
||||
const resolution = (task as ShippingTaskDetail).inventory_source_resolution;
|
||||
const status = resolution && typeof resolution === 'object'
|
||||
? String((resolution as { status?: unknown }).status || '').trim()
|
||||
: '';
|
||||
const isAmbiguous = status === 'ambiguous';
|
||||
return {
|
||||
title: t(isAmbiguous
|
||||
? 'chat.shippingNoticeUi.diagnosisInventorySourceAmbiguousTitle'
|
||||
: 'chat.shippingNoticeUi.diagnosisInventorySourceTitle'),
|
||||
advice: t(isAmbiguous
|
||||
? 'chat.shippingNoticeUi.diagnosisInventorySourceAmbiguousAdvice'
|
||||
: 'chat.shippingNoticeUi.diagnosisInventorySourceAdvice'),
|
||||
};
|
||||
}
|
||||
if (reason === 'map_infer' || processStatus === 'waiting_inventory') {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisInventoryWaitingTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisInventoryWaitingAdvice'),
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisStepWaitingTitle', { step }),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisStepWaitingAdvice'),
|
||||
};
|
||||
};
|
||||
|
||||
const resolveSuggestedAction = (task: ShippingTaskSummary | ShippingTaskDetail) => {
|
||||
const actions = resolveWorkspaceActionButtons(task);
|
||||
if (actions.length) {
|
||||
return actions.map((action) => action.label).join(' / ');
|
||||
}
|
||||
const reason = String(task.pending_human_reason || '').trim();
|
||||
const reviewStatus = String(task.review_status || '').trim();
|
||||
if (hasShortageLines(task) || reason === 'shortage' || reviewStatus === 'shortage_review') {
|
||||
return t('chat.shippingNoticeUi.suggestShortageActions');
|
||||
}
|
||||
if (reason === 'align_review' || reviewStatus === 'align_review') {
|
||||
return t('chat.shippingNoticeUi.suggestConfirmMapping');
|
||||
}
|
||||
if (reason === 'low_confidence' || reviewStatus === 'parse_review') {
|
||||
return t('chat.shippingNoticeUi.suggestReviewParse');
|
||||
}
|
||||
if (reason === 'inventory_source_unresolved') {
|
||||
return t('chat.shippingNoticeUi.suggestConfirmInventorySource');
|
||||
}
|
||||
if (isFailedTask(task)) {
|
||||
return t('chat.shippingNoticeUi.suggestRetryStep');
|
||||
}
|
||||
if (isCompletedTask(task)) {
|
||||
return t('chat.shippingNoticeUi.suggestViewOnly');
|
||||
}
|
||||
return t('chat.shippingNoticeUi.suggestContinue');
|
||||
};
|
||||
|
||||
const resolveActiveStep = (steps: Array<ShippingWorkflowStepItem | { status: string }>) => {
|
||||
const activeIndex = steps.findIndex((step) => step.status === 'current' || step.status === 'blocked');
|
||||
return activeIndex >= 0 ? activeIndex : Math.max(0, steps.length - 1);
|
||||
};
|
||||
|
||||
const handleSwitchBatch = (batchNo: string) => {
|
||||
if (!batchNo || batchNo === activeBatchNo.value) return;
|
||||
activeFilter.value = 'all';
|
||||
emit('switch-batch', batchNo);
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside
|
||||
v-if="open"
|
||||
class="hidden h-full w-[520px] shrink-0 flex-col border-l border-default bg-surface shadow-[-12px_0_40px_rgba(15,23,42,0.08)] lg:flex"
|
||||
>
|
||||
<header class="flex h-[92px] shrink-0 items-center justify-between border-b border-default px-6">
|
||||
<div>
|
||||
<div class="flex items-center gap-2 text-lg font-bold text-primary">
|
||||
<span class="grid h-5 w-5 grid-cols-2 gap-0.5 text-brand-500">
|
||||
<span class="rounded-sm bg-current"></span>
|
||||
<span class="rounded-sm border border-current"></span>
|
||||
<span class="rounded-sm border border-current"></span>
|
||||
<span class="rounded-sm bg-current"></span>
|
||||
</span>
|
||||
{{ t('chat.shippingNoticeUi.batchWorkspaceTitle') }}
|
||||
</div>
|
||||
<p class="mt-1 text-[11px] text-muted">{{ t('chat.shippingNoticeUi.batchWorkspaceSubtitle') }}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-9 w-9 items-center justify-center rounded-full text-muted transition hover:bg-surface-soft hover:text-primary"
|
||||
@click="emit('update:open', false)"
|
||||
>
|
||||
<X class="h-5 w-5" />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div class="border-b border-default px-6 py-5">
|
||||
<div class="flex gap-3 overflow-x-auto pb-1">
|
||||
<button
|
||||
v-for="batch in workspaceBatches"
|
||||
:key="batch.batch_no"
|
||||
type="button"
|
||||
class="relative w-44 shrink-0 overflow-hidden rounded-xl border p-3 text-left transition-colors"
|
||||
:class="batch.batch_no === activeBatchNo ? 'border-brand-300 bg-surface shadow-sm ring-1 ring-brand-100' : 'border-default bg-transparent hover:bg-surface-soft'"
|
||||
@click="handleSwitchBatch(batch.batch_no)"
|
||||
>
|
||||
<div
|
||||
v-if="batch.batch_no === activeBatchNo"
|
||||
class="absolute left-0 top-0 h-1 w-full bg-brand-500"
|
||||
></div>
|
||||
<div class="mb-1 truncate font-mono text-xs font-bold text-primary">{{ batch.batch_no }}</div>
|
||||
<div class="text-[10px] font-medium text-muted">
|
||||
{{
|
||||
batchAbnormalCount(batch) > 0
|
||||
? t('chat.shippingNoticeUi.batchTabAbnormal', { completed: batchCompletedCount(batch), abnormal: batchAbnormalCount(batch) })
|
||||
: t('chat.shippingNoticeUi.batchTabNormal', { total: batchTotalCount(batch) })
|
||||
}}
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex-1 overflow-y-auto px-6 py-6">
|
||||
<section class="rounded-lg border border-default bg-surface p-4 shadow-sm">
|
||||
<h3 class="text-sm font-bold text-primary">{{ t('chat.shippingNoticeUi.taskQueueTitle') }}</h3>
|
||||
<p class="mt-1 text-xs leading-5 text-muted">{{ t('chat.shippingNoticeUi.taskQueueHint') }}</p>
|
||||
<div class="mt-4">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex w-full items-center justify-center gap-2 rounded-lg border border-default bg-white py-2 text-xs font-medium text-secondary transition hover:border-brand-300 hover:bg-brand-50 hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
:disabled="retryingPending || actionBusy"
|
||||
@click="emit('retry-pending')"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" :class="retryingPending ? 'animate-spin' : ''" />
|
||||
{{ retryingPending ? t('chat.shippingNoticeUi.retrying') : t('chat.shippingNoticeUi.retryFailedTasks') }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="mt-3 rounded-lg border border-indigo-100 bg-indigo-50 p-3 text-xs leading-5 text-indigo-900/80">
|
||||
{{ t('chat.shippingNoticeUi.batchActionSafetyNotice') }}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="mt-6">
|
||||
<div class="mb-3 flex items-center justify-between gap-3">
|
||||
<h3 class="text-sm font-bold text-primary">
|
||||
{{ t('chat.shippingNoticeUi.taskDetailCount', { count: filteredTasks.length }) }}
|
||||
</h3>
|
||||
<div class="flex flex-wrap rounded-lg bg-slate-100 p-1 text-xs">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded px-3 py-1 transition-colors"
|
||||
:class="activeFilter === 'all' ? 'bg-white text-primary shadow-sm' : 'text-muted hover:text-secondary'"
|
||||
@click="activeFilter = 'all'"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.filterAll') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded px-3 py-1 transition-colors"
|
||||
:class="activeFilter === 'abnormal' ? 'bg-white text-primary shadow-sm' : 'text-muted hover:text-secondary'"
|
||||
@click="activeFilter = 'abnormal'"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.filterAbnormal', { count: taskCounts.abnormal }) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded px-3 py-1 transition-colors"
|
||||
:class="activeFilter === 'waitingHuman' ? 'bg-white text-primary shadow-sm' : 'text-muted hover:text-secondary'"
|
||||
@click="activeFilter = 'waitingHuman'"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.filterWaitingHuman', { count: taskCounts.waitingHuman }) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded px-3 py-1 transition-colors"
|
||||
:class="activeFilter === 'resumable' ? 'bg-white text-primary shadow-sm' : 'text-muted hover:text-secondary'"
|
||||
@click="activeFilter = 'resumable'"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.filterResumable', { count: taskCounts.resumable }) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded px-3 py-1 transition-colors"
|
||||
:class="activeFilter === 'completed' ? 'bg-white text-primary shadow-sm' : 'text-muted hover:text-secondary'"
|
||||
@click="activeFilter = 'completed'"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.filterCompleted', { count: taskCounts.completed }) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="!filteredTasks.length" class="py-10 text-center text-sm text-muted">
|
||||
{{ t('chat.shippingNoticeUi.emptyFilteredTasks') }}
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-3">
|
||||
<article
|
||||
v-for="task in filteredTasks"
|
||||
:key="task.task_no"
|
||||
class="relative overflow-hidden rounded-lg border bg-white p-3 shadow-sm transition-colors"
|
||||
:class="[
|
||||
isFailedTask(task) ? 'border-rose-100' : isAbnormalTask(task) ? 'border-amber-100' : 'border-default',
|
||||
isCurrentTask(task.task_no) ? 'ring-1 ring-brand-200' : '',
|
||||
]"
|
||||
>
|
||||
<div
|
||||
class="absolute left-0 top-0 h-full w-1"
|
||||
:class="isFailedTask(task) ? 'bg-rose-500' : isAbnormalTask(task) ? 'bg-amber-500' : 'bg-emerald-500'"
|
||||
></div>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="truncate font-mono text-sm font-bold text-primary">{{ task.task_no }}</div>
|
||||
<div class="mt-0.5 truncate text-xs text-muted">
|
||||
{{ task.source_file_name || task.customer_name || t('chat.shippingNoticeUi.currentNotice') }}
|
||||
</div>
|
||||
<div class="mt-1 flex flex-wrap items-center gap-1.5 text-xs font-medium text-secondary">
|
||||
<span>{{ taskStepHeadline(task) }}</span>
|
||||
<span
|
||||
v-if="task.rpa_runtime"
|
||||
class="rounded border px-1.5 py-0.5 text-[10px] font-bold leading-none"
|
||||
:class="rpaRuntimeBadgeClass(task)"
|
||||
>
|
||||
{{ rpaRuntimeLabel(task) }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<span class="rounded border px-2 py-1 text-[10px] font-bold" :class="resolveTaskStateMeta(task).className">
|
||||
{{ resolveTaskStateMeta(task).text }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="my-3">
|
||||
<div class="scheme-stepper">
|
||||
<template v-for="(step, index) in taskWorkflowSteps(task)" :key="step.id">
|
||||
<div
|
||||
class="scheme-step-node"
|
||||
:class="{
|
||||
done: step.status === 'completed',
|
||||
active: step.status === 'current',
|
||||
blocked: step.status === 'blocked',
|
||||
}"
|
||||
>
|
||||
<div class="scheme-step-dot">
|
||||
<span v-if="step.status === 'completed'">✓</span>
|
||||
<X v-else-if="step.status === 'blocked' && isFailedTask(task)" class="h-3 w-3" />
|
||||
<span v-else-if="step.status === 'blocked'">!</span>
|
||||
<span v-else>{{ index + 1 }}</span>
|
||||
</div>
|
||||
<div class="scheme-step-label">{{ step.label.startsWith('chat.') ? t(step.label) : step.label }}</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-for="diagnosis in [resolveTaskDiagnosis(task)]"
|
||||
:key="`${task.task_no}-diagnosis`"
|
||||
class="mb-2 rounded-lg border p-2.5 text-xs font-medium leading-5"
|
||||
:class="isFailedTask(task) ? 'border-rose-100 bg-rose-50 text-rose-700' : isAbnormalTask(task) ? 'border-amber-100 bg-amber-50 text-amber-700' : 'border-emerald-100 bg-emerald-50 text-emerald-700'"
|
||||
>
|
||||
<div class="font-semibold">{{ diagnosis.title }}</div>
|
||||
<ul
|
||||
v-if="(diagnosis.issues || []).length"
|
||||
class="mt-1.5 list-disc space-y-1 pl-4 font-normal text-slate-700"
|
||||
>
|
||||
<li
|
||||
v-for="(issue, issueIndex) in diagnosis.issues"
|
||||
:key="`${task.task_no}-issue-${issueIndex}`"
|
||||
>
|
||||
{{ issue }}
|
||||
</li>
|
||||
</ul>
|
||||
<div class="mt-1 font-normal text-slate-600">{{ diagnosis.advice }}</div>
|
||||
</div>
|
||||
<div v-if="!resolveWorkspaceActionButtons(task).length" class="mb-3 text-xs leading-5 text-muted">
|
||||
<span class="font-semibold text-secondary">{{ t('chat.shippingNoticeUi.suggestedAction') }}</span>
|
||||
{{ resolveSuggestedAction(task) }}
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-1.5">
|
||||
<button
|
||||
v-if="hasShortageLines(task)"
|
||||
type="button"
|
||||
:class="`${resolveWorkspaceAssistButtonClass('shortage')} col-span-2`"
|
||||
:disabled="actionBusy"
|
||||
@click="emit('query-shortage', task.task_no)"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.queryShortageDetails') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
:class="`${resolveWorkspaceAssistButtonClass('focus')} col-span-2`"
|
||||
:disabled="actionBusy"
|
||||
@click="emit('focus-task', task.task_no)"
|
||||
>
|
||||
<Target class="h-3.5 w-3.5" />
|
||||
{{ isCompletedTask(task) ? t('chat.shippingNoticeUi.viewDetail') : t('chat.shippingNoticeUi.switchCurrentTask') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="resolveWorkspaceActionButtons(task).length" class="mt-2 rounded-xl border border-slate-200/80 bg-slate-50/70 p-2">
|
||||
<div class="mb-1.5 px-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-slate-500">
|
||||
{{ t('chat.shippingNoticeActionsHint') }}
|
||||
</div>
|
||||
<div class="grid grid-cols-2 gap-1.5">
|
||||
<button
|
||||
v-for="action in resolveWorkspaceActionButtons(task)"
|
||||
:key="`${task.task_no}-workspace-action-${action.id}-${action.source_code || ''}`"
|
||||
type="button"
|
||||
:class="resolveWorkspaceTaskActionClass(action, resolveWorkspaceActionButtons(task).length)"
|
||||
:disabled="actionBusy"
|
||||
@click="emitWorkspaceAction(task, action)"
|
||||
>
|
||||
{{ action.label }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-[90] bg-slate-900/30 backdrop-blur-sm lg:hidden"
|
||||
@click="emit('update:open', false)"
|
||||
>
|
||||
<aside
|
||||
class="ml-auto flex h-full w-[min(92vw,520px)] flex-col border-l border-default bg-surface shadow-2xl"
|
||||
@click.stop
|
||||
>
|
||||
<header class="flex h-16 shrink-0 items-center justify-between border-b border-default px-4">
|
||||
<div class="font-bold text-primary">{{ t('chat.shippingNoticeUi.batchWorkspaceTitle') }}</div>
|
||||
<button type="button" class="rounded-full p-2 text-muted hover:bg-surface-soft" @click="emit('update:open', false)">
|
||||
<X class="h-5 w-5" />
|
||||
</button>
|
||||
</header>
|
||||
<div class="flex-1 overflow-y-auto p-4 text-sm text-muted">
|
||||
{{ t('chat.shippingNoticeUi.mobileWorkspaceHint') }}
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.scheme-stepper {
|
||||
display: flex;
|
||||
overflow-x: auto;
|
||||
padding-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.scheme-step-node {
|
||||
position: relative;
|
||||
flex: 1;
|
||||
min-width: 52px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.scheme-step-node:not(:last-child)::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
left: calc(50% + 11px);
|
||||
width: calc(100% - 22px);
|
||||
height: 2px;
|
||||
background: #e2e8f0;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.scheme-step-node.done:not(:last-child)::after {
|
||||
background: #0284c7;
|
||||
}
|
||||
|
||||
.scheme-step-node.active:not(:last-child)::after {
|
||||
background: linear-gradient(90deg, #0284c7 50%, #e2e8f0 50%);
|
||||
}
|
||||
|
||||
.scheme-step-dot {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
margin: 0 auto 0.25rem;
|
||||
border: 2px solid #e2e8f0;
|
||||
border-radius: 9999px;
|
||||
background: #fff;
|
||||
color: #64748b;
|
||||
font-size: 0.55rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.scheme-step-node.done .scheme-step-dot {
|
||||
border-color: #0284c7;
|
||||
background: #0284c7;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.scheme-step-node.active .scheme-step-dot {
|
||||
border-color: #0284c7;
|
||||
box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.18);
|
||||
color: #0284c7;
|
||||
}
|
||||
|
||||
.scheme-step-node.blocked .scheme-step-dot {
|
||||
border-color: #f59e0b;
|
||||
background: #fff;
|
||||
color: #f59e0b;
|
||||
box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.18);
|
||||
}
|
||||
|
||||
.scheme-step-node.blocked .scheme-step-label {
|
||||
color: #d97706;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.scheme-step-label {
|
||||
color: #64748b;
|
||||
font-size: 0.58rem;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.scheme-step-node.active .scheme-step-label {
|
||||
color: #0284c7;
|
||||
font-weight: 600;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,41 @@
|
||||
<!--
|
||||
features/chat/components/ShippingCustomerConfirmDialog.vue
|
||||
用途:在 customer_review 检查点搜索并确认启用标准客户。
|
||||
依赖:ShippingCustomerOption、vue-i18n。
|
||||
逻辑:父 composable 提供选项与提交动作;本组件不解析邮件客户名,也不创建客户资料。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingCustomerOption } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{ open: boolean; options: ShippingCustomerOption[]; loading: boolean }>();
|
||||
const emit = defineEmits<{ close: []; search: [query: string]; confirm: [customerId: number] }>();
|
||||
const { t } = useI18n();
|
||||
const query = ref('');
|
||||
const selectedId = ref<number | null>(null);
|
||||
|
||||
/** 每次打开对话框时清空上次选择。 */
|
||||
watch(() => props.open, (open) => {
|
||||
if (open) {
|
||||
query.value = '';
|
||||
selectedId.value = null;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="open" class="admin-modal-overlay animate-fade-in items-center z-[170]">
|
||||
<div class="admin-modal-panel max-w-xl max-h-[90vh] scale-100">
|
||||
<div class="px-6 py-5 border-b border-subtle"><h3 class="section-title">{{ t('chat.shippingCustomer.title') }}</h3><p class="section-desc mt-1">{{ t('chat.shippingCustomer.subtitle') }}</p></div>
|
||||
<div class="px-6 py-5 space-y-4 overflow-y-auto">
|
||||
<div class="flex gap-2"><input v-model="query" class="input-field text-sm" :placeholder="t('chat.shippingCustomer.searchPlaceholder')" @keyup.enter="emit('search', query)" /><button type="button" class="btn-ghost" @click="emit('search', query)">{{ t('chat.shippingCustomer.search') }}</button></div>
|
||||
<div class="space-y-2 max-h-80 overflow-y-auto">
|
||||
<label v-for="customer in options" :key="customer.id" class="flex items-center gap-3 rounded-xl border border-default p-3 cursor-pointer hover:border-brand-300"><input v-model="selectedId" type="radio" :value="customer.id" /><span class="flex-1"><span class="font-medium text-primary">{{ customer.standard_name }}</span><span class="ml-2 font-mono text-xs text-muted">{{ customer.short_code }}</span></span></label>
|
||||
<div v-if="!loading && !options.length" class="text-sm text-muted py-8 text-center">{{ t('chat.shippingCustomer.empty') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="admin-modal-footer"><button type="button" class="btn-ghost" @click="emit('close')">{{ t('common.cancel') }}</button><button type="button" class="btn-primary" :disabled="!selectedId || loading" @click="selectedId && emit('confirm', selectedId)">{{ t('chat.shippingCustomer.confirm') }}</button></div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,57 @@
|
||||
<!--
|
||||
features/chat/components/ShippingFieldEvidencePanel.vue
|
||||
用途:只读展开订单字段级原文证据(Document + quote)。
|
||||
依赖:shipping.api.types、vue-i18n。
|
||||
逻辑:由 ShippingTaskParsedResultCard / Candidate 审核区传入 evidence;本组件不推导业务结论。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingFieldEvidenceItem } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
evidence?: ShippingFieldEvidenceItem[] | null;
|
||||
compact?: boolean;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const items = computed(() =>
|
||||
(props.evidence || []).filter((item) => item && typeof item === 'object'),
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="items.length" class="space-y-2">
|
||||
<div class="text-[11px] font-semibold uppercase tracking-wide text-muted">
|
||||
{{ t('chat.shippingParsedResult.evidenceTitle') }}
|
||||
</div>
|
||||
<details
|
||||
v-for="(item, index) in items"
|
||||
:key="`${item.field || 'field'}-${item.document_id || index}`"
|
||||
class="rounded-lg border border-default bg-surface px-2.5 py-2 text-xs"
|
||||
:open="!compact && index === 0"
|
||||
>
|
||||
<summary class="cursor-pointer font-medium text-secondary">
|
||||
<span class="font-mono">{{ item.field || t('chat.shippingParsedResult.unknownField') }}</span>
|
||||
<span v-if="item.reservation_id" class="ml-2 text-muted">{{ item.reservation_id }}</span>
|
||||
</summary>
|
||||
<div class="mt-2 space-y-1 text-muted">
|
||||
<div v-if="item.document_id != null">
|
||||
{{ t('chat.shippingParsedResult.documentId', { id: item.document_id }) }}
|
||||
</div>
|
||||
<div v-if="item.page_no != null">
|
||||
{{ t('chat.shippingParsedResult.pageNumber', { page: item.page_no }) }}
|
||||
<span v-if="item.table_id" class="ml-1 font-mono">{{ item.table_id }}</span>
|
||||
<span v-if="item.cell_id" class="ml-1 font-mono">{{ item.cell_id }}</span>
|
||||
</div>
|
||||
<blockquote
|
||||
v-if="item.quote"
|
||||
class="rounded border border-default bg-surface-soft px-2 py-1.5 font-mono text-[11px] leading-5 text-secondary"
|
||||
>
|
||||
{{ item.quote }}
|
||||
</blockquote>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
</template>
|
||||
@@ -126,6 +126,18 @@ const statusLabel = computed(() => {
|
||||
<div v-if="match.matchedFields?.length" class="mt-1 text-xs text-muted">
|
||||
{{ t('chat.shippingNoticeDuplicateMatchFields', { fields: match.matchedFields.join(', ') }) }}
|
||||
</div>
|
||||
<div v-if="match.reservationDifferences?.length" class="mt-2 space-y-1 border-t border-default pt-2 text-xs">
|
||||
<p class="font-medium text-amber-700">{{ t('chat.shippingNoticeRevisionDifferences') }}</p>
|
||||
<p v-for="difference in match.reservationDifferences" :key="difference.reservationId">
|
||||
{{ t('chat.shippingNoticeRevisionDifference', {
|
||||
reservation: difference.reservationId,
|
||||
previousPart: difference.previous.partNumber,
|
||||
previousQty: difference.previous.qty,
|
||||
proposedPart: difference.proposed.partNumber,
|
||||
proposedQty: difference.proposed.qty,
|
||||
}) }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 space-y-2">
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
<!--
|
||||
features/chat/components/ShippingTaskFieldConflictPanel.vue
|
||||
用途:展示并解决任务级订单字段冲突(keep / take incoming)。
|
||||
依赖:shipping.api.resolveWorkspaceShippingFieldConflict、vue-i18n、useMessage。
|
||||
逻辑:由 ShippingTaskParsedResultCard 挂载;解决成功后 emit refreshed 让父级重拉 Task Detail。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { resolveWorkspaceShippingFieldConflict } from '@/features/chat/api/shipping.api';
|
||||
import type { ShippingFieldConflict } from '@/features/chat/types/shipping.api.types';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
|
||||
const props = defineProps<{
|
||||
taskNo: string;
|
||||
conflicts?: ShippingFieldConflict[] | null;
|
||||
orderDataVersion?: number | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
refreshed: [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
const resolvingId = ref<number | null>(null);
|
||||
|
||||
const openConflicts = computed(() =>
|
||||
(props.conflicts || []).filter((item) => String(item.status || '') === 'open'),
|
||||
);
|
||||
|
||||
/**
|
||||
* 解决单条冲突。
|
||||
* 核心逻辑:携带 conflict_version 与 order_data_version;409 时提示刷新。
|
||||
*/
|
||||
async function resolveConflict(
|
||||
conflict: ShippingFieldConflict,
|
||||
resolution: 'keep_existing' | 'take_incoming',
|
||||
) {
|
||||
if (!props.taskNo || resolvingId.value != null || props.orderDataVersion == null) return;
|
||||
resolvingId.value = conflict.id;
|
||||
try {
|
||||
await resolveWorkspaceShippingFieldConflict(props.taskNo, conflict.id, {
|
||||
resolution,
|
||||
expectedConflictVersion: conflict.conflict_version,
|
||||
expectedOrderDataVersion: props.orderDataVersion,
|
||||
evidence: { evidence_type: 'manual_input', reason: '工作台人工解决字段冲突' },
|
||||
reason: '工作台人工解决字段冲突',
|
||||
idempotencyKey: `conflict-${conflict.id}-${resolution}-${conflict.conflict_version}`,
|
||||
});
|
||||
msg.success(t('chat.shippingFieldConflict.resolveSuccess'));
|
||||
emit('refreshed');
|
||||
} catch (err) {
|
||||
msg.error(err instanceof Error ? err.message : t('chat.shippingFieldConflict.resolveFailed'));
|
||||
} finally {
|
||||
resolvingId.value = null;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="openConflicts.length"
|
||||
class="space-y-2 rounded-lg border border-rose-200 bg-rose-50/80 px-2.5 py-2"
|
||||
>
|
||||
<div class="text-[11px] font-semibold text-rose-900">
|
||||
{{ t('chat.shippingFieldConflict.title', { count: openConflicts.length }) }}
|
||||
</div>
|
||||
<div class="text-[11px] leading-5 text-rose-800">
|
||||
{{ t('chat.shippingFieldConflict.hint') }}
|
||||
</div>
|
||||
<ul class="space-y-2">
|
||||
<li
|
||||
v-for="conflict in openConflicts"
|
||||
:key="conflict.id"
|
||||
class="rounded-md border border-rose-200 bg-white/90 px-2.5 py-2 text-[11px]"
|
||||
>
|
||||
<div class="font-medium text-rose-900">
|
||||
<span v-if="conflict.position != null">#{{ Number(conflict.position) + 1 }} · </span>
|
||||
<span class="font-mono">{{ conflict.field_name }}</span>
|
||||
</div>
|
||||
<div class="mt-1 grid gap-1 text-secondary sm:grid-cols-2">
|
||||
<div>
|
||||
<span class="text-muted">{{ t('chat.shippingFieldConflict.existing') }}:</span>
|
||||
<span class="ml-1 font-mono">{{ conflict.existing_value || '—' }}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-muted">{{ t('chat.shippingFieldConflict.incoming') }}:</span>
|
||||
<span class="ml-1 font-mono">{{ conflict.incoming_value || '—' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-2 flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-default bg-surface px-2 py-1 text-[11px] font-medium hover-surface-soft disabled:opacity-50"
|
||||
:disabled="resolvingId != null"
|
||||
@click="resolveConflict(conflict, 'keep_existing')"
|
||||
>
|
||||
{{ t('chat.shippingFieldConflict.keepExisting') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-rose-300 bg-rose-100 px-2 py-1 text-[11px] font-medium text-rose-900 hover:bg-rose-200 disabled:opacity-50"
|
||||
:disabled="resolvingId != null"
|
||||
@click="resolveConflict(conflict, 'take_incoming')"
|
||||
>
|
||||
{{ t('chat.shippingFieldConflict.takeIncoming') }}
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,243 @@
|
||||
<!--
|
||||
features/chat/components/ShippingTaskParsedResultCard.vue
|
||||
用途:任务详情持久只读展示订单解析行、流转门禁、字段冲突与来源证据。
|
||||
依赖:ShippingFieldEvidencePanel、ShippingTaskFieldConflictPanel、shipping.api.types、vue-i18n。
|
||||
逻辑:Drawer / ShippingNoticeView 共用;只解释后端 Gate,不自行推导可继续状态。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import ShippingFieldEvidencePanel from '@/features/chat/components/ShippingFieldEvidencePanel.vue';
|
||||
import ShippingTaskFieldConflictPanel from '@/features/chat/components/ShippingTaskFieldConflictPanel.vue';
|
||||
import type {
|
||||
ShippingFieldConflict,
|
||||
ShippingNoticeLine,
|
||||
ShippingOrderDisplayField,
|
||||
ShippingParseIssue,
|
||||
ShippingParseValidation,
|
||||
ShippingProcessFieldGate,
|
||||
ShippingSourceCandidateProjection,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
taskNo?: string | null;
|
||||
poNumber?: string | null;
|
||||
lines?: ShippingNoticeLine[] | null;
|
||||
orderHeader?: Record<string, unknown> | null;
|
||||
orderHeaderFields?: ShippingOrderDisplayField[] | null;
|
||||
orderLineFields?: ShippingOrderDisplayField[] | null;
|
||||
parseValidation?: ShippingParseValidation | null;
|
||||
processFieldGate?: ShippingProcessFieldGate | null;
|
||||
sourceCandidate?: ShippingSourceCandidateProjection | null;
|
||||
fieldConflicts?: ShippingFieldConflict[] | null;
|
||||
orderDataVersion?: number | null;
|
||||
/** 阻断时默认展开;非阻断可折叠。 */
|
||||
defaultExpanded?: boolean;
|
||||
compact?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
refreshed: [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const expanded = ref(true);
|
||||
|
||||
watch(
|
||||
() => props.defaultExpanded,
|
||||
(value) => {
|
||||
if (typeof value === 'boolean') expanded.value = value;
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
const orderLines = computed(() => (props.lines || []).filter((line) => line && typeof line === 'object'));
|
||||
const orderedHeaderFields = computed(() => [...(props.orderHeaderFields || [])].sort((a, b) => a.sequence - b.sequence));
|
||||
const orderedLineFields = computed(() => [...(props.orderLineFields || [])].sort((a, b) => a.sequence - b.sequence));
|
||||
|
||||
const gateIssues = computed(() => {
|
||||
const fromGate = Array.isArray(props.processFieldGate?.issues) ? props.processFieldGate?.issues : [];
|
||||
const fromValidation = Array.isArray(props.parseValidation?.issues) ? props.parseValidation?.issues : [];
|
||||
return [...fromGate, ...fromValidation] as ShippingParseIssue[];
|
||||
});
|
||||
|
||||
const missingFields = computed(() => {
|
||||
const gateMissing = Array.isArray(props.processFieldGate?.missing_fields)
|
||||
? props.processFieldGate?.missing_fields || []
|
||||
: [];
|
||||
const candidateMissing = Array.isArray(props.sourceCandidate?.missing_fields)
|
||||
? props.sourceCandidate?.missing_fields || []
|
||||
: [];
|
||||
return Array.from(new Set([...gateMissing, ...candidateMissing].map((item) => String(item)).filter(Boolean)));
|
||||
});
|
||||
|
||||
const adjudicationDecisions = computed(() => (
|
||||
props.sourceCandidate?.field_adjudication?.decisions || []
|
||||
).filter((item) => item && typeof item === 'object'));
|
||||
|
||||
const hasBlocking = computed(() =>
|
||||
gateIssues.value.some((issue) => String(issue.severity || '') === 'blocking')
|
||||
|| missingFields.value.includes('reservation_id')
|
||||
|| String(props.processFieldGate?.status || '') === 'needs_enrichment'
|
||||
|| String(props.parseValidation?.status || '') === 'needs_review'
|
||||
|| (props.fieldConflicts || []).some((item) => String(item.status || '') === 'open'),
|
||||
);
|
||||
|
||||
const statusLabel = computed(() => {
|
||||
if (hasBlocking.value) return t('chat.shippingParsedResult.statusBlocked');
|
||||
if (orderLines.value.length) return t('chat.shippingParsedResult.statusReady');
|
||||
return t('chat.shippingParsedResult.statusEmpty');
|
||||
});
|
||||
|
||||
const displayValue = (value: unknown) => {
|
||||
const text = String(value ?? '').trim();
|
||||
return text || '—';
|
||||
};
|
||||
|
||||
/**
|
||||
* 将门禁 reason 映射为用户可读文案。
|
||||
* @param reason - 后端 issue.reason
|
||||
*/
|
||||
function issueReasonLabel(reason?: string | null): string {
|
||||
const key = String(reason || '').trim();
|
||||
if (key === 'missing') return t('chat.shippingParsedResult.issueMissing');
|
||||
if (key === 'invalid_format') return t('chat.shippingParsedResult.issueInvalid');
|
||||
if (key === 'source_conflict' || key === 'field_conflict') return t('chat.shippingParsedResult.issueConflict');
|
||||
if (key === 'value_corrected') return t('chat.shippingParsedResult.issueCorrected');
|
||||
if (key === 'plain_text_table_has_no_cell_evidence') return t('chat.shippingParsedResult.issueNoCellEvidence');
|
||||
if (key === 'layout_table_needs_review') return t('chat.shippingParsedResult.issueLayoutNeedsReview');
|
||||
if (key === 'layout_candidate_document_mismatch') return t('chat.shippingParsedResult.issueLayoutDocumentMismatch');
|
||||
return key || t('chat.shippingParsedResult.issueUnknown');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
class="rounded-xl border p-3 text-xs"
|
||||
:class="hasBlocking
|
||||
? 'border-amber-200 bg-amber-50/70'
|
||||
: 'border-default bg-surface-soft/80'"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-start justify-between gap-2 text-left"
|
||||
@click="expanded = !expanded"
|
||||
>
|
||||
<div>
|
||||
<div class="text-[11px] font-bold uppercase tracking-wider text-muted">
|
||||
{{ t('chat.shippingParsedResult.title') }}
|
||||
</div>
|
||||
<div v-if="taskNo" class="mt-0.5 font-mono text-[11px] text-secondary">{{ taskNo }}</div>
|
||||
<div v-if="poNumber" class="mt-0.5 text-muted">PO {{ poNumber }}</div>
|
||||
</div>
|
||||
<span
|
||||
class="rounded-full px-2 py-0.5 text-[10px] font-semibold"
|
||||
:class="hasBlocking ? 'bg-amber-100 text-amber-800' : 'bg-emerald-100 text-emerald-700'"
|
||||
>
|
||||
{{ statusLabel }}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<div v-if="expanded" class="mt-3 space-y-3">
|
||||
<div class="rounded-lg border border-slate-200/80 bg-white/80 px-2.5 py-2 text-[11px] leading-5 text-secondary">
|
||||
{{ t('chat.shippingParsedResult.impactHint') }}
|
||||
</div>
|
||||
|
||||
<ShippingTaskFieldConflictPanel
|
||||
v-if="taskNo"
|
||||
:task-no="taskNo"
|
||||
:conflicts="fieldConflicts || []"
|
||||
:order-data-version="orderDataVersion"
|
||||
@refreshed="emit('refreshed')"
|
||||
/>
|
||||
|
||||
<div v-if="orderedHeaderFields.length" class="rounded-xl border border-default bg-white/90 p-2.5">
|
||||
<div class="mb-2 font-semibold text-secondary">{{ t('chat.shippingParsedResult.orderInformation') }}</div>
|
||||
<dl class="grid gap-2 sm:grid-cols-2">
|
||||
<div v-for="field in orderedHeaderFields" :key="field.field_code" class="rounded-lg bg-surface-soft px-2.5 py-2">
|
||||
<dt class="text-[10px] text-muted">{{ field.display_name }}</dt>
|
||||
<dd class="mt-0.5 break-words text-xs text-primary">{{ displayValue(orderHeader?.[field.field_code]) }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
|
||||
<div v-if="missingFields.length" class="space-y-1">
|
||||
<div class="font-semibold text-amber-800">{{ t('chat.shippingParsedResult.missingFields') }}</div>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
<span
|
||||
v-for="field in missingFields"
|
||||
:key="field"
|
||||
class="rounded border border-amber-200 bg-amber-100 px-1.5 py-0.5 font-mono text-[10px] text-amber-900"
|
||||
>
|
||||
{{ field }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ul v-if="gateIssues.length" class="space-y-1.5">
|
||||
<li
|
||||
v-for="(issue, index) in gateIssues"
|
||||
:key="`${issue.field}-${issue.line_index ?? index}`"
|
||||
class="rounded-lg border px-2.5 py-2"
|
||||
:class="String(issue.severity) === 'blocking'
|
||||
? 'border-rose-200 bg-rose-50 text-rose-800'
|
||||
: String(issue.reason) === 'value_corrected'
|
||||
? 'border-sky-200 bg-sky-50 text-sky-800'
|
||||
: 'border-amber-200 bg-amber-50 text-amber-800'"
|
||||
>
|
||||
<div class="font-medium">
|
||||
<span v-if="issue.line_index != null">#{{ Number(issue.line_index) + 1 }} · </span>
|
||||
<span class="font-mono">{{ issue.field }}</span>
|
||||
<span class="ml-1">{{ issueReasonLabel(issue.reason) }}</span>
|
||||
</div>
|
||||
<div v-if="issue.part_number" class="mt-0.5 text-[11px] opacity-80">
|
||||
{{ t('chat.shippingNoticeUi.partNumber') }} {{ issue.part_number }}
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div v-if="orderLines.length" class="overflow-x-auto rounded-xl border border-default bg-white/90">
|
||||
<table class="min-w-full text-sm">
|
||||
<thead class="bg-surface text-left text-[11px] text-muted">
|
||||
<tr>
|
||||
<th class="px-2.5 py-2">#</th>
|
||||
<th v-for="field in orderedLineFields" :key="field.field_code" class="px-2.5 py-2">{{ field.display_name }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="(line, index) in orderLines"
|
||||
:key="`${line.part_number}-${index}`"
|
||||
class="border-t border-default/60 text-xs"
|
||||
>
|
||||
<td class="px-2.5 py-2 text-muted">{{ index + 1 }}</td>
|
||||
<td v-for="field in orderedLineFields" :key="field.field_code" class="px-2.5 py-2" :class="{ 'font-mono': field.value_type === 'string' }">{{ displayValue((line as unknown as Record<string, unknown>)[field.field_code]) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div v-else class="text-muted">{{ t('chat.shippingParsedResult.noLines') }}</div>
|
||||
|
||||
<div v-if="adjudicationDecisions.length" class="rounded-xl border border-sky-200 bg-sky-50/70 p-2.5">
|
||||
<div class="font-semibold text-sky-900">{{ t('chat.shippingParsedResult.adjudicationTitle') }}</div>
|
||||
<div class="mt-2 grid gap-1.5 md:grid-cols-2">
|
||||
<div
|
||||
v-for="decision in adjudicationDecisions"
|
||||
:key="`${decision.line_index}-${decision.field}`"
|
||||
class="rounded border border-sky-100 bg-white/80 px-2 py-1.5 text-[11px]"
|
||||
>
|
||||
<span class="font-mono">#{{ Number(decision.line_index) + 1 }} {{ decision.field }}</span>
|
||||
<span class="ml-1 font-semibold text-sky-800">{{ decision.status }}</span>
|
||||
<span v-if="decision.score != null" class="ml-1 text-muted">{{ t('chat.shippingParsedResult.score', { score: decision.score }) }}</span>
|
||||
<div class="mt-0.5 truncate text-secondary">{{ displayValue(decision.value) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ShippingFieldEvidencePanel
|
||||
:evidence="sourceCandidate?.evidence || []"
|
||||
:compact="compact"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/chat/components/ShippingWorkflowStepper.vue
|
||||
* 用途:货代发货七步流程 Stepper 展示组件。
|
||||
* 用途:货代发货五阶段 Stepper 展示组件。
|
||||
* 依赖:shipping/shippingStepper、vue-i18n。
|
||||
* 逻辑:Chat 与工作台传入 steps 数组;本组件只负责步骤高亮与标签渲染。
|
||||
*/
|
||||
@@ -33,7 +33,7 @@ const dotClass = (status: ShippingWorkflowStepItem['status']) => {
|
||||
<template>
|
||||
<div class="space-y-2">
|
||||
<div class="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted">{{ t('chat.shippingNoticeUi.stepperTitle') }}</div>
|
||||
<div class="grid gap-2" :class="compact ? 'sm:grid-cols-4 xl:grid-cols-7' : 'md:grid-cols-4 xl:grid-cols-7'">
|
||||
<div class="grid gap-2" :class="compact ? 'sm:grid-cols-5' : 'md:grid-cols-5'">
|
||||
<div
|
||||
v-for="(step, index) in steps"
|
||||
:key="step.id"
|
||||
|
||||
@@ -1,12 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/chat/components/ToolRunProgressCard.vue
|
||||
* 用途:展示文件检核/立账凭证检核等 Agent 异步 tool_run 的实时进度、知识库同步态与 Excel 下载。
|
||||
* 依赖:vue-i18n、lucide 图标、getAuthHeaders、toolRunProgress.api。
|
||||
* 逻辑:由聊天消息列表在绑定 run_id 后挂载;有 progress_metrics 时按领域指标渲染,否则回退八格。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ref } from 'vue';
|
||||
import { AlertCircle, CheckCircle2, Clock3, Download, Loader2 } from 'lucide-vue-next';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type { ToolRunProgress } from '../api/toolRunProgress.api';
|
||||
@@ -19,42 +12,19 @@ const props = defineProps<{
|
||||
fallbackTitle?: string;
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const downloadingExcel = ref(false);
|
||||
const downloadError = ref('');
|
||||
|
||||
/**
|
||||
* 领域自定义进度指标;有值时覆盖默认文件检核八格。
|
||||
* 核心逻辑:读取 progress_metrics,按 label_key 做 i18n,缺省回退 label/key。
|
||||
*/
|
||||
const domainMetrics = computed(() => {
|
||||
const metrics = props.run?.progress_metrics;
|
||||
if (!Array.isArray(metrics) || !metrics.length) return null;
|
||||
return metrics.map((item) => {
|
||||
const labelKey = String(item.label_key || '').trim();
|
||||
const label = labelKey && te(labelKey)
|
||||
? t(labelKey)
|
||||
: (item.label || item.key);
|
||||
return { key: item.key, label, value: Number(item.value) || 0 };
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 将后端 run.status 映射为本地化状态文案。
|
||||
* 核心逻辑:命中已知状态码用 i18n;未知状态回退原始值,再回退“等待中”。
|
||||
* @param status - 任务状态码
|
||||
* @returns 面向用户的状态标签
|
||||
*/
|
||||
const statusLabel = (status?: string) => {
|
||||
const map: Record<string, string> = {
|
||||
running: t('chat.toolRun.statusRunning'),
|
||||
success: t('chat.toolRun.statusSuccess'),
|
||||
partial_failed: t('chat.toolRun.statusPartialFailed'),
|
||||
failed: t('chat.toolRun.statusFailed'),
|
||||
cancelled: t('chat.toolRun.statusCancelled'),
|
||||
canceled: t('chat.toolRun.statusCancelled'),
|
||||
running: '执行中',
|
||||
success: '已完成',
|
||||
partial_failed: '部分失败',
|
||||
failed: '失败',
|
||||
cancelled: '已取消',
|
||||
canceled: '已取消',
|
||||
};
|
||||
return map[String(status || '')] || status || t('chat.toolRun.statusWaiting');
|
||||
return map[String(status || '')] || status || '等待中';
|
||||
};
|
||||
|
||||
const formatTime = (value?: string | null) => {
|
||||
@@ -82,30 +52,21 @@ const percent = () => {
|
||||
return Math.max(0, Math.min(value, 100));
|
||||
};
|
||||
|
||||
/**
|
||||
* 组装知识库同步徽标文案与样式。
|
||||
* 核心逻辑:按 sync_status 分桶映射 tone/icon;未知状态带上原始 status。
|
||||
* @param status - knowledge_base.sync_status
|
||||
*/
|
||||
const kbSyncMeta = (status?: string | null) => {
|
||||
const value = String(status || '').toLowerCase();
|
||||
if (value === 'success') {
|
||||
return { label: t('chat.toolRun.kbSynced'), tone: 'border-emerald-200 bg-emerald-50 text-emerald-700', icon: 'success' };
|
||||
return { label: '知识库已同步', tone: 'border-emerald-200 bg-emerald-50 text-emerald-700', icon: 'success' };
|
||||
}
|
||||
if (value === 'failed') {
|
||||
return { label: t('chat.toolRun.kbSyncFailed'), tone: 'border-rose-200 bg-rose-50 text-rose-700', icon: 'failed' };
|
||||
return { label: '知识库同步失败', tone: 'border-rose-200 bg-rose-50 text-rose-700', icon: 'failed' };
|
||||
}
|
||||
if (['queued', 'cleaning', 'syncing'].includes(value)) {
|
||||
return { label: t('chat.toolRun.kbSyncing'), tone: 'border-sky-200 bg-sky-50 text-sky-700', icon: 'syncing' };
|
||||
return { label: '知识库同步中', tone: 'border-sky-200 bg-sky-50 text-sky-700', icon: 'syncing' };
|
||||
}
|
||||
if (value === 'skipped') {
|
||||
return { label: t('chat.toolRun.kbNotSynced'), tone: 'border-slate-200 bg-slate-50 text-slate-600', icon: 'skipped' };
|
||||
return { label: '知识库未同步', tone: 'border-default bg-surface-soft text-secondary', icon: 'skipped' };
|
||||
}
|
||||
return {
|
||||
label: t('chat.toolRun.kbUnknown', { status: status || t('chat.toolRun.kbStatusUnknown') }),
|
||||
tone: 'border-slate-200 bg-slate-50 text-slate-600',
|
||||
icon: 'skipped',
|
||||
};
|
||||
return { label: `知识库:${status || '未知'}`, tone: 'border-default bg-surface-soft text-secondary', icon: 'skipped' };
|
||||
};
|
||||
|
||||
const parseDownloadFilename = (disposition: string | null, fallback: string) => {
|
||||
@@ -138,7 +99,7 @@ const downloadExcel = async () => {
|
||||
const res = await fetch(url, { headers: getAuthHeaders() });
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}));
|
||||
throw new Error(stringifyDownloadError(body, t('chat.toolRun.downloadFailedStatus', { status: res.status })));
|
||||
throw new Error(stringifyDownloadError(body, `下载失败:${res.status}`));
|
||||
}
|
||||
const blob = await res.blob();
|
||||
const filename = parseDownloadFilename(
|
||||
@@ -154,7 +115,7 @@ const downloadExcel = async () => {
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
} catch (e: any) {
|
||||
downloadError.value = e?.message || t('chat.toolRun.downloadFailed');
|
||||
downloadError.value = e?.message || '下载 Excel 失败';
|
||||
} finally {
|
||||
downloadingExcel.value = false;
|
||||
}
|
||||
@@ -167,25 +128,25 @@ const downloadExcel = async () => {
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3 border-b border-sky-100/80 px-4 py-3">
|
||||
<div>
|
||||
<div class="flex items-center gap-2 text-sm font-semibold text-slate-800">
|
||||
<div class="flex items-center gap-2 text-sm font-semibold text-primary">
|
||||
<Loader2 v-if="run?.status === 'running'" class="h-4 w-4 animate-spin text-sky-600" />
|
||||
<CheckCircle2 v-else-if="run?.status === 'success'" class="h-4 w-4 text-emerald-600" />
|
||||
<AlertCircle v-else-if="run?.status === 'failed' || run?.status === 'partial_failed'" class="h-4 w-4 text-amber-600" />
|
||||
<Clock3 v-else class="h-4 w-4 text-sky-600" />
|
||||
{{ run?.title || fallbackTitle || $t('chat.toolRun.fallbackTitle') }}
|
||||
{{ run?.title || fallbackTitle || '任务进度' }}
|
||||
</div>
|
||||
<p class="mt-1 text-xs text-slate-500">
|
||||
<p class="mt-1 text-xs text-muted">
|
||||
<template v-if="run">
|
||||
{{ $t('chat.toolRun.batch', { runNo: run.run_no }) }} · {{ $t('chat.toolRun.status', { status: statusLabel(run.status) }) }}
|
||||
<span v-if="run.error_message" class="ml-2 text-rose-700">{{ $t('chat.toolRun.errorMessage', { message: run.error_message }) }}</span>
|
||||
批次:{{ run.run_no }} · 状态:{{ statusLabel(run.status) }}
|
||||
<span v-if="run.error_message" class="ml-2 text-rose-700">错误信息:{{ run.error_message }}</span>
|
||||
</template>
|
||||
<template v-else-if="loading || waiting">{{ $t('chat.toolRun.waitingStart') }}</template>
|
||||
<template v-else-if="loading || waiting">正在等待检核任务启动...</template>
|
||||
<template v-else-if="error">{{ error }}</template>
|
||||
</p>
|
||||
<p v-if="run?.status === 'running' && run.current_step" class="mt-1 text-xs text-sky-700">
|
||||
{{ $t('chat.toolRun.currentStep', { step: run.current_step.label || run.current_step.step }) }}
|
||||
<span v-if="run.current_step.row_id"> · {{ $t('chat.toolRun.currentRow', { rowId: run.current_step.row_id }) }}</span>
|
||||
<span v-if="run.current_step.started_at"> · {{ $t('chat.toolRun.stepStarted', { time: formatTime(run.current_step.started_at) }) }}</span>
|
||||
当前阶段:{{ run.current_step.label || run.current_step.step }}
|
||||
<span v-if="run.current_step.row_id"> · 当前记录:{{ run.current_step.row_id }}</span>
|
||||
<span v-if="run.current_step.started_at"> · 阶段开始:{{ formatTime(run.current_step.started_at) }}</span>
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex shrink-0 flex-wrap items-center justify-end gap-2">
|
||||
@@ -210,7 +171,7 @@ const downloadExcel = async () => {
|
||||
>
|
||||
<Loader2 v-if="downloadingExcel" class="h-3.5 w-3.5 animate-spin" />
|
||||
<Download v-else class="h-3.5 w-3.5" />
|
||||
{{ downloadingExcel ? $t('chat.toolRun.downloading') : $t('chat.toolRun.downloadExcel') }}
|
||||
{{ downloadingExcel ? '下载中...' : '下载 Excel' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -220,75 +181,62 @@ const downloadExcel = async () => {
|
||||
{{ downloadError }}
|
||||
</div>
|
||||
|
||||
<div class="h-2.5 overflow-hidden rounded-full bg-slate-200">
|
||||
<div class="h-2.5 overflow-hidden rounded-full bg-surface-strong">
|
||||
<div
|
||||
class="h-full rounded-full bg-gradient-to-r from-sky-500 to-emerald-500 transition-all duration-500"
|
||||
:style="{ width: `${percent()}%` }"
|
||||
></div>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2 text-xs text-slate-500">
|
||||
<span>{{ $t('chat.toolRun.progress', { percent: percent() }) }}</span>
|
||||
<span>{{ $t('chat.toolRun.startedAt', { time: formatTime(run.started_at) }) }} · {{ $t('chat.toolRun.finishedAt', { time: formatTime(run.finished_at) }) }}</span>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2 text-xs text-muted">
|
||||
<span>进度 {{ percent() }}%</span>
|
||||
<span>开始:{{ formatTime(run.started_at) }} · 完成:{{ formatTime(run.finished_at) }}</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="domainMetrics"
|
||||
class="grid grid-cols-2 gap-1.5 sm:grid-cols-3 lg:grid-cols-5"
|
||||
>
|
||||
<div
|
||||
v-for="metric in domainMetrics"
|
||||
:key="metric.key"
|
||||
class="rounded-lg bg-white/80 px-2 py-1.5"
|
||||
>
|
||||
<div class="whitespace-nowrap text-xs text-slate-500">{{ metric.label }}</div>
|
||||
<div class="text-base font-bold text-slate-800">{{ metric.value }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="grid grid-cols-2 gap-1.5 sm:grid-cols-4 lg:grid-cols-8">
|
||||
<div class="grid grid-cols-2 gap-1.5 sm:grid-cols-4 lg:grid-cols-8">
|
||||
<div class="rounded-lg bg-white/80 px-2 py-1.5">
|
||||
<div class="whitespace-nowrap text-xs text-slate-500">{{ $t('chat.toolRun.total') }}</div>
|
||||
<div class="text-base font-bold text-slate-800">{{ run.total_count }}</div>
|
||||
<div class="whitespace-nowrap text-xs text-muted">总数</div>
|
||||
<div class="text-base font-bold text-primary">{{ run.total_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-lg bg-white/80 px-2 py-1.5">
|
||||
<div class="whitespace-nowrap text-xs text-slate-500">{{ $t('chat.toolRun.processed') }}</div>
|
||||
<div class="whitespace-nowrap text-xs text-muted">已处理</div>
|
||||
<div class="text-base font-bold text-sky-700">{{ run.processed_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-lg bg-white/80 px-2 py-1.5">
|
||||
<div class="whitespace-nowrap text-xs text-slate-500">{{ $t('chat.toolRun.success') }}</div>
|
||||
<div class="whitespace-nowrap text-xs text-muted">成功</div>
|
||||
<div class="text-base font-bold text-emerald-700">{{ run.success_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-lg bg-white/80 px-2 py-1.5">
|
||||
<div class="whitespace-nowrap text-xs text-slate-500">{{ $t('chat.toolRun.failed') }}</div>
|
||||
<div class="whitespace-nowrap text-xs text-muted">失败</div>
|
||||
<div class="text-base font-bold text-rose-700">{{ run.failed_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-lg bg-white/80 px-2 py-1.5">
|
||||
<div class="whitespace-nowrap text-xs text-slate-500">{{ $t('chat.toolRun.skipped') }}</div>
|
||||
<div class="whitespace-nowrap text-xs text-muted">跳过</div>
|
||||
<div class="text-base font-bold text-amber-700">{{ run.skipped_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-lg bg-white/80 px-2 py-1.5">
|
||||
<div class="whitespace-nowrap text-xs text-slate-500">{{ $t('chat.toolRun.qualified') }}</div>
|
||||
<div class="whitespace-nowrap text-xs text-muted">合格笔数</div>
|
||||
<div class="text-base font-bold text-emerald-700">{{ run.judgement?.qualified_count ?? 0 }}</div>
|
||||
</div>
|
||||
<div class="rounded-lg bg-white/80 px-2 py-1.5">
|
||||
<div class="whitespace-nowrap text-xs text-slate-500">{{ $t('chat.toolRun.unqualified') }}</div>
|
||||
<div class="whitespace-nowrap text-xs text-muted">不合格笔数</div>
|
||||
<div class="text-base font-bold text-rose-700">{{ run.judgement?.unqualified_count ?? 0 }}</div>
|
||||
</div>
|
||||
<div class="rounded-lg bg-white/80 px-2 py-1.5">
|
||||
<div class="whitespace-nowrap text-xs text-slate-500">{{ $t('chat.toolRun.manual') }}</div>
|
||||
<div class="whitespace-nowrap text-xs text-muted">人工判定笔数</div>
|
||||
<div class="text-base font-bold text-amber-700">{{ run.judgement?.manual_count ?? 0 }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="run.knowledge_base?.error_message" class="rounded-xl bg-amber-50 px-3 py-2 text-xs text-amber-700">
|
||||
{{ $t('chat.toolRun.kbSyncError', { message: run.knowledge_base.error_message }) }}
|
||||
知识库同步错误:{{ run.knowledge_base.error_message }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="waiting || loading" class="space-y-3 px-4 py-4">
|
||||
<div class="h-2.5 overflow-hidden rounded-full bg-slate-200">
|
||||
<div class="h-2.5 overflow-hidden rounded-full bg-surface-strong">
|
||||
<div class="h-full w-1/3 animate-pulse rounded-full bg-gradient-to-r from-sky-400 to-emerald-400" />
|
||||
</div>
|
||||
<p class="text-xs text-slate-500">{{ $t('chat.toolRun.waitingHint') }}</p>
|
||||
<p class="text-xs text-muted">检核启动后,这里会显示实时进度。</p>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,160 @@
|
||||
<!--
|
||||
features/chat/components/TrainingShareModal.vue
|
||||
用途:员工培训分享弹窗——把"当前培训模块深链 + 二维码"提供给有培训管理权限的 HR/管理员,
|
||||
供其复制链接或下载二维码后分发给员工(企微/短信/海报等渠道)。
|
||||
依赖:qrcode(前端生成二维码 dataURL)、copyTextToClipboard(shared/utils/clipboard)、useMessage。
|
||||
逻辑:由 TrainingWorkspacePanel 以 v-model:open 控制显隐;打开时按 shareUrl 生成二维码;
|
||||
接收方打开链接 → 登录 → 由面板深链逻辑自动定位到对应培训模块(见 TrainingWorkspacePanel.vue)。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import QRCode from 'qrcode';
|
||||
import { Copy, Download, Share2, XCircle } from 'lucide-vue-next';
|
||||
import { copyTextToClipboard } from '@/shared/utils/clipboard';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
/** 分享深链:/chat/<agentId>?training_type=<code>,由调用方拼好完整绝对地址。 */
|
||||
shareUrl: string;
|
||||
/** 当前分享的培训模块名称,仅用于弹窗内文案展示。 */
|
||||
trainingName: string;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [open: boolean];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
|
||||
const qrDataUrl = ref('');
|
||||
const qrGenerating = ref(false);
|
||||
|
||||
watch(
|
||||
() => [props.open, props.shareUrl] as const,
|
||||
async ([open, url]) => {
|
||||
if (!open || !url) return;
|
||||
qrGenerating.value = true;
|
||||
try {
|
||||
// 纠错级别 H:二维码可能被打印后裁剪/污损,取最高冗余保证扫码成功率。
|
||||
qrDataUrl.value = await QRCode.toDataURL(url, { width: 240, margin: 2, errorCorrectionLevel: 'H' });
|
||||
} catch {
|
||||
qrDataUrl.value = '';
|
||||
} finally {
|
||||
qrGenerating.value = false;
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
const closeModal = () => emit('update:open', false);
|
||||
|
||||
/**
|
||||
* 复制培训深链到剪贴板(兼容企微 WebView 等 clipboard API 受限环境)。
|
||||
* AI 触发时机:HR 在分享弹窗点击“复制链接”时调用;结果必须用 useMessage 明确反馈成败。
|
||||
*/
|
||||
const copyShareLink = async () => {
|
||||
const ok = await copyTextToClipboard(props.shareUrl);
|
||||
if (ok) {
|
||||
msg.success(t('chat.training.share.copied'));
|
||||
} else {
|
||||
msg.error(t('chat.training.share.copyFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 把当前二维码下载为 PNG 图片,供 HR 插入海报/群公告等离线场景。
|
||||
* AI 触发时机:HR 在分享弹窗点击“下载二维码”时调用;二维码未生成完成时禁止下载。
|
||||
*/
|
||||
const downloadQrCode = () => {
|
||||
if (!qrDataUrl.value) return;
|
||||
const link = document.createElement('a');
|
||||
link.href = qrDataUrl.value;
|
||||
link.download = `training-share-qr-${Date.now()}.png`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-[100] flex items-center justify-center bg-slate-950/80 p-4 backdrop-blur-sm"
|
||||
@click.self="closeModal"
|
||||
>
|
||||
<div class="relative w-full max-w-md overflow-hidden rounded-3xl bg-white shadow-2xl">
|
||||
<div class="flex items-center justify-between border-b border-default px-6 py-4">
|
||||
<h3 class="flex items-center gap-2 text-lg font-semibold text-primary">
|
||||
<Share2 class="h-5 w-5 text-brand-600" />
|
||||
{{ $t('chat.training.share.title') }}
|
||||
</h3>
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-8 w-8 items-center justify-center rounded-full bg-surface-soft text-secondary transition hover:bg-surface hover:text-primary"
|
||||
:aria-label="$t('chat.training.share.close')"
|
||||
@click="closeModal"
|
||||
>
|
||||
<XCircle class="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-4 px-6 py-5">
|
||||
<p class="text-sm leading-6 text-secondary">
|
||||
{{ $t('chat.training.share.description', { name: trainingName }) }}
|
||||
</p>
|
||||
|
||||
<!-- 培训链接:只读展示 + 一键复制,避免长链接被截断导致复制不全。 -->
|
||||
<div>
|
||||
<div class="text-xs font-medium text-secondary">{{ $t('chat.training.share.linkLabel') }}</div>
|
||||
<div class="mt-1.5 flex items-center gap-2">
|
||||
<input
|
||||
type="text"
|
||||
readonly
|
||||
:value="shareUrl"
|
||||
class="input-field h-9 min-w-0 flex-1 truncate text-xs"
|
||||
@focus="($event.target as HTMLInputElement).select()"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-9 shrink-0 items-center gap-1.5 rounded-xl bg-brand-600 px-3.5 text-xs font-medium text-white transition hover:bg-brand-700"
|
||||
@click="copyShareLink"
|
||||
>
|
||||
<Copy class="h-4 w-4" />
|
||||
{{ $t('chat.training.share.copyLink') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 培训二维码:扫码与链接等价,未登录用户扫码后先登录再自动直达对应模块。 -->
|
||||
<div>
|
||||
<div class="text-xs font-medium text-secondary">{{ $t('chat.training.share.qrLabel') }}</div>
|
||||
<div class="mt-1.5 flex items-center gap-4">
|
||||
<div class="flex h-40 w-40 shrink-0 items-center justify-center rounded-2xl border border-default bg-surface-soft">
|
||||
<img
|
||||
v-if="qrDataUrl"
|
||||
:src="qrDataUrl"
|
||||
:alt="$t('chat.training.share.qrLabel')"
|
||||
class="h-36 w-36"
|
||||
/>
|
||||
<span v-else class="text-xs text-secondary">{{ qrGenerating ? '...' : '--' }}</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-9 items-center gap-1.5 rounded-xl border border-default bg-white px-3.5 text-xs font-medium text-secondary transition hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60"
|
||||
:disabled="!qrDataUrl"
|
||||
@click="downloadQrCode"
|
||||
>
|
||||
<Download class="h-4 w-4" />
|
||||
{{ $t('chat.training.share.downloadQr') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* features/chat/components/messages/ChatMessageAttachmentList.spec.ts
|
||||
* 用途:校验已发送附件分层展示(chip / 摘要折叠 / 进度卡并存只留摘要)。
|
||||
* 依赖:Vitest、Vue Test Utils、vue-i18n。
|
||||
* 逻辑:覆盖 ≤3 chip、>3 摘要可展开、summaryOnly 不可展开。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ChatMessageAttachmentList from './ChatMessageAttachmentList.vue';
|
||||
import type { ChatMessageAttachment } from '../../types/chat.types';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
attachment: {
|
||||
summaryCount: '{count} 个附件',
|
||||
expandList: '展开附件列表',
|
||||
collapseList: '收起附件列表',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const makeAttachments = (count: number): ChatMessageAttachment[] =>
|
||||
Array.from({ length: count }, (_, index) => ({
|
||||
name: `file-${index + 1}.eml`,
|
||||
type: 'document' as const,
|
||||
source: 'local' as const,
|
||||
size: 1024 * (index + 1),
|
||||
extension: 'eml',
|
||||
}));
|
||||
|
||||
describe('ChatMessageAttachmentList', () => {
|
||||
it('renders compact chips when there are at most three attachments', () => {
|
||||
const wrapper = mount(ChatMessageAttachmentList, {
|
||||
props: { attachments: makeAttachments(3) },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="chat-message-attachment-chips"]').exists()).toBe(true);
|
||||
expect(wrapper.findAll('[data-testid="chat-message-attachment-chip"]')).toHaveLength(3);
|
||||
expect(wrapper.find('[data-testid="chat-message-attachment-summary"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('collapses many attachments into a summary that expands into a scrollable list', async () => {
|
||||
const wrapper = mount(ChatMessageAttachmentList, {
|
||||
props: { attachments: makeAttachments(5) },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
const summary = wrapper.get('[data-testid="chat-message-attachment-summary"]');
|
||||
expect(summary.text()).toContain('5 个附件');
|
||||
expect(wrapper.find('[data-testid="chat-message-attachment-expanded"]').exists()).toBe(false);
|
||||
|
||||
await summary.trigger('click');
|
||||
const expanded = wrapper.get('[data-testid="chat-message-attachment-expanded"]');
|
||||
expect(expanded.classes()).toContain('max-h-40');
|
||||
expect(expanded.findAll('article')).toHaveLength(5);
|
||||
});
|
||||
|
||||
it('keeps only the summary when a shipping progress card follows the message', async () => {
|
||||
const wrapper = mount(ChatMessageAttachmentList, {
|
||||
props: {
|
||||
attachments: makeAttachments(2),
|
||||
summaryOnly: true,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="chat-message-attachment-chips"]').exists()).toBe(false);
|
||||
const summary = wrapper.get('[data-testid="chat-message-attachment-summary"]');
|
||||
expect(summary.text()).toContain('2 个附件');
|
||||
|
||||
await summary.trigger('click');
|
||||
expect(wrapper.find('[data-testid="chat-message-attachment-expanded"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* features/chat/components/messages/ChatMessageAttachmentList.vue
|
||||
* 用途:在用户消息中分层展示已发送附件快照(少文件 chip / 多文件摘要折叠)。
|
||||
* 依赖:lucide 图标、vue-i18n、attachmentCard.utils、chat.types。
|
||||
* 逻辑:ChatMessageBubble 传入附件与 summaryOnly;≤3 用紧凑 chip,>3 默认摘要条可展开纵向列表;
|
||||
* 下方已有货代进度卡时 summaryOnly=true,只留摘要避免与进度卡重复。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ChevronDown, ChevronUp, FileAudio, FileImage, FileText, FileVideo, Link2, Paperclip } from 'lucide-vue-next';
|
||||
import { formatAttachmentSize } from '../../utils/attachmentCard.utils';
|
||||
import type { ChatMessageAttachment } from '../../types/chat.types';
|
||||
|
||||
/** 超过该数量后默认折叠为摘要条,避免气泡内横排大卡。 */
|
||||
const CHIP_LIMIT = 3;
|
||||
/** 展开列表内部最大高度(约 4~5 行)。 */
|
||||
const EXPANDED_LIST_MAX_HEIGHT_CLASS = 'max-h-40';
|
||||
|
||||
const props = defineProps<{
|
||||
attachments: ChatMessageAttachment[];
|
||||
/** 下方已有货代进度卡时为 true:只显示摘要,不展开明细。 */
|
||||
summaryOnly?: boolean;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const expanded = ref(false);
|
||||
|
||||
const attachmentCount = computed(() => props.attachments.length);
|
||||
const useChips = computed(() => !props.summaryOnly && attachmentCount.value > 0 && attachmentCount.value <= CHIP_LIMIT);
|
||||
const useCollapsibleSummary = computed(() => !props.summaryOnly && attachmentCount.value > CHIP_LIMIT);
|
||||
const showSummaryBar = computed(() => Boolean(props.summaryOnly) || useCollapsibleSummary.value);
|
||||
|
||||
const totalSizeLabel = computed(() => {
|
||||
let total = 0;
|
||||
let known = 0;
|
||||
for (const item of props.attachments) {
|
||||
if (typeof item.size === 'number' && Number.isFinite(item.size) && item.size >= 0) {
|
||||
total += item.size;
|
||||
known += 1;
|
||||
}
|
||||
}
|
||||
if (!known) return '';
|
||||
return formatAttachmentSize(total);
|
||||
});
|
||||
|
||||
/** 根据附件来源与业务类型选择只读消息卡片图标。 */
|
||||
function attachmentIcon(attachment: ChatMessageAttachment) {
|
||||
if (attachment.source === 'remote') return Link2;
|
||||
if (attachment.type === 'image') return FileImage;
|
||||
if (attachment.type === 'audio') return FileAudio;
|
||||
if (attachment.type === 'video') return FileVideo;
|
||||
return FileText;
|
||||
}
|
||||
|
||||
/** 生成附件类型徽标,优先使用快照扩展名。 */
|
||||
function attachmentBadge(attachment: ChatMessageAttachment): string {
|
||||
const extension = String(attachment.extension || '').trim().toUpperCase();
|
||||
if (extension) return extension.slice(0, 5);
|
||||
if (attachment.source === 'remote') return 'URL';
|
||||
return attachment.type.toUpperCase().slice(0, 5);
|
||||
}
|
||||
|
||||
/** 切换多附件摘要的展开/收起;summaryOnly 时不可展开。 */
|
||||
function toggleExpanded() {
|
||||
if (props.summaryOnly) return;
|
||||
expanded.value = !expanded.value;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="attachmentCount > 0"
|
||||
data-testid="chat-message-attachment-list"
|
||||
class="mb-2 w-full"
|
||||
>
|
||||
<!-- ≤3:紧凑 chip,宽度自适应 -->
|
||||
<div
|
||||
v-if="useChips"
|
||||
data-testid="chat-message-attachment-chips"
|
||||
class="flex w-full flex-wrap justify-end gap-1.5"
|
||||
>
|
||||
<article
|
||||
v-for="(attachment, attachmentIndex) in props.attachments"
|
||||
:key="`${attachment.name}-${attachment.size ?? 'unknown'}-${attachmentIndex}`"
|
||||
class="flex h-10 max-w-[220px] items-center gap-2 rounded-lg border border-white/25 bg-white/95 px-2.5 text-slate-800 shadow-sm dark:border-white/10 dark:bg-slate-900/90 dark:text-slate-100"
|
||||
:title="attachment.name"
|
||||
data-testid="chat-message-attachment-chip"
|
||||
>
|
||||
<div
|
||||
class="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-brand-50 text-brand-700 dark:bg-brand-900/40 dark:text-brand-300"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<component :is="attachmentIcon(attachment)" class="h-3.5 w-3.5" />
|
||||
</div>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="truncate text-xs font-semibold leading-tight">{{ attachment.name }}</div>
|
||||
<div class="mt-0.5 flex items-center gap-1 text-[10px] leading-none text-slate-500 dark:text-slate-400">
|
||||
<span>{{ attachmentBadge(attachment) }}</span>
|
||||
<span v-if="attachment.size !== undefined">· {{ formatAttachmentSize(attachment.size) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<!-- >3 或货代进度卡并存:摘要条 -->
|
||||
<div v-else-if="showSummaryBar" class="flex w-full flex-col items-end gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
data-testid="chat-message-attachment-summary"
|
||||
class="inline-flex max-w-full items-center gap-2 rounded-lg border border-white/25 bg-white/15 px-3 py-2 text-left text-white transition hover:bg-white/20"
|
||||
:class="props.summaryOnly ? 'cursor-default' : 'cursor-pointer'"
|
||||
:aria-expanded="props.summaryOnly ? undefined : expanded"
|
||||
:aria-controls="props.summaryOnly || !expanded ? undefined : 'chat-message-attachment-expanded'"
|
||||
:aria-label="props.summaryOnly
|
||||
? t('chat.attachment.summaryCount', { count: attachmentCount })
|
||||
: (expanded ? t('chat.attachment.collapseList') : t('chat.attachment.expandList'))"
|
||||
@click="toggleExpanded"
|
||||
>
|
||||
<Paperclip class="h-3.5 w-3.5 shrink-0 opacity-90" aria-hidden="true" />
|
||||
<span class="truncate text-xs font-semibold">
|
||||
{{ t('chat.attachment.summaryCount', { count: attachmentCount }) }}
|
||||
</span>
|
||||
<span v-if="totalSizeLabel" class="shrink-0 text-[11px] opacity-80">· {{ totalSizeLabel }}</span>
|
||||
<component
|
||||
:is="expanded ? ChevronUp : ChevronDown"
|
||||
v-if="!props.summaryOnly"
|
||||
class="h-3.5 w-3.5 shrink-0 opacity-80"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</button>
|
||||
|
||||
<div
|
||||
v-if="useCollapsibleSummary && expanded"
|
||||
id="chat-message-attachment-expanded"
|
||||
data-testid="chat-message-attachment-expanded"
|
||||
class="w-full max-w-sm overflow-y-auto rounded-xl border border-white/20 bg-white/95 p-1.5 shadow-sm dark:bg-slate-900/95"
|
||||
:class="EXPANDED_LIST_MAX_HEIGHT_CLASS"
|
||||
>
|
||||
<article
|
||||
v-for="(attachment, attachmentIndex) in props.attachments"
|
||||
:key="`expanded-${attachment.name}-${attachment.size ?? 'unknown'}-${attachmentIndex}`"
|
||||
class="flex items-center gap-2 rounded-lg px-2 py-1.5 text-slate-800 dark:text-slate-100"
|
||||
:title="attachment.name"
|
||||
>
|
||||
<div
|
||||
class="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-brand-50 text-brand-700 dark:bg-brand-900/40 dark:text-brand-300"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<component :is="attachmentIcon(attachment)" class="h-3.5 w-3.5" />
|
||||
</div>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="truncate text-xs font-semibold">{{ attachment.name }}</div>
|
||||
<div class="mt-0.5 text-[10px] text-slate-500 dark:text-slate-400">
|
||||
<span>{{ attachmentBadge(attachment) }}</span>
|
||||
<span v-if="attachment.size !== undefined"> · {{ formatAttachmentSize(attachment.size) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,8 +1,10 @@
|
||||
/**
|
||||
* features/chat/components/messages/ChatMessageBubble.vue
|
||||
* 用途:渲染单条聊天消息,统一承接用户气泡、助手 Markdown、内嵌文件下载、请假/出货/合同审查子组件与操作栏。
|
||||
* 依赖:Vue computed、lucide 图标、Leave/Shipping/ContractReview 子消息组件、chat.types 与页面级 handlers。
|
||||
* 逻辑:由 ChatMessageList 按消息逐条挂载;合同审查结果卡自带边框,外层不再套 chat-msg-assistant 气泡以免双层框。
|
||||
* 用途:渲染单条聊天消息,统一承接用户气泡、助手 Markdown、内嵌文件下载、请假/出货子组件与操作栏。
|
||||
* 依赖:Vue computed、lucide 图标、消息附件/Leave/Shipping 子组件、chat.types 与页面级 handlers。
|
||||
* 逻辑:由 ChatMessageList 按消息逐条挂载;货代履约写按钮不在气泡内渲染,仅展示只读卡与深链通知。
|
||||
* 用户附件区支持 summaryOnly:下方已有抽取进度卡时只显示附件摘要。
|
||||
* 兼容:同时承接采购合同审查、库存映射、订单提取和 Mermaid 展示。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, ref, watch } from 'vue';
|
||||
@@ -10,18 +12,21 @@ import { useI18n } from 'vue-i18n';
|
||||
import { Check, Copy, Download, Edit2, Eye, LayoutGrid, MessageSquareText, RotateCw, X } from 'lucide-vue-next';
|
||||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||||
import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue';
|
||||
import ChatMessageAttachmentList from './ChatMessageAttachmentList.vue';
|
||||
import MaintenanceDeviceResultCard from './MaintenanceDeviceResultCard.vue';
|
||||
import ContractReviewResultCard from './ContractReviewResultCard.vue';
|
||||
import ShippingInventoryMappingMessage, { type ShippingMappingHandlers } from './ShippingInventoryMappingMessage.vue';
|
||||
import TransferMessageView from './TransferMessageView.vue';
|
||||
import ShippingMatchResultCard from './ShippingMatchResultCard.vue';
|
||||
import ShippingParseReviewMessage, { type ShippingParseReviewHandlers } from './ShippingParseReviewMessage.vue';
|
||||
import type { ShippingMessageHandlers } from './shippingMessageHandlers';
|
||||
import TrainingExamQuestionMessage, { type TrainingHandlers } from './TrainingExamQuestionMessage.vue';
|
||||
import TrainingVideoMessage from './TrainingVideoMessage.vue';
|
||||
import TrainingSummaryMessage from './TrainingSummaryMessage.vue';
|
||||
import TrainingResultCard from './TrainingResultCard.vue';
|
||||
import ShippingOrderExtractionCard from '../shipping/ShippingOrderExtractionCard.vue';
|
||||
import { buildMermaidFlowFallbackHtml } from '../../utils/mermaidChart';
|
||||
import type { ChatMessage, InlineDownloadFile, SourceFileLink } from '../../types/chat.types';
|
||||
import type { ShippingInventoryMappingFormPayload, ShippingMatchResultPayload } from '../../types/shipping.types';
|
||||
import type { ShippingMatchResultPayload } from '../../types/shipping.types';
|
||||
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
|
||||
import type { MaintenanceRecord } from '@/features/maintenance/types/record.types';
|
||||
|
||||
@@ -32,13 +37,10 @@ export interface ChatMessageBubbleHandlers {
|
||||
openAssetImage: (assetId: string, assetName?: string) => void;
|
||||
getInlineDownloadFiles: (text: string) => { cleanedText: string; files: InlineDownloadFile[] };
|
||||
downloadInlineFile: (file: InlineDownloadFile) => void;
|
||||
getShippingInventoryMappingPayload: (msg: ChatMessage) => ShippingInventoryMappingFormPayload | null;
|
||||
getShippingMatchResultPayload: (msg: ChatMessage) => ShippingMatchResultPayload | null;
|
||||
canOpenQueryPreview: (msg: ChatMessage) => boolean;
|
||||
getQueryPreviewSummary: (msg: ChatMessage) => string;
|
||||
openQueryPreviewDialog: (msg: ChatMessage) => void;
|
||||
shippingActionButtonClass: (variant?: string) => string;
|
||||
onShippingActionClick: (msg: ChatMessage, action: NonNullable<ChatMessage['shipping_actions']>[number]) => void;
|
||||
getDisplayRetrieverResources: (msg: ChatMessage) => Array<Record<string, unknown>>;
|
||||
getSourceLinks: (resources: Array<Record<string, unknown>>) => SourceFileLink[];
|
||||
shouldExpandSourceDetails: (msg: ChatMessage) => boolean;
|
||||
@@ -55,11 +57,11 @@ const {
|
||||
isThinking,
|
||||
showChatRating,
|
||||
copiedIndex,
|
||||
isShippingNoticeAgent,
|
||||
isLatestAssistantMessage,
|
||||
handlers,
|
||||
leaveHandlers,
|
||||
shippingHandlers,
|
||||
attachmentSummaryOnly = false,
|
||||
} = defineProps<{
|
||||
message: ChatMessage;
|
||||
index: number;
|
||||
@@ -71,8 +73,11 @@ const {
|
||||
isLatestAssistantMessage: boolean;
|
||||
handlers: ChatMessageBubbleHandlers;
|
||||
leaveHandlers: LeaveMessageHandlers;
|
||||
shippingHandlers: ShippingMappingHandlers;
|
||||
shippingHandlers: ShippingMessageHandlers;
|
||||
trainingHandlers: TrainingHandlers;
|
||||
compactShippingProgress?: boolean;
|
||||
/** 下方已有货代进度卡时,用户气泡附件只显示摘要。 */
|
||||
attachmentSummaryOnly?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -84,6 +89,7 @@ const emit = defineEmits<{
|
||||
'maintenance-edit-record': [record: MaintenanceRecord];
|
||||
'maintenance-view-record-history': [device: MaintenanceDevice];
|
||||
'maintenance-create-record-for-device': [device: MaintenanceDevice];
|
||||
'open-batch-workbench': [];
|
||||
}>();
|
||||
|
||||
const authStore = useAuthStore();
|
||||
@@ -93,6 +99,12 @@ const RESTRICTED_INLINE_DOWNLOAD_FILE_NAME = '资产明细全量导出表.csv';
|
||||
|
||||
/** 合同审查结果卡:自身已是完整卡片,外层只需透明容器。 */
|
||||
const isContractReviewMessage = computed(() => message.type === 'procurement-contract-review');
|
||||
const isTransferMessage = computed(
|
||||
() =>
|
||||
message.type === 'transfer-precheck'
|
||||
|| message.type === 'transfer-progress'
|
||||
|| message.type === 'transfer-result',
|
||||
);
|
||||
|
||||
const isLeaveMessage = computed(() =>
|
||||
message.type === 'leave-form'
|
||||
@@ -116,12 +128,57 @@ const showSourceSection = computed(() => {
|
||||
|| sourceLinks.value.length > 0;
|
||||
});
|
||||
|
||||
const showActions = computed(() => message.type !== 'leave-form');
|
||||
const showShippingActionsPanel = computed(() =>
|
||||
isShippingNoticeAgent
|
||||
&& !!message.shipping_actions?.length
|
||||
&& message.type !== 'shipping-match-result',
|
||||
);
|
||||
const hasUserContent = computed(() => message.role === 'user' && String(message.content || '').trim().length > 0);
|
||||
const hasUserAttachments = computed(() => message.role === 'user' && !!message.attachments?.length);
|
||||
const hasUserPayload = computed(() => hasUserContent.value || hasUserAttachments.value);
|
||||
const showActions = computed(() => (
|
||||
message.type !== 'leave-form'
|
||||
&& (message.role !== 'user' || hasUserContent.value)
|
||||
));
|
||||
const shippingOrderExtractionState = computed(() => message.shipping_order_extraction_state);
|
||||
const retryingOrderExtraction = ref(false);
|
||||
const refreshingOrderExtraction = ref(false);
|
||||
const cancellingOrderExtraction = ref(false);
|
||||
const shippingOrderExtractionRunNo = computed(() => {
|
||||
const payload = message.payload && typeof message.payload === 'object'
|
||||
? message.payload as Record<string, unknown>
|
||||
: {};
|
||||
return String(payload.order_extraction_run_no || '').trim();
|
||||
});
|
||||
const shippingOrderExtractionReadonly = computed(() => (
|
||||
shippingOrderExtractionState.value?.isCurrent === false
|
||||
|| Boolean(shippingOrderExtractionState.value?.supersedingRunNo)
|
||||
));
|
||||
/** 失败卡片复用原 Run 重试;按钮本地防重,成功后状态卡由 Run 轮询原位更新。 */
|
||||
const retryShippingOrderExtraction = async () => {
|
||||
if (!shippingOrderExtractionRunNo.value || retryingOrderExtraction.value) return;
|
||||
retryingOrderExtraction.value = true;
|
||||
try {
|
||||
await shippingHandlers.retryOrderExtractionRun(shippingOrderExtractionRunNo.value);
|
||||
} finally {
|
||||
retryingOrderExtraction.value = false;
|
||||
}
|
||||
};
|
||||
/** 只读刷新 Run 投影,不改变后台业务状态。 */
|
||||
const refreshShippingOrderExtraction = async () => {
|
||||
if (!shippingOrderExtractionRunNo.value || refreshingOrderExtraction.value) return;
|
||||
refreshingOrderExtraction.value = true;
|
||||
try {
|
||||
await shippingHandlers.refreshOrderExtractionRun(shippingOrderExtractionRunNo.value);
|
||||
} finally {
|
||||
refreshingOrderExtraction.value = false;
|
||||
}
|
||||
};
|
||||
/** 请求取消整批;确认后走请求语义,不伪造即时终态。 */
|
||||
const cancelShippingOrderExtraction = async (reason?: string) => {
|
||||
if (!shippingOrderExtractionRunNo.value || cancellingOrderExtraction.value) return;
|
||||
cancellingOrderExtraction.value = true;
|
||||
try {
|
||||
await shippingHandlers.cancelOrderExtractionRun(shippingOrderExtractionRunNo.value, reason || null);
|
||||
} finally {
|
||||
cancellingOrderExtraction.value = false;
|
||||
}
|
||||
};
|
||||
const isLastMessage = computed(() => index === messageCount - 1 || (message.role === 'assistant' && isLatestAssistantMessage));
|
||||
const isCopied = computed(() => copiedIndex === index);
|
||||
const renderedMarkdown = computed(() => (
|
||||
@@ -662,28 +719,48 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
:class="message.role === 'user' ? 'max-w-[88%] md:max-w-[74%] items-end' : 'w-full'"
|
||||
>
|
||||
<div
|
||||
v-if="message.role === 'assistant' || hasUserPayload"
|
||||
class="text-[15px] leading-relaxed"
|
||||
:class="message.role === 'user'
|
||||
? 'rounded-2xl rounded-tr-sm bg-brand-600 px-5 py-2.5 text-white shadow-sm shadow-brand-500/15'
|
||||
: isContractReviewMessage
|
||||
? 'w-full'
|
||||
: 'chat-msg-assistant'"
|
||||
: shippingOrderExtractionState
|
||||
? 'w-full'
|
||||
: 'chat-msg-assistant'"
|
||||
>
|
||||
<div v-if="message.role === 'user'" class="whitespace-pre-wrap">{{ message.content }}</div>
|
||||
<template v-if="message.role === 'user'">
|
||||
<ChatMessageAttachmentList
|
||||
v-if="message.attachments?.length"
|
||||
:attachments="message.attachments"
|
||||
:summary-only="attachmentSummaryOnly"
|
||||
/>
|
||||
<div v-if="hasUserContent" class="whitespace-pre-wrap px-2.5 py-1">{{ message.content }}</div>
|
||||
</template>
|
||||
<div v-else>
|
||||
<ShippingOrderExtractionCard
|
||||
v-if="shippingOrderExtractionState"
|
||||
:state="shippingOrderExtractionState"
|
||||
:run-no="shippingOrderExtractionRunNo"
|
||||
:readonly="shippingOrderExtractionReadonly"
|
||||
:readonly-reason="shippingOrderExtractionState?.readOnlyReason"
|
||||
:retrying="retryingOrderExtraction"
|
||||
:refreshing="refreshingOrderExtraction"
|
||||
:cancelling="cancellingOrderExtraction"
|
||||
:compact-progress="compactShippingProgress"
|
||||
@retry="retryShippingOrderExtraction"
|
||||
@refresh="refreshShippingOrderExtraction"
|
||||
@cancel="cancelShippingOrderExtraction"
|
||||
@open-batch-workbench="emit('open-batch-workbench')"
|
||||
/>
|
||||
<LeaveMessageBlock
|
||||
v-if="isLeaveMessage"
|
||||
:message="message"
|
||||
:index="index"
|
||||
:handlers="leaveHandlers"
|
||||
/>
|
||||
<ShippingInventoryMappingMessage
|
||||
v-else-if="message.type === 'shipping-inventory-mapping' && handlers.getShippingInventoryMappingPayload(message)"
|
||||
:message="message"
|
||||
:handlers="shippingHandlers"
|
||||
/>
|
||||
<ShippingParseReviewMessage
|
||||
v-else-if="message.type === 'shipping-parse-review' && shippingHandlers.getParseReviewPayload(message)"
|
||||
v-if="message.type === 'shipping-parse-review' && shippingHandlers.getParseReviewPayload(message)"
|
||||
:message="message"
|
||||
:handlers="shippingParseReviewHandlers"
|
||||
/>
|
||||
@@ -693,10 +770,6 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
:match-status="handlers.getShippingMatchResultPayload(message)!.match_status"
|
||||
:line-results="handlers.getShippingMatchResultPayload(message)!.line_results"
|
||||
:shortage-lines="handlers.getShippingMatchResultPayload(message)!.shortage_lines"
|
||||
:action-buttons="handlers.getShippingMatchResultPayload(message)!.action_buttons"
|
||||
:action-busy="isThinking || message.shipping_actions_used"
|
||||
:action-button-class="handlers.shippingActionButtonClass"
|
||||
:on-action-click="(action) => handlers.onShippingActionClick(message, action)"
|
||||
/>
|
||||
<MaintenanceDeviceResultCard
|
||||
v-else-if="message.type === 'maintenance-device-result'"
|
||||
@@ -709,6 +782,10 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
v-else-if="message.type === 'procurement-contract-review'"
|
||||
:message="message"
|
||||
/>
|
||||
<TransferMessageView
|
||||
v-else-if="isTransferMessage"
|
||||
:payload="(message.payload as Record<string, unknown> | undefined)"
|
||||
/>
|
||||
<TrainingExamQuestionMessage
|
||||
v-else-if="isTrainingExamMessage && trainingHandlers.getQuestion()"
|
||||
:question="trainingHandlers.getQuestion()!"
|
||||
@@ -788,24 +865,6 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="showShippingActionsPanel"
|
||||
class="mt-4 space-y-2 border-t border-default pt-4"
|
||||
>
|
||||
<div class="text-xs font-medium text-muted">{{ $t('chat.shippingNoticeActionsHint') }}</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="(action, actionIndex) in message.shipping_actions"
|
||||
:key="`${message.local_id || index}-shipping-action-${action.id}-${actionIndex}`"
|
||||
type="button"
|
||||
:class="handlers.shippingActionButtonClass(action.variant)"
|
||||
:disabled="isThinking || message.shipping_actions_used"
|
||||
@click="handlers.onShippingActionClick(message, action)"
|
||||
>
|
||||
{{ action.label }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -25,7 +25,9 @@ const msg = useMessage();
|
||||
const downloading = ref(false);
|
||||
const downloadingAnnotated = ref(false);
|
||||
const latestReview = ref<ContractReviewRow | null>(null);
|
||||
let refreshTimer: ReturnType<typeof window.setTimeout> | undefined;
|
||||
// 浏览器端 window.setTimeout 返回 number;勿用 ReturnType<typeof window.setTimeout>,
|
||||
// 其在 @types/node 与 DOM lib 混用时会解析为 NodeJS.Timeout 导致 TS2322。
|
||||
let refreshTimer: number | undefined;
|
||||
let refreshing = false;
|
||||
let disposed = false;
|
||||
|
||||
|
||||
@@ -79,7 +79,7 @@ const { message, index, handlers } = defineProps<{
|
||||
@change="handlers.syncLeaveDuration(handlers.getLeaveFormPayload(message)!.form)"
|
||||
>
|
||||
<option value="" disabled>{{ $t('chat.selectLeaveType') }}</option>
|
||||
<option v-for="leaveType in LEAVE_TYPES" :key="leaveType.value" :value="leaveType.value">{{ $t(leaveType.labelKey) }}</option>
|
||||
<option v-for="leaveType in LEAVE_TYPES" :key="leaveType.value" :value="leaveType.value">{{ leaveType.label }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
/**
|
||||
* features/chat/components/messages/ShippingInventoryMappingMessage.vue
|
||||
* 用途:发货 Agent 库存 Excel 列映射表单消息 UI。
|
||||
* 依赖:chat.types、shipping.api.types、shipping.types。
|
||||
* 逻辑:ChatView 渲染 mapping 类型消息时挂载;通过 ShippingMappingHandlers 与 useChatShipping 交互。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import type { ChatMessage } from '../../types/chat.types';
|
||||
import type { ShippingNoticeHeader, ShippingNoticeLine } from '../../types/shipping.api.types';
|
||||
import type { ShippingInventoryMappingFormPayload, ShippingMatchResultPayload, ShippingParseReviewPayload } from '../../types/shipping.types';
|
||||
|
||||
export interface ShippingMappingHandlers {
|
||||
getPayload: (msg: ChatMessage) => ShippingInventoryMappingFormPayload | null;
|
||||
normalizeHeader: (header: string) => string;
|
||||
hasSampleRows: (msg: ChatMessage) => boolean;
|
||||
getSampleRowText: (msg: ChatMessage) => string;
|
||||
reupload: (msg: ChatMessage) => void;
|
||||
apply: (msg: ChatMessage) => void;
|
||||
getParseReviewPayload: (msg: ChatMessage) => ShippingParseReviewPayload | null;
|
||||
getMatchResultPayload: (msg: ChatMessage) => ShippingMatchResultPayload | null;
|
||||
updateParseReviewHeader: (msg: ChatMessage, fields: Partial<ShippingNoticeHeader>) => Promise<boolean>;
|
||||
updateParseReviewLine: (msg: ChatMessage, lineIndex: number, patch: Partial<ShippingNoticeLine>) => Promise<boolean>;
|
||||
updateHeader: (msg: ChatMessage, fields: Partial<ShippingNoticeHeader>) => Promise<boolean>;
|
||||
updateLine: (msg: ChatMessage, lineIndex: number, patch: Partial<ShippingNoticeLine>) => Promise<boolean>;
|
||||
addLine: (msg: ChatMessage, line: Partial<ShippingNoticeLine>) => Promise<boolean>;
|
||||
removeLine: (msg: ChatMessage, lineIndex: number) => Promise<boolean>;
|
||||
}
|
||||
|
||||
const { message, handlers } = defineProps<{
|
||||
message: ChatMessage;
|
||||
handlers: ShippingMappingHandlers;
|
||||
}>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="handlers.getPayload(message)" class="space-y-4">
|
||||
<div class="whitespace-pre-wrap text-sm font-medium text-secondary">{{ message.content }}</div>
|
||||
<div class="space-y-4 rounded-2xl border border-default bg-surface-soft/90 p-4">
|
||||
<div class="space-y-2">
|
||||
<div class="text-xs font-bold uppercase tracking-wider text-muted">{{ $t('chat.shippingNoticeMapping.inventoryHeaders') }}</div>
|
||||
<div class="text-xs text-muted">
|
||||
{{ $t('chat.shippingNoticeMapping.headerRow', { row: handlers.getPayload(message)!.schema_preview.header_row_index || 1 }) }}
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<span
|
||||
v-for="h in (handlers.getPayload(message)!.schema_preview.headers || [])"
|
||||
:key="`inv-h-${h}`"
|
||||
class="rounded-full border border-default bg-surface px-3 py-1 text-xs text-secondary"
|
||||
>{{ handlers.normalizeHeader(h) || $t('chat.shippingNoticeMapping.empty') }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="handlers.hasSampleRows(message)"
|
||||
class="whitespace-pre-wrap text-xs text-muted"
|
||||
>
|
||||
{{ $t('chat.shippingNoticeMapping.sample') }}:{{ handlers.getSampleRowText(message) }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<div class="text-xs font-bold uppercase tracking-wider text-muted">{{ $t('chat.shippingNoticeMapping.orderDetails') }}</div>
|
||||
<div class="text-xs text-muted">
|
||||
{{ $t('chat.shippingNoticeMapping.orderRowCount', { count: handlers.getPayload(message)!.order.line_count }) }};{{ $t('chat.shippingNoticeMapping.orderSkuPreview', { count: handlers.getPayload(message)!.order.skus.length, skus: handlers.getPayload(message)!.order.skus.join(',') || $t('chat.shippingNoticeMapping.unrecognized') }) }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.skuColumnRequired') }}</span>
|
||||
<select
|
||||
v-model="handlers.getPayload(message)!.form.sku"
|
||||
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
|
||||
:disabled="handlers.getPayload(message)!.applying"
|
||||
>
|
||||
<option value="" disabled>{{ $t('chat.shippingNoticeMapping.selectHeader') }}</option>
|
||||
<option v-for="h in (handlers.getPayload(message)!.schema_preview.headers || [])" :key="`sku-${h}`" :value="h">{{ handlers.normalizeHeader(h) }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.availableQtyColumnRequired') }}</span>
|
||||
<select
|
||||
v-model="handlers.getPayload(message)!.form.available_qty"
|
||||
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
|
||||
:disabled="handlers.getPayload(message)!.applying"
|
||||
>
|
||||
<option value="" disabled>{{ $t('chat.shippingNoticeMapping.selectHeader') }}</option>
|
||||
<option v-for="h in (handlers.getPayload(message)!.schema_preview.headers || [])" :key="`qty-${h}`" :value="h">{{ handlers.normalizeHeader(h) }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-1.5 md:col-span-2">
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.reservationIdColumnOptional') }}</span>
|
||||
<select
|
||||
v-model="handlers.getPayload(message)!.form.reservation_id"
|
||||
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
|
||||
:disabled="handlers.getPayload(message)!.applying"
|
||||
>
|
||||
<option value="">{{ $t('chat.shippingNoticeMapping.reservationIdNotUsed') }}</option>
|
||||
<option v-for="h in (handlers.getPayload(message)!.schema_preview.headers || [])" :key="`rid-${h}`" :value="h">{{ handlers.normalizeHeader(h) }}</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end gap-3">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60"
|
||||
:disabled="handlers.getPayload(message)!.applying"
|
||||
@click="handlers.reupload(message)"
|
||||
>
|
||||
{{ $t('chat.shippingNoticeMapping.reupload') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl bg-emerald-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
:disabled="handlers.getPayload(message)!.applying"
|
||||
@click="handlers.apply(message)"
|
||||
>
|
||||
{{ handlers.getPayload(message)!.applying ? $t('chat.shippingNoticeMapping.applying') : $t('chat.shippingNoticeMapping.applyAndParse') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -2,7 +2,8 @@
|
||||
* features/chat/components/messages/ShippingMatchResultCard.vue
|
||||
* 用途:出货 Agent 对话区与工作台共用的库存匹配/缺口结果卡片。
|
||||
* 依赖:shipping.api.types、vue-i18n。
|
||||
* 逻辑:由 Chat 消息区和 ShippingNoticeView 传入匹配结果;本组件只负责结构化展示状态、缺口与操作按钮。
|
||||
* 逻辑:由 Chat 消息区和 ShippingNoticeView 传入匹配结果;本组件只负责结构化展示;
|
||||
* line_status 含 ok/partial/shortage/conflict(含 multi_file_conflict 别名),经 i18n rowStatus 映射。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
@@ -33,6 +34,9 @@ const rowStatusLabel = (status?: string | null) => {
|
||||
if (status === 'ok') return t('chat.shippingNoticeUi.rowStatus.ok');
|
||||
if (status === 'partial') return t('chat.shippingNoticeUi.rowStatus.partial');
|
||||
if (status === 'shortage') return t('chat.shippingNoticeUi.rowStatus.shortage');
|
||||
if (status === 'conflict' || status === 'multi_file_conflict') {
|
||||
return t('chat.shippingNoticeUi.rowStatus.conflict');
|
||||
}
|
||||
return status || '-';
|
||||
};
|
||||
|
||||
@@ -76,7 +80,7 @@ const hasShortage = () => Array.isArray(props.shortageLines) && props.shortageLi
|
||||
<tr>
|
||||
<th class="px-3 py-2">#</th>
|
||||
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.reservationId') }}</th>
|
||||
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.sku') }}</th>
|
||||
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.partNumber') }}</th>
|
||||
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.orderDemand') }}</th>
|
||||
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.inventoryAvailable') }}</th>
|
||||
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.shortageQty') }}</th>
|
||||
@@ -91,7 +95,7 @@ const hasShortage = () => Array.isArray(props.shortageLines) && props.shortageLi
|
||||
>
|
||||
<td class="px-3 py-2 text-secondary">{{ index + 1 }}</td>
|
||||
<td class="px-3 py-2 text-secondary">{{ line.reservation_id || '-' }}</td>
|
||||
<td class="px-3 py-2 font-mono text-secondary">{{ line.sku || '-' }}</td>
|
||||
<td class="px-3 py-2 font-mono text-secondary">{{ line.part_number || '-' }}</td>
|
||||
<td class="px-3 py-2 text-secondary">{{ formatQty(line.required_qty) }}</td>
|
||||
<td class="px-3 py-2 text-secondary">{{ formatQty(line.available_qty) }}</td>
|
||||
<td class="px-3 py-2" :class="Number(line.shortage_qty || 0) > 0 ? 'font-semibold text-rose-700' : 'text-secondary'">
|
||||
@@ -121,7 +125,7 @@ const hasShortage = () => Array.isArray(props.shortageLines) && props.shortageLi
|
||||
v-for="(line, index) in shortageLines"
|
||||
:key="`${taskId}-shortage-${index}`"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.shortageRowDetail', { index: index + 1, reservationId: line.reservation_id || '-', sku: line.sku || '-', shortage: formatQty(line.shortage_qty) }) }}
|
||||
{{ t('chat.shippingNoticeUi.shortageRowDetail', { index: index + 1, reservationId: line.reservation_id || '-', partNumber: line.part_number || '-', shortage: formatQty(line.shortage_qty) }) }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
@@ -36,7 +36,10 @@ const headerForm = reactive<ShippingNoticeHeader>({
|
||||
});
|
||||
const lineForm = reactive<Partial<ShippingNoticeLine>>({
|
||||
reservation_id: '',
|
||||
sku: '',
|
||||
part_number: '',
|
||||
customer_part_number: '',
|
||||
aws_part_number: '',
|
||||
inventory_source_hint: '',
|
||||
qty: 0,
|
||||
required_date: '',
|
||||
uom: '',
|
||||
@@ -61,7 +64,10 @@ watch(
|
||||
const line = payload.value.lines[value];
|
||||
if (!line) return;
|
||||
lineForm.reservation_id = line.reservation_id ?? '';
|
||||
lineForm.sku = line.sku;
|
||||
lineForm.part_number = line.part_number;
|
||||
lineForm.customer_part_number = line.customer_part_number ?? '';
|
||||
lineForm.aws_part_number = line.aws_part_number ?? '';
|
||||
lineForm.inventory_source_hint = line.inventory_source_hint ?? '';
|
||||
lineForm.qty = line.qty;
|
||||
lineForm.required_date = line.required_date ?? '';
|
||||
lineForm.uom = line.uom ?? '';
|
||||
@@ -84,7 +90,10 @@ const saveLine = async () => {
|
||||
if (editingLineIndex.value == null) return;
|
||||
const ok = await handlers.updateLine(message, editingLineIndex.value, {
|
||||
reservation_id: lineForm.reservation_id,
|
||||
sku: lineForm.sku,
|
||||
part_number: lineForm.part_number,
|
||||
customer_part_number: lineForm.customer_part_number,
|
||||
aws_part_number: lineForm.aws_part_number,
|
||||
inventory_source_hint: lineForm.inventory_source_hint,
|
||||
qty: Number(lineForm.qty || 0),
|
||||
required_date: lineForm.required_date,
|
||||
uom: lineForm.uom,
|
||||
@@ -96,7 +105,10 @@ const startAddLine = () => {
|
||||
addingLine.value = true;
|
||||
editingLineIndex.value = null;
|
||||
lineForm.reservation_id = '';
|
||||
lineForm.sku = '';
|
||||
lineForm.part_number = '';
|
||||
lineForm.customer_part_number = '';
|
||||
lineForm.aws_part_number = '';
|
||||
lineForm.inventory_source_hint = '';
|
||||
lineForm.qty = 0;
|
||||
lineForm.required_date = '';
|
||||
lineForm.uom = '';
|
||||
@@ -105,7 +117,10 @@ const startAddLine = () => {
|
||||
const saveAddedLine = async () => {
|
||||
const ok = await handlers.addLine(message, {
|
||||
reservation_id: lineForm.reservation_id,
|
||||
sku: lineForm.sku,
|
||||
part_number: lineForm.part_number,
|
||||
customer_part_number: lineForm.customer_part_number,
|
||||
aws_part_number: lineForm.aws_part_number,
|
||||
inventory_source_hint: lineForm.inventory_source_hint,
|
||||
qty: Number(lineForm.qty || 0),
|
||||
required_date: lineForm.required_date,
|
||||
uom: lineForm.uom,
|
||||
@@ -207,7 +222,9 @@ const removeLine = async (lineIndex: number) => {
|
||||
<tr>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">#</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.reservationId') }}</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.sku') }}</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.partNumber') }}</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.customerPartNumber') }}</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.awsPartNumber') }}</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.qty') }}</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.requiredDate') }}</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.actions') }}</th>
|
||||
@@ -217,7 +234,9 @@ const removeLine = async (lineIndex: number) => {
|
||||
<tr v-for="(line, lineIndex) in payload.lines" :key="`${payload.taskId}-${line.line_no || lineIndex}`">
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ lineIndex + 1 }}</td>
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ line.reservation_id || '-' }}</td>
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ line.sku }}</td>
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ line.part_number }}</td>
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ line.customer_part_number || '-' }}</td>
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ line.aws_part_number || '-' }}</td>
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ line.qty }}</td>
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ line.required_date || '-' }}</td>
|
||||
<td class="border border-default px-3 py-2">
|
||||
@@ -251,8 +270,20 @@ const removeLine = async (lineIndex: number) => {
|
||||
<input v-model="lineForm.reservation_id" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.sku') }}</span>
|
||||
<input v-model="lineForm.sku" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.partNumber') }}</span>
|
||||
<input v-model="lineForm.part_number" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.customerPartNumber') }}</span>
|
||||
<input v-model="lineForm.customer_part_number" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.awsPartNumber') }}</span>
|
||||
<input v-model="lineForm.aws_part_number" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.inventorySourceHint') }}</span>
|
||||
<input v-model="lineForm.inventory_source_hint" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.qty') }}</span>
|
||||
@@ -291,8 +322,20 @@ const removeLine = async (lineIndex: number) => {
|
||||
<input v-model="lineForm.reservation_id" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.sku') }}</span>
|
||||
<input v-model="lineForm.sku" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.partNumber') }}</span>
|
||||
<input v-model="lineForm.part_number" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.customerPartNumber') }}</span>
|
||||
<input v-model="lineForm.customer_part_number" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.awsPartNumber') }}</span>
|
||||
<input v-model="lineForm.aws_part_number" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.inventorySourceHint') }}</span>
|
||||
<input v-model="lineForm.inventory_source_hint" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.qty') }}</span>
|
||||
|
||||
@@ -60,20 +60,20 @@ const emit = defineEmits<{
|
||||
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<div class="text-[11px] font-bold uppercase tracking-[0.15em] text-brand-600/80">
|
||||
{{ $t('chat.training.stepExamTitle') }}
|
||||
第三步:逐题考试
|
||||
</div>
|
||||
<h3 class="mt-1 text-lg font-bold text-slate-800">
|
||||
{{ $t('chat.training.exam.questionCounter', { current: currentQuestionIndex + 1, total: totalCount }) }}
|
||||
第 {{ currentQuestionIndex + 1 }} / {{ totalCount }} 题
|
||||
</h3>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2 text-[13px]">
|
||||
<div class="rounded-lg bg-slate-50 px-3 py-1.5 font-medium text-slate-600 border border-slate-100 flex items-center gap-2">
|
||||
<span>{{ $t('chat.training.currentScoreLabel') }}</span>
|
||||
<span class="text-slate-800 font-bold">{{ $t('chat.training.scoreShort', { score }) }}</span>
|
||||
<span>当前分数:</span>
|
||||
<span class="text-slate-800 font-bold">{{ score }} 分</span>
|
||||
</div>
|
||||
<div class="rounded-lg bg-slate-50 px-3 py-1.5 font-medium text-slate-600 border border-slate-100 flex items-center gap-2">
|
||||
<span>{{ $t('chat.training.passLineLabel') }}</span>
|
||||
<span class="text-slate-800 font-bold">{{ $t('chat.training.passScoreShort', { passScore }) }}</span>
|
||||
<span>及格线:</span>
|
||||
<span class="text-slate-800 font-bold">{{ passScore }} 分</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -158,16 +158,16 @@ const emit = defineEmits<{
|
||||
<div class="flex items-center gap-2 text-sm font-bold" :class="feedbackCorrect ? 'text-emerald-700' : 'text-red-700'">
|
||||
<CheckCircle2 v-if="feedbackCorrect" class="h-4 w-4" />
|
||||
<XCircle v-else class="h-4 w-4" />
|
||||
{{ feedbackCorrect ? $t('chat.training.exam.correctFeedback') : $t('chat.training.wrongFeedbackShort') }}
|
||||
{{ feedbackCorrect ? '回答正确,继续下一题' : '回答错误' }}
|
||||
</div>
|
||||
|
||||
<div class="mt-3 space-y-2 text-[13px] leading-6 text-slate-600">
|
||||
<div class="flex gap-2">
|
||||
<span class="font-medium text-slate-500 shrink-0">{{ $t('chat.training.yourAnswerLabel') }}</span>
|
||||
<span class="font-medium text-slate-500 shrink-0">你的答案:</span>
|
||||
<span class="font-medium" :class="feedbackCorrect ? 'text-emerald-600' : 'text-red-600'">{{ answerLabel || '--' }}</span>
|
||||
</div>
|
||||
<div v-if="!feedbackCorrect" class="flex gap-2">
|
||||
<span class="font-medium text-slate-500 shrink-0">{{ $t('chat.training.correctAnswerLabel') }}</span>
|
||||
<span class="font-medium text-slate-500 shrink-0">正确答案:</span>
|
||||
<span class="text-emerald-600 font-medium">{{ question.options?.find(o => o.id === question.answer)?.label || '--' }}</span>
|
||||
</div>
|
||||
<div class="mt-2 pl-2 border-l-2 border-slate-200/60 text-slate-500/90">
|
||||
@@ -183,7 +183,7 @@ const emit = defineEmits<{
|
||||
@click="emit('next')"
|
||||
>
|
||||
<ClipboardCheck class="h-4 w-4" />
|
||||
{{ answeredCount >= totalCount - 1 ? $t('chat.training.finishAndViewResult') : $t('chat.training.exam.nextQuestion') }}
|
||||
{{ answeredCount >= totalCount - 1 ? '完成考试并查看结果' : '下一题' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -33,10 +33,10 @@ const emit = defineEmits<{
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-[11px] font-bold uppercase tracking-[0.15em] text-slate-500">
|
||||
{{ $t('chat.training.stepResultTitle') }}
|
||||
第四步:结算结果
|
||||
</div>
|
||||
<h3 class="text-lg font-bold text-slate-800">
|
||||
{{ isPassed ? $t('chat.training.passTitleShort') : $t('chat.training.failTitleShort') }}
|
||||
{{ isPassed ? '恭喜,你已通过考核!' : '很遗憾,考试未通过' }}
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
@@ -59,7 +59,7 @@ const emit = defineEmits<{
|
||||
<div class="mt-1 text-2xl font-black text-emerald-600">{{ correctCount }}</div>
|
||||
</div>
|
||||
<div class="rounded-2xl bg-red-50/50 p-4 border border-red-100/50 text-center">
|
||||
<div class="text-[11px] font-bold text-red-400 uppercase">{{ $t('chat.training.wrongCountShort') }}</div>
|
||||
<div class="text-[11px] font-bold text-red-400 uppercase">答错</div>
|
||||
<div class="mt-1 text-2xl font-black text-red-500">{{ wrongCount }}</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -78,12 +78,12 @@ const emit = defineEmits<{
|
||||
@click="emit('restart')"
|
||||
>
|
||||
<RotateCcw class="h-4 w-4" />
|
||||
{{ $t('chat.training.result.retryExam') }}
|
||||
重新考试
|
||||
</button>
|
||||
</div>
|
||||
<div v-else class="flex items-center gap-2 text-emerald-600 font-medium text-sm">
|
||||
<CheckCircle2 class="h-4 w-4" />
|
||||
{{ $t('chat.training.syncedToHr') }}
|
||||
成绩已同步至 HR 管理系统
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -30,7 +30,7 @@ const emit = defineEmits<{
|
||||
<div class="h-12 w-12 flex items-center justify-center rounded-full bg-white/20 backdrop-blur-md border border-white/30 group-hover:bg-brand-600 group-hover:border-brand-500 transition-all duration-300">
|
||||
<PlayCircle class="h-6 w-6 text-white fill-white/20" />
|
||||
</div>
|
||||
<span class="text-white text-xs font-medium drop-shadow-md">{{ $t('chat.training.clickPlayVideo') }}</span>
|
||||
<span class="text-white text-xs font-medium drop-shadow-md">点击播放视频</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
<!--
|
||||
features/chat/components/messages/TransferBacklogSummaryCard.vue
|
||||
用途:待处理异常卡(可恢复/已关闭/结果未知三组)+ 人工重试/人工关闭入口。
|
||||
依赖:props.items、i18n chat.transfer.*。
|
||||
逻辑:result_unknown 只读(无重试/关闭按钮);人工关闭由父组件弹窗处理。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import type { TransferBacklogItem } from '../../types/transfer.types';
|
||||
|
||||
defineProps<{
|
||||
items: TransferBacklogItem[];
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
retry: [itemId: number];
|
||||
close: [item: TransferBacklogItem];
|
||||
refresh: [];
|
||||
}>();
|
||||
|
||||
function agingLabel(level: string): string {
|
||||
const map: Record<string, string> = {
|
||||
warn_3d: 'chat.transfer.agingWarn',
|
||||
escalate_5d: 'chat.transfer.agingEscalate',
|
||||
critical_7d: 'chat.transfer.agingCritical',
|
||||
result_unknown: 'chat.transfer.resultUnknown',
|
||||
closed: 'chat.transfer.statusClosed',
|
||||
};
|
||||
return map[level] ?? 'chat.transfer.agingNormal';
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="my-2 rounded-2xl border border-brand-100 bg-surface p-4 shadow-sm" data-testid="transfer-backlog-card">
|
||||
<div class="mb-2 flex items-center justify-between">
|
||||
<h3 class="text-sm font-bold text-primary">{{ $t('chat.transfer.backlogTitle') }}</h3>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default px-2 py-1 text-xs text-secondary hover-surface-soft"
|
||||
data-testid="transfer-backlog-refresh"
|
||||
@click="emit('refresh')"
|
||||
>
|
||||
{{ $t('chat.transfer.refreshProgress') }}
|
||||
</button>
|
||||
</div>
|
||||
<ul v-if="items.length" class="flex flex-col gap-1.5">
|
||||
<li
|
||||
v-for="item in items"
|
||||
:key="item.item_id"
|
||||
class="flex items-center justify-between gap-2 rounded-lg border border-subtle px-3 py-2 text-xs"
|
||||
:data-testid="`transfer-backlog-${item.invoice_no}`"
|
||||
>
|
||||
<div class="min-w-0">
|
||||
<div class="font-semibold text-secondary">
|
||||
{{ item.invoice_no }}
|
||||
<span class="ml-1 text-muted">{{ item.source_code }}</span>
|
||||
</div>
|
||||
<div class="text-[11px] text-muted">
|
||||
{{ item.reason }} · {{ $t(agingLabel(item.aging_level)) }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex shrink-0 gap-1.5">
|
||||
<template v-if="item.status === 'blocked_recoverable'">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-brand-200 px-2 py-1 font-bold text-brand-700 hover:bg-brand-50"
|
||||
data-testid="transfer-backlog-retry"
|
||||
@click="emit('retry', item.item_id)"
|
||||
>
|
||||
{{ $t('chat.transfer.retryErp') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-red-200 px-2 py-1 font-bold text-red-600 hover:bg-red-50"
|
||||
data-testid="transfer-backlog-close"
|
||||
@click="emit('close', item)"
|
||||
>
|
||||
{{ $t('chat.transfer.manualClose') }}
|
||||
</button>
|
||||
</template>
|
||||
<span v-else-if="item.status === 'result_unknown'" class="text-[11px] text-muted">
|
||||
{{ $t('chat.transfer.resultUnknownReadonly') }}
|
||||
</span>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
<div v-else class="rounded-lg bg-surface-soft p-3 text-xs text-muted">
|
||||
{{ $t('chat.transfer.noBacklog') }}
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,50 @@
|
||||
<!--
|
||||
features/chat/components/messages/TransferFileProgressCard.vue
|
||||
用途:来源实例级收料文件准备进度(决策 18:来源隔离展示,不伪造总百分比)。
|
||||
依赖:props.sources、i18n chat.transfer.*。
|
||||
逻辑:按来源显示 file_ready / waiting_rpa_callback / failed 阶段与文件信息。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import type { TransferSourceProgress } from '../../types/transfer.types';
|
||||
|
||||
defineProps<{
|
||||
sources: TransferSourceProgress[];
|
||||
}>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="my-2 rounded-2xl border border-brand-100 bg-surface p-4 shadow-sm"
|
||||
data-testid="transfer-file-progress-card"
|
||||
>
|
||||
<h3 class="mb-3 text-sm font-bold text-primary">{{ $t('chat.transfer.fileProgressTitle') }}</h3>
|
||||
<ul class="flex flex-col gap-2">
|
||||
<li
|
||||
v-for="source in sources"
|
||||
:key="source.source_code"
|
||||
class="flex items-center justify-between rounded-lg border border-subtle px-3 py-2"
|
||||
:data-testid="`transfer-source-${source.source_code}`"
|
||||
>
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm font-semibold text-secondary">{{ source.source_code }}</div>
|
||||
<div v-if="source.file_no" class="truncate text-xs text-muted">
|
||||
{{ source.file_no }}<template v-if="source.file_version"> · v{{ source.file_version }}</template>
|
||||
</div>
|
||||
<div v-else-if="source.error_message" class="truncate text-xs text-red-500">{{ source.error_message }}</div>
|
||||
</div>
|
||||
<span
|
||||
class="shrink-0 rounded-full px-2 py-0.5 text-xs font-bold"
|
||||
:class="{
|
||||
'bg-emerald-50 text-emerald-700': source.stage === 'file_ready',
|
||||
'bg-amber-50 text-amber-700': source.stage === 'waiting_rpa_callback',
|
||||
'bg-red-50 text-red-700': source.stage === 'failed',
|
||||
}"
|
||||
>
|
||||
<template v-if="source.stage === 'file_ready'">{{ $t('chat.transfer.stageFileReady') }}</template>
|
||||
<template v-else-if="source.stage === 'waiting_rpa_callback'">{{ $t('chat.transfer.stageWaitingRpa') }}</template>
|
||||
<template v-else>{{ $t('chat.transfer.stageFailed') }}</template>
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* features/chat/components/messages/TransferHomePanel.spec.ts
|
||||
* 用途:验证在途仓自动调拨 Agent 的 Chat 首页入口区——
|
||||
* home 视图渲染“今日待办 + 历史待办”计数卡;点击入口独立触发
|
||||
* source-select / backlog 卡片(复用自驱动的 TransferMessageView,不注入消息流)。
|
||||
* 依赖:vi.mock(transfer.api)、@vue/test-utils、i18n。
|
||||
* 逻辑:Mock API 断言入口切换与计数展示;对应后端 backlog/summary 契约面。
|
||||
*/
|
||||
import { mount, flushPromises } from '@vue/test-utils';
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import i18n from '@/i18n';
|
||||
|
||||
const api = vi.hoisted(() => ({
|
||||
createTransferPrecheck: vi.fn(),
|
||||
getTransferPrecheck: vi.fn(),
|
||||
executeTransferPrecheck: vi.fn(),
|
||||
getTransferRun: vi.fn(),
|
||||
retryTransferItem: vi.fn(),
|
||||
manualCloseTransferItem: vi.fn(),
|
||||
downloadTransferReceiptFiles: vi.fn(),
|
||||
downloadTransferErpInventory: vi.fn(),
|
||||
downloadTransferExceptions: vi.fn(),
|
||||
listTransferBacklog: vi.fn(),
|
||||
getTransferBacklogSummary: vi.fn(),
|
||||
listTransferSources: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/api/transfer.api', () => api);
|
||||
|
||||
import TransferHomePanel from './TransferHomePanel.vue';
|
||||
|
||||
function mountHome() {
|
||||
return mount(TransferHomePanel, {
|
||||
props: { agentName: '在途仓自动调拨' },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('TransferHomePanel chat home entry', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
api.getTransferBacklogSummary.mockResolvedValue({
|
||||
recoverable: 6, closed: 2, unknown: 1, aging: { warn_3d: 3, escalate_5d: 2, critical_7d: 1 },
|
||||
});
|
||||
api.listTransferBacklog.mockResolvedValue([]);
|
||||
api.listTransferSources.mockResolvedValue([
|
||||
{ source_code: 'DBS-AWSBI', display_name: 'AWSBI', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('home 视图渲染标题、今日待办入口与三张历史待办计数卡', async () => {
|
||||
const wrapper = mountHome();
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="transfer-home"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="transfer-home-today"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="transfer-home-recoverable"]').text()).toContain('6');
|
||||
expect(wrapper.find('[data-testid="transfer-home-closed"]').text()).toContain('2');
|
||||
expect(wrapper.find('[data-testid="transfer-home-unknown"]').text()).toContain('1');
|
||||
expect(api.getTransferBacklogSummary).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('点击“发起今日调拨预检”独立触发来源选择卡(复用 TransferMessageView)', async () => {
|
||||
api.createTransferPrecheck.mockResolvedValue({
|
||||
precheck_id: 'TPC-1', status: 'ready_to_execute', business_date: '2026-08-06',
|
||||
eligible_receipt_date_to: '2026-08-05', expires_at: '',
|
||||
counts: { file_invoice_count: 1, not_matured_count: 0, prechecked_count: 1, executable_count: 1, blocked_count: 0 },
|
||||
estimated_transfer_quantity: '1200', estimated_erp_write_count: 1, precheck_hash: 'sha256:x',
|
||||
});
|
||||
api.getTransferPrecheck.mockResolvedValue({
|
||||
summary: {
|
||||
precheck_id: 'TPC-1', status: 'ready_to_execute', business_date: '2026-08-06',
|
||||
eligible_receipt_date_to: '2026-08-05', expires_at: '',
|
||||
counts: { file_invoice_count: 1, not_matured_count: 0, prechecked_count: 1, executable_count: 1, blocked_count: 0 },
|
||||
estimated_transfer_quantity: '1200', estimated_erp_write_count: 1, precheck_hash: 'sha256:x',
|
||||
},
|
||||
items: [{
|
||||
source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: '连接器组件', specification: 'A',
|
||||
invoice_no: 'INV-001', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200',
|
||||
to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable',
|
||||
}],
|
||||
sources: [{ source_code: 'DBS-AWSBI', stage: 'file_ready', file_no: 'REC-1' }],
|
||||
});
|
||||
|
||||
const wrapper = mountHome();
|
||||
await flushPromises();
|
||||
await wrapper.find('[data-testid="transfer-home-today"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="transfer-source-select-card"]').exists()).toBe(true);
|
||||
expect(api.listTransferSources).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('点击历史待办计数卡独立触发 backlog 卡片', async () => {
|
||||
api.listTransferBacklog.mockResolvedValue([
|
||||
{ item_id: 7, source_code: 'DBS-AWSBI', invoice_no: 'INV-001', material_no: 'MAT-1',
|
||||
status: 'blocked_recoverable', reason: '收料 1200 / ERP 1000', age_days: 1, aging_level: 'normal' },
|
||||
]);
|
||||
|
||||
const wrapper = mountHome();
|
||||
await flushPromises();
|
||||
await wrapper.find('[data-testid="transfer-home-recoverable"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="transfer-backlog-card"]').exists()).toBe(true);
|
||||
expect(api.listTransferBacklog).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('子视图提供“返回首页”并切回 home', async () => {
|
||||
const wrapper = mountHome();
|
||||
await flushPromises();
|
||||
await wrapper.find('[data-testid="transfer-home-today"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="transfer-source-select-card"]').exists()).toBe(true);
|
||||
|
||||
await wrapper.find('[data-testid="transfer-home-back"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="transfer-home"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('进入子流程时冒泡 flow-active=true,返回首页时 false(父级据此隐藏聊天输入框)', async () => {
|
||||
const wrapper = mountHome();
|
||||
await flushPromises();
|
||||
expect(wrapper.emitted('flow-active')?.[0]?.[0]).toBe(false);
|
||||
|
||||
await wrapper.find('[data-testid="transfer-home-today"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(wrapper.emitted('flow-active')?.at(-1)?.[0]).toBe(true);
|
||||
|
||||
await wrapper.find('[data-testid="transfer-home-back"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(wrapper.emitted('flow-active')?.at(-1)?.[0]).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
<!--
|
||||
features/chat/components/messages/TransferHomePanel.vue
|
||||
用途:在途仓自动调拨 Agent 的 Chat 首页入口区——home 视图展示标题、今日待办
|
||||
入口与三张历史待办计数卡;点击入口独立触发 source-select / backlog 卡片。
|
||||
依赖:TransferMessageView(复用自驱动卡片)、useChatTransfer、i18n chat.transfer.*。
|
||||
逻辑:home 时只消费 backlogSummary 计数;非 home 时渲染 TransferMessageView。
|
||||
卡片不注入消息流,因此无需后端 ChatLog 消息(决策:补首页入口 A 方案)。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
import TransferMessageView from './TransferMessageView.vue';
|
||||
import { useChatTransfer } from '../../composables/useChatTransfer';
|
||||
|
||||
const props = defineProps<{
|
||||
agentName?: string;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
/** 业务流激活状态:true 表示进入来源选择/待处理等子视图(父级据此隐藏聊天输入框)。 */
|
||||
'flow-active': [active: boolean];
|
||||
}>();
|
||||
|
||||
type HomeView = 'home' | 'source-select' | 'backlog';
|
||||
|
||||
const transfer = useChatTransfer();
|
||||
const view = ref<HomeView>('home');
|
||||
|
||||
/** 进入非 home 时通知父级隐藏聊天输入框(决策:来源选择为业务页,无对话输入区)。 */
|
||||
watch(view, (value) => emit('flow-active', value !== 'home'), { immediate: true });
|
||||
|
||||
/** home 视图仅需要待办汇总;进入时拉取计数。 */
|
||||
async function loadHomeSummary() {
|
||||
if (view.value !== 'home') return;
|
||||
await transfer.loadBacklog();
|
||||
}
|
||||
|
||||
onMounted(() => { void loadHomeSummary(); });
|
||||
watch(view, () => { void loadHomeSummary(); });
|
||||
|
||||
const displayAgentName = computed(() => props.agentName || '在途仓自动调拨');
|
||||
|
||||
/** 非 home 视图把当前入口透传给自驱动的 TransferMessageView(决定 source-select 或 backlog)。 */
|
||||
const childPayload = computed(() => (
|
||||
view.value === 'source-select'
|
||||
? { kind: 'source-select' }
|
||||
: { kind: 'backlog' }
|
||||
));
|
||||
|
||||
function goBack() {
|
||||
view.value = 'home';
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex w-full flex-col items-center px-4 pb-2 pt-6 md:pb-4">
|
||||
<!-- home:标题 + 今日/历史待办入口 -->
|
||||
<template v-if="view === 'home'">
|
||||
<h2 data-testid="transfer-home" class="mb-8 mt-6 shrink-0 text-center text-2xl font-bold text-primary md:mt-10 md:text-3xl">
|
||||
{{ $t('chat.transfer.homeWelcome') }}
|
||||
<span class="mx-1 text-brand-600">{{ displayAgentName }}</span>
|
||||
</h2>
|
||||
|
||||
<div class="w-full max-w-3xl space-y-4">
|
||||
<!-- 今日待办 -->
|
||||
<section aria-label="今日待办">
|
||||
<p class="mb-2 text-sm font-bold text-secondary">{{ $t('chat.transfer.homeTodayLabel') }}</p>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="transfer-home-today"
|
||||
class="flex w-full items-center gap-3 rounded-2xl border border-brand-200 bg-brand-50 p-4 text-left transition-colors hover:bg-brand-100"
|
||||
@click="view = 'source-select'"
|
||||
>
|
||||
<span class="grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-brand-600 text-lg font-bold text-white">+</span>
|
||||
<span class="min-w-0 flex-1">
|
||||
<b class="block text-sm font-bold text-brand-700">{{ $t('chat.transfer.homeTodayAction') }}</b>
|
||||
<span class="mt-1 block text-xs text-brand-600/80">{{ $t('chat.transfer.homeTodayHint') }}</span>
|
||||
</span>
|
||||
<span class="shrink-0 text-xl text-brand-600">›</span>
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<!-- 历史待办 -->
|
||||
<section aria-label="历史待办">
|
||||
<p class="mb-2 text-sm font-bold text-secondary">{{ $t('chat.transfer.homeHistoryLabel') }}</p>
|
||||
<div class="grid grid-cols-1 gap-3 sm:grid-cols-3">
|
||||
<button
|
||||
type="button"
|
||||
data-testid="transfer-home-recoverable"
|
||||
class="rounded-2xl border border-brand-200 bg-brand-50 p-4 text-left transition-colors hover:bg-brand-100"
|
||||
@click="view = 'backlog'"
|
||||
>
|
||||
<b class="block text-2xl leading-none text-brand-600">{{ transfer.backlogSummary.value?.recoverable ?? 0 }}</b>
|
||||
<b class="mt-2 block text-sm font-bold text-primary">{{ $t('chat.transfer.homeRecoverable') }}</b>
|
||||
<span class="mt-1 block text-xs text-secondary">{{ $t('chat.transfer.homeRecoverableHint') }}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="transfer-home-closed"
|
||||
class="rounded-2xl border border-default bg-surface p-4 text-left transition-colors hover:border-brand-200 hover:bg-brand-50"
|
||||
@click="view = 'backlog'"
|
||||
>
|
||||
<b class="block text-2xl leading-none text-secondary">{{ transfer.backlogSummary.value?.closed ?? 0 }}</b>
|
||||
<b class="mt-2 block text-sm font-bold text-primary">{{ $t('chat.transfer.homeClosed') }}</b>
|
||||
<span class="mt-1 block text-xs text-secondary">{{ $t('chat.transfer.homeClosedHint') }}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="transfer-home-unknown"
|
||||
class="rounded-2xl border border-amber-200 bg-amber-50 p-4 text-left transition-colors hover:bg-amber-100"
|
||||
@click="view = 'backlog'"
|
||||
>
|
||||
<b class="block text-2xl leading-none text-amber-600">{{ transfer.backlogSummary.value?.unknown ?? 0 }}</b>
|
||||
<b class="mt-2 block text-sm font-bold text-primary">{{ $t('chat.transfer.homeUnknown') }}</b>
|
||||
<span class="mt-1 block text-xs text-secondary">{{ $t('chat.transfer.homeUnknownHint') }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 子流程:复用自驱动的 TransferMessageView -->
|
||||
<div v-else class="w-full max-w-4xl pr-2">
|
||||
<button
|
||||
type="button"
|
||||
data-testid="transfer-home-back"
|
||||
class="mb-2 rounded-lg px-2 py-1 text-sm font-bold text-brand-600 transition-colors hover:bg-brand-50"
|
||||
@click="goBack"
|
||||
>
|
||||
← {{ $t('chat.transfer.homeBack') }}
|
||||
</button>
|
||||
<TransferMessageView :payload="childPayload" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,67 @@
|
||||
<!--
|
||||
features/chat/components/messages/TransferManualCloseDialog.vue
|
||||
用途:人工关闭弹窗(原因必填;关闭后永久排除,历史保留)。
|
||||
依赖:props(open/invoiceNo)、i18n chat.transfer.*。
|
||||
逻辑:原因为空时确认按钮禁用;确认时 emit confirm(reason)。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue';
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
invoiceNo: string;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
confirm: [reason: string];
|
||||
cancel: [];
|
||||
}>();
|
||||
|
||||
const reason = ref('');
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
(open) => {
|
||||
if (open) reason.value = '';
|
||||
},
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 p-4"
|
||||
data-testid="transfer-manual-close-dialog"
|
||||
>
|
||||
<div class="w-full max-w-md rounded-2xl bg-surface p-5 shadow-xl">
|
||||
<h3 class="text-base font-bold text-primary">{{ $t('chat.transfer.manualCloseTitle') }}</h3>
|
||||
<p class="mt-1 text-xs text-muted">{{ invoiceNo }} · {{ $t('chat.transfer.manualCloseHint') }}</p>
|
||||
<textarea
|
||||
v-model="reason"
|
||||
rows="3"
|
||||
class="mt-3 w-full rounded-lg border border-default p-2 text-sm"
|
||||
:placeholder="$t('chat.transfer.closeReasonPlaceholder')"
|
||||
data-testid="transfer-close-reason"
|
||||
/>
|
||||
<div class="mt-4 flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default px-4 py-1.5 text-sm text-secondary hover-surface-soft"
|
||||
data-testid="transfer-close-cancel"
|
||||
@click="emit('cancel')"
|
||||
>
|
||||
{{ $t('chat.transfer.cancel') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg bg-brand-600 px-4 py-1.5 text-sm font-bold text-white hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
:disabled="!reason.trim()"
|
||||
data-testid="transfer-close-confirm"
|
||||
@click="emit('confirm', reason.trim())"
|
||||
>
|
||||
{{ $t('chat.transfer.confirmClose') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* features/chat/components/messages/TransferMessageView.spec.ts
|
||||
* 用途:验证卡片自驱动接线——预检卡渲染、点“直接生成调拨单”真实调 API 并切换结果卡、
|
||||
* 下载按钮调 requestBlob 封装、结果页无审计入口。
|
||||
* 依赖:vi.mock(transfer.api)、@vue/test-utils、i18n。
|
||||
* 逻辑:Mock API 断言调用参数与状态切换(对应后端 197 项测试的契约面)。
|
||||
*/
|
||||
import { mount, flushPromises } from '@vue/test-utils';
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import i18n from '@/i18n';
|
||||
|
||||
const api = vi.hoisted(() => ({
|
||||
createTransferPrecheck: vi.fn(),
|
||||
getTransferPrecheck: vi.fn(),
|
||||
executeTransferPrecheck: vi.fn(),
|
||||
getTransferRun: vi.fn(),
|
||||
retryTransferItem: vi.fn(),
|
||||
manualCloseTransferItem: vi.fn(),
|
||||
downloadTransferReceiptFiles: vi.fn(),
|
||||
downloadTransferErpInventory: vi.fn(),
|
||||
downloadTransferExceptions: vi.fn(),
|
||||
listTransferBacklog: vi.fn(),
|
||||
getTransferBacklogSummary: vi.fn(),
|
||||
listTransferSources: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/api/transfer.api', () => api);
|
||||
|
||||
import TransferMessageView from './TransferMessageView.vue';
|
||||
|
||||
const payload = {
|
||||
kind: 'precheck',
|
||||
summary: {
|
||||
precheck_id: 'TPC-1',
|
||||
status: 'ready_to_execute',
|
||||
business_date: '2026-08-06',
|
||||
eligible_receipt_date_to: '2026-08-05',
|
||||
expires_at: '',
|
||||
counts: { file_invoice_count: 1, not_matured_count: 0, prechecked_count: 1, executable_count: 1, blocked_count: 0 },
|
||||
estimated_transfer_quantity: '1200',
|
||||
estimated_erp_write_count: 1,
|
||||
precheck_hash: 'sha256:x',
|
||||
},
|
||||
items: [{
|
||||
source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: '连接器组件', specification: 'A',
|
||||
invoice_no: 'INV-001', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200',
|
||||
to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable',
|
||||
}],
|
||||
sources: [{ source_code: 'DBS-AWSBI', stage: 'file_ready', file_no: 'REC-1' }],
|
||||
};
|
||||
|
||||
const runPayload = {
|
||||
kind: 'result',
|
||||
run_no: 'RUN-1',
|
||||
status: 'success',
|
||||
run: {
|
||||
run_no: 'RUN-1',
|
||||
status: 'success',
|
||||
result: {
|
||||
erp_documents: [{
|
||||
document_no: 'TRF-10001', from_warehouse: 'DBS-TRANSIT', to_warehouse: 'HUB-CN01',
|
||||
material_count: 1, total_quantity: '1200', posting_status: 'posted',
|
||||
lines: [{ material_no: 'MAT-1', material_name: '连接器组件', specification: 'A', invoice_no: 'INV-001', quantity: '1200' }],
|
||||
}],
|
||||
exceptions: [],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
describe('TransferMessageView self-driving wiring', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
api.executeTransferPrecheck.mockResolvedValue({ run_no: 'RUN-1', status: 'success' });
|
||||
api.getTransferRun.mockResolvedValue(runPayload.run);
|
||||
api.downloadTransferReceiptFiles.mockResolvedValue({ blob: new Blob(['z']), filename: 'r.zip' });
|
||||
api.downloadTransferErpInventory.mockResolvedValue({ blob: new Blob(['c']), filename: 'e.csv' });
|
||||
});
|
||||
|
||||
it('预检 payload 渲染预检卡,且默认勾选可执行项', () => {
|
||||
const wrapper = mount(TransferMessageView, {
|
||||
props: { payload },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="transfer-precheck-card"]').exists()).toBe(true);
|
||||
expect((wrapper.find('[data-testid="transfer-check-INV-001"]').element as HTMLInputElement).checked).toBe(true);
|
||||
});
|
||||
|
||||
it('点击“直接生成调拨单”调用 execute API 并切换为结果卡', async () => {
|
||||
const wrapper = mount(TransferMessageView, {
|
||||
props: { payload },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await wrapper.find('[data-testid="transfer-generate-button"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(api.executeTransferPrecheck).toHaveBeenCalledWith('TPC-1', ['INV-001']);
|
||||
expect(wrapper.find('[data-testid="transfer-result-card"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('结果卡下载按钮调用下载 API(收料来源文件 + ERP 库存表)', async () => {
|
||||
const wrapper = mount(TransferMessageView, {
|
||||
props: { payload: runPayload },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await wrapper.find('[data-testid="transfer-download-receipt"]').trigger('click');
|
||||
await wrapper.find('[data-testid="transfer-download-erp"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(api.downloadTransferReceiptFiles).toHaveBeenCalledWith('RUN-1');
|
||||
expect(api.downloadTransferErpInventory).toHaveBeenCalledWith('RUN-1');
|
||||
});
|
||||
|
||||
it('结果卡不出现执行审计入口(决策 19)', () => {
|
||||
const wrapper = mount(TransferMessageView, {
|
||||
props: { payload: runPayload },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.text()).not.toContain('审计');
|
||||
});
|
||||
|
||||
it('backlog 视图拉取待处理列表,重试/关闭调用对应 API', async () => {
|
||||
api.listTransferBacklog.mockResolvedValue([{
|
||||
item_id: 7, source_code: 'DBS-AWSBI', invoice_no: 'INV-001', material_no: 'MAT-1',
|
||||
status: 'blocked_recoverable', reason: '收料 1200 / ERP 1000', age_days: 1, aging_level: 'normal',
|
||||
}]);
|
||||
api.getTransferBacklogSummary.mockResolvedValue({
|
||||
recoverable: 1, closed: 0, unknown: 0, aging: { warn_3d: 0, escalate_5d: 0, critical_7d: 0 },
|
||||
});
|
||||
api.retryTransferItem.mockResolvedValue({ item_id: 7, status: 'ready_to_execute', attempt_no: 2 });
|
||||
api.manualCloseTransferItem.mockResolvedValue({ item_id: 7, status: 'manually_closed' });
|
||||
|
||||
const wrapper = mount(TransferMessageView, {
|
||||
props: { payload: { kind: 'backlog' } },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="transfer-backlog-card"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('INV-001');
|
||||
|
||||
await wrapper.find('[data-testid="transfer-backlog-retry"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(api.retryTransferItem).toHaveBeenCalledWith(7);
|
||||
|
||||
await wrapper.find('[data-testid="transfer-backlog-close"]').trigger('click');
|
||||
await wrapper.find('[data-testid="transfer-close-reason"]').setValue('线下已处理');
|
||||
await wrapper.find('[data-testid="transfer-close-confirm"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(api.manualCloseTransferItem).toHaveBeenCalledWith(7, '线下已处理');
|
||||
});
|
||||
|
||||
it('来源实例选择:加载列表 → 确认范围 → 创建预检并切换预检卡', async () => {
|
||||
api.listTransferSources.mockResolvedValue([
|
||||
{ source_code: 'DBS-AWSBI', display_name: 'AWSBI', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' },
|
||||
]);
|
||||
api.createTransferPrecheck.mockResolvedValue(payload.summary);
|
||||
api.getTransferPrecheck.mockResolvedValue({
|
||||
summary: payload.summary,
|
||||
items: payload.items,
|
||||
sources: payload.sources,
|
||||
});
|
||||
|
||||
const wrapper = mount(TransferMessageView, {
|
||||
props: { payload: { kind: 'source-select' } },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="transfer-source-select-card"]').exists()).toBe(true);
|
||||
|
||||
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSBI"] input').setValue(true);
|
||||
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(api.createTransferPrecheck).toHaveBeenCalledWith({ source_codes: ['DBS-AWSBI'] });
|
||||
expect(wrapper.find('[data-testid="transfer-precheck-card"]').exists()).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,243 @@
|
||||
<!--
|
||||
features/chat/components/messages/TransferMessageView.vue
|
||||
用途:在途调拨消息卡片的自驱动挂载视图——按 payload 形态渲染卡片,并把卡片按钮
|
||||
(直接生成调拨单 / 下载 / 重试 / 关闭)经 useChatTransfer 真实调用 API。
|
||||
依赖:Transfer*Card、useChatTransfer、i18n chat.transfer.*。
|
||||
逻辑:payload 作为初始状态(ChatLog 回放);执行后切换为结果卡;下载走 requestBlob;
|
||||
不展示执行审计入口(决策 19)。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
import TransferPrecheckCard from './TransferPrecheckCard.vue';
|
||||
import TransferFileProgressCard from './TransferFileProgressCard.vue';
|
||||
import TransferProgressCard from './TransferProgressCard.vue';
|
||||
import TransferResultCard from './TransferResultCard.vue';
|
||||
import TransferBacklogSummaryCard from './TransferBacklogSummaryCard.vue';
|
||||
import TransferManualCloseDialog from './TransferManualCloseDialog.vue';
|
||||
import TransferSourceSelectCard from './TransferSourceSelectCard.vue';
|
||||
import { useChatTransfer } from '../../composables/useChatTransfer';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import type {
|
||||
TransferBacklogItem,
|
||||
TransferPrecheckItem,
|
||||
TransferPrecheckSummary,
|
||||
TransferRunResult,
|
||||
TransferSourceProgress,
|
||||
} from '../../types/transfer.types';
|
||||
|
||||
const props = defineProps<{
|
||||
payload?: Record<string, unknown> | null;
|
||||
}>();
|
||||
|
||||
const { error: notifyError } = useMessage();
|
||||
|
||||
/** 统一错误提示:BusinessError 带本地化 message,其余回退到 String(e)。 */
|
||||
function reportError(e: unknown) {
|
||||
notifyError(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
|
||||
const kind = computed(() => String(props.payload?.kind ?? 'precheck'));
|
||||
const mode = ref(kind.value);
|
||||
const summaryRef = ref<TransferPrecheckSummary | null>((props.payload?.summary as TransferPrecheckSummary) ?? null);
|
||||
const items = ref<TransferPrecheckItem[]>((props.payload?.items as TransferPrecheckItem[]) ?? []);
|
||||
const runNo = ref(String(props.payload?.run_no ?? ''));
|
||||
const status = ref(String(props.payload?.status ?? 'executing'));
|
||||
const run = ref<TransferRunResult | null>((props.payload?.run as TransferRunResult) ?? null);
|
||||
const busy = ref(false);
|
||||
const closeTarget = ref<TransferBacklogItem | null>(null);
|
||||
/** 正在重试收料 RPA 的来源编码集合(按来源独立展示重试中)。 */
|
||||
const retryingSource = ref<Set<string>>(new Set());
|
||||
|
||||
const transfer = useChatTransfer();
|
||||
|
||||
/** 待处理异常视图:进入时拉取列表与汇总 */
|
||||
onMounted(() => {
|
||||
if (kind.value === 'backlog') {
|
||||
void transfer.loadBacklog();
|
||||
}
|
||||
if (kind.value === 'source-select') {
|
||||
void transfer.loadSources();
|
||||
}
|
||||
});
|
||||
|
||||
/** payload 更新时重置本地状态(历史回放/刷新);初始化组合式函数上下文 */
|
||||
function applyPayload(payload?: Record<string, unknown> | null) {
|
||||
if (!payload) return;
|
||||
mode.value = String(payload.kind ?? 'precheck');
|
||||
summaryRef.value = (payload.summary as TransferPrecheckSummary) ?? null;
|
||||
items.value = (payload.items as TransferPrecheckItem[]) ?? [];
|
||||
runNo.value = String(payload.run_no ?? '');
|
||||
status.value = String(payload.status ?? 'executing');
|
||||
run.value = (payload.run as TransferRunResult) ?? null;
|
||||
const summaryValue = (payload.summary as TransferPrecheckSummary) ?? null;
|
||||
if (summaryValue) {
|
||||
transfer.precheckId.value = summaryValue.precheck_id;
|
||||
transfer.selected.value = new Set(
|
||||
(payload.items as TransferPrecheckItem[] ?? [])
|
||||
.filter((item) => item.result === 'executable')
|
||||
.map((item) => item.invoice_no),
|
||||
);
|
||||
}
|
||||
if (runNo.value) {
|
||||
transfer.runNo.value = runNo.value;
|
||||
}
|
||||
}
|
||||
|
||||
applyPayload(props.payload);
|
||||
watch(() => props.payload, applyPayload);
|
||||
|
||||
/** 直接生成调拨单(决策 4/5:无独立确认页) */
|
||||
async function onExecute(invoiceNos: string[]) {
|
||||
busy.value = true;
|
||||
try {
|
||||
transfer.selected.value = new Set(invoiceNos);
|
||||
const outcome = await transfer.execute();
|
||||
if (outcome) {
|
||||
mode.value = 'result';
|
||||
runNo.value = outcome.run_no;
|
||||
status.value = outcome.status;
|
||||
run.value = transfer.run.value;
|
||||
}
|
||||
} catch (e) {
|
||||
reportError(e);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function onDownloadReceipt() {
|
||||
try {
|
||||
await transfer.downloadReceiptFiles();
|
||||
} catch (e) {
|
||||
reportError(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function onDownloadErp() {
|
||||
try {
|
||||
await transfer.downloadErpInventory();
|
||||
} catch (e) {
|
||||
reportError(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function onDownloadExceptions() {
|
||||
try {
|
||||
await transfer.downloadExceptions();
|
||||
} catch (e) {
|
||||
reportError(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function onBacklogRetry(itemId: number) {
|
||||
busy.value = true;
|
||||
try {
|
||||
await transfer.retry(itemId);
|
||||
await transfer.loadBacklog();
|
||||
} catch (e) {
|
||||
reportError(e);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function onBacklogClose(item: TransferBacklogItem) {
|
||||
closeTarget.value = item;
|
||||
}
|
||||
|
||||
async function onCloseConfirm(reason: string) {
|
||||
if (!closeTarget.value) return;
|
||||
busy.value = true;
|
||||
try {
|
||||
await transfer.manualClose(closeTarget.value.item_id, reason);
|
||||
closeTarget.value = null;
|
||||
await transfer.loadBacklog();
|
||||
} catch (e) {
|
||||
reportError(e);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 来源实例选择确认 → 创建预检并切换预检卡(决策 4:两步第一步) */
|
||||
async function onSourceConfirm(sourceCodes: string[]) {
|
||||
busy.value = true;
|
||||
try {
|
||||
await transfer.createPrecheck(sourceCodes);
|
||||
mode.value = 'precheck';
|
||||
summaryRef.value = transfer.precheck.value;
|
||||
items.value = transfer.items.value;
|
||||
run.value = null;
|
||||
} catch (e) {
|
||||
reportError(e);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 对来源(单个或批量)重新触发收料 RPA 抓取,重试期间标记该来源(busy 独立于 confirm busy)。 */
|
||||
async function onSourceRetry(sourceCodes: string[]) {
|
||||
const codes = Array.isArray(sourceCodes) ? sourceCodes : [sourceCodes];
|
||||
retryingSource.value = new Set([...retryingSource.value, ...codes]);
|
||||
try {
|
||||
// 逐来源触发,避免一次并发 EPR/RPA 竞态;失败中断剩余。
|
||||
for (const code of codes) {
|
||||
await transfer.retrySourceRpa(code);
|
||||
}
|
||||
} catch (e) {
|
||||
reportError(e);
|
||||
} finally {
|
||||
const next = new Set(retryingSource.value);
|
||||
for (const code of codes) next.delete(code);
|
||||
retryingSource.value = next;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<TransferFileProgressCard
|
||||
v-if="mode === 'file-progress'"
|
||||
:sources="(props.payload?.sources as TransferSourceProgress[]) ?? []"
|
||||
/>
|
||||
<TransferSourceSelectCard
|
||||
v-else-if="mode === 'source-select'"
|
||||
:sources="transfer.sourceOptions.value"
|
||||
:busy="busy"
|
||||
:retrying="retryingSource"
|
||||
@confirm="onSourceConfirm"
|
||||
@retry="onSourceRetry"
|
||||
/>
|
||||
<TransferPrecheckCard
|
||||
v-else-if="mode === 'precheck' && summaryRef"
|
||||
:summary="summaryRef"
|
||||
:items="items"
|
||||
:selected="transfer.selected.value"
|
||||
:busy="busy"
|
||||
@toggle="(invoiceNo, checked) => transfer.toggleSelect(invoiceNo, checked)"
|
||||
@execute="onExecute"
|
||||
/>
|
||||
<TransferProgressCard v-else-if="mode === 'progress'" :run-no="runNo" :status="status" :busy="busy" />
|
||||
<TransferResultCard
|
||||
v-else-if="mode === 'result' && run"
|
||||
:run="run"
|
||||
@download-receipt="onDownloadReceipt"
|
||||
@download-erp="onDownloadErp"
|
||||
@download-exceptions="onDownloadExceptions"
|
||||
/>
|
||||
<TransferBacklogSummaryCard
|
||||
v-else-if="mode === 'backlog'"
|
||||
:items="transfer.backlog.value"
|
||||
@retry="onBacklogRetry"
|
||||
@close="onBacklogClose"
|
||||
@refresh="() => transfer.loadBacklog()"
|
||||
/>
|
||||
<TransferManualCloseDialog
|
||||
v-if="closeTarget"
|
||||
:open="Boolean(closeTarget)"
|
||||
:invoice-no="closeTarget.invoice_no"
|
||||
@confirm="onCloseConfirm"
|
||||
@cancel="closeTarget = null"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,157 @@
|
||||
<!--
|
||||
features/chat/components/messages/TransferPrecheckCard.vue
|
||||
用途:预检卡——计数 + 调拨明细表(决策 6 十列)+ 勾选 + “直接生成调拨单”按钮。
|
||||
依赖:props(summary/items/selected/busy)、i18n chat.transfer.*。
|
||||
逻辑:阻断/未成熟项 checkbox 禁用;无选择或 busy 时生成按钮禁用;
|
||||
emit execute(invoiceNos)(决策 4/5:无独立确认页)。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import type { TransferPrecheckItem, TransferPrecheckSummary } from '../../types/transfer.types';
|
||||
|
||||
const props = defineProps<{
|
||||
summary: TransferPrecheckSummary;
|
||||
items: TransferPrecheckItem[];
|
||||
selected: Set<string>;
|
||||
busy?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
toggle: [invoiceNo: string, checked: boolean];
|
||||
execute: [invoiceNos: string[]];
|
||||
}>();
|
||||
|
||||
const selectedCount = computed(() =>
|
||||
props.items.filter((item) => item.result === 'executable' && props.selected.has(item.invoice_no)).length,
|
||||
);
|
||||
const executeDisabled = computed(() => props.busy || selectedCount.value === 0);
|
||||
|
||||
function isSelectable(item: TransferPrecheckItem): boolean {
|
||||
return item.result === 'executable';
|
||||
}
|
||||
|
||||
function isChecked(item: TransferPrecheckItem): boolean {
|
||||
return props.selected.has(item.invoice_no);
|
||||
}
|
||||
|
||||
function resultLabel(result: string): string {
|
||||
const map: Record<string, string> = {
|
||||
executable: 'chat.transfer.resultExecutable',
|
||||
not_matured: 'chat.transfer.resultNotMatured',
|
||||
blocked_quantity_mismatch: 'chat.transfer.resultBlocked',
|
||||
blocked_inventory_not_found: 'chat.transfer.resultBlocked',
|
||||
blocked_future_date: 'chat.transfer.resultBlocked',
|
||||
erp_query_timeout: 'chat.transfer.resultUnknown',
|
||||
result_unknown: 'chat.transfer.resultUnknown',
|
||||
};
|
||||
return map[result] ?? 'chat.transfer.resultBlocked';
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="my-2 rounded-2xl border border-brand-100 bg-surface p-4 shadow-sm" data-testid="transfer-precheck-card">
|
||||
<div class="mb-3 flex flex-wrap items-center justify-between gap-3">
|
||||
<h3 class="text-sm font-bold text-primary">{{ $t('chat.transfer.precheckTitle') }}</h3>
|
||||
<span class="text-xs text-muted">{{ $t('chat.transfer.businessDate') }}:{{ summary.business_date }}</span>
|
||||
</div>
|
||||
|
||||
<div class="mb-3 grid grid-cols-2 gap-2 sm:grid-cols-5" data-testid="transfer-precheck-counts">
|
||||
<div class="rounded-lg bg-surface-soft p-2 text-center">
|
||||
<div class="text-lg font-black text-brand-600">{{ summary.counts.executable_count }}</div>
|
||||
<div class="text-[11px] text-muted">{{ $t('chat.transfer.executableCount') }}</div>
|
||||
</div>
|
||||
<div class="rounded-lg bg-surface-soft p-2 text-center">
|
||||
<div class="text-lg font-black text-secondary">{{ summary.counts.not_matured_count }}</div>
|
||||
<div class="text-[11px] text-muted">{{ $t('chat.transfer.notMaturedCount') }}</div>
|
||||
</div>
|
||||
<div class="rounded-lg bg-surface-soft p-2 text-center">
|
||||
<div class="text-lg font-black text-secondary">{{ summary.counts.blocked_count }}</div>
|
||||
<div class="text-[11px] text-muted">{{ $t('chat.transfer.blockedCount') }}</div>
|
||||
</div>
|
||||
<div class="rounded-lg bg-surface-soft p-2 text-center">
|
||||
<div class="text-lg font-black text-brand-600">{{ summary.estimated_transfer_quantity }}</div>
|
||||
<div class="text-[11px] text-muted">{{ $t('chat.transfer.estimatedQuantity') }}</div>
|
||||
</div>
|
||||
<div class="rounded-lg bg-surface-soft p-2 text-center">
|
||||
<div class="text-lg font-black text-brand-600">{{ summary.estimated_erp_write_count }}</div>
|
||||
<div class="text-[11px] text-muted">{{ $t('chat.transfer.estimatedErpWrites') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full min-w-[1100px] text-xs" data-testid="transfer-precheck-table">
|
||||
<thead>
|
||||
<tr class="border-b border-default bg-surface-soft text-left text-[11px] text-muted">
|
||||
<th class="p-2"></th>
|
||||
<th class="p-2">{{ $t('chat.transfer.colSource') }}</th>
|
||||
<th class="p-2">{{ $t('chat.transfer.colMaterial') }}</th>
|
||||
<th class="p-2">{{ $t('chat.transfer.colName') }}</th>
|
||||
<th class="p-2">{{ $t('chat.transfer.colSpec') }}</th>
|
||||
<th class="p-2">{{ $t('chat.transfer.colInvoice') }}</th>
|
||||
<th class="p-2">{{ $t('chat.transfer.colFromWarehouse') }}</th>
|
||||
<th class="p-2">{{ $t('chat.transfer.colFromQty') }}</th>
|
||||
<th class="p-2">{{ $t('chat.transfer.colToWarehouse') }}</th>
|
||||
<th class="p-2">{{ $t('chat.transfer.colToQty') }}</th>
|
||||
<th class="p-2">{{ $t('chat.transfer.colResult') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="item in items"
|
||||
:key="item.invoice_no"
|
||||
class="border-b border-subtle"
|
||||
:class="{ 'bg-surface-soft text-muted': !isSelectable(item) }"
|
||||
:data-testid="`transfer-item-${item.invoice_no}`"
|
||||
>
|
||||
<td class="p-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
:checked="isChecked(item)"
|
||||
:disabled="!isSelectable(item) || busy"
|
||||
:data-testid="`transfer-check-${item.invoice_no}`"
|
||||
@change="emit('toggle', item.invoice_no, ($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
</td>
|
||||
<td class="p-2">{{ item.source_code }}</td>
|
||||
<td class="p-2">{{ item.material_no }}</td>
|
||||
<td class="p-2">{{ item.material_name }}</td>
|
||||
<td class="p-2">{{ item.specification }}</td>
|
||||
<td class="p-2 font-semibold">{{ item.invoice_no }}</td>
|
||||
<td class="p-2">{{ item.from_warehouse }}</td>
|
||||
<td class="p-2">{{ item.from_quantity ?? '—' }}</td>
|
||||
<td class="p-2">{{ item.to_warehouse }}</td>
|
||||
<td class="p-2">{{ item.to_quantity }}</td>
|
||||
<td class="p-2">
|
||||
<span
|
||||
class="rounded-full px-2 py-0.5 font-bold"
|
||||
:class="{
|
||||
'bg-emerald-50 text-emerald-700': item.result === 'executable',
|
||||
'bg-amber-50 text-amber-700': item.result === 'not_matured',
|
||||
'bg-red-50 text-red-700': !isSelectable(item) && item.result !== 'not_matured',
|
||||
}"
|
||||
>
|
||||
{{ $t(resultLabel(item.result)) }}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 flex items-center justify-end gap-3 border-t border-subtle pt-3">
|
||||
<span class="text-xs text-muted">
|
||||
{{ $t('chat.transfer.selectedCount', { count: selectedCount }) }} ·
|
||||
{{ $t('chat.transfer.estimatedErpWrites') }}:{{ summary.estimated_erp_write_count }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg bg-brand-600 px-4 py-1.5 text-sm font-bold text-white hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
:disabled="executeDisabled"
|
||||
:data-testid="'transfer-generate-button'"
|
||||
@click="emit('execute', items.filter(isSelectable).filter(isChecked).map((item) => item.invoice_no))"
|
||||
>
|
||||
{{ $t('chat.transfer.generateTransfer') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,60 @@
|
||||
<!--
|
||||
features/chat/components/messages/TransferProgressCard.vue
|
||||
用途:Run 执行进度卡(页面关闭/刷新后经 run_no 恢复)。
|
||||
依赖:props(runNo/status/busy)、i18n chat.transfer.*。
|
||||
逻辑:展示 Run 编号与状态,提供刷新按钮;页面刷新不取消后台 Run。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
defineProps<{
|
||||
runNo: string;
|
||||
status: string;
|
||||
busy?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
refresh: [];
|
||||
}>();
|
||||
|
||||
function statusLabel(status: string): string {
|
||||
const map: Record<string, string> = {
|
||||
executing: 'chat.transfer.runExecuting',
|
||||
success: 'chat.transfer.runSuccess',
|
||||
partial_failed: 'chat.transfer.runPartialFailed',
|
||||
failed: 'chat.transfer.runFailed',
|
||||
cancelled: 'chat.transfer.runCancelled',
|
||||
};
|
||||
return map[status] ?? 'chat.transfer.runExecuting';
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="my-2 rounded-2xl border border-brand-100 bg-surface p-4 shadow-sm" data-testid="transfer-progress-card">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<div class="text-sm font-bold text-primary">{{ $t('chat.transfer.runProgress') }}</div>
|
||||
<div class="mt-1 text-xs text-muted">{{ runNo }}</div>
|
||||
</div>
|
||||
<span
|
||||
class="rounded-full px-2 py-0.5 text-xs font-bold"
|
||||
:class="{
|
||||
'bg-blue-50 text-blue-700': status === 'executing',
|
||||
'bg-emerald-50 text-emerald-700': status === 'success',
|
||||
'bg-amber-50 text-amber-700': status === 'partial_failed',
|
||||
'bg-red-50 text-red-700': status === 'failed' || status === 'cancelled',
|
||||
}"
|
||||
data-testid="transfer-run-status"
|
||||
>
|
||||
{{ $t(statusLabel(status)) }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default px-3 py-1 text-xs font-bold text-secondary hover-surface-soft"
|
||||
:disabled="busy"
|
||||
data-testid="transfer-run-refresh"
|
||||
@click="emit('refresh')"
|
||||
>
|
||||
{{ $t('chat.transfer.refreshProgress') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,131 @@
|
||||
<!--
|
||||
features/chat/components/messages/TransferResultCard.vue
|
||||
用途:结果卡——按 ERP 单号聚合(决策 20)、可展开物料明细、未生成单据异常区、
|
||||
下载收料来源文件 / ERP 库存表(决策 21)。不展示执行审计入口(决策 19)。
|
||||
依赖:props.run、i18n chat.transfer.*。
|
||||
逻辑:<details> 展开/收起物料行;异常单独分区;两个下载按钮 + 异常 Excel。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import type { TransferRunResult } from '../../types/transfer.types';
|
||||
|
||||
defineProps<{
|
||||
run: TransferRunResult;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
downloadReceipt: [];
|
||||
downloadErp: [];
|
||||
downloadExceptions: [];
|
||||
}>();
|
||||
|
||||
function reasonLabel(reason: string): string {
|
||||
const map: Record<string, string> = {
|
||||
blocked_quantity_mismatch: 'chat.transfer.resultBlocked',
|
||||
blocked_inventory_not_found: 'chat.transfer.resultBlocked',
|
||||
business_failed: 'chat.transfer.exceptionBusinessFailed',
|
||||
technical_failed: 'chat.transfer.exceptionTechnicalFailed',
|
||||
result_unknown: 'chat.transfer.resultUnknown',
|
||||
precheck_expired: 'chat.transfer.exceptionPrecheckExpired',
|
||||
};
|
||||
return map[reason] ?? 'chat.transfer.resultBlocked';
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="my-2 rounded-2xl border border-brand-100 bg-surface p-4 shadow-sm" data-testid="transfer-result-card">
|
||||
<div class="mb-3 flex items-center justify-between">
|
||||
<h3 class="text-sm font-bold text-primary">{{ $t('chat.transfer.resultTitle') }}</h3>
|
||||
<span class="text-xs text-muted">{{ run.run_no }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 已生成 ERP 单据:按单号聚合 + 可展开物料明细 -->
|
||||
<div v-if="run.result.erp_documents.length" class="flex flex-col gap-2">
|
||||
<details
|
||||
v-for="doc in run.result.erp_documents"
|
||||
:key="doc.document_no"
|
||||
class="rounded-lg border border-default"
|
||||
data-testid="transfer-erp-document"
|
||||
>
|
||||
<summary class="flex cursor-pointer flex-wrap items-center justify-between gap-2 px-3 py-2 text-xs">
|
||||
<span class="font-bold text-brand-700">{{ doc.document_no }}</span>
|
||||
<span class="text-secondary">{{ doc.from_warehouse }} → {{ doc.to_warehouse }}</span>
|
||||
<span class="text-muted">{{ $t('chat.transfer.materialCount', { count: doc.material_count }) }}</span>
|
||||
<span class="font-bold text-secondary">{{ doc.total_quantity }}</span>
|
||||
<span class="rounded-full bg-emerald-50 px-2 py-0.5 font-bold text-emerald-700">
|
||||
{{ $t('chat.transfer.posted') }}
|
||||
</span>
|
||||
</summary>
|
||||
<div class="border-t border-subtle px-3 py-2">
|
||||
<table class="w-full text-xs" data-testid="transfer-erp-document-lines">
|
||||
<thead>
|
||||
<tr class="text-left text-[11px] text-muted">
|
||||
<th class="p-1">{{ $t('chat.transfer.colMaterial') }}</th>
|
||||
<th class="p-1">{{ $t('chat.transfer.colName') }}</th>
|
||||
<th class="p-1">{{ $t('chat.transfer.colSpec') }}</th>
|
||||
<th class="p-1">{{ $t('chat.transfer.colInvoice') }}</th>
|
||||
<th class="p-1">{{ $t('chat.transfer.colToQty') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="line in doc.lines" :key="line.invoice_no" class="border-t border-subtle">
|
||||
<td class="p-1">{{ line.material_no }}</td>
|
||||
<td class="p-1">{{ line.material_name }}</td>
|
||||
<td class="p-1">{{ line.specification }}</td>
|
||||
<td class="p-1">{{ line.invoice_no }}</td>
|
||||
<td class="p-1">{{ line.quantity }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
<div v-else class="mb-3 rounded-lg bg-surface-soft p-3 text-xs text-muted">
|
||||
{{ $t('chat.transfer.noDocuments') }}
|
||||
</div>
|
||||
|
||||
<!-- 未生成 ERP 单据的异常区(决策 20 单独展示) -->
|
||||
<div v-if="run.result.exceptions.length" class="mt-3" data-testid="transfer-exceptions-area">
|
||||
<h4 class="mb-1 text-xs font-bold text-secondary">{{ $t('chat.transfer.exceptionsTitle') }}</h4>
|
||||
<ul class="flex flex-col gap-1">
|
||||
<li
|
||||
v-for="exc in run.result.exceptions"
|
||||
:key="exc.invoice_no"
|
||||
class="rounded-lg bg-red-50 px-3 py-1.5 text-xs text-red-700"
|
||||
data-testid="transfer-exception-item"
|
||||
>
|
||||
<span class="font-bold">{{ exc.invoice_no }}</span>
|
||||
<span class="mx-1 text-red-400">·</span>{{ exc.source_code }} · {{ $t(reasonLabel(exc.reason)) }}
|
||||
<div class="text-[11px] text-red-500">{{ exc.facts }}</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<!-- 下载:收料来源文件 + ERP 库存表(决策 21);无审计入口(决策 19) -->
|
||||
<div class="mt-3 flex flex-wrap gap-2 border-t border-subtle pt-3" data-testid="transfer-result-downloads">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-brand-200 px-3 py-1.5 text-xs font-bold text-brand-700 hover:bg-brand-50"
|
||||
data-testid="transfer-download-receipt"
|
||||
@click="emit('downloadReceipt')"
|
||||
>
|
||||
{{ $t('chat.transfer.downloadReceiptFiles') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-brand-200 px-3 py-1.5 text-xs font-bold text-brand-700 hover:bg-brand-50"
|
||||
data-testid="transfer-download-erp"
|
||||
@click="emit('downloadErp')"
|
||||
>
|
||||
{{ $t('chat.transfer.downloadErpInventory') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default px-3 py-1.5 text-xs font-bold text-secondary hover-surface-soft"
|
||||
data-testid="transfer-download-exceptions"
|
||||
@click="emit('downloadExceptions')"
|
||||
>
|
||||
{{ $t('chat.transfer.downloadExceptions') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* features/chat/components/messages/TransferSourceSelectCard.spec.ts
|
||||
* 用途:来源实例选择卡——平台分组、全选已启用、清空、按收料文件状态门禁确认、
|
||||
* 确认提交、重试收料 RPA。
|
||||
* 依赖:@vue/test-utils、i18n。
|
||||
* 逻辑:平台 DBS/Crane 仅分组;实例为选择与执行边界(决策 2/3/4);
|
||||
* 所选来源需至少一个 has_ready_file 才能确认预检(决策:无 ready 文件禁止确认)。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import i18n from '@/i18n';
|
||||
import TransferSourceSelectCard from './TransferSourceSelectCard.vue';
|
||||
|
||||
const readySources = [
|
||||
{ source_code: 'DBS-AWSBI', display_name: 'AWSBI 在途仓', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' },
|
||||
{ source_code: 'DBS-AWSSG', display_name: 'AWSSG 在途仓', platform: 'dbs', enabled: true, file_status: 'none' },
|
||||
{ source_code: 'CRANE-SZ', display_name: '深圳在途仓', platform: 'crane', enabled: true, has_ready_file: true, file_status: 'ready' },
|
||||
];
|
||||
|
||||
function mountCard(props = {}, sources = readySources) {
|
||||
return mount(TransferSourceSelectCard, {
|
||||
props: { sources, ...props },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('TransferSourceSelectCard', () => {
|
||||
it('按平台分组展示来源实例', () => {
|
||||
const wrapper = mountCard();
|
||||
expect(wrapper.find('[data-testid="transfer-source-option-DBS-AWSBI"]').text()).toContain('DBS-AWSBI');
|
||||
expect(wrapper.find('[data-testid="transfer-source-option-CRANE-SZ"]').text()).toContain('CRANE-SZ');
|
||||
});
|
||||
|
||||
it('未选任何来源时确认按钮禁用(需至少一个 ready 文件来源)', () => {
|
||||
const wrapper = mountCard();
|
||||
expect((wrapper.find('[data-testid="transfer-source-confirm"]').element as HTMLButtonElement).disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('勾选含 ready 文件来源后确认提交所选来源', async () => {
|
||||
const wrapper = mountCard();
|
||||
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSBI"] input').setValue(true);
|
||||
await wrapper.find('[data-testid="transfer-source-option-CRANE-SZ"] input').setValue(true);
|
||||
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
|
||||
expect(wrapper.emitted('confirm')?.[0][0]).toEqual(['DBS-AWSBI', 'CRANE-SZ']);
|
||||
});
|
||||
|
||||
it('仅勾选无 ready 文件来源时不提交(门禁)', async () => {
|
||||
const wrapper = mountCard();
|
||||
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSSG"] input').setValue(true);
|
||||
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
|
||||
expect(wrapper.emitted('confirm')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('“全选可见”勾选全部启用实例', async () => {
|
||||
const wrapper = mountCard();
|
||||
await wrapper.find('[data-testid="transfer-source-select-visible"]').trigger('click');
|
||||
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
|
||||
expect(wrapper.emitted('confirm')?.[0][0]).toEqual(['DBS-AWSBI', 'DBS-AWSSG', 'CRANE-SZ']);
|
||||
});
|
||||
|
||||
it('“清空”清空已选实例', async () => {
|
||||
const wrapper = mountCard();
|
||||
await wrapper.find('[data-testid="transfer-source-select-visible"]').trigger('click');
|
||||
await wrapper.find('[data-testid="transfer-source-clear"]').trigger('click');
|
||||
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
|
||||
expect(wrapper.emitted('confirm')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('“只选可重试”勾选无文件/失败来源', async () => {
|
||||
const wrapper = mountCard();
|
||||
await wrapper.find('[data-testid="transfer-source-select-retryable"]').trigger('click');
|
||||
const selected = (wrapper.find('[data-testid="transfer-source-confirm"]').element as HTMLButtonElement).disabled;
|
||||
// 可重试来源为 DBS-AWSSG(none);选中它但无 ready 文件 → 确认仍禁用(门禁)。
|
||||
expect(selected).toBe(true);
|
||||
});
|
||||
|
||||
it('点击行尾重试图标 emit retry([sourceCode])', async () => {
|
||||
const wrapper = mountCard();
|
||||
await wrapper.find('[data-testid="transfer-source-retry-DBS-AWSSG"]').trigger('click');
|
||||
expect(wrapper.emitted('retry')?.[0][0]).toEqual(['DBS-AWSSG']);
|
||||
});
|
||||
|
||||
it('批量重试仅传可重试来源', async () => {
|
||||
const wrapper = mountCard();
|
||||
await wrapper.find('[data-testid="transfer-source-select-retryable"]').trigger('click');
|
||||
await wrapper.find('[data-testid="transfer-source-batch-retry"]').trigger('click');
|
||||
expect(wrapper.emitted('retry')?.[0][0]).toEqual(['DBS-AWSSG']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,246 @@
|
||||
<!--
|
||||
features/chat/components/messages/TransferSourceSelectCard.vue
|
||||
用途:来源实例选择卡(决策 2/3/4:手工两步第一步)——按平台 DBS/Crane 分组勾选实例,
|
||||
“确认范围并预检”发起预检。
|
||||
依赖:props.sources、i18n chat.transfer.*。
|
||||
逻辑:平台仅分组不可直接执行;未选任何实例时确认按钮禁用。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import type { TransferSourceOption } from '../../types/transfer.types';
|
||||
|
||||
const props = defineProps<{
|
||||
sources: TransferSourceOption[];
|
||||
busy?: boolean;
|
||||
/** 正在重试收料 RPA 的来源编码集合 */
|
||||
retrying?: Set<string>;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
confirm: [sourceCodes: string[]];
|
||||
/** 批量重试收料 RPA:传来源编码列表 */
|
||||
retry: [sourceCodes: string[]];
|
||||
}>();
|
||||
|
||||
const { warning: notifyWarning } = useMessage();
|
||||
const { t } = useI18n();
|
||||
|
||||
const selected = ref<Set<string>>(new Set());
|
||||
|
||||
const platforms = computed(() => [...new Set(props.sources.map((source) => source.platform))]);
|
||||
const selectedCount = computed(() => selected.value.size);
|
||||
|
||||
/** 可重试判定:仅 待抓取(none) / 抓取失败(failed) 的来源可重试(ready/fetching 不重复触发)。 */
|
||||
function isRetryable(source: TransferSourceOption): boolean {
|
||||
return source.file_status === 'none' || source.file_status === 'failed';
|
||||
}
|
||||
|
||||
/** 全部可重试来源。 */
|
||||
const retryableSources = computed(() => props.sources.filter(isRetryable));
|
||||
/** 已选来源中可重试的数量。 */
|
||||
const selectedRetryableCount = computed(() =>
|
||||
[...selected.value].filter((code) => props.sources.some((s) => s.source_code === code && isRetryable(s))).length,
|
||||
);
|
||||
const batchRetryDisabled = computed(() => props.busy || selectedRetryableCount.value === 0);
|
||||
|
||||
/** 已选来源中是否有具备 ready 文件的(门禁:都无 ready 文件则禁止确认预检)。 */
|
||||
const selectedHasReadyFile = computed(() =>
|
||||
[...selected.value].some((code) => props.sources.find((s) => s.source_code === code)?.has_ready_file),
|
||||
);
|
||||
const confirmDisabled = computed(() => props.busy || selectedCount.value === 0 || !selectedHasReadyFile.value);
|
||||
|
||||
function toggle(sourceCode: string, checked: boolean) {
|
||||
const next = new Set(selected.value);
|
||||
if (checked) next.add(sourceCode);
|
||||
else next.delete(sourceCode);
|
||||
selected.value = next;
|
||||
}
|
||||
|
||||
function togglePlatform(platform: string, checked: boolean) {
|
||||
const next = new Set(selected.value);
|
||||
for (const source of props.sources) {
|
||||
if (source.platform === platform) {
|
||||
if (checked) next.add(source.source_code);
|
||||
else next.delete(source.source_code);
|
||||
}
|
||||
}
|
||||
selected.value = next;
|
||||
}
|
||||
|
||||
/** 全选当前可见来源(已启用实例)。 */
|
||||
function selectVisible() {
|
||||
selected.value = new Set(props.sources.filter((source) => source.enabled).map((source) => source.source_code));
|
||||
}
|
||||
|
||||
/** 只选可重试来源(待抓取/抓取失败),来源多时一键收敛。 */
|
||||
function selectRetryable() {
|
||||
selected.value = new Set(retryableSources.value.map((source) => source.source_code));
|
||||
}
|
||||
|
||||
/** 清空选择。 */
|
||||
function clearSelected() {
|
||||
selected.value = new Set();
|
||||
}
|
||||
|
||||
/** 批量重试收料 RPA:仅触发所选来源中可重试的那部分。 */
|
||||
function batchRetry() {
|
||||
const codes = [...selected.value].filter(
|
||||
(code) => props.sources.some((s) => s.source_code === code && isRetryable(s)),
|
||||
);
|
||||
if (codes.length === 0) {
|
||||
notifyWarning(t('chat.transfer.noRetryable'), t('chat.transfer.sourceSelectTitle'));
|
||||
return;
|
||||
}
|
||||
emit('retry', codes);
|
||||
}
|
||||
|
||||
function confirm() {
|
||||
if (selectedCount.value === 0) {
|
||||
notifyWarning(t('chat.transfer.needSelectSource'), t('chat.transfer.sourceSelectTitle'));
|
||||
return;
|
||||
}
|
||||
if (!selectedHasReadyFile.value) {
|
||||
notifyWarning(t('chat.transfer.needReadyFile'), t('chat.transfer.sourceSelectTitle'));
|
||||
return;
|
||||
}
|
||||
emit('confirm', [...selected.value]);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="my-2 rounded-2xl border border-brand-100 bg-surface p-4 shadow-sm" data-testid="transfer-source-select-card">
|
||||
<h3 class="mb-1 text-sm font-bold text-primary">{{ $t('chat.transfer.sourceSelectTitle') }}</h3>
|
||||
<p class="mb-3 text-xs text-muted">{{ $t('chat.transfer.sourceSelectHint') }}</p>
|
||||
|
||||
<div class="mb-3 flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-brand-200 px-3 py-1.5 text-xs font-bold text-brand-700 hover:bg-brand-50 disabled:opacity-50"
|
||||
:disabled="busy"
|
||||
data-testid="transfer-source-select-visible"
|
||||
@click="selectVisible"
|
||||
>
|
||||
{{ $t('chat.transfer.selectVisible') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-brand-200 px-3 py-1.5 text-xs font-bold text-brand-700 hover:bg-brand-50 disabled:opacity-50"
|
||||
:disabled="busy"
|
||||
data-testid="transfer-source-select-retryable"
|
||||
@click="selectRetryable"
|
||||
>
|
||||
{{ $t('chat.transfer.selectRetryable') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg bg-brand-600 px-3 py-1.5 text-xs font-bold text-white hover:bg-brand-700 disabled:opacity-50"
|
||||
:disabled="batchRetryDisabled"
|
||||
data-testid="transfer-source-batch-retry"
|
||||
@click="batchRetry"
|
||||
>
|
||||
{{ $t('chat.transfer.batchRetry') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default px-3 py-1.5 text-xs font-bold text-secondary hover-surface-soft disabled:opacity-50"
|
||||
:disabled="busy"
|
||||
data-testid="transfer-source-clear"
|
||||
@click="clearSelected"
|
||||
>
|
||||
{{ $t('chat.transfer.clearSources') }}
|
||||
</button>
|
||||
<span class="ml-auto text-xs text-muted">
|
||||
{{ $t('chat.transfer.selectedSourceCount', { count: selectedCount }) }}
|
||||
<span v-if="selectedRetryableCount > 0" class="text-amber-600"> · {{ $t('chat.transfer.selectedRetryableCount', { count: selectedRetryableCount }) }}</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-for="platform in platforms" :key="platform" class="mb-3 rounded-lg border border-subtle">
|
||||
<div class="flex items-center justify-between rounded-t-lg bg-surface-soft px-3 py-1.5">
|
||||
<b class="text-xs text-secondary">{{ platform.toUpperCase() }}</b>
|
||||
<label class="text-[11px] text-muted">
|
||||
<input
|
||||
type="checkbox"
|
||||
:checked="props.sources.filter((source) => source.platform === platform).every((source) => selected.has(source.source_code))"
|
||||
@change="togglePlatform(platform, ($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
{{ $t('chat.transfer.selectAll') }}
|
||||
</label>
|
||||
</div>
|
||||
<div class="grid grid-cols-1 gap-1 p-2 sm:grid-cols-2">
|
||||
<div
|
||||
v-for="source in props.sources.filter((item) => item.platform === platform)"
|
||||
:key="source.source_code"
|
||||
class="flex items-center gap-2 rounded-lg px-2 py-1.5 hover-surface-soft"
|
||||
:data-testid="`transfer-source-option-${source.source_code}`"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
:checked="selected.has(source.source_code)"
|
||||
:disabled="busy"
|
||||
@change="toggle(source.source_code, ($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
<span class="min-w-0 flex-1">
|
||||
<span class="block truncate text-xs font-semibold text-secondary">{{ source.source_code }}</span>
|
||||
<span class="block truncate text-[11px] text-muted">{{ source.display_name }}</span>
|
||||
</span>
|
||||
<span class="shrink-0">
|
||||
<span
|
||||
v-if="source.has_ready_file"
|
||||
class="inline-flex items-center gap-1 rounded-full bg-emerald-50 px-2 py-0.5 text-[10px] font-bold text-emerald-700"
|
||||
:data-testid="`transfer-source-status-${source.source_code}`"
|
||||
>
|
||||
{{ t('chat.transfer.fileReady') }}
|
||||
</span>
|
||||
<span
|
||||
v-else-if="source.file_status === 'fetching'"
|
||||
class="inline-flex items-center gap-1 rounded-full bg-amber-50 px-2 py-0.5 text-[10px] font-bold text-amber-700"
|
||||
:data-testid="`transfer-source-status-${source.source_code}`"
|
||||
>
|
||||
{{ t('chat.transfer.fileFetching') }}
|
||||
</span>
|
||||
<span
|
||||
v-else-if="source.file_status === 'failed'"
|
||||
class="inline-flex items-center gap-1 rounded-full bg-red-50 px-2 py-0.5 text-[10px] font-bold text-red-700"
|
||||
:data-testid="`transfer-source-status-${source.source_code}`"
|
||||
>
|
||||
{{ t('chat.transfer.fileFailed') }}
|
||||
</span>
|
||||
<span
|
||||
v-else
|
||||
class="inline-flex items-center gap-1 rounded-full bg-surface-strong px-2 py-0.5 text-[10px] font-bold text-muted"
|
||||
:data-testid="`transfer-source-status-${source.source_code}`"
|
||||
>
|
||||
{{ t('chat.transfer.fileNone') }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="ml-1 inline-flex h-6 w-6 items-center justify-center rounded-md border border-default text-sm text-muted hover:border-brand-200 hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
:disabled="busy || !isRetryable(source) || retrying?.has(source.source_code)"
|
||||
:title="t('chat.transfer.retryReceipt')"
|
||||
:data-testid="`transfer-source-retry-${source.source_code}`"
|
||||
@click.stop="emit('retry', [source.source_code])"
|
||||
>
|
||||
<span aria-hidden="true">{{ retrying?.has(source.source_code) ? '…' : '↻' }}</span>
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-end gap-3 border-t border-subtle pt-3">
|
||||
<span class="text-xs text-muted">{{ $t('chat.transfer.selectedCount', { count: selectedCount }) }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg bg-brand-600 px-4 py-1.5 text-sm font-bold text-white hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
:disabled="confirmDisabled"
|
||||
data-testid="transfer-source-confirm"
|
||||
@click="confirm"
|
||||
>
|
||||
{{ $t('chat.transfer.confirmScopeAndPrecheck') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* features/chat/components/messages/shippingMessageHandlers.ts
|
||||
* 用途:定义发货通知订单复核与库存匹配消息共用的页面处理器契约。
|
||||
* 依赖:chat.types、shipping.api.types、shipping.types。
|
||||
* 逻辑:页面组合处理器后传给消息列表;不包含已下线的任务级库存列映射能力。
|
||||
*/
|
||||
import type { ChatMessage } from '../../types/chat.types';
|
||||
import type { ShippingNoticeHeader, ShippingNoticeLine } from '../../types/shipping.api.types';
|
||||
import type { ShippingMatchResultPayload, ShippingParseReviewPayload } from '../../types/shipping.types';
|
||||
|
||||
export interface ShippingMessageHandlers {
|
||||
getParseReviewPayload: (msg: ChatMessage) => ShippingParseReviewPayload | null;
|
||||
getMatchResultPayload: (msg: ChatMessage) => ShippingMatchResultPayload | null;
|
||||
updateHeader: (msg: ChatMessage, fields: Partial<ShippingNoticeHeader>) => Promise<boolean>;
|
||||
updateLine: (msg: ChatMessage, lineIndex: number, patch: Partial<ShippingNoticeLine>) => Promise<boolean>;
|
||||
addLine: (msg: ChatMessage, line: Partial<ShippingNoticeLine>) => Promise<boolean>;
|
||||
removeLine: (msg: ChatMessage, lineIndex: number) => Promise<boolean>;
|
||||
retryOrderExtractionRun: (runNo: string) => Promise<boolean>;
|
||||
refreshOrderExtractionRun: (runNo: string) => Promise<boolean>;
|
||||
cancelOrderExtractionRun: (runNo: string, reason?: string | null) => Promise<boolean>;
|
||||
cancelOrderExtractionUnit: (runNo: string, documentId: number, reason?: string | null) => Promise<boolean>;
|
||||
reparseOrderExtractionRun: (runNo: string, reason: 'rule_updated' | 'field_mapping_error' | 'document_quality' | 'other') => Promise<boolean>;
|
||||
resolveCandidateDuplicate: (candidateNo: string, action: import('../../types/shipping.types').ShippingDuplicateAction, targetTaskNo: string | undefined, reason: string | undefined, done: (success: boolean) => void) => Promise<void>;
|
||||
promoteCandidate: (candidateNo: string, done: (success: boolean) => void) => Promise<void>;
|
||||
rejectCandidate: (candidateNo: string, done: (success: boolean) => void) => Promise<void>;
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* features/chat/components/messages/transferCards.spec.ts
|
||||
* 用途:验证在途调拨三张核心卡片(文件进度/预检/结果)+ 关闭弹窗的交互与禁用语义。
|
||||
* 依赖:@vue/test-utils、i18n、transfer.types。
|
||||
* 逻辑:断言按钮禁用、勾选禁用、ERP 单号展开/收起、异常展示、下载按钮与
|
||||
* 结果页不出现“查看执行审计”入口(决策 19)。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import i18n from '@/i18n';
|
||||
import TransferFileProgressCard from './TransferFileProgressCard.vue';
|
||||
import TransferPrecheckCard from './TransferPrecheckCard.vue';
|
||||
import TransferResultCard from './TransferResultCard.vue';
|
||||
import TransferManualCloseDialog from './TransferManualCloseDialog.vue';
|
||||
|
||||
const mountOptions = { global: { plugins: [i18n] } };
|
||||
|
||||
const summary = {
|
||||
precheck_id: 'TPC-1',
|
||||
status: 'ready_to_execute',
|
||||
business_date: '2026-08-06',
|
||||
eligible_receipt_date_to: '2026-08-05',
|
||||
expires_at: '',
|
||||
counts: { file_invoice_count: 3, not_matured_count: 1, prechecked_count: 2, executable_count: 2, blocked_count: 0 },
|
||||
estimated_transfer_quantity: '2400',
|
||||
estimated_erp_write_count: 2,
|
||||
precheck_hash: 'sha256:x',
|
||||
};
|
||||
|
||||
const items = [
|
||||
{ source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: '连接器', specification: 'A', 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: '控制器', specification: 'B', invoice_no: 'INV-041', from_warehouse: '', from_quantity: null, to_warehouse: '', to_quantity: '400', result: 'not_matured' },
|
||||
];
|
||||
|
||||
describe('TransferFileProgressCard', () => {
|
||||
it('按来源显示阶段,不伪造总百分比', () => {
|
||||
const wrapper = mount(TransferFileProgressCard, {
|
||||
props: { sources: [
|
||||
{ source_code: 'DBS-AWSBI', stage: 'file_ready', file_no: 'REC-1', file_version: 'v3' },
|
||||
{ source_code: 'CRANE-SZ', stage: 'waiting_rpa_callback' },
|
||||
] },
|
||||
...mountOptions,
|
||||
});
|
||||
expect(wrapper.find('[data-testid="transfer-source-DBS-AWSBI"]').text()).toContain('REC-1');
|
||||
expect(wrapper.find('[data-testid="transfer-source-CRANE-SZ"]').text()).toContain('RPA');
|
||||
});
|
||||
});
|
||||
|
||||
describe('TransferPrecheckCard', () => {
|
||||
it('阻断/未成熟项 checkbox 禁用;可执行项可选', () => {
|
||||
const wrapper = mount(TransferPrecheckCard, {
|
||||
props: { summary, items, selected: new Set(['INV-001']) },
|
||||
...mountOptions,
|
||||
});
|
||||
const executableCheck = wrapper.find('[data-testid="transfer-check-INV-001"]');
|
||||
const maturedCheck = wrapper.find('[data-testid="transfer-check-INV-041"]');
|
||||
expect((executableCheck.element as HTMLInputElement).disabled).toBe(false);
|
||||
expect((maturedCheck.element as HTMLInputElement).disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('未选择任何项时生成按钮禁用', () => {
|
||||
const wrapper = mount(TransferPrecheckCard, {
|
||||
props: { summary, items, selected: new Set() },
|
||||
...mountOptions,
|
||||
});
|
||||
expect((wrapper.find('[data-testid="transfer-generate-button"]').element as HTMLButtonElement).disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('busy 时生成按钮禁用', () => {
|
||||
const wrapper = mount(TransferPrecheckCard, {
|
||||
props: { summary, items, selected: new Set(['INV-001']), busy: true },
|
||||
...mountOptions,
|
||||
});
|
||||
expect((wrapper.find('[data-testid="transfer-generate-button"]').element as HTMLButtonElement).disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('点击生成按钮仅提交可执行勾选项', async () => {
|
||||
const wrapper = mount(TransferPrecheckCard, {
|
||||
props: { summary, items, selected: new Set(['INV-001']) },
|
||||
...mountOptions,
|
||||
});
|
||||
await wrapper.find('[data-testid="transfer-generate-button"]').trigger('click');
|
||||
expect(wrapper.emitted('execute')?.[0][0]).toEqual(['INV-001']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TransferResultCard', () => {
|
||||
const run = {
|
||||
run_no: 'RUN-1',
|
||||
status: 'partial_failed',
|
||||
result: {
|
||||
erp_documents: [{
|
||||
document_no: 'TRF-10001',
|
||||
from_warehouse: 'DBS-TRANSIT',
|
||||
to_warehouse: 'HUB-CN01',
|
||||
material_count: 1,
|
||||
total_quantity: '1200',
|
||||
posting_status: 'posted',
|
||||
lines: [{ material_no: 'MAT-1', material_name: '连接器', specification: 'A', invoice_no: 'INV-001', quantity: '1200' }],
|
||||
}],
|
||||
exceptions: [{ source_code: 'DBS-AWSBI', invoice_no: 'INV-999', material_no: 'MAT-9', reason: 'business_failed', facts: '收料 300 / ERP 280' }],
|
||||
},
|
||||
};
|
||||
|
||||
it('按 ERP 单号聚合展示,物料明细可展开/收起', async () => {
|
||||
const wrapper = mount(TransferResultCard, { props: { run }, ...mountOptions });
|
||||
const doc = wrapper.find('[data-testid="transfer-erp-document"]');
|
||||
expect(doc.text()).toContain('TRF-10001');
|
||||
expect(doc.attributes('open')).toBeUndefined();
|
||||
await doc.find('summary').trigger('click');
|
||||
expect(doc.attributes('open')).toBeDefined();
|
||||
expect(wrapper.find('[data-testid="transfer-erp-document-lines"]').text()).toContain('INV-001');
|
||||
});
|
||||
|
||||
it('未生成单据异常单独展示', () => {
|
||||
const wrapper = mount(TransferResultCard, { props: { run }, ...mountOptions });
|
||||
expect(wrapper.find('[data-testid="transfer-exceptions-area"]').text()).toContain('INV-999');
|
||||
});
|
||||
|
||||
it('提供两个下载按钮(收料来源文件 + ERP 库存表)', async () => {
|
||||
const wrapper = mount(TransferResultCard, { props: { run }, ...mountOptions });
|
||||
await wrapper.find('[data-testid="transfer-download-receipt"]').trigger('click');
|
||||
await wrapper.find('[data-testid="transfer-download-erp"]').trigger('click');
|
||||
expect(wrapper.emitted('downloadReceipt')).toBeTruthy();
|
||||
expect(wrapper.emitted('downloadErp')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('结果页不出现“查看执行审计”入口(决策 19)', () => {
|
||||
const wrapper = mount(TransferResultCard, { props: { run }, ...mountOptions });
|
||||
expect(wrapper.text()).not.toContain('审计');
|
||||
});
|
||||
});
|
||||
|
||||
describe('TransferManualCloseDialog', () => {
|
||||
it('原因为空时确认按钮禁用;填写后可提交', async () => {
|
||||
const wrapper = mount(TransferManualCloseDialog, {
|
||||
props: { open: true, invoiceNo: 'INV-001' },
|
||||
...mountOptions,
|
||||
});
|
||||
const confirm = wrapper.find('[data-testid="transfer-close-confirm"]');
|
||||
expect((confirm.element as HTMLButtonElement).disabled).toBe(true);
|
||||
await wrapper.find('[data-testid="transfer-close-reason"]').setValue('线下已处理');
|
||||
expect((confirm.element as HTMLButtonElement).disabled).toBe(false);
|
||||
await confirm.trigger('click');
|
||||
expect(wrapper.emitted('confirm')?.[0][0]).toBe('线下已处理');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,219 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewActionConfirmDialog.vue
|
||||
用途:复核页破坏性/不可逆操作的二次确认弹窗(确认建单、重识别、非订单、质量异常)。
|
||||
依赖:vue-i18n、dialog-overlay / dialog-panel 设计系统样式。
|
||||
逻辑:ShippingOrderReviewView 以 v-model 控制显隐;质量异常须选原因码,other 时备注必填;
|
||||
非订单/重识别将说明写入 comment,并附带稳定 reasonCode。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
export type ReviewConfirmAction = 'confirm' | 'reparse' | 'non_order' | 'quality_issue';
|
||||
|
||||
/** 确认弹窗提交载荷:稳定原因码 + 自由说明,供后端审计复盘。 */
|
||||
export type ReviewConfirmPayload = {
|
||||
reasonCode: string;
|
||||
comment: string;
|
||||
};
|
||||
|
||||
const QUALITY_REASON_CODES = [
|
||||
'blurred',
|
||||
'incomplete_pages',
|
||||
'password_protected',
|
||||
'corrupted',
|
||||
'wrong_orientation',
|
||||
'unsupported_layout',
|
||||
'missing_order_table',
|
||||
'other',
|
||||
] as const;
|
||||
|
||||
interface Props {
|
||||
modelValue: boolean;
|
||||
action: ReviewConfirmAction;
|
||||
confirmLoading?: boolean;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
confirmLoading: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', value: boolean): void;
|
||||
(e: 'confirm', payload: ReviewConfirmPayload): void;
|
||||
(e: 'cancel'): void;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const reasonCode = ref('other');
|
||||
const comment = ref('');
|
||||
const reasonMissing = ref(false);
|
||||
const commentMissing = ref(false);
|
||||
|
||||
/** 非订单 / 重识别 / 质量异常需要说明或原因选择。 */
|
||||
const needsDispositionInput = computed(
|
||||
() => props.action === 'non_order' || props.action === 'reparse' || props.action === 'quality_issue',
|
||||
);
|
||||
|
||||
const title = computed(() => t(`chat.shippingOrderReview.confirmDialog.${props.action}.title`));
|
||||
const impact = computed(() => t(`chat.shippingOrderReview.confirmDialog.${props.action}.impact`));
|
||||
const confirmText = computed(() => t(`chat.shippingOrderReview.confirmDialog.${props.action}.confirm`));
|
||||
const confirmTone = computed(() => (props.action === 'confirm' ? 'primary' : 'danger'));
|
||||
const confirmButtonClass = computed(() =>
|
||||
confirmTone.value === 'primary' ? 'btn-primary btn-sm' : 'btn-danger btn-sm',
|
||||
);
|
||||
|
||||
/**
|
||||
* 质量异常原因码的展示文案。
|
||||
* @param code - 后端允许的 quality reason 码
|
||||
*/
|
||||
const qualityReasonLabel = (code: string) =>
|
||||
t(`chat.shippingOrderReview.confirmDialog.qualityReasons.${code}`);
|
||||
|
||||
/** 关闭弹窗并同步 v-model。 */
|
||||
const closeDialog = () => {
|
||||
emit('update:modelValue', false);
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
emit('cancel');
|
||||
closeDialog();
|
||||
};
|
||||
|
||||
/**
|
||||
* 按 action 组装原因码与备注后触发确认。
|
||||
* 核心逻辑:质量异常 `other` 强制备注;非订单/重识别使用稳定 reasonCode + 自由 comment。
|
||||
*/
|
||||
const handleConfirm = () => {
|
||||
reasonMissing.value = false;
|
||||
commentMissing.value = false;
|
||||
const trimmedComment = comment.value.trim();
|
||||
|
||||
if (props.action === 'quality_issue') {
|
||||
if (!reasonCode.value) {
|
||||
reasonMissing.value = true;
|
||||
return;
|
||||
}
|
||||
if (reasonCode.value === 'other' && !trimmedComment) {
|
||||
commentMissing.value = true;
|
||||
return;
|
||||
}
|
||||
emit('confirm', { reasonCode: reasonCode.value, comment: trimmedComment });
|
||||
closeDialog();
|
||||
return;
|
||||
}
|
||||
|
||||
if (props.action === 'non_order' || props.action === 'reparse') {
|
||||
if (!trimmedComment) {
|
||||
commentMissing.value = true;
|
||||
return;
|
||||
}
|
||||
const code = props.action === 'non_order' ? 'non_order' : 'document_quality';
|
||||
emit('confirm', { reasonCode: code, comment: trimmedComment });
|
||||
closeDialog();
|
||||
return;
|
||||
}
|
||||
|
||||
emit('confirm', { reasonCode: '', comment: '' });
|
||||
closeDialog();
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(open) => {
|
||||
if (!open) {
|
||||
reasonCode.value = 'other';
|
||||
comment.value = '';
|
||||
reasonMissing.value = false;
|
||||
commentMissing.value = false;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const onKeydown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape' && props.modelValue) handleCancel();
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(open) => {
|
||||
if (typeof document === 'undefined') return;
|
||||
if (open) document.addEventListener('keydown', onKeydown);
|
||||
else document.removeEventListener('keydown', onKeydown);
|
||||
},
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (typeof document !== 'undefined') document.removeEventListener('keydown', onKeydown);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="modelValue"
|
||||
class="dialog-overlay z-50 flex items-center justify-center p-4"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-label="title"
|
||||
data-testid="review-action-confirm-dialog"
|
||||
@click.self="handleCancel"
|
||||
>
|
||||
<div class="dialog-panel w-full max-w-md space-y-4 p-5">
|
||||
<header>
|
||||
<h2 class="text-base font-semibold text-primary">{{ title }}</h2>
|
||||
<p class="mt-2 text-sm text-secondary">{{ impact }}</p>
|
||||
</header>
|
||||
|
||||
<template v-if="needsDispositionInput">
|
||||
<label v-if="action === 'quality_issue'" class="block space-y-1 text-sm">
|
||||
<span class="text-secondary">{{ t('chat.shippingOrderReview.confirmDialog.reasonCodeLabel') }}</span>
|
||||
<select
|
||||
v-model="reasonCode"
|
||||
class="select-field w-full text-sm"
|
||||
data-testid="review-action-reason-code"
|
||||
@change="reasonMissing = false"
|
||||
>
|
||||
<option v-for="code in QUALITY_REASON_CODES" :key="code" :value="code">
|
||||
{{ qualityReasonLabel(code) }}
|
||||
</option>
|
||||
</select>
|
||||
<p v-if="reasonMissing" class="text-xs text-rose-600 dark:text-rose-400">
|
||||
{{ t('chat.shippingOrderReview.confirmDialog.reasonCodeRequired') }}
|
||||
</p>
|
||||
</label>
|
||||
|
||||
<label class="block space-y-1 text-sm">
|
||||
<span class="text-secondary">{{ t('chat.shippingOrderReview.confirmDialog.reasonLabel') }}</span>
|
||||
<textarea
|
||||
v-model="comment"
|
||||
rows="3"
|
||||
class="input-field w-full resize-y text-sm"
|
||||
:placeholder="t('chat.shippingOrderReview.confirmDialog.reasonPlaceholder')"
|
||||
data-testid="review-action-reason"
|
||||
@input="commentMissing = false"
|
||||
/>
|
||||
<p v-if="commentMissing" class="text-xs text-rose-600 dark:text-rose-400">
|
||||
{{ t('chat.shippingOrderReview.confirmDialog.reasonRequired') }}
|
||||
</p>
|
||||
</label>
|
||||
</template>
|
||||
|
||||
<footer class="flex justify-end gap-2 pt-1">
|
||||
<button type="button" class="btn-secondary btn-sm" :disabled="confirmLoading" @click="handleCancel">
|
||||
{{ t('common.deleteDialog.cancel') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
:class="confirmButtonClass"
|
||||
:disabled="confirmLoading"
|
||||
data-testid="review-action-confirm-submit"
|
||||
@click="handleConfirm"
|
||||
>
|
||||
{{ confirmLoading ? t('chat.shippingOrderReview.saving') : confirmText }}
|
||||
</button>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
@@ -0,0 +1,326 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewAuditTrailDrawer.vue
|
||||
用途:复核 Case 业务审计时间线按需抽屉(含变更前后快照与字段差异)。
|
||||
依赖:vue-i18n、listWorkspaceShippingOrderReviewAuditTimeline。
|
||||
逻辑:open 时拉取第一页;展开优先展示业务可读差异(字段名/前后值/原因);
|
||||
原始 JSON 折叠为技术详情;敏感事件显示脱敏提示。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { listWorkspaceShippingOrderReviewAuditTimeline } from '@/features/chat/api/shipping.api';
|
||||
import type { ShippingOrderReviewAuditTimelineItem } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
type AuditDiffRow = {
|
||||
key?: string;
|
||||
path?: string;
|
||||
field?: string;
|
||||
label?: string;
|
||||
change?: string;
|
||||
before?: unknown;
|
||||
after?: unknown;
|
||||
};
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
caseNo: string;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const msg = useMessage();
|
||||
const items = ref<ShippingOrderReviewAuditTimelineItem[]>([]);
|
||||
const loading = ref(false);
|
||||
const page = ref(1);
|
||||
const total = ref(0);
|
||||
const expandedId = ref<number | null>(null);
|
||||
const pageSize = 50;
|
||||
|
||||
/**
|
||||
* 格式化审计时间。
|
||||
*/
|
||||
function formatTime(value: string | null | undefined): string {
|
||||
if (!value) return '—';
|
||||
const date = new Date(value);
|
||||
return Number.isNaN(date.getTime()) ? value : date.toLocaleString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 事件类型本地化。
|
||||
*/
|
||||
function eventLabel(item: ShippingOrderReviewAuditTimelineItem): string {
|
||||
const eventType = String(item.event_type || item.action || '').trim();
|
||||
const key = `chat.shippingOrderReview.auditTrail.events.${eventType}`;
|
||||
if (eventType && te(key)) return t(key);
|
||||
return eventType || t('chat.shippingOrderReview.auditTrail.unknownEvent');
|
||||
}
|
||||
|
||||
/**
|
||||
* 将审计标量格式化为业务可读短文本。
|
||||
*/
|
||||
function formatScalar(value: unknown): string {
|
||||
if (value == null || value === '') return '—';
|
||||
if (typeof value === 'boolean') {
|
||||
return value
|
||||
? t('chat.shippingOrderReview.auditTrail.boolTrue')
|
||||
: t('chat.shippingOrderReview.auditTrail.boolFalse');
|
||||
}
|
||||
if (typeof value === 'object') {
|
||||
try {
|
||||
return JSON.stringify(value);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 快照/差异技术详情(原始 JSON)。
|
||||
*/
|
||||
function formatJson(value: unknown): string {
|
||||
if (value == null) return '—';
|
||||
try {
|
||||
return JSON.stringify(value, null, 2);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制技术详情 JSON 到剪贴板。
|
||||
*/
|
||||
async function copyJson(value: unknown) {
|
||||
const text = formatJson(value);
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
msg.success(t('chat.shippingOrderReview.auditTrail.copyDone'));
|
||||
} catch {
|
||||
msg.warning(t('chat.shippingOrderReview.auditTrail.copyFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 差异字段业务名称(优先 label/field,其次 path)。
|
||||
*/
|
||||
function diffFieldLabel(row: AuditDiffRow): string {
|
||||
const label = String(row.label || row.field || row.key || row.path || '').trim();
|
||||
return label || t('chat.shippingOrderReview.auditTrail.unknownField');
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化差异列表,供业务表格渲染。
|
||||
*/
|
||||
function normalizeDiffRows(diff: unknown): AuditDiffRow[] {
|
||||
if (!Array.isArray(diff)) return [];
|
||||
return diff.filter((row): row is AuditDiffRow => Boolean(row) && typeof row === 'object');
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换条目展开。
|
||||
*/
|
||||
function toggleExpand(id: number) {
|
||||
expandedId.value = expandedId.value === id ? null : id;
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取指定页审计条目并合并。
|
||||
*/
|
||||
async function loadPage(nextPage: number, append = false) {
|
||||
if (!props.caseNo || loading.value) return;
|
||||
loading.value = true;
|
||||
try {
|
||||
const result = await listWorkspaceShippingOrderReviewAuditTimeline(props.caseNo, {
|
||||
page: nextPage,
|
||||
page_size: pageSize,
|
||||
});
|
||||
total.value = result.total;
|
||||
page.value = result.page;
|
||||
items.value = append ? [...items.value, ...result.items] : result.items;
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.auditTrail.loadFailed'));
|
||||
msg.warning(message);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开抽屉时重置并加载第一页。
|
||||
*/
|
||||
watch(
|
||||
() => [props.open, props.caseNo] as const,
|
||||
([isOpen, caseNo]) => {
|
||||
if (!isOpen || !caseNo) return;
|
||||
items.value = [];
|
||||
page.value = 1;
|
||||
total.value = 0;
|
||||
expandedId.value = null;
|
||||
void loadPage(1, false);
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* 加载下一页。
|
||||
*/
|
||||
function loadMore() {
|
||||
if (items.value.length >= total.value) return;
|
||||
void loadPage(page.value + 1, true);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-40 flex justify-end bg-slate-900/30"
|
||||
data-testid="review-audit-trail-drawer"
|
||||
@click.self="emit('close')"
|
||||
>
|
||||
<aside class="flex h-full w-full max-w-xl flex-col bg-surface shadow-xl">
|
||||
<header class="flex items-center justify-between gap-2 border-b border-default px-4 py-3">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.auditTrail.title') }}</h2>
|
||||
<p class="text-[11px] text-muted">{{ t('chat.shippingOrderReview.auditTrail.subtitle') }}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-default px-2 py-1 text-xs hover-surface-soft"
|
||||
data-testid="review-audit-trail-close"
|
||||
@click="emit('close')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workbench.close') }}
|
||||
</button>
|
||||
</header>
|
||||
<div class="min-h-0 flex-1 overflow-y-auto p-4">
|
||||
<p v-if="loading && !items.length" class="text-sm text-muted">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.loading') }}
|
||||
</p>
|
||||
<p v-else-if="!items.length" class="text-sm text-muted">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.empty') }}
|
||||
</p>
|
||||
<ol v-else class="space-y-3">
|
||||
<li
|
||||
v-for="item in items"
|
||||
:key="item.id"
|
||||
class="rounded-lg border border-default bg-surface-soft px-3 py-2 text-xs dark:bg-slate-950/40"
|
||||
:data-testid="`review-audit-item-${item.id}`"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full flex-wrap items-center justify-between gap-2 text-left"
|
||||
@click="toggleExpand(item.id)"
|
||||
>
|
||||
<span class="font-medium text-primary">{{ eventLabel(item) }}</span>
|
||||
<time class="text-[10px] text-muted">{{ formatTime(item.created_at) }}</time>
|
||||
</button>
|
||||
<div class="mt-1 space-y-0.5 text-muted">
|
||||
<p v-if="item.actor_display || item.actor_type">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.actor', {
|
||||
actor: item.actor_display || item.actor_type || '—',
|
||||
}) }}
|
||||
</p>
|
||||
<p v-if="item.task_no">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.taskNo', { taskNo: item.task_no }) }}
|
||||
</p>
|
||||
<p v-if="item.result">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.result', { result: item.result }) }}
|
||||
</p>
|
||||
<p v-if="item.error_code" class="text-rose-700 dark:text-rose-300">
|
||||
{{ item.error_code }}
|
||||
</p>
|
||||
<p v-if="item.reason" class="text-secondary">{{ item.reason }}</p>
|
||||
</div>
|
||||
<div
|
||||
v-if="expandedId === item.id"
|
||||
class="mt-2 space-y-2 border-t border-default pt-2"
|
||||
data-testid="review-audit-item-details"
|
||||
>
|
||||
<p v-if="item.sensitive_redacted" class="text-amber-800 dark:text-amber-200">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.sensitiveRedacted') }}
|
||||
</p>
|
||||
<template v-else>
|
||||
<div v-if="normalizeDiffRows(item.diff).length" data-testid="review-audit-business-diff">
|
||||
<p class="mb-1 font-medium text-secondary">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.diff') }}
|
||||
</p>
|
||||
<ul class="space-y-1.5">
|
||||
<li
|
||||
v-for="(row, idx) in normalizeDiffRows(item.diff)"
|
||||
:key="idx"
|
||||
class="rounded bg-surface px-2 py-1.5 text-[11px]"
|
||||
>
|
||||
<p class="font-medium text-primary">{{ diffFieldLabel(row) }}</p>
|
||||
<p class="mt-0.5 text-muted">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.beforeValue') }}:
|
||||
<span class="text-secondary">{{ formatScalar(row.before) }}</span>
|
||||
</p>
|
||||
<p class="text-muted">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.afterValue') }}:
|
||||
<span class="text-secondary">{{ formatScalar(row.after) }}</span>
|
||||
</p>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<p v-if="item.reason" class="text-[11px] text-secondary">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.reason') }}:{{ item.reason }}
|
||||
</p>
|
||||
<details class="rounded border border-default">
|
||||
<summary class="cursor-pointer px-2 py-1 text-[11px] text-muted">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.technicalDetails') }}
|
||||
</summary>
|
||||
<div class="space-y-2 border-t border-default p-2">
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<p class="font-medium text-secondary">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.before') }}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-default px-1.5 py-0.5 text-[11px] hover-surface-soft"
|
||||
data-testid="review-audit-copy-before"
|
||||
@click="copyJson(item.before_snapshot)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.auditTrail.copyJson') }}
|
||||
</button>
|
||||
</div>
|
||||
<pre class="max-h-32 overflow-auto rounded bg-surface p-2 text-xs leading-relaxed">{{ formatJson(item.before_snapshot) }}</pre>
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<p class="font-medium text-secondary">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.after') }}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-default px-1.5 py-0.5 text-[11px] hover-surface-soft"
|
||||
data-testid="review-audit-copy-after"
|
||||
@click="copyJson(item.after_snapshot)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.auditTrail.copyJson') }}
|
||||
</button>
|
||||
</div>
|
||||
<pre class="max-h-32 overflow-auto rounded bg-surface p-2 text-xs leading-relaxed">{{ formatJson(item.after_snapshot) }}</pre>
|
||||
</div>
|
||||
</details>
|
||||
</template>
|
||||
</div>
|
||||
</li>
|
||||
</ol>
|
||||
<button
|
||||
v-if="items.length < total"
|
||||
type="button"
|
||||
class="mt-3 w-full rounded border border-default px-2 py-1.5 text-xs hover-surface-soft disabled:opacity-50"
|
||||
data-testid="review-audit-trail-load-more"
|
||||
:disabled="loading"
|
||||
@click="loadMore"
|
||||
>
|
||||
{{ loading ? t('chat.shippingOrderReview.auditTrail.loading') : t('chat.shippingOrderReview.auditTrail.loadMore') }}
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</template>
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewAutomationStatusPanel.spec.ts
|
||||
* 用途:锁定自动处理状态仅在建单后展示,并保持阶段顺序一致。
|
||||
* 依赖:vitest、@vue/test-utils、vue-i18n。
|
||||
* 逻辑:上游未开始时,下游即使后端旧投影为 passed 也按未开始展示。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ReviewAutomationStatusPanel from './ReviewAutomationStatusPanel.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
automationStatus: {
|
||||
title: '自动处理状态',
|
||||
subtitle: '状态',
|
||||
statuses: { not_started: '未开始', passed: '已通过' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const processGate = {
|
||||
execution_no: 'EX-1',
|
||||
status: 'pending',
|
||||
gates_track: [
|
||||
{ gate_code: 'document', label: '文档解析', status: 'not_started', sequence_no: 1 },
|
||||
{ gate_code: 'reservation', label: '预约校验', status: 'passed', sequence_no: 2 },
|
||||
],
|
||||
};
|
||||
|
||||
describe('ReviewAutomationStatusPanel', () => {
|
||||
it('stays hidden before a ShippingTask is created', () => {
|
||||
const wrapper = mount(ReviewAutomationStatusPanel, {
|
||||
props: { processGate, taskCreated: false },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-automation-status-panel"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('does not show a downstream stage as passed when its upstream stage has not started', () => {
|
||||
const wrapper = mount(ReviewAutomationStatusPanel, {
|
||||
props: { processGate, taskCreated: true },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.text()).toContain('预约校验');
|
||||
expect(wrapper.text()).not.toContain('已通过');
|
||||
expect(wrapper.text().match(/未开始/g)).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewAutomationStatusPanel.vue
|
||||
用途:复核工作台「自动处理状态」只读区(技术 Gate 进度,禁止业务用户点技术重试)。
|
||||
依赖:vue-i18n、ShippingProcessGateUserSummary。
|
||||
逻辑:仅在任务已创建后展示 gates_track;按 sequence_no 排序,并在首个未完成阶段后
|
||||
抑制矛盾的下游“已通过”,不提供技术写操作。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingProcessGateUserSummary } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
processGate: ShippingProcessGateUserSummary | null | undefined;
|
||||
taskCreated?: boolean;
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
const track = computed(() => {
|
||||
if (!props.taskCreated) return [];
|
||||
const ordered = [...(props.processGate?.gates_track || [])]
|
||||
.sort((left, right) => Number(left.sequence_no || 0) - Number(right.sequence_no || 0));
|
||||
let upstreamReached = true;
|
||||
return ordered.map((item) => {
|
||||
const status = String(item.status || 'not_started');
|
||||
const normalizedStatus = upstreamReached ? status : 'not_started';
|
||||
if (!['passed', 'skipped'].includes(status)) upstreamReached = false;
|
||||
return { ...item, status: normalizedStatus };
|
||||
});
|
||||
});
|
||||
const visible = computed(() => track.value.length > 0);
|
||||
const technicalOnly = computed(() => Boolean(
|
||||
(props.processGate as { technical_auto_only?: boolean } | null | undefined)?.technical_auto_only,
|
||||
));
|
||||
|
||||
/**
|
||||
* Gate 状态本地化标签。
|
||||
*/
|
||||
function statusLabel(status: string): string {
|
||||
const key = `chat.shippingOrderReview.automationStatus.statuses.${status}`;
|
||||
return te(key) ? t(key) : status;
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态点样式。
|
||||
*/
|
||||
function statusClass(status: string): string {
|
||||
const s = String(status || '');
|
||||
if (s === 'passed' || s === 'skipped') {
|
||||
return 'bg-emerald-500';
|
||||
}
|
||||
if (s === 'running' || s === 'queued') {
|
||||
return 'bg-sky-500 animate-pulse';
|
||||
}
|
||||
if (s === 'blocked_manual' || s === 'blocked_retryable' || s === 'waiting_external') {
|
||||
return 'bg-amber-500';
|
||||
}
|
||||
if (s === 'failed_terminal') {
|
||||
return 'bg-rose-500';
|
||||
}
|
||||
return 'bg-slate-300 dark:bg-slate-600';
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="visible"
|
||||
class="rounded-xl border border-default bg-surface p-3 shadow-sm"
|
||||
data-testid="review-automation-status-panel"
|
||||
>
|
||||
<header class="mb-2">
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.automationStatus.title') }}</h2>
|
||||
<p class="mt-0.5 text-xs text-muted">{{ t('chat.shippingOrderReview.automationStatus.subtitle') }}</p>
|
||||
</header>
|
||||
|
||||
<ol class="space-y-1.5">
|
||||
<li
|
||||
v-for="item in track"
|
||||
:key="String(item.gate_code)"
|
||||
class="flex items-center gap-2 text-[11px] text-secondary"
|
||||
>
|
||||
<span
|
||||
class="inline-block h-2 w-2 shrink-0 rounded-full"
|
||||
:class="statusClass(String(item.status || ''))"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span class="min-w-0 flex-1 truncate">{{ item.label || item.gate_code }}</span>
|
||||
<span class="shrink-0 text-muted">{{ statusLabel(String(item.status || '')) }}</span>
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
<p
|
||||
v-if="technicalOnly"
|
||||
class="mt-2 text-[11px] text-muted"
|
||||
data-testid="review-automation-technical-hint"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.automationStatus.technicalHint') }}
|
||||
</p>
|
||||
<p
|
||||
v-else-if="processGate?.blocking_message"
|
||||
class="mt-2 text-[11px] text-amber-900 dark:text-amber-100"
|
||||
>
|
||||
{{ processGate.blocking_message }}
|
||||
</p>
|
||||
</section>
|
||||
</template>
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewBuildEligibilityDetailsDrawer.spec.ts
|
||||
* 用途:锁定完整检查必须展示具体冲突字段、行号、来源和值。
|
||||
* 依赖:vitest、@vue/test-utils、vue-i18n。
|
||||
* 逻辑:field_conflict issue 不再输出笼统问题;专用冲突投影负责完整展示。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ReviewBuildEligibilityDetailsDrawer from './ReviewBuildEligibilityDetailsDrawer.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: { shippingOrderReview: {
|
||||
line: '第 {index} 行',
|
||||
buildEligibility: {
|
||||
overallResult: '整单结果', canBuildYes: '可建单', canBuildNo: '待处理',
|
||||
manualBuildLabel: '人工建单', autoBuildLabel: '自动建单',
|
||||
autoBuildYes: '可自动建单', autoBuildNo: '暂不可自动建单',
|
||||
manualConfirmOnly: '需人工确认', blockReasons: { unknown: '未知阻断' },
|
||||
routingStatus: { unknown: '未知' },
|
||||
},
|
||||
workbench: {
|
||||
fullChecksTitle: '完整订单检查', close: '关闭', issueDetails: '问题明细',
|
||||
conflictFields: '字段冲突明细', conflictDetailsPending: '冲突明细尚未同步,请刷新后查看。',
|
||||
requiredField: '字段', missingValue: '缺少值', noLineChecks: '暂无明细检查',
|
||||
manualReview: { customer: '确认客户', lineInventory: '第 {line} 行库存', noCandidates: '无' },
|
||||
},
|
||||
} },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const eligibility = {
|
||||
can_build: false,
|
||||
status: 'qualified',
|
||||
issues: [{ code: 'field_conflict', message: '同一字段存在不同来源值冲突' }],
|
||||
line_projections: [],
|
||||
};
|
||||
|
||||
describe('ReviewBuildEligibilityDetailsDrawer', () => {
|
||||
it('separates manual buildability from automatic creation eligibility', () => {
|
||||
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
|
||||
props: {
|
||||
open: true,
|
||||
eligibility: {
|
||||
can_build: true,
|
||||
can_auto_create: false,
|
||||
status: 'ready',
|
||||
failed_gates: ['field_conflicts_resolved'],
|
||||
issues: [],
|
||||
line_projections: [],
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 关键断言:抽屉不能只写“可建单”而让自动门禁失败看似矛盾。
|
||||
expect(wrapper.find('[data-testid="review-eligibility-manual-status"]').text()).toContain('可建单');
|
||||
expect(wrapper.find('[data-testid="review-eligibility-auto-status"]').text()).toContain('暂不可自动建单');
|
||||
});
|
||||
|
||||
it('does not render an empty diagnostic section when there are no diagnostic facts', () => {
|
||||
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
|
||||
props: {
|
||||
open: true,
|
||||
eligibility: {
|
||||
can_build: true,
|
||||
can_auto_create: false,
|
||||
status: 'ready',
|
||||
issues: [],
|
||||
failed_gates: [],
|
||||
assessment: { missing_required_fields: [] },
|
||||
line_projections: [{ line_key: 'L1', line_index: 0, can_build: true }],
|
||||
},
|
||||
fieldConflicts: [],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 关键断言:没有问题明细时不能留下无内容的边框占位区。
|
||||
expect(wrapper.findAll('section')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('lists the exact conflicting field, line, sources and values', () => {
|
||||
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
|
||||
props: {
|
||||
open: true,
|
||||
eligibility,
|
||||
fieldLabels: { unit_price: '单价' },
|
||||
fieldConflicts: [{
|
||||
conflict_key: 'unit_price:0', field_code: 'unit_price', line_index: 0,
|
||||
reason: 'field_conflict',
|
||||
options: [
|
||||
{ value_key: '50.43', display_value: '50.43', sources: ['PDF 表格'] },
|
||||
{ value_key: '51.00', display_value: '51.00', sources: ['邮件正文'] },
|
||||
],
|
||||
}],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
const details = wrapper.find('[data-testid="review-eligibility-conflict-details"]');
|
||||
expect(details.text()).toContain('第 1 行');
|
||||
expect(details.text()).toContain('单价');
|
||||
expect(details.text()).toContain('PDF 表格:50.43');
|
||||
expect(details.text()).toContain('邮件正文:51.00');
|
||||
expect(wrapper.find('[data-testid="review-eligibility-blocking-reasons"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('shows an explicit synchronization warning when conflict detail is absent', () => {
|
||||
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
|
||||
props: { open: true, eligibility, fieldConflicts: [] },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-eligibility-conflict-details-missing"]').text())
|
||||
.toContain('冲突明细尚未同步');
|
||||
});
|
||||
|
||||
it('filters a stale conflict issue after the current order is buildable', () => {
|
||||
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
|
||||
props: {
|
||||
open: true,
|
||||
eligibility: { ...eligibility, can_build: true },
|
||||
fieldConflicts: [],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-eligibility-conflict-details-missing"]').exists()).toBe(false);
|
||||
expect(wrapper.text()).not.toContain('同一字段存在不同来源值冲突');
|
||||
});
|
||||
});
|
||||
+324
@@ -0,0 +1,324 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewBuildEligibilityDetailsDrawer.vue
|
||||
用途:完整建单检查项抽屉(逐行投影、阻断原因)。
|
||||
依赖:vue-i18n、ShippingOrderReviewBuildEligibility。
|
||||
逻辑:仅在用户主动展开时挂载;字段冲突必须展开 Case.field_conflicts 的字段、行号、
|
||||
来源和值,资格 issue 只作为汇总,不得用笼统文案替代冲突明细。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderReviewBuildEligibility } from '@/features/chat/types/shipping.api.types';
|
||||
import type { ShippingOrderReviewFieldConflict } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
eligibility: ShippingOrderReviewBuildEligibility | null;
|
||||
fieldConflicts?: ShippingOrderReviewFieldConflict[] | null;
|
||||
fieldLabels?: Record<string, string>;
|
||||
/** 客户面板的权威确认事实;已确认时不得重放历史 customer_* issue。 */
|
||||
customerResolved?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
'focus-line': [lineIndex: number];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
/**
|
||||
* 解析行级阻断原因文案。
|
||||
*/
|
||||
function blockReasonLabel(reason?: string | null): string {
|
||||
const normalized = String(reason || '').trim();
|
||||
if (!normalized) return '—';
|
||||
const key = `chat.shippingOrderReview.buildEligibility.blockReasons.${normalized}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.blockReasons.unknown');
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析路由状态文案。
|
||||
*/
|
||||
function routingStatusLabel(status?: string | null): string {
|
||||
const normalized = String(status || '').trim();
|
||||
if (!normalized) return '—';
|
||||
const key = `chat.shippingOrderReview.buildEligibility.routingStatus.${normalized}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.routingStatus.unknown');
|
||||
}
|
||||
|
||||
function issueLabel(issue: Record<string, unknown>): string {
|
||||
const field = String(issue.field_code || issue.field_id || '').trim();
|
||||
const code = String(issue.code || '').trim();
|
||||
if (field) {
|
||||
const label = props.fieldLabels?.[field] || field;
|
||||
return `${t('chat.shippingOrderReview.workbench.requiredField')}: ${label}`;
|
||||
}
|
||||
const lineIndex = Number.isFinite(Number(issue.line_index)) ? Number(issue.line_index) : null;
|
||||
const candidates = Array.isArray(issue.candidate_inventory_source_codes)
|
||||
? issue.candidate_inventory_source_codes.map((item) => {
|
||||
const sourceCode = String(item || '').trim();
|
||||
return props.eligibility?.inventory_source_labels?.[sourceCode] || sourceCode;
|
||||
}).filter(Boolean)
|
||||
: [];
|
||||
if (code === 'customer_unresolved') return t('chat.shippingOrderReview.workbench.manualReview.customer');
|
||||
if (lineIndex !== null && (candidates.length || code === 'require_manual_review' || code.includes('inventory_source'))) {
|
||||
return t('chat.shippingOrderReview.workbench.manualReview.lineInventory', {
|
||||
line: lineIndex + 1,
|
||||
candidates: candidates.length ? candidates.join('、') : t('chat.shippingOrderReview.workbench.manualReview.noCandidates'),
|
||||
});
|
||||
}
|
||||
const key = `chat.shippingOrderReview.workbench.issueCodes.${code}`;
|
||||
return code && te(key) ? t(key) : blockReasonLabel(code);
|
||||
}
|
||||
|
||||
function missingFieldLabel(code: string): string {
|
||||
const label = props.fieldLabels?.[String(code)] || code;
|
||||
return `${label}:${t('chat.shippingOrderReview.workbench.missingValue')}`;
|
||||
}
|
||||
|
||||
function conflictOptionLabel(option: { display_value?: unknown; value_key?: string; sources?: string[] }): string {
|
||||
const value = String(option.display_value ?? option.value_key ?? '—').trim() || '—';
|
||||
const sources = (option.sources || []).map((source) => String(source || '').trim()).filter(Boolean);
|
||||
return sources.length ? `${sources.join('、')}:${value}` : value;
|
||||
}
|
||||
|
||||
/** 异常行置顶,已通过行排后。 */
|
||||
const orderedLines = computed(() => {
|
||||
const lines = [...(props.eligibility?.line_projections || [])];
|
||||
return lines.sort((a, b) => {
|
||||
const aBlocked = a.can_build === false ? 0 : 1;
|
||||
const bBlocked = b.can_build === false ? 0 : 1;
|
||||
if (aBlocked !== bBlocked) return aBlocked - bBlocked;
|
||||
return (a.line_index ?? 0) - (b.line_index ?? 0);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 完整检查与摘要卡共用客户确认事实:服务端刷新前残留的客户 issue 不得误导用户。
|
||||
*/
|
||||
const effectiveIssues = computed(() => (props.eligibility?.issues || []).filter((issue) => {
|
||||
if (props.customerResolved !== true) return true;
|
||||
const code = String(issue.code || '').trim().toLowerCase();
|
||||
const reason = String(issue.reason_code || '').trim().toLowerCase();
|
||||
const gate = String(issue.owning_gate_code || '').trim().toLowerCase();
|
||||
return !(
|
||||
code.startsWith('customer_')
|
||||
|| reason.startsWith('customer_')
|
||||
|| gate === 'customer_resolution'
|
||||
|| gate === 'customer_confirmed'
|
||||
);
|
||||
}));
|
||||
|
||||
/** 资格 issue 中是否声明了字段冲突。 */
|
||||
const hasFieldConflictIssue = computed(() => props.eligibility?.can_build === false && effectiveIssues.value.some((issue) => {
|
||||
const code = String(issue.code || issue.reason_code || '').trim().toLowerCase();
|
||||
const gate = String(issue.owning_gate_code || '').trim().toLowerCase();
|
||||
return code.includes('field_conflict') || gate === 'field_conflict_resolution';
|
||||
}));
|
||||
|
||||
/** 字段冲突由专用明细区展示,避免问题列表重复输出一句笼统说明。 */
|
||||
const nonConflictIssues = computed(() => effectiveIssues.value.filter((issue) => {
|
||||
const code = String(issue.code || issue.reason_code || '').trim().toLowerCase();
|
||||
const gate = String(issue.owning_gate_code || '').trim().toLowerCase();
|
||||
const isConflict = code.includes('field_conflict') || gate === 'field_conflict_resolution';
|
||||
if (!isConflict) return true;
|
||||
// 当前资格已通过且专用冲突投影为空时,这是旧 validation snapshot 残留,禁止误报。
|
||||
return false;
|
||||
}));
|
||||
const unexplainedBlocked = computed(() => Boolean(
|
||||
props.eligibility
|
||||
&& props.eligibility.can_build === false
|
||||
&& !effectiveIssues.value.length
|
||||
&& !props.eligibility.failed_gates?.length
|
||||
&& !props.eligibility.assessment?.missing_required_fields?.length
|
||||
&& !(props.eligibility.line_projections || []).some((line) => line.can_build === false),
|
||||
));
|
||||
|
||||
/** 有可解释的诊断事实时才渲染中段,避免通过订单留下空白占位框。 */
|
||||
const hasDiagnosticDetails = computed(() => Boolean(
|
||||
props.eligibility?.assessment?.missing_required_fields?.length
|
||||
|| nonConflictIssues.value.length
|
||||
|| unexplainedBlocked.value
|
||||
|| props.fieldConflicts?.length
|
||||
|| hasFieldConflictIssue.value
|
||||
));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="open && eligibility"
|
||||
class="fixed inset-0 z-40 flex justify-end bg-slate-900/30"
|
||||
data-testid="review-eligibility-details-drawer"
|
||||
@click.self="emit('close')"
|
||||
>
|
||||
<aside class="flex h-full w-full max-w-md flex-col bg-surface shadow-xl">
|
||||
<header class="flex items-center justify-between gap-2 border-b border-default px-4 py-3">
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.workbench.fullChecksTitle') }}</h2>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-default px-2 py-1 text-xs hover-surface-soft"
|
||||
data-testid="review-eligibility-details-close"
|
||||
@click="emit('close')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workbench.close') }}
|
||||
</button>
|
||||
</header>
|
||||
<div class="min-h-0 flex-1 space-y-2 overflow-y-auto p-4">
|
||||
<section
|
||||
class="rounded-lg border px-3 py-2 text-xs"
|
||||
:class="eligibility.can_build === null
|
||||
? 'border-default bg-surface-soft text-primary '
|
||||
: eligibility.can_build
|
||||
? 'border-emerald-200 bg-emerald-50 text-emerald-900 dark:border-emerald-900 dark:bg-emerald-950/30 dark:text-emerald-100'
|
||||
: 'border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100'"
|
||||
data-testid="review-eligibility-details-overall"
|
||||
>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<span class="font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.overallResult') }}</span>
|
||||
<span class="text-secondary">{{ t('chat.shippingOrderReview.buildEligibility.manualBuildLabel') }}</span>
|
||||
<span class="rounded-full px-2 py-0.5 font-medium" :class="eligibility.can_build === null ? 'bg-surface-strong text-secondary ' : eligibility.can_build ? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/60 dark:text-emerald-100' : 'bg-amber-100 text-amber-900 dark:bg-amber-900/60 dark:text-amber-100'">
|
||||
<span data-testid="review-eligibility-manual-status">{{ eligibility.can_build === null
|
||||
? t('chat.shippingOrderReview.buildEligibility.notValidated')
|
||||
: eligibility.can_build
|
||||
? t('chat.shippingOrderReview.buildEligibility.canBuildYes')
|
||||
: t('chat.shippingOrderReview.buildEligibility.canBuildNo') }}</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-2 flex flex-wrap items-center justify-between gap-2">
|
||||
<span class="text-secondary">{{ t('chat.shippingOrderReview.buildEligibility.autoBuildLabel') }}</span>
|
||||
<span
|
||||
class="rounded-full px-2 py-0.5 font-medium"
|
||||
:class="eligibility.can_auto_create
|
||||
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/60 dark:text-emerald-100'
|
||||
: 'bg-amber-100 text-amber-900 dark:bg-amber-900/60 dark:text-amber-100'"
|
||||
data-testid="review-eligibility-auto-status"
|
||||
>
|
||||
{{ eligibility.can_auto_create
|
||||
? t('chat.shippingOrderReview.buildEligibility.autoBuildYes')
|
||||
: t('chat.shippingOrderReview.buildEligibility.autoBuildNo') }}
|
||||
</span>
|
||||
</div>
|
||||
<p v-if="eligibility.can_build && eligibility.can_auto_create === false" class="mt-1">
|
||||
{{ t('chat.shippingOrderReview.buildEligibility.manualConfirmOnly') }}
|
||||
</p>
|
||||
<div v-if="eligibility.can_build && eligibility.can_auto_create === false && (eligibility.auto_create_diagnostics?.reason_codes?.length || eligibility.auto_create_diagnostics?.failed_gates?.length)" class="mt-2">
|
||||
<div class="font-medium">{{ t('chat.shippingOrderReview.buildEligibility.autoCreateFailureTitle') }}</div>
|
||||
<ul class="mt-1 list-disc pl-4">
|
||||
<li v-for="reason in (eligibility.auto_create_failure_reasons?.length ? eligibility.auto_create_failure_reasons.map((item) => item.message) : (eligibility.auto_create_diagnostics.reason_codes?.length ? eligibility.auto_create_diagnostics.reason_codes : eligibility.auto_create_diagnostics.failed_gates))" :key="reason">
|
||||
{{ reason }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
<section
|
||||
v-if="hasDiagnosticDetails"
|
||||
class="rounded-lg border border-default bg-surface-soft p-3 text-xs dark:bg-slate-950/40"
|
||||
>
|
||||
<div v-if="eligibility.assessment?.missing_required_fields?.length" class="mt-2">
|
||||
<div class="font-medium">{{ t('chat.shippingOrderReview.workbench.requiredFields') }}</div>
|
||||
<div class="mt-1 text-rose-700 dark:text-rose-300">
|
||||
<ul class="mt-1 list-disc pl-4">
|
||||
<li v-for="code in eligibility.assessment.missing_required_fields" :key="String(code)">
|
||||
{{ missingFieldLabel(String(code)) }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="nonConflictIssues.length" class="mt-2" data-testid="review-eligibility-blocking-reasons">
|
||||
<div class="font-medium">{{ t('chat.shippingOrderReview.workbench.issueDetails') }}</div>
|
||||
<ul class="mt-1 list-disc pl-4">
|
||||
<li v-for="(issue, index) in nonConflictIssues" :key="index">
|
||||
{{ issueLabel(issue) }}
|
||||
<span v-if="issue.explainability?.message || issue.message" class="text-secondary">
|
||||
— {{ issue.explainability?.message || issue.message }}
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div v-if="unexplainedBlocked" class="mt-2 rounded border border-rose-200 bg-rose-50 px-2 py-1.5 text-rose-900 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-100" data-testid="review-eligibility-details-unexplained-block">
|
||||
{{ t('chat.shippingOrderReview.buildEligibility.unexplainedBlocked') }}
|
||||
</div>
|
||||
<div
|
||||
v-if="props.fieldConflicts?.length"
|
||||
class="mt-2 rounded-lg border border-rose-200 bg-rose-50 px-2.5 py-2 text-rose-950 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-100"
|
||||
data-testid="review-eligibility-conflict-details"
|
||||
>
|
||||
<div class="font-medium">{{ t('chat.shippingOrderReview.workbench.conflictFields') }}</div>
|
||||
<ul class="mt-2 space-y-2">
|
||||
<li
|
||||
v-for="conflict in props.fieldConflicts"
|
||||
:key="conflict.conflict_key"
|
||||
class="rounded border border-rose-200 bg-surface px-2 py-1.5 dark:border-rose-900"
|
||||
>
|
||||
<div class="font-semibold">
|
||||
<span v-if="conflict.line_index != null">{{ t('chat.shippingOrderReview.line', { index: conflict.line_index + 1 }) }} · </span>
|
||||
{{ props.fieldLabels?.[String(conflict.field_code)] || conflict.field_code }}
|
||||
</div>
|
||||
<ul class="mt-1 space-y-1 font-normal">
|
||||
<li v-for="(option, optionIndex) in conflict.options" :key="`${conflict.conflict_key}-${optionIndex}`">
|
||||
{{ conflictOptionLabel(option) }}
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div
|
||||
v-else-if="hasFieldConflictIssue"
|
||||
class="mt-2 rounded border border-amber-300 bg-amber-50 px-2.5 py-2 text-amber-900 dark:border-amber-800 dark:bg-amber-950/30 dark:text-amber-100"
|
||||
data-testid="review-eligibility-conflict-details-missing"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workbench.conflictDetailsPending') }}
|
||||
</div>
|
||||
</section>
|
||||
<article
|
||||
v-for="line in orderedLines"
|
||||
:key="String(line.line_no)"
|
||||
class="rounded-lg border border-default p-3 text-xs"
|
||||
:data-testid="`review-eligibility-detail-line-${line.line_no}`"
|
||||
>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="font-medium text-sky-700 hover:underline dark:text-sky-300"
|
||||
@click="emit('focus-line', Number(line.line_index ?? 0))"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.line', { index: (line.line_index ?? 0) + 1 }) }}
|
||||
</button>
|
||||
<span
|
||||
class="rounded-full px-2 py-0.5 text-[11px]"
|
||||
:class="line.can_build
|
||||
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
|
||||
: 'bg-rose-100 text-rose-800 dark:bg-rose-950 dark:text-rose-100'"
|
||||
>
|
||||
{{
|
||||
line.can_build
|
||||
? (eligibility.can_build
|
||||
? t('chat.shippingOrderReview.buildEligibility.lineCanBuild')
|
||||
: t('chat.shippingOrderReview.buildEligibility.linePassesOrderBlocked'))
|
||||
: t('chat.shippingOrderReview.buildEligibility.lineBlocked')
|
||||
}}
|
||||
</span>
|
||||
</div>
|
||||
<dl class="mt-2 grid gap-1">
|
||||
<div>
|
||||
<dt class="inline text-muted">{{ t('chat.shippingOrderReview.buildEligibility.routingStatusLabel') }}:</dt>
|
||||
<dd class="inline">{{ routingStatusLabel(line.routing_status) }}</dd>
|
||||
</div>
|
||||
<div v-if="line.block_reason">
|
||||
<dt class="inline text-muted">{{ t('chat.shippingOrderReview.buildEligibility.blockReason') }}:</dt>
|
||||
<dd class="inline">{{ blockReasonLabel(line.block_reason) }}</dd>
|
||||
</div>
|
||||
<div v-if="line.candidate_inventory_source_codes?.length">
|
||||
<dt class="inline text-muted">{{ t('chat.shippingOrderReview.buildEligibility.candidates') }}:</dt>
|
||||
<dd class="inline font-mono">{{ line.candidate_inventory_source_codes.join(', ') }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</article>
|
||||
<p v-if="!orderedLines.length" class="text-xs text-muted">
|
||||
{{ t('chat.shippingOrderReview.workbench.noLineChecks') }}
|
||||
</p>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</template>
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewBuildEligibilityPanel.vue
|
||||
用途:完整建单资格面板(含逐行投影);布局重构后标准侧栏改用 Summary + DetailsDrawer。
|
||||
依赖:vue-i18n、ProcessGateRecoveryCard、ShippingOrderReviewBuildEligibility 类型。
|
||||
逻辑:仍可供需要完整展开的入口复用;标准复核主路径不再默认挂载本组件;
|
||||
confirm_customer 向上转发,由对话页打开客户选择弹窗。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
|
||||
import type {
|
||||
ShippingOrderReviewBuildEligibility,
|
||||
ShippingProcessGateUserSummary,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
import type { ProcessGateNavigationContext } from '@/features/shipping-process-gates/composables/processGateNavigation';
|
||||
|
||||
const props = defineProps<{
|
||||
eligibility: ShippingOrderReviewBuildEligibility | null;
|
||||
processGate?: ShippingProcessGateUserSummary | null;
|
||||
canHandleGate?: boolean;
|
||||
navigationContext?: ProcessGateNavigationContext;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
gateRefreshed: [];
|
||||
confirmCustomer: [taskNo: string];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const canHandle = computed(() => props.canHandleGate !== false);
|
||||
|
||||
/**
|
||||
* 解析建单资格状态文案。
|
||||
*/
|
||||
function statusLabel(status: string): string {
|
||||
const key = `chat.shippingOrderReview.buildEligibility.status.${status}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.status.unknown');
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析行级阻断原因文案。
|
||||
*/
|
||||
function blockReasonLabel(reason?: string | null): string {
|
||||
const normalized = String(reason || '').trim();
|
||||
if (!normalized) return '—';
|
||||
const key = `chat.shippingOrderReview.buildEligibility.blockReasons.${normalized}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.blockReasons.unknown');
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析路由状态文案。
|
||||
*/
|
||||
function routingStatusLabel(status?: string | null): string {
|
||||
const normalized = String(status || '').trim();
|
||||
if (!normalized) return '—';
|
||||
const key = `chat.shippingOrderReview.buildEligibility.routingStatus.${normalized}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.routingStatus.unknown');
|
||||
}
|
||||
|
||||
/** 未满足建单资格的明细行。 */
|
||||
const blockedLines = computed(() =>
|
||||
(props.eligibility?.line_projections || []).filter((line) => line.can_build === false),
|
||||
);
|
||||
|
||||
/** 阻断摘要:按 block_reason 聚合行数。 */
|
||||
const blockingSummary = computed(() => {
|
||||
const counts = new Map<string, number>();
|
||||
for (const line of blockedLines.value) {
|
||||
const reason = String(line.block_reason || 'unknown').trim() || 'unknown';
|
||||
counts.set(reason, (counts.get(reason) || 0) + 1);
|
||||
}
|
||||
return [...counts.entries()].map(([reason, count]) => ({ reason, count }));
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-4">
|
||||
<ProcessGateRecoveryCard
|
||||
v-if="processGate?.current_blocking_gate"
|
||||
:summary="processGate"
|
||||
:can-handle="canHandle"
|
||||
:navigation-context="navigationContext"
|
||||
@refreshed="emit('gateRefreshed')"
|
||||
@refresh-needed="emit('gateRefreshed')"
|
||||
@confirm-customer="(taskNo) => emit('confirmCustomer', taskNo)"
|
||||
/>
|
||||
<section
|
||||
v-if="eligibility"
|
||||
class="rounded-xl border border-default bg-surface p-4 shadow-sm"
|
||||
data-testid="review-build-eligibility-panel"
|
||||
>
|
||||
<header class="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.title') }}</h2>
|
||||
<p class="mt-0.5 text-xs text-muted">
|
||||
{{ t('chat.shippingOrderReview.buildEligibility.subtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
class="rounded-full px-2.5 py-1 text-xs font-medium"
|
||||
:class="eligibility.can_build
|
||||
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
|
||||
: 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'"
|
||||
data-testid="review-build-eligibility-badge"
|
||||
>
|
||||
{{
|
||||
eligibility.can_build
|
||||
? t('chat.shippingOrderReview.buildEligibility.canBuildYes')
|
||||
: t('chat.shippingOrderReview.buildEligibility.canBuildNo')
|
||||
}}
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<dl class="grid gap-2 text-xs text-secondary sm:grid-cols-2">
|
||||
<div>
|
||||
<dt class="inline font-medium">{{ t('chat.shippingOrderReview.buildEligibility.statusLabel') }}:</dt>
|
||||
<dd class="inline">{{ statusLabel(eligibility.status) }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<div
|
||||
v-if="!eligibility.can_build && blockingSummary.length"
|
||||
class="mt-3 rounded-lg border border-amber-200 bg-amber-50 p-3 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
|
||||
data-testid="review-build-eligibility-blocking-summary"
|
||||
>
|
||||
<div class="font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.blockingSummary') }}</div>
|
||||
<ul class="mt-1 list-disc space-y-0.5 pl-4">
|
||||
<li v-for="item in blockingSummary" :key="item.reason">
|
||||
{{ blockReasonLabel(item.reason) }}
|
||||
<span class="text-amber-800 dark:text-amber-200">× {{ item.count }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div v-if="eligibility.line_projections.length" class="mt-3 space-y-2">
|
||||
<div class="text-xs font-semibold text-muted">
|
||||
{{ t('chat.shippingOrderReview.buildEligibility.lineProjections') }}
|
||||
</div>
|
||||
<article
|
||||
v-for="line in eligibility.line_projections"
|
||||
:key="String(line.line_no)"
|
||||
class="rounded-lg border border-default p-3 text-xs"
|
||||
:data-testid="`review-build-eligibility-line-${line.line_no}`"
|
||||
>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<span class="font-medium">
|
||||
{{ t('chat.shippingOrderReview.line', { index: (line.line_index ?? 0) + 1 }) }}
|
||||
</span>
|
||||
<span
|
||||
class="rounded-full px-2 py-0.5 text-[11px]"
|
||||
:class="line.can_build
|
||||
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
|
||||
: 'bg-rose-100 text-rose-800 dark:bg-rose-950 dark:text-rose-100'"
|
||||
>
|
||||
{{
|
||||
line.can_build
|
||||
? t('chat.shippingOrderReview.buildEligibility.lineCanBuild')
|
||||
: t('chat.shippingOrderReview.buildEligibility.lineBlocked')
|
||||
}}
|
||||
</span>
|
||||
</div>
|
||||
<dl class="mt-2 grid gap-1 sm:grid-cols-2">
|
||||
<div>
|
||||
<dt class="inline text-muted">{{ t('chat.shippingOrderReview.buildEligibility.reservation') }}:</dt>
|
||||
<dd class="inline font-mono">{{ line.effective_reservation_id || '—' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="inline text-muted">{{ t('chat.shippingOrderReview.buildEligibility.routingStatusLabel') }}:</dt>
|
||||
<dd class="inline">{{ routingStatusLabel(line.routing_status) }}</dd>
|
||||
</div>
|
||||
<div v-if="line.inventory_source_hint" class="sm:col-span-2">
|
||||
<dt class="inline text-muted">{{ t('chat.shippingOrderReview.buildEligibility.sourceHint') }}:</dt>
|
||||
<dd class="inline">{{ line.inventory_source_hint }}</dd>
|
||||
</div>
|
||||
<div v-if="line.candidate_inventory_source_codes?.length" class="sm:col-span-2">
|
||||
<dt class="inline text-muted">{{ t('chat.shippingOrderReview.buildEligibility.candidates') }}:</dt>
|
||||
<dd class="inline font-mono">{{ line.candidate_inventory_source_codes.join(', ') }}</dd>
|
||||
</div>
|
||||
<div v-if="line.block_reason" class="sm:col-span-2">
|
||||
<dt class="inline text-muted">{{ t('chat.shippingOrderReview.buildEligibility.blockReason') }}:</dt>
|
||||
<dd class="inline">{{ blockReasonLabel(line.block_reason) }}</dd>
|
||||
</div>
|
||||
<div v-if="line.selection_mode === 'manual' && line.manual_reason" class="sm:col-span-2">
|
||||
<dt class="inline text-muted">{{ t('chat.shippingOrderReview.buildEligibility.manualReason') }}:</dt>
|
||||
<dd class="inline">{{ line.manual_reason }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
+330
@@ -0,0 +1,330 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewBuildEligibilitySummary.spec.ts
|
||||
* 用途:锁定建单资格摘要卡默认只展示阻断摘要、完整检查按需展开契约。
|
||||
* 依赖:vitest、@vue/test-utils、vue-i18n。
|
||||
* 逻辑:验证 badge、首要阻断与 open-details emit;不渲染逐行投影列表。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ReviewBuildEligibilitySummary from './ReviewBuildEligibilitySummary.vue';
|
||||
import type { ShippingOrderReviewBuildEligibility } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
/**
|
||||
* 挂载摘要卡。
|
||||
*/
|
||||
function mountSummary(eligibility: ShippingOrderReviewBuildEligibility, customerResolved = false) {
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
issueCodes: { unknown: '未知问题' },
|
||||
buildEligibility: {
|
||||
title: '订单检查',
|
||||
canBuildYes: '可建单',
|
||||
canBuildNo: '待处理',
|
||||
blockReasons: { require_manual_review: '需人工确认', unknown: '未知阻断' },
|
||||
gates: {
|
||||
customer_confirmed: '客户已确认',
|
||||
required_fields_complete: '必填字段完整',
|
||||
},
|
||||
},
|
||||
workbench: {
|
||||
primaryBlock: '首要阻断原因',
|
||||
blockCount: '阻断项 {count} 项',
|
||||
viewFullChecks: '查看完整检查',
|
||||
manualReview: {
|
||||
customer: '请确认客户',
|
||||
field: '请确认字段:{field}',
|
||||
lineInventory: '第 {line} 行:请确认库存来源(候选:{candidates})',
|
||||
noCandidates: '暂无候选',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
return mount(ReviewBuildEligibilitySummary, {
|
||||
props: { eligibility, customerResolved },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('ReviewBuildEligibilitySummary', () => {
|
||||
it('shows primary block and emits open-details without listing all lines', async () => {
|
||||
const wrapper = mountSummary({
|
||||
can_build: false,
|
||||
status: 'blocked',
|
||||
issues: [{
|
||||
code: 'require_manual_review',
|
||||
severity: 'blocking',
|
||||
explainability: { message: '第 2 行库存来源待确认' },
|
||||
}],
|
||||
line_projections: [
|
||||
{ line_key: 'L1', line_index: 0, can_build: true },
|
||||
{ line_key: 'L2', line_index: 1, can_build: false, block_reason: 'require_manual_review' },
|
||||
],
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-build-eligibility-summary"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-build-eligibility-badge"]').text()).toContain('待处理');
|
||||
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').text()).toContain('第 2 行库存来源待确认');
|
||||
expect(wrapper.text()).not.toContain('L1');
|
||||
await wrapper.find('[data-testid="review-open-eligibility-details"]').trigger('click');
|
||||
expect(wrapper.emitted('open-details')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('does not keep a stale customer block after the customer is confirmed', () => {
|
||||
const wrapper = mountSummary({
|
||||
can_build: false,
|
||||
status: 'blocked',
|
||||
issues: [{
|
||||
code: 'customer_unresolved',
|
||||
severity: 'blocking',
|
||||
explainability: { message: '未能识别客户' },
|
||||
}],
|
||||
line_projections: [{
|
||||
line_key: 'L1',
|
||||
line_index: 0,
|
||||
can_build: false,
|
||||
block_reason: 'customer_unresolved',
|
||||
}],
|
||||
gates: { customer_confirmed: false },
|
||||
}, true);
|
||||
|
||||
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-eligibility-gate-checklist"]').text()).toContain('✓');
|
||||
});
|
||||
|
||||
it('ignores failed_gates customer_confirmed when customer is already resolved', () => {
|
||||
// 关键断言:客户已确认后不得再把「客户已确认」门禁文案投影为优先处理。
|
||||
const wrapper = mountSummary({
|
||||
can_build: false,
|
||||
status: 'blocked',
|
||||
issues: [],
|
||||
failed_gates: ['customer_confirmed', 'required_fields_complete'],
|
||||
gates: {
|
||||
customer_confirmed: true,
|
||||
required_fields_complete: false,
|
||||
},
|
||||
line_projections: [],
|
||||
}, true);
|
||||
|
||||
const block = wrapper.find('[data-testid="review-eligibility-primary-block"]');
|
||||
expect(block.exists()).toBe(true);
|
||||
expect(block.text()).not.toContain('客户已确认');
|
||||
});
|
||||
|
||||
it('projects concrete manual review facts before falling back to generic copy', () => {
|
||||
const wrapper = mountSummary({
|
||||
can_build: false,
|
||||
status: 'blocked',
|
||||
issues: [{
|
||||
code: 'require_manual_review',
|
||||
severity: 'blocking',
|
||||
line_index: 1,
|
||||
candidate_inventory_source_codes: ['WH_A', 'WH_B'],
|
||||
}],
|
||||
line_projections: [],
|
||||
inventory_source_labels: { WH_A: '华东仓', WH_B: '华南仓' },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').text())
|
||||
.toContain('第 2 行:请确认库存来源(候选:华东仓、华南仓)');
|
||||
});
|
||||
|
||||
it('explains a blocked order even when the API has no issue detail', () => {
|
||||
const wrapper = mountSummary({
|
||||
can_build: false,
|
||||
status: 'blocked',
|
||||
failed_gates: ['required_fields_complete'],
|
||||
issues: [],
|
||||
line_projections: [],
|
||||
});
|
||||
|
||||
// 有门禁 i18n 时优先展示业务门禁名,禁止露出内部 gate code。
|
||||
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').text())
|
||||
.toContain('必填字段完整');
|
||||
expect(wrapper.text()).not.toContain('required_fields_complete');
|
||||
});
|
||||
|
||||
it('does not expose internal build and auto-create layer names', () => {
|
||||
const wrapper = mountSummary({
|
||||
can_build: true,
|
||||
can_auto_create: false,
|
||||
status: 'qualified',
|
||||
issues: [],
|
||||
line_projections: [],
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="review-eligibility-layers"]').exists()).toBe(false);
|
||||
expect(wrapper.text()).not.toContain('can_build');
|
||||
expect(wrapper.text()).not.toContain('can_auto_create');
|
||||
});
|
||||
|
||||
it('keeps primary-block under focusBuildability for inventory combo (UI-03)', () => {
|
||||
// 关键断言:当前任务卡只承载动作,资格摘要仍保留库存门禁的具体解释。
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
issues: '问题',
|
||||
exceptionNav: { prev: '上', next: '下', prevHint: '', nextHint: '' },
|
||||
issueCodes: { unknown: '未知问题' },
|
||||
buildEligibility: {
|
||||
title: '订单检查',
|
||||
canBuildYes: '可建单',
|
||||
canBuildNo: '待处理',
|
||||
blockReasons: { require_manual_review: '需人工确认', unknown: '未知阻断' },
|
||||
gates: { required_fields_complete: '必填字段完整' },
|
||||
},
|
||||
workbench: {
|
||||
primaryBlock: '首要阻断原因',
|
||||
blockCount: '阻断项 {count} 项',
|
||||
viewFullChecks: '查看完整检查',
|
||||
manualReview: {
|
||||
customer: '请确认客户',
|
||||
field: '请确认字段:{field}',
|
||||
lineInventory: '第 {line} 行:请确认库存来源(候选:{candidates})',
|
||||
noCandidates: '暂无候选',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const wrapper = mount(ReviewBuildEligibilitySummary, {
|
||||
props: {
|
||||
eligibility: {
|
||||
can_build: false,
|
||||
status: 'blocked',
|
||||
issues: [{
|
||||
code: 'require_manual_review',
|
||||
severity: 'blocking',
|
||||
explainability: { message: '库存来源待确认' },
|
||||
}],
|
||||
line_projections: [],
|
||||
},
|
||||
focusBuildability: true,
|
||||
exceptionCount: 2,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-build-eligibility-summary"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-eligibility-gate-checklist"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-exception-nav"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps concrete missing-field diagnostics visible under focusBuildability (UI-03)', () => {
|
||||
// 关键断言:当前任务卡只承载动作;建单资格卡仍必须给出缺失字段和首要阻断,
|
||||
// 否则用户无法从泛化 Gate 文案定位订单明细问题。
|
||||
const wrapper = mount(ReviewBuildEligibilitySummary, {
|
||||
props: {
|
||||
eligibility: {
|
||||
can_build: false,
|
||||
status: 'blocked',
|
||||
issues: [{
|
||||
code: 'required_field_missing',
|
||||
severity: 'blocking',
|
||||
field_code: 'po_number',
|
||||
}],
|
||||
assessment: { missing_required_fields: ['po_number'], invalid_lines: [] },
|
||||
line_projections: [],
|
||||
},
|
||||
fieldLabels: { po_number: 'PO' },
|
||||
focusBuildability: true,
|
||||
exceptionCount: 1,
|
||||
},
|
||||
global: {
|
||||
plugins: [createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
issueCodes: { unknown: '未知' },
|
||||
issues: '问题',
|
||||
exceptionNav: { prev: '上', next: '下', prevHint: '', nextHint: '' },
|
||||
buildEligibility: {
|
||||
title: '订单检查',
|
||||
canBuildYes: '可建单',
|
||||
canBuildNo: '待处理',
|
||||
gates: {},
|
||||
blockReasons: { unknown: '未知' },
|
||||
},
|
||||
workbench: {
|
||||
primaryBlock: '首要阻断原因',
|
||||
blockCount: '{count}',
|
||||
viewFullChecks: '查看完整检查',
|
||||
missingRequiredFields: '缺失必填',
|
||||
conflictFields: '冲突',
|
||||
manualReview: {
|
||||
customer: '',
|
||||
field: '请确认字段:{field}',
|
||||
lineInventory: '',
|
||||
noCandidates: '',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})],
|
||||
},
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-eligibility-gate-checklist"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('缺失必填:PO');
|
||||
});
|
||||
|
||||
it('keeps passing eligibility concise when focusBuildability is enabled (UI-03)', () => {
|
||||
// 关键断言:无阻断时不额外渲染首要阻断;focusBuildability 不影响资格事实展示。
|
||||
const wrapper = mount(ReviewBuildEligibilitySummary, {
|
||||
props: {
|
||||
eligibility: {
|
||||
can_build: true,
|
||||
can_auto_create: true,
|
||||
status: 'qualified',
|
||||
issues: [],
|
||||
line_projections: [],
|
||||
},
|
||||
focusBuildability: true,
|
||||
},
|
||||
global: {
|
||||
plugins: [createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
buildEligibility: {
|
||||
title: '订单检查',
|
||||
canBuildYes: '可建单',
|
||||
canBuildNo: '待处理',
|
||||
gates: {},
|
||||
},
|
||||
workbench: {
|
||||
primaryBlock: '首要阻断原因',
|
||||
viewFullChecks: '查看完整检查',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})],
|
||||
},
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-build-eligibility-badge"]').text()).toContain('可建单');
|
||||
});
|
||||
});
|
||||
+335
@@ -0,0 +1,335 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewBuildEligibilitySummary.vue
|
||||
用途:复核摘要侧栏的建单资格压缩卡(可建单状态、门禁清单、首要阻断)。
|
||||
依赖:vue-i18n、ShippingOrderReviewBuildEligibility。
|
||||
逻辑:只展示业务结论、具体字段/明细问题与异常导航;隐藏 Gate code、
|
||||
can_build/can_auto_create 等实现标识;「查看完整检查」emit open-details。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderReviewBuildEligibility } from '@/features/chat/types/shipping.api.types';
|
||||
import type { ShippingOrderReviewFieldConflict } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
eligibility: ShippingOrderReviewBuildEligibility | null;
|
||||
fieldConflicts?: ShippingOrderReviewFieldConflict[] | null;
|
||||
fieldLabels?: Record<string, string>;
|
||||
customerResolved?: boolean;
|
||||
/** 可定位异常总数;由工作台统一收集草稿与门禁问题。 */
|
||||
exceptionCount?: number;
|
||||
/** 当前定位异常序号;未定位时为 0。 */
|
||||
exceptionOrdinal?: number;
|
||||
/**
|
||||
* 兼容旧调用方的展示偏好。当前任务卡只承载动作,建单门禁仍须完整展示,
|
||||
* 因此该参数不再隐藏字段级诊断,避免用户只能看到泛化阻断原因。
|
||||
*/
|
||||
focusBuildability?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'open-details': [];
|
||||
'navigate-exception': [delta: -1 | 1];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
/** 用户可见的关键建单前门禁(与后端 qualification gates 对齐)。 */
|
||||
const CHECKLIST_GATES = [
|
||||
'customer_confirmed',
|
||||
'required_fields_complete',
|
||||
'evidence_complete',
|
||||
'duplicate_resolved',
|
||||
'field_conflicts_resolved',
|
||||
] as const;
|
||||
|
||||
/** 阻断 issue 数量(优先 blocking severity)。 */
|
||||
const effectiveIssues = computed(() => {
|
||||
const issues = props.eligibility?.issues || [];
|
||||
if (props.customerResolved !== true) return issues;
|
||||
return issues.filter((item) => {
|
||||
const code = String(item.code || '').trim().toLowerCase();
|
||||
const reason = String(item.reason_code || '').trim().toLowerCase();
|
||||
const gate = String(item.owning_gate_code || '').trim().toLowerCase();
|
||||
return !(
|
||||
code.startsWith('customer_')
|
||||
|| reason.startsWith('customer_')
|
||||
|| gate === 'customer_resolution'
|
||||
|| gate === 'customer_confirmed'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const blockingIssueCount = computed(() => {
|
||||
const issues = effectiveIssues.value;
|
||||
const blocking = issues.filter((item) => String(item.severity || '') === 'blocking');
|
||||
return blocking.length || issues.length;
|
||||
});
|
||||
|
||||
/** 首要阻断文案:仅来自当前未解决业务问题;客户已确认时不得再显示客户确认阻断。 */
|
||||
const primaryBlockMessage = computed(() => {
|
||||
const issues = effectiveIssues.value;
|
||||
const primary = issues.find((item) => String(item.severity || '') === 'blocking') || issues[0];
|
||||
if (!primary) {
|
||||
const blockedLines = (props.eligibility?.line_projections || []).filter((line) => {
|
||||
if (line.can_build !== false) return false;
|
||||
if (props.customerResolved !== true) return true;
|
||||
const reason = String(line.block_reason || '').trim().toLowerCase();
|
||||
return !reason.startsWith('customer_');
|
||||
});
|
||||
if (!blockedLines.length) {
|
||||
const failedGate = (props.eligibility?.failed_gates || []).find((gate) => {
|
||||
const code = String(gate || '').trim().toLowerCase();
|
||||
if (props.customerResolved === true && (code === 'customer_confirmed' || code === 'customer_resolution')) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (!failedGate) return '';
|
||||
const gateKey = `chat.shippingOrderReview.buildEligibility.gates.${failedGate}`;
|
||||
return te(gateKey) ? t(gateKey) : t('chat.shippingOrderReview.issueCodes.unknown');
|
||||
}
|
||||
const reason = String(blockedLines[0]?.block_reason || '').trim();
|
||||
const key = `chat.shippingOrderReview.buildEligibility.blockReasons.${reason}`;
|
||||
return reason && te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.blockReasons.unknown');
|
||||
}
|
||||
const code = String(primary.code || '').trim().toLowerCase();
|
||||
// Draft 基础校验按冻结 Schema 返回 field_id,资格评估返回 field_code;两者都要映射,
|
||||
// 否则会丢失“究竟哪个字段没有值”的事实,只剩笼统的不可建单。
|
||||
const field = String(primary.field_code || primary.field_id || '').trim();
|
||||
const lineIndex = Number.isFinite(Number(primary.line_index)) ? Number(primary.line_index) : null;
|
||||
const candidates = Array.isArray(primary.candidate_inventory_source_codes)
|
||||
? primary.candidate_inventory_source_codes.map((item) => {
|
||||
const sourceCode = String(item || '').trim();
|
||||
return props.eligibility?.inventory_source_labels?.[sourceCode] || sourceCode;
|
||||
}).filter(Boolean)
|
||||
: [];
|
||||
if (code === 'customer_unresolved') {
|
||||
return t('chat.shippingOrderReview.workbench.manualReview.customer');
|
||||
}
|
||||
if (field) {
|
||||
return t('chat.shippingOrderReview.workbench.manualReview.field', {
|
||||
field: props.fieldLabels?.[field] || field,
|
||||
});
|
||||
}
|
||||
if (lineIndex !== null && (candidates.length || code === 'require_manual_review' || code.includes('inventory_source'))) {
|
||||
return t('chat.shippingOrderReview.workbench.manualReview.lineInventory', {
|
||||
line: lineIndex + 1,
|
||||
candidates: candidates.length ? candidates.join('、') : t('chat.shippingOrderReview.workbench.manualReview.noCandidates'),
|
||||
});
|
||||
}
|
||||
const message = String(primary.explainability?.message || primary.message || '').trim();
|
||||
if (message) return message;
|
||||
const key = `chat.shippingOrderReview.issueCodes.${code}`;
|
||||
if (code && te(key)) return t(key);
|
||||
const failedGate = (props.eligibility?.failed_gates || []).find((gate) => {
|
||||
const gateCode = String(gate || '').trim().toLowerCase();
|
||||
if (props.customerResolved === true && (gateCode === 'customer_confirmed' || gateCode === 'customer_resolution')) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (failedGate) {
|
||||
const gateKey = `chat.shippingOrderReview.buildEligibility.gates.${failedGate}`;
|
||||
return te(gateKey) ? t(gateKey) : t('chat.shippingOrderReview.issueCodes.unknown');
|
||||
}
|
||||
return t('chat.shippingOrderReview.issueCodes.unknown');
|
||||
});
|
||||
|
||||
/** 不可建单的行数。 */
|
||||
const blockedLineCount = computed(() =>
|
||||
(props.eligibility?.line_projections || []).filter((line) => line.can_build === false).length,
|
||||
);
|
||||
|
||||
const missingRequiredFields = computed(() => (props.eligibility?.assessment?.missing_required_fields || [])
|
||||
.map((code) => props.fieldLabels?.[String(code)] || String(code)));
|
||||
const conflictFields = computed(() => (props.fieldConflicts || []).map((item) => props.fieldLabels?.[String(item.field_code || '').trim()] || String(item.field_code || '').trim())
|
||||
.filter(Boolean));
|
||||
const lowConfidenceFields = computed(() => props.eligibility?.issues?.flatMap((issue) =>
|
||||
(issue.low_confidence_fields || []).map((item) => ({
|
||||
...item,
|
||||
label: props.fieldLabels?.[item.field_code] || item.field_code,
|
||||
})),
|
||||
) || []);
|
||||
const unexplainedBlocked = computed(() => Boolean(
|
||||
props.eligibility
|
||||
&& props.eligibility.status !== 'not_validated'
|
||||
&& props.eligibility.can_build === false
|
||||
&& !props.eligibility.issues?.length
|
||||
&& !props.eligibility.failed_gates?.length
|
||||
&& !props.eligibility.assessment?.missing_required_fields?.length
|
||||
&& !(props.eligibility.line_projections || []).some((line) => line.can_build === false),
|
||||
));
|
||||
|
||||
/**
|
||||
* 门禁勾选列表:优先 gates 映射;客户未确认时强制展示失败项。
|
||||
*/
|
||||
const gateChecklist = computed(() => {
|
||||
const gates = props.eligibility?.gates || {};
|
||||
const failed = new Set((props.eligibility?.failed_gates || []).map(String));
|
||||
const issues = props.eligibility?.issues || [];
|
||||
const customerIssue = issues.some((item) => String(item.code || '').startsWith('customer_'));
|
||||
const checks = CHECKLIST_GATES.map((gate) => {
|
||||
const known = Object.prototype.hasOwnProperty.call(gates, gate);
|
||||
let passed = known ? Boolean(gates[gate]) : !failed.has(gate);
|
||||
if (gate === 'customer_confirmed') {
|
||||
passed = props.customerResolved === true ? true : (customerIssue ? false : passed);
|
||||
}
|
||||
if (gate === 'field_conflicts_resolved' && props.fieldConflicts) {
|
||||
passed = props.fieldConflicts.length === 0;
|
||||
}
|
||||
if (gate === 'required_fields_complete' && props.eligibility?.assessment) {
|
||||
const missing = props.eligibility.assessment.missing_required_fields || [];
|
||||
const invalid = props.eligibility.assessment.invalid_lines || [];
|
||||
passed = missing.length === 0 && invalid.length === 0;
|
||||
}
|
||||
const labelKey = `chat.shippingOrderReview.buildEligibility.gates.${gate}`;
|
||||
return {
|
||||
gate,
|
||||
passed,
|
||||
label: te(labelKey) ? t(labelKey) : t('chat.shippingOrderReview.issueCodes.unknown'),
|
||||
};
|
||||
}).filter((item) => Object.keys(gates).length === 0 || Object.prototype.hasOwnProperty.call(gates, item.gate) || item.gate === 'customer_confirmed');
|
||||
return [
|
||||
{
|
||||
gate: 'overall_build_result',
|
||||
passed: props.eligibility?.can_build === true,
|
||||
label: props.eligibility?.can_build === true
|
||||
? t('chat.shippingOrderReview.buildEligibility.overallPass')
|
||||
: t('chat.shippingOrderReview.buildEligibility.overallBlocked'),
|
||||
},
|
||||
...checks,
|
||||
];
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="eligibility"
|
||||
class="rounded-xl border border-default bg-surface p-3 shadow-sm"
|
||||
data-testid="review-build-eligibility-summary"
|
||||
>
|
||||
<header class="flex flex-wrap items-center justify-between gap-2">
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.title') }}</h2>
|
||||
<span
|
||||
class="rounded-full px-2.5 py-1 text-xs font-medium"
|
||||
:class="eligibility.can_build === null
|
||||
? 'bg-surface-strong text-secondary '
|
||||
: eligibility.can_build
|
||||
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
|
||||
: 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'"
|
||||
data-testid="review-build-eligibility-badge"
|
||||
>
|
||||
{{
|
||||
eligibility.status === 'not_validated'
|
||||
? t('chat.shippingOrderReview.buildEligibility.notValidated')
|
||||
: eligibility.can_build
|
||||
? t('chat.shippingOrderReview.buildEligibility.canBuildYes')
|
||||
: t('chat.shippingOrderReview.buildEligibility.canBuildNo')
|
||||
}}
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<p
|
||||
v-if="eligibility.can_build && eligibility.can_auto_create === false"
|
||||
class="mt-2 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
|
||||
data-testid="review-auto-create-blocked"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.buildEligibility.manualConfirmOnly') }}
|
||||
</p>
|
||||
<ul
|
||||
v-if="gateChecklist.length"
|
||||
class="mt-2 space-y-1 text-xs"
|
||||
data-testid="review-eligibility-gate-checklist"
|
||||
>
|
||||
<li
|
||||
v-for="item in gateChecklist"
|
||||
:key="item.gate"
|
||||
class="flex items-center gap-2"
|
||||
>
|
||||
<span :class="item.passed ? 'text-emerald-600' : 'text-rose-600'">{{ item.passed ? '✓' : '×' }}</span>
|
||||
<span :class="item.passed ? 'text-secondary' : 'font-medium text-rose-700 dark:text-rose-300'">
|
||||
{{ item.label }}
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
<div
|
||||
v-if="exceptionCount"
|
||||
class="mt-2 flex flex-wrap items-center justify-between gap-2 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
|
||||
data-testid="review-exception-nav"
|
||||
>
|
||||
<span>
|
||||
{{ t('chat.shippingOrderReview.issues') }}
|
||||
<span class="ml-1 text-muted">
|
||||
{{ exceptionOrdinal ? `${exceptionOrdinal}/${exceptionCount}` : `0/${exceptionCount}` }}
|
||||
</span>
|
||||
</span>
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-amber-300 px-2 py-1 text-amber-900 hover:bg-amber-100 dark:border-amber-800 dark:text-amber-100 dark:hover:bg-amber-950"
|
||||
data-testid="review-exception-prev"
|
||||
:title="t('chat.shippingOrderReview.exceptionNav.prevHint')"
|
||||
@click="emit('navigate-exception', -1)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.exceptionNav.prev') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-amber-300 px-2 py-1 text-amber-900 hover:bg-amber-100 dark:border-amber-800 dark:text-amber-100 dark:hover:bg-amber-950"
|
||||
data-testid="review-exception-next"
|
||||
:title="t('chat.shippingOrderReview.exceptionNav.nextHint')"
|
||||
@click="emit('navigate-exception', 1)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.exceptionNav.next') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="missingRequiredFields.length || conflictFields.length" class="mt-2 space-y-1 rounded-lg border border-rose-200 bg-rose-50 px-2.5 py-2 text-xs text-rose-900 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-100">
|
||||
<p v-if="missingRequiredFields.length"><span class="font-semibold">{{ t('chat.shippingOrderReview.workbench.missingRequiredFields') }}:</span>{{ missingRequiredFields.join('、') }}</p>
|
||||
<p v-if="conflictFields.length"><span class="font-semibold">{{ t('chat.shippingOrderReview.workbench.conflictFields') }}:</span>{{ [...new Set(conflictFields)].join('、') }}</p>
|
||||
</div>
|
||||
<div
|
||||
v-if="lowConfidenceFields.length"
|
||||
class="mt-2 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
|
||||
data-testid="review-low-confidence-fields"
|
||||
>
|
||||
<p class="font-semibold">{{ t('chat.shippingOrderReview.workbench.lowConfidenceFields') }}:</p>
|
||||
<ul class="mt-1 list-disc pl-4">
|
||||
<li v-for="item in lowConfidenceFields" :key="item.field_code">
|
||||
{{ item.label }}({{ item.confidence == null ? '—' : `${Math.round(item.confidence * 100)}%` }},{{ t('chat.shippingOrderReview.workbench.confidenceThreshold', { threshold: Math.round(Number(item.minimum_confidence || 0) * 100) }) }})
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="!eligibility.can_build && primaryBlockMessage"
|
||||
class="mt-2 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
|
||||
data-testid="review-eligibility-primary-block"
|
||||
>
|
||||
<div class="font-semibold">{{ t('chat.shippingOrderReview.workbench.primaryBlock') }}</div>
|
||||
<p class="mt-0.5">{{ primaryBlockMessage }}</p>
|
||||
<p v-if="blockingIssueCount || blockedLineCount" class="mt-1 text-[11px] opacity-80">
|
||||
{{ t('chat.shippingOrderReview.workbench.blockCount', {
|
||||
count: Math.max(blockingIssueCount, blockedLineCount),
|
||||
}) }}
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
v-if="unexplainedBlocked"
|
||||
class="mt-2 rounded-lg border border-rose-200 bg-rose-50 px-2.5 py-2 text-xs text-rose-900 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-100"
|
||||
data-testid="review-eligibility-unexplained-block"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.buildEligibility.unexplainedBlocked') }}
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="mt-2 w-full rounded border border-default px-2 py-1.5 text-xs hover-surface-soft"
|
||||
data-testid="review-open-eligibility-details"
|
||||
@click="emit('open-details')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workbench.viewFullChecks') }}
|
||||
</button>
|
||||
</section>
|
||||
</template>
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewCloseFulfillmentDialog.vue
|
||||
用途:关闭行级或剩余开放行的履约决定确认弹窗(原因必填)。
|
||||
依赖:vue-i18n、closeWorkspaceShippingOrderReviewLineFulfillment、showReviewResumeOutcome。
|
||||
逻辑:父级传入 lineKeys;空数组表示关闭全部剩余开放行;成功后 emit confirmed。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { closeWorkspaceShippingOrderReviewLineFulfillment } from '@/features/chat/api/shipping.api';
|
||||
import { showReviewResumeOutcome } from '@/features/chat/shipping-review/showReviewResumeOutcome';
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
caseNo: string;
|
||||
draftVersion: number | null | undefined;
|
||||
lineKeys: string[];
|
||||
closeAllRemaining?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean];
|
||||
confirmed: [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
const reason = ref('');
|
||||
const busy = ref(false);
|
||||
|
||||
const title = computed(() => (
|
||||
props.closeAllRemaining || !props.lineKeys.length
|
||||
? t('chat.shippingOrderReview.closeFulfillment.titleAll')
|
||||
: t('chat.shippingOrderReview.closeFulfillment.titleSelected', { count: props.lineKeys.length })
|
||||
));
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
(isOpen) => {
|
||||
if (!isOpen) {
|
||||
reason.value = '';
|
||||
busy.value = false;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* 提交关闭履约行决定。
|
||||
*/
|
||||
async function onConfirm() {
|
||||
const trimmed = reason.value.trim();
|
||||
if (!trimmed || !props.caseNo || busy.value) return;
|
||||
busy.value = true;
|
||||
try {
|
||||
const result = await closeWorkspaceShippingOrderReviewLineFulfillment(props.caseNo, {
|
||||
reason: trimmed,
|
||||
draft_line_ids: props.lineKeys.length ? props.lineKeys : undefined,
|
||||
expected_draft_version: props.draftVersion ?? undefined,
|
||||
});
|
||||
showReviewResumeOutcome(
|
||||
result.resume_outcome,
|
||||
msg,
|
||||
t,
|
||||
t('chat.shippingOrderReview.closeFulfillment.success'),
|
||||
);
|
||||
emit('update:open', false);
|
||||
emit('confirmed');
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.closeFulfillment.failed'));
|
||||
msg.warning(message);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消并关闭弹窗。
|
||||
*/
|
||||
function onCancel() {
|
||||
emit('update:open', false);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 p-4"
|
||||
data-testid="review-close-fulfillment-dialog"
|
||||
@click.self="onCancel"
|
||||
>
|
||||
<div class="w-full max-w-md rounded-xl border border-default bg-surface p-4 shadow-xl">
|
||||
<h2 class="text-sm font-semibold">{{ title }}</h2>
|
||||
<p class="mt-1 text-xs text-muted">{{ t('chat.shippingOrderReview.closeFulfillment.subtitle') }}</p>
|
||||
<label class="mt-3 block text-xs font-medium text-secondary">
|
||||
{{ t('chat.shippingOrderReview.closeFulfillment.reasonLabel') }}
|
||||
<textarea
|
||||
v-model="reason"
|
||||
rows="3"
|
||||
class="mt-1 w-full rounded-md border border-default bg-surface px-2.5 py-2 text-sm"
|
||||
data-testid="review-close-fulfillment-reason"
|
||||
:placeholder="t('chat.shippingOrderReview.closeFulfillment.reasonPlaceholder')"
|
||||
:disabled="busy"
|
||||
/>
|
||||
</label>
|
||||
<div class="mt-4 flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-default px-3 py-1.5 text-sm hover:bg-surface-soft disabled:opacity-50"
|
||||
:disabled="busy"
|
||||
@click="onCancel"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workbench.close') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded bg-rose-600 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-50"
|
||||
data-testid="review-close-fulfillment-submit"
|
||||
:disabled="busy || !reason.trim()"
|
||||
@click="onConfirm"
|
||||
>
|
||||
{{ busy ? t('chat.shippingOrderReview.closeFulfillment.closing') : t('chat.shippingOrderReview.closeFulfillment.confirm') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,58 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewCompletedChecksPanel.vue
|
||||
用途:右侧「已完成检查」折叠列表;仅消费后端 completed_checks。
|
||||
依赖:vue-i18n。
|
||||
逻辑:默认折叠;禁止前端自行拼接 Gate/里程碑。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
export interface CompletedCheckItem {
|
||||
code: string;
|
||||
status?: string;
|
||||
completed_at?: string | null;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
items?: CompletedCheckItem[] | null;
|
||||
defaultOpen?: boolean;
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
const checks = computed(() => (props.items || []).filter((item) => String(item.status || 'passed') === 'passed'));
|
||||
const visible = computed(() => checks.value.length > 0);
|
||||
|
||||
/**
|
||||
* 检查项本地化标签。
|
||||
*/
|
||||
function checkLabel(code: string): string {
|
||||
const key = `chat.shippingOrderReview.completedChecks.codes.${code}`;
|
||||
return te(key) ? t(key) : code;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<details
|
||||
v-if="visible"
|
||||
class="rounded-xl border border-default bg-surface p-2 text-xs"
|
||||
:open="defaultOpen"
|
||||
data-testid="review-completed-checks"
|
||||
>
|
||||
<summary class="cursor-pointer px-1 py-1 font-medium text-muted">
|
||||
{{ t('chat.shippingOrderReview.completedChecks.title', { count: checks.length }) }}
|
||||
</summary>
|
||||
<ul class="mt-2 space-y-1 px-1 pb-1">
|
||||
<li
|
||||
v-for="item in checks"
|
||||
:key="item.code"
|
||||
class="flex items-center gap-2 text-[11px] text-secondary"
|
||||
:data-testid="`review-completed-check-${item.code}`"
|
||||
>
|
||||
<span class="text-emerald-600 dark:text-emerald-400" aria-hidden="true">✓</span>
|
||||
<span>{{ checkLabel(item.code) }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</details>
|
||||
</template>
|
||||
+340
@@ -0,0 +1,340 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewCurrentProcessingCard.spec.ts
|
||||
* 用途:验证工作台右侧当前任务卡只在需要人工处理时渲染业务动作。
|
||||
* 依赖:Vitest、Vue Test Utils、Vue I18n、ReviewCurrentProcessingCard。
|
||||
* 逻辑:库存自动处理中即使遗留 primary_action,也不得显示编辑正式任务;可重试状态仍保留重试入口;
|
||||
* loading 是「权威投影读取中」占位:已知阶段照常展示,状态/下一步给中性加载文案(非系统处理中)。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import ReviewCurrentProcessingCard from './ReviewCurrentProcessingCard.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
'chat.shippingOrderReview.processGate.actionCodes.retry_inventory_matching': '重新库存匹配',
|
||||
workspace: {
|
||||
shippingNotice: {
|
||||
processGate: {
|
||||
actionCodes: {
|
||||
reload_inventory_result: '重新读取库存结果',
|
||||
retry_inventory_preparation: '重新获取库存',
|
||||
},
|
||||
inventoryActions: {
|
||||
reloadInventoryResult: '重新读取库存结果',
|
||||
retryInventoryMatching: '重新库存匹配',
|
||||
retryInventoryPreparation: '重新获取库存',
|
||||
},
|
||||
reasons: {
|
||||
inventory_shortage_review_required: '存在库存缺口,需要人工处理',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
saveOrderAndValidate: '提交订单',
|
||||
currentProcessing: {
|
||||
waitingStart: '等待系统启动',
|
||||
stageLoading: '正在获取最新状态…',
|
||||
statusIdle: '待机',
|
||||
status: '状态',
|
||||
stages: {
|
||||
excel_generating: 'Excel 生成',
|
||||
},
|
||||
},
|
||||
currentTask: {
|
||||
title: '当前任务',
|
||||
labelStage: '当前门禁',
|
||||
statusRunning: '系统处理中',
|
||||
statusWaitingHuman: '待人工处理',
|
||||
statusRetryable: '可重试',
|
||||
statusFailed: '自动处理失败',
|
||||
statusCompleted: '已完成',
|
||||
statusCancelled: '已取消',
|
||||
nextStepTitle: '下一步',
|
||||
nextStepRunning: '系统正在处理,暂不需要人工操作',
|
||||
nextStepUnknown: '状态待确认',
|
||||
nextStepWaitingExternal: '等待外部系统回执,暂不需要人工操作',
|
||||
},
|
||||
},
|
||||
shippingProcessing: {
|
||||
gateReasons: {
|
||||
generic: '当前步骤需要人工处理',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe('ReviewCurrentProcessingCard', () => {
|
||||
it('hides a legacy primary action while inventory preparation is running', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'inventory_preparation',
|
||||
userStatus: 'running',
|
||||
primaryAction: { code: 'edit_formal_task', i18nKey: 'edit_formal_task' },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 自动处理只显示状态,不能让历史的正式任务编辑动作干扰当前库存阶段。
|
||||
expect(wrapper.find('[data-testid="review-current-task-actions"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the retry action for retryable states', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'inventory_preparation', userStatus: 'retryable', retryable: true,
|
||||
primaryAction: { code: 'retry_inventory_preparation', i18nKey: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation' },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 失败后的人工恢复路径不能被运行态过滤误伤。
|
||||
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('renders a code-agnostic primary action label from a registered recovery code', () => {
|
||||
// 卡片是 code-agnostic 渲染器:只要后端下发了受控文案键,就渲染对应业务动作文案。
|
||||
// 此用例用 reload_inventory_result(仍为写契约有效码)验证卡片对库存动作文案的渲染。
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'inventory_preparation', userStatus: 'retryable', retryable: true,
|
||||
primaryAction: { code: 'reload_inventory_result' },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').text()).toBe('重新读取库存结果');
|
||||
});
|
||||
|
||||
it('hides the order-review entry when the user is already in the lifecycle workbench', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'order_review',
|
||||
userStatus: 'waiting_human',
|
||||
primaryAction: { code: 'open_order_review', i18nKey: 'chat.shippingProcessing.action.open_order_review' },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 批次中心可以用它进入工作台;工作台当前阶段不能再显示同一个自跳转入口。
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders Gate label_key for every primary action presentation', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'inventory_matching',
|
||||
userStatus: 'waiting_human',
|
||||
primaryAction: {
|
||||
code: 'retry_inventory_matching',
|
||||
label_key: 'chat.shippingOrderReview.processGate.actionCodes.retry_inventory_matching',
|
||||
} as any,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="review-current-processing-retry"]').text()).toBe('重新库存匹配');
|
||||
});
|
||||
|
||||
it('does not render save and validate as a current-task action', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'order_review',
|
||||
userStatus: 'waiting_human',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 提交订单是底栏唯一动作;未提交前必须给出明确交接提示,不能显示系统处理中。
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
|
||||
expect(wrapper.get('[data-testid="review-current-task-next-step-text"]').text()).toBe('提交订单');
|
||||
});
|
||||
|
||||
it('labels an unqueued automatic Gate as waiting for system start', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'fulfillment_prep',
|
||||
userStatus: 'running',
|
||||
gateStatus: 'pending',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toContain('等待系统启动');
|
||||
});
|
||||
|
||||
it('explains external wait without calling it generic system processing', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'upload_complete',
|
||||
userStatus: 'running',
|
||||
gateStatus: 'waiting_external',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.get('[data-testid="review-current-task-next-step-text"]').text())
|
||||
.toBe('等待外部系统回执,暂不需要人工操作');
|
||||
});
|
||||
|
||||
it('never exposes an internal action code when its presentation is absent', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'order_review',
|
||||
userStatus: 'waiting_human',
|
||||
primaryAction: { code: 'edit_draft' },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 回退显示 edit_draft 会泄漏内部能力码;必须 fail-closed 隐藏。
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
|
||||
expect(wrapper.text()).not.toContain('edit_draft');
|
||||
});
|
||||
|
||||
it('hides an unlabeled primary action instead of rendering an icon-only ghost button', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'fulfillment_prep',
|
||||
userStatus: 'waiting_human',
|
||||
// 后端下发了动作码,但前端无受控文案(缺失 i18n 映射 / 未登记),
|
||||
// 必须整体隐藏按钮,不能渲染成只有 Bot/RefreshCw 图标的“幽灵按钮”。
|
||||
primaryAction: { code: 'unknown_system_action', i18nKey: 'workspace.shippingNotice.processGate.actionCodes.unknown_system_action' },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="review-current-task-actions"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
|
||||
expect(wrapper.text()).not.toContain('unknown_system_action');
|
||||
});
|
||||
|
||||
it('renders a localized reason instead of an internal blocking code in the next step', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'inventory_matching',
|
||||
userStatus: 'waiting_human',
|
||||
blockingReason: { code: 'inventory_shortage_review_required' },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
const nextStep = wrapper.get('[data-testid="review-current-task-next-step-text"]').text();
|
||||
expect(nextStep).toBe('存在库存缺口,需要人工处理');
|
||||
expect(nextStep).not.toContain('inventory_shortage_review_required');
|
||||
});
|
||||
|
||||
it('hides internal inventory recovery targets while retaining the stable primary action', async () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'inventory_matching',
|
||||
userStatus: 'waiting_human',
|
||||
primaryAction: { code: 'retry_inventory_matching', i18nKey: 'retry_inventory_matching' },
|
||||
recoveryActions: [{
|
||||
code: 'retry_inventory_from_preparation',
|
||||
i18nKey: 'chat.shippingOrderReview.processGate.actionCodes.retry_inventory_matching',
|
||||
}],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="review-current-task-recovery-retry_inventory_from_preparation"]').exists()).toBe(false);
|
||||
expect(wrapper.findAll('button').length).toBe(1);
|
||||
});
|
||||
|
||||
it('emits rematch and RPA refresh as distinct actions for a shortage with an active inventory file', async () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'fulfillment_prep',
|
||||
userStatus: 'waiting_human',
|
||||
primaryAction: { code: 'retry_inventory_matching' },
|
||||
recoveryActions: [{ code: 'retry_inventory_preparation' }],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
await wrapper.get('[data-testid="review-current-processing-retry"]').trigger('click');
|
||||
await wrapper.get('[data-testid="review-current-task-recovery-retry_inventory_preparation"]').trigger('click');
|
||||
|
||||
// 两个稳定 action 码分别进入 Gate API:重匹配不可误触 RPA,重新获取库存才会触发 RPA。
|
||||
expect(wrapper.emitted('action')).toEqual([
|
||||
['retry_inventory_matching', {}],
|
||||
['retry_inventory_preparation', {}],
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps the known stage and status while the authoritative projection is still loading', () => {
|
||||
// Case 先到、Projection 后到的过渡窗口:阶段与投影同源(project_stage_for_task),
|
||||
// status 也来自后端 automation 运行态,必须照常展示,不能退回骨架/「正在更新状态」占位。
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
loading: true,
|
||||
stageCode: 'excel_generating',
|
||||
stageLabelKey: 'excel_generating',
|
||||
userStatus: 'running',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).toBe('Excel 生成');
|
||||
// loading 只抑制动作,不掩盖真值:运行态照常显示「系统处理中」。
|
||||
expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toBe('系统处理中');
|
||||
expect(wrapper.get('[data-testid="review-current-task-next-step-text"]').text())
|
||||
.toBe('系统正在处理,暂不需要人工操作');
|
||||
});
|
||||
|
||||
it('shows the neutral idle value instead of a skeleton when nothing is actionable yet', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: { loading: true, stageCode: 'excel_generating', stageLabelKey: 'excel_generating' },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 空用户态自然落到「待机 / 状态待确认」,与投影稳态一致——不做骨架→真值的二次刷新。
|
||||
expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).toBe('Excel 生成');
|
||||
expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toBe('待机');
|
||||
expect(wrapper.get('[data-testid="review-current-task-next-step-text"]').text()).toBe('状态待确认');
|
||||
});
|
||||
|
||||
it('falls back to a neutral stage placeholder only when no stage is known', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: { loading: true },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).toBe('正在获取最新状态…');
|
||||
expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toBe('待机');
|
||||
});
|
||||
|
||||
it('renders an embedded status detail line when provided', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
userStatus: 'running',
|
||||
stageCode: 'intake_parse',
|
||||
statusDetail: { text: '正在等待解析任务启动' },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
// 关键断言:说明内嵌于状态行下方(弱文本一行),带 aria-live 与固定 testid;
|
||||
// 状态行仍为短标签(系统处理中),长句不进入状态位。
|
||||
const detail = wrapper.get('[data-testid="review-current-task-status-detail"]');
|
||||
expect(detail.text()).toBe('正在等待解析任务启动');
|
||||
expect(detail.attributes('aria-live')).toBe('polite');
|
||||
expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toContain('系统处理中');
|
||||
});
|
||||
|
||||
it('renders no status detail line without the prop', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: { userStatus: 'waiting_human', stageCode: 'order_review' },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
// 关键断言:无 statusDetail 时说明行完全不渲染,不留空壳。
|
||||
expect(wrapper.find('[data-testid="review-current-task-status-detail"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
+484
@@ -0,0 +1,484 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewCurrentProcessingCard.vue
|
||||
用途:发货通知工作台右侧唯一的「当前任务」主卡(阶段 + 用户状态 + 阻断 + 动作)。
|
||||
依赖:vue-i18n、ShippingProcessingBlockingReason/PrimaryAction 类型、resolveShippingProcessingStageLabel。
|
||||
逻辑:主卡内部 section = 「当前阶段/状态/正式OT → 下一步 → 动作区」;
|
||||
状态文案严格绑定 user_status;blocking_reason 只作下一步问题说明;按钮显隐由后端 retryable + primary_action.parameters 决定;
|
||||
主动作按钮文案 fail-closed:后端下发动作码但无受控 i18n 文案时整体隐藏该按钮(含图标),禁止渲染无文字裸按钮;
|
||||
loading 仅代表「权威投影读取中」而非系统运行态:已知阶段/状态/阻断仍照常展示
|
||||
(与投影同源或后端 automation 运行态),空态自然落到「待机/状态待确认」,
|
||||
禁止把读取占位误述为「系统处理中」,也不做骨架→真值的二次刷新;
|
||||
loading 仅在挂载期抑制可执行动作,等权威投影到达后再放行(fail-closed);
|
||||
由 ShippingOrderReviewView 在 mountCurrentProcessingCard 时挂载;
|
||||
v2 新增 statusDetail:状态块内嵌动态说明(隐藏裁决在视图侧,见 spec §5.2)。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { Bot, RefreshCw, Crosshair } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type {
|
||||
ShippingProcessingBlockingReason,
|
||||
ShippingProcessingPrimaryAction,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
import { resolveShippingProcessingStageLabel } from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import { resolveGateReasonLabel } from '@/features/shipping-progress/gateReasonLabel';
|
||||
import { lookupWorkbenchAction, shouldRenderWorkbenchAction } from '@/features/shipping-progress/workbenchActionRegistry';
|
||||
import { inventoryActionLabelKey, isInternalInventoryAction } from '@/features/shipping-progress/actionPresentation';
|
||||
|
||||
const props = defineProps<{
|
||||
stageCode?: string | null;
|
||||
stageLabelKey?: string | null;
|
||||
stageInconsistent?: boolean;
|
||||
|
||||
userStatus?:
|
||||
| 'running'
|
||||
| 'waiting_human'
|
||||
| 'retryable'
|
||||
| 'failed'
|
||||
| 'completed'
|
||||
| 'cancelled'
|
||||
| null;
|
||||
retryable?: boolean;
|
||||
blockingReason?: ShippingProcessingBlockingReason | null;
|
||||
primaryAction?: ShippingProcessingPrimaryAction | null;
|
||||
recoveryActions?: Array<{
|
||||
code: string;
|
||||
i18nKey?: string | null;
|
||||
label_key?: string | null;
|
||||
parameters?: Record<string, unknown>;
|
||||
}>;
|
||||
/** 正式 Gate 原始状态仅用于区分未入队、运行中与外部回执等待;不参与按钮裁决。 */
|
||||
gateStatus?: string | null;
|
||||
|
||||
taskMissing?: boolean;
|
||||
confirmedTaskId?: number | null;
|
||||
showAdminDiagnosis?: boolean;
|
||||
retrying?: boolean;
|
||||
locating?: boolean;
|
||||
/** 仅 UI 展示的 running 文案(如 inventory_preparation 正在跑时主卡按钮 loading 附加信息)。 */
|
||||
automation?: {
|
||||
status?: string | null;
|
||||
message?: string | null;
|
||||
} | null;
|
||||
showRetry?: boolean;
|
||||
loading?: boolean;
|
||||
/** 状态块内嵌动态说明(Run 级 lifecycle_progress 解析结果);null/空文本不渲染,显隐裁决在视图侧。 */
|
||||
statusDetail?: { text: string } | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
locate: [draftLineId?: string | null, fieldId?: string | null];
|
||||
action: [code: string, parameters?: Record<string, unknown>];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
/**
|
||||
* 当前阶段展示文案:优先消费 stage_label_key,禁止直接展示 stage 码。
|
||||
* 核心逻辑:loading 是「权威投影读取中」占位,不是业务运行态——只要已有可展示的
|
||||
* 阶段(Case 快照 current_stage 与投影同源,见 currentProcessingStageDisplay),
|
||||
* 照常展示真实阶段;仅在连降级阶段都没有时才回退 stageLoading 占位文案。
|
||||
*/
|
||||
const stageLabel = computed(() => {
|
||||
const hasKnownStage = Boolean(
|
||||
String(props.stageCode || '').trim() || String(props.stageLabelKey || '').trim(),
|
||||
);
|
||||
if (props.loading && !hasKnownStage) {
|
||||
return t('chat.shippingOrderReview.currentProcessing.stageLoading');
|
||||
}
|
||||
if (props.stageInconsistent) {
|
||||
return t('chat.shippingOrderReview.currentProcessing.stateInconsistent');
|
||||
}
|
||||
return resolveShippingProcessingStageLabel(
|
||||
String(props.stageCode || ''),
|
||||
te,
|
||||
t,
|
||||
props.stageLabelKey,
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* 「状态」行用户态文案:严格绑定 user_status,不再由前端推断。
|
||||
* loading 只是「权威投影读取中」:只要已有后端下发的 user_status(如 Case automation
|
||||
* 运行态)就照常展示真实/待机文案,禁止再退回「正在获取最新状态」骨架造成二次刷新
|
||||
* (状态空时 statusIdle 即中性「待机」,与投影稳态一致)。
|
||||
*/
|
||||
const statusLabel = computed(() => {
|
||||
const s = String(props.userStatus || '').trim() as ReviewCurrentUserStatus | '';
|
||||
const map: Record<ReviewCurrentUserStatus, string> = {
|
||||
running: t('chat.shippingOrderReview.currentTask.statusRunning'),
|
||||
waiting_human: t('chat.shippingOrderReview.currentTask.statusWaitingHuman'),
|
||||
retryable: t('chat.shippingOrderReview.currentTask.statusRetryable'),
|
||||
failed: t('chat.shippingOrderReview.currentTask.statusFailed'),
|
||||
completed: t('chat.shippingOrderReview.currentTask.statusCompleted'),
|
||||
cancelled: t('chat.shippingOrderReview.currentTask.statusCancelled'),
|
||||
};
|
||||
if (props.taskMissing) {
|
||||
return t('chat.shippingOrderReview.currentProcessing.taskMissing');
|
||||
}
|
||||
if (s === 'running' && String(props.gateStatus || '').trim().toLowerCase() === 'pending') {
|
||||
return t('chat.shippingOrderReview.currentProcessing.waitingStart');
|
||||
}
|
||||
if (!s) return t('chat.shippingOrderReview.currentProcessing.statusIdle');
|
||||
return map[s] ?? t('chat.shippingOrderReview.currentProcessing.statusIdle');
|
||||
});
|
||||
|
||||
/**
|
||||
* 下一步(「下一步」section 的问题/说明文案):优先展示 blocking_reason 的统一 i18n 映射,
|
||||
* 否则按 user_status 给系统态文案;禁止将后端内部原因码直接展示给用户。
|
||||
*/
|
||||
const nextStepText = computed(() => {
|
||||
const safeMessage = (value: unknown): string => {
|
||||
const raw = String(value || '').trim();
|
||||
const lowered = raw.toLowerCase();
|
||||
if (!raw) return '';
|
||||
if (
|
||||
lowered.includes('cannot import name')
|
||||
|| lowered.includes('traceback')
|
||||
|| lowered.includes('site-packages')
|
||||
|| lowered.includes('\\app\\')
|
||||
|| lowered.includes('/app/')
|
||||
) {
|
||||
return t('chat.shippingOrderReview.currentTask.nextStepFailedNoRetry');
|
||||
}
|
||||
return raw;
|
||||
};
|
||||
// 加载占位不等于系统运行态:只透传后端 automation.message(若有);
|
||||
// 其余按 user_status/blocking_reason 照常渲染,空态自然落在「状态待确认」,不做骨架二次刷新。
|
||||
const automationMessage = props.loading ? safeMessage(props.automation?.message) : '';
|
||||
if (automationMessage) return automationMessage;
|
||||
// 1) blocking_reason → 用后端给的 i18n_key 渲染具体阻断
|
||||
const br = props.blockingReason;
|
||||
if (br) {
|
||||
const i18nKey = String(br.i18nKey || '').trim();
|
||||
if (i18nKey && te(i18nKey)) {
|
||||
return t(i18nKey);
|
||||
}
|
||||
return resolveGateReasonLabel(br.code, { t, te })
|
||||
|| t('chat.shippingOrderReview.currentTask.nextStepUnknown');
|
||||
}
|
||||
// 建单前订单冻结校验尚未提交时,明确告诉用户下一步是保存并校验。
|
||||
// 保存是底栏唯一的表单提交入口,不升级为右栏 CTA;该分支也兼容历史响应
|
||||
// 仍携带 validate 的情形,避免「待人工」与「无需操作」产生语义矛盾。
|
||||
if (
|
||||
String(props.stageCode || '').trim() === 'order_review'
|
||||
&& !props.blockingReason
|
||||
&& (
|
||||
String(props.primaryAction?.code || '').trim() === 'validate'
|
||||
|| String(props.userStatus || '').trim() === 'waiting_human'
|
||||
)
|
||||
) {
|
||||
return t('chat.shippingOrderReview.saveOrderAndValidate');
|
||||
}
|
||||
if (
|
||||
String(props.userStatus || '').trim() === 'running'
|
||||
&& String(props.gateStatus || '').trim().toLowerCase() === 'waiting_external'
|
||||
) {
|
||||
return t('chat.shippingOrderReview.currentTask.nextStepWaitingExternal');
|
||||
}
|
||||
// 2) 无阻断时,按 user_status 给系统说明文案
|
||||
const s = String(props.userStatus || '').trim() as ReviewCurrentUserStatus | '';
|
||||
if (s === 'running') {
|
||||
return t('chat.shippingOrderReview.currentTask.nextStepRunning');
|
||||
}
|
||||
if (s === 'completed') {
|
||||
return t('chat.shippingOrderReview.currentTask.nextStepCompleted');
|
||||
}
|
||||
if (s === 'cancelled') {
|
||||
return t('chat.shippingOrderReview.currentTask.nextStepCancelled');
|
||||
}
|
||||
if (s === 'failed' && !props.retryable) {
|
||||
return t('chat.shippingOrderReview.currentTask.nextStepFailedNoRetry');
|
||||
}
|
||||
if (s === 'waiting_human') {
|
||||
return t('chat.shippingOrderReview.currentTask.nextStepWaitingHumanDefault');
|
||||
}
|
||||
if (s === 'retryable') {
|
||||
return t('chat.shippingOrderReview.currentTask.nextStepRetryableDefault');
|
||||
}
|
||||
return t('chat.shippingOrderReview.currentTask.nextStepUnknown');
|
||||
});
|
||||
|
||||
/** 已完成/已取消时没有后续业务动作,不渲染“下一步”区,避免制造未完成错觉。 */
|
||||
const showNextStep = computed(() => {
|
||||
const status = String(props.userStatus || '').trim().toLowerCase();
|
||||
return !['completed', 'cancelled'].includes(status);
|
||||
});
|
||||
|
||||
/**
|
||||
* 判断当前工作台是否应隐藏后端下发的纯导航动作。
|
||||
* 批次中心可用它打开工作台;进入工作台后必须复用注册表规则,避免当前阶段再次显示
|
||||
* 「进入订单复核」或「编辑正式任务」等自跳转入口。
|
||||
*/
|
||||
function isHiddenWorkbenchNavigationAction(code: string): boolean {
|
||||
const entry = lookupWorkbenchAction(code);
|
||||
return Boolean(entry && !shouldRenderWorkbenchAction(entry, {
|
||||
actionsExecutable: true,
|
||||
surface: 'review',
|
||||
actionCode: code,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前任务卡只承载正式 Gate 的可执行业务动作。
|
||||
*
|
||||
* 草稿编辑/建草稿是页面能力,保存校验是底栏唯一提交;它们即使出现在历史响应中,
|
||||
* 也不能升级为右栏 CTA,更不能因缺失文案泄漏内部动作码。
|
||||
*/
|
||||
function isNonTaskCapabilityAction(code: string): boolean {
|
||||
return new Set(['edit_draft', 'create_draft', 'validate']).has(code.trim().toLowerCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* 业务动作按钮只消费 primary_action;retryable 是状态,不是授权。
|
||||
*
|
||||
* 核心逻辑:除既有授权过滤外,文案必须是后端下发且经受控映射解析出的非空文案
|
||||
* (businessActionLabel 已 fail-closed 为 '');无文案时整体隐藏按钮,防止
|
||||
* 渲染成只有图标/空壳的“幽灵按钮”误导用户以为是开关或其他控件。
|
||||
*/
|
||||
const showBusinessAction = computed(() => {
|
||||
if (props.loading) return false;
|
||||
if (props.taskMissing) return false;
|
||||
// [STEP] 自动处理期间没有人工业务动作;只保留外层的刷新进度入口。
|
||||
// 防止正式任务编辑等历史 primary_action 穿透到库存获取运行态。
|
||||
if (props.userStatus === 'running') return false;
|
||||
const code = String(props.primaryAction?.code || '').trim();
|
||||
if (isInternalInventoryAction(code)) return false;
|
||||
if (!code) return false;
|
||||
if (isNonTaskCapabilityAction(code)) return false;
|
||||
if (isHiddenWorkbenchNavigationAction(code)) return false;
|
||||
// 无对象边界的泛化 retry 永不展示。
|
||||
if (code === 'retry') return false;
|
||||
// [AUTHORITY] 无受控文案的动作码 fail-closed:连图标一起隐藏,不渲染空壳按钮。
|
||||
if (!businessActionLabel.value) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
const businessActionLabel = computed(() => {
|
||||
const code = String(props.primaryAction?.code || '').trim();
|
||||
const inventoryKey = inventoryActionLabelKey(code);
|
||||
if (inventoryKey && te(inventoryKey)) return t(inventoryKey);
|
||||
const pa = props.primaryAction;
|
||||
if (!pa) return '';
|
||||
if (isNonTaskCapabilityAction(String(pa.code || ''))) return '';
|
||||
// Gate action presentation uses label_key; normalize it at the shared card boundary
|
||||
// so every gate renders its business label instead of exposing the action code.
|
||||
const i18nKey = String(
|
||||
pa.i18nKey
|
||||
|| (pa as ShippingProcessingPrimaryAction & { label_key?: string | null }).label_key
|
||||
|| '',
|
||||
).trim();
|
||||
if (i18nKey && te(i18nKey)) {
|
||||
return t(i18nKey);
|
||||
}
|
||||
// 当前任务按钮没有受控文案时 fail-closed,禁止泄漏内部 action code。
|
||||
return '';
|
||||
});
|
||||
|
||||
const businessActionTitle = computed(() => {
|
||||
const retryingFlag = Boolean(props.retrying);
|
||||
if (retryingFlag) {
|
||||
return t('chat.shippingOrderReview.currentTask.actionRetryRunningTooltip');
|
||||
}
|
||||
return '';
|
||||
});
|
||||
|
||||
const actionIsRetry = computed(() => String(props.primaryAction?.code || '').trim().startsWith('retry_'));
|
||||
const actionIsInventoryRpa = computed(() => String(props.primaryAction?.code || '').trim() === 'retry_inventory_preparation');
|
||||
const recoveryActions = computed(() => (props.recoveryActions || []).filter((action) => {
|
||||
const code = String(action.code || '').trim();
|
||||
if (!code || isNonTaskCapabilityAction(code) || isInternalInventoryAction(code)) return false;
|
||||
if (code === String(props.primaryAction?.code || '').trim()) return false;
|
||||
const key = String(
|
||||
action.i18nKey
|
||||
|| action.label_key
|
||||
|| `workspace.shippingNotice.processGate.actionCodes.${code}`,
|
||||
).trim();
|
||||
return Boolean(key && te(key));
|
||||
}));
|
||||
|
||||
function recoveryActionLabel(action: (typeof recoveryActions.value)[number]): string {
|
||||
const inventoryKey = inventoryActionLabelKey(action.code);
|
||||
if (inventoryKey && te(inventoryKey)) return t(inventoryKey);
|
||||
const key = String(
|
||||
action.i18nKey
|
||||
|| action.label_key
|
||||
|| `workspace.shippingNotice.processGate.actionCodes.${action.code}`,
|
||||
).trim();
|
||||
return key && te(key) ? t(key) : '';
|
||||
}
|
||||
|
||||
function handleBusinessActionClick() {
|
||||
const primaryActionCode = String(props.primaryAction?.code || '').trim();
|
||||
if (!primaryActionCode || primaryActionCode === 'retry') return;
|
||||
emit('action', primaryActionCode, props.primaryAction?.parameters ?? {});
|
||||
}
|
||||
|
||||
/**
|
||||
* 辅助导航「定位明细」:仅当后端在 primary_action.parameters 里提供 draft_line_id 或 field_id 才显示。
|
||||
*/
|
||||
const showLocateAction = computed(() => {
|
||||
if (props.loading) return false;
|
||||
if (props.taskMissing) return false;
|
||||
const params = (props.primaryAction?.parameters ?? {}) as Record<string, unknown>;
|
||||
const hasDraftLineId = typeof params.draft_line_id === 'string' && params.draft_line_id.length > 0;
|
||||
const hasFieldId = typeof params.field_id === 'string' && params.field_id.length > 0;
|
||||
return hasDraftLineId || hasFieldId;
|
||||
});
|
||||
|
||||
const locateTargetDraftLineId = computed(() => {
|
||||
const params = (props.primaryAction?.parameters ?? {}) as Record<string, unknown>;
|
||||
return typeof params.draft_line_id === 'string' ? params.draft_line_id : null;
|
||||
});
|
||||
|
||||
const locateTargetFieldId = computed(() => {
|
||||
const params = (props.primaryAction?.parameters ?? {}) as Record<string, unknown>;
|
||||
return typeof params.field_id === 'string' ? params.field_id : null;
|
||||
});
|
||||
|
||||
function handleLocateClick() {
|
||||
emit('locate', locateTargetDraftLineId.value, locateTargetFieldId.value);
|
||||
}
|
||||
|
||||
type ReviewCurrentUserStatus =
|
||||
| 'running'
|
||||
| 'waiting_human'
|
||||
| 'retryable'
|
||||
| 'failed'
|
||||
| 'completed'
|
||||
| 'cancelled';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
class="rounded-xl border border-sky-200 bg-sky-50/80 p-3 shadow-sm dark:border-sky-900 dark:bg-sky-950/30"
|
||||
data-testid="review-current-processing-card"
|
||||
:data-user-status="String(userStatus || '')"
|
||||
:data-task-missing="taskMissing ? '1' : '0'"
|
||||
:data-loading="loading ? '1' : '0'"
|
||||
>
|
||||
<header class="mb-3">
|
||||
<h2 class="text-sm font-semibold text-sky-950 dark:text-sky-100">
|
||||
{{ t('chat.shippingOrderReview.currentTask.title') }}
|
||||
</h2>
|
||||
</header>
|
||||
|
||||
<dl class="space-y-1 text-xs text-sky-950 dark:text-sky-100">
|
||||
<div class="flex flex-wrap gap-x-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.currentTask.labelStage') }}</dt>
|
||||
<dd data-testid="review-current-task-stage" :class="loading ? 'animate-pulse' : ''">{{ stageLabel }}</dd>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-x-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.currentProcessing.status') }}</dt>
|
||||
<dd
|
||||
class="inline-flex items-center gap-1"
|
||||
data-testid="review-current-task-status"
|
||||
:class="loading ? 'animate-pulse' : ''"
|
||||
>
|
||||
<RefreshCw
|
||||
v-if="userStatus === 'running' && !loading"
|
||||
class="h-3 w-3 animate-spin"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
{{ statusLabel }}
|
||||
</dd>
|
||||
<!-- v2:状态块内嵌动态说明(弱文本一行,不加标题/图标/区块;显隐裁决在视图侧)。 -->
|
||||
<p
|
||||
v-if="statusDetail?.text"
|
||||
class="w-full text-[11px] leading-4 text-muted"
|
||||
data-testid="review-current-task-status-detail"
|
||||
aria-live="polite"
|
||||
>{{ statusDetail.text }}</p>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<p
|
||||
v-if="taskMissing"
|
||||
class="mt-2 text-[11px] text-rose-800 dark:text-rose-200"
|
||||
data-testid="review-current-processing-task-missing"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.currentProcessing.taskMissingHint') }}
|
||||
</p>
|
||||
|
||||
<aside
|
||||
v-if="taskMissing && showAdminDiagnosis"
|
||||
class="mt-2 rounded border border-rose-300 bg-rose-50/80 p-2 text-[11px] text-rose-950 dark:border-rose-800 dark:bg-rose-950/40 dark:text-rose-100"
|
||||
data-testid="review-current-processing-admin-diagnosis"
|
||||
>
|
||||
<p class="font-medium">{{ t('chat.shippingOrderReview.currentProcessing.adminDiagnosisTitle') }}</p>
|
||||
<p
|
||||
v-if="confirmedTaskId != null"
|
||||
class="mt-1 font-mono"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.currentProcessing.confirmedTaskId', { id: confirmedTaskId }) }}
|
||||
</p>
|
||||
<p class="mt-1">
|
||||
{{ t('chat.shippingOrderReview.currentProcessing.adminDiagnosisStatus') }}
|
||||
</p>
|
||||
<p class="mt-1 text-muted">
|
||||
{{ t('chat.shippingOrderReview.currentProcessing.adminDiagnosisHint') }}
|
||||
</p>
|
||||
</aside>
|
||||
|
||||
<div
|
||||
v-if="showNextStep"
|
||||
class="mt-3 border-t border-sky-200/70 pt-3 dark:border-sky-800/60"
|
||||
data-testid="review-current-task-next-step-section"
|
||||
>
|
||||
<p class="text-[11px] font-medium uppercase tracking-wide text-sky-900/70 dark:text-sky-200/70">
|
||||
{{ t('chat.shippingOrderReview.currentTask.nextStepTitle') }}
|
||||
</p>
|
||||
<p
|
||||
class="mt-1 text-xs text-sky-950 dark:text-sky-100"
|
||||
data-testid="review-current-task-next-step-text"
|
||||
:class="loading ? 'animate-pulse' : ''"
|
||||
>{{ nextStepText }}</p>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="showBusinessAction || showLocateAction"
|
||||
class="mt-3 flex flex-wrap items-center gap-2"
|
||||
data-testid="review-current-task-actions"
|
||||
>
|
||||
<button
|
||||
v-if="showBusinessAction"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-md bg-sky-700 px-3 py-1.5 text-xs font-medium text-white shadow-sm transition hover:bg-sky-800 disabled:opacity-50 dark:bg-sky-600 dark:hover:bg-sky-500"
|
||||
:data-testid="actionIsRetry ? 'review-current-processing-retry' : 'review-current-task-primary-action'"
|
||||
:disabled="retrying || locating"
|
||||
:title="businessActionTitle"
|
||||
@click="handleBusinessActionClick"
|
||||
>
|
||||
<Bot v-if="actionIsInventoryRpa" class="h-3.5 w-3.5" />
|
||||
<RefreshCw
|
||||
v-else-if="actionIsRetry"
|
||||
class="h-3.5 w-3.5"
|
||||
:class="{ 'animate-spin': Boolean(retrying) }"
|
||||
/>
|
||||
{{ businessActionLabel }}
|
||||
</button>
|
||||
<button
|
||||
v-for="action in recoveryActions"
|
||||
:key="action.code"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-md border border-sky-300 bg-surface px-2.5 py-1.5 text-xs font-medium text-sky-800 shadow-sm transition hover:bg-sky-50 disabled:opacity-50 dark:border-sky-700 dark:bg-sky-900 dark:text-sky-100 dark:hover:bg-sky-800"
|
||||
:data-testid="`review-current-task-recovery-${action.code}`"
|
||||
:disabled="retrying || locating"
|
||||
@click="$emit('action', action.code, action.parameters || {})"
|
||||
>
|
||||
{{ recoveryActionLabel(action) }}
|
||||
</button>
|
||||
<button
|
||||
v-if="showLocateAction"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-md border border-sky-300 bg-surface px-2.5 py-1.5 text-xs font-medium text-sky-800 shadow-sm transition hover:bg-sky-50 disabled:opacity-50 dark:border-sky-700 dark:bg-sky-900 dark:text-sky-100 dark:hover:bg-sky-800"
|
||||
data-testid="review-current-task-locate-action"
|
||||
:disabled="locating"
|
||||
@click="handleLocateClick"
|
||||
>
|
||||
<Crosshair class="h-3.5 w-3.5" />
|
||||
{{ t('chat.shippingOrderReview.currentTask.actionLocateLine') }}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts
|
||||
* 用途:锁定唯一标准客户候选的工作台提示,避免将可自动确认状态误报为未识别。
|
||||
* 依赖:vitest、@vue/test-utils、vue-i18n、ReviewCustomerResolutionPanel。
|
||||
* 逻辑:unique_candidate 显示自动确认说明和明确按钮;其他未确认状态维持人工选择入口。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ReviewCustomerResolutionPanel from './ReviewCustomerResolutionPanel.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingCustomer: { loadFailed: '加载失败', confirmFailed: '确认失败' },
|
||||
shippingOrderReview: {
|
||||
customerResolution: {
|
||||
title: '客户确认', subtitle: '请选择标准客户', uniqueCandidateHint: '已找到唯一标准客户候选;保存校验时系统会自动确认,也可手动确认。',
|
||||
confirmUniqueCandidate: '确认唯一候选', selectCustomer: '选择标准客户', retrying: '识别中…', retryCustomer: '重新识别客户',
|
||||
retryDone: '已重新识别客户', retryFailed: '重新识别客户失败', confirmed: '客户已确认', confirmReason: '人工确认',
|
||||
standardCustomer: '标准客户', customerCode: '客户编码', matchedInputs: '匹配输入', candidates: '候选客户', pdfReparseHint: '请重新识别 PDF',
|
||||
inputLabels: { customerCode: '客户编码', customerName: '客户名称', address: '地址', email: '邮箱', domain: '域名', other: '其他' },
|
||||
status: { unique_candidate: '唯一候选', unmatched: '未匹配', confirmed: '已确认' },
|
||||
},
|
||||
resume: { autoCreated: '已自动建单', waitingManualConfirm: '等待人工确认' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
function mountPanel(status: string) {
|
||||
return mount(ReviewCustomerResolutionPanel, {
|
||||
props: {
|
||||
caseNo: 'CASE-CUSTOMER-1',
|
||||
editable: true,
|
||||
resolution: { resolved: false, status, raw_name: 'ACME' },
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: { ShippingCustomerConfirmDialog: true },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe('ReviewCustomerResolutionPanel', () => {
|
||||
it('唯一候选展示自动确认说明和明确确认入口', () => {
|
||||
const wrapper = mountPanel('unique_candidate');
|
||||
|
||||
expect(wrapper.text()).toContain('保存校验时系统会自动确认');
|
||||
expect(wrapper.get('[data-testid="review-select-customer"]').text()).toContain('确认唯一候选');
|
||||
});
|
||||
|
||||
it('非唯一未确认状态维持人工选择客户入口', () => {
|
||||
const wrapper = mountPanel('unmatched');
|
||||
|
||||
expect(wrapper.text()).not.toContain('保存校验时系统会自动确认');
|
||||
expect(wrapper.get('[data-testid="review-select-customer"]').text()).toContain('选择标准客户');
|
||||
});
|
||||
});
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue
|
||||
用途:复核工作台固定「建单前客户确认」区域(与重新识别 PDF 分层)。
|
||||
依赖:vue-i18n、ShippingCustomerConfirmDialog、shipping.api 客户确认/重识别接口。
|
||||
逻辑:未解决时完整展开置顶;已解决且 compact 时缩为一行摘要;
|
||||
选择标准客户 / 重新识别客户;成功后 emit refreshed 刷新建单资格。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import ShippingCustomerConfirmDialog from '@/features/chat/components/ShippingCustomerConfirmDialog.vue';
|
||||
import {
|
||||
confirmWorkspaceShippingOrderReviewCustomer,
|
||||
listWorkspaceShippingCustomerOptions,
|
||||
retryWorkspaceShippingOrderReviewCustomerResolution,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import type {
|
||||
ShippingCustomerOption,
|
||||
ShippingOrderReviewCustomerResolution,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
caseNo: string;
|
||||
resolution: ShippingOrderReviewCustomerResolution | null | undefined;
|
||||
editable: boolean;
|
||||
/** 已解决时缩为一行摘要(放入「更多状态」) */
|
||||
compact?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
refreshed: [];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const msg = useMessage();
|
||||
const busy = ref(false);
|
||||
const dialogOpen = ref(false);
|
||||
const options = ref<ShippingCustomerOption[]>([]);
|
||||
const loadingOptions = ref(false);
|
||||
|
||||
const resolved = computed(() => Boolean(props.resolution?.resolved));
|
||||
const hasUniqueCandidate = computed(() => (
|
||||
!resolved.value
|
||||
&& String(props.resolution?.status || '').trim() === 'unique_candidate'
|
||||
));
|
||||
const statusLabel = computed(() => {
|
||||
const status = String(props.resolution?.status || '').trim();
|
||||
if (!status) {
|
||||
return resolved.value
|
||||
? t('chat.shippingOrderReview.customerResolution.status.confirmed')
|
||||
: t('chat.shippingOrderReview.customerResolution.status.unmatched');
|
||||
}
|
||||
const key = `chat.shippingOrderReview.customerResolution.status.${status}`;
|
||||
return te(key) ? t(key) : status;
|
||||
});
|
||||
|
||||
const displayName = computed(() => {
|
||||
const name = String(props.resolution?.standard_name || '').trim();
|
||||
const code = String(props.resolution?.short_code || '').trim();
|
||||
if (name && code) return `${name} (${code})`;
|
||||
return name || code || String(props.resolution?.raw_name || '').trim() || '—';
|
||||
});
|
||||
|
||||
const inputValues = computed(() => props.resolution?.input_values || []);
|
||||
const candidateRows = computed(() => props.resolution?.candidates || []);
|
||||
|
||||
function inputLabel(definitionCode: string | null | undefined): string {
|
||||
const code = String(definitionCode || '').trim().toLowerCase();
|
||||
if (code.includes('customer') && code.includes('code')) return t('chat.shippingOrderReview.customerResolution.inputLabels.customerCode');
|
||||
if (code.includes('customer') && code.includes('name')) return t('chat.shippingOrderReview.customerResolution.inputLabels.customerName');
|
||||
if (code.includes('address')) return t('chat.shippingOrderReview.customerResolution.inputLabels.address');
|
||||
if (code.endsWith('customer_code')) return t('chat.shippingOrderReview.customerResolution.inputLabels.customerCode');
|
||||
if (code.endsWith('customer_name')) return t('chat.shippingOrderReview.customerResolution.inputLabels.customerName');
|
||||
if (code.endsWith('address')) return t('chat.shippingOrderReview.customerResolution.inputLabels.address');
|
||||
if (code.includes('email')) return t('chat.shippingOrderReview.customerResolution.inputLabels.email');
|
||||
if (code.includes('domain')) return t('chat.shippingOrderReview.customerResolution.inputLabels.domain');
|
||||
return t('chat.shippingOrderReview.customerResolution.inputLabels.other');
|
||||
}
|
||||
|
||||
function candidateValue(candidate: unknown, key: string): string {
|
||||
const row = candidate && typeof candidate === 'object' ? candidate as Record<string, unknown> : {};
|
||||
return String(row[key] ?? '').trim() || '—';
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开标准客户选择弹窗并加载选项。
|
||||
*/
|
||||
async function openSelectDialog() {
|
||||
if (!props.editable || busy.value) return;
|
||||
dialogOpen.value = true;
|
||||
loadingOptions.value = true;
|
||||
try {
|
||||
options.value = await listWorkspaceShippingCustomerOptions();
|
||||
} catch (error: unknown) {
|
||||
options.value = [];
|
||||
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.loadFailed'));
|
||||
} finally {
|
||||
loadingOptions.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
openSelectDialog,
|
||||
});
|
||||
|
||||
/**
|
||||
* 按关键词搜索标准客户。
|
||||
*/
|
||||
async function searchCustomers(query: string) {
|
||||
loadingOptions.value = true;
|
||||
try {
|
||||
options.value = await listWorkspaceShippingCustomerOptions(query.trim());
|
||||
} catch (error: unknown) {
|
||||
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.loadFailed'));
|
||||
} finally {
|
||||
loadingOptions.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认标准客户并通知父级刷新 Case / 建单资格。
|
||||
*/
|
||||
async function onConfirm(customerId: number) {
|
||||
if (!props.caseNo || busy.value) return;
|
||||
busy.value = true;
|
||||
try {
|
||||
const result = await confirmWorkspaceShippingOrderReviewCustomer(props.caseNo, {
|
||||
customer_id: customerId,
|
||||
reason: t('chat.shippingOrderReview.customerResolution.confirmReason'),
|
||||
});
|
||||
dialogOpen.value = false;
|
||||
const resume = result.resume_outcome;
|
||||
if (resume?.outcome === 'auto_created' || resume?.outcome === 'idempotent_replay') {
|
||||
msg.success(t('chat.shippingOrderReview.resume.autoCreated', {
|
||||
taskNo: resume.task_no || '',
|
||||
}));
|
||||
} else if (resume?.outcome === 'waiting_manual_confirm') {
|
||||
msg.success(t('chat.shippingOrderReview.resume.waitingManualConfirm'));
|
||||
} else {
|
||||
msg.success(t('chat.shippingOrderReview.customerResolution.confirmed'));
|
||||
}
|
||||
emit('refreshed');
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: (error instanceof Error ? error.message : t('chat.shippingCustomer.confirmFailed'));
|
||||
msg.warning(message);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重新识别客户(不触发 PDF 重识别)。
|
||||
*/
|
||||
async function onRetry() {
|
||||
if (!props.caseNo || !props.editable || busy.value) return;
|
||||
busy.value = true;
|
||||
try {
|
||||
await retryWorkspaceShippingOrderReviewCustomerResolution(props.caseNo);
|
||||
msg.success(t('chat.shippingOrderReview.customerResolution.retryDone'));
|
||||
emit('refreshed');
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.customerResolution.retryFailed'));
|
||||
msg.warning(message);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
class="rounded-xl border border-default bg-surface p-3 shadow-sm"
|
||||
data-testid="review-customer-resolution-panel"
|
||||
:data-compact="compact && resolved ? 'true' : 'false'"
|
||||
>
|
||||
<!-- 已解决摘要:一行展示客户与状态,避免占满侧栏首位 -->
|
||||
<div
|
||||
v-if="compact && resolved"
|
||||
class="flex flex-wrap items-center justify-between gap-2"
|
||||
data-testid="review-customer-resolution-compact"
|
||||
>
|
||||
<p class="text-xs text-secondary">
|
||||
<span class="font-medium text-primary">{{ t('chat.shippingOrderReview.customerResolution.title') }}</span>
|
||||
<span class="mx-1 text-muted">·</span>
|
||||
<span>{{ displayName }}</span>
|
||||
</p>
|
||||
<span
|
||||
class="rounded-full bg-emerald-100 px-2 py-0.5 text-[11px] font-medium text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100"
|
||||
data-testid="review-customer-resolution-badge"
|
||||
>
|
||||
{{ statusLabel }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<header class="flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.customerResolution.title') }}</h2>
|
||||
<p class="mt-0.5 text-xs text-muted">
|
||||
{{ hasUniqueCandidate
|
||||
? t('chat.shippingOrderReview.customerResolution.uniqueCandidateHint')
|
||||
: t('chat.shippingOrderReview.customerResolution.subtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
class="rounded-full px-2.5 py-1 text-xs font-medium"
|
||||
:class="resolved
|
||||
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
|
||||
: 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'"
|
||||
data-testid="review-customer-resolution-badge"
|
||||
>
|
||||
{{ statusLabel }}
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<dl class="mt-2 space-y-1 text-xs text-secondary">
|
||||
<div class="flex flex-wrap gap-x-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.standardCustomer') }}</dt>
|
||||
<dd class="font-medium text-primary">{{ displayName }}</dd>
|
||||
</div>
|
||||
<div v-if="resolution?.short_code" class="flex flex-wrap gap-x-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.customerCode') }}</dt>
|
||||
<dd class="font-mono font-medium text-primary">{{ resolution.short_code }}</dd>
|
||||
</div>
|
||||
<div v-if="inputValues.length" class="mt-2 border-t border-default pt-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.matchedInputs') }}</dt>
|
||||
<dd v-for="item in inputValues" :key="`${item.definition_code}:${item.normalized_value}`" class="mt-1 flex flex-wrap gap-x-2">
|
||||
<span class="text-muted">{{ inputLabel(item.definition_label || item.definition_code) }}</span>
|
||||
<span class="font-mono text-primary">{{ item.raw_value || item.normalized_value || '—' }}</span>
|
||||
</dd>
|
||||
</div>
|
||||
<div v-if="candidateRows.length > 1" class="mt-2 border-t border-default pt-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.candidates') }}</dt>
|
||||
<dd v-for="candidate in candidateRows" :key="String(candidate.customer_id)" class="mt-1 flex flex-wrap gap-x-2">
|
||||
<span class="text-primary">{{ candidateValue(candidate, 'standard_name') }}</span>
|
||||
<span class="font-mono text-muted">{{ candidateValue(candidate, 'short_code') }}</span>
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<div v-if="editable" class="mt-3 flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl bg-primary px-3 py-1.5 text-sm font-medium text-on-primary disabled:opacity-60"
|
||||
data-testid="review-select-customer"
|
||||
:disabled="busy"
|
||||
@click="openSelectDialog"
|
||||
>
|
||||
{{ hasUniqueCandidate
|
||||
? t('chat.shippingOrderReview.customerResolution.confirmUniqueCandidate')
|
||||
: t('chat.shippingOrderReview.customerResolution.selectCustomer') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-secondary hover:bg-surface-soft disabled:opacity-60"
|
||||
data-testid="review-retry-customer"
|
||||
:disabled="busy"
|
||||
@click="onRetry"
|
||||
>
|
||||
{{ busy ? t('chat.shippingOrderReview.customerResolution.retrying') : t('chat.shippingOrderReview.customerResolution.retryCustomer') }}
|
||||
</button>
|
||||
</div>
|
||||
<p class="mt-2 text-[11px] text-muted">
|
||||
{{ t('chat.shippingOrderReview.customerResolution.pdfReparseHint') }}
|
||||
</p>
|
||||
|
||||
<ShippingCustomerConfirmDialog
|
||||
:open="dialogOpen"
|
||||
:options="options"
|
||||
:loading="loadingOptions || busy"
|
||||
@close="dialogOpen = false"
|
||||
@search="searchCustomers"
|
||||
@confirm="onConfirm"
|
||||
/>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
+268
@@ -0,0 +1,268 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewDocumentEvidenceDrawer.spec.ts
|
||||
* 用途:锁定 PDF 证据浮窗/侧栏的打开、导航、展开/固定、resize 句柄与无 bbox 引文展示契约。
|
||||
* 依赖:vitest、@vue/test-utils、vue-i18n。
|
||||
* 逻辑:验证上一/下一证据、关闭/展开/固定 emit、「更多」内退出后保留、八向 resize,以及无 bbox 时展示引文。
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { flushPromises, mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ReviewDocumentEvidenceDrawer from './ReviewDocumentEvidenceDrawer.vue';
|
||||
import type { ShippingOrderReviewEvidence } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
vi.mock('./ReviewDocumentPreview.vue', () => ({
|
||||
default: {
|
||||
name: 'ReviewDocumentPreview',
|
||||
template: '<div data-testid="mock-pdf-preview" />',
|
||||
},
|
||||
}));
|
||||
|
||||
const evidenceList: ShippingOrderReviewEvidence[] = [
|
||||
{
|
||||
evidence_id: 'ev-1',
|
||||
field_id: 'fld-po',
|
||||
page_no: 1,
|
||||
quote: 'PO-A',
|
||||
bbox: { x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 },
|
||||
source: 'document_cell',
|
||||
highlight_quality: 'candidate',
|
||||
highlight_source: 'pdf_coordinate',
|
||||
highlight_bbox: { x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 },
|
||||
coordinate_status: 'candidate',
|
||||
coordinate_issue_codes: [],
|
||||
evidence_ref: null,
|
||||
token_ids: [],
|
||||
value_match_status: 'matched',
|
||||
},
|
||||
{
|
||||
evidence_id: 'ev-2',
|
||||
field_id: 'fld-qty',
|
||||
line_index: 0,
|
||||
page_no: 2,
|
||||
quote: '10 EA',
|
||||
bbox: null,
|
||||
source: 'document_cell',
|
||||
highlight_quality: 'unavailable',
|
||||
highlight_source: 'machine_extraction',
|
||||
highlight_bbox: null,
|
||||
coordinate_status: 'unavailable',
|
||||
coordinate_issue_codes: ['coordinate_missing'],
|
||||
evidence_ref: null,
|
||||
token_ids: [],
|
||||
value_match_status: 'matched',
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* 挂载证据抽屉。
|
||||
*/
|
||||
function mountDrawer(overrides: Record<string, unknown> = {}) {
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
previewTitle: 'PDF',
|
||||
previewLoading: '加载',
|
||||
previewUnavailable: '不可用',
|
||||
emptyValue: '空',
|
||||
evidenceAt: '第 {page} 页',
|
||||
evidenceNoHighlight: '无坐标高亮',
|
||||
evidenceInvalidHighlight: '坐标无效',
|
||||
locateUnavailableHint: '无可靠坐标',
|
||||
restoreMachine: '恢复机器值',
|
||||
llmSuggestion: { request: '请求 AI' },
|
||||
workbench: {
|
||||
pinPdf: '退出后保留',
|
||||
unpinPdf: '退出后关闭',
|
||||
closePdf: '关闭',
|
||||
pinPdfHint: '退出后保留',
|
||||
unpinPdfHint: '退出后关闭',
|
||||
expandPdf: '展开',
|
||||
collapsePdf: '收起',
|
||||
expandPdfHint: '放大',
|
||||
collapsePdfHint: '收起',
|
||||
dockPdf: '固定为侧栏',
|
||||
undockPdf: '取消固定',
|
||||
dockPdfHint: '双栏',
|
||||
undockPdfHint: '浮窗',
|
||||
movePdfLeft: '移至左侧',
|
||||
movePdfRight: '移至右侧',
|
||||
movePdfSideHint: '换侧',
|
||||
moreActions: '更多',
|
||||
},
|
||||
highlightQuality: {
|
||||
verified: '已验证',
|
||||
candidate: '候选',
|
||||
unavailable: '无坐标',
|
||||
invalid: '坐标无效',
|
||||
},
|
||||
highlightSource: {
|
||||
pdf_coordinate: 'PDF 原生坐标',
|
||||
machine_extraction: '机器抽取',
|
||||
},
|
||||
coordinateIssues: {
|
||||
coordinate_missing: '未获得可靠字段级坐标',
|
||||
},
|
||||
evidenceDrawer: {
|
||||
title: '证据核对',
|
||||
pageUnknown: '未知页',
|
||||
prevEvidence: '上一证据',
|
||||
nextEvidence: '下一证据',
|
||||
field: '字段:{field}',
|
||||
currentValue: '当前值',
|
||||
machineValue: '机器值',
|
||||
source: '来源',
|
||||
highlightQuality: '高亮质量',
|
||||
highlightSource: '坐标来源',
|
||||
layoutPath: '版面路径',
|
||||
detailsToggle: '证据详情',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return mount(ReviewDocumentEvidenceDrawer, {
|
||||
props: {
|
||||
open: true,
|
||||
pinned: false,
|
||||
expanded: false,
|
||||
docked: false,
|
||||
floatSide: 'right',
|
||||
src: 'blob:mock',
|
||||
evidence: evidenceList[0],
|
||||
evidenceList,
|
||||
fieldLabel: '客户 PO',
|
||||
draftValue: 'PO-A',
|
||||
machineValue: 'PO-A',
|
||||
valueSourceLabel: '系统识别',
|
||||
showAiActions: true,
|
||||
...overrides,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
attachTo: document.body,
|
||||
});
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
describe('ReviewDocumentEvidenceDrawer', () => {
|
||||
it('renders floating panel when open and emits close/expand/dock; pin lives in more menu', async () => {
|
||||
const wrapper = mountDrawer();
|
||||
const root = wrapper.find('[data-testid="review-document-evidence-drawer"]');
|
||||
expect(root.exists()).toBe(true);
|
||||
expect(root.attributes('data-presentation')).toBe('floating');
|
||||
expect(root.attributes('role')).toBe('dialog');
|
||||
expect(root.attributes('aria-modal')).toBe('true');
|
||||
expect(root.classes()).toContain('fixed');
|
||||
expect(root.attributes('data-width')).toBeTruthy();
|
||||
expect(root.attributes('data-height')).toBeTruthy();
|
||||
expect(wrapper.find('[data-testid="review-evidence-ordinal"]').text()).toContain('1/2');
|
||||
await wrapper.find('[data-testid="review-evidence-close"]').trigger('click');
|
||||
expect(wrapper.emitted('close')).toBeTruthy();
|
||||
await wrapper.find('[data-testid="review-evidence-toggle-expand"]').trigger('click');
|
||||
expect(wrapper.emitted('toggle-expand')).toBeTruthy();
|
||||
await wrapper.find('[data-testid="review-evidence-toggle-dock"]').trigger('click');
|
||||
expect(wrapper.emitted('toggle-dock')).toBeTruthy();
|
||||
|
||||
// 关键断言:低频操作收入「更多」,打开后再点「退出后保留」。
|
||||
expect(wrapper.find('[data-testid="review-evidence-toggle-pin"]').exists()).toBe(false);
|
||||
await wrapper.find('[data-testid="review-evidence-more"]').trigger('click');
|
||||
expect(wrapper.find('[data-testid="review-evidence-more-menu"]').exists()).toBe(true);
|
||||
await wrapper.find('[data-testid="review-evidence-toggle-pin"]').trigger('click');
|
||||
expect(wrapper.emitted('toggle-pin')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('exposes eight resize handles on floating panel only', () => {
|
||||
const floating = mountDrawer({ docked: false });
|
||||
for (const dir of ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw']) {
|
||||
expect(floating.find(`[data-testid="review-evidence-resize-${dir}"]`).exists()).toBe(true);
|
||||
}
|
||||
floating.unmount();
|
||||
|
||||
const docked = mountDrawer({ docked: true });
|
||||
expect(docked.find('[data-testid="review-evidence-resize-se"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('persists float geometry to localStorage after resize end', async () => {
|
||||
const wrapper = mountDrawer();
|
||||
const handleEl = wrapper.find('[data-testid="review-evidence-resize-se"]').element;
|
||||
handleEl.dispatchEvent(new PointerEvent('pointerdown', {
|
||||
bubbles: true,
|
||||
clientX: 100,
|
||||
clientY: 100,
|
||||
}));
|
||||
window.dispatchEvent(new PointerEvent('pointermove', { clientX: 180, clientY: 160 }));
|
||||
window.dispatchEvent(new PointerEvent('pointerup'));
|
||||
await flushPromises();
|
||||
const raw = localStorage.getItem('hxops.shippingReview.evidenceFloat.v1');
|
||||
// 关键断言:拖拽结束写入尺寸位置,供下次打开复用。
|
||||
expect(raw).toBeTruthy();
|
||||
const parsed = JSON.parse(String(raw)) as { width: number; height: number };
|
||||
expect(parsed.width).toBeGreaterThanOrEqual(360);
|
||||
expect(parsed.height).toBeGreaterThanOrEqual(320);
|
||||
});
|
||||
|
||||
it('closes floating panel on Escape', async () => {
|
||||
const wrapper = mountDrawer({ open: true, docked: false });
|
||||
await flushPromises();
|
||||
document.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
key: 'Escape',
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}));
|
||||
// 关键断言:浮动态 Esc 关闭,便于键盘退出。
|
||||
expect(wrapper.emitted('close')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('uses complementary semantics when docked as sidebar', () => {
|
||||
const wrapper = mountDrawer({ docked: true });
|
||||
const root = wrapper.find('[data-testid="review-document-evidence-drawer"]');
|
||||
expect(root.attributes('data-presentation')).toBe('docked');
|
||||
expect(root.attributes('role')).toBe('complementary');
|
||||
expect(root.attributes('aria-modal')).toBeUndefined();
|
||||
expect(root.classes()).toContain('relative');
|
||||
expect(root.classes()).not.toContain('fixed');
|
||||
});
|
||||
|
||||
it('enables next evidence and disables prev on first item', async () => {
|
||||
const wrapper = mountDrawer();
|
||||
expect((wrapper.find('[data-testid="review-evidence-prev"]').element as HTMLButtonElement).disabled).toBe(true);
|
||||
expect((wrapper.find('[data-testid="review-evidence-next"]').element as HTMLButtonElement).disabled).toBe(false);
|
||||
await wrapper.find('[data-testid="review-evidence-next"]').trigger('click');
|
||||
expect(wrapper.emitted('next-evidence')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('shows quote when evidence has no bbox', () => {
|
||||
const wrapper = mountDrawer({ evidence: evidenceList[1] });
|
||||
expect(wrapper.find('[data-testid="review-evidence-no-bbox"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-evidence-no-bbox"]').text()).toContain('10 EA');
|
||||
});
|
||||
|
||||
it('renders email evidence through the safe HTML preview URL', () => {
|
||||
const wrapper = mountDrawer({
|
||||
emailPreview: {
|
||||
document_id: 9,
|
||||
filename: 'source.eml',
|
||||
text: 'fallback text',
|
||||
render_kind: 'safe_html',
|
||||
preview_url: '/email-preview?token=one-shot',
|
||||
},
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-email-evidence-html"]').attributes('src'))
|
||||
.toBe('/email-preview?token=one-shot');
|
||||
expect(wrapper.find('[data-testid="review-email-evidence-preview"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('does not render when closed', () => {
|
||||
const wrapper = mountDrawer({ open: false });
|
||||
expect(wrapper.find('[data-testid="review-document-evidence-drawer"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
+839
@@ -0,0 +1,839 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewDocumentEvidenceDrawer.vue
|
||||
用途:复核工作台 PDF 证据面板(默认浮动、可拖拽/resize、可固定为侧栏)。
|
||||
依赖:ReviewDocumentPreview、ShippingOrderReviewEvidence、vue-i18n、field-highlight 契约。
|
||||
逻辑:浮动用 left/top/width/height;四边四角 resize;localStorage 记忆尺寸位置;
|
||||
dialog 语义(Esc/焦点陷阱);打开避让焦点字段;低频操作收入「更多」菜单。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import ReviewDocumentPreview from './ReviewDocumentPreview.vue';
|
||||
import type { ShippingOrderReviewEvidence } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const FOCUSABLE_SELECTOR = [
|
||||
'a[href]',
|
||||
'button:not([disabled])',
|
||||
'textarea:not([disabled])',
|
||||
'input:not([disabled])',
|
||||
'select:not([disabled])',
|
||||
'[tabindex]:not([tabindex="-1"])',
|
||||
].join(',');
|
||||
|
||||
const STORAGE_KEY = 'hxops.shippingReview.evidenceFloat.v1';
|
||||
const MIN_WIDTH = 360;
|
||||
const MIN_HEIGHT = 320;
|
||||
const VIEW_MARGIN = 16;
|
||||
const FOOTER_CLEARANCE = 72;
|
||||
|
||||
type ResizeDir = 'n' | 's' | 'e' | 'w' | 'ne' | 'nw' | 'se' | 'sw';
|
||||
|
||||
interface FloatGeom {
|
||||
left: number;
|
||||
top: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
const RESIZE_DIRS: ResizeDir[] = ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw'];
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
pinned: boolean;
|
||||
expanded: boolean;
|
||||
docked: boolean;
|
||||
floatSide: 'right' | 'left';
|
||||
src: string;
|
||||
emailPreview?: { document_id: number; filename: string; text: string; render_kind: 'safe_html' | 'text'; preview_url?: string } | null;
|
||||
evidence: ShippingOrderReviewEvidence | null;
|
||||
evidenceList: ShippingOrderReviewEvidence[];
|
||||
fieldLabel?: string;
|
||||
draftValue?: string | null;
|
||||
machineValue?: string | null;
|
||||
valueSourceLabel?: string;
|
||||
showAiActions?: boolean;
|
||||
/** Case 切换时重置证据焦点相关态;不清除用户记住的浮窗几何。 */
|
||||
resetKey?: string | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
'toggle-pin': [];
|
||||
'toggle-expand': [];
|
||||
'toggle-dock': [];
|
||||
'toggle-side': [];
|
||||
'prev-evidence': [];
|
||||
'next-evidence': [];
|
||||
'request-ai': [];
|
||||
'restore-machine': [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const panelRef = ref<HTMLElement | null>(null);
|
||||
const closeButtonRef = ref<HTMLButtonElement | null>(null);
|
||||
const moreOpen = ref(false);
|
||||
const detailsOpen = ref(false);
|
||||
const geom = ref<FloatGeom>(defaultGeom('right', false));
|
||||
const dragging = ref(false);
|
||||
const resizing = ref(false);
|
||||
|
||||
let dragOrigin: { x: number; y: number; left: number; top: number } | null = null;
|
||||
let resizeOrigin: {
|
||||
dir: ResizeDir;
|
||||
x: number;
|
||||
y: number;
|
||||
left: number;
|
||||
top: number;
|
||||
width: number;
|
||||
height: number;
|
||||
} | null = null;
|
||||
let previouslyFocused: HTMLElement | null = null;
|
||||
let autoSideAdjustedForOpen = false;
|
||||
|
||||
/**
|
||||
* 视口允许的最大浮窗宽高(70% / 85%)。
|
||||
*/
|
||||
function maxSize() {
|
||||
if (typeof window === 'undefined') return { width: 720, height: 680 };
|
||||
return {
|
||||
width: Math.max(MIN_WIDTH, Math.floor(window.innerWidth * 0.7)),
|
||||
height: Math.max(MIN_HEIGHT, Math.floor(window.innerHeight * 0.85)),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成默认浮窗几何(右下或左下,避开底栏)。
|
||||
*/
|
||||
function defaultGeom(side: 'left' | 'right', expanded: boolean): FloatGeom {
|
||||
const max = maxSize();
|
||||
const width = Math.min(expanded ? 720 : 440, max.width);
|
||||
const height = Math.min(expanded ? 680 : 520, max.height);
|
||||
if (typeof window === 'undefined') {
|
||||
return { left: 16, top: 16, width, height };
|
||||
}
|
||||
const left = side === 'left'
|
||||
? VIEW_MARGIN
|
||||
: Math.max(VIEW_MARGIN, window.innerWidth - width - VIEW_MARGIN);
|
||||
const top = Math.max(
|
||||
VIEW_MARGIN,
|
||||
window.innerHeight - height - FOOTER_CLEARANCE,
|
||||
);
|
||||
return { left, top, width, height };
|
||||
}
|
||||
|
||||
/**
|
||||
* 钳制几何到视口与最小/最大尺寸。
|
||||
*/
|
||||
function clampGeom(next: FloatGeom): FloatGeom {
|
||||
const max = maxSize();
|
||||
const width = Math.min(max.width, Math.max(MIN_WIDTH, Math.round(next.width)));
|
||||
const height = Math.min(max.height, Math.max(MIN_HEIGHT, Math.round(next.height)));
|
||||
if (typeof window === 'undefined') {
|
||||
return { left: next.left, top: next.top, width, height };
|
||||
}
|
||||
const maxLeft = Math.max(VIEW_MARGIN, window.innerWidth - width - VIEW_MARGIN);
|
||||
const maxTop = Math.max(VIEW_MARGIN, window.innerHeight - height - VIEW_MARGIN);
|
||||
return {
|
||||
width,
|
||||
height,
|
||||
left: Math.min(maxLeft, Math.max(VIEW_MARGIN, Math.round(next.left))),
|
||||
top: Math.min(maxTop, Math.max(VIEW_MARGIN, Math.round(next.top))),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 localStorage 恢复浮窗几何。
|
||||
*/
|
||||
function loadStoredGeom(): FloatGeom | null {
|
||||
if (typeof localStorage === 'undefined') return null;
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (!raw) return null;
|
||||
const parsed = JSON.parse(raw) as Partial<FloatGeom>;
|
||||
if (
|
||||
typeof parsed.left !== 'number'
|
||||
|| typeof parsed.top !== 'number'
|
||||
|| typeof parsed.width !== 'number'
|
||||
|| typeof parsed.height !== 'number'
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return clampGeom({
|
||||
left: parsed.left,
|
||||
top: parsed.top,
|
||||
width: parsed.width,
|
||||
height: parsed.height,
|
||||
});
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 持久化浮窗几何(跨 Case 复用尺寸位置,不复用证据焦点)。
|
||||
*/
|
||||
function persistGeom(next: FloatGeom) {
|
||||
if (typeof localStorage === 'undefined') return;
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
|
||||
} catch {
|
||||
/* ignore quota */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用几何并可选持久化。
|
||||
*/
|
||||
function applyGeom(next: FloatGeom, persist = true) {
|
||||
const clamped = clampGeom(next);
|
||||
geom.value = clamped;
|
||||
if (persist) persistGeom(clamped);
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前证据在列表中的序号(1-based);无匹配时为 0。
|
||||
*/
|
||||
const evidenceOrdinal = computed(() => {
|
||||
const id = String(props.evidence?.evidence_id || '');
|
||||
if (!id) return 0;
|
||||
const idx = props.evidenceList.findIndex((item) => item.evidence_id === id);
|
||||
return idx >= 0 ? idx + 1 : 0;
|
||||
});
|
||||
|
||||
const canPrev = computed(() => evidenceOrdinal.value > 1);
|
||||
const canNext = computed(() => {
|
||||
const total = props.evidenceList.length;
|
||||
return evidenceOrdinal.value > 0 && evidenceOrdinal.value < total;
|
||||
});
|
||||
|
||||
const pageLabel = computed(() => {
|
||||
const page = props.evidence?.page_no;
|
||||
if (page == null) return t('chat.shippingOrderReview.evidenceDrawer.pageUnknown');
|
||||
return t('chat.shippingOrderReview.evidenceAt', { page });
|
||||
});
|
||||
|
||||
const hasDrawableHighlight = computed(() => {
|
||||
const quality = String(props.evidence?.highlight_quality || '');
|
||||
return (quality === 'verified' || quality === 'candidate')
|
||||
&& Boolean(props.evidence?.highlight_bbox || props.evidence?.bbox);
|
||||
});
|
||||
|
||||
const highlightQualityLabel = computed(() => {
|
||||
const quality = String(props.evidence?.highlight_quality || 'unavailable');
|
||||
return t(`chat.shippingOrderReview.highlightQuality.${quality}`, quality);
|
||||
});
|
||||
|
||||
const highlightSourceLabel = computed(() => {
|
||||
const source = String(props.evidence?.highlight_source || props.evidence?.source || 'unknown');
|
||||
return t(`chat.shippingOrderReview.highlightSource.${source}`, source);
|
||||
});
|
||||
|
||||
const coordinateIssueLabels = computed(() => {
|
||||
const codes = props.evidence?.coordinate_issue_codes || [];
|
||||
return codes.map((code) => t(`chat.shippingOrderReview.coordinateIssues.${code}`, code));
|
||||
});
|
||||
|
||||
/**
|
||||
* 面板根节点 class:浮动 fixed;固定侧栏走文档流。
|
||||
*/
|
||||
const panelClass = computed(() => {
|
||||
if (props.docked) {
|
||||
return [
|
||||
'relative flex min-h-[320px] min-w-0 flex-col overflow-hidden rounded-xl border border-default',
|
||||
'bg-surface shadow-sm xl:min-h-[520px] ',
|
||||
].join(' ');
|
||||
}
|
||||
return [
|
||||
'fixed z-30 flex flex-col overflow-hidden rounded-xl border border-default',
|
||||
'bg-surface shadow-2xl ',
|
||||
].join(' ');
|
||||
});
|
||||
|
||||
/**
|
||||
* 浮动几何 style;侧栏不使用。
|
||||
*/
|
||||
const panelStyle = computed(() => {
|
||||
if (props.docked) return undefined;
|
||||
return {
|
||||
left: `${geom.value.left}px`,
|
||||
top: `${geom.value.top}px`,
|
||||
width: `${geom.value.width}px`,
|
||||
height: `${geom.value.height}px`,
|
||||
};
|
||||
});
|
||||
|
||||
const resizeCursor: Record<ResizeDir, string> = {
|
||||
n: 'ns-resize',
|
||||
s: 'ns-resize',
|
||||
e: 'ew-resize',
|
||||
w: 'ew-resize',
|
||||
ne: 'nesw-resize',
|
||||
sw: 'nesw-resize',
|
||||
nw: 'nwse-resize',
|
||||
se: 'nwse-resize',
|
||||
};
|
||||
|
||||
/**
|
||||
* resize handle 定位 style(边 6px / 角 10px)。
|
||||
*/
|
||||
function resizeHandleStyle(dir: ResizeDir): Record<string, string> {
|
||||
const edge = '6px';
|
||||
const corner = '10px';
|
||||
const styles: Record<ResizeDir, Record<string, string>> = {
|
||||
n: { top: '0', left: corner, right: corner, height: edge },
|
||||
s: { bottom: '0', left: corner, right: corner, height: edge },
|
||||
e: { top: corner, right: '0', bottom: corner, width: edge },
|
||||
w: { top: corner, left: '0', bottom: corner, width: edge },
|
||||
ne: { top: '0', right: '0', width: corner, height: corner },
|
||||
nw: { top: '0', left: '0', width: corner, height: corner },
|
||||
se: { bottom: '0', right: '0', width: corner, height: corner },
|
||||
sw: { bottom: '0', left: '0', width: corner, height: corner },
|
||||
};
|
||||
return styles[dir];
|
||||
}
|
||||
|
||||
/** 收集面板内可聚焦控件。 */
|
||||
const focusableNodes = (): HTMLElement[] => {
|
||||
if (!panelRef.value) return [];
|
||||
return Array.from(panelRef.value.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR))
|
||||
.filter((node) => !node.hasAttribute('disabled') && node.getAttribute('aria-hidden') !== 'true');
|
||||
};
|
||||
|
||||
const onKeydown = (event: KeyboardEvent) => {
|
||||
if (!props.open || props.docked) return;
|
||||
if (event.key === 'Escape') {
|
||||
if (moreOpen.value) {
|
||||
event.preventDefault();
|
||||
moreOpen.value = false;
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
emit('close');
|
||||
return;
|
||||
}
|
||||
if (event.key !== 'Tab') return;
|
||||
const nodes = focusableNodes();
|
||||
const first = nodes[0];
|
||||
const last = nodes[nodes.length - 1];
|
||||
if (!first || !last) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
const active = document.activeElement as HTMLElement | null;
|
||||
const inside = Boolean(active && panelRef.value?.contains(active));
|
||||
if (event.shiftKey) {
|
||||
if (!inside || active === first) {
|
||||
event.preventDefault();
|
||||
last.focus();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!inside || active === last) {
|
||||
event.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
};
|
||||
|
||||
const rectsOverlap = (a: DOMRect, b: DOMRect) => !(
|
||||
a.right < b.left || a.left > b.right || a.bottom < b.top || a.top > b.bottom
|
||||
);
|
||||
|
||||
/**
|
||||
* 打开浮窗后若遮挡打开前焦点字段,则移到另一侧一次。
|
||||
*/
|
||||
const maybeAvoidFocusedField = async () => {
|
||||
if (props.docked || autoSideAdjustedForOpen || typeof document === 'undefined') return;
|
||||
await nextTick();
|
||||
const panel = panelRef.value;
|
||||
if (!panel) return;
|
||||
const target = previouslyFocused
|
||||
&& previouslyFocused.isConnected
|
||||
&& !panel.contains(previouslyFocused)
|
||||
? previouslyFocused
|
||||
: null;
|
||||
if (!target) return;
|
||||
if (!target.matches('input, textarea, select, [contenteditable="true"]')) return;
|
||||
if (!rectsOverlap(panel.getBoundingClientRect(), target.getBoundingClientRect())) return;
|
||||
autoSideAdjustedForOpen = true;
|
||||
const width = geom.value.width;
|
||||
const left = props.floatSide === 'right'
|
||||
? VIEW_MARGIN
|
||||
: Math.max(VIEW_MARGIN, window.innerWidth - width - VIEW_MARGIN);
|
||||
applyGeom({ ...geom.value, left });
|
||||
emit('toggle-side');
|
||||
};
|
||||
|
||||
/**
|
||||
* 标题栏拖动移动浮窗。
|
||||
*/
|
||||
const onDragStart = (event: PointerEvent) => {
|
||||
if (props.docked || resizing.value) return;
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (target?.closest('button, details, summary, a, input')) return;
|
||||
dragging.value = true;
|
||||
dragOrigin = {
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
left: geom.value.left,
|
||||
top: geom.value.top,
|
||||
};
|
||||
window.addEventListener('pointermove', onDragMove);
|
||||
window.addEventListener('pointerup', onDragEnd);
|
||||
};
|
||||
|
||||
const onDragMove = (event: PointerEvent) => {
|
||||
if (!dragging.value || !dragOrigin) return;
|
||||
applyGeom({
|
||||
...geom.value,
|
||||
left: dragOrigin.left + (event.clientX - dragOrigin.x),
|
||||
top: dragOrigin.top + (event.clientY - dragOrigin.y),
|
||||
}, false);
|
||||
};
|
||||
|
||||
const onDragEnd = () => {
|
||||
dragging.value = false;
|
||||
dragOrigin = null;
|
||||
window.removeEventListener('pointermove', onDragMove);
|
||||
window.removeEventListener('pointerup', onDragEnd);
|
||||
applyGeom(geom.value, true);
|
||||
};
|
||||
|
||||
/**
|
||||
* 八向 resize 开始。
|
||||
*/
|
||||
const onResizeStart = (dir: ResizeDir, event: PointerEvent) => {
|
||||
if (props.docked) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
resizing.value = true;
|
||||
resizeOrigin = {
|
||||
dir,
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
left: geom.value.left,
|
||||
top: geom.value.top,
|
||||
width: geom.value.width,
|
||||
height: geom.value.height,
|
||||
};
|
||||
window.addEventListener('pointermove', onResizeMove);
|
||||
window.addEventListener('pointerup', onResizeEnd);
|
||||
};
|
||||
|
||||
const onResizeMove = (event: PointerEvent) => {
|
||||
if (!resizing.value || !resizeOrigin) return;
|
||||
const dx = event.clientX - resizeOrigin.x;
|
||||
const dy = event.clientY - resizeOrigin.y;
|
||||
const next: FloatGeom = {
|
||||
left: resizeOrigin.left,
|
||||
top: resizeOrigin.top,
|
||||
width: resizeOrigin.width,
|
||||
height: resizeOrigin.height,
|
||||
};
|
||||
const dir = resizeOrigin.dir;
|
||||
if (dir.includes('e')) next.width = resizeOrigin.width + dx;
|
||||
if (dir.includes('w')) {
|
||||
next.width = resizeOrigin.width - dx;
|
||||
next.left = resizeOrigin.left + dx;
|
||||
}
|
||||
if (dir.includes('s')) next.height = resizeOrigin.height + dy;
|
||||
if (dir.includes('n')) {
|
||||
next.height = resizeOrigin.height - dy;
|
||||
next.top = resizeOrigin.top + dy;
|
||||
}
|
||||
// 宽度触底时锁住 left,避免西向拖拽抖动。
|
||||
if (dir.includes('w') && next.width <= MIN_WIDTH) {
|
||||
next.width = MIN_WIDTH;
|
||||
next.left = resizeOrigin.left + (resizeOrigin.width - MIN_WIDTH);
|
||||
}
|
||||
if (dir.includes('n') && next.height <= MIN_HEIGHT) {
|
||||
next.height = MIN_HEIGHT;
|
||||
next.top = resizeOrigin.top + (resizeOrigin.height - MIN_HEIGHT);
|
||||
}
|
||||
applyGeom(next, false);
|
||||
};
|
||||
|
||||
const onResizeEnd = () => {
|
||||
resizing.value = false;
|
||||
resizeOrigin = null;
|
||||
window.removeEventListener('pointermove', onResizeMove);
|
||||
window.removeEventListener('pointerup', onResizeEnd);
|
||||
applyGeom(geom.value, true);
|
||||
};
|
||||
|
||||
/**
|
||||
* 初始化或按展开态重置默认尺寸(保留可恢复的存储几何优先)。
|
||||
*/
|
||||
function ensureFloatGeom(forceDefault = false) {
|
||||
if (forceDefault) {
|
||||
applyGeom(defaultGeom(props.floatSide, props.expanded));
|
||||
return;
|
||||
}
|
||||
const stored = loadStoredGeom();
|
||||
if (stored) {
|
||||
applyGeom(stored, false);
|
||||
return;
|
||||
}
|
||||
applyGeom(defaultGeom(props.floatSide, props.expanded), false);
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.expanded,
|
||||
(expanded, was) => {
|
||||
if (props.docked || was === undefined) return;
|
||||
const max = maxSize();
|
||||
if (expanded) {
|
||||
applyGeom({
|
||||
...geom.value,
|
||||
width: Math.min(720, max.width),
|
||||
height: Math.min(680, max.height),
|
||||
});
|
||||
return;
|
||||
}
|
||||
applyGeom({
|
||||
...geom.value,
|
||||
width: Math.min(440, max.width),
|
||||
height: Math.min(520, max.height),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
watch(
|
||||
() => props.floatSide,
|
||||
(side, prev) => {
|
||||
if (props.docked || prev === undefined || side === prev) return;
|
||||
const width = geom.value.width;
|
||||
const left = side === 'left'
|
||||
? VIEW_MARGIN
|
||||
: Math.max(VIEW_MARGIN, (typeof window !== 'undefined' ? window.innerWidth : 1200) - width - VIEW_MARGIN);
|
||||
applyGeom({ ...geom.value, left });
|
||||
},
|
||||
);
|
||||
|
||||
watch(
|
||||
() => [props.open, props.docked] as const,
|
||||
([open, docked], previous) => {
|
||||
if (typeof document === 'undefined') return;
|
||||
const wasOpen = Boolean(previous?.[0]);
|
||||
const floatingOpen = Boolean(open && !docked);
|
||||
if (floatingOpen && !wasOpen) {
|
||||
autoSideAdjustedForOpen = false;
|
||||
moreOpen.value = false;
|
||||
ensureFloatGeom(false);
|
||||
previouslyFocused = document.activeElement instanceof HTMLElement
|
||||
? document.activeElement
|
||||
: null;
|
||||
document.addEventListener('keydown', onKeydown, true);
|
||||
void nextTick(() => {
|
||||
try {
|
||||
(closeButtonRef.value || focusableNodes()[0])?.focus?.();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
void maybeAvoidFocusedField();
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (floatingOpen && wasOpen) {
|
||||
void maybeAvoidFocusedField();
|
||||
return;
|
||||
}
|
||||
if ((!open || docked) && wasOpen) {
|
||||
document.removeEventListener('keydown', onKeydown, true);
|
||||
const restoreTarget = previouslyFocused;
|
||||
previouslyFocused = null;
|
||||
autoSideAdjustedForOpen = false;
|
||||
moreOpen.value = false;
|
||||
if (!open) {
|
||||
void nextTick(() => {
|
||||
try {
|
||||
restoreTarget?.focus?.();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('pointermove', onDragMove);
|
||||
window.removeEventListener('pointerup', onDragEnd);
|
||||
window.removeEventListener('pointermove', onResizeMove);
|
||||
window.removeEventListener('pointerup', onResizeEnd);
|
||||
if (typeof document !== 'undefined') {
|
||||
document.removeEventListener('keydown', onKeydown, true);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside
|
||||
v-if="open"
|
||||
ref="panelRef"
|
||||
:class="panelClass"
|
||||
:style="panelStyle"
|
||||
:role="docked ? 'complementary' : 'dialog'"
|
||||
:aria-modal="docked ? undefined : 'true'"
|
||||
aria-labelledby="review-evidence-drawer-title"
|
||||
tabindex="-1"
|
||||
data-testid="review-document-evidence-drawer"
|
||||
:data-pinned="pinned ? 'true' : 'false'"
|
||||
:data-expanded="expanded ? 'true' : 'false'"
|
||||
:data-docked="docked ? 'true' : 'false'"
|
||||
:data-float-side="floatSide"
|
||||
:data-presentation="docked ? 'docked' : 'floating'"
|
||||
:data-width="Math.round(geom.width)"
|
||||
:data-height="Math.round(geom.height)"
|
||||
>
|
||||
<div
|
||||
class="flex shrink-0 flex-col gap-1.5 border-b border-default px-3 py-2"
|
||||
:class="docked ? '' : 'cursor-grab active:cursor-grabbing select-none'"
|
||||
data-testid="review-evidence-drag-handle"
|
||||
@pointerdown="onDragStart"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<div class="min-w-0">
|
||||
<div
|
||||
id="review-evidence-drawer-title"
|
||||
class="text-xs font-semibold text-secondary"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.evidenceDrawer.title') }}
|
||||
</div>
|
||||
<p class="truncate text-[11px] text-muted">{{ pageLabel }}</p>
|
||||
</div>
|
||||
<button
|
||||
ref="closeButtonRef"
|
||||
type="button"
|
||||
class="rounded border border-default px-2 py-1 text-xs hover-surface-soft"
|
||||
data-testid="review-evidence-close"
|
||||
@click="emit('close')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workbench.closePdf') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-1.5">
|
||||
<div class="flex items-center gap-1" data-testid="review-evidence-nav-group">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-default px-2 py-1 text-xs hover-surface-soft"
|
||||
data-testid="review-evidence-prev"
|
||||
:disabled="!canPrev"
|
||||
@click="emit('prev-evidence')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.evidenceDrawer.prevEvidence') }}
|
||||
</button>
|
||||
<span class="text-[11px] text-muted" data-testid="review-evidence-ordinal">
|
||||
{{ evidenceOrdinal }}/{{ evidenceList.length || 0 }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-default px-2 py-1 text-xs hover-surface-soft"
|
||||
data-testid="review-evidence-next"
|
||||
:disabled="!canNext"
|
||||
@click="emit('next-evidence')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.evidenceDrawer.nextEvidence') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="ml-auto flex items-center gap-1" data-testid="review-evidence-window-group">
|
||||
<button
|
||||
v-if="!docked"
|
||||
type="button"
|
||||
class="rounded border border-default px-2 py-1 text-xs hover-surface-soft"
|
||||
data-testid="review-evidence-toggle-expand"
|
||||
:title="expanded
|
||||
? t('chat.shippingOrderReview.workbench.collapsePdfHint')
|
||||
: t('chat.shippingOrderReview.workbench.expandPdfHint')"
|
||||
@click="emit('toggle-expand')"
|
||||
>
|
||||
{{ expanded
|
||||
? t('chat.shippingOrderReview.workbench.collapsePdf')
|
||||
: t('chat.shippingOrderReview.workbench.expandPdf') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-default px-2 py-1 text-xs hover-surface-soft"
|
||||
data-testid="review-evidence-toggle-dock"
|
||||
:title="docked
|
||||
? t('chat.shippingOrderReview.workbench.undockPdfHint')
|
||||
: t('chat.shippingOrderReview.workbench.dockPdfHint')"
|
||||
@click="emit('toggle-dock')"
|
||||
>
|
||||
{{ docked
|
||||
? t('chat.shippingOrderReview.workbench.undockPdf')
|
||||
: t('chat.shippingOrderReview.workbench.dockPdf') }}
|
||||
</button>
|
||||
<div class="relative">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-default px-2 py-1 text-xs hover-surface-soft"
|
||||
data-testid="review-evidence-more"
|
||||
:aria-expanded="moreOpen ? 'true' : 'false'"
|
||||
@click="moreOpen = !moreOpen"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workbench.moreActions') }}
|
||||
</button>
|
||||
<div
|
||||
v-if="moreOpen"
|
||||
class="absolute right-0 z-40 mt-1 min-w-[10rem] rounded-md border border-default bg-surface py-1 text-xs shadow-lg"
|
||||
data-testid="review-evidence-more-menu"
|
||||
>
|
||||
<button
|
||||
v-if="!docked"
|
||||
type="button"
|
||||
class="block w-full px-3 py-1.5 text-left hover-surface-soft"
|
||||
data-testid="review-evidence-toggle-side"
|
||||
@click="emit('toggle-side'); moreOpen = false"
|
||||
>
|
||||
{{ floatSide === 'right'
|
||||
? t('chat.shippingOrderReview.workbench.movePdfLeft')
|
||||
: t('chat.shippingOrderReview.workbench.movePdfRight') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="block w-full px-3 py-1.5 text-left hover-surface-soft"
|
||||
data-testid="review-evidence-toggle-pin"
|
||||
@click="emit('toggle-pin'); moreOpen = false"
|
||||
>
|
||||
{{ pinned
|
||||
? t('chat.shippingOrderReview.workbench.unpinPdf')
|
||||
: t('chat.shippingOrderReview.workbench.pinPdf') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="showAiActions"
|
||||
type="button"
|
||||
class="block w-full px-3 py-1.5 text-left hover-surface-soft"
|
||||
data-testid="review-evidence-request-ai"
|
||||
@click="emit('request-ai'); moreOpen = false"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.request') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="showAiActions"
|
||||
type="button"
|
||||
class="block w-full px-3 py-1.5 text-left hover-surface-soft"
|
||||
data-testid="review-evidence-restore-machine"
|
||||
@click="emit('restore-machine'); moreOpen = false"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.restoreMachine') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid min-h-0 flex-1 grid-rows-[minmax(0,1fr)_auto]">
|
||||
<iframe
|
||||
v-if="emailPreview?.render_kind === 'safe_html' && emailPreview.preview_url"
|
||||
:src="emailPreview.preview_url"
|
||||
sandbox=""
|
||||
referrerpolicy="no-referrer"
|
||||
:title="fieldLabel || t('chat.shippingOrderReview.evidenceDrawer.title')"
|
||||
class="min-h-0 h-full w-full border-0 bg-surface"
|
||||
data-testid="review-email-evidence-html"
|
||||
/>
|
||||
<div v-else-if="emailPreview" class="min-h-0 overflow-auto whitespace-pre-wrap p-4 font-mono text-xs leading-6 text-secondary" data-testid="review-email-evidence-preview">
|
||||
{{ emailPreview.text }}
|
||||
</div>
|
||||
<ReviewDocumentPreview
|
||||
v-else-if="src"
|
||||
class="min-h-0"
|
||||
:src="src"
|
||||
:evidence="evidence"
|
||||
:drawer-mode="true"
|
||||
:title="t('chat.shippingOrderReview.previewTitle')"
|
||||
:loading-text="t('chat.shippingOrderReview.previewLoading')"
|
||||
:unavailable-text="t('chat.shippingOrderReview.previewUnavailable')"
|
||||
/>
|
||||
<div
|
||||
v-else
|
||||
class="flex min-h-[140px] items-center justify-center p-4 text-sm text-muted"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.previewUnavailable') }}
|
||||
</div>
|
||||
|
||||
<details
|
||||
class="shrink-0 border-t border-default text-xs"
|
||||
data-testid="review-evidence-details"
|
||||
:open="detailsOpen"
|
||||
@toggle="detailsOpen = ($event.target as HTMLDetailsElement).open"
|
||||
>
|
||||
<summary class="cursor-pointer px-3 py-2 font-medium text-secondary hover-surface-soft dark:hover:bg-slate-800/60">
|
||||
{{ t('chat.shippingOrderReview.evidenceDrawer.detailsToggle') }}
|
||||
<span v-if="fieldLabel" class="ml-1 font-normal text-muted">· {{ fieldLabel }}</span>
|
||||
</summary>
|
||||
<div class="space-y-2 px-3 pb-2">
|
||||
<div v-if="fieldLabel" class="font-medium text-secondary">
|
||||
{{ t('chat.shippingOrderReview.evidenceDrawer.field', { field: fieldLabel }) }}
|
||||
</div>
|
||||
<dl class="grid gap-1 text-secondary">
|
||||
<div class="flex gap-2">
|
||||
<dt class="shrink-0 text-muted">{{ t('chat.shippingOrderReview.evidenceDrawer.currentValue') }}</dt>
|
||||
<dd class="min-w-0 break-words">{{ draftValue || t('chat.shippingOrderReview.emptyValue') }}</dd>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<dt class="shrink-0 text-muted">{{ t('chat.shippingOrderReview.evidenceDrawer.machineValue') }}</dt>
|
||||
<dd class="min-w-0 break-words">{{ machineValue || t('chat.shippingOrderReview.emptyValue') }}</dd>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<dt class="shrink-0 text-muted">{{ t('chat.shippingOrderReview.evidenceDrawer.highlightQuality') }}</dt>
|
||||
<dd data-testid="review-evidence-highlight-quality">{{ highlightQualityLabel }}</dd>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<dt class="shrink-0 text-muted">{{ t('chat.shippingOrderReview.evidenceDrawer.highlightSource') }}</dt>
|
||||
<dd data-testid="review-evidence-highlight-source">{{ highlightSourceLabel }}</dd>
|
||||
</div>
|
||||
<div v-if="valueSourceLabel" class="flex gap-2">
|
||||
<dt class="shrink-0 text-muted">{{ t('chat.shippingOrderReview.evidenceDrawer.source') }}</dt>
|
||||
<dd>{{ valueSourceLabel }}</dd>
|
||||
</div>
|
||||
<div v-if="evidence?.table_id || evidence?.cell_id" class="flex gap-2">
|
||||
<dt class="shrink-0 text-muted">{{ t('chat.shippingOrderReview.evidenceDrawer.layoutPath') }}</dt>
|
||||
<dd class="min-w-0 break-all font-mono text-[11px]">
|
||||
{{ [evidence?.table_id, evidence?.cell_id].filter(Boolean).join(' / ') }}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p
|
||||
v-if="!hasDrawableHighlight"
|
||||
class="rounded bg-amber-50 px-2 py-1 text-[11px] text-amber-900 dark:bg-amber-950/40 dark:text-amber-100"
|
||||
data-testid="review-evidence-no-bbox"
|
||||
>
|
||||
<span v-if="!evidence">
|
||||
{{ t('chat.shippingOrderReview.locateUnavailableHint') }}
|
||||
</span>
|
||||
<span v-else-if="evidence.highlight_quality === 'invalid'">
|
||||
{{ t('chat.shippingOrderReview.evidenceInvalidHighlight') }}
|
||||
</span>
|
||||
<span v-else>
|
||||
{{ t('chat.shippingOrderReview.evidenceNoHighlight') }}
|
||||
</span>
|
||||
<span v-if="coordinateIssueLabels.length" class="mt-1 block">
|
||||
{{ coordinateIssueLabels.join(';') }}
|
||||
</span>
|
||||
<span v-if="evidence?.quote" class="mt-1 block font-mono">{{ evidence.quote }}</span>
|
||||
</p>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<template v-if="!docked">
|
||||
<span
|
||||
v-for="dir in RESIZE_DIRS"
|
||||
:key="dir"
|
||||
class="absolute z-50 touch-none"
|
||||
:data-testid="`review-evidence-resize-${dir}`"
|
||||
:data-resize-dir="dir"
|
||||
:style="{ cursor: resizeCursor[dir], ...resizeHandleStyle(dir) }"
|
||||
@pointerdown="onResizeStart(dir, $event)"
|
||||
/>
|
||||
</template>
|
||||
</aside>
|
||||
</template>
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewDocumentNavigation.spec.ts
|
||||
* 用途:验收 OT 导航数量阈值与模式切换。
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ReviewDocumentNavigation, {
|
||||
type ReviewDocumentNavItem,
|
||||
} from './ReviewDocumentNavigation.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
unnamedDocument: '未命名 PDF',
|
||||
documentNavigation: '导航',
|
||||
caseStatuses: { draft: '草稿', unknown: '未知' },
|
||||
lifecycle: {
|
||||
stages: {
|
||||
order_review: '订单复核',
|
||||
fulfillment_prep: '通知准备',
|
||||
upload_complete: '通知完成',
|
||||
},
|
||||
},
|
||||
otNav: {
|
||||
listTitle: '订单列表 · {count}',
|
||||
searchPlaceholder: '搜索',
|
||||
filterAll: '全部',
|
||||
filterNeedsAction: '待人工',
|
||||
filterProcessing: '处理中',
|
||||
filterDone: '完成',
|
||||
filterFailed: '失败',
|
||||
narrowTrigger: '订单 {current}/{total}',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* 生成 n 个导航项。
|
||||
*/
|
||||
function items(count: number): ReviewDocumentNavItem[] {
|
||||
return Array.from({ length: count }, (_, i) => ({
|
||||
case_no: `C-${i + 1}`,
|
||||
file_name: `f${i + 1}.pdf`,
|
||||
status: 'draft',
|
||||
issue_count: i === 0 ? 1 : 0,
|
||||
}));
|
||||
}
|
||||
|
||||
type NavForceMode = 'hidden' | 'tabs' | 'sidebar' | 'sidebar_search' | 'narrow';
|
||||
|
||||
/**
|
||||
* 挂载导航。
|
||||
*/
|
||||
function mountNav(count: number, forceMode?: NavForceMode) {
|
||||
return mount(ReviewDocumentNavigation, {
|
||||
props: {
|
||||
items: items(count),
|
||||
activeCaseNo: 'C-1',
|
||||
navAriaLabel: 'nav',
|
||||
forceMode: forceMode ?? null,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('ReviewDocumentNavigation', () => {
|
||||
it('hides navigation for a single OT', () => {
|
||||
const wrapper = mountNav(1, 'hidden');
|
||||
expect(wrapper.find('[data-testid="review-document-navigation"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('uses compact top tabs for 2–4 OTs', () => {
|
||||
const wrapper = mountNav(3);
|
||||
expect(wrapper.find('[data-testid="review-doc-nav-tabs"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-doc-nav-list"]').exists()).toBe(false);
|
||||
expect(wrapper.attributes('data-nav-mode')).toBe('tabs');
|
||||
});
|
||||
|
||||
it('uses sidebar list for 5–20 OTs', () => {
|
||||
const wrapper = mountNav(8, 'sidebar');
|
||||
expect(wrapper.find('[data-testid="review-doc-nav-list"]').exists()).toBe(true);
|
||||
expect(wrapper.attributes('data-nav-mode')).toBe('sidebar');
|
||||
expect(wrapper.classes()).toContain('sticky');
|
||||
});
|
||||
|
||||
it('keeps the sidebar collapse rail and the explicitly forced sidebar mode', async () => {
|
||||
const wrapper = mount(ReviewDocumentNavigation, {
|
||||
props: {
|
||||
items: items(8),
|
||||
activeCaseNo: 'C-1',
|
||||
navAriaLabel: 'nav',
|
||||
forceMode: 'sidebar',
|
||||
initiallyCollapsed: true,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 关键断言:收起后仍保留文件身份摘要,不能退化成无法识别的纯编号轨。
|
||||
expect(wrapper.attributes('data-nav-mode')).toBe('sidebar');
|
||||
expect(wrapper.get('[data-testid="review-doc-nav-C-2"]').text()).toContain('f2');
|
||||
await wrapper.get('[data-testid="review-doc-nav-collapse"]').trigger('click');
|
||||
expect(wrapper.get('[data-testid="review-doc-nav-C-2"]').text()).toContain('f2.pdf');
|
||||
expect(wrapper.get('[data-testid="review-doc-nav-list"]').attributes('data-collapsed')).toBe('false');
|
||||
});
|
||||
|
||||
it('keeps the file name as the queue row title while projecting PO, lifecycle stage and status', () => {
|
||||
const rows = items(5);
|
||||
rows[1] = {
|
||||
...rows[1],
|
||||
file_name: 'purchase-order-2.pdf',
|
||||
po_number: 'PO-002',
|
||||
lifecycle_stage: 'fulfillment_prep',
|
||||
status: 'processing',
|
||||
};
|
||||
const wrapper = mount(ReviewDocumentNavigation, {
|
||||
props: {
|
||||
items: rows,
|
||||
activeCaseNo: 'C-1',
|
||||
navAriaLabel: 'nav',
|
||||
forceMode: 'sidebar',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 文件导航先展示可识别的文件名;PO/阶段/状态仍都来自后端队列 DTO。
|
||||
const queueRow = wrapper.get('[data-testid="review-doc-nav-C-2"]');
|
||||
expect(queueRow.find('.font-medium').text()).toBe('purchase-order-2.pdf');
|
||||
expect(queueRow.text()).toContain('PO-002');
|
||||
expect(queueRow.text()).toContain('通知准备');
|
||||
// 关键断言:队列行内容必须是实际 DOM 子节点,不能被原生 template 隐藏成空白框。
|
||||
expect(queueRow.find('template').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('shows search for 20+ OTs', () => {
|
||||
const wrapper = mountNav(25, 'sidebar_search');
|
||||
expect(wrapper.find('[data-testid="review-doc-nav-search"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-doc-nav-filter"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('emits select when a tab is clicked', async () => {
|
||||
const wrapper = mountNav(2, 'tabs');
|
||||
await wrapper.get('[data-testid="review-doc-nav-C-2"]').trigger('click');
|
||||
expect(wrapper.emitted('select')?.[0]).toEqual(['C-2']);
|
||||
});
|
||||
|
||||
it('keeps backend lifecycle stage visible in tabs and narrow queue', async () => {
|
||||
const rows = items(2);
|
||||
rows[1] = { ...rows[1], lifecycle_stage: 'fulfillment_prep', status: 'processing' };
|
||||
const tabs = mount(ReviewDocumentNavigation, {
|
||||
props: { items: rows, activeCaseNo: 'C-1', navAriaLabel: 'nav', forceMode: 'tabs' },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
const narrow = mount(ReviewDocumentNavigation, {
|
||||
props: { items: rows, activeCaseNo: 'C-1', navAriaLabel: 'nav', forceMode: 'narrow' },
|
||||
global: { plugins: [i18n] },
|
||||
attachTo: document.body,
|
||||
});
|
||||
|
||||
// 关键断言:文件队列在任何响应式形态都只投影后端已裁决阶段。
|
||||
expect(tabs.get('[data-testid="review-doc-nav-C-2"]').text()).toContain('通知准备');
|
||||
await narrow.get('[data-testid="review-doc-nav-narrow-trigger"]').trigger('click');
|
||||
// 窄屏抽屉通过 Teleport 挂到 body,断言真实可见容器而非组件根节点。
|
||||
expect(document.body.querySelector('[data-testid="review-doc-nav-C-2"]')?.textContent).toContain('通知准备');
|
||||
narrow.unmount();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,409 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewDocumentNavigation.vue
|
||||
用途:订单处理工作台 OT/PDF 导航(按数量响应式:隐藏 / 紧凑标签 / 左侧列表 / 窄屏抽屉)。
|
||||
依赖:vue-i18n、lucide-vue-next。
|
||||
逻辑:1 份隐藏;桌面端 2–4 紧凑标签、5–20 左侧列表(可收起);20+ 搜索过滤;窄屏「订单 i/n」抽屉。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import {
|
||||
Check,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Circle,
|
||||
Search,
|
||||
TriangleAlert,
|
||||
X,
|
||||
} from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
/** 导航项:一 PDF / 一 OT。 */
|
||||
export type ReviewDocumentNavItem = {
|
||||
case_no: string;
|
||||
file_name?: string | null;
|
||||
status: string;
|
||||
issue_count?: number;
|
||||
po_number?: string | null;
|
||||
customer_name?: string | null;
|
||||
stage_label?: string | null;
|
||||
/** 队列接口下发的生命周期码;仅用于本地化展示,不参与阶段裁决。 */
|
||||
lifecycle_stage?: ReviewLifecycleStageCode | null;
|
||||
};
|
||||
|
||||
type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete';
|
||||
|
||||
export type ReviewDocumentNavMode = 'hidden' | 'tabs' | 'sidebar' | 'sidebar_search' | 'narrow';
|
||||
|
||||
const props = defineProps<{
|
||||
items: ReviewDocumentNavItem[];
|
||||
activeCaseNo?: string | null;
|
||||
/** 导航区域无障碍标签(避免与原生 aria-label 属性在 vue-tsc 中冲突) */
|
||||
navAriaLabel: string;
|
||||
/** 外部强制模式(测试用);默认按数量 + 窄屏自动推导 */
|
||||
forceMode?: ReviewDocumentNavMode | null;
|
||||
/** 侧栏是否默认收起为编号轨 */
|
||||
initiallyCollapsed?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
select: [caseNo: string];
|
||||
'mode-change': [mode: ReviewDocumentNavMode];
|
||||
'collapse-change': [collapsed: boolean];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
const isNarrow = ref(false);
|
||||
const collapsed = ref(Boolean(props.initiallyCollapsed));
|
||||
const drawerOpen = ref(false);
|
||||
const searchQuery = ref('');
|
||||
const statusFilter = ref<'all' | 'needs_action' | 'processing' | 'done' | 'failed'>('all');
|
||||
|
||||
let mediaQuery: MediaQueryList | null = null;
|
||||
|
||||
/**
|
||||
* 同步窄屏断点(lg 以下走抽屉入口)。
|
||||
*/
|
||||
function syncNarrow(event?: MediaQueryListEvent) {
|
||||
isNarrow.value = event ? event.matches : Boolean(mediaQuery?.matches);
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (typeof window === 'undefined' || !window.matchMedia) return;
|
||||
mediaQuery = window.matchMedia('(max-width: 1023px)');
|
||||
syncNarrow();
|
||||
mediaQuery.addEventListener('change', syncNarrow);
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
mediaQuery?.removeEventListener('change', syncNarrow);
|
||||
});
|
||||
|
||||
/**
|
||||
* 推导导航呈现模式。
|
||||
*/
|
||||
const mode = computed<ReviewDocumentNavMode>(() => {
|
||||
if (props.forceMode) return props.forceMode;
|
||||
const count = props.items.length;
|
||||
if (count <= 1) return 'hidden';
|
||||
if (isNarrow.value) return 'narrow';
|
||||
// 多文件先选文件、后查看阶段;2–4 用紧凑标签,5+ 才占用左侧工作列。
|
||||
if (count <= 4) return 'tabs';
|
||||
if (count <= 20) return 'sidebar';
|
||||
return 'sidebar_search';
|
||||
});
|
||||
|
||||
watch(mode, (value) => emit('mode-change', value), { immediate: true });
|
||||
watch(collapsed, (value) => emit('collapse-change', value), { immediate: true });
|
||||
|
||||
const activeIndex = computed(() => {
|
||||
const idx = props.items.findIndex((item) => item.case_no === props.activeCaseNo);
|
||||
return idx >= 0 ? idx + 1 : 1;
|
||||
});
|
||||
|
||||
/**
|
||||
* 将 Case 状态码映射为本地化文案。
|
||||
*/
|
||||
function caseStatusLabel(status: string): string {
|
||||
const key = `chat.shippingOrderReview.caseStatuses.${status}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderReview.caseStatuses.unknown');
|
||||
}
|
||||
|
||||
/** 后端阶段码只做 i18n 投影;缺失时保留空白,禁止按 Case 状态补造阶段。 */
|
||||
function lifecycleStageLabel(item: ReviewDocumentNavItem): string | null {
|
||||
const code = String(item.lifecycle_stage || '').trim() as ReviewLifecycleStageCode;
|
||||
if (!['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'].includes(code)) return null;
|
||||
const key = `chat.shippingOrderReview.lifecycle.stages.${code}`;
|
||||
return te(key) ? t(key) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 导航状态图标语义。
|
||||
*/
|
||||
function navIconKind(item: ReviewDocumentNavItem): 'active' | 'alert' | 'processing' | 'done' | 'failed' | 'idle' {
|
||||
if (props.activeCaseNo === item.case_no) return 'active';
|
||||
const status = String(item.status || '').toLowerCase();
|
||||
if (item.issue_count && item.issue_count > 0) return 'alert';
|
||||
if (status === 'failed' || status === 'error') return 'failed';
|
||||
if (status === 'confirmed' || status === 'completed' || status === 'ready' || status === 'closed') return 'done';
|
||||
if (status === 'processing' || status === 'reparse_pending' || status === 'queued') return 'processing';
|
||||
if (status === 'non_order' || status === 'cancelled' || status === 'superseded') return 'idle';
|
||||
if (status === 'draft' || status === 'pending_review' || status === 'waiting_review') return 'alert';
|
||||
return 'processing';
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否匹配状态分段过滤。
|
||||
*/
|
||||
function matchesStatusFilter(item: ReviewDocumentNavItem): boolean {
|
||||
if (statusFilter.value === 'all') return true;
|
||||
const kind = navIconKind(item);
|
||||
if (statusFilter.value === 'needs_action') return kind === 'alert';
|
||||
if (statusFilter.value === 'processing') return kind === 'processing' || kind === 'active';
|
||||
if (statusFilter.value === 'done') return kind === 'done';
|
||||
if (statusFilter.value === 'failed') return kind === 'failed';
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索 + 过滤后的列表。
|
||||
*/
|
||||
const filteredItems = computed(() => {
|
||||
const q = searchQuery.value.trim().toLowerCase();
|
||||
return props.items.filter((item) => {
|
||||
if (!matchesStatusFilter(item)) return false;
|
||||
if (!q) return true;
|
||||
const hay = [
|
||||
item.file_name,
|
||||
item.case_no,
|
||||
item.po_number,
|
||||
item.customer_name,
|
||||
item.stage_label,
|
||||
].map((v) => String(v || '').toLowerCase()).join(' ');
|
||||
return hay.includes(q);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 选择 OT;窄屏抽屉内选择后关闭。
|
||||
*/
|
||||
function onSelect(caseNo: string) {
|
||||
emit('select', caseNo);
|
||||
drawerOpen.value = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<nav
|
||||
v-if="mode !== 'hidden'"
|
||||
:aria-label="navAriaLabel"
|
||||
data-testid="review-document-navigation"
|
||||
:data-nav-mode="mode"
|
||||
:class="mode === 'tabs'
|
||||
? 'rounded-xl border border-default bg-surface p-2 shadow-sm '
|
||||
: mode === 'narrow'
|
||||
? ''
|
||||
: ['sticky top-3 flex max-h-[calc(100vh-6rem)] w-full shrink-0 flex-col rounded-xl border border-default bg-surface shadow-sm transition-[width] duration-200 ', collapsed ? 'lg:w-20' : 'lg:w-64']"
|
||||
>
|
||||
<!-- 2–4:顶部标签 -->
|
||||
<div
|
||||
v-if="mode === 'tabs'"
|
||||
class="flex gap-1.5 overflow-x-auto"
|
||||
data-testid="review-doc-nav-tabs"
|
||||
>
|
||||
<button
|
||||
v-for="item in items"
|
||||
:key="item.case_no"
|
||||
type="button"
|
||||
class="inline-flex min-w-[9rem] max-w-[240px] shrink-0 flex-col gap-0.5 rounded-lg border px-2.5 py-1.5 text-left text-xs transition-colors"
|
||||
:class="activeCaseNo === item.case_no
|
||||
? 'border-sky-500 bg-sky-50 text-sky-950 ring-1 ring-sky-400 dark:border-sky-700 dark:bg-sky-950/40 dark:text-sky-100'
|
||||
: 'border-default text-secondary hover-surface-soft '"
|
||||
:data-testid="`review-doc-nav-${item.case_no}`"
|
||||
@click="onSelect(item.case_no)"
|
||||
>
|
||||
<span class="flex items-center gap-1 truncate font-medium">
|
||||
<TriangleAlert
|
||||
v-if="navIconKind(item) === 'alert'"
|
||||
class="h-3.5 w-3.5 shrink-0 text-amber-500"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<Check
|
||||
v-else-if="navIconKind(item) === 'done'"
|
||||
class="h-3.5 w-3.5 shrink-0 text-emerald-500"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<X
|
||||
v-else-if="navIconKind(item) === 'failed'"
|
||||
class="h-3.5 w-3.5 shrink-0 text-rose-500"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<Circle
|
||||
v-else
|
||||
class="h-3 w-3 shrink-0 text-muted"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span class="truncate">{{ item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</span>
|
||||
</span>
|
||||
<span class="truncate text-[10px] text-muted">
|
||||
{{ [
|
||||
item.po_number,
|
||||
lifecycleStageLabel(item),
|
||||
item.stage_label,
|
||||
item.customer_name || caseStatusLabel(item.status),
|
||||
].filter(Boolean).join(' · ') }}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- ≥5:左侧列表 -->
|
||||
<template v-else-if="mode === 'sidebar' || mode === 'sidebar_search'">
|
||||
<div class="flex items-center justify-between gap-2 border-b border-subtle px-2 py-2">
|
||||
<span class="text-xs font-semibold text-primary">
|
||||
{{ t('chat.shippingOrderReview.otNav.listTitle', { count: items.length }) }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded p-1 text-muted hover-surface-strong"
|
||||
data-testid="review-doc-nav-collapse"
|
||||
:aria-label="collapsed ? t('chat.shippingOrderReview.documentNavigation') : t('chat.shippingOrderReview.documentNavigation')"
|
||||
@click="collapsed = !collapsed"
|
||||
>
|
||||
<ChevronLeft
|
||||
v-if="!collapsed"
|
||||
class="h-4 w-4"
|
||||
/>
|
||||
<ChevronRight
|
||||
v-else
|
||||
class="h-4 w-4"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="!collapsed && mode === 'sidebar_search'"
|
||||
class="space-y-2 border-b border-subtle px-2 py-2"
|
||||
>
|
||||
<label class="relative block">
|
||||
<Search class="pointer-events-none absolute left-2 top-1.5 h-3.5 w-3.5 text-muted" />
|
||||
<input
|
||||
v-model="searchQuery"
|
||||
type="search"
|
||||
class="w-full rounded-md border border-default bg-surface py-1 pl-7 pr-2 text-[11px]"
|
||||
:placeholder="t('chat.shippingOrderReview.otNav.searchPlaceholder')"
|
||||
data-testid="review-doc-nav-search"
|
||||
>
|
||||
</label>
|
||||
<select
|
||||
v-model="statusFilter"
|
||||
class="w-full rounded-md border border-default bg-surface px-2 py-1 text-[11px]"
|
||||
data-testid="review-doc-nav-filter"
|
||||
>
|
||||
<option value="all">{{ t('chat.shippingOrderReview.otNav.filterAll') }}</option>
|
||||
<option value="needs_action">{{ t('chat.shippingOrderReview.otNav.filterNeedsAction') }}</option>
|
||||
<option value="processing">{{ t('chat.shippingOrderReview.otNav.filterProcessing') }}</option>
|
||||
<option value="done">{{ t('chat.shippingOrderReview.otNav.filterDone') }}</option>
|
||||
<option value="failed">{{ t('chat.shippingOrderReview.otNav.filterFailed') }}</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="min-h-0 flex-1 overflow-y-auto p-1.5"
|
||||
data-testid="review-doc-nav-list"
|
||||
:data-collapsed="collapsed"
|
||||
>
|
||||
<button
|
||||
v-for="(item, index) in (collapsed ? items : filteredItems)"
|
||||
:key="item.case_no"
|
||||
type="button"
|
||||
class="mb-1 flex w-full items-start gap-2 rounded-lg border px-2 py-1.5 text-left text-xs transition-colors"
|
||||
:class="activeCaseNo === item.case_no
|
||||
? 'border-sky-500 bg-sky-50 dark:border-sky-700 dark:bg-sky-950/40'
|
||||
: 'border-transparent hover-surface-soft '"
|
||||
:title="collapsed
|
||||
? `${item.file_name || item.case_no} · ${caseStatusLabel(item.status)}`
|
||||
: undefined"
|
||||
:data-testid="`review-doc-nav-${item.case_no}`"
|
||||
@click="onSelect(item.case_no)"
|
||||
>
|
||||
<span
|
||||
v-if="collapsed"
|
||||
class="flex h-12 w-full min-w-0 flex-col items-center justify-center rounded-md bg-surface-strong px-1 text-[10px]"
|
||||
:title="`${index + 1}. ${item.file_name || item.case_no}`"
|
||||
>
|
||||
<span class="font-semibold">{{ index + 1 }}</span>
|
||||
<span class="mt-0.5 w-full truncate text-center text-[9px] font-medium text-secondary">
|
||||
{{ (item.file_name || item.case_no).replace(/\.[^.]+$/, '').slice(0, 7) }}
|
||||
</span>
|
||||
</span>
|
||||
<template v-else>
|
||||
<TriangleAlert
|
||||
v-if="navIconKind(item) === 'alert'"
|
||||
class="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-500"
|
||||
/>
|
||||
<Check
|
||||
v-else-if="navIconKind(item) === 'done'"
|
||||
class="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500"
|
||||
/>
|
||||
<X
|
||||
v-else-if="navIconKind(item) === 'failed'"
|
||||
class="mt-0.5 h-3.5 w-3.5 shrink-0 text-rose-500"
|
||||
/>
|
||||
<Circle
|
||||
v-else
|
||||
class="mt-0.5 h-3 w-3 shrink-0 text-muted"
|
||||
/>
|
||||
<span class="min-w-0 flex-1">
|
||||
<span class="block truncate font-medium text-primary">
|
||||
{{ item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}
|
||||
</span>
|
||||
<span class="block truncate text-[10px] text-muted">
|
||||
{{ [
|
||||
item.po_number,
|
||||
lifecycleStageLabel(item),
|
||||
item.customer_name || caseStatusLabel(item.status),
|
||||
].filter(Boolean).join(' · ') }}
|
||||
</span>
|
||||
</span>
|
||||
</template>
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 窄屏:入口 + 抽屉 -->
|
||||
<template v-else-if="mode === 'narrow'">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-2 rounded-xl border border-default bg-surface px-3 py-2 text-xs font-medium shadow-sm"
|
||||
data-testid="review-doc-nav-narrow-trigger"
|
||||
@click="drawerOpen = true"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.otNav.narrowTrigger', { current: activeIndex, total: items.length }) }}
|
||||
</button>
|
||||
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="drawerOpen"
|
||||
class="fixed inset-0 z-50 flex justify-end"
|
||||
data-testid="review-doc-nav-narrow-drawer"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="absolute inset-0 bg-slate-900/40"
|
||||
@click="drawerOpen = false"
|
||||
/>
|
||||
<aside class="relative z-10 flex h-full w-full max-w-sm flex-col border-l border-default bg-surface p-3 shadow-xl">
|
||||
<div class="mb-3 flex items-center justify-between">
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.otNav.listTitle', { count: items.length }) }}</h2>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded p-1 hover:bg-surface-muted"
|
||||
@click="drawerOpen = false"
|
||||
>
|
||||
<X class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="min-h-0 flex-1 space-y-1 overflow-y-auto">
|
||||
<button
|
||||
v-for="item in items"
|
||||
:key="item.case_no"
|
||||
type="button"
|
||||
class="flex w-full flex-col rounded-lg border px-3 py-2 text-left text-xs"
|
||||
:class="activeCaseNo === item.case_no
|
||||
? 'border-sky-500 bg-sky-50'
|
||||
: 'border-default'"
|
||||
:data-testid="`review-doc-nav-${item.case_no}`"
|
||||
@click="onSelect(item.case_no)"
|
||||
>
|
||||
<span class="font-medium">{{ item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</span>
|
||||
<span class="text-[10px] text-muted">
|
||||
{{ [lifecycleStageLabel(item), caseStatusLabel(item.status)].filter(Boolean).join(' · ') }}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
</nav>
|
||||
</template>
|
||||
@@ -0,0 +1,486 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewDocumentPreview.vue
|
||||
用途:渲染受控 PDF Blob,并按 highlight_quality 绘制证据高亮(阶段 4+评审修复)。
|
||||
依赖:pdfjs-dist(渲染时动态加载)、pdfHighlightCoords、Review Evidence DTO。
|
||||
逻辑:预览失败独立显示,不影响同页草稿编辑;仅 verified/candidate 绘制;
|
||||
verified=黄实线,candidate=橙虚线并显示画布内候选提示;unavailable/invalid 不画框;
|
||||
Ctrl/Cmd+滚轮缩放;适合宽度/页面/100%;溢出时可拖拽平移;高亮自动滚入视口。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderReviewEvidence } from '../../types/shipping.api.types';
|
||||
import { normalizedTopLeftBBoxToViewportRect } from './pdfHighlightCoords';
|
||||
|
||||
/** 有合法 bbox 时四种质量都绘制;颜色只提示可信度,不隐藏取值位置。 */
|
||||
const DRAWABLE_QUALITIES = new Set(['verified', 'candidate', 'unavailable', 'invalid']);
|
||||
|
||||
type PdfJsModule = typeof import('pdfjs-dist');
|
||||
|
||||
let pdfjsLoader: Promise<PdfJsModule> | null = null;
|
||||
|
||||
/**
|
||||
* 动态加载 pdfjs 与 worker;同页复用单例 Promise。
|
||||
*/
|
||||
async function loadPdfJs(): Promise<PdfJsModule> {
|
||||
if (!pdfjsLoader) {
|
||||
pdfjsLoader = (async () => {
|
||||
const [pdfjs, workerMod] = await Promise.all([
|
||||
import('pdfjs-dist'),
|
||||
import('pdfjs-dist/build/pdf.worker.min.mjs?url'),
|
||||
]);
|
||||
pdfjs.GlobalWorkerOptions.workerSrc = workerMod.default;
|
||||
return pdfjs;
|
||||
})();
|
||||
}
|
||||
return pdfjsLoader;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
src: string;
|
||||
evidence?: ShippingOrderReviewEvidence | null;
|
||||
title: string;
|
||||
loadingText: string;
|
||||
unavailableText: string;
|
||||
/** 证据抽屉内使用更紧凑高度与页码指示。 */
|
||||
drawerMode?: boolean;
|
||||
}>(), {
|
||||
drawerMode: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
'page-change': [pageNo: number];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const canvas = ref<HTMLCanvasElement | null>(null);
|
||||
const scrollHost = ref<HTMLElement | null>(null);
|
||||
const loading = ref(false);
|
||||
const failed = ref(false);
|
||||
const scale = ref(1.25);
|
||||
const pageCount = ref(0);
|
||||
const currentPage = ref(1);
|
||||
/** 用户手动翻页时覆盖证据页码;证据身份变化时清除。 */
|
||||
const manualPageOverride = ref<number | null>(null);
|
||||
const pageJumpInput = ref('');
|
||||
const zoomLabel = computed(() => `${Math.round(scale.value * 100)}%`);
|
||||
/** 最近一次渲染的未缩放页宽高,供适合宽度/页面计算。 */
|
||||
const basePageSize = ref<{ width: number; height: number } | null>(null);
|
||||
|
||||
const highlightQuality = computed(() => String(props.evidence?.highlight_quality || ''));
|
||||
const showCandidateBanner = computed(() => highlightQuality.value === 'candidate');
|
||||
const showVerifiedLegend = computed(() => highlightQuality.value === 'verified');
|
||||
const panning = ref(false);
|
||||
const canPan = ref(false);
|
||||
let panOrigin: { x: number; y: number; left: number; top: number } | null = null;
|
||||
|
||||
/**
|
||||
* 根据滚动容器是否出现溢出刷新可拖拽平移状态。
|
||||
*/
|
||||
const refreshCanPan = () => {
|
||||
const host = scrollHost.value;
|
||||
if (!host || loading.value || failed.value) {
|
||||
canPan.value = false;
|
||||
return;
|
||||
}
|
||||
canPan.value = host.scrollWidth > host.clientWidth + 2
|
||||
|| host.scrollHeight > host.clientHeight + 2;
|
||||
};
|
||||
|
||||
/**
|
||||
* 将高亮矩形滚入滚动容器中心(带边距)。
|
||||
*/
|
||||
const scrollHighlightIntoView = (rect: { x: number; y: number; width: number; height: number }) => {
|
||||
const host = scrollHost.value;
|
||||
if (!host) return;
|
||||
const pad = 24;
|
||||
const targetLeft = Math.max(0, rect.x + rect.width / 2 - host.clientWidth / 2);
|
||||
const targetTop = Math.max(0, rect.y + rect.height / 2 - host.clientHeight / 2 + pad);
|
||||
host.scrollTo({ left: targetLeft, top: targetTop, behavior: 'smooth' });
|
||||
};
|
||||
|
||||
/**
|
||||
* 将当前页渲染到 canvas;高亮以 PDF viewport 矩阵为基准,绝不猜测不可靠坐标。
|
||||
*/
|
||||
const render = async () => {
|
||||
if (!props.src) return;
|
||||
loading.value = true;
|
||||
failed.value = false;
|
||||
try {
|
||||
const pdfjs = await loadPdfJs();
|
||||
const document = await pdfjs.getDocument(props.src).promise;
|
||||
pageCount.value = document.numPages;
|
||||
const evidencePage = props.evidence?.page_no;
|
||||
const preferred = manualPageOverride.value ?? evidencePage ?? currentPage.value ?? 1;
|
||||
const targetPage = Math.min(Math.max(preferred, 1), document.numPages);
|
||||
currentPage.value = targetPage;
|
||||
const page = await document.getPage(targetPage);
|
||||
const baseViewport = page.getViewport({ scale: 1 });
|
||||
basePageSize.value = { width: baseViewport.width, height: baseViewport.height };
|
||||
const viewport = page.getViewport({ scale: scale.value });
|
||||
await nextTick();
|
||||
if (!canvas.value) return;
|
||||
canvas.value.width = Math.ceil(viewport.width);
|
||||
canvas.value.height = Math.ceil(viewport.height);
|
||||
const context = canvas.value.getContext('2d');
|
||||
if (!context) return;
|
||||
await page.render({ canvas: canvas.value, canvasContext: context, viewport }).promise;
|
||||
const highlightRect = drawEvidenceHighlight(context, page, viewport, props.evidence);
|
||||
emit('page-change', targetPage);
|
||||
await nextTick();
|
||||
refreshCanPan();
|
||||
if (highlightRect) scrollHighlightIntoView(highlightRect);
|
||||
} catch {
|
||||
failed.value = true;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
await nextTick();
|
||||
refreshCanPan();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 按后端确认的 highlight_quality 绘制 bbox;非法/缺失质量不绘制。
|
||||
* @param context - canvas 2d 上下文
|
||||
* @param page - PDF.js page(含 view / rotate)
|
||||
* @param viewport - 当前缩放与旋转后的 viewport
|
||||
* @param evidence - 当前证据 DTO
|
||||
*/
|
||||
function drawEvidenceHighlight(
|
||||
context: CanvasRenderingContext2D,
|
||||
page: { view: number[]; rotate?: number },
|
||||
viewport: { width: number; height: number; convertToViewportRectangle: (rect: number[]) => number[] },
|
||||
evidence: ShippingOrderReviewEvidence | null | undefined,
|
||||
): { x: number; y: number; width: number; height: number } | null {
|
||||
const quality = String(evidence?.highlight_quality || '');
|
||||
const bbox = evidence?.highlight_bbox || evidence?.bbox;
|
||||
if (!bbox || !DRAWABLE_QUALITIES.has(quality)) return null;
|
||||
const rect = normalizedTopLeftBBoxToViewportRect(bbox, page, viewport);
|
||||
if (!rect) return null;
|
||||
context.save();
|
||||
if (quality === 'candidate') {
|
||||
context.fillStyle = 'rgba(249, 115, 22, 0.22)';
|
||||
context.strokeStyle = 'rgba(194, 65, 12, 0.95)';
|
||||
context.setLineDash([6, 4]);
|
||||
} else if (quality === 'verified') {
|
||||
context.fillStyle = 'rgba(250, 204, 21, 0.35)';
|
||||
context.strokeStyle = 'rgba(202, 138, 4, 0.95)';
|
||||
context.setLineDash([]);
|
||||
} else {
|
||||
// unavailable / invalid 证据高亮统一使用品牌色(对齐编辑画布匹配锚点的 sky/brand 蓝),
|
||||
// 避免在纯文档预览上出现刺眼的红色,导致「模板预览图标颜色不一致」的观感。
|
||||
// 说明:质量仅影响可信度提示,不改变「该处确有取值位置」的语义,故不再用警示红。
|
||||
context.fillStyle = 'rgba(14, 165, 233, 0.22)';
|
||||
context.strokeStyle = 'rgba(2, 132, 199, 0.95)';
|
||||
context.setLineDash([3, 3]);
|
||||
}
|
||||
context.lineWidth = 2;
|
||||
context.fillRect(rect.x, rect.y, rect.width, rect.height);
|
||||
context.strokeRect(rect.x, rect.y, rect.width, rect.height);
|
||||
context.restore();
|
||||
return rect;
|
||||
}
|
||||
|
||||
/**
|
||||
* 内容溢出时按下拖拽平移滚动位置。
|
||||
*/
|
||||
const onPanStart = (event: PointerEvent) => {
|
||||
if (event.button !== 0 || loading.value || failed.value) return;
|
||||
const host = scrollHost.value;
|
||||
if (!host) return;
|
||||
refreshCanPan();
|
||||
if (!canPan.value) return;
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (!target?.closest('canvas')) return;
|
||||
panning.value = true;
|
||||
panOrigin = {
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
left: host.scrollLeft,
|
||||
top: host.scrollTop,
|
||||
};
|
||||
host.setPointerCapture?.(event.pointerId);
|
||||
window.addEventListener('pointermove', onPanMove);
|
||||
window.addEventListener('pointerup', onPanEnd);
|
||||
};
|
||||
|
||||
const onPanMove = (event: PointerEvent) => {
|
||||
if (!panning.value || !panOrigin) return;
|
||||
const host = scrollHost.value;
|
||||
if (!host) return;
|
||||
host.scrollLeft = panOrigin.left - (event.clientX - panOrigin.x);
|
||||
host.scrollTop = panOrigin.top - (event.clientY - panOrigin.y);
|
||||
};
|
||||
|
||||
const onPanEnd = (event?: PointerEvent) => {
|
||||
const host = scrollHost.value;
|
||||
if (host && event?.pointerId != null) {
|
||||
try {
|
||||
host.releasePointerCapture?.(event.pointerId);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
panning.value = false;
|
||||
panOrigin = null;
|
||||
window.removeEventListener('pointermove', onPanMove);
|
||||
window.removeEventListener('pointerup', onPanEnd);
|
||||
};
|
||||
|
||||
/** 放大预览。 */
|
||||
const zoomIn = () => { scale.value = Math.min(scale.value + 0.25, 3); };
|
||||
/** 缩小预览。 */
|
||||
const zoomOut = () => { scale.value = Math.max(scale.value - 0.25, 0.5); };
|
||||
/** 重置为 100%。 */
|
||||
const zoomActual = () => { scale.value = 1; };
|
||||
|
||||
/**
|
||||
* 按滚动容器宽度适配(留边距)。
|
||||
*/
|
||||
const fitWidth = () => {
|
||||
const host = scrollHost.value;
|
||||
const base = basePageSize.value;
|
||||
if (!host || !base?.width) {
|
||||
scale.value = 1.25;
|
||||
return;
|
||||
}
|
||||
const available = Math.max(120, host.clientWidth - 32);
|
||||
scale.value = Math.min(3, Math.max(0.5, available / base.width));
|
||||
};
|
||||
|
||||
/**
|
||||
* 按滚动容器宽高适配整页。
|
||||
*/
|
||||
const fitPage = () => {
|
||||
const host = scrollHost.value;
|
||||
const base = basePageSize.value;
|
||||
if (!host || !base?.width || !base.height) {
|
||||
scale.value = 1;
|
||||
return;
|
||||
}
|
||||
const availW = Math.max(120, host.clientWidth - 32);
|
||||
const availH = Math.max(120, host.clientHeight - 32);
|
||||
scale.value = Math.min(3, Math.max(0.5, Math.min(availW / base.width, availH / base.height)));
|
||||
};
|
||||
|
||||
/**
|
||||
* Ctrl/Cmd+滚轮缩放;Shift+滚轮横向滚动;普通滚轮纵向滚动。
|
||||
* 使用非 passive 监听以便 preventDefault。
|
||||
*/
|
||||
const onPreviewWheel = (event: WheelEvent) => {
|
||||
const host = scrollHost.value;
|
||||
if (!host) return;
|
||||
if (event.ctrlKey || event.metaKey) {
|
||||
event.preventDefault();
|
||||
const delta = event.deltaY > 0 ? -0.1 : 0.1;
|
||||
scale.value = Math.min(3, Math.max(0.5, Number((scale.value + delta).toFixed(2))));
|
||||
return;
|
||||
}
|
||||
if (event.shiftKey && Math.abs(event.deltaY) > Math.abs(event.deltaX)) {
|
||||
event.preventDefault();
|
||||
host.scrollLeft += event.deltaY;
|
||||
}
|
||||
};
|
||||
|
||||
/** 当前已绑定 wheel 的宿主,避免 ref 切换时解绑错节点。 */
|
||||
let wheelHost: HTMLElement | null = null;
|
||||
|
||||
/**
|
||||
* 绑定滚轮(passive:false),保证 Ctrl 缩放可拦截浏览器默认缩放。
|
||||
*/
|
||||
const bindWheel = () => {
|
||||
const host = scrollHost.value;
|
||||
if (!host || wheelHost === host) return;
|
||||
if (wheelHost) {
|
||||
wheelHost.removeEventListener('wheel', onPreviewWheel);
|
||||
wheelHost = null;
|
||||
}
|
||||
host.addEventListener('wheel', onPreviewWheel, { passive: false });
|
||||
wheelHost = host;
|
||||
};
|
||||
|
||||
/** 解除滚轮绑定。 */
|
||||
const unbindWheel = () => {
|
||||
if (!wheelHost) return;
|
||||
wheelHost.removeEventListener('wheel', onPreviewWheel);
|
||||
wheelHost = null;
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
void nextTick(() => bindWheel());
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
unbindWheel();
|
||||
onPanEnd();
|
||||
});
|
||||
|
||||
watch(scrollHost, () => {
|
||||
void nextTick(() => bindWheel());
|
||||
});
|
||||
|
||||
/**
|
||||
* 跳转到输入页码。
|
||||
*/
|
||||
const jumpToPage = () => {
|
||||
const page = Number.parseInt(String(pageJumpInput.value || ''), 10);
|
||||
if (!Number.isFinite(page) || page < 1 || page > pageCount.value) return;
|
||||
manualPageOverride.value = page;
|
||||
pageJumpInput.value = '';
|
||||
void render();
|
||||
};
|
||||
|
||||
/**
|
||||
* 手动翻到上一页。
|
||||
*/
|
||||
const prevPage = () => {
|
||||
if (currentPage.value <= 1) return;
|
||||
manualPageOverride.value = currentPage.value - 1;
|
||||
void render();
|
||||
};
|
||||
|
||||
/**
|
||||
* 手动翻到下一页。
|
||||
*/
|
||||
const nextPage = () => {
|
||||
if (currentPage.value >= pageCount.value) return;
|
||||
manualPageOverride.value = currentPage.value + 1;
|
||||
void render();
|
||||
};
|
||||
|
||||
watch(
|
||||
() => [props.src, props.evidence?.evidence_id] as const,
|
||||
() => {
|
||||
manualPageOverride.value = null;
|
||||
},
|
||||
);
|
||||
|
||||
watch(
|
||||
() => [
|
||||
props.src,
|
||||
props.evidence?.evidence_id,
|
||||
props.evidence?.page_no,
|
||||
props.evidence?.highlight_quality,
|
||||
props.evidence?.highlight_bbox,
|
||||
scale.value,
|
||||
manualPageOverride.value,
|
||||
] as const,
|
||||
() => { void render(); },
|
||||
{ immediate: true },
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="relative flex flex-1 flex-col overflow-hidden bg-surface-strong"
|
||||
:class="drawerMode ? 'min-h-[200px]' : 'min-h-[180px] xl:min-h-[360px]'"
|
||||
:data-drawer-mode="drawerMode ? 'true' : 'false'"
|
||||
>
|
||||
<div class="flex shrink-0 items-center justify-between gap-1 border-b border-default bg-white/95 px-2 py-1.5 text-xs dark:bg-slate-900/95">
|
||||
<div class="flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border px-2 py-1 hover-surface-soft disabled:opacity-40"
|
||||
data-testid="review-pdf-prev-page"
|
||||
:disabled="currentPage <= 1"
|
||||
@click="prevPage"
|
||||
>‹</button>
|
||||
<span class="min-w-16 text-center text-secondary" data-testid="review-pdf-page-label">
|
||||
{{ currentPage }} / {{ pageCount || '—' }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border px-2 py-1 hover-surface-soft disabled:opacity-40"
|
||||
data-testid="review-pdf-next-page"
|
||||
:disabled="!pageCount || currentPage >= pageCount"
|
||||
@click="nextPage"
|
||||
>›</button>
|
||||
<form class="ml-1 flex items-center gap-1" @submit.prevent="jumpToPage">
|
||||
<input
|
||||
v-model="pageJumpInput"
|
||||
type="number"
|
||||
min="1"
|
||||
:max="pageCount || undefined"
|
||||
class="w-12 rounded border border-default px-1 py-0.5 text-center"
|
||||
data-testid="review-pdf-page-jump"
|
||||
:aria-label="t('chat.shippingOrderReview.previewZoom.jumpPage')"
|
||||
>
|
||||
<button
|
||||
type="submit"
|
||||
class="rounded border px-1.5 py-0.5 hover-surface-soft"
|
||||
data-testid="review-pdf-page-jump-go"
|
||||
>{{ t('chat.shippingOrderReview.previewZoom.go') }}</button>
|
||||
</form>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border px-1.5 py-1 hover-surface-soft"
|
||||
data-testid="review-pdf-zoom-fit-width"
|
||||
:title="t('chat.shippingOrderReview.previewZoom.fitWidth')"
|
||||
@click="fitWidth"
|
||||
>{{ t('chat.shippingOrderReview.previewZoom.fitWidthShort') }}</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border px-1.5 py-1 hover-surface-soft"
|
||||
data-testid="review-pdf-zoom-fit-page"
|
||||
:title="t('chat.shippingOrderReview.previewZoom.fitPage')"
|
||||
@click="fitPage"
|
||||
>{{ t('chat.shippingOrderReview.previewZoom.fitPageShort') }}</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border px-1.5 py-1 hover-surface-soft"
|
||||
data-testid="review-pdf-zoom-actual"
|
||||
:title="t('chat.shippingOrderReview.previewZoom.actual')"
|
||||
@click="zoomActual"
|
||||
>100%</button>
|
||||
<button type="button" class="rounded border px-2 py-1 hover-surface-soft" data-testid="review-pdf-zoom-out" @click="zoomOut">−</button>
|
||||
<span class="min-w-12 text-center text-secondary" data-testid="review-pdf-zoom-label">{{ zoomLabel }}</span>
|
||||
<button type="button" class="rounded border px-2 py-1 hover-surface-soft" data-testid="review-pdf-zoom-in" @click="zoomIn">+</button>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-if="showCandidateBanner || showVerifiedLegend"
|
||||
class="flex shrink-0 flex-wrap items-center gap-2 border-b border-default bg-white/90 px-2 py-1 text-[11px] dark:bg-slate-900/90"
|
||||
data-testid="review-pdf-highlight-legend"
|
||||
>
|
||||
<span
|
||||
v-if="showVerifiedLegend"
|
||||
class="inline-flex items-center gap-1 text-amber-800 dark:text-amber-100"
|
||||
>
|
||||
<span class="inline-block h-2.5 w-4 border-2 border-amber-500 bg-amber-300/50" />
|
||||
{{ t('chat.shippingOrderReview.highlightLegend.verified') }}
|
||||
</span>
|
||||
<span
|
||||
v-if="showCandidateBanner"
|
||||
class="inline-flex items-center gap-1 font-medium text-orange-800 dark:text-orange-100"
|
||||
data-testid="review-pdf-candidate-tip"
|
||||
>
|
||||
<span class="inline-block h-2.5 w-4 border-2 border-dashed border-orange-600 bg-orange-300/40" />
|
||||
{{ t('chat.shippingOrderReview.highlightLegend.candidate') }}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
ref="scrollHost"
|
||||
class="relative flex min-h-0 flex-1 items-start justify-center overflow-auto p-4"
|
||||
data-testid="review-pdf-scroll-host"
|
||||
:data-can-pan="canPan ? 'true' : 'false'"
|
||||
:data-panning="panning ? 'true' : 'false'"
|
||||
:class="canPan ? (panning ? 'cursor-grabbing' : 'cursor-grab') : ''"
|
||||
@pointerdown="onPanStart"
|
||||
>
|
||||
<!-- Keep the canvas mounted while PDF.js is loading; otherwise nextTick cannot obtain a render target. -->
|
||||
<canvas ref="canvas" :aria-label="title" class="bg-surface shadow select-none" :class="{ invisible: loading || failed }" />
|
||||
<span v-if="loading" class="absolute text-sm text-muted">{{ loadingText }}</span>
|
||||
<span v-else-if="failed" class="absolute text-sm text-rose-600">{{ unavailableText }}</span>
|
||||
<div
|
||||
v-else-if="showCandidateBanner && !loading && !failed"
|
||||
class="pointer-events-none absolute left-4 top-4 max-w-[min(100%,18rem)] rounded border border-dashed border-orange-600 bg-orange-50/95 px-2 py-1 text-[11px] font-medium text-orange-900 shadow-sm dark:border-orange-500 dark:bg-orange-950/90 dark:text-orange-100"
|
||||
data-testid="review-pdf-candidate-canvas-tip"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.highlightLegend.candidate') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,252 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewDuplicatePanel.vue
|
||||
用途:复核工作台建单前重复订单对比与裁决区。
|
||||
依赖:vue-i18n、shipping.api 重复裁决/刷新、useMessage。
|
||||
逻辑:needs_adjudication 时展示匹配任务与动作;裁决成功后 emit refreshed。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
refreshWorkspaceShippingOrderReviewDuplicate,
|
||||
resolveWorkspaceShippingOrderReviewDuplicate,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { showReviewResumeOutcome } from '@/features/chat/shipping-review/showReviewResumeOutcome';
|
||||
import type {
|
||||
ShippingDuplicateAction,
|
||||
ShippingOrderReviewDuplicate,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
caseNo: string;
|
||||
duplicate: ShippingOrderReviewDuplicate | null | undefined;
|
||||
editable: boolean;
|
||||
canForceCreate: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
refreshed: [];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const msg = useMessage();
|
||||
const busy = ref(false);
|
||||
const forceReason = ref('');
|
||||
const selectedAction = ref<ShippingDuplicateAction | ''>('');
|
||||
|
||||
const visible = computed(() => Boolean(props.duplicate?.needs_adjudication || props.duplicate?.blocking));
|
||||
const allowed = computed(() => new Set(props.duplicate?.allowed_actions || []));
|
||||
const primaryMatch = computed(() => props.duplicate?.matches?.[0] || null);
|
||||
const resolved = computed(() => Boolean(props.duplicate?.resolved));
|
||||
|
||||
/**
|
||||
* 重复状态本地化文案。
|
||||
*/
|
||||
const statusLabel = computed(() => {
|
||||
const status = String(props.duplicate?.status || '').trim();
|
||||
const key = `chat.shippingOrderReview.duplicate.status.${status}`;
|
||||
if (status && te(key)) return t(key);
|
||||
if (props.duplicate?.blocking) return t('chat.shippingNoticeDuplicateNeedsResolution');
|
||||
return t('chat.shippingOrderReview.duplicate.status.none');
|
||||
});
|
||||
|
||||
/**
|
||||
* 提交重复裁决。
|
||||
*/
|
||||
async function resolve(action: ShippingDuplicateAction) {
|
||||
if (!props.editable || !props.caseNo || busy.value) return;
|
||||
if (!allowed.value.has(action)) {
|
||||
msg.warning(t('chat.shippingNoticeDuplicateActionUnavailable'));
|
||||
return;
|
||||
}
|
||||
const target = String(primaryMatch.value?.task_no || '').trim();
|
||||
if (!target) {
|
||||
msg.warning(t('chat.shippingNoticeDuplicateActionUnavailable'));
|
||||
return;
|
||||
}
|
||||
if (action === 'force_create') {
|
||||
if (!props.canForceCreate) {
|
||||
msg.warning(t('chat.shippingNoticeDuplicateForceForbidden'));
|
||||
return;
|
||||
}
|
||||
if (!forceReason.value.trim()) {
|
||||
msg.warning(t('chat.shippingNoticeDuplicateReasonRequired'));
|
||||
return;
|
||||
}
|
||||
}
|
||||
busy.value = true;
|
||||
selectedAction.value = action;
|
||||
try {
|
||||
const result = await resolveWorkspaceShippingOrderReviewDuplicate(props.caseNo, {
|
||||
action,
|
||||
target_task_no: target,
|
||||
reason: action === 'force_create' ? forceReason.value.trim() : undefined,
|
||||
});
|
||||
forceReason.value = '';
|
||||
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.duplicate.resolveSuccess'));
|
||||
emit('refreshed');
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.duplicate.resolveFailed'));
|
||||
msg.warning(message);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
selectedAction.value = '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重新检测重复(清除陈旧决议)。
|
||||
*/
|
||||
async function onRefresh() {
|
||||
if (!props.editable || !props.caseNo || busy.value) return;
|
||||
busy.value = true;
|
||||
try {
|
||||
const result = await refreshWorkspaceShippingOrderReviewDuplicate(props.caseNo);
|
||||
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.duplicate.refreshDone'));
|
||||
emit('refreshed');
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.duplicate.refreshFailed'));
|
||||
msg.warning(message);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 聚焦裁决区并短暂高亮动作按钮(Footer / Resolver 委托)。
|
||||
*/
|
||||
function focusAdjudication() {
|
||||
const root = document.querySelector('[data-testid="review-duplicate-panel"]');
|
||||
root?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
||||
const actions = document.querySelector('[data-testid="review-duplicate-actions"]');
|
||||
if (!(actions instanceof HTMLElement)) return;
|
||||
actions.classList.add('ring-2', 'ring-amber-400');
|
||||
window.setTimeout(() => {
|
||||
actions.classList.remove('ring-2', 'ring-amber-400');
|
||||
}, 1600);
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
focusAdjudication,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="visible"
|
||||
class="rounded-xl border border-amber-200 bg-amber-50/70 p-3 shadow-sm dark:border-amber-900 dark:bg-amber-950/40"
|
||||
data-testid="review-duplicate-panel"
|
||||
>
|
||||
<header class="flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold text-amber-950 dark:text-amber-50">
|
||||
{{ t('chat.shippingOrderReview.duplicate.title') }}
|
||||
</h2>
|
||||
<p class="mt-0.5 text-xs text-amber-900 dark:text-amber-200">
|
||||
{{ t('chat.shippingOrderReview.duplicate.subtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
class="rounded-full px-2.5 py-1 text-xs font-medium"
|
||||
:class="resolved
|
||||
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
|
||||
: 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'"
|
||||
data-testid="review-duplicate-badge"
|
||||
>
|
||||
{{ resolved ? t('chat.shippingOrderReview.duplicate.resolvedBadge') : statusLabel }}
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<div
|
||||
v-if="primaryMatch"
|
||||
class="mt-2 rounded-lg border border-amber-200 bg-white/90 px-2.5 py-2 text-xs text-secondary dark:border-amber-900"
|
||||
data-testid="review-duplicate-match"
|
||||
>
|
||||
<div class="font-medium text-primary">
|
||||
{{ t('chat.shippingNoticeDuplicateMatchTask', { taskNo: primaryMatch.task_no }) }}
|
||||
</div>
|
||||
<div class="mt-0.5 text-muted">
|
||||
{{ t('chat.shippingNoticeDuplicateMatchStatus', { status: primaryMatch.lifecycle || 'active' }) }}
|
||||
</div>
|
||||
<div v-if="primaryMatch.matched_fields?.length" class="mt-0.5 text-muted">
|
||||
{{ t('chat.shippingNoticeDuplicateMatchFields', { fields: primaryMatch.matched_fields.join(', ') }) }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p v-if="duplicate?.resolution?.action" class="mt-2 text-xs text-secondary">
|
||||
{{ t('chat.shippingOrderReview.duplicate.resolutionLabel', { action: duplicate.resolution.action }) }}
|
||||
<span v-if="duplicate.resolution.target_task_no" class="font-mono">
|
||||
→ {{ duplicate.resolution.target_task_no }}
|
||||
</span>
|
||||
</p>
|
||||
|
||||
<div
|
||||
v-if="editable && duplicate?.needs_adjudication"
|
||||
class="mt-3 space-y-2 rounded-lg transition-shadow"
|
||||
data-testid="review-duplicate-actions"
|
||||
>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-if="allowed.has('open_existing')"
|
||||
type="button"
|
||||
class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-secondary hover:bg-surface-soft disabled:opacity-60"
|
||||
data-testid="review-duplicate-open-existing"
|
||||
:disabled="busy"
|
||||
@click="resolve('open_existing')"
|
||||
>
|
||||
{{ t('chat.shippingNoticeDuplicateOpenExisting') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="allowed.has('create_revision')"
|
||||
type="button"
|
||||
class="rounded-xl border border-amber-300 bg-amber-100 px-3 py-1.5 text-sm font-medium text-amber-950 hover:bg-amber-200 disabled:opacity-60 dark:border-amber-800 dark:bg-amber-950 dark:text-amber-100"
|
||||
data-testid="review-duplicate-create-revision"
|
||||
:disabled="busy"
|
||||
@click="resolve('create_revision')"
|
||||
>
|
||||
{{ t('chat.shippingNoticeDuplicateCreateRevision') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="allowed.has('force_create') && canForceCreate" class="space-y-1.5">
|
||||
<input
|
||||
v-model="forceReason"
|
||||
type="text"
|
||||
class="w-full rounded border border-default bg-surface px-2 py-1.5 text-xs"
|
||||
data-testid="review-duplicate-force-reason"
|
||||
:placeholder="t('chat.shippingNoticeDuplicateReasonPlaceholder')"
|
||||
:disabled="busy"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl bg-rose-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-rose-700 disabled:opacity-60"
|
||||
data-testid="review-duplicate-force-create"
|
||||
:disabled="busy || !forceReason.trim()"
|
||||
@click="resolve('force_create')"
|
||||
>
|
||||
{{ selectedAction === 'force_create' && busy
|
||||
? t('chat.shippingOrderReview.duplicate.resolving')
|
||||
: t('chat.shippingNoticeDuplicateForceCreate') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="editable" class="mt-3">
|
||||
<button
|
||||
type="button"
|
||||
class="text-[11px] text-secondary underline-offset-2 hover:underline disabled:opacity-60"
|
||||
data-testid="review-duplicate-refresh"
|
||||
:disabled="busy"
|
||||
@click="onRefresh"
|
||||
>
|
||||
{{ busy ? t('chat.shippingOrderReview.duplicate.refreshing') : t('chat.shippingOrderReview.duplicate.refresh') }}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewFieldCompletenessPanel.vue
|
||||
用途:字段完整性用户态卡片;与模板匹配分离,消费 Case.field_completeness。
|
||||
依赖:vue-i18n。
|
||||
逻辑:仅展示 blocked/ready 与缺失字段;required_field_missing 不进入模板匹配区。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
export interface FieldCompletenessIssue {
|
||||
code?: string;
|
||||
field_id?: string | null;
|
||||
field_code?: string | null;
|
||||
line_index?: number | null;
|
||||
message?: string | null;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
completeness?: {
|
||||
status?: string;
|
||||
issues?: FieldCompletenessIssue[];
|
||||
} | null;
|
||||
fieldLabels?: Record<string, string>;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const status = computed(() => String(props.completeness?.status || '').trim().toLowerCase());
|
||||
const blocked = computed(() => status.value === 'blocked');
|
||||
const issues = computed(() => props.completeness?.issues || []);
|
||||
const visible = computed(() => Boolean(status.value));
|
||||
|
||||
/**
|
||||
* 字段展示名。
|
||||
*/
|
||||
function fieldLabel(issue: FieldCompletenessIssue): string {
|
||||
const code = String(issue.field_code || issue.field_id || '').trim();
|
||||
if (!code) return t('chat.shippingOrderReview.fieldCompleteness.unknownField');
|
||||
return props.fieldLabels?.[code] || code;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="visible"
|
||||
class="rounded-xl border border-default bg-surface p-3 shadow-sm"
|
||||
data-testid="review-field-completeness-panel"
|
||||
:data-status="status"
|
||||
>
|
||||
<header class="flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.fieldCompleteness.title') }}</h2>
|
||||
<p class="mt-0.5 text-xs text-muted">{{ t('chat.shippingOrderReview.fieldCompleteness.subtitle') }}</p>
|
||||
</div>
|
||||
<span
|
||||
class="rounded-full px-2.5 py-1 text-xs font-medium"
|
||||
:class="blocked
|
||||
? 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'
|
||||
: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'"
|
||||
>
|
||||
{{ blocked
|
||||
? t('chat.shippingOrderReview.fieldCompleteness.blocked')
|
||||
: t('chat.shippingOrderReview.fieldCompleteness.ready') }}
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<ul v-if="blocked && issues.length" class="mt-2 space-y-1 text-[11px] text-secondary">
|
||||
<li
|
||||
v-for="(issue, idx) in issues"
|
||||
:key="`${issue.field_id || issue.field_code || idx}`"
|
||||
class="rounded-lg border border-default bg-surface-soft px-2.5 py-1.5"
|
||||
>
|
||||
<span class="font-medium">{{ fieldLabel(issue) }}</span>
|
||||
<span v-if="issue.code" class="ml-2 font-mono text-muted">{{ issue.code }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</template>
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewFieldConflictPanel.spec.ts
|
||||
* 用途:验证过期字段冲突卡在服务端返回 404 后会刷新,而不会保留为可再次提交的错误入口。
|
||||
* 依赖:Vitest、Vue Test Utils、Vue I18n、ReviewFieldConflictPanel。
|
||||
* 逻辑:模拟并发刷新已消耗冲突,组件必须通知父工作台重取 Case 最新投影。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import ReviewFieldConflictPanel from './ReviewFieldConflictPanel.vue';
|
||||
|
||||
const { resolveFieldConflict } = vi.hoisted(() => ({
|
||||
resolveFieldConflict: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
resolveWorkspaceShippingOrderReviewFieldConflict: resolveFieldConflict,
|
||||
}));
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: { shippingOrderReview: {
|
||||
fieldConflict: {
|
||||
title: '字段冲突 {count} 项', subtitle: '请选择值', focusEvidence: '定位证据',
|
||||
evidenceIssueTitle: '证据待确认({count})', evidenceIssueSubtitle: '请核对证据',
|
||||
scope: { header: '订单头', line: '订单明细' },
|
||||
customValue: '手工值', customPlaceholder: '请输入', submitCustom: '确认手工值',
|
||||
resolveReason: '人工裁决', resolveFailed: '提交失败', resolveSuccess: '已处理',
|
||||
fields: { part_number: '料号' }, reasons: { field_conflict: '字段冲突' },
|
||||
evidenceRole: {}, recoveryAction: { reparse_current_pdf: '建议操作:重新识别此 PDF' },
|
||||
optionLabel: '候选 {index}', adoptOption: '采用候选值',
|
||||
},
|
||||
resume: { autoCreated: '已自动建单', waitingManualConfirm: '待人工确认' },
|
||||
} },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe('ReviewFieldConflictPanel', () => {
|
||||
it('separates evidence gaps from value conflicts and does not offer a duplicate value decision', () => {
|
||||
const wrapper = mount(ReviewFieldConflictPanel, {
|
||||
props: {
|
||||
caseNo: 'SORC-1', draftVersion: 1, editable: true,
|
||||
conflicts: [],
|
||||
evidenceIssues: [{
|
||||
conflict_key: '-1:reservation_id', field_code: 'reservation_id', line_index: null, scope: 'header',
|
||||
reason: 'evidence_missing', options: [],
|
||||
}],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.get('[data-testid="review-evidence-issue-panel"]').text()).toContain('订单头 · reservation_id');
|
||||
expect(wrapper.find('[data-testid="review-field-conflict-custom-toggle"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('shows the server-provided recovery action for a historical evidence gap', () => {
|
||||
const wrapper = mount(ReviewFieldConflictPanel, {
|
||||
props: {
|
||||
caseNo: 'SORC-1', draftVersion: 1, editable: true, conflicts: [],
|
||||
evidenceIssues: [{
|
||||
conflict_key: '-1:unit_price', field_code: 'unit_price', reason: 'supplement_conflict_evidence_insufficient',
|
||||
options: [], recovery_action: 'reparse_current_pdf',
|
||||
}],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.get('[data-testid="review-evidence-issue-recovery-action"]').text()).toContain('重新识别此 PDF');
|
||||
});
|
||||
|
||||
it('refreshes the case when confirming a stale manual value returns conflict-not-found', async () => {
|
||||
resolveFieldConflict.mockRejectedValueOnce(new BusinessError({
|
||||
message: 'Field conflict not found',
|
||||
code: 'SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND',
|
||||
status: 404,
|
||||
}));
|
||||
const wrapper = mount(ReviewFieldConflictPanel, {
|
||||
props: {
|
||||
caseNo: 'SORC-1', draftVersion: 1, editable: true,
|
||||
conflicts: [{
|
||||
conflict_key: '-1:part_number', field_code: 'part_number', line_index: -1,
|
||||
reason: 'field_conflict', options: [],
|
||||
}],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
await wrapper.get('[data-testid="review-field-conflict-custom-toggle"]').trigger('click');
|
||||
await wrapper.get('[data-testid="review-field-conflict-custom-input"]').setValue('PN-001');
|
||||
await wrapper.get('[data-testid="review-field-conflict-custom-submit"]').trigger('click');
|
||||
await vi.waitFor(() => expect(wrapper.emitted('refreshed')).toHaveLength(1));
|
||||
|
||||
// 关键断言:404 代表页面投影过期,父工作台会加载最新 Case 并移除这张卡。
|
||||
expect(resolveFieldConflict).toHaveBeenCalledWith('SORC-1', '-1:part_number', expect.objectContaining({
|
||||
resolution: 'custom', custom_value: 'PN-001', expected_draft_version: 1,
|
||||
}));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,343 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewFieldConflictPanel.vue
|
||||
用途:复核工作台建单前字段冲突集中裁决区(采用候选值 / 手工值)。
|
||||
依赖:vue-i18n、shipping.api.resolveWorkspaceShippingOrderReviewFieldConflict、useMessage。
|
||||
逻辑:展示 Case.field_conflicts;选项标注 evidence_role(主 PDF / 辅助 / 正文);
|
||||
裁决成功后 emit refreshed;可 emit focus-conflict 定位证据。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { resolveWorkspaceShippingOrderReviewFieldConflict } from '@/features/chat/api/shipping.api';
|
||||
import { showReviewResumeOutcome } from '@/features/chat/shipping-review/showReviewResumeOutcome';
|
||||
import type { ShippingOrderReviewFieldConflict } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
caseNo: string;
|
||||
draftVersion: number | null | undefined;
|
||||
conflicts: ShippingOrderReviewFieldConflict[] | null | undefined;
|
||||
evidenceIssues?: ShippingOrderReviewFieldConflict[] | null | undefined;
|
||||
editable: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
refreshed: [];
|
||||
'focus-conflict': [payload: { fieldCode: string; lineIndex: number | null; draftLineId: string | null }];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const msg = useMessage();
|
||||
const resolvingKey = ref<string | null>(null);
|
||||
const customOpenKey = ref<string | null>(null);
|
||||
const customValue = ref('');
|
||||
|
||||
const openConflicts = computed(() => props.conflicts || []);
|
||||
const openEvidenceIssues = computed(() => props.evidenceIssues || []);
|
||||
|
||||
/**
|
||||
* 字段编码本地化标签(无文案时回退 field_code)。
|
||||
*/
|
||||
function fieldLabel(fieldCode: string): string {
|
||||
const key = `chat.shippingOrderReview.fieldConflict.fields.${fieldCode}`;
|
||||
return te(key) ? t(key) : fieldCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* 冲突原因本地化。
|
||||
*/
|
||||
function reasonLabel(reason: string): string {
|
||||
const key = `chat.shippingOrderReview.fieldConflict.reasons.${reason}`;
|
||||
return te(key) ? t(key) : reason;
|
||||
}
|
||||
|
||||
/**
|
||||
* 区分订单头与明细字段;同名字段不能被误读成同一份业务值。
|
||||
*/
|
||||
function scopeLabel(scope: string | null | undefined): string {
|
||||
const code = ['header', 'line', 'line_unassigned', 'unscoped'].includes(String(scope || ''))
|
||||
? String(scope)
|
||||
: 'unscoped';
|
||||
const key = `chat.shippingOrderReview.fieldConflict.scope.${code}`;
|
||||
return t(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 证据角色本地化(主 PDF / 辅助 / 邮件正文)。
|
||||
*/
|
||||
function evidenceRoleLabel(role: string | undefined | null): string {
|
||||
const code = String(role || '').trim();
|
||||
if (!code) return '';
|
||||
const key = `chat.shippingOrderReview.fieldConflict.evidenceRole.${code}`;
|
||||
return te(key) ? t(key) : code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 显示服务端指定的恢复动作;页面只解释并复用既有顶部操作,不自行发起重识别。
|
||||
*/
|
||||
function recoveryActionLabel(action: string | undefined | null): string {
|
||||
const code = String(action || '').trim();
|
||||
if (!code) return '';
|
||||
const key = `chat.shippingOrderReview.fieldConflict.recoveryAction.${code}`;
|
||||
return te(key) ? t(key) : code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 定位冲突字段到草稿/证据区。
|
||||
*/
|
||||
function onFocus(conflict: ShippingOrderReviewFieldConflict) {
|
||||
emit('focus-conflict', {
|
||||
fieldCode: conflict.field_code,
|
||||
lineIndex: conflict.line_index ?? null,
|
||||
draftLineId: conflict.draft_line_id ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 聚焦第一个未解决冲突(Footer / Resolver 委托)。
|
||||
*/
|
||||
function focusFirstConflict() {
|
||||
const first = openConflicts.value[0];
|
||||
if (!first) return;
|
||||
onFocus(first);
|
||||
void Promise.resolve().then(() => {
|
||||
document
|
||||
.querySelector(`[data-testid="review-field-conflict-${first.conflict_key}"]`)
|
||||
?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
||||
});
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
focusFirstConflict,
|
||||
});
|
||||
|
||||
/**
|
||||
* 采用某一候选值。
|
||||
*/
|
||||
async function adoptOption(conflict: ShippingOrderReviewFieldConflict, optionIndex: number) {
|
||||
if (!props.editable || !props.caseNo || props.draftVersion == null || resolvingKey.value) return;
|
||||
resolvingKey.value = conflict.conflict_key;
|
||||
try {
|
||||
const result = await resolveWorkspaceShippingOrderReviewFieldConflict(props.caseNo, conflict.conflict_key, {
|
||||
resolution: 'adopt_option',
|
||||
option_index: optionIndex,
|
||||
expected_draft_version: props.draftVersion,
|
||||
reason: t('chat.shippingOrderReview.fieldConflict.resolveReason'),
|
||||
});
|
||||
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
|
||||
emit('refreshed');
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof BusinessError && error.code === 'SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND') {
|
||||
// 冲突已被其他刷新/裁决消耗:以服务端最新 Case 为准,撤掉当前过期卡片。
|
||||
msg.info(resolveLocalizedErrorMessage(error.code, error.message));
|
||||
emit('refreshed');
|
||||
return;
|
||||
}
|
||||
const message = error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fieldConflict.resolveFailed'));
|
||||
msg.warning(message);
|
||||
} finally {
|
||||
resolvingKey.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 展开/收起手工值输入。
|
||||
*/
|
||||
function toggleCustom(conflictKey: string) {
|
||||
if (customOpenKey.value === conflictKey) {
|
||||
customOpenKey.value = null;
|
||||
customValue.value = '';
|
||||
return;
|
||||
}
|
||||
customOpenKey.value = conflictKey;
|
||||
customValue.value = '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交手工值裁决。
|
||||
*/
|
||||
async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
|
||||
const value = customValue.value.trim();
|
||||
if (!value || !props.editable || props.draftVersion == null || resolvingKey.value) return;
|
||||
resolvingKey.value = conflict.conflict_key;
|
||||
try {
|
||||
const result = await resolveWorkspaceShippingOrderReviewFieldConflict(props.caseNo, conflict.conflict_key, {
|
||||
resolution: 'custom',
|
||||
custom_value: value,
|
||||
expected_draft_version: props.draftVersion,
|
||||
reason: t('chat.shippingOrderReview.fieldConflict.resolveReason'),
|
||||
});
|
||||
customOpenKey.value = null;
|
||||
customValue.value = '';
|
||||
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
|
||||
emit('refreshed');
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof BusinessError && error.code === 'SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND') {
|
||||
// 与采用候选值保持同一 stale-data 恢复路径,禁止把已解决冲突留在页面上。
|
||||
msg.info(resolveLocalizedErrorMessage(error.code, error.message));
|
||||
emit('refreshed');
|
||||
return;
|
||||
}
|
||||
const message = error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fieldConflict.resolveFailed'));
|
||||
msg.warning(message);
|
||||
} finally {
|
||||
resolvingKey.value = null;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="openConflicts.length || openEvidenceIssues.length"
|
||||
class="rounded-xl border border-rose-200 bg-rose-50/70 p-3 shadow-sm dark:border-rose-900 dark:bg-rose-950/40"
|
||||
data-testid="review-field-conflict-panel"
|
||||
>
|
||||
<header v-if="openConflicts.length" class="flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold text-rose-950 dark:text-rose-50">
|
||||
{{ t('chat.shippingOrderReview.fieldConflict.title', { count: openConflicts.length }) }}
|
||||
</h2>
|
||||
<p class="mt-0.5 text-xs text-rose-800 dark:text-rose-200">
|
||||
{{ t('chat.shippingOrderReview.fieldConflict.subtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<ul class="mt-3 space-y-2">
|
||||
<li
|
||||
v-for="conflict in openConflicts"
|
||||
:key="conflict.conflict_key"
|
||||
class="rounded-lg border border-rose-200 bg-white/95 px-2.5 py-2 dark:border-rose-900"
|
||||
:data-testid="`review-field-conflict-${conflict.conflict_key}`"
|
||||
>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<div class="text-xs font-medium text-rose-950 dark:text-rose-50">
|
||||
<span v-if="conflict.line_index != null">#{{ conflict.line_index + 1 }} · </span>
|
||||
<span class="font-mono">{{ fieldLabel(conflict.field_code) }}</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="text-[11px] text-primary underline-offset-2 hover:underline"
|
||||
data-testid="review-field-conflict-focus"
|
||||
@click="onFocus(conflict)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.fieldConflict.focusEvidence') }}
|
||||
</button>
|
||||
</div>
|
||||
<p class="mt-1 text-[11px] text-muted">{{ reasonLabel(conflict.reason) }}</p>
|
||||
|
||||
<div class="mt-2 grid gap-1 text-[11px] text-secondary sm:grid-cols-2">
|
||||
<div
|
||||
v-for="(option, idx) in conflict.options"
|
||||
:key="`${conflict.conflict_key}-${idx}`"
|
||||
class="rounded border border-default bg-surface-soft px-2 py-1.5"
|
||||
>
|
||||
<div class="flex flex-wrap items-center gap-1 text-muted">
|
||||
<span>
|
||||
{{ t('chat.shippingOrderReview.fieldConflict.optionLabel', { index: idx + 1 }) }}
|
||||
<span v-if="option.sources?.length" class="ml-1">({{ option.sources.join(', ') }})</span>
|
||||
</span>
|
||||
<span
|
||||
v-if="evidenceRoleLabel(option.evidence_role)"
|
||||
class="rounded px-1 py-0.5 text-[10px] font-medium"
|
||||
:class="option.evidence_role === 'primary_pdf'
|
||||
? 'bg-sky-100 text-sky-800 dark:bg-sky-950 dark:text-sky-200'
|
||||
: 'bg-surface-strong text-secondary '"
|
||||
:data-testid="`review-field-conflict-evidence-role-${idx}`"
|
||||
:data-evidence-role="option.evidence_role"
|
||||
>
|
||||
{{ evidenceRoleLabel(option.evidence_role) }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-0.5 font-mono text-primary">{{ option.display_value || option.value_key || '—' }}</div>
|
||||
<button
|
||||
v-if="editable"
|
||||
type="button"
|
||||
class="mt-1.5 rounded border border-rose-300 bg-rose-100 px-2 py-0.5 text-[11px] font-medium text-rose-900 hover:bg-rose-200 disabled:opacity-50 dark:border-rose-800 dark:bg-rose-950 dark:text-rose-100"
|
||||
:disabled="resolvingKey != null"
|
||||
:data-testid="`review-field-conflict-adopt-${idx}`"
|
||||
@click="adoptOption(conflict, idx)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.fieldConflict.adoptOption') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="editable" class="mt-2">
|
||||
<button
|
||||
type="button"
|
||||
class="text-[11px] text-secondary underline-offset-2 hover:underline"
|
||||
:disabled="resolvingKey != null"
|
||||
data-testid="review-field-conflict-custom-toggle"
|
||||
@click="toggleCustom(conflict.conflict_key)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.fieldConflict.customValue') }}
|
||||
</button>
|
||||
<div v-if="customOpenKey === conflict.conflict_key" class="mt-1.5 flex flex-wrap gap-2">
|
||||
<input
|
||||
v-model="customValue"
|
||||
type="text"
|
||||
class="min-w-[10rem] flex-1 rounded border border-default bg-surface px-2 py-1 text-xs"
|
||||
data-testid="review-field-conflict-custom-input"
|
||||
:placeholder="t('chat.shippingOrderReview.fieldConflict.customPlaceholder')"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded bg-primary px-2.5 py-1 text-xs font-medium text-on-primary disabled:opacity-50"
|
||||
:disabled="!customValue.trim() || resolvingKey != null"
|
||||
data-testid="review-field-conflict-custom-submit"
|
||||
@click="submitCustom(conflict)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.fieldConflict.submitCustom') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div
|
||||
v-if="openEvidenceIssues.length"
|
||||
class="mt-3 rounded-lg border border-amber-200 bg-amber-50/80 p-2.5 dark:border-amber-900 dark:bg-amber-950/30"
|
||||
data-testid="review-evidence-issue-panel"
|
||||
>
|
||||
<h2 class="text-sm font-semibold text-amber-950 dark:text-amber-50">
|
||||
{{ t('chat.shippingOrderReview.fieldConflict.evidenceIssueTitle', { count: openEvidenceIssues.length }) }}
|
||||
</h2>
|
||||
<p class="mt-0.5 text-xs text-amber-800 dark:text-amber-200">
|
||||
{{ t('chat.shippingOrderReview.fieldConflict.evidenceIssueSubtitle') }}
|
||||
</p>
|
||||
<ul class="mt-2 space-y-1.5">
|
||||
<li
|
||||
v-for="issue in openEvidenceIssues"
|
||||
:key="`${issue.conflict_key}-${issue.reason}`"
|
||||
class="flex flex-wrap items-center justify-between gap-2 rounded border border-amber-200 bg-white/95 px-2.5 py-2 text-xs dark:border-amber-900"
|
||||
>
|
||||
<span class="text-amber-950 dark:text-amber-50">
|
||||
<span class="text-muted">{{ scopeLabel(issue.scope) }} · </span>
|
||||
<span class="font-mono">{{ fieldLabel(issue.field_code) }}</span>
|
||||
</span>
|
||||
<span
|
||||
v-if="recoveryActionLabel(issue.recovery_action)"
|
||||
class="text-[11px] text-amber-800 dark:text-amber-200"
|
||||
data-testid="review-evidence-issue-recovery-action"
|
||||
>
|
||||
{{ recoveryActionLabel(issue.recovery_action) }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="text-[11px] text-primary underline-offset-2 hover:underline"
|
||||
data-testid="review-evidence-issue-focus"
|
||||
@click="onFocus(issue)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.fieldConflict.focusEvidence') }}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
<!-- 履约摘要侧栏;完整明细与批量出单统一由主库存表承载。 -->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderReviewLineFulfillment } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{ caseNo: string; draftVersion: number | null | undefined; lineFulfillment: ShippingOrderReviewLineFulfillment | null | undefined; editable: boolean }>();
|
||||
const emit = defineEmits<{ refreshed: []; 'open-close-dialog': [draftLineIds: string[]] }>();
|
||||
const { t } = useI18n();
|
||||
const TERMINAL_STATUSES = new Set(['task_created', 'fulfilled', 'closed_unfulfillable']);
|
||||
const openLines = computed(() => (props.lineFulfillment?.lines || []).filter((line) => !TERMINAL_STATUSES.has(String(line.line_status || ''))));
|
||||
const visible = computed(() => Boolean(props.lineFulfillment?.has_open_lines || props.lineFulfillment?.has_shortage));
|
||||
function onCloseRemaining() { emit('open-close-dialog', openLines.value.map((line) => line.draft_line_id)); }
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section v-if="visible" class="rounded-xl border border-sky-200 bg-sky-50/70 p-3 shadow-sm dark:border-sky-900 dark:bg-sky-950/40" data-testid="review-fulfillment-decision-panel">
|
||||
<header class="flex flex-wrap items-start justify-between gap-2">
|
||||
<div><h2 class="text-sm font-semibold text-sky-950 dark:text-sky-50">{{ t('chat.shippingOrderReview.fulfillmentDecision.title') }}</h2><p class="mt-0.5 text-xs text-sky-900 dark:text-sky-200">{{ t('chat.shippingOrderReview.fulfillmentDecision.railHint') }}</p></div>
|
||||
<span class="rounded-full bg-sky-100 px-2.5 py-1 text-xs font-medium text-sky-900 dark:bg-sky-950 dark:text-sky-100">{{ t('chat.shippingOrderReview.fulfillmentDecision.openCount', { count: lineFulfillment?.open_count ?? openLines.length }) }}</span>
|
||||
</header>
|
||||
<div class="mt-2 grid grid-cols-2 gap-2 text-xs sm:grid-cols-4">
|
||||
<div class="rounded-lg bg-white/70 px-2.5 py-2 dark:bg-slate-900/50">{{ t('chat.shippingOrderReview.fulfillmentDecision.readyCount', { count: lineFulfillment?.ready_count ?? 0 }) }}</div>
|
||||
<div class="rounded-lg bg-white/70 px-2.5 py-2 dark:bg-slate-900/50">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortageCount', { count: lineFulfillment?.manual_pending_count ?? 0 }) }}</div>
|
||||
<div class="rounded-lg bg-white/70 px-2.5 py-2 dark:bg-slate-900/50">{{ t('chat.shippingOrderReview.fulfillmentDecision.autoProgressCount', { count: lineFulfillment?.auto_progress_count ?? 0 }) }}</div>
|
||||
<div class="rounded-lg bg-white/70 px-2.5 py-2 dark:bg-slate-900/50">{{ t('chat.shippingOrderReview.fulfillmentDecision.summaryHint') }}</div>
|
||||
</div>
|
||||
<div v-if="editable && openLines.length" class="mt-3"><button type="button" class="rounded-xl border border-rose-300 bg-surface px-3 py-1.5 text-sm text-rose-800 hover:bg-rose-50 dark:border-rose-800 dark:text-rose-200" data-testid="review-fulfillment-close-remaining" @click="onCloseRemaining">{{ t('chat.shippingOrderReview.fulfillmentDecision.closeRemaining') }}</button></div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewIntakeParsePanel.spec.ts
|
||||
* 用途:锁定接收解析工作面只展示当前 Case 已授权的邮件正文与附件预览。
|
||||
* 依赖:Vitest、Vue Test Utils、vue-i18n、ReviewIntakeParsePanel。
|
||||
* 逻辑:PDF 才允许嵌入预览;非 PDF 明确降级;所有处置仅向父级发出意图。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import ReviewIntakeParsePanel from './ReviewIntakeParsePanel.vue';
|
||||
import type { ShippingOrderReviewIntakeParseContext } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
lifecycle: {
|
||||
intakeParse: {
|
||||
title: '接收解析',
|
||||
email: '邮件正文',
|
||||
noEmail: '无邮件上下文',
|
||||
attachment: '当前附件',
|
||||
fileName: '文件名',
|
||||
fileType: '文件类型',
|
||||
preview: '附件预览',
|
||||
loadPreview: '加载附件预览',
|
||||
previewUnsupported: '当前附件不支持预览',
|
||||
loadFailed: '接收解析上下文加载失败',
|
||||
retry: '重试',
|
||||
loading: '正在加载接收解析上下文',
|
||||
},
|
||||
},
|
||||
markNonOrder: '标记为非订单',
|
||||
markQualityIssue: '文件质量异常',
|
||||
reparse: '重新识别此 PDF',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const emailPdfContext: ShippingOrderReviewIntakeParseContext = {
|
||||
case_no: 'CASE-1',
|
||||
attachment: {
|
||||
document_id: 11,
|
||||
filename: 'current.pdf',
|
||||
mime_type: 'application/pdf',
|
||||
preview_kind: 'pdf',
|
||||
},
|
||||
email: {
|
||||
document_id: 7,
|
||||
filename: 'source.eml',
|
||||
render_kind: 'text',
|
||||
text: 'approved body text',
|
||||
},
|
||||
};
|
||||
|
||||
const unsupportedContext: ShippingOrderReviewIntakeParseContext = {
|
||||
...emailPdfContext,
|
||||
attachment: {
|
||||
document_id: 12,
|
||||
filename: 'source.xlsx',
|
||||
mime_type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
preview_kind: 'unsupported',
|
||||
},
|
||||
email: null,
|
||||
};
|
||||
|
||||
function mountPanel(props: Record<string, unknown>) {
|
||||
return mount(ReviewIntakeParsePanel, {
|
||||
props: {
|
||||
loading: false,
|
||||
loadFailed: false,
|
||||
previewUrl: null,
|
||||
previewLoading: false,
|
||||
...props,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('ReviewIntakeParsePanel', () => {
|
||||
it('renders EML text and only the selected attachment preview', () => {
|
||||
const wrapper = mountPanel({ context: emailPdfContext, previewUrl: 'blob:pdf' });
|
||||
|
||||
// 关键断言:邮件正文与当前附件来自同一个受控 Case context,PDF 才嵌入预览。
|
||||
expect(wrapper.get('[data-testid="intake-parse-email-body"]').text()).toContain('approved body text');
|
||||
expect(wrapper.get('[data-testid="intake-parse-attachment-preview"] iframe').attributes('src')).toBe('blob:pdf');
|
||||
});
|
||||
|
||||
it('uses a compact attachment heading without duplicate metadata', () => {
|
||||
const wrapper = mountPanel({ context: emailPdfContext, previewUrl: 'blob:pdf' });
|
||||
|
||||
// 关键断言:文件名与当前附件合并展示,MIME 类型不再占用预览空间。
|
||||
expect(wrapper.get('[data-testid="intake-parse-attachment-heading"]').text()).toContain('当前附件');
|
||||
expect(wrapper.get('[data-testid="intake-parse-attachment-heading"]').text()).toContain('current.pdf');
|
||||
expect(wrapper.text()).not.toContain('文件类型');
|
||||
});
|
||||
|
||||
it('loads isolated EML HTML from the backend preview URL inside a sandboxed iframe', () => {
|
||||
const wrapper = mountPanel({
|
||||
context: {
|
||||
...emailPdfContext,
|
||||
email: {
|
||||
...emailPdfContext.email!,
|
||||
render_kind: 'safe_html',
|
||||
preview_url: '/api/workspace/shipping-notice/order-review-cases/CASE-1/email-preview?preview_token=single-use',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// 关键断言:HTML 不得通过 srcdoc 注入工作台 DOM,必须由受控 URL 在无脚本 iframe 中读取。
|
||||
const frame = wrapper.get('[data-testid="intake-parse-email-html"]');
|
||||
expect(frame.attributes('sandbox')).toBeDefined();
|
||||
expect(frame.attributes('src')).toContain('preview_token=single-use');
|
||||
expect(frame.attributes('srcdoc')).toBeUndefined();
|
||||
expect(wrapper.find('[data-testid="intake-parse-email-body"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('does not render a PDF frame for an unsupported attachment', () => {
|
||||
const wrapper = mountPanel({ context: unsupportedContext });
|
||||
|
||||
// 关键断言:非 PDF 不得退化为 iframe,必须明确告知不可预览。
|
||||
expect(wrapper.find('[data-testid="intake-parse-attachment-preview"]').exists()).toBe(false);
|
||||
expect(wrapper.get('[data-testid="intake-parse-preview-unsupported"]').exists()).toBe(true);
|
||||
expect(wrapper.get('[data-testid="intake-parse-no-email"]').text()).toContain('无邮件上下文');
|
||||
});
|
||||
|
||||
it('does not render parse disposition controls inside the scrolling intake panel', () => {
|
||||
const wrapper = mountPanel({
|
||||
context: emailPdfContext,
|
||||
});
|
||||
|
||||
// 关键断言:按钮由父级固定底栏统一承载,面板滚动时不得随内容离开视口。
|
||||
expect(wrapper.find('[data-testid="intake-parse-disposition-actions"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="intake-parse-mark-non-order"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('does not render deprecated parse disposition controls inside the scrolling panel', () => {
|
||||
const wrapper = mountPanel({
|
||||
context: emailPdfContext,
|
||||
});
|
||||
|
||||
// 关键断言:处置由固定底栏承载,滚动内容区不得遗留重复入口。
|
||||
expect(wrapper.find('[data-testid="intake-parse-reparse"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewIntakeParsePanel.vue
|
||||
用途:在接收解析阶段展示当前 Case 已授权的邮件正文、当前附件及安全预览。
|
||||
依赖:vue、vue-i18n、ShippingOrderReviewIntakeParseContext。
|
||||
逻辑:只消费父级按 Case 获取的受控上下文;仅 PDF 可请求/渲染 iframe;处置操作只 emit,
|
||||
由父页沿用既有确认弹窗和 Case 命令。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderReviewIntakeParseContext } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
context: ShippingOrderReviewIntakeParseContext | null;
|
||||
loading: boolean;
|
||||
loadFailed: boolean;
|
||||
previewUrl: string | null;
|
||||
previewLoading: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'retry-context': [];
|
||||
'load-preview': [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
/**
|
||||
* 当前附件为 PDF 且尚无受控 Blob 时,通知父级使用当前 Case 加载预览。
|
||||
* 仅 Case context 改变时触发,禁止对不受支持文件发起预览请求。
|
||||
*/
|
||||
watch(
|
||||
() => props.context,
|
||||
(context) => {
|
||||
if (context?.attachment.preview_kind === 'pdf' && !props.previewUrl) {
|
||||
emit('load-preview');
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
class="space-y-4"
|
||||
data-testid="intake-parse-panel"
|
||||
>
|
||||
<div
|
||||
v-if="loading"
|
||||
class="rounded-xl border border-dashed border-default bg-surface-soft p-4 text-sm text-secondary dark:bg-slate-900/40"
|
||||
data-testid="intake-parse-loading"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.loading') }}
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="loadFailed"
|
||||
class="rounded-xl border border-rose-200 bg-rose-50 p-4 text-sm text-rose-900 dark:border-rose-900 dark:bg-rose-950/40 dark:text-rose-100"
|
||||
data-testid="intake-parse-load-failed"
|
||||
>
|
||||
<p>{{ t('chat.shippingOrderReview.lifecycle.intakeParse.loadFailed') }}</p>
|
||||
<button
|
||||
type="button"
|
||||
class="mt-3 rounded border border-rose-300 px-2.5 py-1 text-xs hover:bg-rose-100 dark:border-rose-800 dark:hover:bg-rose-950"
|
||||
data-testid="intake-parse-retry-context"
|
||||
@click="emit('retry-context')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.retry') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<template v-else-if="context">
|
||||
<section class="rounded-xl border border-default bg-surface p-4 shadow-sm">
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.lifecycle.intakeParse.email') }}</h2>
|
||||
<template v-if="context.email">
|
||||
<p class="mt-1 text-xs text-muted">{{ context.email.filename }}</p>
|
||||
<iframe
|
||||
v-if="context.email.render_kind === 'safe_html' && context.email.preview_url"
|
||||
:src="context.email.preview_url"
|
||||
sandbox=""
|
||||
referrerpolicy="no-referrer"
|
||||
:title="t('chat.shippingOrderReview.lifecycle.intakeParse.emailPreviewTitle')"
|
||||
class="mt-3 h-72 w-full rounded border border-default bg-surface"
|
||||
data-testid="intake-parse-email-html"
|
||||
/>
|
||||
<pre
|
||||
v-else
|
||||
class="mt-3 max-h-72 overflow-auto whitespace-pre-wrap break-words rounded bg-surface-soft p-3 text-xs text-secondary dark:bg-slate-950/50"
|
||||
data-testid="intake-parse-email-body"
|
||||
>{{ context.email.text }}</pre>
|
||||
</template>
|
||||
<p
|
||||
v-else
|
||||
class="mt-2 text-sm text-muted"
|
||||
data-testid="intake-parse-no-email"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.noEmail') }}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section class="rounded-xl border border-default bg-surface p-4 shadow-sm">
|
||||
<h2 class="text-sm font-semibold" data-testid="intake-parse-attachment-heading">
|
||||
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.attachment') }} ·
|
||||
<span class="font-normal text-muted">{{ context.attachment.filename }}</span>
|
||||
</h2>
|
||||
|
||||
<div
|
||||
v-if="context.attachment.preview_kind === 'pdf'"
|
||||
class="mt-3"
|
||||
data-testid="intake-parse-attachment-preview"
|
||||
>
|
||||
<p
|
||||
v-if="previewLoading"
|
||||
class="mt-2 text-sm text-muted"
|
||||
data-testid="intake-parse-preview-loading"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.previewLoading') }}
|
||||
</p>
|
||||
<iframe
|
||||
v-else-if="previewUrl"
|
||||
:src="previewUrl"
|
||||
:title="context.attachment.filename"
|
||||
class="mt-2 h-[32rem] w-full rounded border border-default"
|
||||
/>
|
||||
<button
|
||||
v-else
|
||||
type="button"
|
||||
class="mt-2 rounded border border-default px-2.5 py-1 text-xs hover-surface-soft"
|
||||
data-testid="intake-parse-load-preview"
|
||||
@click="emit('load-preview')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.loadPreview') }}
|
||||
</button>
|
||||
</div>
|
||||
<p
|
||||
v-else
|
||||
class="mt-4 rounded bg-surface-soft p-3 text-sm text-muted dark:bg-slate-950/50"
|
||||
data-testid="intake-parse-preview-unsupported"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.previewUnsupported') }}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewInventoryCandidatesPanel.spec.ts
|
||||
* 用途:验证库存路由面板展示服务端规则结果、规则码与源编码以满足可追溯。
|
||||
* 依赖:Vitest、Vue Test Utils、vue-i18n、chat 文案。
|
||||
* 逻辑:构造带技术编码的行投影;断言显示名+编码与命中规则;两列标签卡可扫描;
|
||||
* 自动重算意图只透传 line_key,不允许出现人工候选表单。
|
||||
*/
|
||||
import { flushPromises, mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import chatZhCn from '@/locales/zh-CN/chat.json';
|
||||
import ReviewInventoryCandidatesPanel from './ReviewInventoryCandidatesPanel.vue';
|
||||
import type { ShippingOrderReviewBuildEligibilityLineProjection } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: { 'zh-CN': { chat: chatZhCn } },
|
||||
});
|
||||
|
||||
function line(
|
||||
overrides: Partial<ShippingOrderReviewBuildEligibilityLineProjection> = {},
|
||||
): ShippingOrderReviewBuildEligibilityLineProjection {
|
||||
return {
|
||||
line_key: 'L1',
|
||||
line_index: 0,
|
||||
candidate_inventory_source_codes: ['DSV360_AWSDU'],
|
||||
raw_rule_source_codes: ['DSV360_AWSSG'],
|
||||
unavailable_source_codes: ['DSV360_AWSSG'],
|
||||
unavailable_reasons: { DSV360_AWSSG: 'source_disabled' },
|
||||
rule_suggestion_source_codes: ['DSV360_AWSDU'],
|
||||
matched_rules: [{ rule_code: 'ROUTE_HINT_AWSSG', version: 1 }],
|
||||
rule_versions: [{ rule_code: 'INVENTORY_RULE_18', version: 18 }],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('ReviewInventoryCandidatesPanel', () => {
|
||||
it('shows source labels with codes and matched rule codes for traceability', () => {
|
||||
const wrapper = mount(ReviewInventoryCandidatesPanel, {
|
||||
props: {
|
||||
lines: [line()],
|
||||
sourceLabels: {
|
||||
DSV360_AWSDU: '杜塞尔多夫仓',
|
||||
DSV360_AWSSG: '新加坡仓',
|
||||
},
|
||||
editable: true,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
const text = wrapper.text();
|
||||
// 显示名与稳定编码同时可见,满足复核线框「命中规则 / 库存源」可追溯。
|
||||
// 显示名与稳定编码必须同时可见,避免仅见名称无法对审计。
|
||||
expect(text).toContain('杜塞尔多夫仓');
|
||||
expect(text).toContain('新加坡仓');
|
||||
expect(text).toContain('DSV360_AWSDU');
|
||||
expect(text).toContain('DSV360_AWSSG');
|
||||
expect(text).toContain('ROUTE_HINT_AWSSG');
|
||||
expect(text).toContain('匹配规则');
|
||||
expect(text).toContain('库存源未启用');
|
||||
expect(wrapper.find('[data-testid="review-inventory-unavailable-sources"]').text()).toContain('DSV360_AWSSG');
|
||||
expect(
|
||||
wrapper.find('[data-testid="review-inventory-unavailable-sources"] [data-source-code="DSV360_AWSSG"]').exists(),
|
||||
).toBe(true);
|
||||
// 不可用候选用标签卡而非行内长串,便于多源扫描。
|
||||
expect(wrapper.find('[data-testid="review-inventory-unavailable-sources"] .grid').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('always shows monospace source_code on inventory hint even when a business name exists', () => {
|
||||
const wrapper = mount(ReviewInventoryCandidatesPanel, {
|
||||
props: {
|
||||
lines: [line({ inventory_source_hint: 'DSV360_AWSSG' })],
|
||||
sourceLabels: { DSV360_AWSSG: '新加坡仓' },
|
||||
editable: false,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
const hintCode = wrapper.get('[data-testid="review-inventory-hint-source-code"]');
|
||||
expect(hintCode.text()).toBe('DSV360_AWSSG');
|
||||
expect(hintCode.attributes('data-source-code')).toBe('DSV360_AWSSG');
|
||||
expect(wrapper.text()).toContain('新加坡仓');
|
||||
});
|
||||
|
||||
it('renders refreshed rule candidates without exposing manual selection inputs', async () => {
|
||||
const wrapper = mount(ReviewInventoryCandidatesPanel, {
|
||||
props: {
|
||||
lines: [line({ candidate_inventory_source_codes: ['DSV360_AWSDU'] })],
|
||||
sourceLabels: { DSV360_AWSDU: '杜塞尔多夫仓', DSV360_AWSBI: '伯明翰仓' },
|
||||
editable: true,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
await wrapper.setProps({
|
||||
lines: [line({
|
||||
candidate_inventory_source_codes: ['DSV360_AWSBI'],
|
||||
raw_rule_source_codes: ['DSV360_AWSBI'],
|
||||
unavailable_source_codes: [],
|
||||
rule_suggestion_source_codes: ['DSV360_AWSBI'],
|
||||
matched_rules: [{ rule_code: 'ROUTE_HINT_AWSBI', version: 2 }],
|
||||
})],
|
||||
});
|
||||
await flushPromises();
|
||||
expect(wrapper.text()).toContain('伯明翰仓');
|
||||
expect(wrapper.text()).toContain('DSV360_AWSBI');
|
||||
expect(wrapper.text()).toContain('ROUTE_HINT_AWSBI');
|
||||
expect(wrapper.find('textarea').exists()).toBe(false);
|
||||
expect(wrapper.find('input[type="checkbox"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewInventoryCandidatesPanel.vue
|
||||
用途:库存路由恢复面板——展示发布规则结果、不可用源并支持自动重算。
|
||||
依赖:vue-i18n、ShippingOrderReviewBuildEligibilityLineProjection 类型。
|
||||
逻辑:只展示服务端规则裁决;服务端行指纹变化时刷新显示;业务名与等宽 source_code 始终可见;
|
||||
原始/不可用/有效候选用两列标签卡降低密度;仅 emit 自动重算意图。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderReviewBuildEligibilityLineProjection } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
lines: ShippingOrderReviewBuildEligibilityLineProjection[];
|
||||
/** 库存源编码 → 业务显示名;提交仍使用编码 */
|
||||
sourceLabels?: Record<string, string>;
|
||||
editable?: boolean;
|
||||
saving?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'reroute', draftLineId?: string): void;
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
/**
|
||||
* 规则建议可用源编码。
|
||||
*/
|
||||
function ruleSuggestionCodes(line: ShippingOrderReviewBuildEligibilityLineProjection): string[] {
|
||||
return line.rule_suggestion?.source_codes
|
||||
|| line.rule_suggestion_source_codes
|
||||
|| line.rule_source_codes
|
||||
|| [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析阻断原因展示文案。
|
||||
*/
|
||||
function blockReasonLabel(reason?: string | null): string {
|
||||
const normalized = String(reason || '').trim();
|
||||
if (!normalized) return '';
|
||||
const key = `chat.shippingOrderReview.buildEligibility.blockReasons.${normalized}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.blockReasons.unknown');
|
||||
}
|
||||
|
||||
/**
|
||||
* 库存源业务显示名(不含编码);编码由 sourceCodeLabel 单独展示,避免仅见名称无法对审计。
|
||||
*/
|
||||
function sourceBusinessName(code: string): string {
|
||||
const normalized = String(code || '').trim().toUpperCase();
|
||||
if (!normalized) return t('chat.shippingOrderReview.inventoryRouting.sourceUnnamed');
|
||||
const label = String(props.sourceLabels?.[normalized] || props.sourceLabels?.[code] || '').trim();
|
||||
if (label && label.toUpperCase() !== normalized) return label;
|
||||
return t('chat.shippingOrderReview.inventoryRouting.sourceUnnamed');
|
||||
}
|
||||
|
||||
/**
|
||||
* 稳定源编码(始终可见,等宽)。
|
||||
*/
|
||||
function sourceCodeLabel(code: string): string {
|
||||
return String(code || '').trim().toUpperCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* 命中规则编码列表(rule_code 优先)。
|
||||
*/
|
||||
function matchedRuleCodes(line: ShippingOrderReviewBuildEligibilityLineProjection): string[] {
|
||||
const fromRules = (line.matched_rules || [])
|
||||
.map((item) => String(item.rule_code || '').trim())
|
||||
.filter(Boolean);
|
||||
if (fromRules.length) return [...new Set(fromRules)];
|
||||
return (line.matched_rule_ids || []).map((id) => String(id));
|
||||
}
|
||||
|
||||
/** 展示规则命中但被运行时配置过滤的具体原因。 */
|
||||
function unavailableReasonLabel(line: ShippingOrderReviewBuildEligibilityLineProjection, code: string): string {
|
||||
const reason = String(line.unavailable_reasons?.[code] || '').trim();
|
||||
if (!reason) return t('chat.shippingOrderReview.inventoryRouting.unavailableReasonUnknown');
|
||||
const key = `chat.shippingOrderReview.inventoryRouting.unavailableReasons.${reason}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderReview.inventoryRouting.unavailableReasonUnknown');
|
||||
}
|
||||
|
||||
/**
|
||||
* 触发行级重新匹配路由。
|
||||
*/
|
||||
function rerouteLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
|
||||
const draftLineId = String(line.draft_line_id || '').trim();
|
||||
emit('reroute', draftLineId || undefined);
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="lines.length"
|
||||
class="rounded-xl border border-sky-200 bg-sky-50/60 p-4 shadow-sm dark:border-sky-900 dark:bg-sky-950/20"
|
||||
data-testid="review-inventory-candidates-panel"
|
||||
>
|
||||
<header class="mb-3">
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.inventoryCandidates.title') }}</h2>
|
||||
<p class="mt-0.5 text-xs text-secondary">
|
||||
{{ t('chat.shippingOrderReview.inventoryCandidates.subtitle') }}
|
||||
</p>
|
||||
<p class="mt-1 text-xs text-muted">
|
||||
{{ t('chat.shippingOrderReview.inventoryRouting.rerouteHint') }}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<article
|
||||
v-for="line in lines"
|
||||
:key="String(line.line_no)"
|
||||
class="mb-3 rounded-lg border border-default bg-surface p-3 last:mb-0"
|
||||
:data-testid="`review-inventory-candidates-line-${line.line_no}`"
|
||||
>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2 text-sm">
|
||||
<span class="font-medium">
|
||||
{{ t('chat.shippingOrderReview.line', { index: (line.line_index ?? 0) + 1 }) }}
|
||||
<span v-if="line.effective_reservation_id" class="ml-1 text-xs text-muted">
|
||||
{{ line.effective_reservation_id }}
|
||||
</span>
|
||||
</span>
|
||||
<span v-if="line.block_reason" class="text-xs text-amber-800 dark:text-amber-200">
|
||||
{{ blockReasonLabel(line.block_reason) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p
|
||||
v-if="line.inventory_source_hint"
|
||||
class="mt-2 text-xs text-secondary"
|
||||
data-testid="review-inventory-routing-hint"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.inventoryRouting.hint') }}:
|
||||
<span>{{ sourceBusinessName(String(line.inventory_source_hint)) }}</span>
|
||||
<span
|
||||
class="ml-1 font-mono text-[11px]"
|
||||
data-testid="review-inventory-hint-source-code"
|
||||
:data-source-code="sourceCodeLabel(String(line.inventory_source_hint))"
|
||||
>{{ sourceCodeLabel(String(line.inventory_source_hint)) }}</span>
|
||||
</p>
|
||||
|
||||
<div class="mt-2 space-y-2 text-xs text-secondary">
|
||||
<div v-if="matchedRuleCodes(line).length" data-testid="review-inventory-matched-rules">
|
||||
<div class="font-medium">{{ t('chat.shippingOrderReview.inventoryRouting.matchedRules') }}</div>
|
||||
<div class="mt-1 flex flex-wrap gap-1.5">
|
||||
<span
|
||||
v-for="ruleCode in matchedRuleCodes(line)"
|
||||
:key="`rule-${ruleCode}`"
|
||||
class="rounded border border-default bg-surface-soft px-1.5 py-0.5 font-mono text-[11px]"
|
||||
>{{ ruleCode }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="(line.raw_rule_source_codes || []).length" data-testid="review-inventory-raw-sources">
|
||||
<div class="font-medium">{{ t('chat.shippingOrderReview.inventoryRouting.rawCandidates') }}</div>
|
||||
<div class="mt-1 grid gap-1.5 sm:grid-cols-2">
|
||||
<div
|
||||
v-for="code in line.raw_rule_source_codes"
|
||||
:key="`raw-${code}`"
|
||||
class="rounded-md border border-default bg-surface px-2 py-1.5"
|
||||
>
|
||||
<div class="truncate font-medium text-secondary">{{ sourceBusinessName(String(code)) }}</div>
|
||||
<div
|
||||
class="mt-0.5 font-mono text-[11px] text-muted"
|
||||
:data-source-code="sourceCodeLabel(String(code))"
|
||||
>{{ sourceCodeLabel(String(code)) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="(line.unavailable_source_codes || []).length" data-testid="review-inventory-unavailable-sources">
|
||||
<div class="font-medium">{{ t('chat.shippingOrderReview.inventoryRouting.unavailableCandidates') }}</div>
|
||||
<div class="mt-1 grid gap-1.5 sm:grid-cols-2">
|
||||
<div
|
||||
v-for="code in line.unavailable_source_codes"
|
||||
:key="code"
|
||||
class="rounded-md border border-rose-200 bg-rose-50/70 px-2 py-1.5 dark:border-rose-900 dark:bg-rose-950/30"
|
||||
>
|
||||
<div class="truncate font-medium text-rose-900 dark:text-rose-100">{{ sourceBusinessName(code) }}</div>
|
||||
<div
|
||||
class="mt-0.5 font-mono text-[11px] text-rose-700 dark:text-rose-300"
|
||||
:data-source-code="sourceCodeLabel(code)"
|
||||
>{{ sourceCodeLabel(code) }}</div>
|
||||
<div class="mt-0.5 text-[11px] text-rose-700 dark:text-rose-300">{{ unavailableReasonLabel(line, code) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="ruleSuggestionCodes(line).length" data-testid="review-inventory-rule-suggestions">
|
||||
<div class="font-medium">{{ t('chat.shippingOrderReview.inventoryRouting.ruleSuggestion') }}</div>
|
||||
<div class="mt-1 grid gap-1.5 sm:grid-cols-2">
|
||||
<div
|
||||
v-for="code in ruleSuggestionCodes(line)"
|
||||
:key="`suggest-${code}`"
|
||||
class="rounded-md border border-sky-200 bg-sky-50/70 px-2 py-1.5 dark:border-sky-900 dark:bg-sky-950/30"
|
||||
>
|
||||
<div class="truncate font-medium text-sky-900 dark:text-sky-100">{{ sourceBusinessName(code) }}</div>
|
||||
<div
|
||||
class="mt-0.5 font-mono text-[11px] text-sky-700 dark:text-sky-300"
|
||||
:data-source-code="sourceCodeLabel(code)"
|
||||
>{{ sourceCodeLabel(code) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 flex flex-wrap items-center justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-default bg-surface px-3 py-1.5 text-xs text-secondary disabled:opacity-50"
|
||||
data-testid="review-inventory-routing-reroute"
|
||||
:disabled="!editable || saving"
|
||||
@click="rerouteLine(line)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.inventoryRouting.reroute') }}
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
</section>
|
||||
</template>
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewInventoryIssueFallbackCard.vue
|
||||
用途:无行投影且库存系统失败时的 Case 级兜底卡;仅重试获取库存。
|
||||
依赖:vue-i18n。
|
||||
逻辑:由 ShippingOrderReviewView 在 inventory_issue_fallback 或行级库存问题聚合时挂载;
|
||||
禁止进库存工作台、禁止匹配/关闭/换源。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { inventoryActionLabelKey } from '@/features/shipping-progress/actionPresentation';
|
||||
|
||||
export interface InventoryIssueFallback {
|
||||
kind?: string | null;
|
||||
reason_label_key?: string | null;
|
||||
affected_line_count?: number | null;
|
||||
file_count?: number | null;
|
||||
allowed_actions?: string[] | null;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
fallback: InventoryIssueFallback | null | undefined;
|
||||
busy?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'retry-preparation': [];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
const visible = computed(() => {
|
||||
const actions = props.fallback?.allowed_actions || [];
|
||||
return Boolean(props.fallback && actions.includes('retry_inventory_preparation'));
|
||||
});
|
||||
|
||||
/**
|
||||
* 失败原因文案。
|
||||
*/
|
||||
const reasonLabel = computed(() => {
|
||||
const keyCode = String(props.fallback?.reason_label_key || props.fallback?.kind || '').trim();
|
||||
const key = `chat.shippingOrderReview.inventoryFallback.kinds.${keyCode}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderReview.inventoryFallback.kinds.inventory_file_missing');
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="visible"
|
||||
class="rounded-xl border border-amber-200 bg-amber-50/70 p-3 shadow-sm dark:border-amber-900 dark:bg-amber-950/30"
|
||||
data-testid="review-inventory-issue-fallback"
|
||||
>
|
||||
<h2 class="text-sm font-semibold text-amber-950 dark:text-amber-50">
|
||||
{{ t('chat.shippingOrderReview.inventoryFallback.title') }}
|
||||
</h2>
|
||||
<p class="mt-1 text-xs text-amber-900 dark:text-amber-100" data-testid="review-inventory-fallback-reason">
|
||||
{{ reasonLabel }}
|
||||
</p>
|
||||
<p
|
||||
v-if="(fallback?.affected_line_count || 0) > 0"
|
||||
class="mt-1 text-[11px] text-amber-800/90 dark:text-amber-200/90"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.inventoryFallback.affectedLines', {
|
||||
count: fallback?.affected_line_count || 0,
|
||||
}) }}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
class="mt-3 w-full rounded-xl border border-amber-300 bg-surface px-3 py-1.5 text-sm text-amber-950 hover:bg-amber-100 disabled:opacity-50 dark:border-amber-800 dark:text-amber-50"
|
||||
data-testid="review-inventory-fallback-retry"
|
||||
:disabled="busy"
|
||||
@click="emit('retry-preparation')"
|
||||
>
|
||||
{{ t(inventoryActionLabelKey('retry_inventory_preparation')!) }}
|
||||
</button>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,83 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewInventoryIssueList.vue
|
||||
用途:标准复核侧栏中的异常库存行摘要列表(只显示需处理行)。
|
||||
依赖:vue-i18n、ShippingOrderReviewBuildEligibilityLineProjection。
|
||||
逻辑:行列表由后端 recovery/suggestion 投影提供,前端不自行发明异常规则;
|
||||
点击行可定位明细;正式 OT 后 showEnterAction=false,禁止切库存工作台。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderReviewBuildEligibilityLineProjection } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
defineProps<{
|
||||
lines: ShippingOrderReviewBuildEligibilityLineProjection[];
|
||||
/**
|
||||
* 仅展示摘要标题,不列出行明细(Gate/履约摘要已表达缺口时使用)。
|
||||
*/
|
||||
summaryOnly?: boolean;
|
||||
/** 是否展示「进入库存」按钮;正式 OT 后应关闭。 */
|
||||
showEnterAction?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'enter-inventory': [];
|
||||
'focus-line': [lineIndex: number];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
/**
|
||||
* 解析阻断原因展示文案。
|
||||
*/
|
||||
function blockReasonLabel(reason?: string | null): string {
|
||||
const normalized = String(reason || '').trim();
|
||||
if (!normalized) return t('chat.shippingOrderReview.buildEligibility.blockReasons.unknown');
|
||||
const key = `chat.shippingOrderReview.buildEligibility.blockReasons.${normalized}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.blockReasons.unknown');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="lines.length"
|
||||
class="rounded-xl border border-default bg-surface p-3 shadow-sm"
|
||||
data-testid="review-inventory-issue-list"
|
||||
>
|
||||
<header class="mb-2 flex items-center justify-between gap-2">
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.workbench.inventoryIssues') }}</h2>
|
||||
<button
|
||||
v-if="showEnterAction"
|
||||
type="button"
|
||||
class="rounded border border-amber-300 px-2 py-1 text-xs text-amber-900 hover:bg-amber-50 dark:border-amber-800 dark:text-amber-100 dark:hover:bg-amber-950/40"
|
||||
data-testid="review-inventory-issues-enter"
|
||||
@click="emit('enter-inventory')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workbench.enterInventory') }}
|
||||
</button>
|
||||
</header>
|
||||
<ul v-if="!summaryOnly" class="space-y-1.5">
|
||||
<li
|
||||
v-for="line in lines"
|
||||
:key="String(line.line_no)"
|
||||
class="rounded-lg border border-amber-200 bg-amber-50/70 px-2.5 py-2 text-xs dark:border-amber-900 dark:bg-amber-950/30"
|
||||
:data-testid="`review-inventory-issue-${line.line_no}`"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="w-full text-left"
|
||||
@click="emit('focus-line', Number(line.line_index ?? 0))"
|
||||
>
|
||||
<div class="font-medium text-amber-950 dark:text-amber-100">
|
||||
{{ t('chat.shippingOrderReview.line', { index: (line.line_index ?? 0) + 1 }) }}
|
||||
<span v-if="line.effective_reservation_id" class="ml-1 font-mono text-[11px] opacity-80">
|
||||
{{ line.effective_reservation_id }}
|
||||
</span>
|
||||
</div>
|
||||
<p class="mt-0.5 text-amber-900/90 dark:text-amber-100/90">
|
||||
{{ blockReasonLabel(line.block_reason) }}
|
||||
</p>
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</template>
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewLifecycleStageNavigation.spec.ts
|
||||
* 用途:验收订单生命周期阶段导航的只读查看与前置阻断交互。
|
||||
* 依赖:ReviewLifecycleStageNavigation;Vue Test Utils 与 Vue I18n 测试运行时。
|
||||
* 逻辑:阶段状态由父级传入;本测试只验证组件不会绕过 blocked 状态发出选择事件。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ReviewLifecycleStageNavigation, {
|
||||
type ReviewLifecycleStageItem,
|
||||
} from './ReviewLifecycleStageNavigation.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingNoticeRetryParse: '重试解析',
|
||||
shippingOrderReview: {
|
||||
lifecycle: {
|
||||
navigation: '订单生命周期阶段',
|
||||
current: '当前可处理',
|
||||
processing: '处理中',
|
||||
completed: '已完成,可查看',
|
||||
blocked: '前置未完成',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const stages: ReviewLifecycleStageItem[] = [
|
||||
{ code: 'order_review', label: '订单复核', state: 'completed' },
|
||||
{ code: 'fulfillment_prep', label: '通知准备', state: 'current' },
|
||||
{ code: 'freight_upload', label: '货代上传', state: 'blocked', reason: '请先完成通知准备' },
|
||||
{ code: 'upload_complete', label: '通知完成', state: 'blocked', reason: '请先完成通知准备' },
|
||||
];
|
||||
|
||||
/** 挂载导航,复用真实 i18n 以覆盖状态文案渲染。 */
|
||||
function mountNavigation() {
|
||||
return mount(ReviewLifecycleStageNavigation, {
|
||||
props: { stages, activeCode: 'fulfillment_prep', processingCode: 'fulfillment_prep' },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('ReviewLifecycleStageNavigation', () => {
|
||||
it('only exposes retry_parse on the current intake stage when the server authorizes it', async () => {
|
||||
const wrapper = mount(ReviewLifecycleStageNavigation, {
|
||||
props: {
|
||||
stages: [
|
||||
{ code: 'intake_parse', label: '接收解析', state: 'current' },
|
||||
...stages,
|
||||
],
|
||||
activeCode: 'intake_parse',
|
||||
availableActions: ['retry_parse'],
|
||||
retrying: false,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 关键断言:重试入口必须位于已发送文件的当前阶段卡,且完全由后端动作授权。
|
||||
const retry = wrapper.get('[data-testid="review-lifecycle-stage-retry-parse"]');
|
||||
expect(retry.text()).toContain('重试解析');
|
||||
await retry.trigger('click');
|
||||
expect(wrapper.emitted('retry-parse')).toEqual([[]]);
|
||||
|
||||
await wrapper.setProps({ availableActions: [] });
|
||||
expect(wrapper.find('[data-testid="review-lifecycle-stage-retry-parse"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders intake_parse as the first lifecycle stage', () => {
|
||||
const wrapper = mount(ReviewLifecycleStageNavigation, {
|
||||
props: {
|
||||
stages: [
|
||||
{ code: 'intake_parse' as ReviewLifecycleStageItem['code'], label: '接收解析', state: 'current' },
|
||||
...stages,
|
||||
],
|
||||
activeCode: 'intake_parse' as ReviewLifecycleStageItem['code'],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
const nodes = wrapper.findAll('div[data-testid^="review-lifecycle-stage-"]');
|
||||
// 关键断言:接收解析必须在用户生命周期导航首位,不得回退为三阶段。
|
||||
expect(nodes.map((node) => node.attributes('data-testid'))).toEqual([
|
||||
'review-lifecycle-stage-intake_parse',
|
||||
'review-lifecycle-stage-order_review',
|
||||
'review-lifecycle-stage-fulfillment_prep',
|
||||
'review-lifecycle-stage-freight_upload',
|
||||
'review-lifecycle-stage-upload_complete',
|
||||
]);
|
||||
expect(wrapper.find('[data-testid="review-lifecycle-stage-navigation"] > div').classes()).toContain('sm:grid-cols-5');
|
||||
});
|
||||
|
||||
it('allows opening a completed stage for inspection', async () => {
|
||||
const wrapper = mountNavigation();
|
||||
await wrapper.get('[data-testid="review-lifecycle-stage-order_review"]').findAll('button')[1].trigger('click');
|
||||
// 关键断言:完成的阶段可回看,不会因已完成而被禁用。
|
||||
expect(wrapper.emitted('select')).toEqual([['order_review']]);
|
||||
});
|
||||
|
||||
it('shows a spinner and processing label on the active stage while automation runs', () => {
|
||||
const wrapper = mountNavigation();
|
||||
const stage = wrapper.get('[data-testid="review-lifecycle-stage-fulfillment_prep"]');
|
||||
expect(stage.attributes('data-processing')).toBe('1');
|
||||
expect(stage.text()).toContain('处理中');
|
||||
expect(stage.find('[data-testid="review-lifecycle-stage-spinner"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('renders the current upload-complete stage as completed instead of running', () => {
|
||||
const wrapper = mount(ReviewLifecycleStageNavigation, {
|
||||
props: {
|
||||
stages: [
|
||||
{ code: 'intake_parse', label: '接收解析', state: 'completed' },
|
||||
{ code: 'order_review', label: '订单复核', state: 'completed' },
|
||||
{ code: 'fulfillment_prep', label: '通知准备', state: 'completed' },
|
||||
{ code: 'freight_upload', label: '货代上传', state: 'completed' },
|
||||
{ code: 'upload_complete', label: '通知完成', state: 'current' },
|
||||
],
|
||||
activeCode: 'upload_complete',
|
||||
// 迟到的运行态不能覆盖后端已裁决的通知完成终态。
|
||||
processingCode: 'upload_complete',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
const stage = wrapper.get('[data-testid="review-lifecycle-stage-upload_complete"]');
|
||||
expect(stage.find('.text-emerald-600').exists()).toBe(true);
|
||||
expect(stage.find('.bg-brand-600').exists()).toBe(false);
|
||||
expect(stage.find('[data-testid="review-lifecycle-stage-spinner"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('disables a future stage and does not emit a selection', async () => {
|
||||
const wrapper = mountNavigation();
|
||||
const future = wrapper.get('[data-testid="review-lifecycle-stage-upload_complete"]');
|
||||
// 关键断言:前置未完成只展示原因,不能通过前端导航越过后端阶段。
|
||||
expect(future.text()).toContain('请先完成通知准备');
|
||||
await future.findAll('button')[1].trigger('click');
|
||||
expect(wrapper.emitted('select')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('opens process details from the stage label without reserving a separate row', async () => {
|
||||
const wrapper = mountNavigation();
|
||||
const detail = wrapper.get('[data-testid="review-lifecycle-stage-detail-fulfillment_prep"]');
|
||||
// 关键断言:阶段名称本身是流程详情入口,不额外占用工作台一整行。
|
||||
await detail.trigger('click');
|
||||
expect(wrapper.emitted('open-detail')).toEqual([['fulfillment_prep']]);
|
||||
});
|
||||
});
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewLifecycleStageNavigation.vue
|
||||
用途:订单生命周期工作台的五阶段导航,只呈现父级已裁决的阶段状态。
|
||||
依赖:父级 ShippingOrderReviewView 提供阶段、状态和阻断原因;lucide-vue-next 图标。
|
||||
逻辑:用户可打开当前或已完成阶段查看;后续阶段由父级传入 blocked 并禁用,本组件不写业务状态。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { Check, LockKeyhole, RefreshCw } from 'lucide-vue-next';
|
||||
|
||||
export type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete';
|
||||
export type ReviewLifecycleStageState = 'current' | 'completed' | 'blocked';
|
||||
|
||||
export interface ReviewLifecycleStageItem {
|
||||
code: ReviewLifecycleStageCode;
|
||||
label: string;
|
||||
state: ReviewLifecycleStageState;
|
||||
reason?: string | null;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
stages: ReviewLifecycleStageItem[];
|
||||
/** 后端尚未下发入口时为空;导航只能展示加载/未授权态,不能自行指定订单复核。 */
|
||||
activeCode: ReviewLifecycleStageCode | null;
|
||||
/** 仅消费当前对象后端下发的恢复动作,禁止按阶段或状态由前端猜测。 */
|
||||
availableActions?: string[];
|
||||
/** 当前阶段正在执行自动推进时的技术阶段码;只影响展示,不授权动作。 */
|
||||
processingCode?: ReviewLifecycleStageCode | null;
|
||||
/** retry_parse 请求中的互斥状态,避免用户重复提交。 */
|
||||
retrying?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
select: [code: ReviewLifecycleStageCode];
|
||||
'open-detail': [code: ReviewLifecycleStageCode];
|
||||
'retry-parse': [];
|
||||
}>();
|
||||
|
||||
/** 接收解析的恢复只在后端明确授权且该阶段为当前阶段时展示。 */
|
||||
function canRetryParse(stage: ReviewLifecycleStageItem): boolean {
|
||||
return stage.code === 'intake_parse'
|
||||
&& stage.state === 'current'
|
||||
&& (props.availableActions || []).includes('retry_parse');
|
||||
}
|
||||
|
||||
/** 通知完成是当前生命周期终态,不是仍在执行的当前工作阶段。 */
|
||||
function isCompletedStage(stage: ReviewLifecycleStageItem): boolean {
|
||||
return stage.state === 'completed' || (
|
||||
stage.code === 'upload_complete' && stage.state === 'current'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 阶段导航只允许进入后端下发为 current / available / completed 的阶段;
|
||||
* blocked 仅说明前置条件,不替代后端 Gate 判定。
|
||||
*/
|
||||
function selectStage(stage: ReviewLifecycleStageItem) {
|
||||
if (stage.state === 'blocked') return;
|
||||
emit('select', stage.code);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<nav
|
||||
class="rounded-xl border border-default bg-surface p-2"
|
||||
:aria-label="$t('chat.shippingOrderReview.lifecycle.navigation')"
|
||||
data-testid="review-lifecycle-stage-navigation"
|
||||
>
|
||||
<div class="grid gap-2 sm:grid-cols-5">
|
||||
<div
|
||||
v-for="stage in props.stages"
|
||||
:key="stage.code"
|
||||
class="min-w-0 rounded-lg border px-3 py-2 text-left transition-colors"
|
||||
:class="[
|
||||
stage.code === props.activeCode
|
||||
? 'border-brand-500 bg-brand-50 text-brand-950 dark:bg-brand-950/30 dark:text-brand-50'
|
||||
: 'border-transparent hover:bg-surface-soft',
|
||||
stage.state === 'blocked' ? 'opacity-60' : '',
|
||||
]"
|
||||
:data-testid="`review-lifecycle-stage-${stage.code}`"
|
||||
:data-processing="stage.code === props.processingCode ? '1' : '0'"
|
||||
>
|
||||
<span class="flex items-center gap-2 text-sm font-semibold">
|
||||
<RefreshCw
|
||||
v-if="stage.code === props.processingCode && !isCompletedStage(stage)"
|
||||
class="h-4 w-4 shrink-0 animate-spin text-brand-600"
|
||||
data-testid="review-lifecycle-stage-spinner"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<Check v-if="isCompletedStage(stage)" class="h-4 w-4 shrink-0 text-emerald-600" />
|
||||
<LockKeyhole v-else-if="stage.state === 'blocked'" class="h-4 w-4 shrink-0 text-muted" />
|
||||
<span v-else class="h-2 w-2 shrink-0 rounded-full bg-brand-600" aria-hidden="true" />
|
||||
<button
|
||||
type="button"
|
||||
class="truncate text-left hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-500"
|
||||
:data-testid="`review-lifecycle-stage-detail-${stage.code}`"
|
||||
@click="emit('open-detail', stage.code)"
|
||||
>{{ stage.label }}</button>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="mt-1 block w-full truncate text-left text-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-500 disabled:cursor-not-allowed"
|
||||
:class="stage.state === 'blocked' ? 'text-muted' : 'text-secondary'"
|
||||
:title="stage.reason || undefined"
|
||||
:disabled="stage.state === 'blocked'"
|
||||
@click="selectStage(stage)"
|
||||
>
|
||||
{{ isCompletedStage(stage)
|
||||
? $t('chat.shippingOrderReview.lifecycle.completed')
|
||||
: stage.state === 'current'
|
||||
? (stage.code === props.processingCode
|
||||
? $t('chat.shippingOrderReview.lifecycle.processing')
|
||||
: $t('chat.shippingOrderReview.lifecycle.current'))
|
||||
: (stage.reason || $t('chat.shippingOrderReview.lifecycle.blocked')) }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canRetryParse(stage)"
|
||||
type="button"
|
||||
class="mt-2 rounded border border-brand-300 px-2 py-1 text-xs font-medium text-brand-700 hover:bg-brand-50 disabled:cursor-not-allowed disabled:opacity-60 dark:border-brand-700 dark:text-brand-200 dark:hover:bg-brand-950/40"
|
||||
data-testid="review-lifecycle-stage-retry-parse"
|
||||
:disabled="props.retrying === true"
|
||||
@click="emit('retry-parse')"
|
||||
>
|
||||
{{ $t('chat.shippingNoticeRetryParse') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</template>
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewLineFulfillmentAggregateCard.spec.ts
|
||||
* 用途:锁定 UI-3 订单级聚合卡——同时展示系统进度与人工待办,无逐行摘要。
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ReviewLineFulfillmentAggregateCard from './ReviewLineFulfillmentAggregateCard.vue';
|
||||
import type { ShippingOrderReviewLineFulfillment } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
lineFulfillmentAggregate: {
|
||||
title: '履约进度摘要',
|
||||
hint: '同时展示系统进度与人工待办',
|
||||
autoProgress: '系统处理中 {count} 行',
|
||||
manualPending: '待人工处理 {count} 行',
|
||||
inventoryPending: '库存处理中 {count} 行',
|
||||
systemFailed: '自动履约失败 {count} 行',
|
||||
enterInventory: '进入库存/履约处理',
|
||||
viewLines: '查看订单明细',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe('ReviewLineFulfillmentAggregateCard', () => {
|
||||
it('shows system progress and manual pending together with inventory entry', async () => {
|
||||
const lineFulfillment: ShippingOrderReviewLineFulfillment = {
|
||||
lines: [],
|
||||
auto_progress_count: 2,
|
||||
manual_pending_count: 1,
|
||||
system_failed_count: 0,
|
||||
inventory_pending_count: 0,
|
||||
};
|
||||
const wrapper = mount(ReviewLineFulfillmentAggregateCard, {
|
||||
props: { lineFulfillment },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="review-line-fulfillment-aggregate-card"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-line-fulfillment-aggregate-auto-progress"]').text())
|
||||
.toContain('2');
|
||||
expect(wrapper.find('[data-testid="review-line-fulfillment-aggregate-manual-pending"]').text())
|
||||
.toContain('1');
|
||||
// 断言:不得只有系统进度而无短缺入口
|
||||
expect(wrapper.find('[data-testid="review-line-fulfillment-aggregate-enter-inventory"]').exists())
|
||||
.toBe(true);
|
||||
await wrapper.get('[data-testid="review-line-fulfillment-aggregate-enter-inventory"]').trigger('click');
|
||||
expect(wrapper.emitted('enter-inventory')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('hides when all aggregate counts are zero', () => {
|
||||
const wrapper = mount(ReviewLineFulfillmentAggregateCard, {
|
||||
props: {
|
||||
lineFulfillment: {
|
||||
lines: [],
|
||||
auto_progress_count: 0,
|
||||
manual_pending_count: 0,
|
||||
system_failed_count: 0,
|
||||
inventory_pending_count: 0,
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-line-fulfillment-aggregate-card"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewLineFulfillmentAggregateCard.vue
|
||||
用途:正式 OT 后右侧订单级履约聚合卡(系统进度 / 人工待办 / 失败),无逐行摘要。
|
||||
依赖:vue-i18n、ShippingOrderReviewLineFulfillment。
|
||||
逻辑:由 ShippingOrderReviewView 在 hasFormalOt 时挂载于侧栏主卡区;
|
||||
同时展示系统进度与短缺入口,禁止只显示「系统处理中」。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderReviewLineFulfillment } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
lineFulfillment: ShippingOrderReviewLineFulfillment | null | undefined;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'enter-inventory': [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
/**
|
||||
* 聚合计数(后端投影;缺省按 0)。
|
||||
*/
|
||||
const autoProgressCount = computed(() => Number(props.lineFulfillment?.auto_progress_count || 0));
|
||||
const manualPendingCount = computed(() => Number(props.lineFulfillment?.manual_pending_count || 0));
|
||||
const systemFailedCount = computed(() => Number(props.lineFulfillment?.system_failed_count || 0));
|
||||
const inventoryPendingCount = computed(() => Number(
|
||||
props.lineFulfillment?.inventory_pending_count || 0,
|
||||
));
|
||||
|
||||
/**
|
||||
* 有任一非零计数才展示;避免空卡占位。
|
||||
*/
|
||||
const visible = computed(() => (
|
||||
autoProgressCount.value > 0
|
||||
|| manualPendingCount.value > 0
|
||||
|| systemFailedCount.value > 0
|
||||
|| inventoryPendingCount.value > 0
|
||||
));
|
||||
|
||||
/**
|
||||
* 人工/库存/失败需进入明细处理;纯系统进度可不强调入口。
|
||||
* 本轮禁止切换库存工作台,入口改为由父级滚到明细。
|
||||
*/
|
||||
const showEnterInventory = computed(() => (
|
||||
manualPendingCount.value > 0
|
||||
|| systemFailedCount.value > 0
|
||||
|| inventoryPendingCount.value > 0
|
||||
));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="visible"
|
||||
class="rounded-xl border border-default bg-surface p-3 shadow-sm"
|
||||
data-testid="review-line-fulfillment-aggregate-card"
|
||||
>
|
||||
<header class="mb-2">
|
||||
<h2 class="text-sm font-semibold text-primary dark:text-slate-50">
|
||||
{{ t('chat.shippingOrderReview.lineFulfillmentAggregate.title') }}
|
||||
</h2>
|
||||
<p class="mt-0.5 text-xs text-muted">
|
||||
{{ t('chat.shippingOrderReview.lineFulfillmentAggregate.hint') }}
|
||||
</p>
|
||||
</header>
|
||||
<ul class="space-y-1 text-xs text-secondary">
|
||||
<li
|
||||
v-if="autoProgressCount > 0"
|
||||
data-testid="review-line-fulfillment-aggregate-auto-progress"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lineFulfillmentAggregate.autoProgress', {
|
||||
count: autoProgressCount,
|
||||
}) }}
|
||||
</li>
|
||||
<li
|
||||
v-if="manualPendingCount > 0"
|
||||
class="font-medium text-amber-800 dark:text-amber-200"
|
||||
data-testid="review-line-fulfillment-aggregate-manual-pending"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lineFulfillmentAggregate.manualPending', {
|
||||
count: manualPendingCount,
|
||||
}) }}
|
||||
</li>
|
||||
<li
|
||||
v-if="inventoryPendingCount > 0"
|
||||
data-testid="review-line-fulfillment-aggregate-inventory-pending"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lineFulfillmentAggregate.inventoryPending', {
|
||||
count: inventoryPendingCount,
|
||||
}) }}
|
||||
</li>
|
||||
<li
|
||||
v-if="systemFailedCount > 0"
|
||||
class="font-medium text-rose-700 dark:text-rose-300"
|
||||
data-testid="review-line-fulfillment-aggregate-system-failed"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lineFulfillmentAggregate.systemFailed', {
|
||||
count: systemFailedCount,
|
||||
}) }}
|
||||
</li>
|
||||
</ul>
|
||||
<button
|
||||
v-if="showEnterInventory"
|
||||
type="button"
|
||||
class="mt-3 w-full rounded-xl border border-default bg-surface-soft px-3 py-1.5 text-sm text-primary hover-surface-strong dark:text-slate-50"
|
||||
data-testid="review-line-fulfillment-aggregate-enter-inventory"
|
||||
@click="emit('enter-inventory')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lineFulfillmentAggregate.viewLines') }}
|
||||
</button>
|
||||
</section>
|
||||
</template>
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewLineFulfillmentDetail.spec.ts
|
||||
* 用途:锁定 UI-2 行内履约摘要字段与审计入口。
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ReviewLineFulfillmentDetail from './ReviewLineFulfillmentDetail.vue';
|
||||
import type { ShippingOrderReviewLineFulfillmentLine } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
lineFulfillmentDetail: {
|
||||
title: '行履约摘要',
|
||||
wave: '履约波次',
|
||||
task: '正式任务',
|
||||
snapshotId: '库存快照 ID',
|
||||
inventorySource: '实际库存源',
|
||||
inventoryFile: '库存文件编号',
|
||||
inventoryFileSha256: '库存文件 SHA-256',
|
||||
inventoryRow: '库存行号',
|
||||
requiredQty: '需求数量',
|
||||
availableQty: '可用数量',
|
||||
matchAttempt: '匹配 Attempt',
|
||||
matchedAt: '匹配校验时间',
|
||||
decisionSource: '决定来源',
|
||||
decisionSourceValue: {
|
||||
system: '系统自动',
|
||||
user: '人工',
|
||||
unknown: '未知',
|
||||
},
|
||||
failureReason: '自动履约失败原因',
|
||||
noFailure: '无',
|
||||
openAudit: '打开审计',
|
||||
close: '收起',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe('ReviewLineFulfillmentDetail', () => {
|
||||
it('renders wave/task/snapshot/source/failure and emits audit', async () => {
|
||||
const line: ShippingOrderReviewLineFulfillmentLine = {
|
||||
line_key: 'L1',
|
||||
inventory_snapshot_id: 42,
|
||||
inventory_checked_at: '2026-08-07T01:00:00Z',
|
||||
inventory_source_code: 'DBS_DUB',
|
||||
inventory_file_no: 'INV-001',
|
||||
inventory_file_sha256: 'a'.repeat(64),
|
||||
inventory_row_index: 17,
|
||||
required_qty: '3',
|
||||
available_qty: '8',
|
||||
match_attempt_id: 301,
|
||||
decision_source: 'system',
|
||||
auto_fulfill_error_message: 'wave_explode',
|
||||
decision: {
|
||||
wave_no: 3,
|
||||
task_id: 9,
|
||||
decision_source: 'system',
|
||||
},
|
||||
};
|
||||
const wrapper = mount(ReviewLineFulfillmentDetail, {
|
||||
props: { line, taskNo: 'SN-100' },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="review-line-fulfillment-summary"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-line-fulfillment-field-wave"]').text()).toContain('3');
|
||||
expect(wrapper.find('[data-testid="review-line-fulfillment-field-task"]').text()).toContain('SN-100');
|
||||
expect(wrapper.find('[data-testid="review-line-fulfillment-field-snapshot"]').text()).toContain('42');
|
||||
expect(wrapper.find('[data-testid="review-line-fulfillment-field-inventorySource"]').text()).toContain('DBS_DUB');
|
||||
expect(wrapper.find('[data-testid="review-line-fulfillment-field-inventoryFile"]').text()).toContain('INV-001');
|
||||
expect(wrapper.find('[data-testid="review-line-fulfillment-field-inventoryFileSha256"]').text()).toContain('a'.repeat(64));
|
||||
expect(wrapper.find('[data-testid="review-line-fulfillment-field-inventoryRow"]').text()).toContain('17');
|
||||
expect(wrapper.find('[data-testid="review-line-fulfillment-field-requiredQty"]').text()).toContain('3');
|
||||
expect(wrapper.find('[data-testid="review-line-fulfillment-field-availableQty"]').text()).toContain('8');
|
||||
expect(wrapper.find('[data-testid="review-line-fulfillment-field-matchAttempt"]').text()).toContain('301');
|
||||
expect(wrapper.find('[data-testid="review-line-fulfillment-field-decisionSource"]').text()).toContain('系统自动');
|
||||
expect(wrapper.find('[data-testid="review-line-fulfillment-field-failure"]').text()).toContain('wave_explode');
|
||||
|
||||
await wrapper.get('[data-testid="review-line-fulfillment-open-audit"]').trigger('click');
|
||||
expect(wrapper.emitted('open-audit')).toBeTruthy();
|
||||
await wrapper.get('[data-testid="review-line-fulfillment-summary-close"]').trigger('click');
|
||||
expect(wrapper.emitted('close')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewLineFulfillmentDetail.vue
|
||||
用途:订单明细行内履约摘要(查看履约详情);不进入库存工作台。
|
||||
依赖:vue-i18n、ShippingOrderReviewLineFulfillmentLine。
|
||||
逻辑:由 ShippingOrderReviewView 在展开行下方挂载;展示 wave/task/快照/匹配时间/
|
||||
决定来源/失败原因,并提供审计入口。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderReviewLineFulfillmentLine } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
line: ShippingOrderReviewLineFulfillmentLine | null | undefined;
|
||||
taskNo?: string | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'open-audit': [];
|
||||
close: [];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
/**
|
||||
* 展示用字段行。
|
||||
*/
|
||||
const rows = computed(() => {
|
||||
const line = props.line;
|
||||
const decision = line?.decision;
|
||||
const waveNo = decision?.wave_no ?? null;
|
||||
const taskNo = String(props.taskNo || '').trim()
|
||||
|| (decision?.task_id != null ? String(decision.task_id) : '');
|
||||
const source = String(line?.decision_source || decision?.decision_source || '').trim();
|
||||
const sourceKey = `chat.shippingOrderReview.lineFulfillmentDetail.decisionSourceValue.${source}`;
|
||||
const sourceLabel = source
|
||||
? (te(sourceKey) ? t(sourceKey) : source)
|
||||
: '—';
|
||||
const failure = String(line?.auto_fulfill_error_message || '').trim();
|
||||
|
||||
return [
|
||||
{
|
||||
key: 'wave',
|
||||
label: t('chat.shippingOrderReview.lineFulfillmentDetail.wave'),
|
||||
value: waveNo != null ? String(waveNo) : '—',
|
||||
},
|
||||
{
|
||||
key: 'task',
|
||||
label: t('chat.shippingOrderReview.lineFulfillmentDetail.task'),
|
||||
value: taskNo || '—',
|
||||
},
|
||||
{
|
||||
key: 'snapshot',
|
||||
label: t('chat.shippingOrderReview.lineFulfillmentDetail.snapshotId'),
|
||||
value: line?.inventory_snapshot_id != null ? String(line.inventory_snapshot_id) : '—',
|
||||
},
|
||||
{
|
||||
key: 'inventorySource',
|
||||
label: t('chat.shippingOrderReview.lineFulfillmentDetail.inventorySource'),
|
||||
value: String(line?.inventory_source_code || line?.inventory_source?.code || '').trim() || '—',
|
||||
},
|
||||
{
|
||||
key: 'inventoryFile',
|
||||
label: t('chat.shippingOrderReview.lineFulfillmentDetail.inventoryFile'),
|
||||
value: String(line?.inventory_file_no || '').trim() || '—',
|
||||
},
|
||||
{
|
||||
key: 'inventoryFileSha256',
|
||||
label: t('chat.shippingOrderReview.lineFulfillmentDetail.inventoryFileSha256'),
|
||||
value: String(line?.inventory_file_sha256 || '').trim() || '—',
|
||||
},
|
||||
{
|
||||
key: 'inventoryRow',
|
||||
label: t('chat.shippingOrderReview.lineFulfillmentDetail.inventoryRow'),
|
||||
value: line?.inventory_row_index != null ? String(line.inventory_row_index) : '—',
|
||||
},
|
||||
{
|
||||
key: 'requiredQty',
|
||||
label: t('chat.shippingOrderReview.lineFulfillmentDetail.requiredQty'),
|
||||
value: String(line?.required_qty || '').trim() || '—',
|
||||
},
|
||||
{
|
||||
key: 'availableQty',
|
||||
label: t('chat.shippingOrderReview.lineFulfillmentDetail.availableQty'),
|
||||
value: String(line?.available_qty || '').trim() || '—',
|
||||
},
|
||||
{
|
||||
key: 'matchAttempt',
|
||||
label: t('chat.shippingOrderReview.lineFulfillmentDetail.matchAttempt'),
|
||||
value: line?.match_attempt_id != null ? String(line.match_attempt_id) : '—',
|
||||
},
|
||||
{
|
||||
key: 'matchedAt',
|
||||
label: t('chat.shippingOrderReview.lineFulfillmentDetail.matchedAt'),
|
||||
value: formatTime(line?.inventory_checked_at),
|
||||
},
|
||||
{
|
||||
key: 'decisionSource',
|
||||
label: t('chat.shippingOrderReview.lineFulfillmentDetail.decisionSource'),
|
||||
value: sourceLabel,
|
||||
},
|
||||
{
|
||||
key: 'failure',
|
||||
label: t('chat.shippingOrderReview.lineFulfillmentDetail.failureReason'),
|
||||
value: failure || t('chat.shippingOrderReview.lineFulfillmentDetail.noFailure'),
|
||||
emphasize: Boolean(failure),
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
/**
|
||||
* 格式化匹配/校验时间。
|
||||
*/
|
||||
function formatTime(value: string | null | undefined): string {
|
||||
if (!value) return '—';
|
||||
const date = new Date(value);
|
||||
return Number.isNaN(date.getTime()) ? String(value) : date.toLocaleString();
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="rounded-md border border-default bg-slate-50/80 px-3 py-2 text-xs dark:bg-slate-950/50"
|
||||
data-testid="review-line-fulfillment-summary"
|
||||
role="region"
|
||||
:aria-label="t('chat.shippingOrderReview.lineFulfillmentDetail.title')"
|
||||
>
|
||||
<div class="mb-2 flex items-center justify-between gap-2">
|
||||
<p class="font-medium text-secondary">
|
||||
{{ t('chat.shippingOrderReview.lineFulfillmentDetail.title') }}
|
||||
</p>
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-default px-2 py-0.5 text-[11px] text-sky-700 hover:bg-white dark:text-sky-300"
|
||||
data-testid="review-line-fulfillment-open-audit"
|
||||
@click="emit('open-audit')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lineFulfillmentDetail.openAudit') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded px-2 py-0.5 text-[11px] text-muted hover-surface-strong"
|
||||
data-testid="review-line-fulfillment-summary-close"
|
||||
@click="emit('close')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lineFulfillmentDetail.close') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<dl class="grid gap-1.5 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<div
|
||||
v-for="row in rows"
|
||||
:key="row.key"
|
||||
class="min-w-0 rounded bg-white/70 px-2 py-1.5 dark:bg-slate-900/60"
|
||||
:data-testid="`review-line-fulfillment-field-${row.key}`"
|
||||
>
|
||||
<dt class="text-[10px] font-medium text-muted">{{ row.label }}</dt>
|
||||
<dd
|
||||
class="mt-0.5 break-words text-[11px] text-primary"
|
||||
:class="row.emphasize ? 'font-medium text-rose-700 dark:text-rose-300' : ''"
|
||||
>
|
||||
{{ row.value }}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewLineInventoryOps.spec.ts
|
||||
* 用途:锁定明细行不渲染库存重试,只保留行生命周期关闭动作。
|
||||
*/
|
||||
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ReviewLineInventoryOps from './ReviewLineInventoryOps.vue';
|
||||
import type { ShippingOrderReviewLineFulfillmentLine } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
lineOps: { moreActions: '更多操作' },
|
||||
fulfillmentDecision: {
|
||||
closeLine: '关闭该明细',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
function mountOps(line: Partial<ShippingOrderReviewLineFulfillmentLine>, extra: Record<string, unknown> = {}) {
|
||||
return mount(ReviewLineInventoryOps, {
|
||||
props: {
|
||||
line: line as ShippingOrderReviewLineFulfillmentLine,
|
||||
editable: true,
|
||||
...extra,
|
||||
},
|
||||
attachTo: document.body,
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
describe('ReviewLineInventoryOps', () => {
|
||||
it('does not show generic retry even when retryable', async () => {
|
||||
const wrapper = mountOps({
|
||||
retryable: true,
|
||||
line_allowed_actions: [],
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-line-retry"]').exists()).toBe(false);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('keeps inventory actions out of the line even when present', () => {
|
||||
const wrapper = mountOps({
|
||||
retryable: false,
|
||||
inventory_allowed_actions: ['retry_inventory_preparation', 'retry_inventory_matching'],
|
||||
line_allowed_actions: ['close_unfulfillable'],
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-line-retry"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-line-more-actions"]').exists()).toBe(true);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('does not add a retry while task running', () => {
|
||||
const wrapper = mountOps({
|
||||
retryable: true,
|
||||
line_allowed_actions: [],
|
||||
}, { taskRunning: true });
|
||||
expect(wrapper.find('[data-testid="review-line-retry"]').exists()).toBe(false);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('puts close under more actions', async () => {
|
||||
const wrapper = mountOps({
|
||||
retryable: false,
|
||||
line_allowed_actions: ['close_unfulfillable'],
|
||||
});
|
||||
await wrapper.get('[data-testid="review-line-more-actions"]').trigger('click');
|
||||
expect(document.querySelector('[data-testid="review-line-decide-close"]')).toBeTruthy();
|
||||
wrapper.unmount();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewLineInventoryOps.vue
|
||||
用途:明细行只展示行生命周期操作(关闭无法履约)。
|
||||
依赖:vue-i18n、lucide、line.line_allowed_actions。
|
||||
逻辑:库存重新获取/匹配属于任务 Gate,禁止在明细行降级为笼统「重试」。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { MoreHorizontal } from 'lucide-vue-next';
|
||||
import type { ShippingOrderReviewLineFulfillmentLine } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
line: ShippingOrderReviewLineFulfillmentLine | null | undefined;
|
||||
editable: boolean;
|
||||
busy?: boolean;
|
||||
/** 任务整体 queued/running 时禁用行级写 */
|
||||
taskRunning?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'close-line': [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const moreMenuOpen = ref(false);
|
||||
const moreBtnRef = ref<HTMLElement | null>(null);
|
||||
const moreMenuStyle = ref<Record<string, string>>({});
|
||||
|
||||
const canClose = computed(() => (
|
||||
[...(props.line?.line_allowed_actions || [])].includes('close_unfulfillable')
|
||||
));
|
||||
const showMore = computed(() => canClose.value);
|
||||
|
||||
/**
|
||||
* 定位更多菜单。
|
||||
*/
|
||||
function placeMenu(anchor: HTMLElement | null) {
|
||||
if (!anchor || typeof window === 'undefined') return;
|
||||
const rect = anchor.getBoundingClientRect();
|
||||
const width = 168;
|
||||
const left = Math.max(8, Math.min(rect.right - width, window.innerWidth - width - 8));
|
||||
moreMenuStyle.value = {
|
||||
position: 'fixed',
|
||||
top: `${Math.round(rect.bottom + 4)}px`,
|
||||
left: `${Math.round(left)}px`,
|
||||
width: `${width}px`,
|
||||
zIndex: '80',
|
||||
};
|
||||
}
|
||||
|
||||
function closeMenus() {
|
||||
moreMenuOpen.value = false;
|
||||
}
|
||||
|
||||
function onDocPointerDown(event: Event) {
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (!target) return;
|
||||
if (target.closest?.('[data-testid="review-line-more-menu"]')) return;
|
||||
if (target.closest?.('[data-testid="review-line-more-actions"]')) return;
|
||||
closeMenus();
|
||||
}
|
||||
|
||||
async function toggleMoreMenu() {
|
||||
moreMenuOpen.value = !moreMenuOpen.value;
|
||||
if (moreMenuOpen.value) {
|
||||
await nextTick();
|
||||
placeMenu(moreBtnRef.value);
|
||||
}
|
||||
}
|
||||
|
||||
function onCloseLine() {
|
||||
closeMenus();
|
||||
emit('close-line');
|
||||
}
|
||||
|
||||
if (typeof document !== 'undefined') {
|
||||
document.addEventListener('pointerdown', onDocPointerDown, true);
|
||||
}
|
||||
onBeforeUnmount(() => {
|
||||
if (typeof document === 'undefined') return;
|
||||
document.removeEventListener('pointerdown', onDocPointerDown, true);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="relative inline-flex items-center gap-0.5">
|
||||
<button
|
||||
v-if="showMore"
|
||||
ref="moreBtnRef"
|
||||
type="button"
|
||||
class="rounded p-1.5 hover-surface-strong disabled:opacity-50"
|
||||
data-testid="review-line-more-actions"
|
||||
:disabled="!editable || busy || taskRunning"
|
||||
:aria-label="t('chat.shippingOrderReview.lineOps.moreActions')"
|
||||
:title="t('chat.shippingOrderReview.lineOps.moreActions')"
|
||||
:aria-expanded="moreMenuOpen"
|
||||
@click="toggleMoreMenu"
|
||||
>
|
||||
<MoreHorizontal class="h-3.5 w-3.5" aria-hidden="true" />
|
||||
</button>
|
||||
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="moreMenuOpen && showMore"
|
||||
class="rounded-md border border-default bg-surface py-1 shadow-lg"
|
||||
role="menu"
|
||||
data-testid="review-line-more-menu"
|
||||
:style="moreMenuStyle"
|
||||
>
|
||||
<button
|
||||
v-if="canClose"
|
||||
type="button"
|
||||
class="block w-full px-3 py-2 text-left text-xs text-rose-700 hover:bg-rose-50 dark:text-rose-300 dark:hover:bg-rose-950/40"
|
||||
role="menuitem"
|
||||
data-testid="review-line-decide-close"
|
||||
@click="onCloseLine"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.fulfillmentDecision.closeLine') }}
|
||||
</button>
|
||||
</div>
|
||||
</Teleport>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,85 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewLlmEvidenceComparison.vue
|
||||
用途:三列对比当前草稿、AI 建议与原文证据。
|
||||
依赖:vue-i18n、ShippingOrderReviewEvidence / LlmSuggestion 类型。
|
||||
逻辑:嵌入 ReviewLlmSuggestionDialog;逐字失败码与后端 value_not_in_evidence 对齐;只读展示。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderReviewEvidence, ShippingOrderReviewLlmSuggestion } from '../../types/shipping.api.types';
|
||||
|
||||
/** 三列对比入参;建议/证据可空,标签缺省为空串。 */
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
draftValue?: unknown;
|
||||
suggestion?: ShippingOrderReviewLlmSuggestion | null;
|
||||
evidence?: ShippingOrderReviewEvidence | null;
|
||||
fieldLabel?: string;
|
||||
}>(),
|
||||
{
|
||||
fieldLabel: '',
|
||||
},
|
||||
);
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const suggestedValue = computed(() => props.suggestion?.suggested_value ?? '-');
|
||||
const draftDisplay = computed(() => {
|
||||
const value = props.draftValue;
|
||||
if (value === null || value === undefined || value === '') return '-';
|
||||
return String(value);
|
||||
});
|
||||
const evidenceQuote = computed(() => props.evidence?.quote || '-');
|
||||
const evidenceLocation = computed(() => {
|
||||
const page = props.evidence?.page_no;
|
||||
const cell = props.evidence?.cell_id;
|
||||
if (page && cell) return t('chat.shippingOrderReview.llmSuggestion.evidenceAtCell', { page, cell });
|
||||
if (page) return t('chat.shippingOrderReview.evidenceAt', { page });
|
||||
return t('chat.shippingOrderReview.llmSuggestion.noEvidenceCoords');
|
||||
});
|
||||
/** 与后端 rejection_reason 对齐;含历史别名 suggested_value_not_in_evidence。 */
|
||||
const VERBATIM_FAIL_CODES = new Set([
|
||||
'value_not_in_evidence',
|
||||
'suggested_value_not_in_evidence',
|
||||
'empty_suggestion',
|
||||
'field_id_mismatch',
|
||||
]);
|
||||
const verbatimOk = computed(() => {
|
||||
if (String(props.suggestion?.status || '') === 'validation_failed') return false;
|
||||
const issues = props.suggestion?.validation_issues || [];
|
||||
return !issues.some((item) => VERBATIM_FAIL_CODES.has(String(item.code || '')));
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="grid gap-3 md:grid-cols-3" data-testid="review-llm-evidence-comparison">
|
||||
<div class="rounded-lg border border-default bg-surface-soft p-3">
|
||||
<p class="text-xs font-medium uppercase tracking-wide text-muted">
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.currentDraft') }}
|
||||
</p>
|
||||
<p class="mt-2 text-sm font-semibold text-primary">{{ props.fieldLabel }}</p>
|
||||
<p class="mt-1 text-sm text-secondary">{{ draftDisplay }}</p>
|
||||
</div>
|
||||
<div class="rounded-lg border border-indigo-200 bg-indigo-50/60 p-3">
|
||||
<p class="text-xs font-medium uppercase tracking-wide text-indigo-600">
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.aiSuggestion') }}
|
||||
</p>
|
||||
<p class="mt-2 text-sm font-semibold text-primary">{{ suggestedValue }}</p>
|
||||
<p class="mt-1 text-xs" :class="verbatimOk ? 'text-emerald-700' : 'text-amber-700'">
|
||||
{{
|
||||
verbatimOk
|
||||
? t('chat.shippingOrderReview.llmSuggestion.verbatimOk')
|
||||
: t('chat.shippingOrderReview.llmSuggestion.verbatimFailed')
|
||||
}}
|
||||
</p>
|
||||
</div>
|
||||
<div class="rounded-lg border border-default bg-surface p-3">
|
||||
<p class="text-xs font-medium uppercase tracking-wide text-muted">
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.sourceEvidence') }}
|
||||
</p>
|
||||
<p class="mt-2 text-sm text-primary">{{ evidenceQuote }}</p>
|
||||
<p class="mt-1 text-xs text-muted">{{ evidenceLocation }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,233 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewLlmSuggestionDialog.vue
|
||||
用途:复核工作台内 AI 建议对比与裁决对话框。
|
||||
依赖:vue-i18n、ReviewLlmEvidenceComparison、ShippingOrderReview* 类型。
|
||||
逻辑:接受可备注;修改/拒绝必须填写原因;validation_failed 仅允许拒绝;
|
||||
含 dialog 语义、Escape、焦点陷阱与恢复。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type {
|
||||
ShippingOrderReviewEvidence,
|
||||
ShippingOrderReviewLlmSuggestion,
|
||||
} from '../../types/shipping.api.types';
|
||||
import ReviewLlmEvidenceComparison from './ReviewLlmEvidenceComparison.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
suggestion?: ShippingOrderReviewLlmSuggestion | null;
|
||||
evidence?: ShippingOrderReviewEvidence | null;
|
||||
draftValue?: unknown;
|
||||
/** 订单字段展示名;缺省时使用通用业务名称。 */
|
||||
fieldLabel?: string;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
decide: [payload: { decision: 'accept' | 'modify' | 'reject'; reason: string; value?: unknown }];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const decision = ref<'accept' | 'modify' | 'reject'>('accept');
|
||||
const reason = ref('');
|
||||
const modifiedValue = ref('');
|
||||
const panelRef = ref<HTMLElement | null>(null);
|
||||
const previousFocus = ref<HTMLElement | null>(null);
|
||||
|
||||
/** 逐字验证失败时仅允许拒绝,禁止 accept/modify。 */
|
||||
const rejectOnly = computed(() => String(props.suggestion?.status || '') === 'validation_failed');
|
||||
|
||||
const displayFieldLabel = computed(() =>
|
||||
String(props.fieldLabel || t('chat.shippingOrderReview.unknownField')).trim(),
|
||||
);
|
||||
|
||||
const evidenceLevelText = computed(() => {
|
||||
const code = String(props.suggestion?.evidence_level || 'L1_field').trim() || 'L1_field';
|
||||
const key = `chat.shippingOrderReview.llmSuggestion.evidenceLevel.${code}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderReview.llmSuggestion.evidenceLevel.unknown');
|
||||
});
|
||||
|
||||
const canSubmit = computed(() => {
|
||||
if (decision.value === 'accept') return !rejectOnly.value;
|
||||
return Boolean(reason.value.trim());
|
||||
});
|
||||
|
||||
/**
|
||||
* 提交裁决;修改/拒绝无原因时按钮禁用。
|
||||
*/
|
||||
function submit() {
|
||||
if (!canSubmit.value) return;
|
||||
emit('decide', {
|
||||
decision: decision.value,
|
||||
reason: reason.value.trim(),
|
||||
value: decision.value === 'modify' ? modifiedValue.value : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭弹窗并通知父级。
|
||||
*/
|
||||
function close() {
|
||||
emit('close');
|
||||
}
|
||||
|
||||
/**
|
||||
* 收集面板内可聚焦控件,供焦点陷阱使用。
|
||||
*/
|
||||
function focusableElements(): HTMLElement[] {
|
||||
const root = panelRef.value;
|
||||
if (!root) return [];
|
||||
return Array.from(
|
||||
root.querySelectorAll<HTMLElement>(
|
||||
'button:not([disabled]), input:not([disabled]), textarea:not([disabled]), [href], [tabindex]:not([tabindex="-1"])',
|
||||
),
|
||||
).filter((el) => !el.hasAttribute('disabled') && el.tabIndex !== -1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开时聚焦首个可交互控件;关闭时恢复触发焦点。
|
||||
*/
|
||||
async function restoreOrCaptureFocus(open: boolean) {
|
||||
if (typeof document === 'undefined') return;
|
||||
if (open) {
|
||||
previousFocus.value = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||
await nextTick();
|
||||
const first = focusableElements()[0];
|
||||
first?.focus();
|
||||
return;
|
||||
}
|
||||
previousFocus.value?.focus?.();
|
||||
previousFocus.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape 关闭;Tab 在对话框内循环,防止焦点落到遮罩后的复核页。
|
||||
*/
|
||||
function onKeydown(event: KeyboardEvent) {
|
||||
if (!props.open) return;
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
close();
|
||||
return;
|
||||
}
|
||||
if (event.key !== 'Tab') return;
|
||||
const nodes = focusableElements();
|
||||
const first = nodes[0];
|
||||
const last = nodes[nodes.length - 1];
|
||||
// [STEP] noUncheckedIndexedAccess:空数组或越界时 first/last 为 undefined,禁止直接 .focus()。
|
||||
if (!first || !last) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
const active = document.activeElement as HTMLElement | null;
|
||||
if (event.shiftKey && active === first) {
|
||||
event.preventDefault();
|
||||
last.focus();
|
||||
} else if (!event.shiftKey && active === last) {
|
||||
event.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
(open) => {
|
||||
if (open) {
|
||||
decision.value = rejectOnly.value ? 'reject' : 'accept';
|
||||
reason.value = '';
|
||||
modifiedValue.value = String(props.suggestion?.suggested_value ?? '');
|
||||
}
|
||||
void restoreOrCaptureFocus(open);
|
||||
if (typeof document === 'undefined') return;
|
||||
if (open) document.addEventListener('keydown', onKeydown);
|
||||
else document.removeEventListener('keydown', onKeydown);
|
||||
},
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (typeof document !== 'undefined') document.removeEventListener('keydown', onKeydown);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-label="t('chat.shippingOrderReview.llmSuggestion.dialogTitle')"
|
||||
data-testid="review-llm-suggestion-dialog"
|
||||
@click.self="close"
|
||||
>
|
||||
<div
|
||||
ref="panelRef"
|
||||
class="max-h-[80vh] w-full max-w-3xl overflow-auto rounded-lg bg-surface p-4 shadow-lg"
|
||||
data-testid="review-llm-suggestion-panel"
|
||||
>
|
||||
<h3 class="text-base font-semibold">{{ t('chat.shippingOrderReview.llmSuggestion.dialogTitle') }}</h3>
|
||||
<p class="mt-1 text-xs text-muted">
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.dialogHint') }}
|
||||
· {{ evidenceLevelText }}
|
||||
</p>
|
||||
|
||||
<div class="mt-4">
|
||||
<ReviewLlmEvidenceComparison
|
||||
:draft-value="draftValue"
|
||||
:suggestion="suggestion"
|
||||
:evidence="evidence"
|
||||
:field-label="displayFieldLabel"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 flex flex-wrap gap-4 text-sm">
|
||||
<label v-if="!rejectOnly" class="inline-flex items-center gap-1">
|
||||
<input v-model="decision" type="radio" value="accept" />
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.decisions.accept') }}
|
||||
</label>
|
||||
<label v-if="!rejectOnly" class="inline-flex items-center gap-1">
|
||||
<input v-model="decision" type="radio" value="modify" />
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.decisions.modify') }}
|
||||
</label>
|
||||
<label class="inline-flex items-center gap-1">
|
||||
<input v-model="decision" type="radio" value="reject" />
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.decisions.reject') }}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<input
|
||||
v-if="decision === 'modify'"
|
||||
v-model="modifiedValue"
|
||||
class="mt-2 w-full rounded border p-2 text-sm"
|
||||
:placeholder="t('chat.shippingOrderReview.llmSuggestion.modifiedValue')"
|
||||
/>
|
||||
<textarea
|
||||
v-model="reason"
|
||||
class="mt-2 w-full rounded border p-2 text-sm"
|
||||
rows="2"
|
||||
:placeholder="
|
||||
decision === 'accept'
|
||||
? t('chat.shippingOrderReview.llmSuggestion.noteOptional')
|
||||
: t('chat.shippingOrderReview.llmSuggestion.reasonRequired')
|
||||
"
|
||||
/>
|
||||
|
||||
<div class="mt-3 flex justify-end gap-2">
|
||||
<button type="button" class="rounded border px-3 py-1 text-sm" @click="close">
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.cancel') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border px-3 py-1 text-sm disabled:opacity-50"
|
||||
:disabled="!canSubmit"
|
||||
data-testid="review-llm-submit-decision"
|
||||
@click="submit"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.submit') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
@@ -0,0 +1,78 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewLlmSuggestionDrawer.vue
|
||||
用途:字段级 AI 建议按需抽屉外壳;内容复用 ReviewLlmSuggestionPanel。
|
||||
依赖:vue-i18n、ReviewLlmSuggestionPanel。
|
||||
逻辑:无聚焦字段时父级不打开;AI 只能建议,裁决仍走既有保存/审计流程。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import ReviewLlmSuggestionPanel from './ReviewLlmSuggestionPanel.vue';
|
||||
import type {
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewEvidence,
|
||||
ShippingOrderReviewLlmAdjudicationPayload,
|
||||
ShippingOrderReviewLlmSuggestion,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
defineProps<{
|
||||
open: boolean;
|
||||
activeCase?: ShippingOrderReviewCase | null;
|
||||
evidence?: ShippingOrderReviewEvidence[] | null;
|
||||
editable?: boolean;
|
||||
saving?: boolean;
|
||||
suggestions?: ShippingOrderReviewLlmSuggestion[];
|
||||
suggestionLoading?: boolean;
|
||||
focusedFieldId?: string | null;
|
||||
focusedLineKey?: string | null;
|
||||
draftValue?: unknown;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
'request-suggestion': [];
|
||||
adjudicate: [payload: {
|
||||
suggestion: ShippingOrderReviewLlmSuggestion;
|
||||
body: ShippingOrderReviewLlmAdjudicationPayload;
|
||||
}];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-40 flex justify-end bg-slate-900/30"
|
||||
data-testid="review-llm-suggestion-drawer"
|
||||
@click.self="emit('close')"
|
||||
>
|
||||
<aside class="flex h-full w-full max-w-lg flex-col bg-surface shadow-xl">
|
||||
<header class="flex items-center justify-between gap-2 border-b border-default px-4 py-3">
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.llmSuggestion.panelTitle') }}</h2>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-default px-2 py-1 text-xs hover-surface-soft"
|
||||
data-testid="review-llm-drawer-close"
|
||||
@click="emit('close')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workbench.closePdf') }}
|
||||
</button>
|
||||
</header>
|
||||
<div class="min-h-0 flex-1 overflow-y-auto p-4">
|
||||
<ReviewLlmSuggestionPanel
|
||||
:active-case="activeCase"
|
||||
:evidence="evidence"
|
||||
:editable="editable"
|
||||
:saving="saving"
|
||||
:suggestions="suggestions"
|
||||
:suggestion-loading="suggestionLoading"
|
||||
:focused-field-id="focusedFieldId"
|
||||
:focused-line-key="focusedLineKey"
|
||||
:draft-value="draftValue"
|
||||
@request-suggestion="emit('request-suggestion')"
|
||||
@adjudicate="emit('adjudicate', $event)"
|
||||
/>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</template>
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewLlmSuggestionPanel.spec.ts
|
||||
* 用途:锁定 LLM 建议面板的草稿对比与裁决弹窗契约。
|
||||
* 依赖:vitest、@vue/test-utils、vue-i18n。
|
||||
* 逻辑:按建议字段解析 header 草稿值;弹窗含 dialog 语义;修改/拒绝无原因不可提交。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { flushPromises, mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ReviewLlmSuggestionPanel from './ReviewLlmSuggestionPanel.vue';
|
||||
import type {
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewLlmSuggestion,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const messages = {
|
||||
en: {
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
unknownField: 'Order field',
|
||||
llmSuggestion: {
|
||||
panelTitle: 'AI suggestion',
|
||||
panelHint: 'Minimal evidence only',
|
||||
request: 'Request',
|
||||
requesting: 'Requesting',
|
||||
review: 'Review',
|
||||
empty: 'No suggestions',
|
||||
scope: 'Scope {level}',
|
||||
dialogTitle: 'AI suggestion dialog',
|
||||
dialogHint: 'Compare draft and evidence',
|
||||
currentDraft: 'Current draft',
|
||||
aiSuggestion: 'AI suggestion',
|
||||
sourceEvidence: 'Evidence',
|
||||
verbatimOk: 'OK',
|
||||
verbatimFailed: 'Failed',
|
||||
unavailableDisabled: 'AI suggestions are disabled in this environment.',
|
||||
unavailableProvider: 'AI suggestion service is unavailable. Try again later.',
|
||||
evidenceAtCell: 'page {page} {cell}',
|
||||
noEvidenceCoords: 'no coords',
|
||||
cancel: 'Cancel',
|
||||
submit: 'Submit',
|
||||
modifiedValue: 'Modified',
|
||||
noteOptional: 'Note',
|
||||
reasonRequired: 'Reason required',
|
||||
evidenceLevel: { L1_field: 'Current field content', unknown: 'Relevant document content' },
|
||||
status: {
|
||||
idle: 'Idle',
|
||||
pending: 'Pending',
|
||||
validated: 'Validated',
|
||||
provider_unavailable: 'Unavailable',
|
||||
unknown: 'Status pending confirmation',
|
||||
},
|
||||
decisions: { accept: 'Accept', modify: 'Modify', reject: 'Reject' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* 构造最小 Case + 建议夹具。
|
||||
*/
|
||||
function fixtures() {
|
||||
const suggestion: ShippingOrderReviewLlmSuggestion = {
|
||||
suggestion_no: 'RSG-TEST001',
|
||||
field_id: 'fld-po',
|
||||
scope: 'header',
|
||||
evidence_level: 'L1_field',
|
||||
status: 'validated',
|
||||
suggested_value: 'PO-NEW',
|
||||
validation_issues: [],
|
||||
};
|
||||
const activeCase = {
|
||||
case_no: 'SRC-1',
|
||||
draft: {
|
||||
draft_version: 3,
|
||||
header_values: {
|
||||
values: { 'fld-po': { value: 'PO-OLD', source: 'manual' } },
|
||||
machine_fields: [{ field_id: 'fld-po', value: 'PO-MACHINE' }],
|
||||
},
|
||||
lines: [],
|
||||
},
|
||||
} as unknown as ShippingOrderReviewCase;
|
||||
return { suggestion, activeCase };
|
||||
}
|
||||
|
||||
/**
|
||||
* 挂载建议面板。
|
||||
*/
|
||||
function mountPanel(overrides?: {
|
||||
suggestions?: ShippingOrderReviewLlmSuggestion[];
|
||||
editable?: boolean;
|
||||
focusedFieldId?: string;
|
||||
}) {
|
||||
const { suggestion, activeCase } = fixtures();
|
||||
const i18n = createI18n({ legacy: false, locale: 'en', messages });
|
||||
return mount(ReviewLlmSuggestionPanel, {
|
||||
props: {
|
||||
activeCase,
|
||||
evidence: [{
|
||||
evidence_id: 'e1',
|
||||
field_id: 'fld-po',
|
||||
quote: 'PO-NEW',
|
||||
page_no: 1,
|
||||
source: 'layout',
|
||||
highlight_quality: 'unavailable',
|
||||
highlight_source: 'machine_extraction',
|
||||
highlight_bbox: null,
|
||||
coordinate_status: 'unavailable',
|
||||
coordinate_issue_codes: ['coordinate_missing'],
|
||||
evidence_ref: null,
|
||||
token_ids: [],
|
||||
value_match_status: 'matched',
|
||||
}],
|
||||
editable: overrides?.editable ?? true,
|
||||
saving: false,
|
||||
suggestions: overrides?.suggestions ?? [suggestion],
|
||||
suggestionLoading: false,
|
||||
focusedFieldId: overrides?.focusedFieldId ?? 'fld-po',
|
||||
focusedLineKey: null,
|
||||
draftValue: null,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
attachTo: document.body,
|
||||
});
|
||||
}
|
||||
|
||||
describe('ReviewLlmSuggestionPanel', () => {
|
||||
it('opens dialog with current draft value for three-way compare', async () => {
|
||||
const wrapper = mountPanel();
|
||||
await wrapper.get('ul button').trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
const dialog = document.querySelector('[data-testid="review-llm-suggestion-dialog"]');
|
||||
expect(dialog).not.toBeNull();
|
||||
expect(dialog?.getAttribute('role')).toBe('dialog');
|
||||
expect(dialog?.getAttribute('aria-modal')).toBe('true');
|
||||
expect(document.body.textContent).toContain('PO-OLD');
|
||||
expect(document.body.textContent).toContain('PO-NEW');
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('blocks submit for reject without reason and closes on Escape', async () => {
|
||||
const wrapper = mountPanel();
|
||||
await wrapper.get('ul button').trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
const radios = Array.from(document.querySelectorAll<HTMLInputElement>('input[type="radio"]'));
|
||||
const reject = radios.find((el) => el.value === 'reject');
|
||||
expect(reject).toBeTruthy();
|
||||
reject!.checked = true;
|
||||
reject!.dispatchEvent(new Event('change'));
|
||||
await flushPromises();
|
||||
|
||||
const submit = document.querySelector<HTMLButtonElement>('[data-testid="review-llm-submit-decision"]');
|
||||
expect(submit?.disabled).toBe(true);
|
||||
|
||||
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[data-testid="review-llm-suggestion-dialog"]')).toBeNull();
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('keeps validation_failed suggestions out of accept list and reject-only in dialog', async () => {
|
||||
const failed: ShippingOrderReviewLlmSuggestion = {
|
||||
suggestion_no: 'RSG-FAIL',
|
||||
field_id: 'fld-po',
|
||||
scope: 'header',
|
||||
evidence_level: 'L1_field',
|
||||
status: 'validation_failed',
|
||||
suggested_value: 'PO-BAD',
|
||||
validation_issues: [{ code: 'value_not_in_evidence', severity: 'blocking' }],
|
||||
};
|
||||
const wrapper = mountPanel({ suggestions: [failed] });
|
||||
expect(wrapper.find('ul:not([data-testid="review-llm-failed-list"])').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-llm-failed-list"]').exists()).toBe(true);
|
||||
|
||||
await wrapper.get('[data-testid="review-llm-open-failed"]').trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
const radios = Array.from(document.querySelectorAll<HTMLInputElement>('input[type="radio"]'));
|
||||
expect(radios.map((el) => el.value)).toEqual(['reject']);
|
||||
expect(document.body.textContent).toContain('Failed');
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('does not expose unknown field id or evidence level', async () => {
|
||||
const unknown: ShippingOrderReviewLlmSuggestion = {
|
||||
suggestion_no: 'RSG-UNKNOWN',
|
||||
field_id: 'internal-field-id',
|
||||
scope: 'header',
|
||||
evidence_level: 'internal_evidence_level',
|
||||
status: 'validated',
|
||||
suggested_value: 'PO-NEW',
|
||||
validation_issues: [],
|
||||
};
|
||||
const wrapper = mountPanel({ suggestions: [unknown], focusedFieldId: 'internal-field-id' });
|
||||
expect(wrapper.text()).toContain('Order field');
|
||||
expect(wrapper.text()).not.toContain('internal-field-id');
|
||||
await wrapper.get('ul button').trigger('click');
|
||||
await flushPromises();
|
||||
expect(document.body.textContent).toContain('Relevant document content');
|
||||
expect(wrapper.text()).not.toContain('internal_evidence_level');
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('shows a visible disabled message when Dify was not called', () => {
|
||||
const unavailable: ShippingOrderReviewLlmSuggestion = {
|
||||
suggestion_no: 'RSG-DISABLED',
|
||||
field_id: 'fld-po',
|
||||
scope: 'header',
|
||||
evidence_level: 'L1_field',
|
||||
status: 'provider_unavailable',
|
||||
error_code: 'SHIPPING.REVIEW_LLM_DISABLED',
|
||||
validation_issues: [],
|
||||
};
|
||||
const wrapper = mountPanel({ suggestions: [unavailable] });
|
||||
|
||||
expect(wrapper.get('[data-testid="review-llm-provider-unavailable"]').text())
|
||||
.toContain('AI suggestions are disabled in this environment.');
|
||||
expect(wrapper.text()).not.toContain('No suggestions');
|
||||
wrapper.unmount();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,356 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewLlmSuggestionPanel.vue
|
||||
用途:AI 建议列表与裁决内容(布局重构后作为抽屉内容组件,非常驻主区大卡片)。
|
||||
依赖:vue-i18n、ReviewLlmSuggestionDialog、ShippingOrderReview* 类型。
|
||||
逻辑:由 ReviewLlmSuggestionDrawer 挂载;请求须用户主动触发;仅 validated 可接受;
|
||||
validation_failed 仅可拒绝;provider_unavailable 明示原因;证据按 field_id + draft_line_id/line_index 绑定。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type {
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewEvidence,
|
||||
ShippingOrderReviewLlmAdjudicationPayload,
|
||||
ShippingOrderReviewLlmSuggestion,
|
||||
} from '../../types/shipping.api.types';
|
||||
import ReviewLlmSuggestionDialog from './ReviewLlmSuggestionDialog.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
activeCase?: ShippingOrderReviewCase | null;
|
||||
evidence?: ShippingOrderReviewEvidence[] | null;
|
||||
editable?: boolean;
|
||||
saving?: boolean;
|
||||
suggestions?: ShippingOrderReviewLlmSuggestion[];
|
||||
suggestionLoading?: boolean;
|
||||
focusedFieldId?: string | null;
|
||||
focusedLineKey?: string | null;
|
||||
/** 父级传入的聚焦字段草稿;弹窗优先用建议字段自身解析值。 */
|
||||
draftValue?: unknown;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
requestSuggestion: [];
|
||||
adjudicate: [payload: {
|
||||
suggestion: ShippingOrderReviewLlmSuggestion;
|
||||
body: ShippingOrderReviewLlmAdjudicationPayload;
|
||||
}];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const dialogOpen = ref(false);
|
||||
const selected = ref<ShippingOrderReviewLlmSuggestion | null>(null);
|
||||
|
||||
/** 仅已通过逐字校验的建议可进入 accept/modify 待裁决列表。 */
|
||||
const pendingSuggestions = computed(() =>
|
||||
(props.suggestions || []).filter((item) => String(item.status || '') === 'validated' && !item.decision),
|
||||
);
|
||||
|
||||
/** 验证失败建议仅可查看/拒绝,不进入可接受列表。 */
|
||||
const failedSuggestions = computed(() =>
|
||||
(props.suggestions || []).filter((item) => String(item.status || '') === 'validation_failed' && !item.decision),
|
||||
);
|
||||
|
||||
/** Provider 未调用或调用失败的记录必须明确展示,避免用户把静默空态误认为 AI 已执行。 */
|
||||
const unavailableSuggestions = computed(() =>
|
||||
(props.suggestions || []).filter((item) => String(item.status || '') === 'provider_unavailable'),
|
||||
);
|
||||
|
||||
/** 前门禁失败(未调用 Dify)的记录必须明确展示,错误码指向 i18n errors.json;避免用户误认为 AI 已跑过。 */
|
||||
const gatedFailedSuggestions = computed(() =>
|
||||
(props.suggestions || []).filter((item) => String(item.status || '') === 'gated_failed'),
|
||||
);
|
||||
|
||||
/** 将 Provider 失败码转成可执行的业务提示,不向用户暴露底层地址或异常正文。 */
|
||||
function unavailableMessage(item?: ShippingOrderReviewLlmSuggestion): string {
|
||||
if (String(item?.error_code || '') === 'SHIPPING.REVIEW_LLM_DISABLED') {
|
||||
return t('chat.shippingOrderReview.llmSuggestion.unavailableDisabled');
|
||||
}
|
||||
return t('chat.shippingOrderReview.llmSuggestion.unavailableProvider');
|
||||
}
|
||||
|
||||
/**
|
||||
* 门禁失败 short 提示(一层标题):用 errors.json 本地化;缺失时给通用提示避免裸 code。
|
||||
* 完全消费后端投影的 item.error_code,前端绝对不推导「为什么失败」。
|
||||
*/
|
||||
function gatedShortMessage(item: ShippingOrderReviewLlmSuggestion): string {
|
||||
const code = String(item.error_code || '');
|
||||
const key = `errors.${code}`;
|
||||
if (code && te(key)) return t(key);
|
||||
return t('chat.shippingOrderReview.llmSuggestion.status.gated_failed');
|
||||
}
|
||||
|
||||
/**
|
||||
* 门禁失败 detail 提示(二层详情):查 errors.json 的 `${code}Detail` 或通用 hint。
|
||||
* 同样不推导原因,纯 i18n 查表。
|
||||
*/
|
||||
function gatedDetailMessage(item: ShippingOrderReviewLlmSuggestion): string | null {
|
||||
const code = String(item.error_code || '');
|
||||
if (!code) return null;
|
||||
const detailKey = `errors.${code}Detail`;
|
||||
if (te(detailKey)) return t(detailKey);
|
||||
const hintKey = `chat.shippingOrderReview.llmSuggestion.gateDetail.${code.replace(/^SHIPPING\./, '')}`;
|
||||
if (te(hintKey)) return t(hintKey);
|
||||
return null;
|
||||
}
|
||||
|
||||
const statusLabel = computed(() => {
|
||||
if (props.suggestionLoading) return t('chat.shippingOrderReview.llmSuggestion.status.pending');
|
||||
const latest = (props.suggestions || [])[0];
|
||||
const code = String(latest?.status || latest?.decision || 'idle');
|
||||
const key = `chat.shippingOrderReview.llmSuggestion.status.${code}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderReview.llmSuggestion.status.unknown');
|
||||
});
|
||||
|
||||
const canRequest = computed(() =>
|
||||
Boolean(props.editable && props.activeCase && props.focusedFieldId && !props.suggestionLoading && !props.saving),
|
||||
);
|
||||
|
||||
/**
|
||||
* 证据须同时匹配 field_id 与明细行(machine-N → line_index)。
|
||||
*/
|
||||
function evidenceMatchesFieldLine(
|
||||
item: ShippingOrderReviewEvidence,
|
||||
fieldId: string,
|
||||
lineKey: string | null | undefined,
|
||||
): boolean {
|
||||
if (String(item.field_id || '') !== fieldId) return false;
|
||||
const key = String(lineKey || '').trim();
|
||||
if (!key) {
|
||||
return item.line_index == null || item.line_index === undefined;
|
||||
}
|
||||
const matched = /^machine-(\d+)$/i.exec(key);
|
||||
if (matched) {
|
||||
const idx = Number(matched[1]) - 1;
|
||||
return Number(item.line_index) === idx;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const selectedEvidence = computed(() => {
|
||||
const items = props.evidence || [];
|
||||
const fieldId = String(selected.value?.field_id || props.focusedFieldId || '');
|
||||
const draftLineId = selected.value?.draft_line_id ?? props.focusedLineKey;
|
||||
return items.find((item) => evidenceMatchesFieldLine(item, fieldId, draftLineId)) || null;
|
||||
});
|
||||
|
||||
/**
|
||||
* 从草稿容器读取字段当前值(人工值优先,否则机器投影)。
|
||||
*/
|
||||
function readContainerDraftValue(container: Record<string, unknown> | null | undefined, fieldId: string): unknown {
|
||||
if (!container || !fieldId) return null;
|
||||
const values = container.values as Record<string, { value?: unknown }> | undefined;
|
||||
if (values?.[fieldId] && 'value' in values[fieldId]) return values[fieldId].value ?? null;
|
||||
const machine = Array.isArray(container.machine_fields)
|
||||
? (container.machine_fields as Array<Record<string, unknown>>)
|
||||
: [];
|
||||
const hit = machine.find((item) => String(item.field_id || '') === fieldId);
|
||||
return hit?.value ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按建议(或聚焦字段)解析当前草稿值,供三方对比。
|
||||
*/
|
||||
const dialogDraftValue = computed(() => {
|
||||
const fieldId = String(selected.value?.field_id || props.focusedFieldId || '');
|
||||
const draftLineId = selected.value?.draft_line_id ?? props.focusedLineKey;
|
||||
const draft = props.activeCase?.draft;
|
||||
if (!draft || !fieldId) return props.draftValue ?? null;
|
||||
if (draftLineId) {
|
||||
const lines = Array.isArray(draft.lines) ? draft.lines : [];
|
||||
const line = lines.find((item) => String((item as { draft_line_id?: string }).draft_line_id || '') === String(draftLineId));
|
||||
return readContainerDraftValue(line as Record<string, unknown> | undefined, fieldId);
|
||||
}
|
||||
return readContainerDraftValue(draft.header_values as Record<string, unknown> | undefined, fieldId);
|
||||
});
|
||||
|
||||
/**
|
||||
* 打开指定建议的对比裁决对话框。
|
||||
*/
|
||||
function openSuggestion(item: ShippingOrderReviewLlmSuggestion) {
|
||||
selected.value = item;
|
||||
dialogOpen.value = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将建议字段解析为订单字段名称;缺失时使用通用名称,避免显示内部字段 ID。
|
||||
*/
|
||||
function suggestionFieldLabel(item: ShippingOrderReviewLlmSuggestion): string {
|
||||
const fieldId = String(item.field_id || '').trim();
|
||||
const fields = props.activeCase?.schema?.fields || [];
|
||||
const hit = fields.find((field) => String(field.field_id || '') === fieldId);
|
||||
const name = String(hit?.display_name || hit?.field_code || '').trim();
|
||||
if (name && item.draft_line_id) {
|
||||
return `${name} · ${item.draft_line_id}`;
|
||||
}
|
||||
return name || t('chat.shippingOrderReview.unknownField');
|
||||
}
|
||||
|
||||
/**
|
||||
* 将证据等级转为业务文案,避免直接展示 L1_field。
|
||||
*/
|
||||
function evidenceLevelLabel(level?: string | null): string {
|
||||
const code = String(level || 'L1_field').trim() || 'L1_field';
|
||||
const key = `chat.shippingOrderReview.llmSuggestion.evidenceLevel.${code}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderReview.llmSuggestion.evidenceLevel.unknown');
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对话框裁决转发给父级。
|
||||
*/
|
||||
function onDecide(payload: { decision: 'accept' | 'modify' | 'reject'; reason: string; value?: unknown }) {
|
||||
if (!selected.value) return;
|
||||
emit('adjudicate', {
|
||||
suggestion: selected.value,
|
||||
body: {
|
||||
decision: payload.decision,
|
||||
reason: payload.reason || undefined,
|
||||
value: payload.value,
|
||||
expected_draft_version: props.activeCase?.draft?.draft_version,
|
||||
},
|
||||
});
|
||||
dialogOpen.value = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="rounded-xl border border-default bg-surface p-3 text-sm shadow-sm">
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<div>
|
||||
<div class="font-semibold">{{ t('chat.shippingOrderReview.llmSuggestion.panelTitle') }}</div>
|
||||
<div class="mt-1 text-xs text-muted">
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.panelHint') }}
|
||||
· {{ evidenceLevelLabel(selected?.evidence_level || 'L1_field') }}
|
||||
· {{ statusLabel }}
|
||||
<span v-if="suggestions?.length">· {{ suggestions.length }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border px-2 py-1 text-xs disabled:opacity-50"
|
||||
:disabled="!canRequest"
|
||||
data-testid="review-llm-request"
|
||||
@click="emit('requestSuggestion')"
|
||||
>
|
||||
{{
|
||||
suggestionLoading
|
||||
? t('chat.shippingOrderReview.llmSuggestion.requesting')
|
||||
: t('chat.shippingOrderReview.llmSuggestion.request')
|
||||
}}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="unavailableSuggestions.length"
|
||||
class="mt-3 rounded border border-rose-200 bg-rose-50 px-2 py-2 text-xs text-rose-700 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-300"
|
||||
data-testid="review-llm-provider-unavailable"
|
||||
role="alert"
|
||||
>
|
||||
{{ unavailableMessage(unavailableSuggestions[0]) }}
|
||||
</div>
|
||||
<ul
|
||||
v-if="gatedFailedSuggestions.length"
|
||||
class="mt-3 space-y-2"
|
||||
data-testid="review-llm-gated-failed-list"
|
||||
>
|
||||
<li
|
||||
v-for="item in gatedFailedSuggestions"
|
||||
:key="item.suggestion_no"
|
||||
class="rounded border border-sky-200 bg-sky-50/60 px-2 py-2 text-xs text-sky-800 dark:border-sky-900 dark:bg-sky-950/30 dark:text-sky-200"
|
||||
role="note"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="font-medium leading-snug">{{ suggestionFieldLabel(item) }}</div>
|
||||
<p class="mt-1 leading-snug">{{ gatedShortMessage(item) }}</p>
|
||||
<p
|
||||
v-if="gatedDetailMessage(item)"
|
||||
class="mt-1 text-[11px] leading-relaxed opacity-80"
|
||||
>
|
||||
{{ gatedDetailMessage(item) }}
|
||||
</p>
|
||||
<p
|
||||
v-if="item.evidence_summary"
|
||||
class="mt-1 flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] opacity-80"
|
||||
>
|
||||
<span v-if="item.evidence_summary.level">
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.evidenceLevelLabel') }}:{{ evidenceLevelLabel(item.evidence_summary.level) }}
|
||||
</span>
|
||||
<span v-if="item.evidence_summary.auto_upgraded">
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.autoUpgradedLabel') }}
|
||||
</span>
|
||||
<span v-if="typeof item.evidence_summary.field_count === 'number'">
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.fieldCountLabel') }}:{{ item.evidence_summary.field_count }}
|
||||
</span>
|
||||
<span v-if="item.evidence_summary.context_truncated">
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.contextTruncatedLabel') }}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded border border-sky-300 bg-surface px-2 py-0.5 text-xs text-sky-700 dark:border-sky-700 dark:text-sky-200"
|
||||
:disabled="!canRequest"
|
||||
:aria-label="t('chat.shippingOrderReview.llmSuggestion.request')"
|
||||
@click="emit('requestSuggestion')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.request') }}
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
<p
|
||||
v-if="!pendingSuggestions.length && !failedSuggestions.length && !unavailableSuggestions.length && !gatedFailedSuggestions.length"
|
||||
class="mt-3 text-xs text-muted"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.empty') }}
|
||||
</p>
|
||||
<ul v-if="pendingSuggestions.length" class="mt-3 space-y-2">
|
||||
<li
|
||||
v-for="item in pendingSuggestions"
|
||||
:key="item.suggestion_no"
|
||||
class="flex items-center justify-between gap-2 rounded border border-default px-2 py-1.5"
|
||||
>
|
||||
<div class="min-w-0 truncate text-xs">
|
||||
<span class="font-medium">{{ suggestionFieldLabel(item) }}</span>
|
||||
<span class="ml-2 opacity-70">{{ item.suggested_value ?? '—' }}</span>
|
||||
</div>
|
||||
<button type="button" class="shrink-0 rounded border px-2 py-0.5 text-xs" @click="openSuggestion(item)">
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.review') }}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
<ul v-if="failedSuggestions.length" class="mt-3 space-y-2" data-testid="review-llm-failed-list">
|
||||
<li
|
||||
v-for="item in failedSuggestions"
|
||||
:key="item.suggestion_no"
|
||||
class="flex items-center justify-between gap-2 rounded border border-amber-200 bg-amber-50/50 px-2 py-1.5 dark:border-amber-900 dark:bg-amber-950/30"
|
||||
>
|
||||
<div class="min-w-0 truncate text-xs">
|
||||
<span class="font-medium">{{ suggestionFieldLabel(item) }}</span>
|
||||
<span class="ml-2 text-amber-700 dark:text-amber-300">
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.verbatimFailed') }}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded border px-2 py-0.5 text-xs"
|
||||
data-testid="review-llm-open-failed"
|
||||
@click="openSuggestion(item)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.review') }}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<ReviewLlmSuggestionDialog
|
||||
:open="dialogOpen"
|
||||
:suggestion="selected"
|
||||
:evidence="selectedEvidence"
|
||||
:draft-value="dialogDraftValue"
|
||||
:field-label="selected ? suggestionFieldLabel(selected) : ''"
|
||||
@close="dialogOpen = false"
|
||||
@decide="onDecide"
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewProfileMatchPanel.spec.ts
|
||||
* 用途:锁定模板匹配侧栏的候选披露规则,避免候选数量增长撑长工作台。
|
||||
* 依赖:vitest、@vue/test-utils、vue-i18n、ReviewProfileMatchPanel。
|
||||
* 逻辑:所有状态默认收起;用户可手动展开/收起候选列表。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ReviewProfileMatchPanel from './ReviewProfileMatchPanel.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: { shippingOrderReview: { profileMatch: {
|
||||
title: '文档模板匹配', subtitle: '摘要', selected: '命中模板', noSelected: '未选定模板',
|
||||
expandCandidates: '查看候选模板({count})', collapseCandidates: '收起候选模板',
|
||||
routeType: '路由类型', executionMode: '执行模式',
|
||||
extractionBlocked: '模板已命中,但字段提取仍被安全门禁阻断',
|
||||
extractionBlockedNoMatch: '模板未唯一命中,字段提取被阻断',
|
||||
extractionBlockedReason: '阻断原因:{reasons}',
|
||||
coordinateModel: {
|
||||
anchorFrame: '锚点坐标框架', status: '变换状态', translateX: '横向平移',
|
||||
translateY: '纵向平移', reasonCodes: '原因码',
|
||||
},
|
||||
status: { matched: '已匹配', ambiguous: '多个候选' },
|
||||
} } },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
function mountPanel(needsReview = false) {
|
||||
return mount(ReviewProfileMatchPanel, {
|
||||
props: {
|
||||
profileMatch: {
|
||||
available: true,
|
||||
visibility: 'admin',
|
||||
status: needsReview ? 'ambiguous' : 'matched',
|
||||
needs_review: needsReview,
|
||||
selected_profile: { profile_code: 'ODP-A', display_name: '客户订单模板', version: 1 },
|
||||
candidates: [
|
||||
{ profile_code: 'ODP-A', display_name: '客户订单模板', score: 0.99 },
|
||||
{ profile_code: 'ODP-B', display_name: '客户订单模板(旧版)', score: 0.98 },
|
||||
],
|
||||
fallback_reason_codes: [],
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
function mountAnchorFramePanel(visibility: 'admin' | 'admin_only' = 'admin') {
|
||||
return mount(ReviewProfileMatchPanel, {
|
||||
props: {
|
||||
profileMatch: {
|
||||
available: true,
|
||||
visibility,
|
||||
status: 'unique_match',
|
||||
needs_review: false,
|
||||
selected_profile: { profile_code: 'ODP-A', display_name: '客户订单模板', version: 1 },
|
||||
candidates: [{
|
||||
profile_code: 'ODP-A',
|
||||
version: 1,
|
||||
display_name: '客户订单模板',
|
||||
score: 0.99,
|
||||
coordinate_transform: {
|
||||
status: 'applied',
|
||||
translate_x: 0.001,
|
||||
translate_y: 0.03,
|
||||
reason_codes: [],
|
||||
},
|
||||
}],
|
||||
fallback_reason_codes: [],
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('ReviewProfileMatchPanel', () => {
|
||||
it('默认收起无需关注的候选列表', () => {
|
||||
const wrapper = mountPanel(false);
|
||||
expect(wrapper.find('[data-testid="review-profile-match-candidates"]').exists()).toBe(false);
|
||||
expect(wrapper.get('[data-testid="review-profile-match-candidates-toggle"]').text()).toContain('查看候选模板(2)');
|
||||
});
|
||||
|
||||
it('多个候选且需要人工处理时也默认收起,并允许展开后收起', async () => {
|
||||
const wrapper = mountPanel(true);
|
||||
expect(wrapper.find('[data-testid="review-profile-match-candidates"]').exists()).toBe(false);
|
||||
await wrapper.get('[data-testid="review-profile-match-candidates-toggle"]').trigger('click');
|
||||
expect(wrapper.find('[data-testid="review-profile-match-candidates"]').exists()).toBe(true);
|
||||
await wrapper.get('[data-testid="review-profile-match-candidates-toggle"]').trigger('click');
|
||||
expect(wrapper.find('[data-testid="review-profile-match-candidates"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('候选模板优先展示模板名称,不把内部编号作为主文案', async () => {
|
||||
const wrapper = mountPanel(true);
|
||||
|
||||
await wrapper.get('[data-testid="review-profile-match-candidates-toggle"]').trigger('click');
|
||||
|
||||
// 关键断言:业务用户辨认模板依赖 display_name,ODP 编号不应出现在候选列表主展示中。
|
||||
expect(wrapper.get('[data-testid="review-profile-match-candidates"]').text()).toContain('客户订单模板');
|
||||
expect(wrapper.get('[data-testid="review-profile-match-candidates"]').text()).not.toContain('ODP-A');
|
||||
});
|
||||
|
||||
it('唯一命中时仍展示下游字段提取门禁的阻断原因', () => {
|
||||
const wrapper = mount(ReviewProfileMatchPanel, {
|
||||
props: {
|
||||
profileMatch: {
|
||||
available: true,
|
||||
visibility: 'admin',
|
||||
status: 'unique_match',
|
||||
needs_review: true,
|
||||
selected_profile: { profile_code: 'ODP-A', display_name: '客户订单模板', version: 1 },
|
||||
candidates: [{ profile_code: 'ODP-A', display_name: '客户订单模板', score: 0.99 }],
|
||||
fallback_reason_codes: ['PARSE_STRATEGY_ROW_MODE_AMBIGUOUS'],
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 关键断言:唯一模板命中不等于字段已提取,必须明确暴露下游阻断原因。
|
||||
expect(wrapper.get('[data-testid="review-profile-match-extraction-blocked"]').text())
|
||||
.toContain('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS');
|
||||
expect(wrapper.get('[data-testid="review-profile-match-extraction-blocked"]').text())
|
||||
.toContain('模板已命中');
|
||||
});
|
||||
|
||||
it('未选定模板时阻断文案不得再写模板已命中', () => {
|
||||
const wrapper = mount(ReviewProfileMatchPanel, {
|
||||
props: {
|
||||
profileMatch: {
|
||||
available: true,
|
||||
visibility: 'admin',
|
||||
status: 'evidence_insufficient',
|
||||
needs_review: true,
|
||||
selected_profile: null,
|
||||
candidates: [],
|
||||
fallback_reason_codes: ['coordinate_evidence_unavailable'],
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
const blocked = wrapper.get('[data-testid="review-profile-match-extraction-blocked"]').text();
|
||||
expect(blocked).toContain('模板未唯一命中');
|
||||
expect(blocked).not.toContain('模板已命中');
|
||||
expect(blocked).toContain('coordinate_evidence_unavailable');
|
||||
});
|
||||
|
||||
it('管理员技术详情展示锚点框架平移和稳定原因码,不展示原始正文或完整坐标', async () => {
|
||||
const wrapper = mountAnchorFramePanel();
|
||||
|
||||
await wrapper.get('[data-testid="review-profile-match-candidates-toggle"]').trigger('click');
|
||||
|
||||
const details = wrapper.get('[data-testid="review-profile-match-details"]');
|
||||
expect(details.text()).toContain('锚点坐标框架');
|
||||
expect(details.text()).toContain('纵向平移');
|
||||
expect(details.text()).toContain('0.03');
|
||||
expect(details.text()).not.toContain('ORDER NO.');
|
||||
expect(details.text()).not.toContain('x0');
|
||||
});
|
||||
|
||||
it('非管理员不可见锚点框架技术详情', async () => {
|
||||
const wrapper = mountAnchorFramePanel('admin_only');
|
||||
expect(wrapper.find('[data-testid="review-profile-match-panel"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-profile-match-coordinate-transform"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,187 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewProfileMatchPanel.vue
|
||||
用途:复核工作台文档模板匹配只读区(用户四态;管理员详细在技术诊断)。
|
||||
依赖:vue-i18n、ShippingOrderReviewProfileMatch。
|
||||
逻辑:普通用户只显示 matched/unmatched/ambiguous/unknown;
|
||||
required_field_missing 不在此展示;分数/Profile ID 仅 admin visibility。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderReviewProfileMatch } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
profileMatch: ShippingOrderReviewProfileMatch | null | undefined;
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
const visible = computed(() => {
|
||||
const match = props.profileMatch;
|
||||
if (!match) return false;
|
||||
if (match.visibility === 'admin_only' && match.available === false) return false;
|
||||
return Boolean(match.available !== false);
|
||||
});
|
||||
|
||||
const isAdminView = computed(() => String(props.profileMatch?.visibility || '') === 'admin');
|
||||
const needsReview = computed(() => Boolean(props.profileMatch?.needs_review));
|
||||
const candidateCount = computed(() => (props.profileMatch?.candidates || []).length);
|
||||
// 候选模板始终按需披露,避免模板数量增长撑长工作台;人工关注状态仍通过徽标表达。
|
||||
const defaultCandidatesExpanded = computed(() => false);
|
||||
const candidatesOpenOverride = ref<boolean | null>(null);
|
||||
const candidatesExpanded = computed(() => candidatesOpenOverride.value ?? defaultCandidatesExpanded.value);
|
||||
const selectedCoordinateTransform = computed(() => {
|
||||
if (!isAdminView.value) return null;
|
||||
const selectedCode = String(props.profileMatch?.selected_profile?.profile_code || '');
|
||||
const selectedVersion = props.profileMatch?.selected_profile?.version;
|
||||
const candidate = (props.profileMatch?.candidates || []).find((item) => (
|
||||
item.profile_code === selectedCode
|
||||
&& (selectedVersion == null || item.version === selectedVersion)
|
||||
));
|
||||
return candidate?.coordinate_transform || null;
|
||||
});
|
||||
const coordinateTransformReasonCodes = computed(() => (
|
||||
selectedCoordinateTransform.value?.reason_codes || []
|
||||
));
|
||||
/** 唯一命中仅证明版式身份;下游字段/明细恢复若受门禁阻断,必须在同卡明确说明。
|
||||
* 未选定模板时不得再写「模板已命中」,避免与上方「未选定模板」矛盾。 */
|
||||
const extractionBlockReasons = computed(() => (
|
||||
(props.profileMatch?.fallback_reason_codes || []).filter((code) => String(code).trim())
|
||||
));
|
||||
const hasSelectedProfile = computed(() => Boolean(
|
||||
String(props.profileMatch?.selected_profile?.profile_code || '').trim()
|
||||
|| String(props.profileMatch?.selected_profile?.display_name || '').trim(),
|
||||
));
|
||||
const extractionBlockedTitle = computed(() => (
|
||||
hasSelectedProfile.value
|
||||
? t('chat.shippingOrderReview.profileMatch.extractionBlocked')
|
||||
: t('chat.shippingOrderReview.profileMatch.extractionBlockedNoMatch')
|
||||
));
|
||||
|
||||
watch(
|
||||
() => `${props.profileMatch?.status || ''}:${props.profileMatch?.selected_profile?.profile_code || ''}:${candidateCount.value}`,
|
||||
() => { candidatesOpenOverride.value = null; },
|
||||
);
|
||||
|
||||
function toggleCandidates() {
|
||||
candidatesOpenOverride.value = !candidatesExpanded.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 匹配状态本地化(用户四态)。
|
||||
*/
|
||||
const statusLabel = computed(() => {
|
||||
const status = String(props.profileMatch?.status || '').trim();
|
||||
const key = `chat.shippingOrderReview.profileMatch.status.${status}`;
|
||||
return status && te(key) ? t(key) : (status || '—');
|
||||
});
|
||||
|
||||
/**
|
||||
* 选中模板展示名(用户仅 display_name)。
|
||||
*/
|
||||
const selectedLabel = computed(() => {
|
||||
const selected = props.profileMatch?.selected_profile;
|
||||
if (!selected) {
|
||||
return t('chat.shippingOrderReview.profileMatch.noSelected');
|
||||
}
|
||||
const name = String(selected.display_name || '').trim();
|
||||
if (!name) return t('chat.shippingOrderReview.profileMatch.noSelected');
|
||||
if (!isAdminView.value) return name;
|
||||
const version = selected.version != null ? ` v${selected.version}` : '';
|
||||
return `${name}${version}`;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="visible"
|
||||
class="rounded-xl border border-default bg-surface p-3 shadow-sm"
|
||||
data-testid="review-profile-match-panel"
|
||||
:data-status="String(profileMatch?.status || '')"
|
||||
>
|
||||
<header class="flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.profileMatch.title') }}</h2>
|
||||
<p class="mt-0.5 text-xs text-muted">{{ t('chat.shippingOrderReview.profileMatch.subtitle') }}</p>
|
||||
</div>
|
||||
<span
|
||||
class="rounded-full px-2.5 py-1 text-xs font-medium"
|
||||
:class="needsReview
|
||||
? 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'
|
||||
: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'"
|
||||
data-testid="review-profile-match-badge"
|
||||
>
|
||||
{{ statusLabel }}
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<dl class="mt-2 space-y-1 text-xs text-secondary">
|
||||
<div class="flex flex-wrap gap-x-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.profileMatch.selected') }}</dt>
|
||||
<dd class="font-medium text-primary" data-testid="review-profile-match-selected">{{ selectedLabel }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<div
|
||||
v-if="extractionBlockReasons.length"
|
||||
class="mt-3 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-900 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
|
||||
data-testid="review-profile-match-extraction-blocked"
|
||||
>
|
||||
<p class="font-medium">{{ extractionBlockedTitle }}</p>
|
||||
<p class="mt-1 text-amber-800 dark:text-amber-200">
|
||||
{{ t('chat.shippingOrderReview.profileMatch.extractionBlockedReason', { reasons: extractionBlockReasons.join(', ') }) }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<template v-if="isAdminView && candidateCount">
|
||||
<button
|
||||
type="button"
|
||||
class="mt-3 flex w-full items-center justify-between rounded-lg border border-default bg-surface-soft px-2.5 py-2 text-left text-xs font-medium text-secondary transition-colors hover-surface-soft"
|
||||
data-testid="review-profile-match-candidates-toggle"
|
||||
:aria-expanded="candidatesExpanded"
|
||||
@click="toggleCandidates"
|
||||
>
|
||||
<span>{{ candidatesExpanded
|
||||
? t('chat.shippingOrderReview.profileMatch.collapseCandidates')
|
||||
: t('chat.shippingOrderReview.profileMatch.expandCandidates', { count: candidateCount }) }}</span>
|
||||
<span aria-hidden="true" class="text-muted">{{ candidatesExpanded ? '−' : '+' }}</span>
|
||||
</button>
|
||||
<div v-if="candidatesExpanded" data-testid="review-profile-match-details">
|
||||
<dl class="mt-2 space-y-1 text-xs text-secondary">
|
||||
<div v-if="profileMatch?.route_type" class="flex flex-wrap gap-x-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.profileMatch.routeType') }}</dt>
|
||||
<dd class="font-mono">{{ profileMatch.route_type }}</dd>
|
||||
</div>
|
||||
<div v-if="profileMatch?.execution_mode" class="flex flex-wrap gap-x-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.profileMatch.executionMode') }}</dt>
|
||||
<dd class="font-mono">{{ profileMatch.execution_mode }}</dd>
|
||||
</div>
|
||||
<div v-if="selectedCoordinateTransform" data-testid="review-profile-match-coordinate-transform" class="mt-2 rounded-lg border border-sky-200 bg-sky-50 px-2.5 py-2 text-[11px] text-sky-950 dark:border-sky-900 dark:bg-sky-950/30 dark:text-sky-100">
|
||||
<div class="font-medium">{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.anchorFrame') }}</div>
|
||||
<div class="mt-1 flex flex-wrap gap-x-3 gap-y-1">
|
||||
<span>{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.status') }}: {{ selectedCoordinateTransform.status }}</span>
|
||||
<span v-if="selectedCoordinateTransform.translate_x != null">{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.translateX') }}: {{ selectedCoordinateTransform.translate_x }}</span>
|
||||
<span v-if="selectedCoordinateTransform.translate_y != null">{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.translateY') }}: {{ selectedCoordinateTransform.translate_y }}</span>
|
||||
</div>
|
||||
<div v-if="coordinateTransformReasonCodes.length" class="mt-1">
|
||||
{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.reasonCodes') }}: {{ coordinateTransformReasonCodes.join(', ') }}
|
||||
</div>
|
||||
</div>
|
||||
</dl>
|
||||
<ul
|
||||
class="mt-2 max-h-48 space-y-1.5 overflow-y-auto pr-1"
|
||||
data-testid="review-profile-match-candidates"
|
||||
>
|
||||
<li
|
||||
v-for="(item, idx) in profileMatch?.candidates || []"
|
||||
:key="`${item.profile_code}-${item.version}-${idx}`"
|
||||
class="rounded-lg border border-default bg-surface-soft px-2.5 py-1.5 text-[11px] text-secondary"
|
||||
>
|
||||
<span>{{ item.display_name || t('chat.shippingOrderReview.profileMatch.noSelected') }}</span>
|
||||
<span v-if="item.score != null" class="ml-2 text-muted">{{ item.score }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
Loaded 100 of 2050 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user