feat(shipping-notice): 增强订单文档 Profile 管理功能,新增复核与草稿管理
- 添加订单复核相关模型及 API,支持复核案例的创建、更新和确认 - 实现复核草稿的管理功能,允许用户对复核内容进行编辑和保存 - 引入复核事件审计,确保复核过程的可追溯性 - 更新数据库模型以支持复核和草稿的关系管理 - 完善相关服务逻辑,确保复核与草稿的状态管理和数据一致性 - 增强文档模板的管理能力,支持更复杂的业务场景
This commit is contained in:
1 parent
61ac6403c4
commit
b7307fc573
147 files changed
+15108
-1522
No files matched your search
@@ -27,6 +27,11 @@ import type {
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionRunCreateResponse,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewDraftWrite,
|
||||
ShippingOrderReviewEvidence,
|
||||
ShippingOrderReviewReparseResponse,
|
||||
ShippingOrderReviewRun,
|
||||
ShippingTaskUiState,
|
||||
} from '../types/shipping.api.types';
|
||||
|
||||
@@ -200,6 +205,127 @@ export const listWorkspaceShippingOrderExtractionDocuments = (runNo: string) =>
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/documents`,
|
||||
);
|
||||
|
||||
/** 获取 Run 下每份 PDF 的建单前复核摘要,服务端负责 owner 隔离。 */
|
||||
export const getWorkspaceShippingOrderReviewRun = (runNo: string) =>
|
||||
requestJson<ShippingOrderReviewRun>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/review`,
|
||||
);
|
||||
|
||||
/** 获取一份 PDF 的冻结 Schema 与只读机器/草稿投影。 */
|
||||
export const getWorkspaceShippingOrderReviewCase = (caseNo: string) =>
|
||||
requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}`,
|
||||
);
|
||||
|
||||
/** 保存一个复核订单头字段;后端以 expected_draft_version 拒绝过期窗口覆盖。 */
|
||||
export const patchWorkspaceShippingOrderReviewHeaderField = (
|
||||
caseNo: string, fieldId: string, payload: ShippingOrderReviewDraftWrite,
|
||||
) => requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/header-fields/${encodeURIComponent(fieldId)}`,
|
||||
{ method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
|
||||
);
|
||||
|
||||
/** 保存一个复核订单行字段;line_key 仅接受当前 Case DTO 返回的稳定标识。 */
|
||||
export const patchWorkspaceShippingOrderReviewLineField = (
|
||||
caseNo: string, lineKey: string, fieldId: string, payload: ShippingOrderReviewDraftWrite,
|
||||
) => requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines/${encodeURIComponent(lineKey)}/fields/${encodeURIComponent(fieldId)}`,
|
||||
{ method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
|
||||
);
|
||||
|
||||
export const addWorkspaceShippingOrderReviewLine = (caseNo: string, expectedDraftVersion: number) =>
|
||||
requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines`,
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ expected_draft_version: expectedDraftVersion }) },
|
||||
);
|
||||
|
||||
export const copyWorkspaceShippingOrderReviewLine = (caseNo: string, lineKey: string, expectedDraftVersion: number) =>
|
||||
requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines/${encodeURIComponent(lineKey)}/copy`,
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ expected_draft_version: expectedDraftVersion }) },
|
||||
);
|
||||
|
||||
export const deleteWorkspaceShippingOrderReviewLine = (caseNo: string, lineKey: string, expectedDraftVersion: number) =>
|
||||
requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines/${encodeURIComponent(lineKey)}`,
|
||||
{ method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ expected_draft_version: expectedDraftVersion }) },
|
||||
);
|
||||
|
||||
export const validateWorkspaceShippingOrderReviewDraft = (caseNo: string, expectedDraftVersion: number) =>
|
||||
requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/validate`,
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ expected_draft_version: expectedDraftVersion }) },
|
||||
);
|
||||
|
||||
/** 确认当前 PDF 的已校验草稿;服务端以版本和幂等键确保只创建一张 Task。 */
|
||||
export const confirmWorkspaceShippingOrderReviewCase = (
|
||||
caseNo: string,
|
||||
payload: { expected_draft_version: number; idempotency_key: string; warning_acknowledgements?: Array<{ code: string; comment?: string }> },
|
||||
) => requestJson<import('../types/shipping.api.types').ShippingOrderReviewConfirmResponse>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/confirm`,
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json', 'Idempotency-Key': payload.idempotency_key }, body: JSON.stringify(payload) },
|
||||
);
|
||||
|
||||
/** 启用无机器订单 PDF 的唯一人工草稿;不创建第二个订单对象。 */
|
||||
export const createWorkspaceShippingOrderReviewManualDraft = (caseNo: string, comment?: string) =>
|
||||
requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/manual-draft`,
|
||||
jsonPost({ comment }),
|
||||
);
|
||||
|
||||
/** 将当前 PDF 独立处置为非订单,服务端不会影响同一 Run 的其他 PDF。 */
|
||||
export const markWorkspaceShippingOrderReviewNonOrder = (caseNo: string, reason: string, comment?: string) =>
|
||||
requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/disposition/non-order`,
|
||||
jsonPost({ reason, comment }),
|
||||
);
|
||||
|
||||
/** 标记质量异常但保留原始 PDF、机器结果和草稿,供补件或重识别。 */
|
||||
export const markWorkspaceShippingOrderReviewQualityIssue = (caseNo: string, reason: string, comment?: string) =>
|
||||
requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/disposition/quality-issue`,
|
||||
jsonPost({ reason, comment }),
|
||||
);
|
||||
|
||||
/** 仅创建当前 Case PDF 的后继识别 Run,重复点击幂等复用同一个处理中 Run。 */
|
||||
export const reparseWorkspaceShippingOrderReviewDocument = (caseNo: string, reason: string, comment?: string) =>
|
||||
requestJson<ShippingOrderReviewReparseResponse>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/reparse`,
|
||||
jsonPost({ reason, comment }),
|
||||
);
|
||||
|
||||
/** 绑定已上传的替代 PDF;预解析成功后再单独创建替代识别 Run。 */
|
||||
export const createWorkspaceShippingOrderReviewReplacementIntake = (caseNo: string, assetNo: string) =>
|
||||
requestJson<ShippingNoticeIntakeResponse>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/replacement-intakes`,
|
||||
jsonPost({ asset_no: assetNo }),
|
||||
);
|
||||
|
||||
/** 替代 Intake 解析成唯一 PDF 后创建新的单文档 Run。 */
|
||||
export const createWorkspaceShippingOrderReviewReplacementRun = (caseNo: string, intakeNo: string) =>
|
||||
requestJson<ShippingOrderReviewReparseResponse>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/replacement-runs`,
|
||||
jsonPost({ intake_no: intakeNo }),
|
||||
);
|
||||
|
||||
/** 获取复核字段的安全证据摘要;PDF 二进制继续由受控同源预览接口提供。 */
|
||||
export const getWorkspaceShippingOrderReviewEvidence = (caseNo: string) =>
|
||||
requestJson<{ case_no: string; items: ShippingOrderReviewEvidence[] }>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/evidence`,
|
||||
);
|
||||
|
||||
/** 以认证请求取得 PDF Blob,避免 iframe 无法携带 JWT 而退化为公开预览 URL。 */
|
||||
export async function getWorkspaceShippingOrderReviewPreview(caseNo: string): Promise<Blob> {
|
||||
const response = await fetch(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/document-preview`,
|
||||
{ headers: getAuthHeaders() },
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new BusinessError({ message: 'Review PDF preview failed', code: 'SHIPPING.REVIEW_PREVIEW_NOT_FOUND', status: response.status });
|
||||
}
|
||||
return response.blob();
|
||||
}
|
||||
|
||||
/** 用户展开状态卡时获取脱敏进度时间线;不返回节点或Workflow诊断数据。 */
|
||||
export const listWorkspaceShippingOrderExtractionProgressEvents = (runNo: string) =>
|
||||
requestJson<{ items: ShippingOrderExtractionProgressEvent[] }>(
|
||||
@@ -762,7 +888,7 @@ export const refreshShippingNoticeDuplicate = (intakeNo: string) =>
|
||||
|
||||
export const updateShippingNoticeCandidate = (
|
||||
candidateNo: string,
|
||||
patch: { selected?: boolean; business_summary?: Record<string, unknown> },
|
||||
patch: { selected: boolean },
|
||||
) => requestJson<import('../types/shipping.api.types').ShippingNoticeCandidateResponse>(
|
||||
`/api/workspace/shipping-notice/candidates/${encodeURIComponent(candidateNo)}`,
|
||||
{
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
* 逻辑:附件卡片位于文本框上方;订单审核结果随对应聊天消息展示,输入区只保留附件处理状态。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { Ref } from 'vue';
|
||||
import {
|
||||
@@ -82,7 +82,6 @@ const emit = defineEmits<{
|
||||
'retry-shipping-notice-attachment': [id: string];
|
||||
'resolve-shipping-notice-duplicate': [id: string];
|
||||
'select-shipping-candidate': [candidateNo: string, selected: boolean];
|
||||
'update-shipping-candidate': [candidateNo: string, businessSummary: Record<string, unknown>, done: (success: boolean) => void];
|
||||
'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];
|
||||
@@ -104,6 +103,16 @@ const showAttachmentUrlPanel = ref(false);
|
||||
const showKbDropdown = ref(false);
|
||||
const attachmentUrlInput = ref('');
|
||||
|
||||
/** 当前发货通知是否仍在上传或预解析,决定输入框下方的操作提示。 */
|
||||
const hasShippingNoticeInProgress = computed(() => props.attachments.some(
|
||||
(attachment) => attachment.kind === 'shipping_notice'
|
||||
&& (
|
||||
attachment.uploadStatus === 'waiting'
|
||||
|| attachment.uploadStatus === 'uploading'
|
||||
|| ['waiting', 'queued', 'parsing'].includes(attachment.parseStatus)
|
||||
),
|
||||
));
|
||||
|
||||
/**
|
||||
* 汇总 EML 附件解析进度,供输入栏徽标展示。
|
||||
* 核心逻辑:阶段 1 仅展示快览结果;优先说明发现了多少附件,技术失败/目录不完整再退化为问题提示。
|
||||
@@ -464,14 +473,7 @@ watch(
|
||||
v-if="isShippingNoticeAgent && attachments.length > 0"
|
||||
class="flex flex-wrap items-center gap-2 px-3 pb-1 text-xs text-muted"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full border border-default bg-surface-soft px-3 py-1 font-medium text-secondary transition-colors hover:bg-surface-soft/70"
|
||||
@click="emit('use-shipping-suggested-prompt')"
|
||||
>
|
||||
{{ shippingSuggestedPrompt || '推荐问题' }}
|
||||
</button>
|
||||
<span>{{ t('chat.shippingNoticeConfirmBatchHint') }}</span>
|
||||
<span>{{ hasShippingNoticeInProgress ? t('chat.shippingNoticeWaitingForParse') : t('chat.shippingNoticeConfirmBatchHint') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="mt-1.5 flex items-center justify-between px-1.5 pb-0.5">
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, 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';
|
||||
@@ -18,6 +19,7 @@ import ShippingBatchWorkspaceDrawer from '@/features/chat/components/ShippingBat
|
||||
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 ShippingOrderReviewView from '@/features/chat/views/ShippingOrderReviewView.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';
|
||||
@@ -36,6 +38,8 @@ type MaintenanceRecordPanelCommand = {
|
||||
};
|
||||
|
||||
const page = useChatPageContext();
|
||||
const route = useRoute();
|
||||
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'));
|
||||
const embeddedIframeSrc = computed(() => {
|
||||
@@ -195,7 +199,8 @@ watch(() => page.currentAgentId, () => {
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<div class="flex min-h-0 min-w-0 flex-1">
|
||||
<ShippingOrderReviewView v-if="isOrderReviewMode" />
|
||||
<div v-else class="flex min-h-0 min-w-0 flex-1">
|
||||
<div class="flex min-h-0 min-w-0 flex-1 flex-col">
|
||||
<TrainingWorkspacePanel
|
||||
:current-agent="page.currentAgent"
|
||||
@@ -291,7 +296,6 @@ watch(() => page.currentAgentId, () => {
|
||||
@retry-shipping-notice-attachment="page.retryShippingNoticeAttachment"
|
||||
@resolve-shipping-notice-duplicate="page.openShippingDuplicateDialog"
|
||||
@select-shipping-candidate="page.setShippingCandidateSelected"
|
||||
@update-shipping-candidate="page.updateShippingCandidateSummary"
|
||||
@resolve-shipping-candidate-duplicate="page.resolveShippingCandidateDuplicate"
|
||||
@local-files-selected="page.handleLocalFilesSelected"
|
||||
@add-remote-url="page.addRemoteUrlAttachment"
|
||||
|
||||
@@ -1,344 +0,0 @@
|
||||
<!--
|
||||
features/chat/components/ShippingNoticeCandidateReview.vue
|
||||
用途:展示一封 EML 下的订单候选,并提供选择、结构化修订与重复决策入口。
|
||||
依赖:shipping.types、Vue I18n。
|
||||
逻辑:组件维护 PO 与订单行编辑草稿,持久化操作通过事件交给 useShippingNoticeIntakes。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingDuplicateAction, ShippingNoticePendingAttachment } from '../types/shipping.types';
|
||||
|
||||
interface EditableCandidateLine {
|
||||
source: Record<string, unknown>;
|
||||
part_number: string;
|
||||
customer_part_number: string;
|
||||
aws_part_number: string;
|
||||
qty: string;
|
||||
reservation_id: string;
|
||||
inventory_source_hint: string;
|
||||
uom: string;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
attachment: ShippingNoticePendingAttachment;
|
||||
canForceCreate: boolean;
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
update: [candidateNo: string, businessSummary: Record<string, unknown>, done: (success: boolean) => void];
|
||||
resolveDuplicate: [candidateNo: string, action: ShippingDuplicateAction, targetTaskNo: string | undefined, reason: string | undefined, done: (success: boolean) => void];
|
||||
promote: [candidateNo: string, done: (success: boolean) => void];
|
||||
reject: [candidateNo: string, done: (success: boolean) => void];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const editingCandidateNo = ref('');
|
||||
const editError = ref('');
|
||||
const editPoNumber = ref('');
|
||||
const editLines = reactive<EditableCandidateLine[]>([]);
|
||||
const forceReasonCandidateNo = ref('');
|
||||
const forceReason = ref('');
|
||||
const submittingCandidateNo = ref('');
|
||||
const candidates = computed(() => props.attachment.candidates || []);
|
||||
|
||||
watch(() => props.attachment.candidates, () => {
|
||||
if (editingCandidateNo.value && !candidates.value.some((item) => item.candidateNo === editingCandidateNo.value)) {
|
||||
editingCandidateNo.value = '';
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 将 Candidate 摘要投影为可编辑的 PO 与订单行。
|
||||
* 核心逻辑:保留原始扩展字段,并显式映射三类料号、数量、Reservation ID、库存源线索与单位。
|
||||
* @param candidateNo - 待编辑的 Candidate 编号
|
||||
* @returns 无返回值;Candidate 不存在时保持当前编辑状态
|
||||
*/
|
||||
function startEdit(candidateNo: string): void {
|
||||
const candidate = candidates.value.find((item) => item.candidateNo === candidateNo);
|
||||
if (!candidate) return;
|
||||
const sourceLines = Array.isArray(candidate.businessSummary.lines)
|
||||
? candidate.businessSummary.lines.filter((item): item is Record<string, unknown> => !!item && typeof item === 'object')
|
||||
: [];
|
||||
editingCandidateNo.value = candidateNo;
|
||||
editPoNumber.value = String(candidate.businessSummary.po_number || candidate.poNumber || '');
|
||||
editLines.splice(0, editLines.length, ...sourceLines.map((line) => ({
|
||||
source: { ...line },
|
||||
part_number: String(line.part_number || ''),
|
||||
customer_part_number: String(line.customer_part_number || ''),
|
||||
aws_part_number: String(line.aws_part_number || ''),
|
||||
qty: String(line.qty ?? ''),
|
||||
reservation_id: String(line.reservation_id || ''),
|
||||
inventory_source_hint: String(line.inventory_source_hint || ''),
|
||||
uom: String(line.uom || 'EA'),
|
||||
})));
|
||||
if (!editLines.length) addLine();
|
||||
editError.value = '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增一条待修订订单行。
|
||||
* 核心逻辑:创建带三类料号和可选库存源线索的空白草稿。
|
||||
* @returns 无返回值
|
||||
*/
|
||||
function addLine(): void {
|
||||
editLines.push({
|
||||
source: {},
|
||||
part_number: '',
|
||||
customer_part_number: '',
|
||||
aws_part_number: '',
|
||||
qty: '',
|
||||
reservation_id: '',
|
||||
inventory_source_hint: '',
|
||||
uom: 'EA',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并提交 Candidate 修订。
|
||||
* 核心逻辑:保留原始扩展字段,并按 v2 契约提交三类料号与唯一库存源线索。
|
||||
* @returns 无返回值;校验失败时写入本地错误提示
|
||||
*/
|
||||
function saveEdit(): void {
|
||||
const candidate = candidates.value.find((item) => item.candidateNo === editingCandidateNo.value);
|
||||
if (!candidate || !editLines.length) return;
|
||||
const normalizedLines = editLines.map((line) => {
|
||||
const source = { ...line.source };
|
||||
return {
|
||||
...source,
|
||||
part_number: line.part_number.trim(),
|
||||
customer_part_number: line.customer_part_number.trim() || undefined,
|
||||
aws_part_number: line.aws_part_number.trim() || undefined,
|
||||
qty: Number(line.qty),
|
||||
reservation_id: line.reservation_id.trim() || undefined,
|
||||
inventory_source_hint: line.inventory_source_hint.trim() || undefined,
|
||||
uom: line.uom.trim() || 'EA',
|
||||
};
|
||||
});
|
||||
if (normalizedLines.some((line) => !line.part_number || !Number.isFinite(line.qty) || line.qty <= 0)) {
|
||||
editError.value = t('chat.shippingCandidateInvalidLine');
|
||||
return;
|
||||
}
|
||||
submittingCandidateNo.value = candidate.candidateNo;
|
||||
emit('update', candidate.candidateNo, {
|
||||
...candidate.businessSummary,
|
||||
po_number: editPoNumber.value.trim() || null,
|
||||
lines: normalizedLines,
|
||||
}, (success) => {
|
||||
submittingCandidateNo.value = '';
|
||||
if (success) {
|
||||
editingCandidateNo.value = '';
|
||||
editError.value = '';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 非编辑态展示 Candidate 订单行摘要。
|
||||
* @param candidate - 当前 Candidate
|
||||
*/
|
||||
function readonlyLines(candidate: typeof candidates.value[number]): Array<Record<string, unknown>> {
|
||||
const lines = candidate.businessSummary?.lines;
|
||||
return Array.isArray(lines)
|
||||
? lines.filter((item): item is Record<string, unknown> => !!item && typeof item === 'object')
|
||||
: [];
|
||||
}
|
||||
|
||||
/** 将未知值格式化为表格占位文本。 */
|
||||
function displayCell(value: unknown): string {
|
||||
const text = String(value ?? '').trim();
|
||||
return text || '—';
|
||||
}
|
||||
|
||||
/** 将客户匹配状态转换为面向业务用户的文案。 */
|
||||
function customerMatchStatus(status: string): string {
|
||||
return t(`chat.shippingCustomerMatch.status.${status}`);
|
||||
}
|
||||
|
||||
/** 对当前首个重复目标应用决策;强制新建时要求填写原因。 */
|
||||
function resolveDuplicate(candidateNo: string, action: ShippingDuplicateAction): void {
|
||||
const candidate = candidates.value.find((item) => item.candidateNo === candidateNo);
|
||||
const target = candidate?.duplicate?.matches?.[0]?.taskNo;
|
||||
if (action === 'force_create') {
|
||||
forceReasonCandidateNo.value = candidateNo;
|
||||
forceReason.value = '';
|
||||
return;
|
||||
}
|
||||
submittingCandidateNo.value = candidateNo;
|
||||
emit('resolveDuplicate', candidateNo, action, target, undefined, () => {
|
||||
submittingCandidateNo.value = '';
|
||||
});
|
||||
}
|
||||
|
||||
/** 提交内联强制新建原因,避免浏览器 prompt 丢失上下文或不可访问。 */
|
||||
function submitForceCreate(candidateNo: string): void {
|
||||
const candidate = candidates.value.find((item) => item.candidateNo === candidateNo);
|
||||
const reason = forceReason.value.trim();
|
||||
if (!candidate || !reason) return;
|
||||
submittingCandidateNo.value = candidateNo;
|
||||
emit(
|
||||
'resolveDuplicate',
|
||||
candidateNo,
|
||||
'force_create',
|
||||
candidate.duplicate?.matches?.[0]?.taskNo,
|
||||
reason,
|
||||
(success) => {
|
||||
submittingCandidateNo.value = '';
|
||||
if (success) forceReasonCandidateNo.value = '';
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** 发起后端决定的人工采纳或驳回;UI 不自行推导履约资格。 */
|
||||
function decideCandidate(candidateNo: string, action: 'promote' | 'reject'): void {
|
||||
submittingCandidateNo.value = candidateNo;
|
||||
const done = () => { submittingCandidateNo.value = ''; };
|
||||
if (action === 'promote') emit('promote', candidateNo, done);
|
||||
else emit('reject', candidateNo, done);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="candidates.length" class="w-full space-y-2 rounded-xl border border-default bg-surface px-3 py-2">
|
||||
<div class="flex items-center justify-between text-xs">
|
||||
<span class="font-semibold text-primary">{{ t('chat.shippingCandidateTitle') }}</span>
|
||||
<span class="text-muted">{{ t('chat.shippingCandidateCount', { count: candidates.length }) }}</span>
|
||||
</div>
|
||||
<div v-for="candidate in candidates" :key="candidate.candidateNo" class="rounded-lg border border-default bg-surface-soft p-2 text-xs">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="font-mono text-primary">{{ candidate.candidateNo }}</span>
|
||||
<span class="font-medium text-secondary">PO {{ candidate.poNumber || '-' }}</span>
|
||||
<span v-if="candidate.documentFilename" class="max-w-40 truncate text-muted">{{ candidate.documentFilename }}</span>
|
||||
<span :class="candidate.candidateStatus === 'accepted' ? 'text-emerald-700' : 'text-amber-700'">
|
||||
{{ candidate.candidateStatus === 'accepted' ? (candidate.acceptanceMode === 'automatic' ? t('chat.shippingCandidateAutoAccepted') : t('chat.shippingCandidateAccepted')) : (candidate.candidateStatus === 'rejected' ? t('chat.shippingCandidateRejected') : t('chat.shippingCandidateNeedsReview')) }}
|
||||
</span>
|
||||
<button v-if="candidate.actionButtons.includes('edit')" type="button" class="ml-auto text-brand-700 hover:underline" @click="startEdit(candidate.candidateNo)">
|
||||
{{ t('chat.shippingCandidateEdit') }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="candidate.conflicts.length" class="mt-1 text-amber-700">
|
||||
{{ t('chat.shippingCandidateConflictCount', { count: candidate.conflicts.length }) }}
|
||||
</div>
|
||||
<div
|
||||
v-if="candidate.customerMatches?.length"
|
||||
class="mt-2 overflow-x-auto rounded-lg border border-default bg-surface"
|
||||
>
|
||||
<div class="border-b border-default bg-surface-soft px-2 py-1.5 font-semibold text-primary">
|
||||
{{ t('chat.shippingCustomerMatch.title') }}
|
||||
</div>
|
||||
<table class="min-w-full text-[11px]">
|
||||
<thead class="text-left text-muted">
|
||||
<tr>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingCustomerMatch.role') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingCustomerMatch.rawName') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingCustomerMatch.standardName') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingCustomerMatch.shortCode') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingCustomerMatch.site') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingCustomerMatch.statusLabel') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="match in candidate.customerMatches" :key="match.role" class="border-t border-default/60">
|
||||
<td class="px-2 py-1 font-medium">{{ t(`chat.shippingCustomerMatch.roles.${match.role}`) }}</td>
|
||||
<td class="px-2 py-1">{{ displayCell(match.raw_name) }}</td>
|
||||
<td class="px-2 py-1">{{ displayCell(match.standard_name) }}</td>
|
||||
<td class="px-2 py-1 font-mono">{{ displayCell(match.short_code) }}</td>
|
||||
<td class="px-2 py-1">{{ displayCell(match.candidates?.find((item) => item.site_id === match.site_id)?.site_name) }}</td>
|
||||
<td class="px-2 py-1">{{ customerMatchStatus(match.status) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div
|
||||
v-if="editingCandidateNo !== candidate.candidateNo && readonlyLines(candidate).length"
|
||||
class="mt-2 overflow-x-auto rounded-lg border border-default bg-surface"
|
||||
>
|
||||
<table class="min-w-full text-[11px]">
|
||||
<thead class="bg-surface-soft text-left text-muted">
|
||||
<tr>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingNoticeUi.partNumber') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingNoticeUi.customerPartNumber') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingNoticeUi.awsPartNumber') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingCandidateQty') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingCandidateReservation') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingNoticeUi.inventorySourceHint') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="(line, index) in readonlyLines(candidate)"
|
||||
:key="`${candidate.candidateNo}-line-${index}`"
|
||||
class="border-t border-default/60"
|
||||
>
|
||||
<td class="px-2 py-1 font-mono">{{ displayCell(line.part_number) }}</td>
|
||||
<td class="px-2 py-1 font-mono">{{ displayCell(line.customer_part_number) }}</td>
|
||||
<td class="px-2 py-1 font-mono">{{ displayCell(line.aws_part_number) }}</td>
|
||||
<td class="px-2 py-1">{{ displayCell(line.qty) }}</td>
|
||||
<td class="px-2 py-1 font-mono">{{ displayCell(line.reservation_id) }}</td>
|
||||
<td class="px-2 py-1">{{ displayCell(line.inventory_source_hint) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div v-if="(candidate.missingFields || []).length" class="mt-1 text-amber-700">
|
||||
{{ t('chat.shippingCandidateMissingFields', { fields: (candidate.missingFields || []).join(', ') }) }}
|
||||
</div>
|
||||
<div v-if="candidate.duplicate?.blocking && !candidate.duplicateResolution" class="mt-2 flex flex-wrap items-center gap-2 text-amber-700">
|
||||
<span>{{ t('chat.shippingCandidateDuplicate', { task: candidate.duplicate.matches[0]?.taskNo || '-' }) }}</span>
|
||||
<button
|
||||
v-if="candidate.duplicate.allowedActions.includes('open_existing')"
|
||||
type="button"
|
||||
class="rounded border border-default bg-surface px-2 py-0.5"
|
||||
@click="resolveDuplicate(candidate.candidateNo, 'open_existing')"
|
||||
>{{ t('chat.shippingNoticeDuplicateOpenExisting') }}</button>
|
||||
<button
|
||||
v-if="candidate.duplicate.allowedActions.includes('create_revision')"
|
||||
type="button"
|
||||
class="rounded border border-default bg-surface px-2 py-0.5"
|
||||
@click="resolveDuplicate(candidate.candidateNo, 'create_revision')"
|
||||
>{{ t('chat.shippingNoticeDuplicateCreateRevision') }}</button>
|
||||
<button
|
||||
v-if="canForceCreate && candidate.duplicate.allowedActions.includes('force_create')"
|
||||
type="button"
|
||||
class="rounded border border-amber-300 bg-surface px-2 py-0.5"
|
||||
@click="resolveDuplicate(candidate.candidateNo, 'force_create')"
|
||||
>{{ t('chat.shippingNoticeDuplicateForceCreate') }}</button>
|
||||
</div>
|
||||
<div v-if="forceReasonCandidateNo === candidate.candidateNo" class="mt-2 flex gap-2">
|
||||
<input v-model="forceReason" :placeholder="t('chat.shippingCandidateForceReasonPrompt')" class="min-w-0 flex-1 rounded border border-default bg-surface px-2 py-1" />
|
||||
<button type="button" class="rounded bg-amber-600 px-2 py-1 text-white disabled:opacity-50" :disabled="!forceReason.trim() || submittingCandidateNo === candidate.candidateNo" @click="submitForceCreate(candidate.candidateNo)">{{ t('chat.shippingNoticeDuplicateConfirm') }}</button>
|
||||
<button type="button" class="text-muted" @click="forceReasonCandidateNo = ''">{{ t('common.cancel') }}</button>
|
||||
</div>
|
||||
<div v-else-if="candidate.duplicateResolution" class="mt-1 text-muted">
|
||||
{{ t('chat.shippingCandidateDuplicateResolved', { action: candidate.duplicateResolution.action }) }}
|
||||
</div>
|
||||
<div v-if="candidate.actionButtons.includes('promote') || candidate.actionButtons.includes('reject')" class="mt-2 flex gap-2">
|
||||
<button v-if="candidate.actionButtons.includes('promote')" type="button" class="rounded bg-brand-600 px-2 py-1 text-white disabled:opacity-50" :disabled="submittingCandidateNo === candidate.candidateNo" @click="decideCandidate(candidate.candidateNo, 'promote')">{{ t('chat.shippingCandidatePromote') }}</button>
|
||||
<button v-if="candidate.actionButtons.includes('reject')" type="button" class="rounded border border-default px-2 py-1 text-secondary disabled:opacity-50" :disabled="submittingCandidateNo === candidate.candidateNo" @click="decideCandidate(candidate.candidateNo, 'reject')">{{ t('chat.shippingCandidateReject') }}</button>
|
||||
</div>
|
||||
<div v-if="editingCandidateNo === candidate.candidateNo" class="mt-2 space-y-2">
|
||||
<label class="block">
|
||||
<span class="text-muted">{{ t('chat.shippingCandidatePoNumber') }}</span>
|
||||
<input v-model="editPoNumber" class="mt-1 w-full rounded border border-default bg-surface px-2 py-1 text-primary" />
|
||||
</label>
|
||||
<div v-for="(line, index) in editLines" :key="index" class="grid grid-cols-2 gap-2 rounded border border-default bg-surface p-2 md:grid-cols-4">
|
||||
<input v-model="line.part_number" :placeholder="t('chat.shippingNoticeUi.partNumber')" class="rounded border border-default px-2 py-1" />
|
||||
<input v-model="line.customer_part_number" :placeholder="t('chat.shippingNoticeUi.customerPartNumber')" class="rounded border border-default px-2 py-1" />
|
||||
<input v-model="line.aws_part_number" :placeholder="t('chat.shippingNoticeUi.awsPartNumber')" class="rounded border border-default px-2 py-1" />
|
||||
<input v-model="line.qty" type="number" min="0.0001" step="any" :placeholder="t('chat.shippingCandidateQty')" class="rounded border border-default px-2 py-1" />
|
||||
<input v-model="line.reservation_id" :placeholder="t('chat.shippingCandidateReservation')" class="rounded border border-default px-2 py-1" />
|
||||
<input v-model="line.inventory_source_hint" :placeholder="t('chat.shippingNoticeUi.inventorySourceHint')" class="rounded border border-default px-2 py-1" />
|
||||
<div class="flex gap-1">
|
||||
<input v-model="line.uom" :placeholder="t('chat.shippingCandidateUom')" class="min-w-0 flex-1 rounded border border-default px-2 py-1" />
|
||||
<button v-if="editLines.length > 1" type="button" class="text-red-600" @click="editLines.splice(index, 1)">×</button>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" class="text-brand-700 hover:underline" @click="addLine">{{ t('chat.shippingCandidateAddLine') }}</button>
|
||||
<div v-if="editError" class="text-red-600">{{ editError }}</div>
|
||||
<div class="flex justify-end gap-2">
|
||||
<button type="button" class="rounded px-2 py-1 text-secondary" @click="editingCandidateNo = ''">{{ t('common.cancel') }}</button>
|
||||
<button type="button" class="rounded bg-brand-600 px-2 py-1 text-white disabled:opacity-50" :disabled="submittingCandidateNo === candidate.candidateNo" @click="saveEdit">{{ t('chat.shippingCandidateSave') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -23,7 +23,6 @@ import ChatMessageAttachmentList from './ChatMessageAttachmentList.vue';
|
||||
import MaintenanceDeviceResultCard from './MaintenanceDeviceResultCard.vue';
|
||||
import ShippingMatchResultCard from './ShippingMatchResultCard.vue';
|
||||
import ShippingParseReviewMessage, { type ShippingParseReviewHandlers } from './ShippingParseReviewMessage.vue';
|
||||
import ShippingNoticeCandidateReview from '../ShippingNoticeCandidateReview.vue';
|
||||
import type { ShippingMessageHandlers } from './shippingMessageHandlers';
|
||||
import TrainingExamQuestionMessage, { type TrainingHandlers } from './TrainingExamQuestionMessage.vue';
|
||||
import TrainingVideoMessage from './TrainingVideoMessage.vue';
|
||||
@@ -32,8 +31,6 @@ import TrainingResultCard from './TrainingResultCard.vue';
|
||||
import ShippingOrderExtractionCard from '../shipping/ShippingOrderExtractionCard.vue';
|
||||
import type { ChatMessage, InlineDownloadFile, SourceFileLink } from '../../types/chat.types';
|
||||
import type { ShippingMatchResultPayload } from '../../types/shipping.types';
|
||||
import type { ShippingNoticePendingAttachment } from '../../types/shipping.types';
|
||||
import type { ShippingOrderExtractionReviewAttachment } from '../../types/chat.types';
|
||||
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
|
||||
import type { MaintenanceRecord } from '@/features/maintenance/types/record.types';
|
||||
|
||||
@@ -137,60 +134,12 @@ const showShippingActionsPanel = computed(() =>
|
||||
);
|
||||
const shippingOrderExtractionState = computed(() => message.shipping_order_extraction_state);
|
||||
const retryingOrderExtraction = ref(false);
|
||||
const reviewAttachmentsSection = ref<HTMLElement | null>(null);
|
||||
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 shippingOrderExtractionReviewAttachments = computed<ShippingNoticePendingAttachment[]>(() => {
|
||||
const payload = message.payload && typeof message.payload === 'object' ? message.payload as Record<string, unknown> : {};
|
||||
const reviews = Array.isArray(payload.shipping_order_extraction_review)
|
||||
? payload.shipping_order_extraction_review as ShippingOrderExtractionReviewAttachment[]
|
||||
: [];
|
||||
return reviews
|
||||
.filter((item) => item && Array.isArray(item.candidates) && item.candidates.length)
|
||||
.map((item) => ({
|
||||
id: `shipping-order-extraction-review-${item.intakeNo}`,
|
||||
kind: 'shipping_notice' as const,
|
||||
type: 'document' as const,
|
||||
intakeNo: item.intakeNo,
|
||||
uploadStatus: 'uploaded' as const,
|
||||
parseStatus: 'parsed' as const,
|
||||
uploadProgress: 100,
|
||||
originalFilename: item.originalFilename,
|
||||
fileSize: 0,
|
||||
candidates: item.candidates,
|
||||
}));
|
||||
});
|
||||
|
||||
const updateOrderExtractionCandidate = async (
|
||||
candidateNo: string,
|
||||
businessSummary: Record<string, unknown>,
|
||||
done: (success: boolean) => void,
|
||||
) => {
|
||||
await shippingHandlers.updateCandidate(candidateNo, businessSummary, done);
|
||||
};
|
||||
|
||||
const promoteOrderExtractionCandidate = async (candidateNo: string, done: (success: boolean) => void) => {
|
||||
await shippingHandlers.promoteCandidate(candidateNo, done);
|
||||
};
|
||||
|
||||
const rejectOrderExtractionCandidate = async (candidateNo: string, done: (success: boolean) => void) => {
|
||||
await shippingHandlers.rejectCandidate(candidateNo, done);
|
||||
};
|
||||
|
||||
const resolveOrderExtractionCandidateDuplicate = async (
|
||||
candidateNo: string,
|
||||
action: import('../../types/shipping.types').ShippingDuplicateAction,
|
||||
targetTaskNo: string | undefined,
|
||||
reason: string | undefined,
|
||||
done: (success: boolean) => void,
|
||||
) => {
|
||||
await shippingHandlers.resolveCandidateDuplicate(candidateNo, action, targetTaskNo, reason, done);
|
||||
};
|
||||
|
||||
/** 失败卡片复用原 Run 重试;按钮本地防重,成功后状态卡由 Run 轮询原位更新。 */
|
||||
const retryShippingOrderExtraction = async () => {
|
||||
if (!shippingOrderExtractionRunNo.value || retryingOrderExtraction.value) return;
|
||||
@@ -201,11 +150,6 @@ const retryShippingOrderExtraction = async () => {
|
||||
retryingOrderExtraction.value = false;
|
||||
}
|
||||
};
|
||||
const enterOrderExtractionManualReview = async () => {
|
||||
if (!shippingOrderExtractionReviewAttachments.value.length) return;
|
||||
await nextTick();
|
||||
reviewAttachmentsSection.value?.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
};
|
||||
const isLastMessage = computed(() => index === messageCount - 1 || (message.role === 'assistant' && isLatestAssistantMessage));
|
||||
const isCopied = computed(() => copiedIndex === index);
|
||||
const renderedMarkdown = computed(() => (
|
||||
@@ -732,26 +676,8 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
v-if="shippingOrderExtractionState"
|
||||
:state="shippingOrderExtractionState"
|
||||
:run-no="shippingOrderExtractionRunNo"
|
||||
:has-review-attachments="shippingOrderExtractionReviewAttachments.length > 0"
|
||||
@retry="retryShippingOrderExtraction"
|
||||
@enter-manual-review="enterOrderExtractionManualReview"
|
||||
/>
|
||||
<div
|
||||
v-if="shippingOrderExtractionReviewAttachments.length"
|
||||
ref="reviewAttachmentsSection"
|
||||
class="mb-3 space-y-2"
|
||||
>
|
||||
<ShippingNoticeCandidateReview
|
||||
v-for="attachment in shippingOrderExtractionReviewAttachments"
|
||||
:key="attachment.intakeNo"
|
||||
:attachment="attachment"
|
||||
:can-force-create="false"
|
||||
@update="updateOrderExtractionCandidate"
|
||||
@resolve-duplicate="resolveOrderExtractionCandidateDuplicate"
|
||||
@promote="promoteOrderExtractionCandidate"
|
||||
@reject="rejectOrderExtractionCandidate"
|
||||
/>
|
||||
</div>
|
||||
<LeaveMessageBlock
|
||||
v-if="isLeaveMessage"
|
||||
:message="message"
|
||||
|
||||
@@ -17,7 +17,6 @@ export interface ShippingMessageHandlers {
|
||||
removeLine: (msg: ChatMessage, lineIndex: number) => Promise<boolean>;
|
||||
retryOrderExtractionRun: (runNo: string) => Promise<boolean>;
|
||||
reparseOrderExtractionRun: (runNo: string, reason: 'rule_updated' | 'field_mapping_error' | 'document_quality' | 'other') => Promise<boolean>;
|
||||
updateCandidate: (candidateNo: string, businessSummary: Record<string, unknown>, done: (success: boolean) => void) => Promise<void>;
|
||||
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,73 @@
|
||||
<!--
|
||||
用途:渲染受控 PDF Blob,并仅为服务端验证的 bbox 绘制证据高亮。
|
||||
依赖:pdfjs-dist、Review Evidence DTO。
|
||||
逻辑:预览失败独立显示,不影响同页草稿编辑;缺少可靠 bbox 时只保留页码定位。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { nextTick, ref, watch } from 'vue';
|
||||
import * as pdfjs from 'pdfjs-dist';
|
||||
import workerUrl from 'pdfjs-dist/build/pdf.worker.min.mjs?url';
|
||||
import type { ShippingOrderReviewEvidence } from '../../types/shipping.api.types';
|
||||
|
||||
pdfjs.GlobalWorkerOptions.workerSrc = workerUrl;
|
||||
|
||||
const props = defineProps<{
|
||||
src: string;
|
||||
evidence?: ShippingOrderReviewEvidence | null;
|
||||
title: string;
|
||||
loadingText: string;
|
||||
unavailableText: string;
|
||||
}>();
|
||||
const canvas = ref<HTMLCanvasElement | null>(null);
|
||||
const loading = ref(false);
|
||||
const failed = ref(false);
|
||||
|
||||
/** 将当前页渲染到 canvas;高亮以 PDF viewport 为基准,绝不猜测不可靠坐标。 */
|
||||
const render = async () => {
|
||||
if (!props.src) return;
|
||||
loading.value = true;
|
||||
failed.value = false;
|
||||
try {
|
||||
const document = await pdfjs.getDocument(props.src).promise;
|
||||
const pageNo = Math.min(Math.max(props.evidence?.page_no || 1, 1), document.numPages);
|
||||
const page = await document.getPage(pageNo);
|
||||
const viewport = page.getViewport({ scale: 1.4 });
|
||||
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 bbox = props.evidence?.bbox;
|
||||
if (bbox) {
|
||||
context.save();
|
||||
context.fillStyle = 'rgba(250, 204, 21, 0.35)';
|
||||
context.strokeStyle = 'rgba(202, 138, 4, 0.95)';
|
||||
context.lineWidth = 2;
|
||||
const x = bbox.x0 * viewport.width;
|
||||
const y = bbox.y0 * viewport.height;
|
||||
const width = (bbox.x1 - bbox.x0) * viewport.width;
|
||||
const height = (bbox.y1 - bbox.y0) * viewport.height;
|
||||
context.fillRect(x, y, width, height);
|
||||
context.strokeRect(x, y, width, height);
|
||||
context.restore();
|
||||
}
|
||||
} catch {
|
||||
failed.value = true;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
watch(() => [props.src, props.evidence?.evidence_id], () => { void render(); }, { immediate: true });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="relative flex min-h-[360px] items-center justify-center overflow-auto bg-slate-100 p-3 dark:bg-slate-950">
|
||||
<!-- Keep the canvas mounted while PDF.js is loading; otherwise nextTick cannot obtain a render target. -->
|
||||
<canvas ref="canvas" :aria-label="title" class="max-w-full bg-white shadow" :class="{ invisible: loading || failed }" />
|
||||
<span v-if="loading" class="absolute text-sm text-slate-500">{{ loadingText }}</span>
|
||||
<span v-else-if="failed" class="absolute text-sm text-rose-600">{{ unavailableText }}</span>
|
||||
</div>
|
||||
</template>
|
||||
@@ -3,7 +3,7 @@
|
||||
* features/chat/components/shipping/ShippingOrderDocumentResultItem.vue
|
||||
* 用途:渲染单个 PDF 的订单抽取结果摘要,供详情抽屉按文档逐项展示。
|
||||
* 依赖:订单抽取文档 DTO、vue-i18n。
|
||||
* 逻辑:只显示用户可理解的业务字段;人工复核入口复用现有候选审核区,不直接暴露内部证据细节。
|
||||
* 逻辑:只显示用户可理解的业务字段;人工复核由上层统一跳转独立工作台。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
@@ -12,14 +12,13 @@ import type { ShippingOrderExtractionDocumentResult } from '../../types/shipping
|
||||
|
||||
const props = defineProps<{
|
||||
document: ShippingOrderExtractionDocumentResult;
|
||||
hasReviewAttachments?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
enterManualReview: [];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const { t, te, locale } = useI18n();
|
||||
|
||||
const statusTone = computed(() => {
|
||||
switch (props.document.status) {
|
||||
@@ -36,6 +35,23 @@ const statusTone = computed(() => {
|
||||
});
|
||||
|
||||
const statusLabel = computed(() => t(`chat.shippingOrderExtractionDocumentStatus.${props.document.status}`));
|
||||
const statusActivityLabel = computed(() => {
|
||||
const key = `chat.shippingOrderExtractionActivity.${props.document.activity_event_code || props.document.status}`;
|
||||
return te(key) ? t(key) : statusLabel.value;
|
||||
});
|
||||
const formatTime = (value: string | null | undefined): string => {
|
||||
const date = new Date(String(value || ''));
|
||||
if (Number.isNaN(date.getTime())) return '';
|
||||
return new Intl.DateTimeFormat(String(locale.value || 'zh-CN'), {
|
||||
hour: '2-digit', minute: '2-digit', hour12: false,
|
||||
}).format(date);
|
||||
};
|
||||
const activityTimeLabel = computed(() => {
|
||||
if (props.document.finished_at) return t('chat.shippingOrderExtractionDocumentTiming.finished', { time: formatTime(props.document.finished_at) });
|
||||
if (props.document.last_activity_at) return t('chat.shippingOrderExtractionDocumentTiming.updated', { time: formatTime(props.document.last_activity_at) });
|
||||
if (props.document.started_at) return t('chat.shippingOrderExtractionDocumentTiming.started', { time: formatTime(props.document.started_at) });
|
||||
return '';
|
||||
});
|
||||
const reasonLabel = computed(() => (
|
||||
props.document.reason_code
|
||||
? t(`chat.shippingOrderExtractionReason.${props.document.reason_code}`)
|
||||
@@ -81,13 +97,9 @@ const reviewFieldLabel = (fieldCode: string | null | undefined): string => {
|
||||
};
|
||||
|
||||
const canEnterManualReview = computed(() => (
|
||||
props.hasReviewAttachments
|
||||
&& props.document.available_actions.some((action) => action === 'review_candidate' || action === 'manual_review')
|
||||
));
|
||||
const canViewEvidence = computed(() => (
|
||||
props.hasReviewAttachments
|
||||
&& props.document.available_actions.includes('view_evidence')
|
||||
props.document.available_actions.some((action) => action === 'review_candidate' || action === 'manual_review')
|
||||
));
|
||||
const canViewEvidence = computed(() => props.document.available_actions.includes('view_evidence'));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -105,7 +117,11 @@ const canViewEvidence = computed(() => (
|
||||
<div class="truncate text-sm font-semibold">{{ document.file_name || t('chat.shippingOrderExtractionUnknownDocument') }}</div>
|
||||
<span class="rounded-full bg-black/10 px-2 py-0.5 text-[11px] dark:bg-white/10">{{ statusLabel }}</span>
|
||||
</div>
|
||||
<div v-if="['pending', 'routing', 'matching_profile', 'extracting', 'merging_supplement'].includes(document.status) || document.activity_event_code" class="mt-1 text-xs font-medium opacity-85">
|
||||
{{ statusActivityLabel }}
|
||||
</div>
|
||||
<div class="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs opacity-85">
|
||||
<span v-if="activityTimeLabel">{{ activityTimeLabel }}</span>
|
||||
<span v-if="document.selection_batch">
|
||||
{{ t('chat.shippingOrderExtractionSelectionBatch', { batch: document.selection_batch }) }}
|
||||
</span>
|
||||
|
||||
@@ -8,6 +8,7 @@ import { nextTick } from 'vue';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { createMemoryHistory, createRouter } from 'vue-router';
|
||||
import chatZhCn from '@/locales/zh-CN/chat.json';
|
||||
import ShippingOrderDocumentResultItem from './ShippingOrderDocumentResultItem.vue';
|
||||
import ShippingOrderExtractionCard from './ShippingOrderExtractionCard.vue';
|
||||
@@ -43,6 +44,14 @@ const flushUi = async () => {
|
||||
await nextTick();
|
||||
};
|
||||
|
||||
const makeRouter = () => createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/chat/:agentId', name: 'Chat', component: { template: '<div />' } },
|
||||
{ path: '/chat/:agentId/order-review/:runNo', name: 'ShippingOrderReview', component: { template: '<div />' } },
|
||||
],
|
||||
});
|
||||
|
||||
const buildState = (patch: Partial<ShippingOrderExtractionState> = {}): ShippingOrderExtractionState => ({
|
||||
status: 'processing',
|
||||
summary: {
|
||||
@@ -116,7 +125,7 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('loads documents once when opening details from server actions', async () => {
|
||||
it('refreshes documents whenever the details drawer is opened', async () => {
|
||||
api.listDocuments.mockResolvedValue({ items: [buildDocument()] });
|
||||
api.listProgressEvents.mockResolvedValue({ items: [buildProgressEvent()] });
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
@@ -189,21 +198,24 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
await detailButton!.trigger('click');
|
||||
await flushUi();
|
||||
|
||||
expect(api.listDocuments).toHaveBeenCalledTimes(1);
|
||||
expect(api.listProgressEvents).toHaveBeenCalledTimes(1);
|
||||
expect(api.listDocuments).toHaveBeenCalledTimes(2);
|
||||
expect(api.listProgressEvents).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('emits manual review directly when attachments are already available', async () => {
|
||||
it('routes manual review directly to the dedicated workspace', async () => {
|
||||
const router = makeRouter();
|
||||
await router.push({ name: 'Chat', params: { agentId: 'agent-1' } });
|
||||
await router.isReady();
|
||||
const pushSpy = vi.spyOn(router, 'push');
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
availableActions: ['enter_manual_review'],
|
||||
}),
|
||||
runNo: 'SNER-002',
|
||||
hasReviewAttachments: true,
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
plugins: [i18n, router],
|
||||
stubs: {
|
||||
teleport: true,
|
||||
},
|
||||
@@ -215,10 +227,37 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
|
||||
await reviewButton!.trigger('click');
|
||||
|
||||
expect(wrapper.emitted('enterManualReview')).toHaveLength(1);
|
||||
await vi.waitFor(() => expect(pushSpy).toHaveBeenCalled());
|
||||
expect(pushSpy).toHaveBeenCalledWith({
|
||||
name: 'Chat',
|
||||
params: { agentId: 'agent-1' },
|
||||
query: { mode: 'order-review', run_no: 'SNER-002' },
|
||||
});
|
||||
expect(api.listDocuments).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('preserves the originating conversation when entering manual review', async () => {
|
||||
const router = makeRouter();
|
||||
await router.push({ name: 'Chat', params: { agentId: 'agent-1' }, query: { conversation_id: 'conv-123' } });
|
||||
await router.isReady();
|
||||
const pushSpy = vi.spyOn(router, 'push');
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState({ availableActions: ['enter_manual_review'] }), runNo: 'SNER-003' },
|
||||
global: { plugins: [i18n, router], stubs: { teleport: true } },
|
||||
});
|
||||
|
||||
const reviewButton = wrapper.findAll('button').find((item) => item.text().includes('进入人工复核'));
|
||||
expect(reviewButton).toBeTruthy();
|
||||
await reviewButton!.trigger('click');
|
||||
|
||||
await vi.waitFor(() => expect(pushSpy).toHaveBeenCalled());
|
||||
expect(pushSpy).toHaveBeenCalledWith({
|
||||
name: 'Chat',
|
||||
params: { agentId: 'agent-1' },
|
||||
query: { conversation_id: 'conv-123', mode: 'order-review', run_no: 'SNER-003' },
|
||||
});
|
||||
});
|
||||
|
||||
it('emits retry for failed attachments without mutating state locally', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
@@ -305,7 +344,6 @@ describe('ShippingOrderExtractionDetailsDrawer', () => {
|
||||
loadFailed: false,
|
||||
progressLoading: false,
|
||||
progressLoadFailed: false,
|
||||
hasReviewAttachments: true,
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
@@ -369,7 +407,6 @@ describe('ShippingOrderDocumentResultItem', () => {
|
||||
},
|
||||
available_actions: ['view_evidence', 'manual_review'],
|
||||
}),
|
||||
hasReviewAttachments: true,
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
* 依赖:订单抽取 Run 状态卡 DTO、documents API、详情抽屉。
|
||||
* 逻辑:卡片只显示 Run 汇总、当前活动和下一步动作;逐 PDF 结果与 Run 事实时间线延迟到抽屉内按需加载。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { CircleCheck, CircleX, LoaderCircle, TriangleAlert } from 'lucide-vue-next';
|
||||
import {
|
||||
@@ -22,7 +23,6 @@ import ShippingOrderExtractionDetailsDrawer from './ShippingOrderExtractionDetai
|
||||
const props = defineProps<{
|
||||
state: ShippingOrderExtractionState;
|
||||
runNo?: string;
|
||||
hasReviewAttachments?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -31,6 +31,8 @@ const emit = defineEmits<{
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
const detailsOpen = ref(false);
|
||||
const documents = ref<ShippingOrderExtractionDocumentResult[]>([]);
|
||||
@@ -41,6 +43,17 @@ const documentsLoadedForRun = ref('');
|
||||
const loadingProgressEvents = ref(false);
|
||||
const progressEventsLoadFailed = ref(false);
|
||||
const progressEventsLoadedForRun = ref('');
|
||||
let detailsRefreshTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const detailsFreshnessKey = computed(() => JSON.stringify({
|
||||
runNo: props.runNo || '',
|
||||
status: props.state.status,
|
||||
phase: props.state.currentActivity?.eventCode || '',
|
||||
total: props.state.summary.totalDocuments,
|
||||
completed: props.state.summary.completedDocuments,
|
||||
reviewRequired: props.state.summary.reviewRequiredDocuments,
|
||||
failed: props.state.summary.failedDocuments,
|
||||
}));
|
||||
|
||||
watch(
|
||||
() => props.runNo,
|
||||
@@ -152,11 +165,16 @@ const currentActivityContextSummary = computed(() => {
|
||||
return parts.join(' · ');
|
||||
});
|
||||
|
||||
const openDetails = async () => {
|
||||
/**
|
||||
* 刷新抽屉中的 Run 详情。
|
||||
*
|
||||
* 文档列表可能在布局 Job 完成后才落库;抽屉绝不能缓存首次打开时的空结果,
|
||||
* 否则聊天卡已显示新状态而详情仍停留在旧的“暂无结果”。
|
||||
*/
|
||||
const refreshDetails = async () => {
|
||||
if (!props.runNo) return;
|
||||
detailsOpen.value = true;
|
||||
const tasks: Promise<void>[] = [];
|
||||
if (documentsLoadedForRun.value !== props.runNo && !loadingDocuments.value) {
|
||||
if (!loadingDocuments.value) {
|
||||
loadingDocuments.value = true;
|
||||
documentsLoadFailed.value = false;
|
||||
tasks.push(
|
||||
@@ -173,7 +191,7 @@ const openDetails = async () => {
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (progressEventsLoadedForRun.value !== props.runNo && !loadingProgressEvents.value) {
|
||||
if (!loadingProgressEvents.value) {
|
||||
loadingProgressEvents.value = true;
|
||||
progressEventsLoadFailed.value = false;
|
||||
tasks.push(
|
||||
@@ -195,17 +213,55 @@ const openDetails = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
const openDetails = async () => {
|
||||
if (!props.runNo) return;
|
||||
detailsOpen.value = true;
|
||||
await refreshDetails();
|
||||
};
|
||||
|
||||
/** 详情打开期间独立刷新,避免长任务只在聊天卡状态变更时才显示新阶段。 */
|
||||
const stopDetailsRefresh = () => {
|
||||
if (detailsRefreshTimer) clearInterval(detailsRefreshTimer);
|
||||
detailsRefreshTimer = null;
|
||||
};
|
||||
|
||||
watch(detailsOpen, (open) => {
|
||||
stopDetailsRefresh();
|
||||
if (!open || !props.runNo || !['queued', 'processing'].includes(props.state.status)) return;
|
||||
detailsRefreshTimer = setInterval(() => void refreshDetails(), 2000);
|
||||
});
|
||||
|
||||
watch(() => props.state.status, (status) => {
|
||||
if (!['queued', 'processing'].includes(status)) stopDetailsRefresh();
|
||||
});
|
||||
|
||||
onBeforeUnmount(stopDetailsRefresh);
|
||||
|
||||
watch(detailsFreshnessKey, () => {
|
||||
if (detailsOpen.value) void refreshDetails();
|
||||
});
|
||||
|
||||
/** 新建单前复核统一进入独立工作台,不能再落入聊天内旧 Candidate 编辑区。 */
|
||||
const openReviewWorkspace = async () => {
|
||||
if (!props.runNo) return;
|
||||
await router.push({
|
||||
name: 'Chat',
|
||||
params: { agentId: String(route.params.agentId || '') },
|
||||
query: {
|
||||
...route.query,
|
||||
mode: 'order-review',
|
||||
run_no: props.runNo,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const handleActionClick = async (action: string) => {
|
||||
switch (action) {
|
||||
case 'view_details':
|
||||
await openDetails();
|
||||
return;
|
||||
case 'enter_manual_review':
|
||||
if (props.hasReviewAttachments) {
|
||||
emit('enterManualReview');
|
||||
} else {
|
||||
await openDetails();
|
||||
}
|
||||
await openReviewWorkspace();
|
||||
return;
|
||||
case 'retry_failed_attachments':
|
||||
emit('retry');
|
||||
@@ -235,7 +291,6 @@ const handleActionClick = async (action: string) => {
|
||||
<div class="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-xs opacity-90">
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.total', { count: state.summary.totalDocuments }) }}</span>
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.completedProgress', { value: completedLabel }) }}</span>
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.candidates', { count: state.summary.candidateCount }) }}</span>
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.reviewRequired', { count: state.summary.reviewRequiredDocuments }) }}</span>
|
||||
<span v-if="state.summary.failedDocuments > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.failed', { count: state.summary.failedDocuments }) }}
|
||||
@@ -294,9 +349,8 @@ const handleActionClick = async (action: string) => {
|
||||
:load-failed="documentsLoadFailed"
|
||||
:progress-loading="loadingProgressEvents"
|
||||
:progress-load-failed="progressEventsLoadFailed"
|
||||
:has-review-attachments="hasReviewAttachments"
|
||||
@close="detailsOpen = false"
|
||||
@enter-manual-review="emit('enterManualReview')"
|
||||
@enter-manual-review="openReviewWorkspace"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
+23
-49
@@ -5,7 +5,7 @@
|
||||
* 依赖:订单抽取状态卡、文档结果项、订单抽取 progress-events DTO、vue-i18n。
|
||||
* 逻辑:聊天摘要卡只显示概览;需要查看逐文档结果和每轮事件原因时由本抽屉承接新的 Run 级事实时间线。
|
||||
*/
|
||||
import { onBeforeUnmount, watch } from 'vue';
|
||||
import { onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { X } from 'lucide-vue-next';
|
||||
import type { ShippingOrderExtractionState } from '../../types/chat.types';
|
||||
@@ -25,7 +25,6 @@ const props = defineProps<{
|
||||
loadFailed: boolean;
|
||||
progressLoading: boolean;
|
||||
progressLoadFailed: boolean;
|
||||
hasReviewAttachments?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -35,6 +34,7 @@ const emit = defineEmits<{
|
||||
|
||||
const { t, te, locale } = useI18n();
|
||||
let removeKeydownListener: (() => void) | null = null;
|
||||
const timelineOpen = ref(false);
|
||||
|
||||
const translateReasonCodes = (codes: string[] | undefined): string[] => (
|
||||
(codes || [])
|
||||
@@ -155,37 +155,27 @@ onBeforeUnmount(() => {
|
||||
</header>
|
||||
|
||||
<div class="flex-1 space-y-3 overflow-y-auto px-4 py-4">
|
||||
<div
|
||||
v-if="state.selectionPlan?.totalAttachmentCount || state.unitSummary?.technicalFailureReasonCodes?.length"
|
||||
class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-3 text-xs text-slate-700 dark:border-slate-700 dark:bg-slate-900/60 dark:text-slate-200"
|
||||
>
|
||||
<div v-if="state.selectionPlan?.totalAttachmentCount">
|
||||
{{ t('chat.shippingOrderExtractionPlanSummary', {
|
||||
total: state.selectionPlan.totalAttachmentCount,
|
||||
groups: state.selectionPlan.groupCount || 0,
|
||||
attachments: state.selectionPlan.maxInitialAttachments || 0,
|
||||
concurrency: state.selectionPlan.maxInitialConcurrency || 0,
|
||||
}) }}
|
||||
</div>
|
||||
<div v-if="state.unitSummary?.reviewRequiredReasonCodes?.length" class="mt-1">
|
||||
{{ t('chat.shippingOrderExtractionReviewReasonCodes', {
|
||||
codes: translateReasonCodes(state.unitSummary.reviewRequiredReasonCodes).join(' / '),
|
||||
}) }}
|
||||
</div>
|
||||
<div v-if="state.unitSummary?.expansionTriggerReasonCodes?.length" class="mt-1">
|
||||
{{ t('chat.shippingOrderExtractionExpansionTriggerCodes', {
|
||||
codes: translateReasonCodes(state.unitSummary.expansionTriggerReasonCodes).join(' / '),
|
||||
}) }}
|
||||
</div>
|
||||
<div v-if="state.unitSummary?.technicalFailureReasonCodes?.length" class="mt-1">
|
||||
{{ t('chat.shippingOrderExtractionTechnicalFailureCodes', {
|
||||
codes: state.unitSummary.technicalFailureReasonCodes.join(', '),
|
||||
}) }}
|
||||
</div>
|
||||
<div v-if="loading" class="rounded-lg border border-dashed border-slate-300 px-3 py-4 text-sm text-slate-600 dark:border-slate-700 dark:text-slate-300">
|
||||
{{ t('chat.shippingOrderExtractionDocumentsLoading') }}
|
||||
</div>
|
||||
<div class="rounded-lg border border-slate-200 bg-white px-3 py-3 dark:border-slate-700 dark:bg-slate-950/40">
|
||||
<div class="text-xs font-semibold text-slate-900 dark:text-slate-100">
|
||||
{{ t('chat.shippingOrderExtractionTimelineTitle') }}
|
||||
<div v-else-if="loadFailed" class="rounded-lg border border-amber-300 bg-amber-50 px-3 py-4 text-sm text-amber-900 dark:border-amber-700 dark:bg-amber-950/30 dark:text-amber-100">
|
||||
{{ t('chat.shippingOrderExtractionDocumentsUnavailable') }}
|
||||
</div>
|
||||
<div v-else-if="documents.length === 0" class="rounded-lg border border-dashed border-slate-300 px-3 py-4 text-sm text-slate-600 dark:border-slate-700 dark:text-slate-300">
|
||||
{{ t('chat.shippingOrderExtractionNoDocuments') }}
|
||||
</div>
|
||||
<ShippingOrderDocumentResultItem
|
||||
v-for="document in documents"
|
||||
:key="document.unit_id"
|
||||
:document="document"
|
||||
@enter-manual-review="emit('enterManualReview')"
|
||||
/>
|
||||
<details :open="timelineOpen" class="rounded-lg border border-slate-200 bg-white px-3 py-3 dark:border-slate-700 dark:bg-slate-950/40" @toggle="timelineOpen = ($event.currentTarget as HTMLDetailsElement).open">
|
||||
<summary class="cursor-pointer text-xs font-semibold text-slate-900 dark:text-slate-100">{{ t('chat.shippingOrderExtractionTimelineTitle') }}</summary>
|
||||
<div v-if="state.selectionPlan?.totalAttachmentCount || state.unitSummary?.technicalFailureReasonCodes?.length" class="mt-3 rounded-lg bg-slate-50 px-3 py-3 text-xs text-slate-700 dark:bg-slate-900/60 dark:text-slate-200">
|
||||
<div v-if="state.selectionPlan?.totalAttachmentCount">{{ t('chat.shippingOrderExtractionPlanSummary', { total: state.selectionPlan.totalAttachmentCount, groups: state.selectionPlan.groupCount || 0, attachments: state.selectionPlan.maxInitialAttachments || 0, concurrency: state.selectionPlan.maxInitialConcurrency || 0 }) }}</div>
|
||||
<div v-if="state.unitSummary?.reviewRequiredReasonCodes?.length" class="mt-1">{{ t('chat.shippingOrderExtractionReviewReasonCodes', { codes: translateReasonCodes(state.unitSummary.reviewRequiredReasonCodes).join(' / ') }) }}</div>
|
||||
<div v-if="state.unitSummary?.technicalFailureReasonCodes?.length" class="mt-1">{{ t('chat.shippingOrderExtractionTechnicalFailureCodes', { codes: state.unitSummary.technicalFailureReasonCodes.join(', ') }) }}</div>
|
||||
</div>
|
||||
<div
|
||||
v-if="progressLoading"
|
||||
@@ -227,23 +217,7 @@ onBeforeUnmount(() => {
|
||||
</div>
|
||||
</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div v-if="loading" class="rounded-lg border border-dashed border-slate-300 px-3 py-4 text-sm text-slate-600 dark:border-slate-700 dark:text-slate-300">
|
||||
{{ t('chat.shippingOrderExtractionDocumentsLoading') }}
|
||||
</div>
|
||||
<div v-else-if="loadFailed" class="rounded-lg border border-amber-300 bg-amber-50 px-3 py-4 text-sm text-amber-900 dark:border-amber-700 dark:bg-amber-950/30 dark:text-amber-100">
|
||||
{{ t('chat.shippingOrderExtractionDocumentsUnavailable') }}
|
||||
</div>
|
||||
<div v-else-if="documents.length === 0" class="rounded-lg border border-dashed border-slate-300 px-3 py-4 text-sm text-slate-600 dark:border-slate-700 dark:text-slate-300">
|
||||
{{ t('chat.shippingOrderExtractionNoDocuments') }}
|
||||
</div>
|
||||
<ShippingOrderDocumentResultItem
|
||||
v-for="document in documents"
|
||||
:key="document.unit_id"
|
||||
:document="document"
|
||||
:has-review-attachments="hasReviewAttachments"
|
||||
@enter-manual-review="emit('enterManualReview')"
|
||||
/>
|
||||
</details>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
@@ -551,7 +551,6 @@ export function useChatPage() {
|
||||
},
|
||||
retryShippingNoticeAttachment: shipping.retryShippingNoticeAttachment,
|
||||
setShippingCandidateSelected: shipping.setShippingCandidateSelected,
|
||||
updateShippingCandidateSummary: shipping.updateShippingCandidateSummary,
|
||||
resolveShippingCandidateDuplicate: shipping.resolveShippingCandidateDuplicate,
|
||||
showShippingDuplicateDialog: shipping.showShippingDuplicateDialog,
|
||||
shippingDuplicateAttachment: shipping.shippingDuplicateAttachment,
|
||||
|
||||
@@ -1007,24 +1007,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
}
|
||||
};
|
||||
|
||||
/** 保存 Candidate 结构化修订,并保留服务端校验错误。 */
|
||||
const updateShippingCandidateSummary = async (
|
||||
candidateNo: string,
|
||||
businessSummary: Record<string, unknown>,
|
||||
done?: (success: boolean) => void,
|
||||
) => {
|
||||
try {
|
||||
await shippingIntakes.updateCandidateSummary(candidateNo, businessSummary);
|
||||
const candidate = shippingIntakes.noticeAttachments.value.flatMap((item) => item.candidates || []).find((item) => item.candidateNo === candidateNo);
|
||||
if (candidate) await shippingOrderExtractionRuns.updateCandidateReviewSnapshot(candidate);
|
||||
msg.success(t('chat.shippingCandidateUpdateDone'));
|
||||
done?.(true);
|
||||
} catch (error: unknown) {
|
||||
msg.warning(error instanceof Error ? error.message : t('chat.shippingCandidateUpdateFailed'));
|
||||
done?.(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** 保存 Candidate 重复决策,并统一展示权限或目标漂移错误。 */
|
||||
const resolveShippingCandidateDuplicate = async (
|
||||
candidateNo: string,
|
||||
@@ -1121,6 +1103,12 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
t,
|
||||
});
|
||||
|
||||
// 快览完成后补充可见的用户请求;用户已输入备注时绝不覆盖。
|
||||
watch([isShippingNoticeAgent, shippingIntakes.allParsedReady], ([isShippingAgent, allParsedReady]) => {
|
||||
if (!isShippingAgent || !allParsedReady || input.value.trim()) return;
|
||||
input.value = t('chat.shippingOrderExtractionDefaultUserMessage');
|
||||
});
|
||||
|
||||
const { handleShippingMenuAction, handleShippingActionClick } = createShippingMenuHandlers({
|
||||
isThinking,
|
||||
currentAgentId,
|
||||
@@ -1510,7 +1498,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
reparseOrderExtractionRun: shippingOrderExtractionRuns.reparseRun,
|
||||
shippingNoticeAllReadyForConfirmation: shippingIntakes.allReadyForConfirmation,
|
||||
setShippingCandidateSelected,
|
||||
updateShippingCandidateSummary,
|
||||
resolveShippingCandidateDuplicate,
|
||||
promoteShippingCandidate,
|
||||
rejectShippingCandidate,
|
||||
|
||||
@@ -37,7 +37,6 @@ type ShippingHandlerSource = Pick<
|
||||
| 'removeShippingParseReviewLine'
|
||||
| 'retryOrderExtractionRun'
|
||||
| 'reparseOrderExtractionRun'
|
||||
| 'updateShippingCandidateSummary'
|
||||
| 'resolveShippingCandidateDuplicate'
|
||||
| 'promoteShippingCandidate'
|
||||
| 'rejectShippingCandidate'
|
||||
@@ -76,7 +75,6 @@ export function createShippingMessageHandlers(shipping: ShippingHandlerSource):
|
||||
removeLine: shipping.removeShippingParseReviewLine,
|
||||
retryOrderExtractionRun: shipping.retryOrderExtractionRun,
|
||||
reparseOrderExtractionRun: shipping.reparseOrderExtractionRun,
|
||||
updateCandidate: shipping.updateShippingCandidateSummary,
|
||||
resolveCandidateDuplicate: shipping.resolveShippingCandidateDuplicate,
|
||||
promoteCandidate: shipping.promoteShippingCandidate,
|
||||
rejectCandidate: shipping.rejectShippingCandidate,
|
||||
|
||||
@@ -27,4 +27,24 @@ describe('createChatPageLocalMessageApi', () => {
|
||||
expect(conversationId.value).toBe('conv-local');
|
||||
expect(message.chat_log_id).toBe(42);
|
||||
});
|
||||
|
||||
it('persists user attachment snapshots so history restores the submitted files', async () => {
|
||||
const conversationId = ref<string | null>('conv-attachments');
|
||||
api.saveLocalChatMessage.mockResolvedValue({ chat_log_id: 43 });
|
||||
const helpers = createChatPageLocalMessageApi({ conversationId, currentAgentId: computed(() => 7) });
|
||||
const message: ChatMessage = {
|
||||
role: 'user', type: 'text', content: '',
|
||||
attachments: [{ name: 'orders.eml', size: 128, extension: 'eml', type: 'document', source: 'shipping_notice' }],
|
||||
payload: { formId: 'shipping-order-extraction-user:SNER-ATTACHMENTS' },
|
||||
};
|
||||
|
||||
await helpers.saveLocalMessageToBackend(message);
|
||||
|
||||
expect(api.saveLocalChatMessage).toHaveBeenCalledWith(expect.objectContaining({
|
||||
payload: {
|
||||
formId: 'shipping-order-extraction-user:SNER-ATTACHMENTS',
|
||||
user_attachments: message.attachments,
|
||||
},
|
||||
}));
|
||||
});
|
||||
});
|
||||
@@ -35,7 +35,15 @@ export function createChatPageLocalMessageApi(ctx: ChatPageLocalMessageContext)
|
||||
role: localMsg.role,
|
||||
type: localMsg.type,
|
||||
content: localMsg.content,
|
||||
payload: localMsg.payload,
|
||||
// 专用业务发送路径也必须持久化附件展示快照;否则会话同步会用不含附件的历史记录替换当前气泡。
|
||||
payload: {
|
||||
...(localMsg.payload && typeof localMsg.payload === 'object'
|
||||
? localMsg.payload as Record<string, unknown>
|
||||
: {}),
|
||||
...(localMsg.role === 'user' && localMsg.attachments?.length
|
||||
? { user_attachments: localMsg.attachments }
|
||||
: {}),
|
||||
},
|
||||
query: userQuery,
|
||||
agent_id: ctx.currentAgentId.value,
|
||||
});
|
||||
|
||||
@@ -154,7 +154,9 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
|
||||
onAssistantMessageFinished: ctx.onAssistantMessageFinished,
|
||||
},
|
||||
);
|
||||
if (!sent.accepted) {
|
||||
// Keep the legacy boolean result compatible while callers migrate to ChatMessageSendResult.
|
||||
const accepted = (sent as unknown) === true || Boolean(sent.accepted);
|
||||
if (!accepted) {
|
||||
if (shouldClearInput) ctx.input.value = content;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* features/chat/shipping-review/useShippingOrderReview.ts
|
||||
* 用途:加载建单前复核 Run 和当前 PDF Case 的只读数据。
|
||||
* 依赖:shipping API、Vue 响应式状态。
|
||||
* 逻辑:路由刷新后以 runNo 重建列表,再按 case_no 加载详情;阶段 2 不写入草稿。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import {
|
||||
addWorkspaceShippingOrderReviewLine,
|
||||
createWorkspaceShippingOrderReviewManualDraft,
|
||||
createWorkspaceShippingOrderReviewReplacementIntake,
|
||||
createWorkspaceShippingOrderReviewReplacementRun,
|
||||
copyWorkspaceShippingOrderReviewLine,
|
||||
confirmWorkspaceShippingOrderReviewCase,
|
||||
deleteWorkspaceShippingOrderReviewLine,
|
||||
getWorkspaceShippingOrderReviewCase,
|
||||
getWorkspaceShippingOrderReviewEvidence,
|
||||
getWorkspaceShippingOrderReviewPreview,
|
||||
getShippingNoticeIntake,
|
||||
getWorkspaceShippingOrderReviewRun,
|
||||
patchWorkspaceShippingOrderReviewHeaderField,
|
||||
patchWorkspaceShippingOrderReviewLineField,
|
||||
markWorkspaceShippingOrderReviewNonOrder,
|
||||
markWorkspaceShippingOrderReviewQualityIssue,
|
||||
reparseWorkspaceShippingOrderReviewDocument,
|
||||
validateWorkspaceShippingOrderReviewDraft,
|
||||
} from '../api/shipping.api';
|
||||
import type { ShippingOrderReviewCase, ShippingOrderReviewEvidence, ShippingOrderReviewRun } from '../types/shipping.api.types';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
|
||||
export function useShippingOrderReview() {
|
||||
const reviewRun = ref<ShippingOrderReviewRun | null>(null);
|
||||
const activeCase = ref<ShippingOrderReviewCase | null>(null);
|
||||
const loading = ref(false);
|
||||
const loadFailed = ref(false);
|
||||
const saving = ref(false);
|
||||
const saveFailed = ref(false);
|
||||
const evidence = ref<ShippingOrderReviewEvidence[]>([]);
|
||||
const previewUrl = ref('');
|
||||
|
||||
/** 加载 Run 汇总后优先恢复 URL 指定 Case,否则打开首个 PDF。 */
|
||||
const load = async (runNo: string, preferredCaseNo?: string) => {
|
||||
loading.value = true;
|
||||
loadFailed.value = false;
|
||||
try {
|
||||
const run = await getWorkspaceShippingOrderReviewRun(runNo);
|
||||
reviewRun.value = run;
|
||||
const caseNo = preferredCaseNo || run.items[0]?.case_no;
|
||||
activeCase.value = caseNo ? await getWorkspaceShippingOrderReviewCase(caseNo) : null;
|
||||
evidence.value = caseNo ? (await getWorkspaceShippingOrderReviewEvidence(caseNo)).items : [];
|
||||
if (previewUrl.value) URL.revokeObjectURL(previewUrl.value);
|
||||
previewUrl.value = '';
|
||||
if (caseNo) {
|
||||
try { previewUrl.value = URL.createObjectURL(await getWorkspaceShippingOrderReviewPreview(caseNo)); } catch { /* PDF failure must not block the draft. */ }
|
||||
}
|
||||
} catch {
|
||||
loadFailed.value = true;
|
||||
reviewRun.value = null;
|
||||
activeCase.value = null;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 切换 PDF 时仅换详情,列表保持已加载结果,避免重复请求。 */
|
||||
const selectCase = async (caseNo: string) => {
|
||||
const [detail, result] = await Promise.all([
|
||||
getWorkspaceShippingOrderReviewCase(caseNo),
|
||||
getWorkspaceShippingOrderReviewEvidence(caseNo),
|
||||
]);
|
||||
activeCase.value = detail;
|
||||
evidence.value = result.items;
|
||||
if (previewUrl.value) URL.revokeObjectURL(previewUrl.value);
|
||||
previewUrl.value = '';
|
||||
try { previewUrl.value = URL.createObjectURL(await getWorkspaceShippingOrderReviewPreview(caseNo)); } catch { /* Preview remains independently recoverable. */ }
|
||||
};
|
||||
|
||||
/** 串行保存当前 Case,成功后使用服务端 DTO 替换本地草稿,避免旧响应回写。 */
|
||||
const save = async (action: () => Promise<ShippingOrderReviewCase>) => {
|
||||
saving.value = true;
|
||||
saveFailed.value = false;
|
||||
try {
|
||||
activeCase.value = await action();
|
||||
if (reviewRun.value && activeCase.value) {
|
||||
const item = reviewRun.value.items.find((row) => row.case_no === activeCase.value?.case_no);
|
||||
if (item) {
|
||||
item.status = activeCase.value.status;
|
||||
item.draft_version = activeCase.value.draft?.draft_version;
|
||||
item.issue_count = activeCase.value.draft?.issues.length || 0;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
saveFailed.value = true;
|
||||
throw error;
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
const version = () => activeCase.value?.draft?.draft_version || 0;
|
||||
const patchHeader = (fieldId: string, value: unknown, restoreMachine = false) => {
|
||||
if (!activeCase.value) return Promise.resolve();
|
||||
return save(() => patchWorkspaceShippingOrderReviewHeaderField(activeCase.value!.case_no, fieldId, {
|
||||
expected_draft_version: version(), value, restore_machine: restoreMachine,
|
||||
}));
|
||||
};
|
||||
const patchLine = (lineKey: string, fieldId: string, value: unknown, restoreMachine = false) => {
|
||||
if (!activeCase.value) return Promise.resolve();
|
||||
return save(() => patchWorkspaceShippingOrderReviewLineField(activeCase.value!.case_no, lineKey, fieldId, {
|
||||
expected_draft_version: version(), value, restore_machine: restoreMachine,
|
||||
}));
|
||||
};
|
||||
const addLine = () => activeCase.value && save(() => addWorkspaceShippingOrderReviewLine(activeCase.value!.case_no, version()));
|
||||
const copyLine = (lineKey: string) => activeCase.value && save(() => copyWorkspaceShippingOrderReviewLine(activeCase.value!.case_no, lineKey, version()));
|
||||
const deleteLine = (lineKey: string) => activeCase.value && save(() => deleteWorkspaceShippingOrderReviewLine(activeCase.value!.case_no, lineKey, version()));
|
||||
const validate = () => activeCase.value && save(() => validateWorkspaceShippingOrderReviewDraft(activeCase.value!.case_no, version()));
|
||||
/** 确认动作不复用自动保存:服务端返回 Task 与只读 Case,而不是仅草稿 DTO。 */
|
||||
const confirm = async () => {
|
||||
if (!activeCase.value) return null;
|
||||
saving.value = true;
|
||||
saveFailed.value = false;
|
||||
try {
|
||||
const response = await confirmWorkspaceShippingOrderReviewCase(activeCase.value.case_no, {
|
||||
expected_draft_version: version(),
|
||||
idempotency_key: crypto.randomUUID(),
|
||||
});
|
||||
activeCase.value = response.case;
|
||||
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
|
||||
return response;
|
||||
} catch (error) {
|
||||
saveFailed.value = true;
|
||||
throw error;
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
const createManualDraft = () => activeCase.value && save(() => createWorkspaceShippingOrderReviewManualDraft(activeCase.value!.case_no));
|
||||
const markNonOrder = (reason: string) => activeCase.value && save(() => markWorkspaceShippingOrderReviewNonOrder(activeCase.value!.case_no, reason));
|
||||
const markQualityIssue = (reason: string) => activeCase.value && save(() => markWorkspaceShippingOrderReviewQualityIssue(activeCase.value!.case_no, reason));
|
||||
const reparseDocument = async (reason: string) => {
|
||||
if (!activeCase.value) return null;
|
||||
const response = await reparseWorkspaceShippingOrderReviewDocument(activeCase.value.case_no, reason);
|
||||
activeCase.value = await getWorkspaceShippingOrderReviewCase(activeCase.value.case_no);
|
||||
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
|
||||
return response;
|
||||
};
|
||||
/** 上传替代 PDF 后等待既有 Intake 预解析;只有获得唯一 Document 才创建替代 Run。 */
|
||||
const uploadReplacement = async (file: File) => {
|
||||
if (!activeCase.value) return null;
|
||||
const asset = await uploadFileAsset(file);
|
||||
const intake = await createWorkspaceShippingOrderReviewReplacementIntake(activeCase.value.case_no, asset.asset_no);
|
||||
for (let attempt = 0; attempt < 60; attempt += 1) {
|
||||
const current = await getShippingNoticeIntake(intake.intake_no);
|
||||
if (current.parse_status === 'parsed') return startReplacementRun(current.intake_no);
|
||||
if (['parse_failed', 'cancelled', 'expired'].includes(current.parse_status)) {
|
||||
throw new Error('Replacement PDF parsing failed');
|
||||
}
|
||||
await new Promise<void>((resolve) => window.setTimeout(resolve, 1000));
|
||||
}
|
||||
throw new Error('Replacement PDF parsing is still pending');
|
||||
};
|
||||
const startReplacementRun = async (intakeNo: string) => {
|
||||
if (!activeCase.value) return null;
|
||||
const response = await createWorkspaceShippingOrderReviewReplacementRun(activeCase.value.case_no, intakeNo);
|
||||
activeCase.value = await getWorkspaceShippingOrderReviewCase(activeCase.value.case_no);
|
||||
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
|
||||
return response;
|
||||
};
|
||||
|
||||
return { reviewRun, activeCase, evidence, previewUrl, loading, loadFailed, saving, saveFailed, load, selectCase, patchHeader, patchLine, addLine, copyLine, deleteLine, validate, confirm, createManualDraft, markNonOrder, markQualityIssue, reparseDocument, uploadReplacement, startReplacementRun };
|
||||
}
|
||||
@@ -8,10 +8,14 @@ import { computeNoticeFilesContentFingerprint } from './shippingNoticeBatchIdemp
|
||||
describe('shippingNoticeBatchIdempotency', () => {
|
||||
it('treats duplicate files as one content set', async () => {
|
||||
const content = 'same-notice-content';
|
||||
const single = new File([content], 'a.txt', { type: 'text/plain' });
|
||||
const createFile = (name: string) => ({
|
||||
name,
|
||||
arrayBuffer: async () => new TextEncoder().encode(content),
|
||||
}) as File;
|
||||
const single = createFile('a.txt');
|
||||
const duplicatePair = [
|
||||
new File([content], 'a.txt', { type: 'text/plain' }),
|
||||
new File([content], 'b.txt', { type: 'text/plain' }),
|
||||
createFile('a.txt'),
|
||||
createFile('b.txt'),
|
||||
];
|
||||
|
||||
const singleFp = await computeNoticeFilesContentFingerprint([single]);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingSendHandler.spec.ts
|
||||
* 用途:验证阶段 2 发送语义,只冻结当前输入框这批 Intake,并允许空备注启动识别。
|
||||
* 用途:验证阶段 2 发送语义,只冻结当前输入框这批 Intake,并为仅附件发送补充用户可见的默认请求。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
@@ -149,7 +149,7 @@ describe('useChatShippingSendHandler', () => {
|
||||
expect(attachments.value).toEqual([laterNotice, otherAttachment]);
|
||||
});
|
||||
|
||||
it('allows an empty note when the user only authorizes attachment analysis', async () => {
|
||||
it('adds a visible default request when the user only sends attachments', async () => {
|
||||
const startOrderExtractionRun = vi.fn(async () => true);
|
||||
const ctx = createContext({
|
||||
attachments: ref([{
|
||||
@@ -174,7 +174,7 @@ describe('useChatShippingSendHandler', () => {
|
||||
|
||||
expect(consumed).toBe(true);
|
||||
expect(startOrderExtractionRun).toHaveBeenCalledWith(
|
||||
'',
|
||||
'chat.shippingOrderExtractionDefaultUserMessage',
|
||||
['SNI-EMPTY-NOTE'],
|
||||
[{
|
||||
name: 'orders.eml',
|
||||
|
||||
@@ -236,8 +236,8 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
&& submittedIntakes.has(item.intakeNo.trim().toUpperCase()),
|
||||
),
|
||||
);
|
||||
// 阶段 2:发送是“授权开始识别”,备注允许为空,不能再偷偷注入默认提示词。
|
||||
const query = trimmed;
|
||||
// 阶段 2:空备注补充用户可见的默认请求,便于会话记录与审计;不改变 Worker 的确定性识别流程。
|
||||
const query = trimmed || ctx.t('chat.shippingOrderExtractionDefaultUserMessage');
|
||||
ctx.shippingAutoFlowRequested.value = false;
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
try {
|
||||
|
||||
@@ -68,7 +68,7 @@ describe('shipping notice order extraction state', () => {
|
||||
expect(resolveShippingOrderExtractionStatus(undefined, 'not_started')).toBe('not_started');
|
||||
});
|
||||
|
||||
it('restores in-progress, retryable, and pending-candidate attachments into the input area', () => {
|
||||
it('restores only in-progress and retryable attachments into the input area', () => {
|
||||
expect(shouldRestoreShippingNoticeIntake('queued')).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsing')).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parse_failed')).toBe(true);
|
||||
@@ -78,15 +78,15 @@ describe('shipping notice order extraction state', () => {
|
||||
attachment_directory_complete: true,
|
||||
})).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'failed', 0)).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'partially_completed', 2)).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'not_started', 0, {
|
||||
preview_status: 'directory_incomplete',
|
||||
ready_for_extraction: false,
|
||||
attachment_directory_complete: false,
|
||||
})).toBe(false);
|
||||
|
||||
// 已完成且没有待审核 Candidate 的文件仅保留在用户消息气泡中。
|
||||
// 已发送的终态文件(包括待人工复核)仅保留在用户消息气泡和结果卡中。
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'completed')).toBe(false);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'partially_completed', 2)).toBe(false);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'partially_completed', 0)).toBe(false);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'completed', 2)).toBe(false);
|
||||
expect(shouldRestoreShippingNoticeIntake('consumed')).toBe(false);
|
||||
|
||||
@@ -41,16 +41,16 @@ const ACTIVE_ORDER_EXTRACTION = new Set(['extracting']);
|
||||
* 判断服务端 Intake 是否应恢复到输入栏。
|
||||
* AI 触发时机:无;页面刷新或重新打开会话时调用。
|
||||
* 上传快览与发送授权已拆分:未发送但已快览成功的附件,刷新后也必须恢复到输入栏;
|
||||
* 已进入订单抽取终态的附件仅保留在消息气泡中,避免把旧批次误带回当前输入框。
|
||||
* 已进入订单抽取终态(包括待人工复核)的附件仅保留在消息气泡和结果卡中,
|
||||
* 避免把已发送的旧批次误带回当前输入框。
|
||||
* @param parseStatus - 服务端返回的预解析状态。
|
||||
* @param orderExtractionStatus - 服务端返回的订单抽取状态。
|
||||
* @param candidateCount - 当前仍可审核的订单 Candidate 数量。
|
||||
* @returns 是否恢复为待发送附件卡片
|
||||
*/
|
||||
export function shouldRestoreShippingNoticeIntake(
|
||||
parseStatus: string | null | undefined,
|
||||
orderExtractionStatus?: string | null,
|
||||
candidateCount = 0,
|
||||
_candidateCount = 0,
|
||||
parseSummary?: ShippingNoticePendingAttachment['parseSummary'],
|
||||
): boolean {
|
||||
const status = String(parseStatus || '').trim().toLowerCase();
|
||||
@@ -62,8 +62,7 @@ export function shouldRestoreShippingNoticeIntake(
|
||||
&& (!extractionStatus || extractionStatus === 'not_started')
|
||||
&& !isShippingNoticeAttachmentParseIncomplete(parseSummary)
|
||||
)
|
||||
|| extractionStatus === 'failed'
|
||||
|| (extractionStatus === 'partially_completed' && candidateCount > 0);
|
||||
|| extractionStatus === 'failed';
|
||||
}
|
||||
|
||||
/** 判断 Intake 是否仍需轮询上传预处理或订单抽取状态。 */
|
||||
@@ -582,19 +581,6 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
}
|
||||
};
|
||||
|
||||
/** 保存 Candidate 人工修订后的订单摘要。 */
|
||||
const updateCandidateSummary = async (candidateNo: string, businessSummary: Record<string, unknown>) => {
|
||||
const remote = await updateShippingNoticeCandidate(candidateNo, { business_summary: businessSummary });
|
||||
for (const attachment of noticeAttachments.value) {
|
||||
if (!(attachment.candidates || []).some((item) => item.candidateNo === candidateNo)) continue;
|
||||
patchAttachment(attachment.id, {
|
||||
candidates: (attachment.candidates || []).map((item) =>
|
||||
item.candidateNo === candidateNo ? mapServerCandidate(remote) : item,
|
||||
),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/** 人工采纳已复核的 Dify Candidate;后端决定是否已满足履约门禁。 */
|
||||
const promoteCandidate = async (candidateNo: string) => {
|
||||
const remote = await promoteShippingNoticeCandidate(candidateNo);
|
||||
@@ -667,7 +653,6 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
resolveDuplicateAttachment,
|
||||
resolveCandidateDuplicate,
|
||||
setCandidateSelected,
|
||||
updateCandidateSummary,
|
||||
promoteCandidate,
|
||||
rejectCandidate,
|
||||
getParsedIntakeNos,
|
||||
|
||||
@@ -692,6 +692,10 @@ export interface ShippingOrderExtractionDocumentResult {
|
||||
reason_code?: string | null;
|
||||
review_details?: Array<{ line_number: number; field_code?: string | null; reason_code: string }>;
|
||||
available_actions: string[];
|
||||
activity_event_code?: string | null;
|
||||
started_at?: string | null;
|
||||
last_activity_at?: string | null;
|
||||
finished_at?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionRun {
|
||||
@@ -783,6 +787,82 @@ export interface ShippingOrderExtractionDocumentsResponse {
|
||||
items: ShippingOrderExtractionDocumentResult[];
|
||||
}
|
||||
|
||||
/** 建单前订单复核的冻结 Schema 字段;阶段 2 只读展示,编辑能力由后续阶段扩展。 */
|
||||
export interface ShippingOrderReviewSchemaField {
|
||||
field_id: string;
|
||||
field_code: string;
|
||||
display_name: string;
|
||||
scope: string;
|
||||
value_type: string;
|
||||
required: boolean;
|
||||
options: unknown[];
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewCaseSummary {
|
||||
case_no: string;
|
||||
document_id: number;
|
||||
file_name?: string | null;
|
||||
status: string;
|
||||
draft_version?: number | null;
|
||||
issue_count: number;
|
||||
available_actions: string[];
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewRun {
|
||||
run_no: string;
|
||||
summary: Record<string, number>;
|
||||
items: ShippingOrderReviewCaseSummary[];
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewCase {
|
||||
case_no: string;
|
||||
run_no: string;
|
||||
document: { id: number; file_name?: string | null };
|
||||
status: string;
|
||||
disposition?: string | null;
|
||||
confirmed_task_id?: number | null;
|
||||
candidate?: { candidate_no: string; validation_status: string; po_number?: string | null } | null;
|
||||
schema: { schema_version_id: number; fields: ShippingOrderReviewSchemaField[] };
|
||||
draft?: {
|
||||
draft_version: number;
|
||||
header_values: Record<string, unknown>;
|
||||
lines: Array<Record<string, unknown>>;
|
||||
issues: Array<{ code?: string; severity?: string }>;
|
||||
validation: Record<string, unknown>;
|
||||
} | null;
|
||||
available_actions: string[];
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewConfirmResponse {
|
||||
task_no?: string | null;
|
||||
idempotent_replay: boolean;
|
||||
case: ShippingOrderReviewCase;
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewReparseResponse {
|
||||
run: ShippingOrderExtractionRun;
|
||||
reused: boolean;
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewDraftWrite {
|
||||
expected_draft_version: number;
|
||||
value?: unknown;
|
||||
restore_machine?: boolean;
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewEvidence {
|
||||
evidence_id: string;
|
||||
field_id: string;
|
||||
line_index?: number | null;
|
||||
machine_value?: unknown;
|
||||
quote?: string | null;
|
||||
page_no?: number | null;
|
||||
table_id?: string | null;
|
||||
cell_id?: string | null;
|
||||
bbox?: { x0: number; y0: number; x1: number; y1: number } | null;
|
||||
source: string;
|
||||
}
|
||||
|
||||
export interface ShippingNoticeDocumentResponse {
|
||||
id: number;
|
||||
document_type: string;
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
<!--
|
||||
用途:提供按 PDF 独立处理的建单前订单人工复核工作台。
|
||||
依赖:路由参数、复核 composable、冻结 Schema DTO、受控 PDF 预览组件。
|
||||
逻辑:复用聊天壳的历史侧栏;中心维护订单单头和表格化单身,右侧固定 PDF/证据检查器;处置、重识别及确认建单均只消费当前 Case Draft。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { ArrowLeft, Copy, FileText, MapPin, Plus, RefreshCw, Save, Trash2, TriangleAlert, Undo2 } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { useIsMobile } from '@/shared/composables/useIsMobile';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import { useChatPageContext } from '@/features/chat/composables/chat.context';
|
||||
import { useShippingOrderReview } from '../shipping-review/useShippingOrderReview';
|
||||
import ReviewDocumentPreview from '../components/shipping-review/ReviewDocumentPreview.vue';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const page = useChatPageContext();
|
||||
const { t } = useI18n();
|
||||
const { reviewRun, activeCase, evidence, previewUrl, loading, loadFailed, saving, saveFailed, load, selectCase, patchHeader, patchLine, addLine, copyLine, deleteLine, validate, confirm, createManualDraft, markNonOrder, markQualityIssue, reparseDocument, uploadReplacement } = useShippingOrderReview();
|
||||
const msg = useMessage();
|
||||
const { isMobile } = useIsMobile();
|
||||
/** 新模式从 query 读取 run_no;保留旧路径参数以兼容已收藏的复核链接。 */
|
||||
const runNo = computed(() => String(route.query.run_no || route.params.runNo || ''));
|
||||
const agentId = computed(() => String(route.params.agentId || ''));
|
||||
|
||||
const headerSchemaFields = computed(() => (activeCase.value?.schema.fields || []).filter((field) => field.scope === 'header'));
|
||||
const lineSchemaFields = computed(() => (activeCase.value?.schema.fields || []).filter((field) => field.scope === 'line'));
|
||||
const headerHasMachineValue = (fieldId: string) => machineValueByIdFor(
|
||||
Array.isArray(activeCase.value?.draft?.header_values.machine_fields)
|
||||
? activeCase.value?.draft?.header_values.machine_fields as Array<Record<string, unknown>> : [],
|
||||
fieldId,
|
||||
) !== '';
|
||||
const primaryHeaderFields = computed(() => headerSchemaFields.value.filter((field) => field.required || headerHasMachineValue(field.field_id)));
|
||||
const optionalEmptyHeaderFields = computed(() => headerSchemaFields.value.filter((field) => !field.required && !headerHasMachineValue(field.field_id)));
|
||||
const lineHasValue = (fieldId: string) => (activeCase.value?.draft?.lines || []).some((line) => draftValue(line, fieldId) !== '');
|
||||
const primaryLineFields = computed(() => lineSchemaFields.value.filter((field) => field.required || lineHasValue(field.field_id)));
|
||||
const optionalEmptyLineFields = computed(() => lineSchemaFields.value.filter((field) => !field.required && !lineHasValue(field.field_id)));
|
||||
const machineValue = (field: Record<string, unknown>) => {
|
||||
const observations = Array.isArray(field.observations) ? field.observations as Array<Record<string, unknown>> : [];
|
||||
return String(observations[0]?.value || t('chat.shippingOrderReview.emptyValue'));
|
||||
};
|
||||
const draftValue = (container: Record<string, unknown>, fieldId: string) => {
|
||||
const values = container.values as Record<string, { value?: unknown }> | undefined;
|
||||
if (values?.[fieldId] && 'value' in values[fieldId]) return String(values[fieldId].value ?? '');
|
||||
const machine = Array.isArray(container.machine_fields) ? container.machine_fields as Array<Record<string, unknown>> : [];
|
||||
return machineValueByIdFor(machine, fieldId);
|
||||
};
|
||||
const machineValueByIdFor = (fields: Array<Record<string, unknown>>, fieldId: string) => {
|
||||
const field = fields.find((item) => String(item.field_id || '') === fieldId);
|
||||
return field ? machineValue(field) : '';
|
||||
};
|
||||
const editable = computed(() => activeCase.value?.available_actions.includes('edit_draft') || false);
|
||||
const selectedEvidenceId = ref('');
|
||||
const contextOpen = ref(false);
|
||||
const confirmDialogOpen = ref(false);
|
||||
const selectedEvidence = computed(() => evidence.value.find((item) => item.evidence_id === selectedEvidenceId.value) || null);
|
||||
// PDF.js uses evidence.page_no to select the page; retain the original Blob URL while switching evidence.
|
||||
const previewSrc = computed(() => previewUrl.value);
|
||||
const selectEvidence = (fieldId: string, lineIndex?: number) => {
|
||||
const item = evidence.value.find((entry) => entry.field_id === fieldId && entry.line_index === lineIndex);
|
||||
selectedEvidenceId.value = item?.evidence_id || '';
|
||||
};
|
||||
const reportSave = async (action: () => Promise<unknown> | null) => {
|
||||
try { await action(); }
|
||||
catch (error) {
|
||||
const message = error instanceof BusinessError ? error.message : t('errors.generic');
|
||||
msg.error(message);
|
||||
}
|
||||
};
|
||||
const reportDisposition = async (action: () => Promise<unknown> | null) => {
|
||||
try { await action(); }
|
||||
catch (error) {
|
||||
const message = error instanceof BusinessError ? error.message : t('errors.generic');
|
||||
msg.error(message);
|
||||
}
|
||||
};
|
||||
const confirmCase = () => {
|
||||
confirmDialogOpen.value = true;
|
||||
};
|
||||
const confirmCaseSubmit = async () => {
|
||||
await reportDisposition(() => confirm());
|
||||
};
|
||||
const selectReplacement = (event: Event) => {
|
||||
const file = (event.target as HTMLInputElement).files?.[0];
|
||||
if (file) void reportDisposition(() => uploadReplacement(file));
|
||||
(event.target as HTMLInputElement).value = '';
|
||||
};
|
||||
const select = async (caseNo: string) => {
|
||||
await selectCase(caseNo);
|
||||
// Preserve review mode and the originating conversation while switching PDFs.
|
||||
await router.replace({ query: { ...route.query, case: caseNo } });
|
||||
};
|
||||
/** 在同一 ChatView 内退出复核模式,保留原会话实例及其滚动位置。 */
|
||||
const back = () => router.replace({
|
||||
name: 'Chat',
|
||||
params: { agentId: agentId.value },
|
||||
query: Object.fromEntries(Object.entries(route.query).filter(([key]) => key !== 'mode' && key !== 'run_no')),
|
||||
});
|
||||
|
||||
watch(
|
||||
[runNo, () => String(route.query.case || '')],
|
||||
([nextRun, nextCase]) => { if (nextRun) void load(nextRun, nextCase || undefined); },
|
||||
{ immediate: true },
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="flex min-h-0 flex-1 flex-col bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-slate-100">
|
||||
<header class="flex shrink-0 items-center gap-3 border-b border-slate-200 bg-white px-4 py-3 dark:border-slate-800 dark:bg-slate-900">
|
||||
<button type="button" class="rounded-md p-1 hover:bg-slate-100 dark:hover:bg-slate-800" :aria-label="t('chat.shippingOrderReview.back')" @click="back"><ArrowLeft class="h-5 w-5" /></button>
|
||||
<div class="min-w-0"><h1 class="text-base font-semibold">{{ t('chat.shippingOrderReview.title') }}</h1><p class="truncate text-xs text-slate-500 dark:text-slate-400">{{ t('chat.shippingOrderReview.run', { runNo }) }}</p></div>
|
||||
<button type="button" class="ml-auto rounded border border-slate-200 px-2.5 py-1.5 text-xs hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800" @click="contextOpen = !contextOpen">{{ contextOpen ? '收起对话上下文' : '对话上下文' }}</button>
|
||||
<span class="shrink-0 rounded-full bg-sky-100 px-2.5 py-1 text-xs text-sky-800 dark:bg-sky-950 dark:text-sky-100">{{ saving ? t('chat.shippingOrderReview.saving') : saveFailed ? t('chat.shippingOrderReview.saveFailed') : t('chat.shippingOrderReview.saved') }}</span>
|
||||
</header>
|
||||
|
||||
<div v-if="loading" class="p-8 text-sm text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.loading') }}</div>
|
||||
<div v-else-if="loadFailed" class="m-4 rounded-lg border border-rose-300 bg-rose-50 p-4 text-sm text-rose-900 dark:border-rose-800 dark:bg-rose-950/30 dark:text-rose-100">{{ t('chat.shippingOrderReview.unavailable') }}</div>
|
||||
<div v-else class="grid min-h-0 flex-1 grid-cols-1 xl:grid-cols-[minmax(0,1fr)_minmax(340px,420px)]">
|
||||
<section class="min-h-0 overflow-y-auto p-4 lg:p-5">
|
||||
<div v-if="activeCase?.draft?.issues?.length" class="mb-4 rounded-lg border border-amber-300 bg-amber-50 p-3 text-xs text-amber-950 dark:border-amber-800 dark:bg-amber-950/30 dark:text-amber-100"><div class="font-semibold">{{ t('chat.shippingOrderReview.issues') }}</div><div v-for="issue in activeCase.draft.issues" :key="`${issue.code}-${issue.severity}`" class="mt-1">{{ issue.code }}</div></div>
|
||||
<section class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900">
|
||||
<div class="flex items-center justify-between gap-3"><div><h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.orderFields') }}</h2><p class="mt-1 text-xs text-slate-500">{{ t('chat.shippingOrderReview.schemaVersion', { version: activeCase?.schema.schema_version_id || '-' }) }}</p></div></div>
|
||||
<div v-if="primaryHeaderFields.length" class="mt-4 grid gap-3 md:grid-cols-2 2xl:grid-cols-3">
|
||||
<div v-for="field in primaryHeaderFields" :key="field.field_id" class="min-w-0">
|
||||
<label class="flex items-center justify-between gap-2 text-xs font-medium text-slate-600 dark:text-slate-300"><span class="truncate">{{ field.display_name }}<span v-if="field.required"> *</span></span><button type="button" class="shrink-0 text-slate-500 hover:text-sky-600" :aria-label="t('chat.shippingOrderReview.viewEvidence')" @click="selectEvidence(field.field_id)"><MapPin class="h-3.5 w-3.5" /></button></label>
|
||||
<input :value="draftValue(activeCase?.draft?.header_values || {}, field.field_id)" :disabled="!editable || saving" class="mt-1 w-full rounded-md border border-slate-300 bg-white px-2.5 py-2 text-sm dark:border-slate-600 dark:bg-slate-950" @change="reportSave(() => patchHeader(field.field_id, ($event.target as HTMLInputElement).value))">
|
||||
<div class="mt-1 flex items-center justify-between gap-2 text-[11px] text-slate-500"><span>{{ (activeCase?.draft?.header_values as Record<string, unknown>)?.values && Object.prototype.hasOwnProperty.call((activeCase?.draft?.header_values as Record<string, unknown>).values as object, field.field_id) ? t('chat.shippingOrderReview.manualSource') : t('chat.shippingOrderReview.machineSource') }}</span><button v-if="editable" type="button" class="hover:text-sky-600" @click="reportSave(() => patchHeader(field.field_id, null, true))"><Undo2 class="mr-1 inline h-3 w-3" />{{ t('chat.shippingOrderReview.restoreMachine') }}</button></div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="mt-4 rounded-lg border border-dashed border-slate-300 p-3 text-sm text-slate-500 dark:border-slate-700"><p>{{ t('chat.shippingOrderReview.noMachineOrder') }}</p><div v-if="activeCase?.available_actions.includes('create_draft')" class="mt-3 flex flex-wrap gap-2"><button type="button" class="rounded border px-2 py-1 text-xs" :disabled="saving" @click="reportDisposition(() => createManualDraft())">{{ t('chat.shippingOrderReview.createManualDraft') }}</button><button type="button" class="rounded border px-2 py-1 text-xs" :disabled="saving" @click="reportDisposition(() => markNonOrder('non_order'))">{{ t('chat.shippingOrderReview.markNonOrder') }}</button></div></div>
|
||||
<details v-if="optionalEmptyHeaderFields.length" class="mt-4 rounded-lg border border-slate-200 p-3 text-sm dark:border-slate-700"><summary class="cursor-pointer font-medium">{{ t('chat.shippingOrderReview.moreFields', { count: optionalEmptyHeaderFields.length }) }}</summary><div class="mt-3 grid gap-2 sm:grid-cols-2"><div v-for="field in optionalEmptyHeaderFields" :key="field.field_id" class="text-xs"><div class="text-slate-500">{{ field.display_name }}</div><div>{{ t('chat.shippingOrderReview.emptyValue') }}</div></div></div></details>
|
||||
</section>
|
||||
|
||||
<section class="mt-4 rounded-xl border border-slate-200 bg-white shadow-sm dark:border-slate-800 dark:bg-slate-900">
|
||||
<div class="flex items-center justify-between gap-3 border-b border-slate-200 px-4 py-3 dark:border-slate-800"><div><h3 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.lines') }}</h3><p class="mt-1 text-xs text-slate-500">{{ (activeCase?.draft?.lines || []).length }} {{ t('chat.shippingOrderReview.lines') }}</p></div><button v-if="!isMobile" type="button" :disabled="!editable || saving" class="inline-flex items-center gap-1 rounded border px-2 py-1 text-xs disabled:opacity-50" @click="reportSave(() => addLine())"><Plus class="h-3.5 w-3.5" />{{ t('chat.shippingOrderReview.addLine') }}</button></div>
|
||||
<div v-if="activeCase?.draft?.lines?.length" class="overflow-x-auto"><table class="min-w-full border-collapse text-left text-xs"><thead class="bg-slate-50 text-slate-500 dark:bg-slate-950/40 dark:text-slate-400"><tr><th class="sticky left-0 z-10 min-w-14 border-b border-slate-200 bg-slate-50 px-3 py-2 font-medium dark:border-slate-800 dark:bg-slate-950">#</th><th v-for="field in primaryLineFields" :key="field.field_id" class="min-w-40 border-b border-slate-200 px-3 py-2 font-medium dark:border-slate-800">{{ field.display_name }}<span v-if="field.required"> *</span></th><th v-if="!isMobile" class="sticky right-0 z-10 border-b border-slate-200 bg-slate-50 px-3 py-2 dark:border-slate-800 dark:bg-slate-950"><span class="sr-only">{{ t('chat.shippingOrderReview.line', { index: '' }) }}</span></th></tr></thead><tbody><tr v-for="(line, index) in activeCase?.draft?.lines || []" :key="String(line.line_key || index)" class="border-b border-slate-100 last:border-0 dark:border-slate-800"><td class="sticky left-0 z-10 bg-white px-3 py-2 font-medium dark:bg-slate-900">{{ index + 1 }}</td><td v-for="field in primaryLineFields" :key="field.field_id" class="min-w-40 px-3 py-2 align-top"><div class="flex min-w-0 items-center gap-1"><input :value="draftValue(line, field.field_id)" :disabled="!editable || saving" class="min-w-0 flex-1 rounded border border-slate-300 bg-white px-2 py-1.5 dark:border-slate-600 dark:bg-slate-950" @change="reportSave(() => patchLine(String(line.line_key), field.field_id, ($event.target as HTMLInputElement).value))"><button type="button" class="shrink-0 text-slate-500 hover:text-sky-600" :aria-label="t('chat.shippingOrderReview.viewEvidence')" @click="selectEvidence(field.field_id, index)"><MapPin class="h-3.5 w-3.5" /></button></div></td><td v-if="!isMobile" class="sticky right-0 z-10 whitespace-nowrap bg-white px-2 py-2 dark:bg-slate-900"><button type="button" :disabled="!editable || saving" class="rounded p-1 hover:bg-slate-100 disabled:opacity-50 dark:hover:bg-slate-800" :aria-label="t('chat.shippingOrderReview.copyLine')" @click="reportSave(() => copyLine(String(line.line_key)))"><Copy class="h-3.5 w-3.5" /></button><button type="button" :disabled="!editable || saving" class="rounded p-1 hover:bg-slate-100 disabled:opacity-50 dark:hover:bg-slate-800" :aria-label="t('chat.shippingOrderReview.deleteLine')" @click="reportSave(() => deleteLine(String(line.line_key)))"><Trash2 class="h-3.5 w-3.5" /></button></td></tr></tbody></table></div>
|
||||
<div v-else class="p-4 text-sm text-slate-500">{{ t('chat.shippingOrderReview.noLines') }}</div>
|
||||
<details v-if="optionalEmptyLineFields.length" class="border-t border-slate-200 px-4 py-3 text-xs dark:border-slate-800"><summary class="cursor-pointer text-slate-500">{{ t('chat.shippingOrderReview.moreFields', { count: optionalEmptyLineFields.length }) }}</summary><p class="mt-2 text-slate-500">{{ optionalEmptyLineFields.map((field) => field.display_name).join(' · ') }}</p></details>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<aside class="flex min-h-0 flex-col border-t border-slate-200 bg-white xl:border-l xl:border-t-0 dark:border-slate-800 dark:bg-slate-900">
|
||||
<nav class="shrink-0 border-b border-slate-200 p-3 dark:border-slate-800" :aria-label="t('chat.shippingOrderReview.documentNavigation')"><div class="mb-2 text-xs font-semibold text-slate-500">{{ t('chat.shippingOrderReview.documents') }}</div><div class="flex gap-2 overflow-x-auto xl:flex-col xl:overflow-y-auto"><button v-for="item in reviewRun?.items || []" :key="item.case_no" type="button" class="min-w-52 rounded-lg border p-2.5 text-left text-sm xl:min-w-0" :class="activeCase?.case_no === item.case_no ? 'border-sky-500 bg-sky-50 dark:bg-sky-950/30' : 'border-slate-200 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800'" @click="select(item.case_no)"><div class="truncate font-medium">{{ item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</div><div class="mt-1 flex items-center gap-1 text-xs text-slate-500"><TriangleAlert v-if="item.issue_count" class="h-3.5 w-3.5 text-amber-500" />{{ t('chat.shippingOrderReview.caseStatus', { status: item.status, count: item.issue_count }) }}</div></button></div></nav>
|
||||
<div v-if="contextOpen" class="min-h-0 flex-1 overflow-y-auto p-4"><h2 class="text-sm font-semibold">对话上下文</h2><p class="mt-1 text-xs text-slate-500">当前会话中最近的订单抽取消息与附件。</p><div class="mt-4 space-y-3"><article v-for="(message, index) in page.messages.slice(-6)" :key="`${message.local_id || index}`" class="rounded-lg border border-slate-200 p-3 text-sm dark:border-slate-700"><div class="mb-1 text-xs font-medium text-slate-500">{{ message.role === 'user' ? '用户' : 'AI' }}</div><p class="whitespace-pre-wrap break-words">{{ message.content }}</p><div v-if="message.attachments?.length" class="mt-2 text-xs text-slate-500">{{ message.attachments.map((item) => item.name || '附件').join(' · ') }}</div></article><p v-if="page.messages.length === 0" class="text-sm text-slate-500">暂无可显示的对话上下文。</p></div></div>
|
||||
<div v-else class="flex min-h-0 flex-1 flex-col p-3"><div class="mb-2 flex items-center gap-2 text-sm font-semibold"><FileText class="h-4 w-4" />{{ activeCase?.document.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</div><div class="min-h-[320px] flex-1 overflow-hidden rounded-xl border border-slate-300 bg-slate-50 dark:border-slate-700 dark:bg-slate-950"><ReviewDocumentPreview v-if="previewSrc" :src="previewSrc" :evidence="selectedEvidence" :title="t('chat.shippingOrderReview.previewTitle')" :loading-text="t('chat.shippingOrderReview.previewLoading')" :unavailable-text="t('chat.shippingOrderReview.previewUnavailable')" /></div><div v-if="selectedEvidence" class="mt-3 rounded-lg border border-sky-200 bg-sky-50 p-3 text-xs text-sky-950 dark:border-sky-900 dark:bg-sky-950/30 dark:text-sky-100"><div class="flex items-center gap-1 font-semibold"><MapPin class="h-3.5 w-3.5" />{{ t('chat.shippingOrderReview.evidenceAt', { page: selectedEvidence.page_no || '-' }) }}</div><p v-if="selectedEvidence.quote" class="mt-1 break-words">{{ selectedEvidence.quote }}</p><p v-if="!selectedEvidence.bbox" class="mt-1">{{ t('chat.shippingOrderReview.evidenceNoHighlight') }}</p></div><p v-else class="mt-3 text-xs text-slate-500">{{ t('chat.shippingOrderReview.evidenceSummary') }}</p></div>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<footer v-if="activeCase?.draft" class="flex shrink-0 flex-wrap items-center justify-end gap-2 border-t border-slate-200 bg-white p-3 dark:border-slate-800 dark:bg-slate-900"><button v-if="activeCase?.available_actions.includes('mark_non_order')" type="button" :disabled="saving" class="rounded border px-3 py-2 text-sm disabled:opacity-50" @click="reportDisposition(() => markNonOrder('non_order'))">{{ t('chat.shippingOrderReview.markNonOrder') }}</button><button v-if="activeCase?.available_actions.includes('mark_quality_issue')" type="button" :disabled="saving" class="rounded border px-3 py-2 text-sm disabled:opacity-50" @click="reportDisposition(() => markQualityIssue('other'))">{{ t('chat.shippingOrderReview.markQualityIssue') }}</button><button v-if="activeCase?.available_actions.includes('reparse')" type="button" :disabled="saving" class="inline-flex items-center gap-1 rounded border px-3 py-2 text-sm disabled:opacity-50" @click="reportDisposition(() => reparseDocument('document_quality'))"><RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.reparse') }}</button><label v-if="activeCase?.available_actions.includes('mark_quality_issue')" class="cursor-pointer rounded border px-3 py-2 text-sm"><input class="sr-only" type="file" accept="application/pdf,.pdf" :disabled="saving" @change="selectReplacement">{{ t('chat.shippingOrderReview.uploadReplacement') }}</label><button v-if="activeCase?.available_actions.includes('validate')" type="button" :disabled="saving" class="inline-flex items-center gap-1 rounded bg-sky-600 px-3 py-2 text-sm text-white disabled:opacity-50" @click="reportSave(() => validate())"><Save class="h-4 w-4" />{{ t('chat.shippingOrderReview.saveNow') }}</button><button v-if="activeCase?.available_actions.includes('confirm')" type="button" :disabled="saving" class="rounded bg-emerald-600 px-3 py-2 text-sm text-white disabled:opacity-50" @click="confirmCase">{{ t('chat.shippingOrderReview.confirmCreate') }}</button></footer>
|
||||
<DeleteConfirmDialog v-model="confirmDialogOpen" :title="t('chat.shippingOrderReview.confirmCreate')" :message="t('chat.shippingOrderReview.confirmPrompt')" :confirm-text="t('chat.shippingOrderReview.confirmCreate')" confirm-tone="primary" :confirm-loading="saving" @confirm="confirmCaseSubmit" />
|
||||
</main>
|
||||
</template>
|
||||
Reference in new issue
Block a user