Files
syops/frontend/src/features/chat/views/ShippingOrderReviewView.vue
T
hugo eed1068ae3 feat(shipping-notice): 通知准备履约字段就地编辑并修复缺口复核入口
- 编辑闸门翻转为状态制:Excel 生成前+无活动 Attempt 即可编辑,原因不强制(审计自动记录操作人与变更)
- 修复 Decimal 字段人工编辑无法持久化(单字段+整行替换两路径)
- 预约注册与核验比对改读有效订单值视图,消除编辑后重匹配 RESERVATION_MISMATCH 阻断
- 通知准备值列改读有效视图:保存即显新值,匹配结果列保持最近一轮事实
- 行编辑入口为更多操作列编辑按钮;编辑态替换为保存/取消;库存源行内改选随保存统一提交
- 展示态动作收纳进更多菜单(Teleport 浮层,防表格 overflow 裁剪)
- 修复缺口复核投影键错位(has_shortage 恒 False 致入口隐藏)并补齐行级结案入口
- 缺口放行改行内补录条(菜单放行或缺 N 项徽标展开,确认放行/取消收起),放行原因可选
- i18n 四语言;technical.md/funclist.md 语义文档同步
2026-09-18 14:59:39 +08:00

6266 lines
304 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!--
features/chat/views/ShippingOrderReviewView.vue
用途:建单前/正式任务「订单生命周期工作台」(主编辑区 + 五阶段导航 + 工作台侧栏 + workbenchMode)。
依赖:路由参数、useShippingOrderReview、ReviewWorkbenchHeader/Footer、ReviewDocumentNavigation、
ReviewProcessDetailDrawer、ReviewUnsavedSwitchDialog、
ReviewWorkbenchModeToggle、ReviewDocumentEvidenceDrawer、ReviewVersionHistoryDrawer、
ReviewLlmSuggestionDrawer、ReviewActionConfirmDialog、
ReviewCustomerResolutionPanel / ReviewCurrentProcessingCard / ReviewCompletedChecksPanel /
ReviewBuildEligibilitySummary、ReviewInventory*、
ReviewLineInventoryOps(履约操作并入明细右侧列)、ReviewLineFulfillmentDetail(行内履约摘要)、
正式任务动作直接提交后端 Gate,避免以无界面组件充当隐藏执行器;
逻辑:建单前订单检查为主卡;正式 OT 后保持 standard,不自动切 formal_task 空壳;
当前 Case 的明确恢复动作优先右栏 CurrentProcessingCard,
不回落至底栏;库存动作仅明细行浮层;表单保存校验仅底栏;
STP waiting_to_start/queued/running 时 automating=true 且后端剥离 edit_draft;
货代上传确认成功后须 refreshReviewQueue,左侧本批阶段与五阶段对齐。
-->
<script setup lang="ts">
import { computed, defineAsyncComponent, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import type { Component } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Bot, Check, ChevronDown, Crosshair, Download, MoreHorizontal, Pencil, Plus, RefreshCw, Undo2, Copy, Trash2, X } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { loadReportLayoutPref, saveReportLayoutPref } from '@/shared/composables/useReportLayoutStorage';
import { inventoryActionLabelKey } from '@/features/shipping-progress/actionPresentation';
import { useChatPageContext } from '@/features/chat/composables/chat.context';
import {
auditWorkspaceShippingOrderReviewEligibilityDetails,
auditWorkspaceShippingOrderReviewVersionHistory,
attemptWorkspaceShippingOrderReviewFieldLocate,
getWorkspaceShippingOrderReviewEvidenceItem,
getWorkspaceShippingTask,
getWorkspaceShippingFreightNoticeGroups,
batchConfirmWorkspaceShippingNoticesUploaded,
batchStartWorkspaceShippingNoticeRpaUpload,
retryWorkspaceShippingOrderStpAutoCreate,
retryShippingNoticeIntake,
decideWorkspaceShippingOrderReviewLineFulfillment,
updateWorkspaceShippingNoticeLine,
waveWorkspaceShippingOrderReviewLineFulfillment,
setWorkspaceShippingTaskOdmChoice,
viewWorkspaceShippingOrderReviewHighlightDiagnostic,
} from '../api/shipping.api';
import type {
ShippingOrderReviewLineFulfillmentLine,
} from '../types/shipping.api.types';
import {
extractExtractionProgressReasonCode,
isRedundantExtractionDetail,
resolveExtractionActivityMessage,
resolveRunLifecycleUserStatus,
} from '../shipping/shippingProcessingLabels';
import ReviewActionConfirmDialog, {
type ReviewConfirmAction,
type ReviewConfirmPayload,
} from '../components/shipping-review/ReviewActionConfirmDialog.vue';
import ReviewBuildEligibilityDetailsDrawer from '../components/shipping-review/ReviewBuildEligibilityDetailsDrawer.vue';
import ReviewBuildEligibilitySummary from '../components/shipping-review/ReviewBuildEligibilitySummary.vue';
import ReviewCustomerResolutionPanel from '../components/shipping-review/ReviewCustomerResolutionPanel.vue';
import ReviewDuplicatePanel from '../components/shipping-review/ReviewDuplicatePanel.vue';
import ReviewFieldConflictPanel from '../components/shipping-review/ReviewFieldConflictPanel.vue';
import ReviewCloseFulfillmentDialog from '../components/shipping-review/ReviewCloseFulfillmentDialog.vue';
import ReviewLineInventoryOps from '../components/shipping-review/ReviewLineInventoryOps.vue';
import ReviewLineFulfillmentDetail from '../components/shipping-review/ReviewLineFulfillmentDetail.vue';
import ReviewInventoryIssueFallbackCard from '../components/shipping-review/ReviewInventoryIssueFallbackCard.vue';
import ReviewAuditTrailDrawer from '../components/shipping-review/ReviewAuditTrailDrawer.vue';
import ReviewCompletedChecksPanel from '../components/shipping-review/ReviewCompletedChecksPanel.vue';
import ReviewCurrentProcessingCard from '../components/shipping-review/ReviewCurrentProcessingCard.vue';
import ReviewDocumentNavigation, {
type ReviewDocumentNavMode,
} from '../components/shipping-review/ReviewDocumentNavigation.vue';
import ReviewLifecycleStageNavigation, {
type ReviewLifecycleStageCode,
type ReviewLifecycleStageItem,
} from '../components/shipping-review/ReviewLifecycleStageNavigation.vue';
import ReviewIntakeParsePanel from '../components/shipping-review/ReviewIntakeParsePanel.vue';
import ReviewInventoryCandidatesPanel from '../components/shipping-review/ReviewInventoryCandidatesPanel.vue';
import ReviewWorkbenchFooter from '../components/shipping-review/ReviewWorkbenchFooter.vue';
import ReviewWorkbenchHeader from '../components/shipping-review/ReviewWorkbenchHeader.vue';
import ReviewWorkbenchModeToggle from '../components/shipping-review/ReviewWorkbenchModeToggle.vue';
import ReviewUnsavedSwitchDialog from '../components/shipping-review/ReviewUnsavedSwitchDialog.vue';
import { useShippingProcessGateRecovery } from '@/features/shipping-process-gates/composables/useShippingProcessGateRecovery';
import ManualUploadEvidenceDialog from '@/features/workspace/shipping-task-center/ManualUploadEvidenceDialog.vue';
import { downloadWorkspaceShippingExcelFile } from '@/features/workspace/api/shipping-tasks.api';
import { downloadWorkspaceShippingLineInventoryFile, downloadWorkspaceShippingNoticeExcelFile, downloadWorkspaceShippingNoticeExportArchive } from '@/features/chat/shipping/shippingDownload';
import ReviewLlmSuggestionDrawer from '../components/shipping-review/ReviewLlmSuggestionDrawer.vue';
import ReviewProfileMatchPanel from '../components/shipping-review/ReviewProfileMatchPanel.vue';
import ReviewReservationPanel from '../components/shipping-review/ReviewReservationPanel.vue';
import ReviewVersionHistoryDrawer from '../components/shipping-review/ReviewVersionHistoryDrawer.vue';
import ReviewProcessDetailDrawer from '@/features/shipping-progress/components/ReviewProcessDetailDrawer.vue';
import { useProcessingActionPresentation } from '@/features/shipping-progress/composables/useProcessingActionPresentation';
import {
resolveWorkbenchActionItem,
type WorkbenchPanelAvailability,
} from '@/features/shipping-progress/workbenchActionRegistry';
import { parseOrderReviewConfirmResponse } from '../shipping-review/parseOrderReviewConfirmResponse';
import { showReviewResumeOutcome } from '../shipping-review/showReviewResumeOutcome';
import { buildReviewWorkbenchDisplayCase } from '../shipping-review/reviewWorkbenchDisplayState';
import { REVIEW_BUILD_ELIGIBILITY_BLOCKED, useShippingOrderReview } from '../shipping-review/useShippingOrderReview';
import type { ActionPresentationItem } from '@/features/shipping-progress/types';
import type {
ReviewWorkbenchMode,
ReviewWorkbenchPanelState,
ShippingOrderReviewCase,
ShippingOrderReviewDraftFieldMeta,
ShippingOrderReviewEvidence,
ShippingOrderReviewValueSource,
ShippingProcessingLifecycleEntry,
ShippingTaskDetail,
ShippingFreightNoticeGroup,
ShippingUnifiedAction,
} from '../types/shipping.api.types';
/** 证据模式才加载,避免标准复核首屏拉入 pdfjs 预览组件。 */
const ReviewDocumentEvidenceDrawer = defineAsyncComponent(
() => import('../components/shipping-review/ReviewDocumentEvidenceDrawer.vue'),
);
const route = useRoute();
const router = useRouter();
const page = useChatPageContext();
const { t, te } = useI18n();
const { submitPrimaryAction: submitProcessGatePrimaryAction } = useShippingProcessGateRecovery();
/**
* 确认后履约待办详情;任务中心不再挂工作台,由本工作台承接。
* 必须在 useShippingOrderReview 调用前声明:工作台统一投影的 immediate watch 会在
* setup 期间读取 externalOrderTaskNo(引用本 ref),若在此之后再声明会触发 TDZ。
*/
const formalTaskDetail = ref<ShippingTaskDetail | null>(null);
const {
reviewRun,
reviewQueue,
activeCase,
caseProjectionVersion,
caseLoadingContext,
reviewProgressContext,
extractionLifecycleProgress,
shippingProcessingProjection,
shippingProcessingLoading,
authoritativeOrderTaskNo,
refreshShippingProcessing,
versions,
statusMessage,
draftConflict,
draftConflictDiffLines,
buildEligibility,
canConfirmBuild,
routingRecoveryLines,
isViewingHistoricalVersion,
isReadOnly,
initialLoading,
runLoading,
runSwitchFailed,
loadFailed,
caseSwitchLoading,
caseSwitchFailed,
saving,
validationInProgress,
saveFailed,
versionsLoading,
evidence,
llmSuggestions,
suggestionLoading,
focusedFieldId,
focusedLineKey,
previewUrl,
previewLoading,
ensurePreviewLoaded,
ensureEmailEvidenceLoaded,
emailPreview,
intakeParseContext,
intakeParseLoading,
intakeParseLoadFailed,
ensureIntakeParseContextLoaded,
load,
selectCase,
beginCrossRunSwitch,
requestedCaseNo,
refreshWorkItemContext,
openCurrentVersion,
reloadLatestDraft,
refreshReviewQueue,
toggleConflictDiff,
patchHeader,
patchLine,
addLine,
copyLine,
deleteLine,
validate,
rerouteInventoryRouting,
confirm,
startStpAutoCreateTracking,
createManualDraft,
markNonOrder,
markQualityIssue,
reparseDocument,
focusSuggestionField,
setEvidenceDrawerFocus,
clearEvidenceDrawerFocus,
requestSuggestion,
decideSuggestion,
editable,
isFieldEditable,
loadReviewCase,
showWorkflowProgress,
workflowProgressPolling,
startWorkflowProgressPolling,
stopWorkflowProgressPolling,
stopReparseCaseRefreshPolling,
} = useShippingOrderReview({
onWorkflowRefresh: page.bumpWorkflowRefresh,
onReparseCaseReady: handleReparseCaseReady,
// [选法 2] 正式任务下游阶段不再反推复核 Case;OT 号改由已拉取的任务详情提供,
// 使 work-item 统一投影能在 activeCase 为空时仍正常加载。
// order_task_no 优先;若后端 enrich 曾把 OT 自序列化的 order_task_no 冲成 null,
// 则当 task_no 本身是 OT- 前缀时回退 task_no(禁止把 SN 号当 work-item 键)。
externalOrderTaskNo: () => {
const orderTaskNo = String(formalTaskDetail.value?.order_task_no || '').trim();
if (orderTaskNo) return orderTaskNo;
const taskNo = String(formalTaskDetail.value?.task_no || '').trim();
return taskNo.startsWith('OT-') ? taskNo : null;
},
});
const msg = useMessage();
/**
* 右侧主卡阶段:单源只读 shippingProcessingProjection(实时、轻量、已轮询)。
* [Task3 单源] 不再读取 formalTaskDetail.ui_state / activeCase.current_stage /
* automation 状态——同一阶段语义多源先后到达会「先 A 后 B」闪烁;投影未就绪时
* 返回空阶段,由右卡 :loading 驱动 ReviewCurrentProcessingCard 的 stageLoading
* 骨架占位。labelKey 优先投影 stageLabelKey,禁止把 code 直接当用户文案。
*/
const currentProcessingStageDisplay = computed(() => {
// [单源] 右卡「当前阶段/场景」只由 shippingProcessingProjection 提供(实时、轻量、已轮询)。
// 不读 ui_state / activeCase.current_stage:避免同一语义多源先A后B的闪烁。
const projection = shippingProcessingProjection.value;
const uiState = projection?.uiState;
const projectionStage = String(projection?.stage || '').trim();
// [终态同源] 「已完成」不在前端判定:后端验证成功(Notice 三层成功事实齐备,见
// order_review_workbench_projection.project_stage_for_task)才把投影 stage 置
// 'completed',与在途阶段一样经下方主分支原样输出(本 computed 不读
// formalTaskDetail.ui_state / activeCase,终态与在途态同源)。禁止前置终态判定
// (lifecycleStage / userStatus):upload_status 已置但验证未齐的窗口 stage 停在
// 'freight_uploading',必须显示「上传货代」而非「已完成」。
if (projectionStage || (uiState?.lifecycleStage && `${uiState.lifecycleStage}` !== 'upload_complete')) {
const stage = projectionStage || String(uiState?.lifecycleStage || '').trim();
return {
code: stage,
labelKey: projection?.stageLabelKey
|| (stage === 'order_creating' ? 'waiting_system_start' : stage),
inconsistent: false,
};
}
// 投影未就绪:返回空阶段;由右卡(loading=true)渲染骨架占位,而不是「步骤未指定」等误导值。
return { code: '', labelKey: '', inconsistent: false };
});
const runNo = computed(() => String(route.query.run_no || route.params.runNo || ''));
const agentId = computed(() => String(route.params.agentId || ''));
const conversationId = computed(() => String(page.conversationId || route.query.conversation_id || ''));
const itemNoFromQuery = computed(() => String(route.query.item_no || ''));
const reviewFocus = computed(() => String(route.query.focus || '').trim());
const focusedEvidenceRef = ref<{ fieldId: string; lineIndex?: number } | null>(null);
const workbenchMode = ref<ReviewWorkbenchMode>('standard');
const LIFECYCLE_STAGE_CODES: ReviewLifecycleStageCode[] = [
'intake_parse',
'order_review',
'fulfillment_prep',
'freight_upload',
'upload_complete',
];
/**
* 生命周期阶段只描述用户工作 surface;订单、库存、上传状态仍由后端 Projection/Gate 裁决。
* 读序(契约 §1.1 / §6):正式 OT 优先 A → A 未就绪降级 B → 建单前 reviewQueue/Run → A 兜底。
*/
const lifecycleUiState = computed(() => {
const processing = shippingProcessingProjection.value?.uiState;
const formal = formalTaskDetail.value?.ui_state;
const formalOtReady = Boolean(
activeCase.value?.has_formal_ot
|| (
activeCase.value?.confirmed_task_id
&& String(activeCase.value?.confirmed_task_no || '').trim()
&& !activeCase.value?.task_missing
),
);
const aHasLifecycle = Boolean(
processing?.lifecycleStage
|| (Array.isArray(processing?.lifecycleEntries) && processing.lifecycleEntries.length > 0),
);
/**
* 将 A.blocking_reason 解析为页签阻断文案;无 i18n 时退回 code/message。
* @returns 可展示的阻断说明;无可展示内容时为空串
*/
const resolveBlockerFromProcessing = (): string => {
const reason = processing?.blocking_reason;
if (!reason) return '';
const key = String(reason.i18nKey || '').trim();
if (key && te(key)) {
return String(t(key, (reason.details || {}) as Record<string, unknown>)).trim();
}
return String(reason.code || '').trim();
};
// [STEP 1] 正式 OT:页签 stage/entries/blocker 认 A(与右卡同源)。
if (formalOtReady && aHasLifecycle) {
return {
stage: processing?.lifecycleStage || null,
entries: processing?.lifecycleEntries || [],
blocker: resolveBlockerFromProcessing(),
intakeParseAuthorized: false,
};
}
// [STEP 2] A 轮询未落位时短暂降级 B,避免页签空窗。
if (formal?.lifecycle_stage || formal?.lifecycle_entries?.length) {
return {
stage: formal.lifecycle_stage || null,
entries: formal.lifecycle_entries || [],
blocker: String(formal.reason?.message || '').trim(),
intakeParseAuthorized: false,
};
}
// [STEP 3] 建单前:Run/Queue 项仍由后端下发生命周期入口。
// 选法 2(正式下游回看)下 activeCase 刻意为 null,此时以切换管线的 requestedCaseNo
// 定位队列项,否则 entries 永远为空、阶段导航整体退化为 blocked。
const currentCaseNo = String(activeCase.value?.case_no || requestedCaseNo.value || '').trim();
const reviewEntry = (reviewQueue.value?.items || reviewRun.value?.items || []).find(
(item) => String(item.case_no || '').trim() === currentCaseNo,
);
const hasLifecycleEntriesField = reviewEntry
&& Object.prototype.hasOwnProperty.call(reviewEntry, 'lifecycle_entries');
// 字段明确存在时,空 entries 同样是后端的拒绝结果;不能回退到会话级其他 PDF
// 的投影,否则无 Candidate 文件会错误继承别的文件的可进入阶段。仅兼容旧接口
// 未下发该字段的历史响应,才允许使用会话级实时投影。
if (reviewEntry && hasLifecycleEntriesField) {
return {
stage: reviewEntry.lifecycle_stage || null,
entries: Array.isArray(reviewEntry.lifecycle_entries) ? reviewEntry.lifecycle_entries : [],
blocker: '',
intakeParseAuthorized: reviewEntry.intake_parse_authorized === true,
};
}
return {
stage: processing?.lifecycleStage || null,
entries: processing?.lifecycleEntries || [],
blocker: '',
intakeParseAuthorized: false,
};
});
const lifecycleCurrentStageCode = computed<ReviewLifecycleStageCode | null>(() => {
const code = String(lifecycleUiState.value.stage || '').trim();
return LIFECYCLE_STAGE_CODES.includes(code as ReviewLifecycleStageCode)
? code as ReviewLifecycleStageCode
: null;
});
/** 生命周期查看面只有后端 current / available 状态可以进入;其余一律 fail-closed。 */
function lifecycleEntryIsEnterable(entry: { state?: string | null } | undefined): boolean {
return entry?.state === 'current' || entry?.state === 'available';
}
const lifecycleActiveStageCode = computed<ReviewLifecycleStageCode | null>(() => {
const requested = String(route.query.lifecycle_stage || '').trim() as ReviewLifecycleStageCode;
const entry = lifecycleUiState.value.entries.find((item) => item.code === requested);
if (requested === 'intake_parse' && lifecycleUiState.value.intakeParseAuthorized === true) {
return 'intake_parse';
}
const current = lifecycleCurrentStageCode.value;
// 用户可回看后端已授权的 available 前置阶段;自动推进由下方 watcher 在
// 「路由仍停留原 current 阶段且用户未固定查看」时处理,不能在这里抢占用户选择。
return lifecycleEntryIsEnterable(entry) ? requested : current;
});
/** 当前后端投影明确在自动推进时,五阶段导航只为该阶段展示 Spinner,不改变授权。 */
const lifecycleProcessingStageCode = computed<ReviewLifecycleStageCode | null>(() => {
const status = String(
shippingProcessingProjection.value?.uiState?.status
|| shippingProcessingProjection.value?.userStatus
|| shippingProcessingProjection.value?.status
|| '',
).trim().toLowerCase();
if (!['running', 'processing', 'automating', 'queued'].includes(status)) return null;
// 运行态展示以实时 OT Projection 为准,但不参与生命周期入口/工作面裁决。
const stage = String(
shippingProcessingProjection.value?.uiState?.lifecycleStage
|| lifecycleUiState.value.stage
|| '',
).trim();
return LIFECYCLE_STAGE_CODES.includes(stage as ReviewLifecycleStageCode)
? stage as ReviewLifecycleStageCode
: null;
});
/** 接收解析上下文读取必须由当前路由和后端 lifecycle entry 同时授权。 */
const intakeParseContextAuthorized = computed(() => {
const requested = String(route.query.lifecycle_stage || '').trim();
const entry = lifecycleUiState.value.entries.find((item) => item.code === 'intake_parse');
return requested === 'intake_parse' && (
lifecycleUiState.value.intakeParseAuthorized === true
|| lifecycleEntryIsEnterable(entry)
);
});
/**
* 接收解析工作面的目标 Case:选法 2(正式下游回看)下 activeCase 刻意为 null,
* 必须以切换管线的 requestedCaseNo 兜底,否则上下文加载会被静默跳过(面板空白)。
*/
const intakeTargetCaseNo = computed(() => (
String(activeCase.value?.case_no || requestedCaseNo.value || '').trim()
));
const lifecycleStageItems = computed<ReviewLifecycleStageItem[]>(() => {
const blocker = lifecycleUiState.value.blocker;
const entries = lifecycleUiState.value.entries;
return LIFECYCLE_STAGE_CODES.map((code) => {
const entry = entries.find((item) => item.code === code);
// 无 Candidate 的解析处置 capability 是后端单独授权的工作面;它只令首阶段
// 可见为当前,绝不补造订单复核或后续阶段入口。
const intakeParseCapabilityCurrent = code === 'intake_parse'
&& lifecycleUiState.value.intakeParseAuthorized === true;
return {
code,
label: t(`chat.shippingOrderReview.lifecycle.stages.${code}`),
// 生命周期入口必须由后端明确授权;没有 entries 只表示实时裁决尚未到达,
// 不得把默认订单复核伪造成当前可操作阶段。
state: intakeParseCapabilityCurrent || entry?.state === 'current'
? 'current'
: entry?.state === 'available'
? 'completed'
: 'blocked',
reason: entry?.state === 'current' || entry?.state === 'available'
? null
: blocker || t('chat.shippingOrderReview.lifecycle.prerequisite'),
};
});
});
// Case 编辑区是复核对象的兼容展示面,不等于生命周期的“当前订单复核”裁决。
// 后端入口尚未抵达时保留编辑/校验能力,但导航不得高亮或授权任何生命周期阶段。
const showOrderReviewEditor = computed(() => (
lifecycleActiveStageCode.value === 'order_review'
|| lifecycleActiveStageCode.value === null
));
const isLifecycleIntakeParse = computed(() => (
lifecycleActiveStageCode.value === 'intake_parse' && intakeParseContextAuthorized.value
));
const isLifecycleFulfillmentPrep = computed(() => lifecycleActiveStageCode.value === 'fulfillment_prep');
const isLifecycleFreightUpload = computed(() => lifecycleActiveStageCode.value === 'freight_upload');
const isLifecycleUploadComplete = computed(() => lifecycleActiveStageCode.value === 'upload_complete');
/** 正式任务已通知完成时,即使用户回看前置阶段也只能查看,不能再修改已产出通知。 */
const isCompletedFormalTask = computed(() => lifecycleCurrentStageCode.value === 'upload_complete');
const isReviewContentReadOnly = computed(() => isReadOnly.value || isCompletedFormalTask.value);
/** 二期编辑窗(D10):读正式任务 ui_state.edit_window;前端 fail-closed,锁定字段禁用/提示。 */
const formalEditWindow = computed(() => formalTaskDetail.value?.ui_state?.edit_window ?? null);
/** 头字段可编辑:edit_window.header 缺省视为可编辑(后端为权威守卫)。 */
function formalHeaderEditable(): boolean {
return formalEditWindow.value?.header !== false;
}
/**
* 统一字段写权限,确保通知完成后的前置阶段回看不会绕过只读边界。
* @param fieldId - 后端 Schema 下发的字段标识。
* @returns 当前字段是否允许编辑。
*/
function canEditReviewField(fieldId: string): boolean {
return !isReviewContentReadOnly.value && isFieldEditable(fieldId);
}
/** 当前阶段重试只取 Case 的服务端授权,不从输入框附件卡或本地状态推断。 */
const intakeParseRetryAvailable = computed(() => (
isLifecycleIntakeParse.value
&& (
activeCase.value?.available_actions?.includes('retry_parse')
|| [
currentTaskUiState.value?.primary_action,
...(currentTaskUiState.value?.secondary_actions || []),
].some((action) => action?.code === 'retry_parse')
)
&& Boolean(String(activeCase.value?.intake_no || '').trim())
));
const intakeParseRetrying = ref(false);
/**
* 对已发送文件重投原 Intake 的解析任务。
* 成功后同步 Case、统一处理投影并重新读取 Intake 上下文;后端状态会转为 queued,
* 原有 polling 会继续推进,运行中不再展示 retry_parse。
*/
async function retryCurrentIntakeParse(): Promise<void> {
const intakeNo = String(activeCase.value?.intake_no || '').trim();
if (!intakeParseRetryAvailable.value || !intakeNo || intakeParseRetrying.value) return;
intakeParseRetrying.value = true;
try {
await retryShippingNoticeIntake(intakeNo);
await Promise.all([
reloadLatestDraft(),
refreshShippingProcessing(),
intakeTargetCaseNo.value
? ensureIntakeParseContextLoaded(intakeTargetCaseNo.value)
: Promise.resolve(false),
]);
} catch (error) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingNoticeRetryParse'));
} finally {
intakeParseRetrying.value = false;
}
}
/**
* 只切换前端工作面并同步可分享深链;禁止在导航点击中修改任何订单生命周期字段。
*/
const lifecycleStagePinnedByUserForCase = ref<string | null>(null);
/** 仅库存短缺放行可建立一次性自动推进许可,避免通用 Gate 恢复抢占用户导航。 */
const pendingReleaseAutoAdvanceCaseNo = ref<string | null>(null);
/**
* 当前重解析完成前的一次性导航许可。
*
* 重解析是系统恢复流程,Case 替换后应进入后端 current 阶段;但用户等待期间若主动
* 查看某个阶段,保留该意图(前提是新版仍授权该阶段),不能被异步投影强制抢回。
*/
const pendingReparseNavigation = ref<{
sourceCaseNo: string;
documentId: number;
runNo: string | null;
preferredStage: ReviewLifecycleStageCode | null;
cancelled: boolean;
} | null>(null);
/** 兼容详情 DTO 的 document.id 与历史快照的 document_id,始终以同一原始 PDF 识别重解析。 */
function activeReviewDocumentId(): number {
return Number(activeCase.value?.document?.id || activeCase.value?.document_id || 0);
}
/** 记录仍停留在同一 PDF 上的用户手动阶段选择。 */
function rememberPendingReparseStage(code: ReviewLifecycleStageCode) {
const pending = pendingReparseNavigation.value;
const caseNo = String(activeCase.value?.case_no || '').trim();
const documentId = activeReviewDocumentId();
if (!pending || pending.cancelled || pending.sourceCaseNo !== caseNo || pending.documentId !== documentId) return;
pending.preferredStage = code;
}
/** 用户离开本次重解析的原 PDF 或显式打开历史版本时,撤销自动导航。 */
function cancelPendingReparseNavigation() {
if (!pendingReparseNavigation.value || pendingReparseNavigation.value.cancelled) return;
pendingReparseNavigation.value.cancelled = true;
// 用户已主动离开当前 PDF,不能让旧重解析轮询随后把工作台数据重新加载回来。
stopReparseCaseRefreshPolling();
}
/**
* 消费库存短缺放行后的自动推进许可。
*
* 仅当同一 Case 仍停留在放行前的通知准备路由、用户未在放行后手动选阶段,且后端
* 权威投影已推进时替换深链。异步 Job 的首个投影可直接到目标阶段,不能依赖 watch
* 是否曾观察到旧阶段。
*/
async function syncPendingReleaseAutoAdvance(): Promise<boolean> {
const caseNo = String(activeCase.value?.case_no || '').trim();
if (!caseNo || pendingReleaseAutoAdvanceCaseNo.value !== caseNo) return false;
const requested = String(route.query.lifecycle_stage || '').trim();
if (
requested !== 'fulfillment_prep'
|| lifecycleStagePinnedByUserForCase.value === caseNo
) {
pendingReleaseAutoAdvanceCaseNo.value = null;
return false;
}
const current = lifecycleCurrentStageCode.value;
const currentIndex = current ? LIFECYCLE_STAGE_CODES.indexOf(current) : -1;
if (currentIndex <= LIFECYCLE_STAGE_CODES.indexOf('fulfillment_prep')) return false;
pendingReleaseAutoAdvanceCaseNo.value = null;
await selectLifecycleStage(current!, { replace: true });
return true;
}
async function selectLifecycleStage(code: ReviewLifecycleStageCode, options: { replace?: boolean } = {}) {
const target = lifecycleStageItems.value.find((item) => item.code === code);
if (!target || target.state === 'blocked') return;
// 用户主动回看后端 available 或已完成阶段时,异步投影抵达不得将其强制带回当前阶段。
// 自动推进均使用 replace,不会写入该意图。
if (!options.replace) {
const caseNo = String(activeCase.value?.case_no || '').trim() || null;
lifecycleStagePinnedByUserForCase.value = caseNo;
rememberPendingReparseStage(code);
if (pendingReleaseAutoAdvanceCaseNo.value === caseNo) {
pendingReleaseAutoAdvanceCaseNo.value = null;
}
}
if (code === 'intake_parse' && intakeParseContextAuthorized.value && intakeTargetCaseNo.value) {
void ensureIntakeParseContextLoaded(intakeTargetCaseNo.value);
}
const mode: ReviewWorkbenchMode = code === 'order_review' || code === 'intake_parse'
? 'standard'
: (hasFormalOt.value ? 'formal_task' : 'inventory');
workbenchMode.value = mode;
const navigate = options.replace ? router.replace : router.push;
await navigate({ query: { ...route.query, lifecycle_stage: code } });
}
/** 根据已裁决且可查看的阶段恢复对应工作面;不触发业务命令。 */
function syncLifecycleWorkbenchMode(code: ReviewLifecycleStageCode) {
workbenchMode.value = code === 'order_review' || code === 'intake_parse'
? 'standard'
: (hasFormalOt.value ? 'formal_task' : 'inventory');
}
const panelState = ref<ReviewWorkbenchPanelState>({
pdfOpen: false,
pdfPinned: false,
pdfExpanded: false,
pdfDocked: false,
pdfFloatSide: 'right',
eligibilityDetailsOpen: false,
llmSuggestionOpen: false,
versionHistoryOpen: false,
scrollRestoreKey: null,
});
const auditTrailOpen = ref(false);
const lastResolvedCase = ref<ShippingOrderReviewCase | null>(null);
/** 当前展开履约摘要的行键;null 表示全部收起。 */
const fulfillmentDetailLineKey = ref<string | null>(null);
const processDetailOpen = ref(false);
const unsavedSwitchOpen = ref(false);
const pendingSwitchCaseNo = ref<string | null>(null);
/** 导航组件上报的实际呈现模式;仅桌面侧栏模式才为主区预留左列。 */
const reviewDocumentNavigationMode = ref<ReviewDocumentNavMode>('hidden');
/**
* 跨 Run 切换的路由锚点。load() 期间 reviewRun 可能先完成更新并触发路由同步;
* 必须始终使用用户刚选中的目标 Case,不能短暂回写旧文件或清空 case_no。
*/
const pendingCrossRunCaseNo = ref<string | null>(null);
const closeFulfillmentOpen = ref(false);
const closeFulfillmentLineKeys = ref<string[]>([]);
/** focus=evidence 深链只消费一次,切换 PDF 后不得再次自动打开。 */
const evidenceFocusConsumed = ref(false);
watch(activeCase, (value) => {
if (value) {
lastResolvedCase.value = value;
}
}, { immediate: true });
watch(
() => String(activeCase.value?.case_no || '').trim(),
(caseNo, previousCaseNo) => {
if (caseNo !== previousCaseNo) {
lifecycleStagePinnedByUserForCase.value = null;
pendingReleaseAutoAdvanceCaseNo.value = null;
}
},
);
const displayCase = computed(() => buildReviewWorkbenchDisplayCase({
activeCase: activeCase.value,
lastResolvedCase: lastResolvedCase.value,
reviewRun: reviewRun.value,
requestedCaseNo: requestedCaseNo.value,
}));
const displayHeaderValues = computed(() => (
(displayCase.value?.draft?.header_values as Record<string, unknown> | undefined) || {}
));
const displayDraftLines = computed(() => displayCase.value?.draft?.lines || []);
const showWorkbenchCaseShell = computed(() => Boolean(displayCase.value));
/** 切换期间和失败回退均保留旧快照;无稳定 Case 时才进入空状态骨架。 */
const caseContentSkeleton = computed(() => caseSwitchFailed.value && !activeCase.value);
/** can_build && can_auto_create 时,系统接管自动入队;不显示第二个确认按钮。 */
/** queued|running|已有正式 OT|task_missing 时隐藏提交入口。 */
const hideConfirmBecauseAutoGate = computed(() => {
if (hasFormalOt.value || Boolean(activeCase.value?.task_missing)) return true;
if (activeCase.value?.confirmed_task_id) return true;
const automationStatus = String(activeCase.value?.automation?.status || '').trim().toLowerCase();
if (['queued', 'running'].includes(automationStatus)) return true;
if (String(activeCase.value?.status || '') === 'confirmed') return true;
if (String(activeCase.value?.confirmed_task_no || '').trim()) return true;
return false;
});
/** 底栏是否展示自动建单/推进提示(等待 / 推进中)。 */
const showAutoGateHint = computed(() => {
if (validationInProgress.value) return false;
if (hasFormalOt.value || Boolean(activeCase.value?.task_missing)) return true;
const automationStatus = String(activeCase.value?.automation?.status || '').trim().toLowerCase();
return ['waiting_to_start', 'queued', 'running'].includes(automationStatus);
});
/**
* 是否挂载右侧/窄屏「当前处理」卡:task_missing、正式 OT、自动化进行中/失败态,或人工 Gate。
* 核心逻辑:当前任务是本页唯一 Gate 写入口,对象级重试只挂在此卡上。
*/
const mountCurrentProcessingCard = computed(() => {
if (!displayCase.value) return false;
if (caseContentSkeleton.value) return true;
if (Boolean(displayCase.value.task_missing)) return true;
if (hasFormalOt.value) return true;
// v2(spec §5.5):Run 级解析/复核仍活跃且无正式 OT——横幅已收窄为无 Case 轻提示,
// 该区间的状态叙事统一交给当前任务卡承载。
const runStatus = String(lifecycleProgressForView.value?.lifecycle_status || '').trim().toLowerCase();
if (['running', 'waiting', 'failed'].includes(runStatus)) return true;
const gate = displayCase.value.process_gate;
if (
gate?.current_blocking_gate
&& !gate.technical_auto_only
&& String(gate.owner_type || '') !== 'system'
) return true;
const status = String(displayCase.value.automation?.status || '').trim().toLowerCase();
return ['waiting_to_start', 'queued', 'running', 'failed', 'manual_fallback'].includes(status);
});
/** 对象级重试只由当前任务卡承载,禁止与表单底栏重复。 */
const showObjectRetryOnRail = computed(() => (
mountCurrentProcessingCard.value
&& String(currentTaskUiState.value?.primary_action?.code || '').trim().startsWith('retry_')
));
/** 建单前 STP 失败/人工兜底时,底栏显示后端已授权的专用重试入口。 */
const showObjectRetryOnFooter = computed(() => (
!hasFormalOt.value
&& !hasConfirmedAutomationJob.value
&& availableActions.value.includes('retry_stp_auto_create')
&& ['failed', 'manual_fallback'].includes(String(activeCase.value?.automation?.status || '').trim().toLowerCase())
&& activeCase.value?.automation?.retryable === true
));
/**
* 当前任务卡的动作来源。
* 正式 OT 已有 processing.ui_state 时必须直接消费该后端裁决;Case Gate 只服务于
* 尚未形成 OT 投影的建单前复核,避免同一任务在复核页和批次中心出现不同主按钮。
*/
/**
* 右栏当前任务的完整事实源。
*
* 有统一处理投影时,状态、阻断、主/恢复动作必须全部来自该投影;禁止用 Case Gate
* 补任一字段。否则“检查已通过”与旧 Gate 的“待裁决”会被拼到同一张卡上。
*/
const currentTaskUiState = computed(() => shippingProcessingProjection.value?.uiState ?? null);
/**
* Gate/RPA 动作已受理但新投影尚未落位时的本地过渡态。
* 仅用于避免上一帧 failed 在轮询窗口继续冒充当前状态;真实终态仍以后端
* shippingProcessingProjection 为准,不新增业务状态或动作权限。
*/
const recoveryProjectionPending = ref(false);
const recoveryProjectionBaselineVersion = ref<number | null>(null);
watch(
shippingProcessingProjection,
(projection) => {
if (!recoveryProjectionPending.value || !projection) return;
const version = Number(projection.progressVersion || 0);
const baseline = recoveryProjectionBaselineVersion.value;
const status = String(projection.userStatus || projection.status || '').trim().toLowerCase();
const gateStatus = String(projection.currentGate?.status || '').trim().toLowerCase();
const hasFreshVersion = baseline == null || version > baseline;
const isActive = ['running', 'processing', 'automating', 'queued'].includes(status)
|| ['pending', 'queued', 'running', 'waiting_external'].includes(gateStatus);
const isSettled = ['completed', 'cancelled', 'waiting_human', 'retryable'].includes(status);
if (hasFreshVersion || isActive || isSettled) {
recoveryProjectionPending.value = false;
recoveryProjectionBaselineVersion.value = null;
}
},
);
/**
* 正式 OT 已存在且文件切换或统一处理投影读取中时,Case Gate 只是降级快照,不能先暴露可执行动作。
* Projection 返回后才拥有动作裁决权;非切换错误路径仍保留原有的 Case Gate 恢复能力。
* [Task3 单源] 右卡 :loading 另含 formalTaskDetailLoading:任务详情请求在途时投影必然
* 尚未启动,同属「权威阶段未就绪」窗口,右卡阶段行需 stageLoading 骨架占位而非空值「—」。
*/
const formalTaskProjectionPending = computed(() => (
hasFormalOt.value
&& !shippingProcessingProjection.value
&& (caseSwitchLoading.value || shippingProcessingLoading.value)
));
/**
* 发货通知单级写操作只能在主区按 business_no 选择或单条触发。
* 核心逻辑:右侧当前任务卡只保留任务状态与非 Notice 级 Gate 引导,避免其 task_no
* 上下文与主区多选集合竞争同一业务动作;服务端仍是动作授权和状态裁决的唯一来源。
*/
const NOTICE_SCOPED_ACTION_CODES = new Set([
'mark_manual_uploaded',
'retry_freight_upload_rpa',
'regenerate_excel_artifact',
]);
/**
* 判断动作是否属于 Notice 作用域(应在通知组而非任务卡展示)。
* 核心逻辑:只读 code,兼容 ShippingUnifiedAction 与 Projection 的 primary/secondary 动作形状。
* @param action - 任意带 code 的动作对象
* @returns 是否为 Notice 作用域动作
*/
function isNoticeScopedAction(action: { code?: string | null } | null | undefined): boolean {
return NOTICE_SCOPED_ACTION_CODES.has(String(action?.code || '').trim());
}
const formalTaskActions = computed(() => {
const actions = formalTaskDetail.value?.ui_state?.actions;
return [actions?.primary, ...(actions?.secondary || [])]
.filter((action): action is ShippingUnifiedAction => Boolean(action?.code));
});
/** 行级库存选源动作:只在表格逐行处理,禁止作为任务级按钮出现在右侧"当前任务"卡(避免与表格打勾重复)。 */
const LINE_SCOPE_INVENTORY_ACTIONS = new Set([
'override_line_inventory_source',
]);
const currentTaskPrimaryAction = computed(() => {
if (formalTaskProjectionPending.value) return null;
if (hasFormalOt.value) {
// [§2.4 单源] 正式 OT 的主动作只从 A(shippingProcessingProjection.ui_state.primary_action)读,
// 不再读 B(formalTaskDetail.ui_state.actions —— 之后仅作工作面事实)。后端 flatten 已保证
// A==C==B(动作码同源),故该改动纯收敛、不改变已授权按钮。
// 注意:A 的 i18nKey 可能是 chat 域(如 chat.shippingProcessing.action.*),而右卡
// ReviewCurrentProcessingCard 只解析 workspace.shippingNotice.processGate.actionCodes.*,
// 故必须统一映射到卡片域,否则按钮会因 businessActionLabel 为空而 fail-closed 消失。
const action = currentTaskUiState.value?.primary_action ?? null;
if (!action?.code || LINE_SCOPE_INVENTORY_ACTIONS.has(action.code)) return null;
return {
code: String(action.code).trim(),
i18nKey: `workspace.shippingNotice.processGate.actionCodes.${action.code}`,
};
}
const projection = shippingProcessingProjection.value;
if (projection) {
const action = currentTaskUiState.value?.primary_action ?? null;
// Case 已明确没有开放字段冲突时,旧 Projection 不得继续暴露无效的
// resolve_field_conflicts;后端 Gate 仍会在下一次轮询中完成收敛。
if (
action?.code === 'resolve_field_conflicts'
&& Array.isArray(displayCase.value?.field_conflicts)
&& displayCase.value.field_conflicts.length === 0
) {
return null;
}
return action;
}
// 建单前人工 Gate 的权威动作来自当前 Case 投影;只适配后端已下发的动作,
// 不根据字段冲突、生命周期或状态自行生成按钮。
const caseAction = displayCase.value?.process_gate?.primary_action;
if (caseAction?.code && displayCase.value?.process_gate?.owner_type !== 'system') {
return caseAction;
}
return null;
});
const currentTaskUserStatus = computed(() => {
if (formalTaskDetail.value?.ui_state?.lifecycle_stage === 'upload_complete') return 'completed';
if (recoveryProjectionPending.value) return 'running';
// 已确认 OT 且权威投影在途时,先消费后端 automation 运行态(queued/running → running,
// failed/manual_fallback → failed),状态行即显真实值,不应退回「正在获取最新状态」骨架;
// authority 仍以右侧投影为准,投影到达后覆盖。
if (currentTaskUiState.value?.status) return currentTaskUiState.value.status;
// 建单前没有正式 OT 投影时,直接消费后端 Case automation 状态,避免页面看起来卡死。
const status = String(activeCase.value?.automation?.status || '').trim().toLowerCase();
if (['queued', 'running'].includes(status)) return 'running';
if (['failed', 'manual_fallback'].includes(status)) return 'failed';
// v2(spec §5.1):以上全无值时用 Run 级 lifecycle_status 兜底(受控映射,
// completed/cancelled/未知不映射),消除「待机 vs 等待解析任务启动」矛盾。
return resolveRunLifecycleUserStatus(lifecycleProgressForView.value);
});
/**
* v2(spec §5.2):当前任务卡状态块内嵌动态说明。
* 核心逻辑:completed/cancelled 不渲染;共享函数解析 run 级说明;
* 仅当原因码在隐藏白名单且映射结果==当前状态(纯重复)才隐藏,其余诊断信息一律保留。
*/
const currentTaskStatusDetail = computed<{ text: string } | null>(() => {
if (recoveryProjectionPending.value) return null;
if (['completed', 'cancelled'].includes(String(currentTaskUserStatus.value || ''))) return null;
const message = resolveExtractionActivityMessage(lifecycleProgressForView.value, { t, te });
if (!message) return null;
if (isRedundantExtractionDetail(extractExtractionProgressReasonCode(lifecycleProgressForView.value), currentTaskUserStatus.value)) {
return null;
}
return { text: message.text };
});
const currentTaskBlockingReason = computed(() => {
if (formalTaskDetail.value?.ui_state?.lifecycle_stage === 'upload_complete') return null;
if (recoveryProjectionPending.value) return null;
if (formalTaskProjectionPending.value) return null;
return currentTaskUiState.value?.blocking_reason ?? null;
});
/** 当前 Gate 状态必须与右栏动作同源,均来自统一处理 Projection。 */
const currentTaskGateStatus = computed(() => {
if (formalTaskDetail.value?.ui_state?.lifecycle_stage === 'upload_complete') return null;
if (recoveryProjectionPending.value) return 'running';
if (formalTaskProjectionPending.value) return null;
const projection = shippingProcessingProjection.value;
if (projection?.currentGate?.status) return projection.currentGate.status;
return String(activeCase.value?.automation?.status || '').trim().toLowerCase() === 'queued'
? 'pending'
: null;
});
const currentTaskRetryable = computed(() => (
formalTaskProjectionPending.value
? false
: !hasFormalOt.value && showObjectRetryOnRail.value
));
const currentTaskRecoveryActions = computed(() => {
if (formalTaskProjectionPending.value) return [];
if (hasFormalOt.value) {
// [§2.4 单源] 任务级恢复按钮只读 A.secondary_actions;不再叠加 B.capabilities。
// capabilities 仍可作点击执行的 stageCapabilityBypass 查找(见 handleCurrentTaskAction),
// 但不得单独渲成右卡按钮——能力要展示须先并进 A。行级选源禁止出现在右卡。
return (currentTaskUiState.value?.secondary_actions || [])
.filter((action) => action.enabled
&& String(action.code || '').trim() !== 'download_excel'
&& !isNoticeScopedAction(action))
.map((action) => ({
code: String(action.code || '').trim(),
// 统一右卡 domain:actionCodes.<code>(见 currentTaskPrimaryAction 注;A 的 i18nKey 可能是 chat 域)。
i18nKey: `workspace.shippingNotice.processGate.actionCodes.${String(action.code || '').trim()}`,
}))
.filter((action): action is { code: string; i18nKey: string } => {
const code = String(action.code || '').trim();
return Boolean(code) && !LINE_SCOPE_INVENTORY_ACTIONS.has(code);
});
}
const projection = shippingProcessingProjection.value;
if (projection) {
return (currentTaskUiState.value?.secondary_actions || [])
.filter((action) => action.enabled)
.map((action) => ({ code: String(action.code || '').trim(), i18nKey: action.i18nKey ?? null }))
.filter((action) => action.code);
}
return [];
});
/**
* 已验证的通知完成面只展示成功证据,不能因迟到或历史 Gate 动作再次提供写入口。
* 核心逻辑:货代上传工作面仍原样消费后端授权动作;完成面只把动作降为只读,
* 不修改服务端授权,也不根据客户端状态推导新的操作。
* @returns 当前工作面允许交给 ReviewCurrentProcessingCard 展示的动作。
*/
const visibleCurrentTaskPrimaryAction = computed(() => (
isCompletedFormalTask.value ? null : currentTaskPrimaryAction.value
));
const visibleCurrentTaskRecoveryActions = computed(() => (
isCompletedFormalTask.value ? [] : currentTaskRecoveryActions.value
));
const visibleCurrentTaskRetryable = computed(() => (
isCompletedFormalTask.value ? false : currentTaskRetryable.value
));
/** 管理员诊断:后端 technical_progress / automation.technical 仅 admin 投影。 */
const showAdminTaskMissingDiagnosis = computed(() => (
Boolean(displayCase.value?.task_missing)
&& (
Boolean(displayCase.value?.technical_progress)
|| Boolean((displayCase.value?.automation as { technical?: unknown } | undefined)?.technical)
)
));
/**
* 是否存在已确认的自动建单/推进 Job(queued|running)。
* 核心逻辑:仅 post_confirm 或投影 status 明确入队/运行时为 true;资格达标不算。
*/
const hasConfirmedAutomationJob = computed(() => {
const automationStatus = String(activeCase.value?.automation?.status || '').trim().toLowerCase();
if (['queued', 'running', 'completed'].includes(automationStatus)) return true;
const progress = activeCase.value?.post_confirm_auto_progress;
const progressStatus = String(progress?.status || '').trim().toLowerCase();
if (['queued', 'running', 'started', 'in_progress'].includes(progressStatus)) return true;
const projStatus = String(shippingProcessingProjection.value?.status || '').trim().toLowerCase();
const hasTask = Boolean(
String(activeCase.value?.confirmed_task_no || '').trim()
|| String(authoritativeOrderTaskNo.value || '').trim(),
);
return hasTask && ['processing', 'automating', 'queued'].includes(projStatus);
});
/**
* 底栏自动资格提示:消费 automation.phase,禁止前端猜「建单/推进」文案。
*/
const autoGateHintKey = computed(() => {
const phase = String(activeCase.value?.automation?.phase || '').trim();
const status = String(activeCase.value?.automation?.status || '').trim().toLowerCase();
if (displayCase.value?.task_missing) {
return 'chat.shippingOrderReview.currentProcessing.taskMissingHint';
}
if (status === 'waiting_to_start') {
return phase === 'pre_ot_stp'
? 'chat.shippingOrderReview.automation.waitingPreOt'
: 'chat.shippingOrderReview.automation.waitingPostOt';
}
return hasConfirmedAutomationJob.value
? 'chat.shippingOrderReview.buildEligibility.autoGateRunningHint'
: 'chat.shippingOrderReview.buildEligibility.autoGateWaitingHint';
});
/** 是否展示人工阻断卡:必须后端 owner_type=human 且非 technical_auto_only。 */
const showHumanBlockingGate = computed(() => {
const gate = activeCase.value?.process_gate;
if (!gate?.current_blocking_gate) return false;
if (gate.technical_auto_only) return false;
if (String(gate.owner_type || '') === 'system') return false;
return true;
});
/** 正式 OT 后是否将订单检查降级折叠。 */
const showEligibilityAsPrimary = computed(() => !hasFormalOt.value && !displayCase.value?.task_missing);
/** 证据浮窗是否以浮动方式展示(打开且未固定为侧栏)。 */
const evidenceFloating = computed(
() => workbenchMode.value === 'evidence' && panelState.value.pdfOpen && !panelState.value.pdfDocked,
);
/** 证据是否以双栏侧栏方式展示。 */
const evidenceDocked = computed(
() => workbenchMode.value === 'evidence' && panelState.value.pdfOpen && panelState.value.pdfDocked,
);
const mainEditorScrollEl = ref<HTMLElement | null>(null);
const savedScrollTop = ref(0);
const confirmSuccess = ref<{
taskNo: string;
/** Candidate 一对一 OT;返回对话聚焦用。 */
orderTaskNo: string;
/** 建单已成功 */
confirmOk: boolean;
/** 自动推进已入队/启动 */
autoProgress: boolean;
/** 入队失败或同步执行失败,需用户可见告警 */
progressFailed: boolean;
progressStatus: string;
progressMessage: string;
/** Gate 位置标签(derive_position) */
position: string;
/** 来自 Case 投影的刷新恢复(非本次确认即时响应) */
restoredFromProjection?: boolean;
} | null>(null);
const progressRetrying = ref(false);
/**
* 题9A:任务级三重禁用总开关。
* 优先级:① 请求中 progressRetrying/caseSwitchLoading → ② 服务端 inventoryPreparation 仍在运行。
*/
const taskRetryButtonDisabled = computed(() => {
if (Boolean(activeCase.value?.task_missing)) return true;
if (progressRetrying.value || caseSwitchLoading.value) return true;
const inv = shippingProcessingProjection.value?.inventoryPreparation;
if (inv) {
if (Number(inv.activeAttemptCount || 0) > 0) return true;
if (Boolean(inv.gateAttemptActive)) return true;
if ((inv.pendingSources || []).length > 0) return true;
}
return false;
});
/**
* 从 Case 投影恢复「已建单但仍待推进」琥珀色重试条(覆盖页面刷新场景)。
* 核心逻辑:仅当 post_confirm_auto_progress.needs_retry 时写入;不覆盖同会话即时 confirm 结果。
* 注:确认成功琥珀色 UI 已移除(避免与对话级/对象级重试重复);本 hydrate 仍供内部状态与流程动作使用。
*/
function hydrateConfirmProgressFromCase() {
const caseRow = activeCase.value;
if (!caseRow || String(caseRow.status || '') !== 'confirmed') return;
if (confirmSuccess.value && !confirmSuccess.value.restoredFromProjection) return;
const progress = caseRow.post_confirm_auto_progress;
if (!progress?.needs_retry) {
if (confirmSuccess.value?.restoredFromProjection && !progress?.needs_retry) {
confirmSuccess.value = null;
}
return;
}
const taskNo = String(progress.task_no || caseRow.confirmed_task_no || '').trim();
if (!taskNo) return;
confirmSuccess.value = {
taskNo,
orderTaskNo: String(caseRow.order_task_no || '').trim(),
confirmOk: true,
autoProgress: false,
progressFailed: true,
progressStatus: String(progress.status || 'needs_retry'),
progressMessage: String(progress.message || ''),
position: '',
restoredFromProjection: true,
};
}
/**
* 深链 focus=evidence:仅首次进入且尚未消费时打开证据模式;消费后立即从 URL 清除 focus。
* 切换 PDF/Case 不得因残留 query 或新 evidence 加载再次自动打开。
*/
watch(
() => [evidence.value, reviewFocus.value, activeCase.value?.case_no] as const,
([items, focus]) => {
if (focus !== 'evidence' || evidenceFocusConsumed.value || !items?.length) return;
const first = items.find((item) => item.bbox) || items[0];
if (!first) return;
evidenceFocusConsumed.value = true;
focusedEvidenceRef.value = {
fieldId: String(first.field_id || '').trim(),
lineIndex: first.line_index == null ? undefined : Number(first.line_index),
};
workbenchMode.value = 'evidence';
panelState.value = { ...panelState.value, pdfOpen: true };
void ensurePreviewLoaded();
const nextQuery = { ...route.query };
delete nextQuery.focus;
void router.replace({ query: nextQuery });
},
{ immediate: true },
);
/**
* 当前用于 PDF 证据高亮的条目:明细同时按字段与行号匹配,避免多行同字段定位错位。
*/
const selectedEvidence = computed((): ShippingOrderReviewEvidence | null => {
const items = evidence.value || [];
const fieldId = String(focusedEvidenceRef.value?.fieldId || '').trim();
if (fieldId) {
const lineIndex = focusedEvidenceRef.value?.lineIndex;
// 有聚焦字段时按质量优选,不回退到其他字段证据。
return findFieldEvidence(fieldId, lineIndex) || null;
}
if (!items.length) return null;
return items.find((item) => item.highlight_bbox || item.bbox) || items[0] || null;
});
const selectedEvidenceIsEmail = computed(() => String(selectedEvidence.value?.document_type || '') === 'email_body');
/**
* 证据面板打开、Case 或当前证据变化时按 Document 类型读取受控预览。
* 邮件正文绝不回退到 Case 主 PDF,避免证据载体与弹窗内容不一致。
*/
watch(
() => [activeCase.value?.case_no, panelState.value.pdfOpen, selectedEvidence.value?.document_id, selectedEvidence.value?.evidence_id, selectedEvidenceIsEmail.value] as const,
([caseNo, pdfOpen, documentId, evidenceId, isEmail]) => {
if (!pdfOpen || !caseNo) return;
if (isEmail && documentId) {
void ensureEmailEvidenceLoaded(caseNo, Number(documentId), evidenceId || undefined);
return;
}
emailPreview.value = null;
void ensurePreviewLoaded(caseNo);
},
);
/** 多 evidence 优选顺序:verified > candidate > unavailable > invalid;同级优先有 highlight_bbox。 */
const HIGHLIGHT_QUALITY_RANK: Record<string, number> = {
verified: 0,
candidate: 1,
unavailable: 2,
invalid: 3,
};
/**
* 选择字段最佳证据:多 Observation 时按质量与可绘制 bbox 优选,禁止盲取首条。
*/
const findFieldEvidence = (fieldId: string, lineIndex?: number) => {
const matches = (evidence.value || []).filter((item) =>
String(item.field_id || '') === String(fieldId || '').trim()
&& (lineIndex === undefined || Number(item.line_index) === lineIndex),
);
if (!matches.length) return undefined;
return [...matches].sort((left, right) => {
const leftRank = HIGHLIGHT_QUALITY_RANK[String(left.highlight_quality || '')] ?? 9;
const rightRank = HIGHLIGHT_QUALITY_RANK[String(right.highlight_quality || '')] ?? 9;
if (leftRank !== rightRank) return leftRank - rightRank;
const leftDrawable = left.highlight_bbox || left.bbox ? 0 : 1;
const rightDrawable = right.highlight_bbox || right.bbox ? 0 : 1;
return leftDrawable - rightDrawable;
})[0];
};
/**
* 读取字段高亮质量(与自动确认状态独立,仅用于展示)。
* 无 Observation / 无证据时默认 unavailable,避免与「前端未加载」混淆。
*/
const fieldHighlightQuality = (fieldId: string, lineIndex?: number) => {
const quality = String(findFieldEvidence(fieldId, lineIndex)?.highlight_quality || '').trim();
return quality || 'unavailable';
};
/**
* 是否仅诊断、不可精确高亮(红色入口)。
*/
const isLocateDiagnoseOnly = (quality: string) => quality === 'unavailable' || quality === 'invalid';
/**
* 定位图标颜色:绿=verified,橙=candidate,红=unavailable/invalid。
* 不得仅依赖颜色:调用方须同步设置 title / aria-label。
*/
const locateIconButtonClass = (quality: string) => {
if (quality === 'verified') {
return 'rounded p-1 text-emerald-600 hover:bg-emerald-50 dark:text-emerald-400 dark:hover:bg-emerald-950/40';
}
if (quality === 'candidate') {
return 'rounded p-1 text-orange-600 hover:bg-orange-50 dark:text-orange-400 dark:hover:bg-orange-950/40';
}
return (
'rounded p-1 text-rose-600 hover:bg-rose-50 dark:text-rose-400 dark:hover:bg-rose-950/40'
);
};
/**
* 定位控件可访问文案:含字段名、质量状态与无坐标/候选说明。
*/
const locateControlLabel = (fieldDisplayName: string, fieldId: string, lineIndex?: number) => {
const quality = fieldHighlightQuality(fieldId, lineIndex);
const qualityLabel = t(`chat.shippingOrderReview.highlightQuality.${quality}`);
const base = t('chat.shippingOrderReview.locateSource', { field: fieldDisplayName });
if (quality === 'unavailable' || quality === 'invalid') {
return `${base} — ${qualityLabel}. ${t('chat.shippingOrderReview.locateUnavailableHint')}`;
}
if (quality === 'candidate') {
return `${base} — ${qualityLabel}. ${t('chat.shippingOrderReview.locateCandidateHint')}`;
}
return `${base} — ${qualityLabel}`;
};
/**
* 写定位点击审计;无 evidence 也记录,失败不阻断 UI。
*/
const auditFieldLocateAttempt = (
fieldId: string,
lineIndex: number | undefined,
matched: ShippingOrderReviewEvidence | null | undefined,
) => {
const caseNo = String(activeCase.value?.case_no || '').trim();
if (!caseNo) return;
const quality = String(matched?.highlight_quality || fieldHighlightQuality(fieldId, lineIndex));
const pdfLocated = Boolean(
matched
&& (matched.highlight_quality === 'verified' || matched.highlight_quality === 'candidate')
&& (matched.highlight_bbox || matched.bbox),
);
void attemptWorkspaceShippingOrderReviewFieldLocate(caseNo, {
field_id: fieldId,
line_index: lineIndex ?? null,
highlight_quality: quality,
has_evidence: Boolean(matched?.evidence_id),
evidence_id: matched?.evidence_id || null,
pdf_located: pdfLocated,
coordinate_issue_codes: matched?.coordinate_issue_codes || [],
}).catch(() => undefined);
};
/**
* 同步当前编辑字段焦点(不切换工作台模式)。
* 用途:输入框 focus 时更新 AI 建议焦点与证据引用,避免误开 PDF 抽屉。
*/
const syncFieldFocus = (fieldId: string, lineIndex?: number) => {
const lineKey = lineIndex != null ? activeCase.value?.draft?.lines?.[lineIndex]?.draft_line_id : undefined;
focusSuggestionField(String(fieldId || '').trim(), typeof lineKey === 'string' ? lineKey : null);
focusedEvidenceRef.value = findFieldEvidence(fieldId, lineIndex)
? { fieldId: String(fieldId || '').trim(), lineIndex }
: null;
};
/**
* 当前证据模式下是否与 PDF 联动的字段输入(用于边框高亮)。
*/
const isEvidenceLinkedField = (fieldId: string, lineIndex?: number) => {
if (workbenchMode.value !== 'evidence' || !panelState.value.pdfOpen) return false;
const focused = focusedEvidenceRef.value;
if (!focused) return false;
if (String(focused.fieldId || '') !== String(fieldId || '').trim()) return false;
if (lineIndex === undefined) return focused.lineIndex == null;
return Number(focused.lineIndex) === Number(lineIndex);
};
/**
* 从草稿问题与建单门禁问题收集可跳转的异常字段目标(去重保序)。
*/
const exceptionTargets = computed(() => {
type Target = { fieldId: string; lineIndex?: number; key: string };
const seen = new Set<string>();
const out: Target[] = [];
const lines = activeCase.value?.draft?.lines || [];
const lineIndexByKey = new Map(
lines.map((line, index) => [String(line.draft_line_id || '').trim(), index] as const),
);
const schemaFields = activeCase.value?.schema?.fields || [];
const resolveLineIndex = (lineIndexRaw: unknown, draftLineIdRaw?: unknown) => {
if (lineIndexRaw != null && lineIndexRaw !== '' && Number.isFinite(Number(lineIndexRaw))) {
return Number(lineIndexRaw);
}
const draftLineId = String(draftLineIdRaw || '').trim();
return draftLineId ? lineIndexByKey.get(draftLineId) : undefined;
};
const fieldIdForCode = (fieldCodeRaw: unknown) => {
const fieldCode = String(fieldCodeRaw || '').trim();
return fieldCode ? schemaFields.find((field) => field.field_code === fieldCode)?.field_id || '' : '';
};
const push = (fieldIdRaw: unknown, lineIndexRaw: unknown, draftLineIdRaw?: unknown) => {
const fieldId = String(fieldIdRaw || '').trim();
if (!fieldId) return;
const lineIndex = resolveLineIndex(lineIndexRaw, draftLineIdRaw);
const key = lineIndex == null || !Number.isFinite(lineIndex)
? fieldId
: `${fieldId}:${lineIndex}`;
if (seen.has(key)) return;
seen.add(key);
out.push({
fieldId,
lineIndex: lineIndex == null || !Number.isFinite(lineIndex) ? undefined : lineIndex,
key,
});
};
for (const issue of activeCase.value?.draft?.issues || []) {
const reviewIssue = issue as typeof issue & { draft_line_id?: string | null };
push(reviewIssue.field_id || fieldIdForCode(reviewIssue.field_code), reviewIssue.line_index, reviewIssue.draft_line_id);
}
for (const issue of buildEligibility.value?.issues || []) {
const rawFieldId = String((issue as { field_id?: string | null }).field_id || '').trim();
const byCode = fieldIdForCode(issue.field_code);
const fields = Array.isArray((issue as unknown as { fields?: unknown[] }).fields)
? (issue as unknown as { fields: unknown[] }).fields
: [];
if (rawFieldId || byCode) {
push(rawFieldId || byCode, issue.line_index, issue.draft_line_id);
continue;
}
for (const fieldCode of fields) {
push(fieldIdForCode(fieldCode), issue.line_index, issue.draft_line_id);
}
}
return out;
});
const exceptionOrdinal = computed(() => {
const targets = exceptionTargets.value;
if (!targets.length) return 0;
const fieldId = String(focusedEvidenceRef.value?.fieldId || focusedFieldId.value || '').trim();
if (!fieldId) return 0;
const lineIndex = focusedEvidenceRef.value?.lineIndex;
const idx = targets.findIndex((item) => (
item.fieldId === fieldId
&& (item.lineIndex == null ? lineIndex == null : Number(item.lineIndex) === Number(lineIndex))
));
return idx >= 0 ? idx + 1 : 0;
});
/**
* 跳转到上一个/下一个异常字段并定位 PDF。
* @param delta - -1 上一异常,+1 下一异常
*/
const navigateExceptionField = (delta: number) => {
const targets = exceptionTargets.value;
if (!targets.length) return;
let idx = exceptionOrdinal.value > 0 ? exceptionOrdinal.value - 1 : -1;
if (idx < 0) idx = delta > 0 ? -1 : 0;
const next = targets[Math.min(Math.max(idx + delta, 0), targets.length - 1)];
if (!next) return;
focusFieldEvidence(next.fieldId, next.lineIndex);
if (next.lineIndex != null) focusOrderLine(next.lineIndex);
};
/**
* Alt+[ / Alt+]:上一个 / 下一个异常字段(输入框内同样生效,避免与文本输入冲突)。
*/
const onExceptionNavKeydown = (event: KeyboardEvent) => {
if (!(event.altKey) || event.ctrlKey || event.metaKey) return;
if (event.key !== '[' && event.key !== ']') return;
if (!exceptionTargets.value.length) return;
event.preventDefault();
navigateExceptionField(event.key === '[' ? -1 : 1);
};
onMounted(() => {
document.addEventListener('keydown', onExceptionNavKeydown, true);
// [PERF] 深链进入时尽早并行发起任务详情,与 load() 重叠,削减首屏串行加载。
prefetchDeepLinkedTaskDetail();
// OT 直链(无 case_no)下 confirmedNoticeTaskNo 恒空、watch(hasFormalOt) 永不触发;
// 挂载即消费深链预取(复用同一请求,不重复拉取),任务详情才能落地驱动五阶段页签。
if (deepLinkOrderTaskNo.value) void loadFormalTaskDetail();
});
onBeforeUnmount(() => {
document.removeEventListener('keydown', onExceptionNavKeydown, true);
});
/**
* 定位字段证据:保存滚动、进入 evidence 模式并打开 PDF 浮窗(默认不挤占主编辑区)。
* 由「定位原文」按钮或字段双击触发;无 Observation 时仍可点击(红色),打开诊断说明。
*/
const focusFieldEvidence = (fieldId: string, lineIndex?: number) => {
if (mainEditorScrollEl.value) {
savedScrollTop.value = mainEditorScrollEl.value.scrollTop;
}
const normalizedFieldId = String(fieldId || '').trim();
const lineKey = lineIndex != null ? activeCase.value?.draft?.lines?.[lineIndex]?.draft_line_id : undefined;
focusSuggestionField(normalizedFieldId, typeof lineKey === 'string' ? lineKey : null);
// 无证据也保留字段焦点,供抽屉展示「无坐标」诊断,禁止回退到其他字段。
focusedEvidenceRef.value = { fieldId: normalizedFieldId, lineIndex };
const matched = findFieldEvidence(fieldId, lineIndex);
setEvidenceDrawerFocus({
fieldId: normalizedFieldId,
lineKey: typeof lineKey === 'string' ? lineKey : null,
lineIndex: lineIndex ?? null,
pageNo: matched?.page_no ?? null,
evidenceId: matched?.evidence_id ?? null,
});
workbenchMode.value = 'evidence';
panelState.value = {
...panelState.value,
pdfOpen: true,
// 定位证据默认浮窗;保留用户已选的 docked/expanded/side。
scrollRestoreKey: typeof lineKey === 'string' ? `${fieldId}:${lineKey}` : normalizedFieldId,
};
const caseNo = String(activeCase.value?.case_no || '').trim();
if (selectedEvidenceIsEmail.value && caseNo && selectedEvidence.value?.document_id) {
void ensureEmailEvidenceLoaded(caseNo, Number(selectedEvidence.value.document_id));
} else {
void ensurePreviewLoaded();
}
// [STEP] 所有定位点击写 locate 审计(含无 evidence);有 evidence_id 再写 focus/诊断。
auditFieldLocateAttempt(normalizedFieldId, lineIndex, matched);
const quality = String(matched?.highlight_quality || fieldHighlightQuality(fieldId, lineIndex));
if (caseNo && matched?.evidence_id) {
void getWorkspaceShippingOrderReviewEvidenceItem(caseNo, matched.evidence_id)
.catch(() => undefined);
if (quality === 'unavailable' || quality === 'invalid') {
void viewWorkspaceShippingOrderReviewHighlightDiagnostic(
caseNo,
matched.evidence_id,
).catch(() => undefined);
}
}
};
/**
* 退出证据核对模式:恢复滚动;未勾选「退出后保留」时关闭面板。
*/
const closeEvidenceMode = () => {
workbenchMode.value = 'standard';
if (!panelState.value.pdfPinned) {
panelState.value = { ...panelState.value, pdfOpen: false };
}
panelState.value = { ...panelState.value, scrollRestoreKey: null };
clearEvidenceDrawerFocus();
void nextTick(() => {
if (mainEditorScrollEl.value) {
mainEditorScrollEl.value.scrollTop = savedScrollTop.value;
}
});
};
/** 切换浮窗紧凑/展开尺寸(不改变主布局)。 */
const togglePdfExpanded = () => {
panelState.value = { ...panelState.value, pdfExpanded: !panelState.value.pdfExpanded };
};
/** 切换浮动面板 ↔ 固定侧栏双栏。 */
const togglePdfDocked = () => {
const nextDocked = !panelState.value.pdfDocked;
panelState.value = {
...panelState.value,
pdfDocked: nextDocked,
pdfOpen: true,
// 固定侧栏时收起「展开」态,避免语义混淆。
pdfExpanded: nextDocked ? false : panelState.value.pdfExpanded,
};
void ensurePreviewLoaded();
};
/** 浮窗左右切换,减轻对当前字段的遮挡。 */
const togglePdfFloatSide = () => {
panelState.value = {
...panelState.value,
pdfFloatSide: panelState.value.pdfFloatSide === 'right' ? 'left' : 'right',
};
};
/** 进入库存处理模式,突出库存候选面板。 */
const enterInventoryMode = () => {
// 正式 OT 后禁止完整库存工作台;行级动作走明细浮层 / Case 兜底卡。
if (hasFormalOt.value) return;
workbenchMode.value = 'inventory';
};
/** 退出库存处理模式,回到标准复核布局。 */
const exitInventoryMode = () => {
workbenchMode.value = 'standard';
};
/**
* 处理模式切换条事件;evidence/inventory 返回 standard 时走专用清理逻辑。
*/
const onWorkbenchModeChange = (mode: ReviewWorkbenchMode) => {
if (mode === 'standard') {
if (workbenchMode.value === 'evidence') {
closeEvidenceMode();
return;
}
if (workbenchMode.value === 'inventory') {
exitInventoryMode();
return;
}
}
if (mode === 'inventory') {
enterInventoryMode();
return;
}
workbenchMode.value = mode;
};
/** 切换「退出后保留」:离开证据模式时是否保留 pdfOpen(≠ 固定侧栏)。 */
const togglePdfPinned = () => {
panelState.value = { ...panelState.value, pdfPinned: !panelState.value.pdfPinned };
if (panelState.value.pdfPinned) {
panelState.value = { ...panelState.value, pdfOpen: true };
void ensurePreviewLoaded();
}
};
/**
* 在证据列表中移动到上一项/下一项,并同步字段焦点。
* @param delta - -1 上一证据,+1 下一证据
*/
const navigateEvidence = (delta: number) => {
const items = evidence.value || [];
if (!items.length) return;
const currentId = String(selectedEvidence.value?.evidence_id || '');
let idx = items.findIndex((item) => item.evidence_id === currentId);
if (idx < 0) idx = 0;
const next = items[Math.min(Math.max(idx + delta, 0), items.length - 1)];
if (!next) return;
const lineIndex = next.line_index == null ? undefined : Number(next.line_index);
const lineKey = lineIndex != null
? activeCase.value?.draft?.lines?.[lineIndex]?.draft_line_id
: undefined;
syncFieldFocus(String(next.field_id || ''), lineIndex);
focusedEvidenceRef.value = {
fieldId: String(next.field_id || '').trim(),
lineIndex,
};
setEvidenceDrawerFocus({
fieldId: String(next.field_id || '').trim(),
lineKey: typeof lineKey === 'string' ? lineKey : null,
lineIndex: lineIndex ?? null,
pageNo: next.page_no ?? null,
evidenceId: next.evidence_id,
});
panelState.value = { ...panelState.value, pdfOpen: true };
};
/** 打开版本历史抽屉。 */
/**
* 打开版本历史抽屉:先写入访问审计,失败则告警并拒绝展示(硬性可追溯)。
*/
const openVersionHistory = async () => {
const caseNo = String(activeCase.value?.case_no || '').trim();
if (!caseNo) return;
try {
await auditWorkspaceShippingOrderReviewVersionHistory(caseNo);
panelState.value = { ...panelState.value, versionHistoryOpen: true };
} catch {
msg.warning(t('chat.shippingOrderReview.workbench.auditFailed'));
}
};
/** 关闭版本历史抽屉。 */
const closeVersionHistory = () => {
panelState.value = { ...panelState.value, versionHistoryOpen: false };
};
/** 打开审计时间线抽屉(按需加载 timeline)。 */
const openAuditTrail = () => {
auditTrailOpen.value = true;
};
/**
* 收起行内履约摘要。
*/
function closeFulfillmentDetail() {
fulfillmentDetailLineKey.value = null;
}
/** 关闭审计时间线抽屉。 */
const closeAuditTrail = () => {
auditTrailOpen.value = false;
};
/**
* 打开关闭履约行对话框。
* @param lineKeys - 待关闭行键;空数组表示全部剩余开放行
*/
const openCloseFulfillmentDialog = (lineKeys: string[]) => {
closeFulfillmentLineKeys.value = [...lineKeys];
closeFulfillmentOpen.value = true;
};
/** 库存事实只属于「通知准备」工作面;正式 OT 已创建不能让它泄漏到订单复核。 */
const showLineInventoryColumns = computed(() => (
isLifecycleFulfillmentPrep.value
));
/**
* 按冻结快照行身份取履约投影行;通知准备不使用草稿身份。
*/
function draftLineFulfillmentFor(draftLineId: string): ShippingOrderReviewLineFulfillmentLine | null {
const rows = displayCase.value?.line_fulfillment?.lines || [];
return rows.find((item) => String(item.draft_line_id ?? '') === String(draftLineId ?? '')) || null;
}
function preparationLineFulfillmentFor(snapshotLineId: number | string | null | undefined): ShippingOrderReviewLineFulfillmentLine | null {
const rows = formalTaskDetail.value?.ui_state?.stage_context?.preparation?.lines || [];
return rows.find((item) => String(item.snapshot_line_id ?? '') === String(snapshotLineId ?? '')) as ShippingOrderReviewLineFulfillmentLine | null;
}
/**
* 是否为行 Schema 数量字段(qty/quantity)。
*/
function isQtySchemaField(field: { field_code?: string }): boolean {
const code = String(field.field_code || '').trim().toLowerCase();
return code === 'qty' || code === 'quantity';
}
/**
* 将 API 的 Decimal 文本规范为稳定展示值,不转为 JavaScript Number,避免精度丢失。
*
* 核心逻辑:库存事实和 Case 回退投影都可能携带等价的 ``3.0`` / ``3``;展示层去除
* 无业务含义的尾随零,保证异步详情到达时不会造成数字闪变。非 Decimal 文本原样保留,
* 以免掩盖服务端数据异常。
*/
function displayDecimalQty(value: unknown): string {
const raw = String(value ?? '').trim();
if (!raw) return '—';
if (!/^[+-]?\d+(?:\.\d+)?$/.test(raw)) return raw;
const normalized = raw.replace(/(\.\d*?[1-9])0+$/, '$1').replace(/\.0+$/, '');
return normalized === '-0' ? '0' : normalized;
}
/**
* 是否为行 Schema 库存源线索字段(inventory_source_hint,按 field_code 或 fulfillment_role 判定)。
*/
function isInventorySourceHintField(field: {
field_code?: string;
fulfillment_role?: string;
}): boolean {
const code = String(field.field_code || '').trim();
const role = String(field.fulfillment_role || '').trim();
return code === 'inventory_source_hint' || role === 'inventory_source_hint';
}
/** 可见行字段中是否已有数量列(用于决定库存列插入点)。 */
const hasVisibleQtyField = computed(() => (
visibleLineSchemaFields.value.some((field) => isQtySchemaField(field))
));
/**
* 缺口展示:库存未就绪时不得显示数字(避免把「待确认」误当成短缺 30)。
*/
function displayShortageQty(line: ShippingOrderReviewLineFulfillmentLine | null): string {
if (!line) return '—';
if (
line.display_available === 'pending'
|| ['preparing', 'mapping_failed', 'source_conflict', 'unavailable', 'invalid_key'].includes(
String(line.inventory_status || ''),
)
|| ['inventory_pending', 'source_conflict', 'invalid', 'auto_fulfill_failed'].includes(
String(line.user_line_status || ''),
)
) {
return '—';
}
if (line.shortage_qty == null || line.shortage_qty === '') return '—';
return displayDecimalQty(line.shortage_qty);
}
/**
* 可用数量展示:pending → 待确认;短缺标红由模板 class 处理。
*/
function displayAvailableQty(line: ShippingOrderReviewLineFulfillmentLine | null): string {
if (!line) return '—';
if (line.display_available === 'pending' || line.available_qty == null || line.available_qty === '') {
return t('chat.shippingOrderReview.lineOps.availablePending');
}
return displayDecimalQty(line.available_qty);
}
/** Case 级库存兜底卡:统一由当前 Gate 卡提供精确动作。 */
async function retryCaseInventoryFallback() {
const code = String(currentTaskPrimaryAction.value?.code || '').trim();
if (code) await submitFormalGateAction(code);
}
/**
* 右侧主卡「定位明细」:滚动到订单行(0-based lineIndex)或字段冲突证据。
* 优先处理 draft_line_id(从草稿行身份解析行索引并滚动),无行号时回滚到字段冲突视图。
*/
function handleCurrentTaskLocate(
draftLineId: string | null | undefined,
fieldId: string | null | undefined,
) {
if (draftLineId) {
const draftLines = (activeCase.value?.draft?.lines || []) as Array<{
draft_line_id?: string | null;
line_index?: number | null;
}>;
const draftLine = draftLines.find(
(row) => String(row.draft_line_id || '') === String(draftLineId),
);
if (draftLine?.line_index != null) {
focusOrderLine(draftLine.line_index);
return;
}
const m = /line[-_:\s]*([0-9]+)$/i.exec(String(draftLineId));
if (m) {
focusOrderLine(Math.max(0, Number(m[1]) - 1));
return;
}
}
if (fieldId) {
const fieldCode = String(fieldId).split('.').pop() || String(fieldId);
focusFieldConflict({ fieldCode, lineIndex: null, draftLineId: null });
return;
}
}
/**
* 正式 OT 货代上传 RPA 恢复:提交 Gate 已授权的精确动作。
*/
async function retryFormalUploadRpa(taskNo: string) {
if (taskNo) await submitFormalGateAction('retry_freight_upload_rpa');
}
/**
* 处理 Gate 恢复已被后端受理后的页面同步。
*
* 核心逻辑:恢复 Job 尚未完成时立即恢复用户交互,并重启五阶段轮询;三个只读投影
* 在后台刷新,避免把网络读取时间误表现为“恢复按钮卡住”。库存短缺放行可额外建立
* 一次性自动推进许可,待后端生命周期投影确认后才更新深链。
*/
function handleGateRecoveryAccepted(options: { releaseAutoAdvance?: boolean } = {}) {
if (hasFormalOt.value) {
recoveryProjectionBaselineVersion.value = shippingProcessingProjection.value?.progressVersion ?? null;
recoveryProjectionPending.value = true;
}
const caseNo = String(activeCase.value?.case_no || '').trim();
if (options.releaseAutoAdvance && caseNo) {
// 放行前可能是用户手动进入通知准备;该历史意图不能阻止本次放行后的自动推进。
lifecycleStagePinnedByUserForCase.value = null;
pendingReleaseAutoAdvanceCaseNo.value = caseNo;
}
page.bumpWorkflowRefresh?.();
startWorkflowProgressPolling();
void Promise.allSettled([
loadFormalTaskDetail(),
reloadLatestDraft(),
refreshShippingProcessing(),
]).then(() => { void syncPendingReleaseAutoAdvance(); });
}
/**
* 执行正式任务的后端已授权动作。
*
* ``dispatch`` 和 ``ui_handler`` 均由 Gate 合同下发:前者决定这是变更、查看、
* 刷新还是页面宿主交互,后者只选择已挂载的 UI 能力。这里不依据 action code
* 决定按钮、权限或业务执行路径;未知分派一律拒绝,避免客户端语义漂移。
*/
async function executeFormalTaskAction(
action: ShippingUnifiedAction,
params: Record<string, unknown>,
): Promise<void> {
const dispatch = String(action.dispatch || 'mutation').trim();
const uiHandler = String(action.ui_handler || '').trim();
const taskNo = String(
(params.task_no as string | undefined)
|| confirmedNoticeTaskNo.value
|| authoritativeOrderTaskNo.value
|| '',
).trim();
if (dispatch === 'view') {
if (uiHandler === 'excel_download' && taskNo) {
await downloadWorkspaceShippingExcelFile(taskNo);
return;
}
msg.info(t('chat.shippingOrderReview.currentTask.actionUnknown', { code: action.code }));
return;
}
if (dispatch === 'refresh') {
await Promise.all([loadFormalTaskDetail(), refreshShippingProcessing()]);
return;
}
if (dispatch === 'dialog') {
if (uiHandler === 'manual_upload_confirmation') {
openManualUploadRegistration();
return;
}
msg.info(t('chat.shippingOrderReview.currentTask.actionUnknown', { code: action.code }));
return;
}
if (dispatch === 'navigation') {
const navigationHandlers: Record<string, () => Promise<void> | void> = {
order_review: () => {
workbenchMode.value = 'standard';
scrollWorkbenchAnchor('review-order-lines-table');
},
customer_resolution: async () => {
if (taskNo && typeof page.openShippingCustomerDialog === 'function') {
await page.openShippingCustomerDialog(taskNo);
return;
}
scrollWorkbenchAnchor('review-customer-resolution-panel');
},
inventory_match_review: () => scrollWorkbenchAnchor('review-order-lines-table'),
shortage_review: async () => {
workbenchMode.value = 'formal_task';
await nextTick();
scrollWorkbenchAnchor('review-fulfillment-prep-workspace');
},
inventory_upload: () => scrollWorkbenchAnchor('review-formal-task-todo-panel'),
order_fields: () => scrollWorkbenchAnchor('review-order-lines-table'),
reservation: () => scrollWorkbenchAnchor('review-order-lines-table'),
duplicate_review: () => scrollWorkbenchAnchor('review-duplicate-panel'),
field_conflicts: () => scrollWorkbenchAnchor('review-field-conflict-panel'),
profile_review: () => scrollWorkbenchAnchor('review-profile-match-panel'),
};
const handler = navigationHandlers[uiHandler];
if (handler) {
await handler();
return;
}
msg.info(t('chat.shippingOrderReview.currentTask.actionUnknown', { code: action.code }));
return;
}
if (dispatch !== 'mutation') {
msg.info(t('chat.shippingOrderReview.currentTask.actionUnknown', { code: action.code }));
return;
}
const formalGate = formalTaskDetail.value?.ui_state?.process_gate;
if (!formalGate) return;
const result = await submitProcessGatePrimaryAction(formalGate, { actionCode: action.code });
if (result.outcome === 'submitted' || result.outcome === 'refresh_needed') {
handleGateRecoveryAccepted();
}
}
/** 右侧当前任务按钮入口;授权动作仅来自正式任务 ``ui_state.actions``。 */
async function handleCurrentTaskAction(
code: string,
parameters?: Record<string, unknown> | null,
) {
const params = (parameters || {}) as Record<string, unknown>;
const normalizedCode = String(code || '').trim();
// [AUTHORITY] 正式 OT:右卡按钮只读 A(shippingProcessingProjection.ui_state),
// 点击必须与展示同源授权;capabilities 供 stageCapabilityBypass,B.actions
// 仅作兼容回退。禁止「A 已展示、B 无同码」时落到 actionUnknown。
if (hasFormalOt.value) {
if (!(await ensureFormalTaskDetailReady())) return;
// [STAGE_CAPABILITY] 命中能力(含 disabled)走 submitFormalGateAction,
// 由能力分支展示 disabled_reason 或 stageCapabilityBypass 提交。
const capability = formalPreparationContext.value?.capabilities?.find(
(cap) => String(cap.action_code || '').trim() === normalizedCode,
);
if (capability) {
await submitFormalGateAction(normalizedCode);
return;
}
// [§2.4 单源] A 已下发的主/侧路动作与展示同源,直接提交 Gate,不要求 B.actions。
const aPrimary = String(currentTaskUiState.value?.primary_action?.code || '').trim();
const aSecondaryHit = (currentTaskUiState.value?.secondary_actions || []).some(
(action) => action.enabled && String(action.code || '').trim() === normalizedCode,
);
if (normalizedCode && (normalizedCode === aPrimary || aSecondaryHit)) {
await submitFormalGateAction(normalizedCode);
return;
}
const formalAction = formalTaskActions.value.find((action) => (
action.enabled && String(action.code || '').trim() === normalizedCode
));
if (!formalAction) {
msg.info(t('chat.shippingOrderReview.currentTask.actionUnknown', { code: normalizedCode }));
return;
}
await executeFormalTaskAction(formalAction, params);
return;
}
const primary = currentTaskPrimaryAction.value;
const primaryMetadata = primary as {
i18nKey?: string | null;
label_key?: string | null;
targetLifecycleStage?: ActionPresentationItem['targetLifecycleStage'];
} | null;
const presentationItem: ActionPresentationItem = {
// 后端裁决 action_code;前端只适配为统一执行器输入,不自行生成业务动作。
intent: normalizedCode as ActionPresentationItem['intent'],
actionCode: normalizedCode,
labelKey: String(primaryMetadata?.i18nKey || primaryMetadata?.label_key || 'chat.shippingProcessing.action.none'),
targetLifecycleStage: primaryMetadata?.targetLifecycleStage ?? null,
};
// [AUTHORITY] 当前任务卡先消费后端 Gate 已授权动作;不按动作码、生命周期或
// 页面位置选择执行路径。Recovery composable 会再次按 allowed_actions /
// recovery_targets 和当前 Gate 版本校验,前端只传回原始 action_code。
const processGate = shippingProcessingProjection.value?.processGate;
const serverAuthorizedGateAction = processGate && (
(processGate.allowed_actions || []).some((action) => String(action) === normalizedCode)
|| (processGate.recovery_targets || []).some(
(target) => String(target.action_code || '') === normalizedCode,
)
);
if (serverAuthorizedGateAction) {
const result = await submitProcessGatePrimaryAction(processGate, { actionCode: normalizedCode });
if (result.outcome === 'submitted' || result.outcome === 'refresh_needed') {
handleGateRecoveryAccepted();
}
return;
}
if (resolveWorkbenchActionItem(presentationItem, { postCreate: hasCreatedShippingTask.value })) {
await onUnifiedProcessingAction(presentationItem);
return;
}
switch (normalizedCode) {
case 'download_excel': {
const taskNo = (params.task_no as string | undefined) || confirmedNoticeTaskNo.value;
if (!taskNo) {
msg.warning(t('chat.shippingOrderReview.workbench.resultNotReady'));
return;
}
await downloadWorkspaceShippingExcelFile(taskNo);
msg.success(t('chat.shippingOrderReview.workbench.actionSuccess'));
break;
}
case 'view_result':
case 'open_fulfillment':
case 'view_details':
workbenchMode.value = 'formal_task';
await nextTick();
scrollWorkbenchAnchor('review-formal-task-result-region');
break;
case 'open_inventory_match_review':
if (hasFormalOt.value) {
// 正式 OT 后匹配/缺口语境的真实宿主是通知准备工作区;订单明细表不承载库存结果。
scrollWorkbenchAnchor('review-fulfillment-prep-workspace');
} else {
workbenchMode.value = 'inventory';
scrollWorkbenchAnchor('review-inventory-issue-list');
}
break;
case 'open_shortage_review':
workbenchMode.value = 'formal_task';
await nextTick();
scrollWorkbenchAnchor('review-fulfillment-prep-workspace');
break;
case 'open_order_review':
workbenchMode.value = 'standard';
scrollWorkbenchAnchor('review-order-lines-table');
break;
case 'confirm_customer': {
const taskNo = (params.task_no as string | undefined)
|| confirmedNoticeTaskNo.value
|| authoritativeOrderTaskNo.value;
if (taskNo && typeof page.openShippingCustomerDialog === 'function') {
await page.openShippingCustomerDialog(taskNo);
}
break;
}
case 'retry_freight_upload_rpa': {
const taskNo = (params.task_no as string | undefined) || confirmedNoticeTaskNo.value;
if (taskNo) {
await retryFormalUploadRpa(taskNo);
}
break;
}
case 'retry_inventory_matching': {
const summary = displayCase.value?.process_gate;
if (!summary) return;
const result = await submitProcessGatePrimaryAction(summary, { actionCode: code });
if (result.outcome === 'submitted' || result.outcome === 'refresh_needed') {
handleGateRecoveryAccepted();
}
break;
}
default:
// 未被实时 Gate 授权的动作不可降级到旧 Case 快照执行,避免动作码前缀绕过
// 当前 Execution/Gate/version 校验。
msg.info(t('chat.shippingOrderReview.currentTask.actionUnknown', { code }));
}
}
/**
* 行是否允许删除(已入波次/已履约则禁用)。
*/
function canDeleteDraftLine(lineKey: string): boolean {
const lf = draftLineFulfillmentFor(lineKey);
if (!lf) return true;
const status = String(lf.line_status || lf.user_line_status || '');
return !['task_created', 'fulfilled', 'wave_created'].includes(status);
}
/** 关闭履约成功后刷新 Case。 */
const onCloseFulfillmentConfirmed = () => {
closeFulfillmentOpen.value = false;
closeFulfillmentLineKeys.value = [];
void reloadLatestDraft();
};
/**
* 复核门禁处置完成后同步 Case 与正式处理投影。
*
* 客户、字段冲突、重复订单和预约校验都会改写统一 Gate;右栏优先读取
* shippingProcessingProjection,故只刷新 Case 会留下过期的主操作。
*/
async function handleReviewGateDataRefreshed() {
await reloadLatestDraft();
await refreshShippingProcessing();
startStpAutoCreateTracking();
}
/** 关闭 AI 建议抽屉。 */
const closeLlmSuggestionDrawer = () => {
panelState.value = { ...panelState.value, llmSuggestionOpen: false };
};
/** 打开完整建单检查抽屉。 */
/**
* 打开完整建单检查抽屉:先写入访问审计,失败则告警并拒绝展示。
*/
const openEligibilityDetails = async () => {
const caseNo = String(activeCase.value?.case_no || '').trim();
if (!caseNo) return;
try {
await auditWorkspaceShippingOrderReviewEligibilityDetails(caseNo);
panelState.value = { ...panelState.value, eligibilityDetailsOpen: true };
} catch {
msg.warning(t('chat.shippingOrderReview.workbench.auditFailed'));
}
};
/** 关闭完整建单检查抽屉。 */
const closeEligibilityDetails = () => {
panelState.value = { ...panelState.value, eligibilityDetailsOpen: false };
};
/**
* 将视口滚动到订单明细指定行(0-based)。
*/
const focusOrderLine = (lineIndex: number) => {
void nextTick(() => {
const root = mainEditorScrollEl.value;
if (!root) return;
const target = root.querySelector(`[data-review-line-index="${lineIndex}"]`) as HTMLElement | null;
target?.scrollIntoView({ block: 'center', behavior: 'smooth' });
});
};
/**
* 从字段冲突面板定位到对应草稿字段与证据。
* 核心逻辑:field_code → schema.field_id,再复用 focusFieldEvidence。
*/
const focusFieldConflict = (payload: {
fieldCode: string;
lineIndex: number | null;
draftLineId: string | null;
}) => {
const code = String(payload.fieldCode || '').trim();
if (!code) return;
const field = (activeCase.value?.schema.fields || []).find(
(item) => String(item.field_code || '') === code,
);
const fieldId = String(field?.field_id || '').trim();
if (!fieldId) {
if (payload.lineIndex != null) focusOrderLine(payload.lineIndex);
return;
}
focusFieldEvidence(fieldId, payload.lineIndex ?? undefined);
if (payload.lineIndex != null) focusOrderLine(payload.lineIndex);
};
/**
* 当前证据抽屉字段展示名。
*/
const evidenceFieldLabel = computed(() => {
const fieldId = String(focusedEvidenceRef.value?.fieldId || focusedFieldId.value || '');
if (!fieldId) return '';
const field = (activeCase.value?.schema.fields || []).find((item) => item.field_id === fieldId);
return field?.display_name || fieldId;
});
/**
* 当前证据对应机器识别值。
*/
const evidenceMachineValue = computed(() => {
const fieldId = String(focusedEvidenceRef.value?.fieldId || focusedFieldId.value || '');
if (!fieldId || !activeCase.value?.draft) return '';
const lineIndex = focusedEvidenceRef.value?.lineIndex;
if (lineIndex != null) {
const line = activeCase.value.draft.lines?.[lineIndex] as Record<string, unknown> | undefined;
const machine = Array.isArray(line?.machine_fields) ? line.machine_fields as Array<Record<string, unknown>> : [];
return machineValueByIdFor(machine, fieldId);
}
const headerMachine = Array.isArray(activeCase.value.draft.header_values?.machine_fields)
? activeCase.value.draft.header_values.machine_fields as Array<Record<string, unknown>>
: [];
return machineValueByIdFor(headerMachine, fieldId);
});
/**
* 当前证据字段来源标签。
*/
const evidenceValueSourceLabel = computed(() => {
const fieldId = String(focusedEvidenceRef.value?.fieldId || focusedFieldId.value || '');
if (!fieldId || !activeCase.value?.draft) return '';
const lineIndex = focusedEvidenceRef.value?.lineIndex;
if (lineIndex != null) {
const line = activeCase.value.draft.lines?.[lineIndex] as Record<string, unknown> | undefined;
return valueSourceLabel(draftFieldMeta(line, fieldId).value_source);
}
return valueSourceLabel(
draftFieldMeta(activeCase.value.draft.header_values as Record<string, unknown>, fieldId).value_source,
);
});
/**
* 证据抽屉「恢复机器值」:按当前焦点字段写回。
*/
const restoreEvidenceMachineValue = () => {
const fieldId = String(focusedEvidenceRef.value?.fieldId || focusedFieldId.value || '');
if (!fieldId || !editable.value) return;
const lineIndex = focusedEvidenceRef.value?.lineIndex;
if (lineIndex != null) {
const lineKey = String(activeCase.value?.draft?.lines?.[lineIndex]?.draft_line_id || '');
if (!lineKey) return;
void reportSave(() => patchLine(lineKey, fieldId, null, true));
return;
}
void reportSave(() => patchHeader(fieldId, null, true));
};
const canEnterInventory = computed(() => {
// 正式 OT 后库存动作只在明细行 / Case 兜底卡,禁止切换完整库存工作台。
if (hasFormalOt.value) return false;
return (
(routingRecoveryLines.value?.length ?? 0) > 0
|| Boolean(activeCase.value?.line_fulfillment?.has_shortage)
|| Boolean(activeCase.value?.line_fulfillment?.has_open_lines)
|| Number(activeCase.value?.line_fulfillment?.open_count || 0) > 0
);
});
const availableActions = computed(() => activeCase.value?.available_actions || []);
/** 订单处理工作台写权限(历史查看、通知完成回看或 Case 切换中均为 false)。 */
const workbenchActionsExecutable = computed(() => (
!isReviewContentReadOnly.value
&& !runLoading.value
&& !caseSwitchLoading.value
&& !progressRetrying.value
));
/** 当前 Case 面板可用性,供注册表 requiresPanel 守卫。 */
const workbenchPanelAvailability = computed((): WorkbenchPanelAvailability => {
const c = activeCase.value;
return {
customerUnresolved: Boolean(c && !c.customer_resolution?.resolved),
hasFieldConflicts: Boolean((c?.field_conflicts || []).length),
hasDuplicateAdjudication: Boolean(c?.duplicate?.needs_adjudication),
hasProfileMatch: Boolean(c?.profile_match?.available),
hasInventoryCandidates: Boolean((routingRecoveryLines.value || []).length),
hasInventoryIssues: Boolean(
(routingRecoveryLines.value || []).length
|| c?.line_fulfillment?.has_shortage,
),
};
});
/** 底栏流程写操作:与原进度条 ActionBar 同源,surface=review。 */
const flowProjectionRef = computed(() => shippingProcessingProjection.value);
const flowPresentationOptions = computed(() => ({
surface: 'review' as const,
actionsExecutable: workbenchActionsExecutable.value,
panels: workbenchPanelAvailability.value,
}));
const flowPresentation = useProcessingActionPresentation(flowProjectionRef, flowPresentationOptions);
const flowActionBusy = ref(false);
const viewResultLoading = ref(false);
const customerResolutionWideRef = ref<{ openSelectDialog: () => Promise<void> } | null>(null);
const fieldConflictPanelRef = ref<{ focusFirstConflict: () => void } | null>(null);
const duplicatePanelRef = ref<{ focusAdjudication: () => void } | null>(null);
/** 系统自动推进中:STP 等待入队/排队/执行时隐藏主写按钮。 */
const isProcessingAutomating = computed(() => {
// STP 建单前没有正式 OT 投影;等待入队与已入队/运行均由 Case automation 作为唯一运行事实。
const stpStatus = String(activeCase.value?.automation?.status || '').trim().toLowerCase();
if (!hasFormalOt.value && ['waiting_to_start', 'queued', 'running'].includes(stpStatus)) return true;
if (!hasConfirmedAutomationJob.value) return false;
const status = String(
shippingProcessingProjection.value?.uiState?.status
|| shippingProcessingProjection.value?.status
|| '',
).trim().toLowerCase();
const projection = shippingProcessingProjection.value;
const hasPrimaryAction = Boolean(projection?.uiState?.primary_action);
return ['processing', 'automating', 'queued'].includes(status) && !hasPrimaryAction;
});
/** OT 导航仅在桌面侧栏模式(≥5)时与主区并排;hidden/tabs/narrow 不预留左列。 */
const reviewDocumentNavigationUsesSidebar = computed(() => (
reviewDocumentNavigationMode.value === 'sidebar'
|| reviewDocumentNavigationMode.value === 'sidebar_search'
));
const reviewDocumentNavigationCollapsed = ref(false);
/**
* 导航项:一 PDF 一 Case;PO/生命周期均由队列后端下发,当前 Case 仅补充客户显示名。
*/
const documentNavItems = computed(() => {
const items = reviewQueue.value?.items || reviewRun.value?.items || [];
const header = activeCase.value?.draft?.header_values as Record<string, unknown> | undefined;
const activeNo = activeCase.value?.case_no;
return items.map((item) => {
const isActive = item.case_no === activeNo;
return {
...item,
customer_name: isActive ? (String(header?.customer_name || '').trim() || null) : null,
};
});
});
/**
* 当前文件对应的导航项(选法 2):正式任务身份来源,供正式任务下游阶段在
* activeCase 为空时推导 confirmed_task_no / has_formal_ot。
*/
const activeReviewNavItem = computed(() => {
const activeNo = String(
displayCase.value?.case_no
|| route.query.case
|| route.query.case_no
|| '',
).trim();
return documentNavItems.value.find((item) => String(item.case_no || '').trim() === activeNo) || null;
});
/** 流程详情标题用 PO。 */
const processDetailPoNumber = computed(() => {
const header = activeCase.value?.draft?.header_values as Record<string, unknown> | undefined;
return String(header?.po_number || shippingProcessingProjection.value?.sourceSummary?.poNumber || '').trim() || null;
});
/**
* 工作台标题下的当前订单摘要。fileName/caseNo/version 三腿零 Case:文件名按 route
* case_no 匹配队列/Run items 下发的 file_name,caseNo 取 route query,版本取进度标签;
* poNumber 腿暂仍 Case 头优先、shippingProcessingProjection.sourceSummary 兜底
* (processDetailPoNumber 既有实现,本计划未改)——属已知暂留,随后续「波次写路径
* 改源到任务级」计划(E)一并收敛。
*/
const selectedOrderSummary = computed(() => {
const activeNo = String(
route.query.case || route.query.case_no
|| '',
).trim();
const item = reviewQueue.value?.items?.find((candidate) => candidate.case_no === activeNo)
|| reviewRun.value?.items?.find((candidate) => candidate.case_no === activeNo)
|| null;
return {
fileName: String(item?.file_name || '').trim() || t('chat.shippingOrderReview.unnamedDocument'),
poNumber: processDetailPoNumber.value,
caseNo: activeNo || null,
version: reviewProgressVersionLabel.value || null,
};
});
const selectedOrderSummaryText = computed(() => [
selectedOrderSummary.value.fileName,
selectedOrderSummary.value.poNumber,
selectedOrderSummary.value.caseNo,
selectedOrderSummary.value.version,
].filter(Boolean).join(' · '));
const isConfirmProgressPrimary = computed(
() => workbenchMode.value === 'confirm_progress' && (Boolean(confirmSuccess.value) || showWorkflowProgress.value),
);
const showWorkbenchGrid = computed(
// 重识别:保留原订单上下文。确认后 formal_task 仍展示字段区;仅旧 confirm_progress 隐藏网格。
() => workbenchMode.value === 'formal_task' || !isConfirmProgressPrimary.value,
);
const lifecycleProgressForView = computed(() => (
extractionLifecycleProgress.value
|| reviewRun.value?.lifecycle_progress
|| null
));
const lifecycleProgressStageItems = computed<ReviewLifecycleStageItem[]>(() => {
const progress = lifecycleProgressForView.value;
if (!progress) return [];
const current = progress.lifecycle_stage;
const order: ReviewLifecycleStageCode[] = ['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'];
const currentIndex = order.indexOf(current as ReviewLifecycleStageCode);
return order.map((code, index) => ({
code,
label: t(`chat.shippingOrderReview.lifecycle.stages.${code}`),
state: code === current
? 'current'
: index < currentIndex
? 'completed'
: 'blocked',
reason: index > currentIndex ? t('chat.shippingOrderReview.lifecycle.prerequisite') : null,
}));
});
/**
* 五阶段导航始终优先使用后端 Case/任务授权;Case 尚未生成时才以 Run 的 lifecycle_progress
* 作为同一位置的只读回退,禁止为重解析另起一条进度轨。
*/
const lifecycleNavigationItems = computed<ReviewLifecycleStageItem[]>(() => (
lifecycleStageItems.value.length ? lifecycleStageItems.value : lifecycleProgressStageItems.value
));
const lifecycleNavigationActiveCode = computed<ReviewLifecycleStageCode | null>(() => (
lifecycleActiveStageCode.value || lifecycleProgressActiveCode.value
));
/**
* v2(spec §5.3):无 Case 瞬态的单行轻提示(原横幅收窄遗留)。
* 核心逻辑:有 Case 或有正式 OT 一律不渲染;lifecycle_status 白名单
* {running, waiting, failed, cancelled} 才取文本,completed/未知不渲染、
* 不得回退成“等待启动”;文本一律来自共享解析器(failed/cancelled 强制原因 key)。
*/
const runProgressHintText = computed<string | null>(() => {
if (displayCase.value || hasFormalOt.value) return null;
const progress = lifecycleProgressForView.value;
if (!progress) return null;
const status = String(progress.lifecycle_status || '').trim().toLowerCase();
if (!['running', 'waiting', 'failed', 'cancelled'].includes(status)) return null;
return resolveExtractionActivityMessage(progress, { t, te })?.text ?? null;
});
const lifecycleProgressActiveCode = computed<ReviewLifecycleStageCode | null>(() => {
const code = lifecycleProgressForView.value?.lifecycle_stage;
return LIFECYCLE_STAGE_CODES.includes(code as ReviewLifecycleStageCode)
? code as ReviewLifecycleStageCode
: null;
});
const headerSchemaFields = computed(() => (displayCase.value?.schema.fields || []).filter((field) => field.scope === 'header'));
const lineSchemaFields = computed(() => (displayCase.value?.schema.fields || []).filter((field) => field.scope === 'line'));
/**
* 订单复核明细的个人列宽偏好。字段列只存用户实际拖动过的值,Schema 变更后新列仍走默认宽度。
* 依赖:共享布局偏好存储;业务字段顺序始终由 Schema field_code 决定,不能由本地偏好改写。
*/
const LINE_TABLE_LAYOUT_KEY = 'shipping_order_review_lines';
const DEFAULT_LINE_COLUMN_WIDTH = 140;
const MIN_LINE_COLUMN_WIDTH = 88;
const MAX_LINE_COLUMN_WIDTH = 360;
const savedLineTableLayout = loadReportLayoutPref<{ widths?: Record<string, number> }>(LINE_TABLE_LAYOUT_KEY);
const lineColumnWidths = ref<Record<string, number>>(
savedLineTableLayout?.widths && typeof savedLineTableLayout.widths === 'object'
? savedLineTableLayout.widths
: {},
);
function defaultLineColumnWidth(field: { field_code?: string }): number {
switch (String(field.field_code || '').trim()) {
case 'customer_po_line_no': return 120;
case 'part_number':
case 'customer_part_number': return 160;
case 'qty':
case 'quantity': return 96;
default: return DEFAULT_LINE_COLUMN_WIDTH;
}
}
function lineColumnWidth(field: { field_id: string; field_code?: string }): number {
const saved = Number(lineColumnWidths.value[field.field_id]);
return Number.isFinite(saved)
? Math.min(MAX_LINE_COLUMN_WIDTH, Math.max(MIN_LINE_COLUMN_WIDTH, saved))
: defaultLineColumnWidth(field);
}
function lineColumnStyle(field: { field_id: string; field_code?: string }): Record<string, string> {
return { width: `${lineColumnWidth(field)}px` };
}
/** 拖动表头右缘调整单个字段列;宽度按用户与页面隔离持久化。 */
function beginLineColumnResize(field: { field_id: string; field_code?: string }, event: MouseEvent): void {
const initialX = event.clientX;
const initialWidth = lineColumnWidth(field);
const onMove = (moveEvent: MouseEvent) => {
const width = Math.min(MAX_LINE_COLUMN_WIDTH, Math.max(
MIN_LINE_COLUMN_WIDTH,
initialWidth + moveEvent.clientX - initialX,
));
lineColumnWidths.value = { ...lineColumnWidths.value, [field.field_id]: width };
};
const onUp = () => {
saveReportLayoutPref(LINE_TABLE_LAYOUT_KEY, { widths: lineColumnWidths.value });
window.removeEventListener('mousemove', onMove);
window.removeEventListener('mouseup', onUp);
};
window.addEventListener('mousemove', onMove);
window.addEventListener('mouseup', onUp);
}
/** 双击列分隔线只恢复当前列,避免误伤用户对其他业务字段的阅读偏好。 */
function resetLineColumnWidth(field: { field_id: string }): void {
const widths = { ...lineColumnWidths.value };
delete widths[field.field_id];
lineColumnWidths.value = widths;
saveReportLayoutPref(LINE_TABLE_LAYOUT_KEY, { widths });
}
/** Gate 卡片正在表达当前业务阻断时,资格卡只保留建单结论,避免重复叙事。 */
const hasActiveBusinessGate = computed(() => showHumanBlockingGate.value);
/** 正式 OT 已创建(以后端 has_formal_ot 为准;confirmed_task_id 仅作短期展示兜底)。 */
const hasFormalOt = computed(() => Boolean(
activeReviewNavItem.value?.has_formal_ot
|| displayCase.value?.has_formal_ot
|| (
displayCase.value?.confirmed_task_id
&& String(displayCase.value?.confirmed_task_no || '').trim()
&& !displayCase.value?.task_missing
),
));
/** 只有 ShippingTask 已实际创建后,才进入库存履约与自动推进展示阶段。 */
const hasCreatedShippingTask = computed(() => Boolean(
hasFormalOt.value
|| displayCase.value?.confirmed_task_id
|| String(displayCase.value?.confirmed_task_no || '').trim()
|| String(reviewProgressContext.value?.current_task_no || '').trim(),
));
/**
* 正式 Notice 编号(SN),供履约写 API / TaskTodoPanel。
* 核心逻辑:必须锚定**当前查看订单**的确认任务号(displayCase/activeCase 同源),
* 禁止回退到会话层 reviewProgressContext.current_task_no。
* 后者是会话“当前正在处理的任务”,在多订单批次里可能指向**另一个订单**(兄弟单),
* 会在 activeCase 短暂为空(加载/切换)时把任务详情拉成串单(如本订单却展示 F5CDD796),
* 造成“重复投影两次 / 不可编辑→可编辑”闪烁(实证见 trace #13-15)。此回退即为根因。
*/
const confirmedNoticeTaskNo = computed(() => String(
activeReviewNavItem.value?.confirmed_task_no
|| displayCase.value?.confirmed_task_no
|| '',
).trim());
/**
* 深链显式携带的 OT 号(任务中心抽屉等 OT 直链)。
* 仅认 OT- 前缀;Notice 的 SN 号不是 work-item 键,与 externalOrderTaskNo 同一口径。
*/
const deepLinkOrderTaskNo = computed(() => {
const taskNo = String(route.query.task_no || '').trim();
return taskNo.startsWith('OT-') ? taskNo : '';
});
const freightNoticeGroups = ref<ShippingFreightNoticeGroup[]>([]);
const freightNoticeGroupsLoading = ref(false);
const freightNoticeGroupsReason = ref<string | null>(null);
const freightNoticeGroupsLoadFailed = ref(false);
/** 货代上传分组请求在途守卫:独立于 loading,避免轮询 tick 与动作后刷新并发重载。 */
const freightGroupsInFlight = ref(false);
const selectedFreightBusinessNos = ref<string[]>([]);
const freightBatchBusy = ref<'download' | 'confirm' | 'rpa' | 'regenerate' | null>(null);
/**
* 判断货代通知聚合行是否已具备上传成功事实。
* 核心逻辑:聚合接口 upload_status 已经过后端 project_notice_upload_status 归一,
* 成功终态只认 uploaded;禁止再扩 succeeded/success 同义词兜底。
* @param group - 当前发货通知单聚合行。
* @returns 是否已上传成功。
*/
function isFreightNoticeUploaded(group: ShippingFreightNoticeGroup): boolean {
return String(group.upload_status || '').trim().toLowerCase() === 'uploaded';
}
/**
* 通知完成面的只读聚合:同 PO 中已有上传成功证据的发货通知。
* 核心逻辑:与货代上传面消费同一份 freightNoticeGroups,仅按终态过滤;未上传的
* 通知仍留在货代上传面处理,完成面不出现混淆态。
*/
const uploadedFreightNoticeGroups = computed(() =>
freightNoticeGroups.value.filter((item) => isFreightNoticeUploaded(item)),
);
/** 批次留底下载:把已完成通知全部打包为 ZIP(复用后端 /shipping-notices/batch/export)。 */
const uploadingBatchArchive = ref(false);
async function downloadCompletedBatchArchive() {
const businessNos = uploadedFreightNoticeGroups.value
.map((item) => String(item.business_no || '').trim())
.filter(Boolean);
if (!businessNos.length || uploadingBatchArchive.value) return;
uploadingBatchArchive.value = true;
try {
await downloadWorkspaceShippingNoticeExportArchive(businessNos);
} catch (error) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
} finally {
uploadingBatchArchive.value = false;
}
}
/** 通知完成面的展开明细:同一时刻只展开一张通知(与货代上传面交互一致)。 */
const expandedCompletedNoticeNo = ref<string | null>(null);
function toggleCompletedNoticeLine(businessNo: string) {
expandedCompletedNoticeNo.value = expandedCompletedNoticeNo.value === businessNo ? null : businessNo;
}
const formalTaskDetailLoading = ref(false);
const formalTaskDetailLoadFailed = ref(false);
/**
* 通知准备详情是否仍在等待正式任务 ui_state(含可编辑矩阵)。
* 核心逻辑:preparation 的属性(source_options / edit_window)只在正式任务详情就绪后才有。
* 历史方案([B1])曾在详情未到时用 displayCase 兜底渲染,得到一份“只读假象”的局部表单
* (库存源变只读 span),让用户误以为不可编辑——该兜底已于 2026-09-01 随单源化删除;
* 现详情未到即渲染加载态,Prep 面只认正式任务 ui_state,不再有误导性的只读兜底表单。
*/
const formalTaskDetailPending = computed(() => Boolean(
hasCreatedShippingTask.value
&& isLifecycleFulfillmentPrep.value
&& !formalTaskDetail.value
&& !formalTaskDetailLoadFailed.value,
));
/**
* 正式任务详情只属于当前 PDF/Case。切换文件或任务后递增代际,拒绝旧异步响应覆盖
* lifecycle_entries;否则 B 文件会短暂显示 A 文件的阶段与入口。
*/
let formalTaskDetailGeneration = 0;
const manualUploadRegistrationOpen = ref(false);
/** 深链预取:批次进度中心已带 task_no 时,挂载即并行发起任务详情读取,与 load() 重叠。
* [PERF] 订单生命周期工作台首屏的关键路径是 load() 完成后才轮到 loadFormalTaskDetail
* (getWorkspaceShippingTask)。提前发起让这两个重型请求并行,消除串行叠加;
* 结果仅在被 loadFormalTaskDetail 认领且任务号一致时使用,避免双源身份。 */
const deepLinkTaskPrefetch = ref<{ taskNo: string; promise: Promise<ShippingTaskDetail | null> } | null>(null);
function prefetchDeepLinkedTaskDetail() {
const taskNo = String(route.query.task_no || route.query.task_id || '').trim();
if (!taskNo) return;
const promise = getWorkspaceShippingTask(taskNo, { view: 'workbench' })
.then((detail) => detail)
.catch(() => null);
deepLinkTaskPrefetch.value = { taskNo, promise };
}
/** 通知准备面是否就绪:正式任务 ui_state 单源完整(含矩阵内容 + editable)。 */
const preparationSurfaceReady = computed(() => Boolean(
formalTaskDetail.value
&& formalTaskDetail.value.ui_state?.stage_context?.preparation,
));
/** 通知准备面可编辑/可波次出单:权威 = 正式任务 ui_state.stage_context.preparation.editable。 */
const preparationEditable = computed(() =>
Boolean(formalTaskDetail.value?.ui_state?.stage_context?.preparation?.editable),
);
/**
* 通知准备只认正式任务 ui_state 单源(formalTaskDetail.ui_state.stage_context.preparation);
* 不再回退 displayCase.line_fulfillment——Case 投影只有只读行矩阵,既让用户误以为不可编辑,
* 又与 ui_state 就绪后的可编辑矩阵形成两次投影闪烁。
*/
const formalPreparationContext = computed(() => {
const preparation = formalTaskDetail.value?.ui_state?.stage_context?.preparation;
if (!preparation) return null;
return { ...preparation, capabilities: preparation.capabilities ?? [] };
});
/** 通知准备的唯一行级工作表;短缺优先呈现。 */
const formalPreparationLines = computed(() => {
const rows = formalPreparationContext.value?.lines || [];
return rows.map((line) => ({
...line,
required_qty: displayDecimalQty(line.required_qty),
available_qty: displayDecimalQty(line.available_qty),
shortage_qty: displayDecimalQty(line.shortage_qty),
})) as Array<typeof rows[number] & { snapshot_line_id?: number | null; required_qty: string; available_qty: string; shortage_qty: string }>;
});
/** 通知准备固定展示冻结订单明细;库存匹配结果只作为附加事实合并。 */
const formalPreparationDisplayLines = computed(() => {
const preparation = formalPreparationContext.value;
if (!preparation) return [];
const frozen = Array.isArray(preparation.frozen_order_lines) ? preparation.frozen_order_lines : [];
const matched = formalPreparationLines.value;
const matchedByKey = new Map(matched.map((line) => [String(line.snapshot_line_id ?? ''), line]));
return frozen.map((line, index) => ({
...line,
...(matchedByKey.get(String(line.snapshot_line_id ?? '')) || matched[index] || {}),
}));
});
/** 阶段详情只承载库存结果;按 snapshot_line_id 合并,禁止用任务级 inventory_sources 回填到订单行。
*/
function formalPreparationLineFulfillment(line: { snapshot_line_id?: number | null }): ShippingOrderReviewLineFulfillmentLine | null {
return preparationLineFulfillmentFor(line.snapshot_line_id);
}
/**
* 行「库存源」只读展示文案:Match 正式源优先,其次 CandidateSet 取数目标。
* 核心逻辑:不把任务级 inventory_sources 回填到行;无正式/选中源时显示 —。
*/
function formalPreparationLineSource(line: {
snapshot_line_id?: number | null;
source_code?: string | null;
selected_source_code?: string | null;
}): string {
const fulfillment = formalPreparationLineFulfillment(line);
const source = fulfillment?.inventory_source;
const label = String(source?.label || '').trim();
// 展示优先级:Match 正式源 → CandidateSet 取数目标 → fulfillment 兼容字段。
const code = String(
source?.code
|| line.source_code
|| line.selected_source_code
|| fulfillment?.inventory_source_code
|| '',
).trim();
if (label && code) return `${label}(${code})`;
return label || code || '—';
}
/** 锁定边界 = Excel 生成(D7):后端 preparation.source_locked 下发,生成后行源只读。 */
const formalPreparationSourceLocked = computed(() => Boolean(formalPreparationContext.value?.source_locked));
/** 库存源选择不再有独立确认流:行进入就地编辑态后在下拉中改选,随行级「保存」统一提交
* (override_line_inventory_source Gate 动作,见 saveInlineEdit);展示态回退为文本。 */
/** 选源下拉项文案:源编码始终可见(等宽语义由样式层保证)。 */
function lineSourceOptionLabel(code: string): string {
// 兜底:只会展示源编码(如 DSV360_AWSSG),不展示冗长显示名。
return String(code || '').trim().toUpperCase();
}
/** 人工覆写库存源(方案 3·放开):后端下发全部已启用源 source_options,供行级下拉人工指定。 */
const formSourceOptions = computed(() => formalPreparationContext.value?.source_options || []);
function overrideSourceOptionLabel(code: string): string {
// 兜底:下拉只展示源编码(如 DSV360_AWSSG),不展示冗长 display_name,便于快速识别。
return String(code || '').trim().toUpperCase();
}
/** 整单 ODM 裁决列可见性:任一行候选多于一个时展示(候选已经客户范围过滤)。 */
const formalPreparationOdmColumnVisible = computed(() =>
(formalPreparationContext.value?.lines || []).some((line) => (line.odm_values?.length || 0) > 1),
);
const lineOdmSelections = ref<Record<string, string>>({});
const lineOdmBusy = ref(false);
/**
* 提交行级 ODM 选择:后端把同一快照文件的全部当前匹配行同步为同一值,
* 刷新详情后其他行回显同步结果,并在门禁仍授权时自动重试生成 Excel。
*/
async function submitLineOdmChoice(line: { snapshot_line_id?: number | null }) {
const selectionKey = String(line.snapshot_line_id ?? '');
const odmId = String(lineOdmSelections.value[selectionKey] || '').trim();
const taskNo = String(confirmedNoticeTaskNo.value || '').trim();
if (!odmId || !taskNo || lineOdmBusy.value) return;
lineOdmBusy.value = true;
try {
await setWorkspaceShippingTaskOdmChoice(taskNo, { snapshot_line_id: selectionKey, odm_id: odmId });
delete lineOdmSelections.value[selectionKey];
await loadFormalTaskDetail();
const canRegenerate = formalTaskActions.value.some(
(action) => action.enabled && String(action.code || '').trim() === 'regenerate_excel_artifact',
);
if (canRegenerate) await submitFormalGateAction('regenerate_excel_artifact');
} catch (error) {
msg.error(resolveReviewErrorMessage(error));
} finally {
lineOdmBusy.value = false;
}
}
function formalPreparationLineAllows(
line: { snapshot_line_id?: number | null },
action: 'retry_inventory_preparation' | 'retry_inventory_matching' | 'close_unfulfillable' | 'release_inventory_shortage',
): boolean {
const fulfillment = formalPreparationLineFulfillment(line);
if (action === 'close_unfulfillable' || action === 'release_inventory_shortage') {
return Boolean(
fulfillment?.line_allowed_actions?.includes(action)
&& (action !== 'release_inventory_shortage' || !fulfillment?.release_field_resolution_error),
);
}
return Boolean(fulfillment?.inventory_allowed_actions?.includes(action));
}
/**
* 通知准备行匹配状态文案:后端 status 现为 user_line_status(如 inventory_matched),
* 优先履约用户态文案,再回退 prepare.matchStatus;禁止把原始码直接展示给用户。
*/
function formalPreparationLineStatusLabel(line: { snapshot_line_id?: number | null; status?: string | null; shortage_qty?: string | number | null }): string {
const fulfillment = formalPreparationLineFulfillment(line);
if (fulfillment?.decision?.decision_code === 'release_inventory_shortage') {
return t('chat.shippingOrderReview.lifecycle.prepare.releaseShortage');
}
const status = String(line.status || '').trim().toLowerCase();
if ((status === 'matched' || status === 'inventory_matched') && Number(line.shortage_qty || 0) <= 0) {
return t('chat.shippingOrderReview.lifecycle.prepare.matched');
}
if (status === 'shortage' || Number(line.shortage_qty || 0) > 0) {
return t('chat.shippingOrderReview.lifecycle.prepare.shortage');
}
const userKey = `chat.shippingOrderReview.fulfillmentDecision.userLineStatus.${status}`;
if (status && te(userKey)) return t(userKey);
const key = `chat.shippingOrderReview.lifecycle.prepare.matchStatus.${status || 'unknown'}`;
return te(key) ? t(key) : status || '—';
}
/**
* 通知准备区右上角阶段徽标:后端下发 ready/processing/blocked,必须走 i18n。
*/
function formalPreparationStatusLabel(status?: string | null): string {
const code = String(status || '').trim().toLowerCase();
if (!code) return '';
const key = `chat.shippingOrderReview.lifecycle.prepare.status.${code}`;
return te(key) ? t(key) : code;
}
const releaseInventoryLine = ref<ShippingOrderReviewLineFulfillmentLine | null>(null);
const releaseInventoryReason = ref('');
const releaseInventoryFieldValues = ref<Record<string, string>>({});
const releaseInventoryBusy = ref(false);
function openReleaseInventoryShortage(line: { snapshot_line_id?: number | null }) {
const fulfillment = formalPreparationLineFulfillment(line);
if (!fulfillment) return;
releaseInventoryLine.value = fulfillment;
releaseInventoryReason.value = '';
releaseInventoryFieldValues.value = {};
}
async function confirmReleaseInventoryShortage() {
const line = releaseInventoryLine.value;
const caseNo = activeCase.value?.case_no;
const reason = releaseInventoryReason.value.trim();
const requiredFields = line?.release_required_fields || [];
if (!line || !caseNo || requiredFields.some((field) => !releaseInventoryFieldValues.value[field.field_id]?.trim()) || releaseInventoryBusy.value) return;
releaseInventoryBusy.value = true;
try {
await decideWorkspaceShippingOrderReviewLineFulfillment(caseNo, {
draft_line_id: String(line.draft_line_id || ''),
decision_code: 'release_inventory_shortage',
reason,
release_field_values: releaseInventoryFieldValues.value,
expected_draft_version: activeCase.value?.draft?.draft_version,
});
releaseInventoryLine.value = null;
// 放行写入成功即结束用户交互;Notice/Excel 由后端 Job 异步创建,不能让只读刷新
// 持续占用确认按钮。重启工作台轮询以立即接住新 Notice 的处理投影。
releaseInventoryBusy.value = false;
handleGateRecoveryAccepted({ releaseAutoAdvance: true });
} catch (error) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
} finally {
releaseInventoryBusy.value = false;
}
}
function formalPreparationLineInventoryFileNo(line: { snapshot_line_id?: number | null; inventory_file_no?: string | null }): string {
const fulfillment = formalPreparationLineFulfillment(line);
return String(line.inventory_file_no || fulfillment?.inventory_file_no || '').trim();
}
/** 行内放行补录条(常显子行):短缺行携带必填放行字段时直接在行下补填,替代弹窗。 */
const releaseBarValues = ref<Record<string, Record<string, string>>>({});
const releaseBarBusy = ref<Record<string, boolean>>({});
function releaseBarKey(line: { snapshot_line_id?: number | null }): string {
return String(line.snapshot_line_id ?? '');
}
/** 放行必填字段:仅短缺行且投影声明了必填补录项(有候选缺失才需要补录)。 */
function releaseBarLineRequiredFields(line: { snapshot_line_id?: number | null }) {
const fulfillment = formalPreparationLineFulfillment(line);
return fulfillment?.release_required_fields || [];
}
/** 缺字段型短缺行:放行走行内补录(而非仅原因的旧弹窗路径)。 */
function releaseBarHasFields(line: {
snapshot_line_id?: number | null;
shortage_qty?: string | number | null;
}): boolean {
return Number(line.shortage_qty || 0) > 0 && releaseBarLineRequiredFields(line).length > 0;
}
/** 补录条展开态:默认收起(表格保持干净),由 ⋯ 菜单「放行缺口」或缺 N 项徽标点击展开。 */
const releaseBarExpandedFor = ref<string | null>(null);
function expandReleaseBar(line: { snapshot_line_id?: number | null }) {
if (inlineEditBusy.value) {
msg.warning(t('chat.shippingOrderReview.inlineEdit.busy'));
return;
}
releaseBarExpandedFor.value = releaseBarKey(line);
}
function releaseBarValue(
line: { snapshot_line_id?: number | null },
field: { field_id?: string | null },
): string {
return releaseBarValues.value[releaseBarKey(line)]?.[String(field.field_id)] ?? '';
}
function updateReleaseBarValue(
line: { snapshot_line_id?: number | null },
field: { field_id?: string | null },
value: string,
) {
const key = releaseBarKey(line);
releaseBarValues.value = {
...releaseBarValues.value,
[key]: { ...(releaseBarValues.value[key] || {}), [String(field.field_id)]: value },
};
}
/** 放行按钮可用性:后端授权 + 必填补录项全部已填 + 非保存中。 */
function releaseBarReadyFor(line: { snapshot_line_id?: number | null }): boolean {
const fulfillment = formalPreparationLineFulfillment(line);
const required = releaseBarLineRequiredFields(line);
return Boolean(
fulfillment?.line_allowed_actions?.includes('release_inventory_shortage')
&& required.every((field) => releaseBarValue(line, field).trim())
&& !releaseBarBusy.value[releaseBarKey(line)],
);
}
/** 行内放行提交:走既有 decide 通道;原因可选(人工放行事实由审计链记录)。 */
async function confirmReleaseBar(line: { snapshot_line_id?: number | null }) {
const caseNo = activeCase.value?.case_no;
const fulfillment = formalPreparationLineFulfillment(line);
const key = releaseBarKey(line);
const required = releaseBarLineRequiredFields(line);
if (
!caseNo || !fulfillment?.draft_line_id
|| !required.every((field) => releaseBarValue(line, field).trim())
|| releaseBarBusy.value[key]
) return;
releaseBarBusy.value = { ...releaseBarBusy.value, [key]: true };
try {
await decideWorkspaceShippingOrderReviewLineFulfillment(caseNo, {
draft_line_id: String(fulfillment.draft_line_id || ''),
decision_code: 'release_inventory_shortage',
reason: '',
release_field_values: { ...(releaseBarValues.value[key] || {}) },
expected_draft_version: activeCase.value?.draft?.draft_version,
});
const next = { ...releaseBarValues.value };
delete next[key];
releaseBarValues.value = next;
// 放行写入成功即结束用户交互;Notice/Excel 由后端 Job 异步创建(与原弹窗通道一致)。
handleGateRecoveryAccepted({ releaseAutoAdvance: true });
} catch (error) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
} finally {
releaseBarBusy.value = { ...releaseBarBusy.value, [key]: false };
}
}
/** 行结案弹窗状态;与放行缺口弹窗同款交互(原因必填),走 line-fulfillment decide 通道。 */
const closeLineDialogLine = ref<ShippingOrderReviewLineFulfillmentLine | null>(null);
const closeLineReason = ref('');
const closeLineBusy = ref(false);
/**
* 结案按钮可见性:仅「无货可发」的未终态 prep 行开放。
* 核心逻辑:line_allowed_actions 由后端投影下发(终态行返回空数组,天然排除已结案/
* 已放行/已入波次行),前端再叠加短缺信号(is_shortage / 缺量>0 / not_found)过滤;
* 后端 decide API 才是权威闸门,这里只做入口收敛。
*/
function formalPreparationLineCloseVisible(line: { snapshot_line_id?: number | null; shortage_qty?: string | number | null }): boolean {
if (!formalPreparationLineAllows(line, 'close_unfulfillable')) return false;
const fulfillment = formalPreparationLineFulfillment(line);
if (fulfillment?.decision?.decision_code === 'close_unfulfillable') return false;
const notFound = String(fulfillment?.match_result || '').trim().toLowerCase() === 'not_found';
const shortageQty = Number(line.shortage_qty ?? fulfillment?.shortage_qty ?? 0) > 0;
return Boolean(fulfillment?.is_shortage) || shortageQty || notFound;
}
/**
* 打开行结案弹窗:按快照行身份定位履约投影行(携带 draft_line_id)。
* 核心逻辑:与行内编辑互斥——弹窗打开即取消该行编辑态,避免两套写路径叠加。
*/
function openCloseLineDialog(line: { snapshot_line_id?: number | null }) {
const fulfillment = formalPreparationLineFulfillment(line);
if (!fulfillment) return;
cancelInlineEdit();
closeLineDialogLine.value = fulfillment;
closeLineReason.value = '';
}
/**
* 提交行结案决定(decision_code='close_unfulfillable',原因必填)。
* 核心逻辑:复用既有 line-fulfillment decide API;成功后走恢复协调刷新三投影,
* prep 表即时反映已结案状态(后端拒绝无效流转时以 BusinessError 文案提示)。
*/
async function confirmCloseLine() {
const line = closeLineDialogLine.value;
const caseNo = activeCase.value?.case_no;
const reason = closeLineReason.value.trim();
if (!line || !caseNo || !reason || closeLineBusy.value) return;
closeLineBusy.value = true;
try {
await decideWorkspaceShippingOrderReviewLineFulfillment(caseNo, {
draft_line_id: String(line.draft_line_id || ''),
decision_code: 'close_unfulfillable',
reason,
expected_draft_version: activeCase.value?.draft?.draft_version,
});
closeLineDialogLine.value = null;
handleGateRecoveryAccepted();
} catch (error) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
} finally {
closeLineBusy.value = false;
}
}
/** 下载行级实际匹配快照,禁止退回到任务级 active link。 */
async function downloadFormalPreparationLineInventoryFile(line: {
snapshot_line_id?: number | null;
inventory_file_no?: string | null;
}) {
const taskNo = confirmedNoticeTaskNo.value || authoritativeOrderTaskNo.value;
const inventoryFileNo = formalPreparationLineInventoryFileNo(line);
if (!taskNo || !inventoryFileNo) return;
try {
await downloadWorkspaceShippingLineInventoryFile(taskNo, inventoryFileNo);
} catch (error) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
}
}
/** 行级恢复提交当前 Gate 的精确动作,使用冻结快照行身份。 */
async function retryFormalPreparationLine(
snapshotLineId: number | string,
actionCode: 'retry_inventory_preparation' | 'retry_inventory_matching',
) {
if (!snapshotLineId) return;
await submitFormalGateAction(actionCode, { snapshot_line_id: Number(snapshotLineId) });
}
/**
* 库存 RPA 是否运行中(就地编辑的 busy 禁用条件)。
* 核心逻辑:后端 preparation 摘要当前未下发 inventory_rpa_is_running(仅内部计算),
* 故先消费可选下发字段(后端补发即生效),缺失时以 status==='processing'
* (尚无匹配结果且无门禁 → 首轮抓取进行中)兜底;重匹配期间的写冲突由
* 后端 SHIPPING.EDIT_WINDOW_SYSTEM_BUSY 守卫兜底。
*/
const inlineEditBusy = computed(() => {
const preparation = formalTaskDetail.value?.ui_state?.stage_context?.preparation;
if (!preparation) return false;
const running = (preparation as { inventory_rpa_is_running?: unknown }).inventory_rpa_is_running;
if (typeof running === 'boolean') return running;
return preparation.status === 'processing';
});
/** 就地编辑状态:仅一行处于编辑态;保存走既有 update-notice-line 通道(免证据人工修订)。
* 编辑入口 = 行级「编辑」按钮(防单元格误触);编辑态下更多操作列替换为保存/取消。 */
const editingLine = ref<{
snapshot_line_id: number;
line_no: number;
part_number: string;
reservation_id: string;
required_qty: string;
source_code: string;
} | null>(null);
const inlineEditSaving = ref(false);
/**
* 就地编辑草稿种子值:把展示占位「—」还原为空串,避免占位符被当作真实值提交。
* @param value - prep 行展示值(可能为 null / '—' / 数字)
* @returns 可直接进入输入框的字符串
*/
function inlineEditSeedValue(value: unknown): string {
const text = String(value ?? '').trim();
return text === '—' ? '' : text;
}
/**
* 进入单个准备行的就地编辑(料号 / 预约号 / 需求数量三个值列)。
* @param line - prep 展示行;snapshot_line_id 定位编辑行,line_no-1 与后端 line_index 0 基对齐
*/
function startInlineEdit(line: {
snapshot_line_id?: number | null;
line_no?: string | number | null;
part_number?: string | null;
reservation_id?: string | null;
required_qty?: string | number | null;
selected_source_code?: string | null;
source_code?: string | null;
}) {
if (!line.snapshot_line_id || inlineEditSaving.value) return;
// 库存 RPA 运行中禁止改值:匹配进行中修改会与重匹配竞态。
if (inlineEditBusy.value) {
msg.warning(t('chat.shippingOrderReview.inlineEdit.busy'));
return;
}
editingLine.value = {
snapshot_line_id: Number(line.snapshot_line_id),
line_no: Number(line.line_no || 0),
part_number: inlineEditSeedValue(line.part_number),
reservation_id: inlineEditSeedValue(line.reservation_id),
required_qty: inlineEditSeedValue(line.required_qty),
source_code: inlineEditSeedValue(line.selected_source_code || line.source_code),
};
}
/** 行是否处于就地编辑态(统一 Number 收敛,避免模板严格等于的类型漂移)。 */
function isInlineEditing(line: { snapshot_line_id?: number | null }): boolean {
return editingLine.value?.snapshot_line_id === Number(line.snapshot_line_id);
}
/**
* 编辑态库存源下拉选项:多文件冲突行优先取候选源,其余行取全部已启用源;
* 无可用项返回空——此时编辑态库存源保持文本展示(无可选即不可改)。
*/
function inlineSourceOptions(line: {
source_ambiguous?: boolean;
source_candidates?: Array<string>;
}): Array<{ value: string; label: string }> {
if (line.source_ambiguous && (line.source_candidates?.length || 0) > 0) {
return (line.source_candidates || []).map((code) => ({ value: String(code), label: lineSourceOptionLabel(String(code)) }));
}
if (formSourceOptions.value.length) {
return formSourceOptions.value.map((s) => ({ value: String(s.source_code), label: overrideSourceOptionLabel(String(s.source_code)) }));
}
return [];
}
/** 同步编辑态库存源草稿(与三个值列一致:改动仅在保存时提交)。 */
function updateInlineEditSource(value: string) {
if (editingLine.value) editingLine.value.source_code = value;
}
/** 行级动作收纳菜单(⋯)打开状态:键 = snapshot_line_id,单行互斥;坐标视口固定定位,
* Teleport 到 body——表格祖先容器 overflow-auto 会裁剪 absolute 浮层并转为滚动高度。 */
const overflowMenuOpenFor = ref<string | null>(null);
const overflowMenuPos = ref<{ top: number; left: number }>({ top: 0, left: 0 });
function toggleOverflowMenu(key: string, event?: MouseEvent) {
if (overflowMenuOpenFor.value === key) {
overflowMenuOpenFor.value = null;
return;
}
const rect = (event?.currentTarget as HTMLElement | undefined)?.getBoundingClientRect();
const menuWidth = 176;
overflowMenuPos.value = {
top: rect ? Math.min(rect.bottom + 4, window.innerHeight - 8) : 0,
left: rect ? Math.max(8, Math.min(rect.right - menuWidth, window.innerWidth - menuWidth - 8)) : 0,
};
overflowMenuOpenFor.value = key;
}
/**
* 行级收纳菜单项:低频/诊断类动作入口(守卫条件与原常显按钮完全一致),
* 高频的「编辑」保持常显;无可用项时 ⋯ 整体不渲染。
*/
function overflowItems(line: {
snapshot_line_id?: number | null;
shortage_qty?: string | number | null;
}): Array<{ key: string; icon: Component; labelKey: string; run: () => void | Promise<void> }> {
const items: Array<{ key: string; icon: Component; labelKey: string; run: () => void | Promise<void> }> = [];
if (formalPreparationLineAllows(line, 'retry_inventory_matching')) {
items.push({
key: 'retry_inventory_matching',
icon: RefreshCw,
labelKey: inventoryActionLabelKey('retry_inventory_matching')!,
run: () => retryFormalPreparationLine(Number(line.snapshot_line_id), 'retry_inventory_matching'),
});
}
// 放行缺口:缺字段型短缺行 → 行内展开补录条(替代弹窗);仅缺原因的行 → 旧弹窗(原因已可选)。
if (formalPreparationLineAllows(line, 'release_inventory_shortage')) {
items.push({
key: 'release_inventory_shortage',
icon: Check,
labelKey: inventoryActionLabelKey('release_inventory_shortage')!,
run: () => {
if (releaseBarHasFields(line)) expandReleaseBar(line);
else openReleaseInventoryShortage(line);
},
});
}
if (formalPreparationLineCloseVisible(line)) {
items.push({
key: 'close_unfulfillable',
icon: X,
labelKey: 'chat.shippingOrderReview.lineActions.closeLine',
run: () => openCloseLineDialog(line),
});
}
if (formalPreparationLineAllows(line, 'retry_inventory_preparation')) {
items.push({
key: 'retry_inventory_preparation',
icon: Bot,
labelKey: inventoryActionLabelKey('retry_inventory_preparation')!,
run: () => retryFormalPreparationLine(Number(line.snapshot_line_id), 'retry_inventory_preparation'),
});
}
if (formalPreparationLineInventoryFileNo(line)) {
items.push({
key: 'download_inventory_file',
icon: Download,
labelKey: inventoryActionLabelKey('download_inventory_file') || 'chat.shippingOrderReview.lifecycle.prepare.downloadInventory',
run: () => downloadFormalPreparationLineInventoryFile(line),
});
}
return items;
}
/** 同步需求数量输入:数字输入框经 @input 手动回写,避免 v-model 的隐式 number 转型。 */
function updateInlineEditQty(value: string) {
if (editingLine.value) editingLine.value.required_qty = value;
}
/** 退出就地编辑并丢弃未保存修改。 */
function cancelInlineEdit() {
editingLine.value = null;
}
/**
* 保存就地编辑:仅提交有变化且非空的字段(part_number / reservation_id / qty),
* 成功后提示「请点击重新匹配库存」并刷新任务详情(值列即刻显示新值,重匹配仍需手动触发)。
* @param line - 当前编辑行,用于与编辑起始值比对计算差量补丁
*/
async function saveInlineEdit(line: {
snapshot_line_id?: number | null;
part_number?: string | null;
reservation_id?: string | null;
required_qty?: string | number | null;
selected_source_code?: string | null;
source_code?: string | null;
}) {
const draft = editingLine.value;
if (!draft || !draft.snapshot_line_id || inlineEditSaving.value) return;
// 编辑态行与触发行的快照身份不一致(如刷新后错位)时直接丢弃,禁止错行提交。
if (draft.snapshot_line_id !== Number(line.snapshot_line_id)) {
cancelInlineEdit();
return;
}
const taskNo = String(formalTaskDetail.value?.task_no || '').trim();
const lineIndex = Number(draft.line_no) - 1;
if (!taskNo || !Number.isInteger(lineIndex) || lineIndex < 0) {
cancelInlineEdit();
return;
}
const patch: Record<string, string> = {};
const nextPartNumber = draft.part_number.trim();
if (nextPartNumber !== inlineEditSeedValue(line.part_number)) patch.part_number = nextPartNumber;
const nextReservationId = draft.reservation_id.trim();
if (nextReservationId !== inlineEditSeedValue(line.reservation_id)) patch.reservation_id = nextReservationId;
const nextQty = draft.required_qty.trim();
if (nextQty !== inlineEditSeedValue(line.required_qty) && nextQty) patch.qty = nextQty;
// 库存源草稿与进入编辑时的种子值比对:变化即随保存提交行级源覆写。
const seedSourceCode = inlineEditSeedValue(line.selected_source_code || line.source_code);
const nextSourceCode = draft.source_code.trim();
const sourceChanged = Boolean(nextSourceCode) && nextSourceCode !== seedSourceCode;
if (!Object.keys(patch).length && !sourceChanged) {
cancelInlineEdit();
return;
}
inlineEditSaving.value = true;
try {
// 字段值先落库(update-notice-line);随后的源覆写会触发单行重匹配,读到的是修正后的字段值。
if (Object.keys(patch).length) {
await updateWorkspaceShippingNoticeLine(
taskNo,
lineIndex,
patch,
undefined,
// 免证据人工修订(后端 Task 2 已放宽 evidence/reason);乐观锁版本缺失时
// 退回后端初值 1,冲突由后端 ORDER_DATA_VERSION_MISMATCH 的 409 语义兜底。
{ expectedOrderDataVersion: Number(formalTaskDetail.value?.order_data_version ?? 1) },
);
}
// 库存源覆写沿用既有 Gate 动作(override_line_inventory_source),后端校验后仅重匹配该行。
if (sourceChanged) {
await submitFormalGateAction('override_line_inventory_source', {
line_no: draft.line_no,
source_code: nextSourceCode,
});
}
cancelInlineEdit();
msg.success(t('chat.shippingOrderReview.inlineEdit.saved'));
await loadFormalTaskDetail();
} catch (error) {
// BusinessError.message 即后端业务文案(版本冲突 / 系统处理中),复用既有提示通道。
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
} finally {
inlineEditSaving.value = false;
}
}
/**
* 人工上传登记是后端 Gate 的受控写动作;仅进入「货代上传」工作面不构成授权。
* [§2 单源] 授权从 A(shippingProcessingProjection.ui_state)读 —— §2.5 差异① 已归一,A 的
* secondary_actions/primary_action 透传原始 mark_manual_uploaded 码(与 B/C 一致的写契约码)。
* 避免页面按上传状态或生命周期自行放行。
*/
const manualUploadRegistrationAuthorized = computed(() => {
const uiState = currentTaskUiState.value;
// primary_action 无 enabled 字段,出现即视为已授权;secondary_actions 必须 enabled === true。
if (uiState?.primary_action?.code === 'mark_manual_uploaded') return true;
return (uiState?.secondary_actions || []).some(
(action) => action.code === 'mark_manual_uploaded' && action.enabled === true,
);
});
/** 直接在订单复核页打开人工上传登记,避免依赖仅在 formal_task 模式挂载的 TaskTodoPanel ref。 */
function openManualUploadRegistration() {
if (!confirmedNoticeTaskNo.value || !manualUploadRegistrationAuthorized.value) {
msg.warning(t('chat.shippingOrderReview.workbench.resultNotReady'));
return;
}
manualUploadRegistrationOpen.value = true;
}
/**
* 人工上传登记成功后刷新完整工作台状态。
* 先重新拉取 Review Case(顶部阶段与 Gate 的权威投影),再刷新左侧本批队列生命周期、
* 任务详情和统一处理投影;不能只刷新 OT 详情,否则登记已落库但页面仍会显示旧的人工上传阻断状态;
* 也不能省略 refreshReviewQueue,否则五阶段已到「通知完成」而左侧仍停在「货代上传」。
*/
async function handleManualUploadSuccess() {
manualUploadRegistrationOpen.value = false;
await Promise.all([
reloadLatestDraft(),
refreshReviewQueue(),
]);
await Promise.all([
loadFormalTaskDetail(),
refreshShippingProcessing(),
]);
}
/**
* 拉取确认后的 Notice 履约详情,供 Gate Action 与 Artifact 视图使用。
*/
async function loadFormalTaskDetail() {
// 深链 OT 兜底:无 case_no 的 OT 直链下选法 2 不拉 Case,activeCase/displayCase
// 均为空、confirmedNoticeTaskNo 恒空;此时必须消费深链 task_no,否则挂载预取的
// 任务详情被丢弃、五阶段页签无身份可裁决(全锁死)。一旦存在任何 Case 上下文
// 则禁止回退,防止深链 OT 串到用户切换后的其他文件。
const taskNo = confirmedNoticeTaskNo.value
|| (displayCase.value ? '' : deepLinkOrderTaskNo.value);
const generation = ++formalTaskDetailGeneration;
if (!taskNo) {
formalTaskDetail.value = null;
formalTaskDetailLoadFailed.value = false;
return;
}
// 仅任务切换时清空旧详情。同一任务的刷新若先清空,会让 lifecycle_stage 在
// freight_upload 与空值之间来回跳,进而触发工作面 watcher 的重复拉取循环。
if (formalTaskDetail.value?.task_no !== taskNo) {
formalTaskDetail.value = null;
}
// [PERF] 复用深链预取的任务详情:首次进入时它与 load() 并行发起,避免任务详情在
// load() 完成之后再串行重拉;仅当预取与当前确认任务号一致时使用,用完即清空,
// 后续 Gate 动作后的写后刷新仍走正常网络读取,保证新鲜度。
const prefetch = deepLinkTaskPrefetch.value;
if (prefetch && prefetch.taskNo === taskNo) {
deepLinkTaskPrefetch.value = null;
const prefetched = await prefetch.promise;
if (
prefetched
&& String(prefetched.task_no || '').trim() === taskNo
&& generation === formalTaskDetailGeneration
) {
formalTaskDetail.value = prefetched;
formalTaskDetailLoadFailed.value = false;
formalTaskDetailLoading.value = false;
return;
}
}
formalTaskDetailLoadFailed.value = false;
formalTaskDetailLoading.value = true;
try {
const detail = await getWorkspaceShippingTask(taskNo, { view: 'workbench' });
if (generation !== formalTaskDetailGeneration) return;
// 同代也必须核对任务身份;服务端异常返回或旧请求均不能成为当前生命周期事实。
if (String(detail?.task_no || '').trim() !== taskNo) {
if (generation === formalTaskDetailGeneration) formalTaskDetailLoadFailed.value = true;
return;
}
formalTaskDetail.value = detail;
formalTaskDetailLoadFailed.value = false;
} catch {
if (generation === formalTaskDetailGeneration) {
formalTaskDetail.value = null;
formalTaskDetailLoadFailed.value = true;
}
} finally {
if (generation === formalTaskDetailGeneration) formalTaskDetailLoading.value = false;
}
}
/** 货代上传阶段按当前 PO 读取全部 Notice 聚合;每个 business_no 只保留一张 Excel 动作。 */
async function loadFreightNoticeGroups(taskNo: string) {
if (!taskNo) {
freightNoticeGroups.value = [];
freightNoticeGroupsReason.value = null;
freightNoticeGroupsLoadFailed.value = false;
selectedFreightBusinessNos.value = [];
return;
}
// 在途请求去重:同 tick 与动作后刷新并发调用时丢弃后继,避免重复网络请求。
if (freightGroupsInFlight.value) return;
// [PERF] 已有数据时采用 stale-while-revalidate:保留旧表格直至新数据替换,仅首屏
// (此时无任何分组)才展示加载占位,避免“已有表格 → 加载中 → 表格”每 5 秒整块闪烁。
const hasExisting = freightNoticeGroups.value.length > 0;
freightNoticeGroupsLoading.value = !hasExisting;
freightNoticeGroupsLoadFailed.value = false;
freightNoticeGroupsReason.value = null;
freightGroupsInFlight.value = true;
try {
const result = await getWorkspaceShippingFreightNoticeGroups(taskNo);
freightNoticeGroups.value = Array.isArray(result?.items) ? result.items : [];
freightNoticeGroupsReason.value = result?.reason || null;
const visible = new Set(freightNoticeGroups.value.map((item) => item.business_no));
selectedFreightBusinessNos.value = selectedFreightBusinessNos.value.filter((item) => visible.has(item));
} catch {
freightNoticeGroups.value = [];
freightNoticeGroupsLoadFailed.value = true;
freightNoticeGroupsReason.value = null;
} finally {
freightGroupsInFlight.value = false;
freightNoticeGroupsLoading.value = false;
}
}
// [STEP] 货代上传分组不再单独挂定时轮询:CRANE/RPA 上传可能耗时数分钟,期间 upload_status 恒为
// uploading,固定 5s 重拉只会重复几十次无变化请求。任务级处理投影(startWorkflowProgressPolling
// 每 5s 轮询 refreshShippingProcessing)已依据 notice_upload_status / has_verified_upload_success 把
// 货代上传终态投影为 uiState.lifecycleStage=upload_complete;这里只在投影进入该终态时一次性
// 刷新分组,使通知列表/完成面落到回调后的真实状态,其余在途阶段一律静默。
let freightNoticeGroupsFinalized = false;
/** 投影驱动的货代上传终态:upload_complete 阶段或用户态已结束。 */
function isFreightUploadProjectionTerminal(): boolean {
const uiState = shippingProcessingProjection.value?.uiState;
const lifecycleStage = String(uiState?.lifecycleStage || '').trim();
const userStatus = String(
shippingProcessingProjection.value?.userStatus
|| shippingProcessingProjection.value?.status
|| shippingProcessingProjection.value?.uiState?.status
|| '',
).trim().toLowerCase();
return lifecycleStage === 'upload_complete'
|| ['completed', 'cancelled', 'waiting_human', 'failed'].includes(userStatus);
}
/**
* 投影到达货代上传终态时刷新一次分组列表与左侧队列(幂等守卫,防止投影在途反复触发)。
* 核心逻辑:只在“上传行为已结束”时写列表;uploading 期间不产生任何额外请求;
* 同时 refreshReviewQueue,使 RPA 自动完成路径下左侧 lifecycle_stage 与五阶段一致。
*/
function maybeRefreshFreightGroupsOnTerminal() {
if (!isLifecycleFreightUpload.value && !isLifecycleUploadComplete.value) return;
if (freightNoticeGroupsFinalized) return;
const taskNo = String(confirmedNoticeTaskNo.value || '').trim();
if (!taskNo) return;
if (!isFreightUploadProjectionTerminal()) return;
freightNoticeGroupsFinalized = true;
void loadFreightNoticeGroups(taskNo);
void refreshReviewQueue();
}
// [PERF] 以任务级处理投影为唯一终态信号,替代独立的 5s 分组轮询:进入货代上传时的初始拉取由
// 下方 confirmedNoticeTaskNo watcher 负责,这里只负责「投影到达 upload_complete 终态时刷新一次」。
// 任务号/工作面切换时重置幂等守卫,避免同任务重复拉取、或新任务被旧终态误跳过。
watch(
[shippingProcessingProjection, confirmedNoticeTaskNo, isLifecycleFreightUpload, isLifecycleUploadComplete],
([, taskNo, isFreightUpload, isUploadComplete]) => {
const no = String(taskNo || '').trim();
// 任务号变化或切出货代工作面对清守卫与列表,回到空闲态不残留旧分组。
if (!no || !isFreightUpload && !isUploadComplete) {
freightNoticeGroupsFinalized = false;
return;
}
maybeRefreshFreightGroupsOnTerminal();
},
{ immediate: true },
);
/**
* 货代上传分组是否正在等待异步 RPA 回调。
* 核心逻辑:只认投影后的 upload_status(uploading);禁止再读 OT 人工原因列。
*/
function hasFreightGroupsInFlightRpa(groups: ShippingFreightNoticeGroup[]): boolean {
return (groups || []).some((group) => {
const st = String(group.upload_status || '').trim().toLowerCase();
return st === 'uploading';
});
}
// [PERF] 仅在「货代上传有在途 RPA」时才启用任务级处理投影轮询:投影用于感知 RPA 回调把
// 状态推进到 upload_complete 终态,从而一次性刷新分组。空闲(等待人工/自动上传关闭)、已终态、
// 或已切出货代工作面对都立即停止,避免工作台在无变化的页面徒劳轮询 shipping-processing-work-item。
// startWorkflowProgressPolling 到达终态后内部也会自停,这里负责“非终态但无需等待”的停轮询。
watch(
[freightNoticeGroups, isLifecycleFreightUpload, isLifecycleUploadComplete, authoritativeOrderTaskNo],
([groups, isFreightUpload, isUploadComplete, otNo]) => {
const taskNo = String(confirmedNoticeTaskNo.value || '').trim();
const onFreightStage = Boolean(taskNo && (isFreightUpload || isUploadComplete));
const inFlight = hasFreightGroupsInFlightRpa(groups || []);
if (!onFreightStage || !otNo || !inFlight) {
stopWorkflowProgressPolling();
return;
}
startWorkflowProgressPolling();
},
{ immediate: true },
);
// ============================================================================
// 正式 OT 自动推进的「阶段无关」投影轮询(问题1修复的正解)
// ============================================================================
// 背景:shippingProcessingProjection 是整工作台唯一的轻量实时投影(progressVersion 变化会
// 触发 [REFRESH_ON_CHANGE] 重新加载正式任务详情 → 表格数字/门禁/阶段自动更新)。但它的刷新
// 完全依赖 startWorkflowProgressPolling(useShippingProcessingWorkItem 已关 continuousPolling),
// 而历史上只有「货代上传」watching 会持续推进该轮询;通知准备阶段的 RPA 取数→匹配→满足性
// 异步推进期间轮询被停,导致「可用数量/缺口/匹配状态」停在初值,需手动刷新。
// 方案:新增一条与业务阶段解耦的推进监控——只要存在正式 OT、且其投影仍处于「自动推进中」
// (非终态/非等待人工/非中断),就保持轮询;落到终态/等待人工即停止。与货代上传 watcher 互不耦合,
// prep 阶段不再寄生在 freight 逻辑上。
const OT_PROGRESS_ACTIVE_STATUSES = new Set(['running', 'processing', 'automating', 'queued']);
const OT_PROGRESS_IDLE_STATUSES = new Set(['waiting_human', 'interrupted', 'failed', 'completed', 'cancelled']);
function isOtProgressing(projection: typeof shippingProcessingProjection.value): boolean {
const status = String(
projection?.uiState?.status
|| projection?.userStatus
|| projection?.status
|| '',
).trim().toLowerCase();
return OT_PROGRESS_ACTIVE_STATUSES.has(status) && !OT_PROGRESS_IDLE_STATUSES.has(status);
}
watch(
[() => hasFormalOt.value, authoritativeOrderTaskNo, shippingProcessingProjection],
([hasOt, otNo, projection]) => {
// 仅当正式 OT 存在且其投影处于自动推进态时保持轮询;否则停止,避免空转。
if (!hasOt || !otNo || !projection || !isOtProgressing(projection)) {
if (workflowProgressPolling.value) stopWorkflowProgressPolling();
return;
}
// 已在轮询则不动,避免每次投影刷新都重建 interval(否则 2.5s 定时器被反复重置)。
if (!workflowProgressPolling.value) startWorkflowProgressPolling();
},
{ immediate: true },
);
function toggleFreightNoticeSelection(businessNo: string, checked: boolean) {
selectedFreightBusinessNos.value = checked
? Array.from(new Set([...selectedFreightBusinessNos.value, businessNo]))
: selectedFreightBusinessNos.value.filter((item) => item !== businessNo);
}
/** 已选通知单中任一已上传时,批量写入动作必须 fail-closed,避免重复提交成功通知。 */
const selectedFreightNoticesContainUploaded = computed(() => {
const selected = new Set(selectedFreightBusinessNos.value);
return freightNoticeGroups.value.some((group) => (
selected.has(group.business_no) && isFreightNoticeUploaded(group)
));
});
async function downloadFreightNotice(businessNo: string) {
try {
await downloadWorkspaceShippingNoticeExcelFile(businessNo);
} catch (error) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
}
}
async function runFreightBatchAction(action: 'download' | 'confirm' | 'rpa') {
if (!selectedFreightBusinessNos.value.length || freightBatchBusy.value) return;
if (action !== 'download' && selectedFreightNoticesContainUploaded.value) return;
freightBatchBusy.value = action;
try {
if (action === 'download') {
await downloadWorkspaceShippingNoticeExportArchive(selectedFreightBusinessNos.value);
} else if (action === 'confirm') {
await batchConfirmWorkspaceShippingNoticesUploaded(selectedFreightBusinessNos.value);
} else {
await batchStartWorkspaceShippingNoticeRpaUpload(selectedFreightBusinessNos.value);
}
// 确认/RPA 后重拉同 PO 通知聚合,使通知完成面能立即呈现最新 uploaded 状态。
if (action === 'confirm' || action === 'rpa') {
const taskNo = String(confirmedNoticeTaskNo.value || '').trim();
if (taskNo) await loadFreightNoticeGroups(taskNo);
// 不挂独立 5s 轮询:RPA 上传结果由任务级处理投影感知(endpoint terminal),
// 由下方 refreshShippingProcessing 驱动的投影 watcher 在 upload_complete 时一次性刷新。
// 这里重置守卫允许重新触发,确认是人工即时终态、RPA 是等待异步回传的唯一窗口。
freightNoticeGroupsFinalized = false;
startWorkflowProgressPolling();
}
await Promise.all([loadFormalTaskDetail(), refreshShippingProcessing()]);
} catch (error) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
} finally {
freightBatchBusy.value = null;
}
}
/**
* 对主区单个发货通知单执行已存在的业务动作。
* 核心逻辑:RPA 与人工确认复用批量 API 的单元素请求,确保始终按 business_no 裁决;
* Excel 重生仍复用当前正式任务已经授权的 Gate 执行器,且只在该任务对应行显示。
* @param group - 主区当前发货通知单聚合行。
* @param action - 单条 RPA、人工确认或 Excel 重生动作。
*/
async function runFreightNoticeAction(
group: ShippingFreightNoticeGroup,
action: 'confirm' | 'rpa' | 'regenerate',
) {
if (freightBatchBusy.value) return;
if (action !== 'regenerate' && isFreightNoticeUploaded(group)) return;
freightBatchBusy.value = action;
try {
if (action === 'confirm') {
await batchConfirmWorkspaceShippingNoticesUploaded([group.business_no]);
} else if (action === 'rpa') {
await batchStartWorkspaceShippingNoticeRpaUpload([group.business_no]);
} else {
if (String(formalTaskDetail.value?.business_no || '').trim() !== group.business_no) return;
await submitFormalGateAction('regenerate_excel_artifact');
return;
}
// 确认/RPA 后重拉同 PO 通知聚合,使通知完成面能立即呈现最新 uploaded 状态。
const taskNo = String(confirmedNoticeTaskNo.value || '').trim();
if (taskNo) await loadFreightNoticeGroups(taskNo);
// 不挂独立 5s 轮询:RPA 上传结果由任务级处理投影感知,由下方 refreshShippingProcessing
// 驱动的投影 watcher 在 upload_complete 时一次性刷新;这里重置守卫允许重新触发。
freightNoticeGroupsFinalized = false;
startWorkflowProgressPolling();
await Promise.all([loadFormalTaskDetail(), refreshShippingProcessing()]);
} catch (error) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
} finally {
freightBatchBusy.value = null;
}
}
/** 当前任务的 Excel 重生只可映射到其自身 business_no,禁止跨 PO/通知单展示。 */
function canRegenerateFreightNotice(group: ShippingFreightNoticeGroup): boolean {
return canRunFreightNoticeAction(group, 'regenerate_excel_artifact')
&& String(formalTaskDetail.value?.business_no || '').trim() === group.business_no
&& formalTaskActions.value.some((action) => (
action.enabled && String(action.code || '').trim() === 'regenerate_excel_artifact'
));
}
/**
* 判断单条通知单是否存在可展开的更多操作。
* 核心逻辑:已上传通知一律不展示更多按钮;RPA/确认已提到行内主按钮,
* 更多菜单仅承载低频的 Excel 重生,避免空白菜单。
* @param group - 当前发货通知单聚合行。
* @returns 是否显示更多操作入口。
*/
function hasFreightNoticeMoreActions(group: ShippingFreightNoticeGroup): boolean {
if (isFreightNoticeUploaded(group)) return false;
return canRegenerateFreightNotice(group);
}
/** 仅展示 Notice 聚合接口下发的已授权动作;最终写入仍由对应 API 二次校验。 */
function canRunFreightNoticeAction(group: ShippingFreightNoticeGroup, actionCode: string): boolean {
return (group.available_actions || []).includes(actionCode);
}
watch(
[confirmedNoticeTaskNo, workbenchMode, hasCreatedShippingTask, isLifecycleFreightUpload, isLifecycleUploadComplete],
([taskNo, mode, created, isFreightUpload, isUploadComplete]) => {
const completed = String(displayCase.value?.current_stage?.code || '').trim().toLowerCase() === 'completed'
|| String(displayCase.value?.user_status || '').trim().toLowerCase() === 'completed';
// Notice 聚合服务货代上传与通知完成两个工作面;通知准备/文件切换不扫描同 PO 全部 Notice。
const needsNoticeGroups = isFreightUpload || isUploadComplete;
if (taskNo && created && needsNoticeGroups) void loadFreightNoticeGroups(taskNo);
if (!needsNoticeGroups) {
freightNoticeGroups.value = [];
selectedFreightBusinessNos.value = [];
}
if (taskNo && created && (mode === 'formal_task' || mode === 'confirm_progress' || completed)) {
void loadFormalTaskDetail();
return;
}
if (!taskNo) {
++formalTaskDetailGeneration;
formalTaskDetail.value = null;
void loadFreightNoticeGroups('');
}
},
{ immediate: true },
);
/** Schema 字段显示名同时按 field_code / field_id 建索引,避免阻断只显示内部标识。 */
const reviewFieldLabels = computed(() => Object.fromEntries(
(displayCase.value?.schema.fields || []).flatMap((field) => [
[field.field_code, field.display_name],
[field.field_id, field.display_name],
]),
));
const showAllHeaderFields = ref(false);
const showAllLineFields = ref(false);
/**
* 判断字段是否应默认展示(必填 / 异常 / 有值 / 人工修改)。
* @param field - Schema 字段
* @param scope - header | line
* @param line - 行容器(行级判断时传入)
*/
function isPrimarySchemaField(
field: { field_id: string; required?: boolean },
scope: 'header' | 'line',
line?: Record<string, unknown>,
): boolean {
if (field.required) return true;
const fieldId = String(field.field_id || '').trim();
if (!fieldId) return false;
if (exceptionTargets.value.some((item) => item.fieldId === fieldId)) return true;
if (scope === 'header') {
const header = displayCase.value?.draft?.header_values as Record<string, unknown> | undefined;
const value = String(draftValue(header || {}, fieldId) || '').trim();
if (value) return true;
const meta = draftFieldMeta(header, fieldId);
return String(meta.value_source || '') === 'manual';
}
const container = (line || {}) as Record<string, unknown>;
const value = String(draftValue(container, fieldId) || '').trim();
if (value) return true;
return String(draftFieldMeta(container, fieldId).value_source || '') === 'manual';
}
const visibleHeaderSchemaFields = computed(() => {
const all = headerSchemaFields.value;
if (showAllHeaderFields.value) return all;
const primary = all.filter((field) => isPrimarySchemaField(field, 'header'));
return primary.length ? primary : all.slice(0, Math.min(4, all.length));
});
const hiddenHeaderFieldCount = computed(
() => Math.max(0, headerSchemaFields.value.length - visibleHeaderSchemaFields.value.length),
);
const visibleLineSchemaFields = computed(() => {
// 客户 PO 项次是业务核对的主键,始终列首;内部项次只读展示;
// 库存源线索是库存路由核对列,无论解析是否命中都保留在主表,方便用户核对各行对应库存源。
const all = lineSchemaFields.value;
const ordered = [...all].sort((left, right) => {
const leftPriority = left.field_code === 'customer_po_line_no' ? 0 : 1;
const rightPriority = right.field_code === 'customer_po_line_no' ? 0 : 1;
return leftPriority - rightPriority;
});
if (showAllLineFields.value) return ordered;
const lines = displayDraftLines.value as Array<Record<string, unknown>>;
const primary = ordered.filter((field) => (
lines.some((line) => isPrimarySchemaField(field, 'line', line))
|| isPrimarySchemaField(field, 'line')
));
const customerPoLine = ordered.find((field) => field.field_code === 'customer_po_line_no');
const primaryWithCustomerPoLine = customerPoLine && !primary.some((field) => field.field_id === customerPoLine.field_id)
? [customerPoLine, ...primary]
: primary;
// 库存源线索固定追加到主列末尾,作为路由核对列始终可见。
const inventorySourceField = ordered.find((field) => isInventorySourceHintField(field));
const withInventorySource = inventorySourceField
? [...primaryWithCustomerPoLine.filter((field) => field.field_id !== inventorySourceField.field_id), inventorySourceField]
: primaryWithCustomerPoLine;
return withInventorySource.length
? withInventorySource
: ordered.slice(0, Math.min(4, ordered.length));
});
/** 主库存表是唯一明细入口;批量出单只允许库存满足或已人工放行的开放行。 */
const selectedPreparationSnapshotLineIds = ref<string[]>([]);
const preparationWaveBusy = ref(false);
// [Task4] 列头:标准字段名(不再依赖 review Case schema 的 display_name)。
const preparationCustomerPoLineLabel = () => t('chat.shippingOrderReview.lifecycle.prepare.customerPoLine');
// [Task4] 列展示判定:prep 行中任一行下发原生 customer_po_line_no 即显示整列,否则整列隐藏。
// 类型文件已声明该字段(shipping.api.types.ts stage_context.preparation.lines),直接读取,语义与
// 行值 helper 一致(按 trim 后非空判定,空白值不触发整列显示)。
const preparationCustomerPoLineVisible = computed(() => (
formalPreparationLines.value.some((line) => Boolean(String(line.customer_po_line_no || '').trim()))
));
const preparationWaveSelectableLines = computed(() => formalPreparationLines.value.filter((line) => {
const fulfillment = formalPreparationLineFulfillment(line);
if (!fulfillment) return false;
if (['task_created', 'fulfilled', 'closed_unfulfillable'].includes(String(fulfillment.line_status || ''))) return false;
return Boolean(fulfillment.can_fulfill_complete_line)
|| fulfillment.decision?.decision_code === 'release_inventory_shortage';
}));
const allPreparationWaveSelected = computed(() => (
preparationWaveSelectableLines.value.length > 0
&& preparationWaveSelectableLines.value.every((line) => selectedPreparationSnapshotLineIds.value.includes(String(line.snapshot_line_id)))
));
function toggleAllPreparationLineSelection(checked: boolean) {
selectedPreparationSnapshotLineIds.value = checked
? preparationWaveSelectableLines.value.map((line) => String(line.snapshot_line_id))
: [];
}
function togglePreparationLineSelection(snapshotLineId: string, checked: boolean) {
const key = String(snapshotLineId || '').trim();
if (!key) return;
const selected = new Set(selectedPreparationSnapshotLineIds.value);
if (checked) selected.add(key);
else selected.delete(key);
selectedPreparationSnapshotLineIds.value = [...selected];
}
/**
* [Task4] 行值:直接读后端 prep line 下发的原生 customer_po_line_no(ui_state 单源),
* 不再回退 Case 草稿字段展示;缺失显示 —。参数保留 draft_line_id 以满足 prep 行类型的弱类型检查。
*/
function preparationLineCustomerPoLine(line: { draft_line_id?: string | null; customer_po_line_no?: string | null }): string {
return String(line.customer_po_line_no || '').trim() || '—';
}
/** 发货通知项次直接读取后端 ShippingNoticeLine.line_no,不显示来源或派生提示。 */
function freightLineNoDisplay(line: { line_no?: string | number | null }): {
text: string;
muted: boolean;
title: string;
} {
const value = line.line_no ?? null;
return { text: value === null || value === '' ? '—' : String(value), muted: false, title: '' };
}
/**
* 逐发货通知单的货代上传状态展示。
* 核心逻辑:只认投影后的 upload_status 与 upload_error_*;禁止读 OT 人工原因列。
* @param group - 当前发货通知单聚合行(含 upload_status 与逐单错误字段)。
*/
function freightUploadStatusDisplay(group: ShippingFreightNoticeGroup): {
state: 'uploaded' | 'uploading' | 'failed' | 'needs_human' | 'pending';
label: string;
chipClass: string;
reason: string | null;
} {
const status = String(group.upload_status || '').trim().toLowerCase();
const reason = group.upload_error_message || group.upload_error_code || null;
if (status === 'uploaded') {
return {
state: 'uploaded',
label: t('chat.shippingOrderReview.lifecycle.freightUpload.uploadStatus.uploaded'),
chipClass: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950/50 dark:text-emerald-200',
reason: null,
};
}
if (status === 'failed') {
return {
state: 'failed',
label: t('chat.shippingOrderReview.lifecycle.freightUpload.uploadStatus.failed'),
chipClass: 'bg-rose-100 text-rose-700 dark:bg-rose-950/50 dark:text-rose-300',
reason: reason ? t('chat.shippingOrderReview.lifecycle.freightUpload.uploadError', { reason }) : null,
};
}
// 存在错误码但状态未置 failed(如超时/结果未知):按“需人工”展示并始终带出逐单原因。
if (reason) {
return {
state: 'needs_human',
label: t('chat.shippingOrderReview.lifecycle.freightUpload.uploadStatus.needsHuman'),
chipClass: 'bg-amber-100 text-amber-800 dark:bg-amber-950/50 dark:text-amber-200',
reason: t('chat.shippingOrderReview.lifecycle.freightUpload.uploadError', { reason }),
};
}
if (status === 'uploading') {
return {
state: 'uploading',
label: t('chat.shippingOrderReview.lifecycle.freightUpload.uploadStatus.uploading'),
chipClass: 'bg-blue-100 text-blue-800 dark:bg-blue-950/50 dark:text-blue-200',
reason: null,
};
}
return {
state: 'pending',
label: t('chat.shippingOrderReview.lifecycle.freightUpload.uploadStatus.pending'),
chipClass: 'bg-surface-strong text-secondary dark:bg-slate-800/60 ',
reason: null,
};
}
/**
* 通知完成面:解析上传成功证据的来源方式(人工确认 / RPA),用于徽标展示。
* 核心逻辑:upload_mode 为后端从 ShippingUploadAttempt 权威事实解析的 rpa|manual;
* 仅该两值可映射,未知/空一律返回 null,避免把历史遗留或未知模式伪装成人话。
* @param mode - 后端解析出的上传方式(rpa / manual / 空)。
*/
function freightUploadModeLabel(mode: string | null | undefined): string | null {
const value = String(mode || '').trim().toLowerCase();
if (value === 'rpa') return t('chat.shippingOrderReview.lifecycle.uploadComplete.uploadModeRpa');
if (value === 'manual') return t('chat.shippingOrderReview.lifecycle.uploadComplete.uploadModeManual');
return null;
}
async function confirmPreparationWave() {
const caseNo = String(activeCase.value?.case_no || '').trim();
const draftVersion = activeCase.value?.draft?.draft_version;
if (!caseNo || draftVersion == null || preparationWaveBusy.value || !selectedPreparationSnapshotLineIds.value.length) return;
preparationWaveBusy.value = true;
try {
const result = await waveWorkspaceShippingOrderReviewLineFulfillment(caseNo, {
snapshot_line_ids: [...selectedPreparationSnapshotLineIds.value].map((value) => Number(value)),
expected_draft_version: draftVersion,
idempotency_key: `review-wave-${caseNo}-${Date.now()}-${selectedPreparationSnapshotLineIds.value.sort().join(',')}`,
});
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.fulfillmentDecision.waveSuccess', {
taskNo: result.notice_no || result.task_no || '',
}));
selectedPreparationSnapshotLineIds.value = [];
await handleReviewGateDataRefreshed();
// [FIX] wave 确认后后端是「入队异步后台推进」(生成 Excel → OT 进入货代上传),不是同步完成。
// 仅做一次 handleReviewGateDataRefreshed 的单次读取无法感知自动推进落地(后端早已变成货代上传,
// 前台一直停在通知准备——反复出现的 bug)。因此成功生成后必须重载正式任务详情;且当后端确认
// 已调度推进(auto_progress_started)时立即起任务级处理投影轮询,让五阶段导航/右栏在自动推进
// 落到货代上传时自动刷新(未调度则表示无异步可等,无需驻留轮询)。
void loadFormalTaskDetail();
if (result.auto_progress_started) {
startWorkflowProgressPolling();
}
} catch (error: unknown) {
msg.warning(error instanceof BusinessError ? error.message : (error instanceof Error ? error.message : t('chat.shippingOrderReview.fulfillmentDecision.waveFailed')));
} finally {
preparationWaveBusy.value = false;
}
}
const hiddenLineFieldCount = computed(
() => Math.max(0, lineSchemaFields.value.filter((field) => (
field.field_code !== 'line_no'
)).length - visibleLineSchemaFields.value.length),
);
const linesTableMinWidthClass = computed(() => {
const cols = visibleLineSchemaFields.value.length;
if (cols <= 3) return 'min-w-[36rem]';
if (cols <= 5) return 'min-w-[48rem]';
return 'min-w-[56rem]';
});
/** 明细表列数(含库存插入列与操作列),供履约摘要 rowspan/colspan。 */
const linesTableColumnCount = computed(() => {
let count = 1 + visibleLineSchemaFields.value.length + 1; // # + schema + ops
if (!showLineInventoryColumns.value) return count;
if (hasVisibleQtyField.value) {
count += visibleLineSchemaFields.value.filter((field) => isQtySchemaField(field)).length * 2;
} else {
count += 2;
}
return count;
});
/**
* 履约摘要展示用正式任务号。
*/
const fulfillmentDetailTaskNo = computed(() => String(
activeCase.value?.confirmed_task_no
|| authoritativeOrderTaskNo.value
|| reviewProgressContext.value?.current_task_no
|| '',
).trim());
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);
};
/**
* 当前聚焦字段的草稿值,供 LLM 建议面板做三方对比。
*/
const focusedLlmDraftValue = computed(() => {
const fieldId = String(focusedFieldId.value || '');
if (!fieldId || !activeCase.value?.draft) return null;
const lineKey = focusedLineKey.value;
if (lineKey) {
const line = (activeCase.value.draft.lines || []).find(
(item) => String((item as { draft_line_id?: string }).draft_line_id || '') === String(lineKey),
);
if (!line) return null;
return draftValue(line as Record<string, unknown>, fieldId);
}
const header = activeCase.value.draft.header_values as Record<string, unknown> | undefined;
return header ? draftValue(header, fieldId) : null;
});
/**
* 读取投影字段元数据(值来源 / 锁定 / 覆盖原因)。
* @param container - 表头或明细草稿容器
* @param fieldId - Schema field_id
*/
const draftFieldMeta = (
container: Record<string, unknown> | undefined,
fieldId: string,
): ShippingOrderReviewDraftFieldMeta => {
const metaMap = container?.field_meta as Record<string, ShippingOrderReviewDraftFieldMeta> | undefined;
if (metaMap?.[fieldId]) return metaMap[fieldId];
const values = container?.values as Record<string, { source?: string; locked?: boolean }> | undefined;
const entry = values?.[fieldId];
if (entry && typeof entry === 'object') {
const source = String(entry.source || 'manual') as ShippingOrderReviewValueSource;
return { value_source: source, locked: Boolean(entry.locked) };
}
return { value_source: 'machine', locked: false };
};
/**
* 将 value_source 映射为复核页来源文案。
* @param source - 后端投影来源枚举
*/
const valueSourceLabel = (source?: ShippingOrderReviewValueSource | string) => {
const normalized = String(source || 'machine');
const key = `chat.shippingOrderReview.valueSources.${normalized}`;
return te(key) ? t(key) : t('chat.shippingOrderReview.valueSources.machine');
};
/**
* 组装字段血缘/覆盖详情说明,供来源徽章 title 与无障碍文案。
* @param meta - 投影字段元数据
*/
const fieldMetaDetail = (meta: ShippingOrderReviewDraftFieldMeta) => {
return fieldMetaLineageRows(meta)
.map((row) => `${row.label}: ${row.value}`)
.join(' · ');
};
/**
* 将 field_meta 拆成结构化血缘行,供 line_no 来源徽章浮层展示。
* @param meta - 投影字段元数据
*/
const fieldMetaLineageRows = (meta: ShippingOrderReviewDraftFieldMeta) => {
const rows: Array<{ label: string; value: string }> = [
{
label: t('chat.shippingOrderReview.lineage.source'),
value: valueSourceLabel(meta.value_source),
},
];
if (meta.locked) {
rows.push({
label: t('chat.shippingOrderReview.lineage.locked'),
value: t('chat.shippingOrderReview.lockedHint'),
});
}
return rows;
};
const machineValueByIdFor = (fields: Array<Record<string, unknown>>, fieldId: string) => {
const field = fields.find((item) => String(item.field_id || '') === fieldId);
return field ? machineValue(field) : '';
};
/**
* 遗留响应仍可能携带 reparse_in_progress;该值已从 ReviewStatusMessage 联合类型移除
* (解析进度改由 lifecycle_progress 承载),此处仅作为运行时兜底,避免重新渲染旧黄色横幅。
*/
const legacyReparseInProgress: string = 'reparse_in_progress';
const statusBannerText = computed(() => {
// 解析中的反馈完全由五阶段导航下方的 lifecycle_progress 承载;兼容旧响应时
// 也不得重新渲染黄色 reparse 横幅。
if (!statusMessage.value || statusMessage.value === legacyReparseInProgress) return '';
const key = `chat.shippingOrderReview.statusBanner.${statusMessage.value}`;
return te(key) ? t(key) : t('chat.shippingOrderReview.statusBanner.unknown');
});
const reviewProgressVersionLabel = computed(() => {
const versionNo = reviewProgressContext.value?.displayed_version?.version_no
?? reviewProgressContext.value?.current_version_no;
if (!versionNo) return '';
return t('chat.shippingSessionWorkItem.versionLabel', { version: versionNo });
});
const pendingAction = ref<ReviewConfirmAction | null>(null);
const actionDialogOpen = ref(false);
/** 当前 DOM 编辑会话的最后 input 值;没有 input 前不得接受孤立的 change。 */
const pendingLineFieldInputValues = ref(new Map<string, string>());
/**
* 已提交的明细编辑键。用于屏蔽旧 DOM 节点在异步刷新后补发的 change,
* 真正的跨端并发仍由后端 Draft version 乐观锁处理。
*/
const committedLineEditValues = ref(new Map<string, string>());
/** 提交正式任务当前 Gate 已授权的精确动作;不再提供任务级泛化 retry。 */
const submitFormalGateAction = async (
actionCode: string,
payload?: Record<string, unknown>,
) => {
if (
Boolean(activeCase.value?.task_missing)
|| progressRetrying.value
|| caseSwitchLoading.value
) return;
if (!(await ensureFormalTaskDetailReady())) return;
const normalizedCode = String(actionCode || '').trim();
const gate = formalTaskDetail.value?.ui_state?.process_gate;
const authorized = formalTaskActions.value.some((action) => (
action.enabled && String(action.code || '').trim() === normalizedCode
));
// [§2.4 单源] A 已展示的主/侧路动作与右卡同源,允许作为写路径授权(B.actions 可能滞后)。
const aPrimary = String(currentTaskUiState.value?.primary_action?.code || '').trim();
const aAuthorized = Boolean(normalizedCode) && (
normalizedCode === aPrimary
|| (currentTaskUiState.value?.secondary_actions || []).some(
(action) => action.enabled && String(action.code || '').trim() === normalizedCode,
)
);
// [STEP] 阶段能力分支:capability 命中优先按 enabled/disabled_reason 裁决,
// 仅在未命中能力时回退到 A 展示授权或 B.actions / Gate noAction 校验。
const capability = formalPreparationContext.value?.capabilities?.find(
(c) => String(c.action_code || '') === normalizedCode,
);
if (capability) {
if (!capability.enabled) {
msg.info(capability.disabled_reason
? t(`chat.shippingOrderReview.lifecycle.prepare.capabilityDisabled.${capability.disabled_reason}`)
: t('workspace.shippingNotice.processGate.noAction'));
return;
}
} else if (!normalizedCode || !gate || !(authorized || aAuthorized)) {
msg.info(t('workspace.shippingNotice.processGate.noAction'));
return;
}
// 能力执行仍经由当前 Gate 裁决;无 Gate 时(含 enabled 能力路径)禁止执行。
if (!gate) {
msg.info(t('workspace.shippingNotice.processGate.noAction'));
return;
}
progressRetrying.value = true;
try {
const result = await submitProcessGatePrimaryAction(gate, {
actionCode: normalizedCode,
payload,
// 阶段能力(enabled)跳过门禁 serverRecoveryAction 守卫,由后端按
// execute_stage_capability 审批;非能力动作保持服务端校验不变。
stageCapabilityBypass: Boolean(capability),
});
if (result.outcome === 'submitted' || result.outcome === 'refresh_needed') {
progressRetrying.value = false;
handleGateRecoveryAccepted();
}
} catch (error) {
msg.error(resolveReviewErrorMessage(error));
} finally {
progressRetrying.value = false;
}
};
/**
* 底栏仅保留建单前 STP 的专用重试;正式 OT 只在当前 Gate 卡执行精确动作。
*/
const onFooterRetryAutomation = async () => {
await retryStpAutoCreate();
};
/**
* STP 自动建单失败 / manual_fallback:调用专用 retry API 重新入队。
* 核心逻辑:与确认后 auto_progress 重试分离;成功后刷新 Case 投影。
*/
const retryStpAutoCreate = async () => {
const caseNo = String(activeCase.value?.case_no || '').trim();
if (!caseNo || progressRetrying.value || caseSwitchLoading.value) return;
progressRetrying.value = true;
try {
const result = await retryWorkspaceShippingOrderStpAutoCreate(caseNo);
if (result.case) {
activeCase.value = result.case;
} else {
await reloadLatestDraft();
}
handleGateRecoveryAccepted();
msg.success(t('chat.shippingOrderReview.autoProgress.retryStpSuccess'));
} catch (error) {
msg.error(resolveReviewErrorMessage(error));
} finally {
progressRetrying.value = false;
}
};
/**
* 滚动到工作台锚点(data-testid)。
*/
function scrollWorkbenchAnchor(testId: string | null | undefined) {
const id = String(testId || '').trim();
if (!id) return;
void nextTick(() => {
document
.querySelector(`[data-testid="${id}"]`)
?.scrollIntoView({ behavior: 'smooth', block: 'start' });
});
}
/**
* 确保正式任务详情已加载且身份一致,再委托 TaskTodoPanel。
*
* @returns 是否可继续 invoke
*/
async function ensureFormalTaskDetailReady(): Promise<boolean> {
// 正式任务详情本身是当前工作台的身份锚点;Case 导航尚未回填 confirmed_task_no
// 时不能因此吞掉恢复动作。
const taskNo = String(
confirmedNoticeTaskNo.value
|| formalTaskDetail.value?.task_no
|| formalTaskDetail.value?.order_task_no
|| authoritativeOrderTaskNo.value
|| '',
).trim();
if (!taskNo) {
msg.warning(t('chat.shippingOrderReview.workbench.resultNotReady'));
return false;
}
if (!formalTaskDetail.value || formalTaskDetail.value.task_no !== taskNo) {
await loadFormalTaskDetail();
}
if (!formalTaskDetail.value || formalTaskDetail.value.task_no !== taskNo) {
msg.warning(t('chat.shippingOrderReview.workbench.resultNotReady'));
return false;
}
return true;
}
/**
* 统一动作栏点击:经注册表派发到显式执行器(禁止散落 if / Gate POST / 盲调 API)。
*/
const onUnifiedProcessingAction = async (item: ActionPresentationItem) => {
if (flowActionBusy.value) return;
// 建单后库存源别名须解析为 todo_panel,禁止再走候选面板。
const entry = resolveWorkbenchActionItem(item, {
postCreate: hasCreatedShippingTask.value,
});
if (!entry) {
return;
}
if (entry.isWrite && !workbenchActionsExecutable.value) {
return;
}
flowActionBusy.value = true;
try {
const behavior = entry.reviewBehavior;
if (behavior === 'hidden_on_review' || behavior === 'refresh_strip_only') {
return;
}
if (behavior === 'open_customer_dialog') {
// [A1] 先滚动客户面板,再打开既有确认弹窗;禁止直调确认 API。
scrollWorkbenchAnchor(entry.scrollTestId || 'review-customer-resolution-panel');
const taskNo = String(
confirmedNoticeTaskNo.value
|| activeCase.value?.confirmed_task_no
|| activeCase.value?.order_task_no
|| authoritativeOrderTaskNo.value
|| '',
).trim();
if (taskNo && typeof page.openShippingCustomerDialog === 'function') {
await page.openShippingCustomerDialog(taskNo);
return;
}
const panel = customerResolutionWideRef.value;
if (panel?.openSelectDialog) {
await panel.openSelectDialog();
return;
}
msg.warning(t('chat.shippingOrderReview.workbench.resultNotReady'));
return;
}
if (behavior === 'focus_field_conflicts') {
scrollWorkbenchAnchor(entry.scrollTestId || 'review-field-conflict-panel');
if (fieldConflictPanelRef.value?.focusFirstConflict) {
fieldConflictPanelRef.value.focusFirstConflict();
} else {
const first = activeCase.value?.field_conflicts?.[0];
if (first) {
focusFieldConflict({
fieldCode: first.field_code,
lineIndex: first.line_index ?? null,
draftLineId: (first as typeof first & { draft_line_id?: string | null }).draft_line_id ?? null,
});
}
}
return;
}
if (behavior === 'focus_duplicate_panel') {
scrollWorkbenchAnchor(entry.scrollTestId || 'review-duplicate-panel');
duplicatePanelRef.value?.focusAdjudication?.();
void nextTick(() => {
document
.querySelector('[data-testid="review-duplicate-actions"]')
?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
});
return;
}
if (behavior === 'focus_profile_panel') {
void router.replace({ query: { ...route.query, focus: 'profile' } });
scrollWorkbenchAnchor(entry.scrollTestId || 'review-profile-match-panel');
return;
}
if (behavior === 'focus_inventory_issues') {
// 正式 OT 后禁止切完整库存工作台;仅滚动到明细 / 兜底卡。
if (hasFormalOt.value) {
scrollWorkbenchAnchor(entry.scrollTestId || 'review-order-lines-table');
return;
}
workbenchMode.value = 'inventory';
scrollWorkbenchAnchor(entry.scrollTestId || 'review-inventory-issue-list');
return;
}
if (behavior === 'view_result') {
// 后端指定生命周期目标时,这是“进入阶段”而不是“查看最终结果”。
// 通知准备必须允许在 Excel 尚未生成、详情请求失败或仍在刷新时看到已知库存事实。
if (item.targetLifecycleStage) {
await selectLifecycleStage(item.targetLifecycleStage);
return;
}
// 未指定目标才是旧兼容的查看结果动作;详情未返回时先加载再定位。
viewResultLoading.value = true;
try {
workbenchMode.value = 'formal_task';
const expectedTaskNo = String(confirmedNoticeTaskNo.value || '').trim();
if (expectedTaskNo) {
const ready = await ensureFormalTaskDetailReady();
if (!ready) return;
if (String(formalTaskDetail.value?.task_no || '').trim() !== expectedTaskNo) {
msg.warning(t('chat.shippingOrderReview.workbench.resultNotReady'));
return;
}
}
await nextTick();
const resultEl = document.querySelector('[data-testid="review-formal-task-result-region"]');
if (resultEl) {
resultEl.scrollIntoView({ behavior: 'smooth', block: 'start' });
msg.info(t('chat.shippingOrderReview.workbench.actionSuccess'));
} else {
scrollWorkbenchAnchor('review-formal-task-todo-panel');
msg.info(t('chat.shippingOrderReview.workbench.resultNotReady'));
}
} finally {
viewResultLoading.value = false;
}
return;
}
if (behavior === 'view_record') {
openAuditTrail();
return;
}
if (behavior === 'download') {
if (!confirmedNoticeTaskNo.value) {
msg.warning(t('chat.shippingOrderReview.workbench.resultNotReady'));
return;
}
await downloadWorkspaceShippingExcelFile(confirmedNoticeTaskNo.value);
await loadFormalTaskDetail();
await refreshShippingProcessing();
msg.success(t('chat.shippingOrderReview.workbench.actionSuccess'));
return;
}
if (behavior === 'submit_gate_action') {
await submitFormalGateAction(item.actionCode);
return;
}
if (behavior === 'todo_panel') {
const todoCode = entry.todoActionCode || item.actionCode;
if (todoCode === 'mark_manual_uploaded') {
openManualUploadRegistration();
return;
}
workbenchMode.value = 'formal_task';
if (!(await ensureFormalTaskDetailReady())) return;
scrollWorkbenchAnchor(entry.scrollTestId || 'review-formal-task-todo-panel');
const authorized = formalTaskActions.value.find((action) => (
action.enabled && String(action.code || '').trim() === todoCode
));
if (!authorized) return;
const formalGate = formalTaskDetail.value?.ui_state?.process_gate;
if (!formalGate) return;
const result = await submitProcessGatePrimaryAction(formalGate, { actionCode: authorized.code });
if (result.outcome === 'submitted' || result.outcome === 'refresh_needed') {
handleGateRecoveryAccepted();
}
return;
}
} catch (error: unknown) {
msg.warning(error instanceof Error ? error.message : t('errors.generic'));
} finally {
flowActionBusy.value = false;
}
};
const reportSave = async (action: () => Promise<unknown> | null) => {
try { await action(); }
catch (error) {
const message = resolveReviewErrorMessage(error);
msg.error(message);
}
};
/** 保存并校验的入队状态来自后端 resume_outcome;页面不自行推断下一流程节点。 */
const onValidate = async () => {
try {
const resume = await validate();
showReviewResumeOutcome(resume, msg, t, t('chat.shippingOrderReview.saveOrderAndValidateSuccess'));
} catch (error) {
msg.error(resolveReviewErrorMessage(error));
}
};
const reportDisposition = async (action: () => Promise<unknown> | null) => {
try { await action(); }
catch (error) {
const message = resolveReviewErrorMessage(error);
msg.error(message);
}
};
/**
* 将复核写路径错误映射为用户可见文案;建单资格阻断使用专用 i18n。
*/
const resolveReviewErrorMessage = (error: unknown) => {
if (error instanceof BusinessError && error.code === REVIEW_BUILD_ELIGIBILITY_BLOCKED) {
return t('chat.shippingOrderReview.buildEligibility.confirmBlocked');
}
return error instanceof BusinessError ? error.message : t('errors.generic');
};
/**
* 重新匹配库存路由(行级或整单);进度复用 saving。
*/
const onInventoryRoutingReroute = async (draftLineId?: string) => {
await reportSave(() => rerouteInventoryRouting(draftLineId));
};
/** 打开指定类型的二次确认弹窗。 */
const openActionDialog = (action: ReviewConfirmAction) => {
pendingAction.value = action;
actionDialogOpen.value = true;
};
/**
* 明细字段变更:内部项次 line_no 只读,其余字段仅在值实际变化时 patch。
*
* 核心逻辑:Vue 重新渲染可能让已替换的 input 再触发旧的 change 事件;先同 Draft
* 真值比较可阻止旧空值覆盖刚保存的人工料号,后端乐观锁仍负责跨端并发保护。
* @param line - 当前明细行
* @param field - Schema 字段
* @param value - 输入框新值
*/
const onLineFieldChange = (
line: Record<string, unknown>,
field: { field_id: string; field_code: string },
value: string,
) => {
const lineKey = String(line.draft_line_id || '');
if (!lineKey) return;
if (field.field_code === 'line_no') return;
const editKey = `${lineKey}:${field.field_id}`;
if (pendingLineFieldInputValues.value.get(editKey) !== value) return;
pendingLineFieldInputValues.value.delete(editKey);
const currentLine = (activeCase.value?.draft?.lines || []).find(
(item) => String(item.draft_line_id || '') === lineKey,
) as Record<string, unknown> | undefined;
const currentValue = currentLine ? draftValue(currentLine, field.field_id) : draftValue(line, field.field_id);
if (value === currentValue || value === committedLineEditValues.value.get(editKey)) return;
committedLineEditValues.value.set(editKey, value);
void reportSave(async () => {
try {
await patchLine(lineKey, field.field_id, value);
} finally {
if (committedLineEditValues.value.get(editKey) === value) {
committedLineEditValues.value.delete(editKey);
}
}
});
};
/**
* 明细输入过程回调;仅内部项次需要即时未保存提示。
*/
const onLineFieldInput = (
line: Record<string, unknown>,
field: { field_id: string; field_code: string },
value: string,
) => {
const lineKey = String(line.draft_line_id || '');
if (!lineKey) return;
pendingLineFieldInputValues.value.set(`${lineKey}:${field.field_id}`, value);
if (field.field_code === 'line_no') return;
};
/**
* 明细单元格展示值:覆盖弹窗打开或编辑中时优先显示待提交值,避免与草稿真值漂移。
*/
const lineFieldDisplayValue = (
line: Record<string, unknown>,
field: { field_id: string; field_code: string },
) => {
return draftValue(line, field.field_id);
};
/**
* 确认弹窗提交:按 action 分发至对应写操作。
* 核心逻辑:质量异常/非订单/重识别携带 reasonCode + comment,供后端统一审计复盘。
* @param payload - 弹窗确认载荷
*/
const submitPendingAction = async (payload: ReviewConfirmPayload) => {
const action = pendingAction.value;
if (!action) return;
try {
if (action === 'confirm') {
if (!canConfirmBuild.value) {
msg.error(t('chat.shippingOrderReview.buildEligibility.confirmBlocked'));
return;
}
const response = await confirm();
// [STEP] 统一解析器:禁止仅凭 HTTP/confirm_ok 判定推进成功。
const parsed = parseOrderReviewConfirmResponse(response);
if (parsed) {
confirmSuccess.value = {
taskNo: parsed.taskNo,
orderTaskNo: parsed.orderTaskNo,
confirmOk: parsed.confirmOk,
autoProgress: parsed.autoProgressStarted,
progressFailed: parsed.progressFailed,
progressStatus: parsed.progressStatus,
progressMessage: parsed.progressMessage,
position: parsed.position,
restoredFromProjection: false,
};
if (parsed.progressFailed) {
msg.warning(t('chat.shippingOrderReview.confirmProgressFailed', { taskNo: parsed.taskNo }));
}
}
return;
}
if (action === 'reparse') {
// 重识别的新版 Case 由 composable 轮询确认落位;页面仅保存一次性导航许可,
// 以便区分系统恢复的自动切换与用户等待期间的手动阶段查看。
const sourceCaseNo = String(activeCase.value?.case_no || '').trim();
const documentId = activeReviewDocumentId();
pendingReparseNavigation.value = sourceCaseNo && documentId > 0
? { sourceCaseNo, documentId, runNo: null, preferredStage: null, cancelled: false }
: null;
const response = await reparseDocument(payload.reasonCode || 'document_quality', payload.comment);
if (pendingReparseNavigation.value) {
pendingReparseNavigation.value.runNo = String(response?.run?.run_no || '').trim() || null;
}
return;
}
if (action === 'non_order') {
await markNonOrder(payload.reasonCode || 'non_order', payload.comment);
return;
}
if (action === 'quality_issue') {
await markQualityIssue(payload.reasonCode || 'other', payload.comment);
return;
}
} catch (error) {
const message = resolveReviewErrorMessage(error);
msg.error(message);
} finally {
pendingAction.value = null;
}
};
/**
* 切换 Case 前统一关闭附属面板,避免旧 Case 侧栏内容残留。
*/
const closeAuxiliaryPanelsForCaseSwitch = () => {
auditTrailOpen.value = false;
processDetailOpen.value = false;
fulfillmentDetailLineKey.value = null;
closeFulfillmentOpen.value = false;
closeFulfillmentLineKeys.value = [];
panelState.value = {
...panelState.value,
eligibilityDetailsOpen: false,
llmSuggestionOpen: false,
versionHistoryOpen: false,
};
// [NO-OPTIMISTIC MEMORY] 行级就地编辑是「点保存才生效」的实提交,未保存的编辑草稿
// 不得跨文件/切换残留(否则会把上一文件的未保存意图带进新行)。切换即丢弃草稿,
// 行回到后端 selected_source_code / source_code,用户须重新进入编辑并保存。
cancelInlineEdit();
};
/**
* 从目标队列项读取后端已裁决的生命周期入口。
*
* @param queueItem - 与目标 Case 对应的 Queue DTO;允许旧快照的 camelCase 兼容字段。
* @param preferredStage - 用户在本次重解析等待期间手动选择的阶段。
* @returns 新版仍授权的手动阶段,或目标 Case 的后端 current 阶段;无法裁决时返回 null。
*/
function resolveQueueLifecycleStage(
queueItem: (typeof documentNavItems.value)[number] | undefined,
preferredStage: ReviewLifecycleStageCode | null = null,
): ReviewLifecycleStageCode | null {
const rawQueueItem = queueItem as (typeof queueItem & {
lifecycleEntries?: ShippingProcessingLifecycleEntry[];
intakeParseAuthorized?: boolean;
}) | undefined;
const entries = rawQueueItem?.lifecycle_entries || rawQueueItem?.lifecycleEntries || [];
const preferred = entries.find((entry) => entry.code === preferredStage);
if (
preferredStage
&& LIFECYCLE_STAGE_CODES.includes(preferredStage)
&& lifecycleEntryIsEnterable(preferred)
) {
return preferredStage;
}
const current = entries.find((entry) => entry.state === 'current');
if (current && LIFECYCLE_STAGE_CODES.includes(current.code as ReviewLifecycleStageCode)) {
return current.code as ReviewLifecycleStageCode;
}
return rawQueueItem?.intake_parse_authorized === true || rawQueueItem?.intakeParseAuthorized === true
? 'intake_parse'
: null;
}
/**
* 原子同步已落位目标 Case 的可分享深链。
*
* 核心逻辑:仅消费 Queue 的 source_run_no、case_no 与 lifecycle_entries,不由 Run 状态或
* 前端默认阶段猜测;供重解析恢复与“跳到当前版本”复用,避免两条自动路径口径分叉。
*/
async function syncTargetCaseRoute(
target: { runNo: string; caseNo: string; documentId?: number },
preferredStage: ReviewLifecycleStageCode | null = null,
): Promise<ReviewLifecycleStageCode | null> {
const targetDocumentId = Number(target.documentId || 0);
const queueItem = documentNavItems.value.find((item) => (
item.case_no === target.caseNo
&& (!targetDocumentId || Number(item.document_id || 0) === targetDocumentId)
));
const lifecycleStage = resolveQueueLifecycleStage(queueItem, preferredStage);
await router.replace({
query: {
...route.query,
run_no: target.runNo,
case_no: target.caseNo,
case: undefined,
document_id: targetDocumentId > 0 ? String(targetDocumentId) : undefined,
lifecycle_stage: lifecycleStage || undefined,
},
});
return lifecycleStage;
}
/**
* 新版重解析 Case 落位后的受控导航。
*
* 只对同一原始 PDF 的当前一次重解析生效;用户未干预时进入后端 current,手动选择仍被
* 新版 lifecycle_entries 授权时保留。其它文件/历史版本的显式查看不会触发此路径。
*/
async function handleReparseCaseReady(target: { runNo: string; caseNo: string; documentId: number }) {
const pending = pendingReparseNavigation.value;
if (
!pending
|| pending.cancelled
|| pending.documentId !== target.documentId
|| (pending.runNo && pending.runNo !== target.runNo)
) return;
const selectedStage = await syncTargetCaseRoute(target, pending.preferredStage);
if (selectedStage && selectedStage === pending.preferredStage) {
lifecycleStagePinnedByUserForCase.value = target.caseNo;
}
pendingReparseNavigation.value = null;
}
/**
* 实际切换 Case(无未保存拦截)。
* 核心逻辑:清理证据焦点与确认成功条;非 dock 关闭证据模式;只更新 URL,
* 由 run/case watch 在同 Run 内走轻量 selectCase,避免整页 load 误报历史版与加载中。
*/
const select = async (caseNo: string) => {
const queueItem = documentNavItems.value.find((item) => item.case_no === caseNo);
if (caseNo !== String(activeCase.value?.case_no || '').trim()) {
cancelPendingReparseNavigation();
}
// 文件切换是展示上下文切换,不是流程推进。仅消费目标文件后端已下发的
// current entry;目标未获生命周期授权时清除旧文件留下的深链阶段,保持 fail-closed。
const selectedLifecycleStage = resolveQueueLifecycleStage(queueItem);
const sourceRunNo = String(queueItem?.source_run_no || runNo.value).trim();
if (sourceRunNo && sourceRunNo !== String(reviewRun.value?.run_no || '').trim()) {
pendingCrossRunCaseNo.value = caseNo;
try {
// 先进入切换态并清掉上一 OT 投影权威,再改路由;否则 load() 完成前会出现
// 「文件 B 高亮 + 库存/右卡仍是 A」的串味。工作台壳仍保留(无大骨架)。
beginCrossRunSwitch(caseNo);
formalTaskDetailGeneration += 1;
formalTaskDetail.value = null;
formalTaskDetailLoadFailed.value = false;
formalTaskDetailLoading.value = false;
// 先原子提交目标 Run/Case/阶段深链,再读取目标 Case。否则 load() 期间旧文件的
// lifecycle watcher 会把 target stage 写回,形成“文件 B + 阶段 A”的错误组合。
await router.replace({ query: {
...route.query,
run_no: sourceRunNo,
case_no: caseNo,
case: undefined,
lifecycle_stage: selectedLifecycleStage || undefined,
} });
} finally {
pendingCrossRunCaseNo.value = null;
}
return;
}
const wasDocked = panelState.value.pdfDocked && panelState.value.pdfOpen;
const switchingToCurrent = Boolean(
reviewProgressContext.value?.current_case_no
&& caseNo === reviewProgressContext.value.current_case_no
&& isViewingHistoricalVersion.value,
);
focusedEvidenceRef.value = null;
confirmSuccess.value = null;
closeAuxiliaryPanelsForCaseSwitch();
// [STEP 1] 浮窗模式关闭;dock 保留布局。切到当前版本强制关浮窗(G19)。
if (!wasDocked || switchingToCurrent) {
if (workbenchMode.value === 'evidence') {
workbenchMode.value = 'standard';
}
panelState.value = {
...panelState.value,
pdfOpen: wasDocked && !switchingToCurrent,
pdfExpanded: false,
pdfDocked: wasDocked && !switchingToCurrent ? panelState.value.pdfDocked : false,
eligibilityDetailsOpen: false,
};
}
// [STEP 2] 先轻量加载目标 Case,再同步 URL;watch 见已是当前 Case 则跳过二次 load。
await selectCase(caseNo);
const docId = activeCase.value?.document?.id;
const nextQuery: Record<string, unknown> = {
...route.query,
case_no: caseNo,
// 读取旧链接时仍兼容 case;后续任意导航统一写回 case_no,避免同一 Case
// 出现两套 URL 状态而使文件切换和外部生命周期深链互相覆盖。
case: undefined,
};
delete nextQuery.focus;
delete nextQuery.candidate;
if (docId != null) nextQuery.document_id = String(docId);
else delete nextQuery.document_id;
if (selectedLifecycleStage) nextQuery.lifecycle_stage = selectedLifecycleStage;
else delete nextQuery.lifecycle_stage;
await router.replace({ query: nextQuery as typeof route.query });
if (wasDocked && !switchingToCurrent && panelState.value.pdfOpen) {
void ensurePreviewLoaded(caseNo);
}
};
/** 未保存本地修改数(与底栏提示、切换拦截同源)。 */
const unsavedEditCount = computed(() => 0);
const hasUnsavedEdits = computed(() => false);
/**
* 请求切换 OT:有未保存修改时硬拦截。
*/
const requestSelectCase = async (caseNo: string) => {
if (caseNo === activeCase.value?.case_no) return;
if (hasUnsavedEdits.value) {
pendingSwitchCaseNo.value = caseNo;
unsavedSwitchOpen.value = true;
return;
}
await select(caseNo);
};
/**
* 放弃本地未保存修改并切换。
*/
const discardAndSwitchCase = async () => {
const target = pendingSwitchCaseNo.value;
unsavedSwitchOpen.value = false;
pendingSwitchCaseNo.value = null;
if (target) await select(target);
};
/**
* 保存校验后切换(丢弃无法单独落库的行号 pending,再走 validate)。
*/
const saveAndSwitchCase = async () => {
const target = pendingSwitchCaseNo.value;
await onValidate();
unsavedSwitchOpen.value = false;
pendingSwitchCaseNo.value = null;
if (target) await select(target);
};
/** 用户在版本历史面板显式打开的 Case:这类查看保留只读横幅,不做自动跳转。 */
const explicitlyViewedHistoricalCaseNos = ref(new Set<string>());
/** 已尝试过自动跳转的 Case:目标缺失时防止 watch 循环重试。 */
const autoJumpAttemptedCaseNos = ref(new Set<string>());
/**
* 版本历史面板选择:历史版本只读打开,当前版本正常编辑。
*/
const selectVersionFromHistory = async (caseNo: string) => {
// 显式查看记录在案:这是用户主动回看,不触发自动跳转。
cancelPendingReparseNavigation();
explicitlyViewedHistoricalCaseNos.value.add(String(caseNo || '').trim());
await select(caseNo);
await refreshWorkItemContext(conversationId.value, reviewProgressContext.value?.item_no || itemNoFromQuery.value);
};
/**
* 跳转至工作项当前版本 Case。
* 核心逻辑:统一由 openCurrentVersion 按 Stream 队列裁决目标;队列接口异常
* 不再静默无反应,load 未真正落位(内部回滚旧快照)也按失败提示。
* @returns 是否成功落到当前版本。
*/
const jumpToCurrentVersion = async (): Promise<boolean> => {
try {
const target = await openCurrentVersion();
if (!target || String(activeCase.value?.case_no || '').trim() !== target.caseNo) {
msg.warning(t('chat.shippingOrderReview.currentVersionUnavailable'));
return false;
}
await syncTargetCaseRoute({ runNo: target.runNo, caseNo: target.caseNo });
return true;
} catch (error) {
const message = error instanceof BusinessError ? error.message : t('errors.generic');
msg.error(message);
return false;
}
};
/**
* 历史版本自动跳转:重新解析完成后,工作台重新落在被替代 Case 上的所有路径
* (重开/刷新页面、会话卡批次重解析、深链进入)都不会再触发旧的重识别轮询,
* 这里统一兜底自动切换到 Stream 当前版本,替代仅出横幅提示;
* 版本历史面板的显式查看(explicitlyViewedHistoricalCaseNos)保持停留。
*/
watch(
[isViewingHistoricalVersion, () => String(activeCase.value?.case_no || '').trim(), runLoading, caseSwitchLoading],
async ([historical, caseNo, runBusy, switchBusy]) => {
if (!historical || !caseNo || runBusy || switchBusy) return;
if (explicitlyViewedHistoricalCaseNos.value.has(caseNo)) return;
if (autoJumpAttemptedCaseNos.value.has(caseNo)) return;
autoJumpAttemptedCaseNos.value.add(caseNo);
if (await jumpToCurrentVersion()) {
msg.success(t('chat.shippingOrderReview.autoJumpedToCurrentVersion'));
}
},
);
/**
* 草稿版本冲突后重新加载服务端最新 Case,丢弃本地过期编辑。
*/
const onReloadLatestDraft = async () => {
try {
await reloadLatestDraft();
msg.success(t('chat.shippingOrderReview.versionConflict.reloaded'));
} catch (error) {
const message = error instanceof BusinessError ? error.message : t('errors.generic');
msg.error(message);
}
};
/**
* 退出复核模式回到普通对话,并携带一次性任务焦点。
* 核心逻辑:普通对话不绑定 Run/Case/文档;仅保留 conversation_id 与
* focus_task_no,供右侧任务卡聚焦后立即消费。
*/
const back = () => {
const activeConversationId = String(route.query.conversation_id || conversationId.value || '').trim();
const focusTask = String(
route.query.focus_task_no
|| confirmSuccess.value?.orderTaskNo
|| '',
).trim();
const nextQuery: Record<string, string> = {};
if (activeConversationId) nextQuery.conversation_id = activeConversationId;
if (focusTask) {
nextQuery.focus_task_no = focusTask;
nextQuery.focus_notice = '1';
}
void router.replace({
name: 'Chat',
params: { agentId: agentId.value },
query: nextQuery,
});
};
/**
* 就地重试加载复核 Run/Case(不依赖整页刷新)。
*/
function retryLoad() {
const nextRun = runNo.value;
if (!nextRun) return;
void load(nextRun, String(route.query.case || route.query.case_no || '') || undefined, {
conversationId: conversationId.value || undefined,
itemNo: itemNoFromQuery.value || undefined,
});
}
watch(
() => activeCase.value,
() => {
hydrateConfirmProgressFromCase();
},
{ immediate: true, deep: true },
);
watch(
[() => confirmSuccess.value, showWorkflowProgress, hasCreatedShippingTask],
([confirm, workflow, hasTask]) => {
// [STEP] 确认建单/正式 OT 后保持 standard 主编辑面,禁止自动切 formal_task 空壳。
// formal_task 仅由 Footer/registry 显式动作(如查看处理结果)进入。
if (confirm || workflow || hasTask) {
if (workbenchMode.value === 'confirm_progress') {
workbenchMode.value = 'standard';
}
return;
}
if (
workbenchMode.value === 'confirm_progress'
|| workbenchMode.value === 'formal_task'
) {
workbenchMode.value = 'standard';
}
},
);
watch(
[
lifecycleActiveStageCode,
hasFormalOt,
intakeParseContextAuthorized,
// 接收解析文件互切时 stage/授权通常不变;必须以 Case 变化触发新附件/邮件上下文重载,
// 否则接收解析工作面停留上一份 PDF 的附件名且预览不再自动加载。
() => String(activeCase.value?.case_no || '').trim(),
],
([code, , intakeAuthorized]) => {
// 确认进度是当前阶段内的短暂辅助视图,不由生命周期页签覆盖。
if (workbenchMode.value === 'confirm_progress') return;
// 未收到后端 lifecycle_entries 时只保留 Case 编辑上下文;禁止默认订单复核
// surface 反向成为前端阶段裁决。
if (code === null) return;
syncLifecycleWorkbenchMode(code);
if (code === 'intake_parse' && intakeAuthorized && intakeTargetCaseNo.value) {
void ensureIntakeParseContextLoaded(intakeTargetCaseNo.value);
}
},
{ immediate: true },
);
// [REFRESH_ON_CHANGE] 订单经自动推进后 formalTaskDetail 会 stale(阶段页签/右侧动作/表格数字不更新,需手动刷新)。
// 用处理投影的 progressVersion(后端"领域服务单调推进"的版本号,只在真实状态变化时增加)做变化检测:
// 版本一变 → 刷新正式详情 → 页面整体更新(阶段/按钮/表格数字);版本不变(每 3s 轮询同值)→ 不刷新,非常驻轮询。
watch(
() => shippingProcessingProjection.value?.progressVersion,
(next, previous) => {
if (next == null) return;
if (previous == null || next !== previous) {
if (formalTaskDetail.value) void loadFormalTaskDetail();
}
},
);
watch(
() => [
lifecycleCurrentStageCode.value,
String(activeCase.value?.case_no || '').trim(),
activeReviewDocumentId(),
] as const,
async (current, previous) => {
const [currentStage, currentCaseNo, currentDocumentId] = current;
const [previousStage, previousCaseNo, previousDocumentId] = previous || [];
if (await syncPendingReleaseAutoAdvance()) return;
// 切换文件时生命周期阶段会随新 Case 一起变更;这不是当前文件的自动推进,
// 不能跳转或弹出“已自动推进”提示。
if (
!previous
|| currentCaseNo !== previousCaseNo
|| currentDocumentId !== previousDocumentId
) return;
if (!currentStage || !previousStage || currentStage === previousStage) return;
const pendingReparse = pendingReparseNavigation.value;
if (
pendingReparse
&& !pendingReparse.cancelled
&& pendingReparse.preferredStage
&& pendingReparse.documentId === activeReviewDocumentId()
) return;
// 只响应后端 current 阶段的真实推进:用户点击已完成阶段只会改路由,
// 绝不能触发自动跳转而被带回当前阶段。
// 无 lifecycle_stage 深链 = 尚未钉工作面,视为仍跟随系统(与「仍停在旧 current」同权)。
const requested = String(route.query.lifecycle_stage || '').trim();
const followingSystem = !requested || requested === previousStage;
if (!followingSystem) return;
if (lifecycleStagePinnedByUserForCase.value === String(activeCase.value?.case_no || '').trim()) return;
const previousIndex = LIFECYCLE_STAGE_CODES.indexOf(previousStage);
const currentIndex = LIFECYCLE_STAGE_CODES.indexOf(currentStage);
if (previousIndex < 0 || currentIndex <= previousIndex) return;
await selectLifecycleStage(currentStage, { replace: true });
// 自动推进落点一次性提示:告知系统已带到新阶段;用户仍可点页签回看原阶段。
msg.success(t('chat.shippingOrderReview.lifecycle.autoAdvanced', {
stage: t(`chat.shippingOrderReview.lifecycle.stages.${currentStage}`),
}));
},
);
/** 通知准备详情失败时保留可见诊断和重试入口,禁止静默空白。 */
function retryFormalTaskDetail() {
void loadFormalTaskDetail();
}
/**
* 【裁决 C(2026-09-01)】下游阶段首屏默认不拉复核编辑器(省请求),集合按工作面的
* Case 依赖收窄:
* - 仅 `freight_upload` 移出(2026-09-01 裁决 C):货代上传工作面零 Case 依赖(只读
* formalTaskDetail.ui_state 与 freightNoticeGroups),进入该阶段自动补拉 Case 纯属浪费请求;
* - `fulfillment_prep` 有意保留:通知准备渲染已单源(行矩阵只认 ui_state.stage_context.preparation),
* 但波次出单/缺口放行写路径仍依赖 Case——confirmPreparationWave / confirmReleaseInventoryShortage
* 需要 case_no + draft_version,preparationWaveSelectableLines 读 displayCase.line_fulfillment。
* 该自动补拉是写路径必需的已知暂留债务;根治 = 后续计划「波次出单写路径改源到任务级」,
* 完成后随任务把 fulfillment_prep 一并移出本集合;
* - 通知准备只补 Case、不补 Evidence;订单复核/接收解析补 Case+Evidence(含从准备切回时补证据)。
*/
const REVIEW_EDITOR_NEEDED_STAGES: ReviewLifecycleStageCode[] = ['intake_parse', 'order_review', 'fulfillment_prep'];
watch(
// 用户查看面(含回看已完成阶段)驱动 Case 懒加载:选法 2 正式下游切 PDF 后 activeCase
// 为 null,回看接收解析/订单复核/通知准备时必须按需补拉目标 Case,否则这些工作面
// 只能渲染空白或残留上一份 PDF 的数据。
// [2026-09-17] 初次装配(initialLoading/runLoading)未完成前必须让位:loadReviewCase
// 会自增 caseLoadGeneration,令在途 load() 的 finally 跳过 initialLoading 清旗,
// 首屏永久卡在「正在加载复核结果...」且 run/queue 永不装配。装配完成后由旗标
// 翻转重新触发本 watcher,按当前 stage 补拉 Case。
[lifecycleActiveStageCode, initialLoading, runLoading],
([stage]) => {
if (initialLoading.value || runLoading.value) return;
if (!stage || !REVIEW_EDITOR_NEEDED_STAGES.includes(stage)) return;
// 禁止使用 displayCase 兜底:它可能停留在上一份 PDF 的快照上造成串味;
// 目标一律取当前工作面的 activeCase 或切换管线的 requestedCaseNo。
const caseNo = String(activeCase.value?.case_no || requestedCaseNo.value || '').trim();
if (!caseNo) return;
if (stage === 'fulfillment_prep') {
if (activeCase.value) return;
void loadReviewCase(caseNo, { includeEvidence: false });
return;
}
// intake_parse / order_review:需要复核编辑器(Case + Evidence)
void loadReviewCase(caseNo, { includeEvidence: true });
},
);
watch(
hasFormalOt,
(hasFormalTask) => {
// 生命周期阶段以正式任务 ui_state 为准;预载只读投影,不触发库存、导出或上传命令。
// 这里是页面初始化/Case 切换的读取路径,详情暂不可用只能由阶段工作面展示
// 加载态或可重试诊断;不能调用面向用户动作的 ensure*,否则会把异步加载中的
// 详情错误提示为“处理结果尚未生成”。
if (hasFormalTask) void loadFormalTaskDetail();
},
{ immediate: true },
);
watch(
[runNo, () => String(route.query.case || route.query.case_no || ''), conversationId, itemNoFromQuery],
([nextRun, nextCase, nextConversationId, nextItemNo], previous) => {
if (!nextRun) return;
const prevRun = previous?.[0] ? String(previous[0]) : '';
const activeNo = String(activeCase.value?.case_no || '').trim();
const sameRunLoaded = Boolean(
reviewRun.value?.run_no
&& String(reviewRun.value.run_no) === String(nextRun)
&& prevRun === String(nextRun),
);
// [STEP] 同 Run 仅切换 PDF/Case:走轻量 selectCase,禁止整页 load 清空进度与闪「正在加载」。
if (sameRunLoaded && nextCase) {
if (nextCase === activeNo) return;
void selectCase(nextCase);
return;
}
void load(nextRun, nextCase || undefined, {
conversationId: nextConversationId || undefined,
itemNo: nextItemNo || undefined,
});
},
{ immediate: true },
);
watch(
() => reviewRun.value?.run_no,
(resolvedRunNo) => {
if (resolvedRunNo && resolvedRunNo !== runNo.value) {
const resolvedCaseNo = String(
pendingCrossRunCaseNo.value
|| requestedCaseNo.value
|| route.query.case_no
|| route.query.case
|| activeCase.value?.case_no
|| '',
).trim();
void router.replace({
query: {
...route.query,
run_no: resolvedRunNo,
case: undefined,
case_no: resolvedCaseNo || undefined,
},
});
}
},
);
</script>
<template>
<main
class="flex h-full min-h-0 flex-1 flex-col overflow-hidden bg-surface-soft text-primary"
data-testid="shipping-order-review-view"
:data-readonly="isReviewContentReadOnly ? 'true' : 'false'"
:data-workbench-mode="workbenchMode"
>
<ReviewWorkbenchHeader
:run-no="runNo"
:item-no="reviewProgressContext?.item_no"
:version-label="reviewProgressVersionLabel"
:selected-order-summary="selectedOrderSummaryText"
:saving="saving"
:save-failed="saveFailed"
:draft-conflict="Boolean(draftConflict)"
:is-read-only="isReviewContentReadOnly"
:show-version-history="Boolean(activeCase)"
:show-audit-trail="Boolean(activeCase)"
@back="back"
@open-version-history="openVersionHistory"
@open-audit-trail="openAuditTrail"
/>
<div
v-if="statusBannerText"
class="mx-4 mt-3 rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-100"
data-testid="review-status-banner"
>
<div class="flex flex-wrap items-center justify-between gap-2">
<div class="min-w-0 flex-1 space-y-1">
<span>{{ statusBannerText }}</span>
<p
v-if="draftConflict"
class="text-xs text-amber-800 dark:text-amber-200"
data-testid="review-version-conflict-hint"
>
{{ t('chat.shippingOrderReview.versionConflict.hint', {
local: draftConflict.localVersion,
server: draftConflict.serverVersion ?? t('chat.shippingOrderReview.versionConflict.unknownServer'),
}) }}
</p>
</div>
<div class="flex flex-wrap items-center gap-2">
<button
v-if="draftConflict"
type="button"
class="rounded border border-amber-400 px-2 py-1 text-xs font-medium hover:bg-amber-100 dark:hover:bg-amber-900"
data-testid="reload-latest-draft"
:disabled="saving"
@click="onReloadLatestDraft"
>
{{ t('chat.shippingOrderReview.versionConflict.reload') }}
</button>
<button
v-if="draftConflict"
type="button"
class="rounded border border-amber-400 px-2 py-1 text-xs font-medium hover:bg-amber-100 dark:hover:bg-amber-900"
data-testid="toggle-draft-conflict-diff"
@click="toggleConflictDiff"
>
{{ draftConflict.showDiff
? t('chat.shippingOrderReview.versionConflict.hideDiff')
: t('chat.shippingOrderReview.versionConflict.viewDiff') }}
</button>
<button
v-if="isViewingHistoricalVersion"
type="button"
class="rounded border border-amber-400 px-2 py-1 text-xs font-medium hover:bg-amber-100 dark:hover:bg-amber-900"
data-testid="jump-to-current-version"
@click="jumpToCurrentVersion"
>
{{ t('chat.shippingOrderReview.jumpToCurrentVersion') }}
</button>
</div>
</div>
<ul
v-if="draftConflict?.showDiff && draftConflictDiffLines.length"
class="mt-2 list-disc space-y-0.5 pl-5 text-xs"
data-testid="review-version-conflict-diff"
>
<li v-for="line in draftConflictDiffLines" :key="line">{{ line }}</li>
</ul>
<p
v-else-if="draftConflict?.showDiff"
class="mt-2 text-xs"
data-testid="review-version-conflict-diff-empty"
>
{{ t('chat.shippingOrderReview.versionConflict.diffUnavailable') }}
</p>
</div>
<!-- 确认后统一进度主路径留在本页;返回对话仅作次要聚焦链接。 -->
<div v-if="initialLoading" class="p-8 text-sm text-secondary">{{ 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"
data-testid="shipping-order-review-load-failed"
>
<p>{{ t('chat.shippingOrderReview.unavailable') }}</p>
<button
type="button"
class="mt-3 inline-flex items-center gap-1 rounded border border-current/30 px-3 py-1.5 text-xs font-medium hover:bg-black/5 dark:hover:bg-white/5"
data-testid="shipping-order-review-retry-load"
@click="retryLoad"
>
<RefreshCw class="h-3.5 w-3.5" />
{{ t('chat.shippingOrderReview.retryLoad') }}
</button>
</div>
<div v-else class="min-h-0 flex-1 overflow-y-auto" data-testid="review-workbench-scroll">
<section class="flex flex-col gap-2 p-2.5 lg:p-3">
<div
v-if="showWorkbenchGrid"
:class="reviewDocumentNavigationUsesSidebar
? (reviewDocumentNavigationCollapsed
? 'grid gap-2 lg:grid-cols-[5rem_minmax(0,1fr)] lg:items-start lg:gap-3'
: 'grid gap-2 lg:grid-cols-[16rem_minmax(0,1fr)] lg:items-start lg:gap-3')
: 'contents'"
data-testid="review-workbench-ot-shell"
>
<ReviewDocumentNavigation
:items="documentNavItems"
:active-case-no="requestedCaseNo || displayCase?.case_no"
:nav-aria-label="t('chat.shippingOrderReview.documentNavigation')"
@mode-change="(mode) => { reviewDocumentNavigationMode = mode; }"
@collapse-change="(collapsed) => { reviewDocumentNavigationCollapsed = collapsed; }"
@select="(caseNo) => { void requestSelectCase(caseNo); }"
/>
<div
class="min-w-0 flex-1 space-y-2"
:class="reviewDocumentNavigationUsesSidebar ? '' : 'contents'"
>
<div class="flex flex-col gap-2" data-testid="review-workbench-status-region">
<section v-if="showWorkbenchGrid" data-testid="review-run-lifecycle-progress" aria-live="polite">
<ReviewLifecycleStageNavigation
:stages="lifecycleNavigationItems"
:active-code="lifecycleNavigationActiveCode"
:processing-code="lifecycleProcessingStageCode"
:available-actions="activeCase?.available_actions || []"
:retrying="intakeParseRetrying"
@select="(code) => { void selectLifecycleStage(code); }"
@open-detail="() => { processDetailOpen = true; }"
@retry-parse="() => void retryCurrentIntakeParse()"
/>
<p
v-if="runProgressHintText"
class="mt-2 px-2.5 py-1 text-xs text-secondary"
data-testid="review-run-lifecycle-current-step"
aria-live="polite"
>{{ runProgressHintText }}</p>
</section>
</div>
<template v-if="showWorkbenchGrid">
<div
v-if="caseSwitchFailed"
class="rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-900 dark:border-rose-900 dark:bg-rose-950/40 dark:text-rose-100"
data-testid="review-case-switch-failed"
>
<p>{{ t('chat.shippingOrderReview.caseSwitchFailed') }}</p>
<div
class="mt-3 space-y-2"
aria-hidden="true"
data-testid="review-case-switch-failed-skeleton"
>
<div class="h-4 w-2/5 animate-pulse rounded bg-rose-200/70 dark:bg-rose-900/50" />
<div class="h-10 w-full animate-pulse rounded bg-rose-200/70 dark:bg-rose-900/50" />
<div class="h-24 w-full animate-pulse rounded bg-rose-200/70 dark:bg-rose-900/50" />
</div>
<button
type="button"
class="mt-3 rounded border border-rose-300 px-2 py-1 text-xs hover:bg-rose-100 dark:border-rose-800 dark:hover:bg-rose-950"
data-testid="review-case-switch-retry"
@click="() => { const target = requestedCaseNo; if (target) void selectCase(target); }"
>
{{ t('chat.shippingOrderReview.caseSwitchRetry') }}
</button>
</div>
<div
v-if="runSwitchFailed"
class="rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-900 dark:border-rose-900 dark:bg-rose-950/40 dark:text-rose-100"
data-testid="review-run-switch-failed"
>
<p>{{ t('chat.shippingOrderReview.unavailable') }}</p>
<button
type="button"
class="mt-3 rounded border border-rose-300 px-2 py-1 text-xs hover:bg-rose-100 dark:border-rose-800 dark:hover:bg-rose-950"
data-testid="review-run-switch-retry"
@click="retryLoad"
>
{{ t('chat.shippingOrderReview.retryLoad') }}
</button>
</div>
<div
v-if="showWorkbenchCaseShell"
class="relative space-y-2 transition-opacity duration-150"
:class="(caseSwitchLoading || runLoading) ? 'pointer-events-none opacity-70' : ''"
data-testid="review-case-workbench-shell"
:data-case-switching="(caseSwitchLoading || runLoading) ? '1' : '0'"
:data-case-switch-failed="caseSwitchFailed ? '1' : '0'"
:data-case-projection-version="caseProjectionVersion ?? ''"
:aria-busy="(caseSwitchLoading || runLoading) ? 'true' : 'false'"
>
<div
v-if="caseSwitchLoading || runLoading"
class="absolute right-3 top-3 z-30 inline-flex items-center gap-2 rounded-full border border-brand-200 bg-surface/95 px-3 py-1.5 text-xs text-secondary shadow-sm dark:border-brand-800"
data-testid="review-case-switch-indicator"
role="status"
>
<span class="h-2 w-2 animate-pulse rounded-full bg-brand-500" aria-hidden="true" />
{{ caseLoadingContext?.message || t('chat.shippingOrderReview.caseSwitchLoading') }}
</div>
<ReviewWorkbenchModeToggle
v-if="workbenchMode === 'evidence'"
:mode="workbenchMode"
:can-enter-inventory="canEnterInventory"
@set-mode="onWorkbenchModeChange"
/>
<!-- 窄屏:阻断卡 + 当前处理卡(对象级重试优先于此) -->
<div
class="space-y-2 xl:hidden"
data-testid="review-primary-blockers-narrow"
>
<ReviewCurrentProcessingCard
v-if="mountCurrentProcessingCard"
:stage-code="currentProcessingStageDisplay.code"
:stage-label-key="currentProcessingStageDisplay.labelKey"
:stage-inconsistent="currentProcessingStageDisplay.inconsistent"
:task-missing="Boolean(displayCase?.task_missing)"
:task-no="displayCase?.confirmed_task_no || displayCase?.post_confirm_auto_progress?.task_no"
:confirmed-task-id="displayCase?.confirmed_task_id"
:show-admin-diagnosis="showAdminTaskMissingDiagnosis"
:automation="displayCase?.automation"
:show-retry="showObjectRetryOnRail"
:user-status="currentTaskUserStatus"
:retryable="visibleCurrentTaskRetryable"
:blocking-reason="currentTaskBlockingReason"
:gate-status="currentTaskGateStatus"
:primary-action="visibleCurrentTaskPrimaryAction"
:recovery-actions="visibleCurrentTaskRecoveryActions"
:retrying="taskRetryButtonDisabled || progressRetrying || caseSwitchLoading"
:loading="caseContentSkeleton || formalTaskProjectionPending || formalTaskDetailLoading"
:status-detail="currentTaskStatusDetail"
@action="(code, params) => void handleCurrentTaskAction(code, params)"
/>
<ReviewBuildEligibilitySummary
v-if="showEligibilityAsPrimary"
:eligibility="buildEligibility"
:field-conflicts="displayCase?.field_conflicts"
:customer-resolved="Boolean(displayCase?.customer_resolution?.resolved)"
:field-labels="reviewFieldLabels"
:exception-count="exceptionTargets.length"
:exception-ordinal="exceptionOrdinal"
:focus-buildability="hasActiveBusinessGate"
@open-details="openEligibilityDetails"
@navigate-exception="navigateExceptionField"
/>
<ReviewCompletedChecksPanel
:items="displayCase?.completed_checks"
/>
<ReviewProfileMatchPanel
class="hidden xl:block"
:profile-match="displayCase?.profile_match"
/>
</div>
<div
class="grid gap-3 xl:grid-cols-[minmax(0,1fr)_minmax(260px,0.35fr)]"
data-testid="review-workbench-grid"
>
<div
ref="mainEditorScrollEl"
class="min-h-0 min-w-0 space-y-3"
data-testid="review-main-editor"
>
<!-- 阶段主内容固定在左列;右列复用唯一 Gate 卡,避免文件/库存与操作区割裂。 -->
<section
v-if="hasCreatedShippingTask && isLifecycleFulfillmentPrep"
class="rounded-xl border border-default bg-surface p-4 shadow-sm"
data-testid="review-lifecycle-fulfillment-prep"
>
<div data-testid="review-formal-task-result-region" :data-view-result-loading="viewResultLoading ? '1' : '0'">
<template v-if="preparationSurfaceReady">
<div class="flex flex-wrap items-start justify-between gap-3 border-b border-default pb-3">
<div>
<h3 class="text-sm font-semibold text-primary">{{ t('chat.shippingOrderReview.lifecycle.prepare.title') }}</h3>
<p class="mt-1 text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.prepare.subtitle') }}</p>
</div>
<span
v-if="formalPreparationContext?.status"
class="rounded-full bg-brand-50 px-2.5 py-1 text-xs font-medium text-brand-700 dark:bg-brand-950/30 dark:text-brand-300"
>{{ formalPreparationStatusLabel(formalPreparationContext?.status) }}</span>
</div>
<div v-if="formalPreparationDisplayLines.length" class="review-fulfillment-prep-workspace mt-4 rounded-lg border border-default" data-testid="review-fulfillment-prep-workspace">
<!-- 标题与选行操作条固定不参与横向滚动,仅表头/表体横向滑动。 -->
<div class="flex items-center justify-between gap-3 border-b border-default bg-surface-muted/30 px-3 py-2">
<div class="text-xs font-semibold text-primary">{{ t('chat.shippingOrderReview.lifecycle.prepare.matchWorkspace') }}</div>
<span class="text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineCount', { count: formalPreparationDisplayLines.length }) }}</span>
</div>
<div v-if="preparationEditable && formalHeaderEditable()" class="flex flex-wrap items-center justify-between gap-2 border-b border-default bg-brand-50/50 px-3 py-2 text-xs dark:bg-brand-950/20">
<div class="flex items-center gap-3 text-secondary">
<span class="font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.selectReady') }}</span>
<span>{{ t('chat.shippingOrderReview.fulfillmentDecision.selectedCount', { count: selectedPreparationSnapshotLineIds.length }) }}</span>
</div>
<button type="button" class="rounded-lg bg-emerald-600 px-3 py-1.5 font-medium text-white disabled:opacity-50" data-testid="review-fulfillment-prep-confirm-wave" :disabled="preparationWaveBusy || !selectedPreparationSnapshotLineIds.length" @click="confirmPreparationWave">{{ preparationWaveBusy ? t('chat.shippingOrderReview.fulfillmentDecision.waving') : t('chat.shippingOrderReview.fulfillmentDecision.confirmWave', { count: selectedPreparationSnapshotLineIds.length }) }}</button>
</div>
<div class="overflow-x-auto overscroll-x-contain" data-testid="review-fulfillment-prep-table-scroll">
<table class="review-fulfillment-prep-table min-w-[1060px] text-xs">
<thead class="border-b border-default bg-surface-muted/50 text-left"><tr><th v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="allPreparationWaveSelected" :disabled="!preparationWaveSelectableLines.length || preparationWaveBusy" :aria-label="t('chat.shippingOrderReview.fulfillmentDecision.selectReady')" @change="toggleAllPreparationLineSelection(($event.target as HTMLInputElement).checked)"></th><th v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationCustomerPoLineLabel() }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultReservation') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultPartNumber') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.requiredQty') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.inventorySource') }}</th><th v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.odmConflict.column') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineStatus') }}</th><th class="review-fulfillment-sticky-action-head whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lineOps.moreActions') }}</th></tr></thead>
<tbody><template v-for="(line, lineIndex) in formalPreparationDisplayLines" :key="line.snapshot_line_id || `${line.reservation_id}-${line.part_number}`"><tr :class="Number(line.shortage_qty || 0) > 0 ? 'border-b border-amber-100 bg-amber-50/40 last:border-0 dark:border-amber-950 dark:bg-amber-950/10' : 'border-b border-default last:border-0'"><td v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="selectedPreparationSnapshotLineIds.includes(String(line.snapshot_line_id))" :disabled="preparationWaveBusy || !preparationWaveSelectableLines.some((item) => String(item.snapshot_line_id) === String(line.snapshot_line_id))" :aria-label="`${t('chat.shippingOrderReview.fulfillmentDecision.selectReady')}: ${preparationLineCustomerPoLine(line)}`" :data-testid="`review-fulfillment-line-select-${line.snapshot_line_id || lineIndex}`" @change="togglePreparationLineSelection(String(line.snapshot_line_id || lineIndex), ($event.target as HTMLInputElement).checked)"></td><td v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationLineCustomerPoLine(line) }}</td><td class="whitespace-nowrap px-3 py-2 font-medium text-primary"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.reservation_id" type="text" class="w-28 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultReservation')" :data-testid="`review-fulfillment-line-edit-reservation-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.reservation_id || '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.part_number" type="text" class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultPartNumber')" :data-testid="`review-fulfillment-line-edit-part-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else class="block max-w-[220px] truncate" :title="line.part_number || '—'">{{ line.part_number || '—' }}</span></td><td class="whitespace-nowrap px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input :value="editingLine.required_qty" type="number" min="0" step="any" class="w-20 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.requiredQty')" :data-testid="`review-fulfillment-line-edit-qty-${line.snapshot_line_id}`" @input="updateInlineEditQty(($event.target as HTMLInputElement).value)" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.required_qty ?? '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="isInlineEditing(line) && inlineSourceOptions(line).length"><select class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-fulfillment-line-edit-source-${line.snapshot_line_id}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="editingLine?.source_code" :disabled="inlineEditSaving" @change="updateInlineEditSource(($event.target as HTMLSelectElement).value)"><option v-for="option in inlineSourceOptions(line)" :key="option.value" :value="option.value">{{ option.label }}</option></select></template><span v-else class="block max-w-[220px] truncate" :title="formalPreparationLineSource(line)">{{ formalPreparationLineSource(line) || '—' }}</span></td><td v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2"><div v-if="(line.odm_values?.length || 0) > 1 && !formalPreparationSourceLocked" class="flex items-center gap-1" :data-testid="`review-line-odm-${line.snapshot_line_id || lineIndex}`"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-odm-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.odmConflict.title')" :value="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || line.chosen_odm_id || ''" @change="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.odmConflict.placeholder') }}</option><option v-for="value in line.odm_values" :key="value" :value="value">{{ value }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-odm-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || lineOdmBusy" :aria-label="t('chat.shippingOrderReview.odmConflict.confirm')" :title="t('chat.shippingOrderReview.odmConflict.hint')" @click="submitLineOdmChoice(line)"><Check class="h-3.5 w-3.5" /></button></div><span v-else class="font-mono text-xs">{{ line.chosen_odm_id || '—' }}</span></td><td class="whitespace-nowrap px-3 py-2">{{ line.available_qty ?? '—' }}</td><td class="whitespace-nowrap px-3 py-2 font-medium" :class="Number(line.shortage_qty || 0) > 0 ? 'text-amber-700 dark:text-amber-300' : 'text-emerald-700 dark:text-emerald-300'">{{ line.shortage_qty ?? '—' }}</td><td class="whitespace-nowrap px-3 py-2"><span class="rounded-full px-2 py-0.5" :class="Number(line.shortage_qty || 0) > 0 ? 'bg-amber-100 text-amber-800 dark:bg-amber-950/50 dark:text-amber-200' : 'bg-emerald-100 text-emerald-800 dark:text-emerald-200'">{{ formalPreparationLineStatusLabel(line) }}</span><span v-if="releaseBarHasFields(line)" class="ml-1 cursor-pointer rounded-full bg-rose-100 px-2 py-0.5 text-xs text-rose-800 dark:bg-rose-950/50 dark:text-rose-200" :title="releaseBarLineRequiredFields(line).map((field) => field.display_name).join('、')" :data-testid="`review-fulfillment-release-missing-${line.snapshot_line_id}`" @click="expandReleaseBar(line)">{{ t('chat.shippingOrderReview.releaseBar.missingBadge', { n: releaseBarLineRequiredFields(line).length }) }}</span></td><td class="review-fulfillment-sticky-action-cell whitespace-nowrap px-3 py-2"><div class="flex justify-center gap-1"><template v-if="editingLine && isInlineEditing(line)"><button type="button" class="rounded p-1.5 text-emerald-700 hover:bg-emerald-50 disabled:opacity-50" :disabled="inlineEditSaving" :data-testid="`review-fulfillment-line-save-${line.snapshot_line_id}`" :aria-label="t('chat.shippingOrderReview.inlineEdit.save')" :title="t('chat.shippingOrderReview.inlineEdit.save')" @click="saveInlineEdit(line)"><Check class="h-3.5 w-3.5" /></button><button type="button" class="rounded p-1.5 text-rose-700 hover:bg-rose-50 disabled:opacity-50" :disabled="inlineEditSaving" :data-testid="`review-fulfillment-line-cancel-${line.snapshot_line_id}`" :aria-label="t('chat.shippingOrderReview.inlineEdit.cancel')" :title="t('chat.shippingOrderReview.inlineEdit.cancel')" @click="cancelInlineEdit"><X class="h-3.5 w-3.5" /></button></template><template v-else><button type="button" class="rounded p-1.5 text-brand-700 hover:bg-brand-50 disabled:opacity-50" :disabled="formalPreparationSourceLocked || inlineEditBusy" :data-testid="`review-fulfillment-line-edit-${line.snapshot_line_id}`" :aria-label="t('chat.shippingOrderReview.lineActions.editLine')" :title="formalPreparationSourceLocked ? t('chat.shippingOrderReview.lifecycle.prepare.sourceLocked') : t('chat.shippingOrderReview.lineActions.editLine')" @click="startInlineEdit(line)"><Pencil class="h-3.5 w-3.5" /></button><div v-if="overflowItems(line).length"><button type="button" class="rounded p-1.5 text-brand-700 hover:bg-brand-50" :data-testid="`review-fulfillment-line-more-${line.snapshot_line_id}`" :aria-label="t('chat.shippingOrderReview.lineActions.more')" :title="t('chat.shippingOrderReview.lineActions.more')" @click="toggleOverflowMenu(String(line.snapshot_line_id), $event)"><MoreHorizontal class="h-3.5 w-3.5" /></button><Teleport to="body"><template v-if="overflowMenuOpenFor === String(line.snapshot_line_id)"><div class="fixed inset-0 z-[60]" @click="overflowMenuOpenFor = null"></div><div class="fixed z-[70] w-44 overflow-hidden rounded border border-default bg-surface py-1 shadow-lg" :style="{ top: `${overflowMenuPos.top}px`, left: `${overflowMenuPos.left}px` }"><button v-for="item in overflowItems(line)" :key="item.key" type="button" class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-xs text-default hover:bg-brand-50 dark:hover:bg-brand-950/40" @click="overflowMenuOpenFor = null; void item.run()"><component :is="item.icon" class="h-3.5 w-3.5 shrink-0" /> {{ t(item.labelKey) }}</button></div></template></Teleport></div></template></div></td></tr><tr v-if="releaseBarExpandedFor === releaseBarKey(line)" class="border-b border-amber-100 bg-amber-50/40 dark:border-amber-950 dark:bg-amber-950/10"><td :colspan="12" class="px-3 py-2"><div class="flex flex-wrap items-center gap-2 text-xs"><span class="font-medium text-secondary" :data-testid="`review-fulfillment-release-bar-${line.snapshot_line_id}`">{{ t('chat.shippingOrderReview.releaseBar.label') }}</span><label v-for="field in releaseBarLineRequiredFields(line)" :key="field.field_id" class="flex items-center gap-1"><span class="text-secondary">{{ field.display_name }}</span><input type="text" class="w-28 rounded border border-default bg-surface px-1.5 py-1" :value="releaseBarValue(line, field)" :disabled="releaseBarBusy[releaseBarKey(line)]" :aria-label="field.display_name" :data-testid="`review-fulfillment-release-input-${line.snapshot_line_id}-${field.field_id}`" @input="updateReleaseBarValue(line, field, ($event.target as HTMLInputElement).value)" /></label><button type="button" class="rounded bg-amber-600 px-2.5 py-1 text-xs font-medium text-white disabled:opacity-50" :disabled="!releaseBarReadyFor(line)" :data-testid="`review-fulfillment-release-confirm-${line.snapshot_line_id}`" @click="confirmReleaseBar(line)">{{ t('chat.shippingOrderReview.lifecycle.prepare.releaseConfirm') }}</button><button type="button" class="rounded border border-default px-2.5 py-1 text-xs text-secondary disabled:opacity-50" :data-testid="`review-fulfillment-release-cancel-${line.snapshot_line_id}`" @click="releaseBarExpandedFor = null">{{ t('chat.shippingOrderReview.inlineEdit.cancel') }}</button></div></td></tr></template></tbody>
</table>
</div>
</div>
<p v-else class="mt-3 rounded-lg border border-default bg-surface-muted/50 p-3 text-xs text-secondary" data-testid="review-fulfillment-prep-pending">
{{ t('chat.shippingOrderReview.lifecycle.prepare.pending') }}
</p>
</template>
<div v-else-if="formalTaskDetailPending" class="py-4 text-center text-xs text-muted">{{ t('workspace.shippingNotice.loading') }}</div>
<div v-else-if="formalTaskDetailLoadFailed" class="rounded-lg border border-rose-200 bg-rose-50 p-3 text-xs text-rose-700 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-300">
<p>{{ t('chat.shippingOrderReview.lifecycle.prepare.loadFailed') }}</p>
<button type="button" class="mt-2 rounded border border-current/30 px-2.5 py-1.5 font-medium hover:bg-black/5 dark:hover:bg-white/5" @click="retryFormalTaskDetail">{{ t('chat.shippingOrderReview.lifecycle.prepare.retry') }}</button>
</div>
<div v-else-if="!formalTaskDetail" class="rounded-lg border border-default bg-surface-muted/50 p-3 text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.prepare.detailUnavailable') }}</div>
</div>
</section>
<section
v-if="isLifecycleFulfillmentPrep && !hasCreatedShippingTask"
class="rounded-xl border border-default bg-surface p-3"
data-testid="review-lifecycle-fulfillment-prep-draft"
>
<h2 class="text-sm font-semibold text-primary">{{ t('chat.shippingOrderReview.lifecycle.prepare.title') }}</h2>
<p class="mt-1 text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.prepare.subtitle') }}</p>
<div class="mt-3">
<ReviewInventoryCandidatesPanel
:lines="routingRecoveryLines"
:source-labels="buildEligibility?.inventory_source_labels || {}"
:editable="editable"
:saving="saving"
@reroute="onInventoryRoutingReroute"
/>
</div>
</section>
<section
v-if="hasCreatedShippingTask && formalTaskDetail && isLifecycleFreightUpload"
class="rounded-xl border border-default bg-surface p-3"
data-testid="review-lifecycle-freight-upload"
>
<div class="flex flex-wrap items-start justify-between gap-3">
<div>
<h2 class="text-sm font-semibold text-primary">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.title') }}</h2>
<p class="mt-1 text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.subtitle') }}</p>
</div>
<span class="rounded-full bg-surface-muted px-2 py-1 text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.noticeCount', { count: freightNoticeGroups.length }) }}</span>
</div>
<div v-if="freightNoticeGroupsLoading" class="mt-3 text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.loading') }}</div>
<p v-else-if="freightNoticeGroupsLoadFailed" class="mt-3 rounded-lg border border-rose-200 bg-rose-50/70 p-3 text-xs text-rose-700 dark:border-rose-900 dark:bg-rose-950/20 dark:text-rose-200">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.loadFailed') }}</p>
<div v-else-if="freightNoticeGroups.length" class="mt-3 space-y-3" data-testid="review-freight-upload-groups">
<div class="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-default bg-surface-muted/30 px-3 py-2 text-xs" data-testid="review-freight-upload-batch-toolbar">
<span class="text-secondary">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.selected', { count: selectedFreightBusinessNos.length }) }}</span>
<div class="flex flex-wrap gap-2">
<button type="button" class="rounded border border-default px-2 py-1 disabled:opacity-50" :disabled="!selectedFreightBusinessNos.length || freightBatchBusy !== null" @click="void runFreightBatchAction('download')">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.batchDownload') }}</button>
<button type="button" class="rounded border border-default px-2 py-1 disabled:opacity-50" data-testid="review-freight-upload-batch-rpa" :disabled="!selectedFreightBusinessNos.length || selectedFreightNoticesContainUploaded || freightBatchBusy !== null" @click="void runFreightBatchAction('rpa')">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.batchRpa') }}</button>
<button type="button" class="rounded border border-default px-2 py-1 disabled:opacity-50" data-testid="review-freight-upload-batch-confirm" :disabled="!selectedFreightBusinessNos.length || selectedFreightNoticesContainUploaded || freightBatchBusy !== null" @click="void runFreightBatchAction('confirm')">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.batchConfirm') }}</button>
</div>
</div>
<div v-for="group in freightNoticeGroups" :key="group.business_no" class="rounded-lg border border-default" data-testid="review-freight-upload-notice">
<div class="flex flex-wrap items-center justify-between gap-3 border-b border-default bg-surface-muted/40 px-3 py-2 text-xs">
<label class="flex items-center gap-2 font-semibold text-primary"><input type="checkbox" :checked="selectedFreightBusinessNos.includes(group.business_no)" :aria-label="group.business_no" @change="toggleFreightNoticeSelection(group.business_no, ($event.target as HTMLInputElement).checked)"><span>{{ group.business_no }}</span></label>
<span class="text-secondary">PO: {{ group.po_number || '—' }} · {{ group.export_file_name || '—' }}</span>
<div class="flex items-center gap-2">
<span :class="freightUploadStatusDisplay(group).chipClass" :title="freightUploadStatusDisplay(group).reason || undefined" class="rounded-full px-2 py-0.5 font-medium cursor-help" tabindex="0">{{ freightUploadStatusDisplay(group).label }}</span>
<button type="button" class="rounded border border-brand-200 px-2 py-1 font-medium text-brand-700 hover:bg-brand-50" data-testid="review-freight-upload-download" :disabled="saving" @click="void downloadFreightNotice(group.business_no)">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.download') }}</button>
<button
v-if="canRunFreightNoticeAction(group, 'retry_freight_upload_rpa')"
type="button"
class="rounded border border-default px-2 py-1 font-medium text-primary hover:bg-surface-muted disabled:opacity-50"
data-testid="review-freight-upload-rpa"
:disabled="freightBatchBusy !== null"
@click="void runFreightNoticeAction(group, 'rpa')"
>{{ t('chat.shippingOrderReview.lifecycle.freightUpload.rpa') }}</button>
<button
v-if="canRunFreightNoticeAction(group, 'mark_manual_uploaded')"
type="button"
class="rounded border border-default px-2 py-1 font-medium text-primary hover:bg-surface-muted disabled:opacity-50"
data-testid="review-freight-upload-confirm"
:disabled="freightBatchBusy !== null"
@click="void runFreightNoticeAction(group, 'confirm')"
>{{ t('chat.shippingOrderReview.lifecycle.freightUpload.confirm') }}</button>
<details v-if="hasFreightNoticeMoreActions(group)" class="relative" data-testid="review-freight-upload-more">
<summary class="list-none rounded border border-default p-1 text-secondary hover:bg-surface" :aria-label="t('chat.shippingProcessing.action.more')"><MoreHorizontal class="h-3.5 w-3.5" aria-hidden="true" /></summary>
<div class="absolute right-0 top-7 z-10 flex min-w-40 flex-col gap-1 rounded border border-default bg-surface p-1 shadow-lg">
<button v-if="canRegenerateFreightNotice(group)" type="button" class="rounded px-2 py-1 text-left text-[11px] text-primary hover:bg-surface-muted disabled:opacity-50" :disabled="freightBatchBusy !== null" data-testid="review-freight-upload-regenerate" @click="void runFreightNoticeAction(group, 'regenerate')">{{ t('workspace.shippingNotice.processGate.actionCodes.regenerate_excel_artifact') }}</button>
</div>
</details>
</div>
</div>
<table class="min-w-full text-left text-xs"><thead class="border-b border-default bg-surface-muted/30"><tr><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.lineNo') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultPartNumber') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultReservation') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.requiredQty') }}</th></tr></thead><tbody><tr v-for="line in group.lines" :key="`${group.business_no}-${line.line_no}-${line.part_number}`" class="border-b border-default last:border-0" data-testid="review-freight-upload-line"><td class="px-3 py-2"><span :class="freightLineNoDisplay(line).muted ? 'text-muted' : ''" :title="freightLineNoDisplay(line).title">{{ freightLineNoDisplay(line).text }}</span></td><td class="px-3 py-2">{{ line.part_number || '—' }}</td><td class="px-3 py-2">{{ line.reservation_id || '—' }}</td><td class="px-3 py-2">{{ line.shipment_qty || '—' }}</td></tr></tbody></table>
</div>
</div>
<p v-else class="mt-3 rounded-lg border border-default bg-surface-muted/50 p-3 text-xs text-secondary">{{ freightNoticeGroupsReason === 'po_missing' ? t('chat.shippingOrderReview.lifecycle.freightUpload.poMissing') : t('chat.shippingOrderReview.lifecycle.freightUpload.empty') }}</p>
</section>
<section
v-if="hasCreatedShippingTask && formalTaskDetail && isLifecycleUploadComplete"
class="rounded-xl border border-emerald-200 bg-emerald-50/40 p-3 dark:border-emerald-900 dark:bg-emerald-950/20"
data-testid="review-lifecycle-upload-complete"
>
<h2 class="text-sm font-semibold text-primary">{{ t('chat.shippingOrderReview.lifecycle.uploadComplete.title') }}</h2>
<p class="mt-1 text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.uploadComplete.subtitle') }}</p>
<!-- 直入通知完成时分组可能仍在加载:与货代上传段一致先渲染 loading/失败占位,
仅在非加载/失败状态下渲染 batchCount 工具栏与列表/空态,避免直入闪「0 已上传/空」。 -->
<div v-if="freightNoticeGroupsLoading" class="mt-3 text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.loading') }}</div>
<p v-else-if="freightNoticeGroupsLoadFailed" class="mt-3 rounded-lg border border-rose-200 bg-rose-50/70 p-3 text-xs text-rose-700 dark:border-rose-900 dark:bg-rose-950/20 dark:text-rose-200">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.loadFailed') }}</p>
<template v-else>
<!-- 聚合头:本批已上传数量 + 留底下载(ZIP 打包全部已完成通知) -->
<div class="mt-3 flex flex-wrap items-center justify-between gap-2 rounded-lg border border-emerald-200 bg-surface px-3 py-2 text-xs dark:border-emerald-900" data-testid="review-upload-complete-toolbar">
<span class="font-medium text-emerald-900 dark:text-emerald-100">{{ t('chat.shippingOrderReview.lifecycle.uploadComplete.batchCount', { count: uploadedFreightNoticeGroups.length }) }}</span>
<button
type="button"
class="rounded border border-emerald-300 px-2 py-1 font-medium text-emerald-700 hover:bg-emerald-50 disabled:opacity-50 dark:border-emerald-700 dark:text-emerald-200 dark:hover:bg-emerald-950/40"
:disabled="!uploadedFreightNoticeGroups.length || uploadingBatchArchive"
data-testid="review-upload-complete-batch-download"
@click="void downloadCompletedBatchArchive()"
>
{{ uploadingBatchArchive
? t('chat.shippingOrderReview.lifecycle.uploadComplete.batchDownloading')
: t('chat.shippingOrderReview.lifecycle.uploadComplete.batchDownload') }}
</button>
</div>
<div v-if="uploadedFreightNoticeGroups.length" class="mt-3 space-y-3" data-testid="review-upload-complete-groups">
<div
v-for="group in uploadedFreightNoticeGroups"
:key="group.business_no"
class="rounded-lg border border-emerald-200 bg-surface/70 dark:border-emerald-900"
data-testid="review-upload-complete-notice"
>
<!-- 单据行:identity + 状态 + 单张下载 + 展开明细 -->
<div class="flex flex-wrap items-center justify-between gap-3 border-b border-emerald-200/70 px-3 py-2 text-xs dark:border-emerald-900/70">
<div class="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1">
<span class="font-semibold text-primary">{{ group.business_no }}</span>
<span class="inline-flex items-center gap-1 font-medium text-emerald-700 dark:text-emerald-300">
<Check class="h-3.5 w-3.5" aria-hidden="true" />
{{ t('chat.shippingOrderReview.lifecycle.uploadComplete.uploaded') }}
</span>
<span
v-if="freightUploadModeLabel(group.upload_mode)"
class="inline-flex items-center gap-1 rounded-full border border-emerald-300/60 bg-emerald-100/60 px-2 py-0.5 font-medium text-emerald-700 dark:border-emerald-700/60 dark:bg-emerald-950/40 dark:text-emerald-300"
data-testid="review-upload-complete-mode"
>
{{ freightUploadModeLabel(group.upload_mode) }}
</span>
<span class="text-secondary">{{ group.po_number ? `PO: ${group.po_number}` : '' }}</span>
</div>
<div class="flex items-center gap-2">
<button
type="button"
class="rounded border border-emerald-300 px-2 py-1 font-medium text-emerald-700 hover:bg-emerald-50 dark:border-emerald-700 dark:text-emerald-200 dark:hover:bg-emerald-950/40"
data-testid="review-upload-complete-download"
@click="void downloadFreightNotice(group.business_no)"
>{{ t('chat.shippingOrderReview.lifecycle.freightUpload.download') }}</button>
<button
type="button"
class="inline-flex items-center gap-1 rounded border border-default px-2 py-1 font-medium text-primary hover:bg-surface disabled:opacity-50"
:aria-expanded="expandedCompletedNoticeNo === group.business_no"
:aria-label="expandedCompletedNoticeNo === group.business_no
? t('chat.shippingOrderReview.lifecycle.uploadComplete.collapse')
: t('chat.shippingOrderReview.lifecycle.uploadComplete.expand')"
data-testid="review-upload-complete-toggle-lines"
@click="toggleCompletedNoticeLine(group.business_no)"
>
{{ expandedCompletedNoticeNo === group.business_no
? t('chat.shippingOrderReview.lifecycle.uploadComplete.collapse')
: t('chat.shippingOrderReview.lifecycle.uploadComplete.expand') }}
<ChevronDown class="h-3.5 w-3.5 transition-transform" :class="{ 'rotate-180': expandedCompletedNoticeNo === group.business_no }" aria-hidden="true" />
</button>
</div>
</div>
<div v-if="expandedCompletedNoticeNo === group.business_no" class="space-y-2 px-3 pb-3 pt-2 text-xs" data-testid="review-upload-complete-lines">
<p v-if="group.export_file_name" class="text-secondary">{{ t('chat.shippingOrderReview.lifecycle.uploadComplete.exportFile', { file: group.export_file_name }) }}</p>
<table class="min-w-full text-left">
<thead class="border-b border-default bg-surface-muted/30">
<tr>
<th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.lineNo') }}</th>
<th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultPartNumber') }}</th>
<th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultReservation') }}</th>
<th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.requiredQty') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="line in group.lines" :key="`${group.business_no}-${line.line_no}-${line.part_number}`" class="border-b border-default last:border-0" data-testid="review-upload-complete-line">
<td class="px-3 py-2"><span :class="freightLineNoDisplay(line).muted ? 'text-muted' : ''" :title="freightLineNoDisplay(line).title">{{ freightLineNoDisplay(line).text }}</span></td>
<td class="px-3 py-2">{{ line.part_number || '—' }}</td>
<td class="px-3 py-2">{{ line.reservation_id || '—' }}</td>
<td class="px-3 py-2">{{ line.shipment_qty ?? '—' }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p v-else class="mt-3 rounded-lg border border-emerald-200 bg-surface/70 p-3 text-xs text-secondary dark:border-emerald-900">{{ t('chat.shippingOrderReview.lifecycle.uploadComplete.empty') }}</p>
</template>
</section>
<ReviewIntakeParsePanel
v-if="isLifecycleIntakeParse"
:context="intakeParseContext"
:loading="intakeParseLoading"
:load-failed="intakeParseLoadFailed"
:preview-url="previewUrl || null"
:preview-loading="previewLoading"
@retry-context="() => { if (intakeTargetCaseNo) void ensureIntakeParseContextLoaded(intakeTargetCaseNo); }"
@load-preview="() => { if (intakeTargetCaseNo) void ensurePreviewLoaded(intakeTargetCaseNo); }"
/>
<!-- 仅「固定为侧栏」时 PDF 占网格列;默认浮窗挂在根节点,不挤压订单区。 -->
<div
v-if="showOrderReviewEditor"
:class="evidenceDocked
? 'grid gap-4 min-[1440px]:grid-cols-[minmax(280px,0.38fr)_minmax(420px,1fr)]'
: 'space-y-4'"
data-testid="review-editor-body"
:data-evidence-docked="evidenceDocked ? 'true' : 'false'"
>
<ReviewDocumentEvidenceDrawer
v-if="evidenceDocked"
:open="panelState.pdfOpen"
:pinned="panelState.pdfPinned"
:expanded="panelState.pdfExpanded"
:docked="true"
:float-side="panelState.pdfFloatSide"
:src="previewUrl"
:email-preview="selectedEvidenceIsEmail ? emailPreview : null"
:evidence="selectedEvidence"
:evidence-list="evidence || []"
:field-label="evidenceFieldLabel"
:draft-value="focusedLlmDraftValue"
:machine-value="evidenceMachineValue"
:value-source-label="evidenceValueSourceLabel"
:show-ai-actions="editable"
:reset-key="displayCase?.case_no || null"
@close="closeEvidenceMode"
@toggle-pin="togglePdfPinned"
@toggle-expand="togglePdfExpanded"
@toggle-dock="togglePdfDocked"
@toggle-side="togglePdfFloatSide"
@prev-evidence="navigateEvidence(-1)"
@next-evidence="navigateEvidence(1)"
@request-ai="requestSuggestion()"
@restore-machine="restoreEvidenceMachineValue"
/>
<div class="min-w-0 space-y-3" data-testid="review-order-form">
<section class="rounded-xl border border-default bg-surface p-4 shadow-sm">
<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-muted">{{ t('chat.shippingOrderReview.schemaVersion', { version: displayCase?.schema.schema_version_id || '-' }) }}</p>
</div>
<span v-if="isReviewContentReadOnly" class="rounded-full bg-surface-strong px-2 py-0.5 text-xs text-secondary">
{{ t('chat.shippingOrderReview.readOnly') }}
</span>
</div>
<div v-if="headerSchemaFields.length" class="mt-4 grid gap-3 md:grid-cols-2 2xl:grid-cols-3">
<div v-for="field in visibleHeaderSchemaFields" :key="field.field_id" class="min-w-0">
<div class="flex items-center justify-between gap-2 text-xs font-medium text-secondary">
<span class="truncate">{{ field.display_name }}<span v-if="field.required"> *</span></span>
<button
type="button"
class="shrink-0"
data-testid="review-field-locate"
:data-highlight-quality="fieldHighlightQuality(field.field_id)"
:data-locate-mode="isLocateDiagnoseOnly(fieldHighlightQuality(field.field_id)) ? 'diagnose' : 'locate'"
:class="locateIconButtonClass(fieldHighlightQuality(field.field_id))"
:aria-label="locateControlLabel(field.display_name, field.field_id)"
:title="locateControlLabel(field.display_name, field.field_id)"
@click="focusFieldEvidence(field.field_id)"
>
<Crosshair class="h-3.5 w-3.5" aria-hidden="true" />
</button>
</div>
<input
:value="draftValue(displayHeaderValues, field.field_id)"
:disabled="caseContentSkeleton || !canEditReviewField(field.field_id) || saving"
class="mt-1 w-full rounded-md border border-default bg-surface px-2.5 py-2 text-sm"
:class="{
'border-sky-400 ring-2 ring-sky-300 dark:border-sky-500 dark:ring-sky-700': isEvidenceLinkedField(field.field_id),
}"
data-testid="review-header-field-input"
:data-evidence-active="isEvidenceLinkedField(field.field_id) ? 'true' : 'false'"
:title="t('chat.shippingOrderReview.dblclickLocateHint')"
@focus="syncFieldFocus(field.field_id)"
@dblclick="focusFieldEvidence(field.field_id)"
@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-muted">
<span>{{ valueSourceLabel(draftFieldMeta(displayHeaderValues as Record<string, unknown> | undefined, field.field_id).value_source) }}</span>
<button v-if="!caseContentSkeleton && canEditReviewField(field.field_id)" 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-if="hiddenHeaderFieldCount > 0 || showAllHeaderFields" class="mt-3">
<button
type="button"
class="rounded border border-default px-2.5 py-1 text-xs hover-surface-soft"
data-testid="review-toggle-header-fields"
@click="showAllHeaderFields = !showAllHeaderFields"
>
{{ showAllHeaderFields
? t('chat.shippingOrderReview.collapseFields')
: t('chat.shippingOrderReview.moreFields', { count: hiddenHeaderFieldCount }) }}
</button>
</div>
<div v-else class="mt-4 rounded-lg border border-dashed border-default p-3 text-sm text-muted">
<p>{{ t('chat.shippingOrderReview.noMachineOrder') }}</p>
<div v-if="editable && displayCase?.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="openActionDialog('non_order')">{{ t('chat.shippingOrderReview.markNonOrder') }}</button>
</div>
</div>
</section>
<section class="rounded-xl border border-default bg-surface shadow-sm">
<div class="flex items-center justify-between gap-3 border-b border-default px-4 py-3">
<div>
<h3 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.lines') }}</h3>
<p class="mt-1 text-xs text-muted">{{ displayDraftLines.length }} {{ t('chat.shippingOrderReview.lines') }}</p>
</div>
<div class="flex flex-wrap items-center gap-2">
<button
v-if="hiddenLineFieldCount > 0 || showAllLineFields"
type="button"
class="rounded border border-default px-2 py-1 text-xs hover-surface-soft"
data-testid="review-toggle-line-fields"
@click="showAllLineFields = !showAllLineFields"
>
{{ showAllLineFields
? t('chat.shippingOrderReview.collapseFields')
: t('chat.shippingOrderReview.moreLineFields', { count: hiddenLineFieldCount }) }}
</button>
<button v-if="editable" type="button" :disabled="saving" class="inline-flex items-center gap-1 rounded border px-2 py-1 text-xs disabled:opacity-50" data-testid="review-add-line" @click="reportSave(() => addLine())">
<Plus class="h-3.5 w-3.5" />{{ t('chat.shippingOrderReview.addLine') }}
</button>
</div>
</div>
<div v-if="displayDraftLines.length" class="overflow-x-auto overscroll-x-contain" data-testid="review-lines-scroll">
<table :class="[linesTableMinWidthClass, 'w-full border-collapse text-left text-xs']">
<thead class="bg-surface-soft text-muted dark:bg-slate-950/40">
<tr>
<th class="sticky left-0 z-10 min-w-10 border-b border-default bg-surface-soft px-2 py-1.5 font-medium">#</th>
<template v-for="field in visibleLineSchemaFields" :key="field.field_id">
<th class="review-line-column-head border-b border-default px-2 py-1.5 font-medium" :style="lineColumnStyle(field)">
{{ field.display_name }}<span v-if="field.required"> *</span>
<button
type="button"
class="review-line-column-resizer"
:aria-label="t('chat.shippingOrderReview.resizeColumn', { label: field.display_name })"
:title="t('chat.shippingOrderReview.resizeColumn', { label: field.display_name })"
@mousedown.prevent="beginLineColumnResize(field, $event)"
@dblclick.prevent="resetLineColumnWidth(field)"
/>
</th>
<th
v-if="showLineInventoryColumns && isQtySchemaField(field)"
class="min-w-20 border-b border-default px-2 py-1.5 font-medium"
>
{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}
</th>
<th
v-if="showLineInventoryColumns && isQtySchemaField(field)"
class="min-w-16 border-b border-default px-2 py-1.5 font-medium"
>
{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}
</th>
</template>
<template v-if="showLineInventoryColumns && !hasVisibleQtyField">
<th class="min-w-20 border-b border-default px-2 py-1.5 font-medium">
{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}
</th>
<th class="min-w-16 border-b border-default px-2 py-1.5 font-medium">
{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}
</th>
</template>
<th class="sticky right-0 z-10 min-w-28 border-b border-default bg-surface-soft px-2 py-1.5">
<span class="sr-only">{{ t('chat.shippingOrderReview.fulfillmentDecision.actions') }}</span>
</th>
</tr>
</thead>
<tbody>
<template
v-for="(line, index) in displayDraftLines"
:key="String(line.draft_line_id || index)"
>
<tr
class="border-b border-subtle last:border-0"
:data-review-line-index="index"
>
<td class="sticky left-0 z-10 bg-surface px-2 py-1.5 font-medium">{{ index + 1 }}</td>
<template v-for="field in visibleLineSchemaFields" :key="field.field_id">
<td class="px-2 py-1.5 align-top" :style="lineColumnStyle(field)" :data-testid="isInventorySourceHintField(field) ? 'review-line-inventory-source' : undefined">
<div class="flex min-w-0 flex-col gap-0.5">
<div class="relative flex min-w-0 items-center gap-1">
<input
:value="lineFieldDisplayValue(line, field)"
:disabled="field.field_code === 'line_no' || !canEditReviewField(field.field_id) || saving"
class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs"
:class="{ 'border-sky-400 ring-2 ring-sky-300 dark:border-sky-500 dark:ring-sky-700': isEvidenceLinkedField(field.field_id, index), }"
data-testid="review-line-field-input"
:data-evidence-active="isEvidenceLinkedField(field.field_id, index) ? 'true' : 'false'"
:title="t('chat.shippingOrderReview.dblclickLocateHint')"
@focus="syncFieldFocus(field.field_id, index)"
@dblclick="focusFieldEvidence(field.field_id, index)"
@input="onLineFieldInput(line, field, ($event.target as HTMLInputElement).value)"
@change="onLineFieldChange(line, field, ($event.target as HTMLInputElement).value)"
>
<button
type="button"
class="shrink-0"
data-testid="review-line-field-locate"
:data-highlight-quality="fieldHighlightQuality(field.field_id, index)"
:data-locate-mode="isLocateDiagnoseOnly(fieldHighlightQuality(field.field_id, index)) ? 'diagnose' : 'locate'"
:class="locateIconButtonClass(fieldHighlightQuality(field.field_id, index))"
:aria-label="locateControlLabel(field.display_name, field.field_id, index)"
:title="locateControlLabel(field.display_name, field.field_id, index)"
@click="focusFieldEvidence(field.field_id, index)"
>
<Crosshair class="h-3.5 w-3.5" aria-hidden="true" />
</button>
<details
v-if="draftFieldMeta(line, field.field_id).value_source !== 'machine'"
class="relative shrink-0 min-w-0"
data-testid="review-field-lineage"
>
<summary
class="cursor-pointer list-none truncate whitespace-nowrap rounded bg-surface-strong px-1.5 py-0.5 text-[10px] text-secondary marker:content-none [&::-webkit-details-marker]:hidden"
:title="fieldMetaDetail(draftFieldMeta(line, field.field_id))"
:aria-label="fieldMetaDetail(draftFieldMeta(line, field.field_id))"
>
{{ valueSourceLabel(draftFieldMeta(line, field.field_id).value_source) }}
</summary>
<div
class="absolute right-0 top-full z-30 mt-1 w-56 rounded-md border border-default bg-surface p-2 shadow-md"
role="tooltip"
>
<dl class="grid gap-1.5">
<div
v-for="row in fieldMetaLineageRows(draftFieldMeta(line, field.field_id))"
:key="`${row.label}:${row.value}`"
class="min-w-0"
>
<dt class="text-[10px] font-medium text-muted">{{ row.label }}</dt>
<dd class="break-words text-[11px] text-secondary">{{ row.value }}</dd>
</div>
</dl>
</div>
</details>
</div>
</div>
</td>
<td
v-if="showLineInventoryColumns && isQtySchemaField(field)"
class="px-2 py-1.5 align-middle tabular-nums"
:class="draftLineFulfillmentFor(String(line.draft_line_id || ''))?.is_shortage ? 'font-medium text-rose-600 dark:text-rose-400' : ''"
>
{{ displayAvailableQty(draftLineFulfillmentFor(String(line.draft_line_id || ''))) }}
</td>
<td
v-if="showLineInventoryColumns && isQtySchemaField(field)"
class="px-2 py-1.5 align-middle tabular-nums"
:class="draftLineFulfillmentFor(String(line.draft_line_id || ''))?.is_shortage ? 'font-medium text-rose-600 dark:text-rose-400' : ''"
>
{{ displayShortageQty(draftLineFulfillmentFor(String(line.draft_line_id || ''))) }}
</td>
</template>
<template v-if="showLineInventoryColumns && !hasVisibleQtyField">
<td
class="px-2 py-1.5 align-middle tabular-nums"
:class="draftLineFulfillmentFor(String(line.draft_line_id || ''))?.is_shortage ? 'font-medium text-rose-600 dark:text-rose-400' : ''"
>
{{ displayAvailableQty(draftLineFulfillmentFor(String(line.draft_line_id || ''))) }}
</td>
<td
class="px-2 py-1.5 align-middle tabular-nums"
:class="draftLineFulfillmentFor(String(line.draft_line_id || ''))?.is_shortage ? 'font-medium text-rose-600 dark:text-rose-400' : ''"
>
{{ displayShortageQty(draftLineFulfillmentFor(String(line.draft_line_id || ''))) }}
</td>
</template>
<td class="sticky right-0 z-10 min-w-28 whitespace-nowrap bg-surface px-2 py-1.5">
<div class="flex items-center justify-end gap-0.5">
<button
type="button"
:disabled="!editable || saving"
class="rounded p-1.5 hover-surface-strong disabled:opacity-50"
data-testid="review-copy-line"
:aria-label="t('chat.shippingOrderReview.copyLine')"
:title="t('chat.shippingOrderReview.copyLine')"
@click="reportSave(() => copyLine(String(line.draft_line_id)))"
>
<Copy class="h-3.5 w-3.5" />
</button>
<button
type="button"
:disabled="!editable || saving || !canDeleteDraftLine(String(line.draft_line_id || ''))"
class="rounded p-1.5 hover-surface-strong disabled:opacity-50"
data-testid="review-delete-line"
:aria-label="t('chat.shippingOrderReview.deleteLine')"
:title="t('chat.shippingOrderReview.deleteLine')"
@click="reportSave(() => deleteLine(String(line.draft_line_id)))"
>
<Trash2 class="h-3.5 w-3.5" />
</button>
<ReviewLineInventoryOps
:line="draftLineFulfillmentFor(String(line.draft_line_id || ''))"
:editable="editable"
:busy="saving"
@close-line="openCloseFulfillmentDialog([String(line.draft_line_id || '')])"
/>
</div>
</td>
</tr>
<tr
v-if="fulfillmentDetailLineKey && fulfillmentDetailLineKey === String(line.draft_line_id || '')"
class="border-b border-subtle bg-slate-50/40 dark:bg-slate-950/30"
data-testid="review-line-fulfillment-detail-row"
>
<td :colspan="linesTableColumnCount" class="px-2 py-2">
<ReviewLineFulfillmentDetail
:line="draftLineFulfillmentFor(String(line.draft_line_id || ''))"
:task-no="fulfillmentDetailTaskNo"
@open-audit="openAuditTrail"
@close="closeFulfillmentDetail"
/>
</td>
</tr>
</template>
</tbody>
</table>
</div>
<div v-else-if="caseContentSkeleton" class="overflow-x-auto overscroll-x-contain p-4" data-testid="review-lines-skeleton">
<table :class="[linesTableMinWidthClass, 'w-full border-collapse text-left text-xs']">
<thead class="bg-surface-soft text-muted dark:bg-slate-950/40">
<tr>
<th class="sticky left-0 z-10 min-w-10 border-b border-default bg-surface-soft px-2 py-1.5 font-medium">#</th>
<template v-for="field in visibleLineSchemaFields" :key="`skeleton-${field.field_id}`">
<th class="border-b border-default px-2 py-1.5 font-medium" :style="lineColumnStyle(field)">
{{ field.display_name }}<span v-if="field.required"> *</span>
</th>
<th
v-if="showLineInventoryColumns && isQtySchemaField(field)"
class="min-w-20 border-b border-default px-2 py-1.5 font-medium"
>
{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}
</th>
<th
v-if="showLineInventoryColumns && isQtySchemaField(field)"
class="min-w-16 border-b border-default px-2 py-1.5 font-medium"
>
{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}
</th>
</template>
<th class="sticky right-0 z-10 min-w-28 border-b border-default bg-surface-soft px-2 py-1.5">
<span class="sr-only">{{ t('chat.shippingOrderReview.fulfillmentDecision.actions') }}</span>
</th>
</tr>
</thead>
<tbody>
<tr v-for="index in 3" :key="`line-skeleton-${index}`" class="border-b border-subtle last:border-0">
<td class="sticky left-0 z-10 bg-surface px-2 py-2">
<div class="h-4 w-4 animate-pulse rounded bg-surface-strong" />
</td>
<td v-for="column in Math.max(visibleLineSchemaFields.length + 1, 3)" :key="`line-skeleton-${index}-${column}`" class="px-2 py-2">
<div class="h-8 w-full animate-pulse rounded bg-surface-strong" />
</td>
</tr>
</tbody>
</table>
</div>
<div v-else class="p-4 text-sm text-muted">{{ t('chat.shippingOrderReview.noLines') }}</div>
</section>
<ReviewInventoryCandidatesPanel
v-if="workbenchMode === 'inventory'"
:lines="routingRecoveryLines"
:source-labels="buildEligibility?.inventory_source_labels || {}"
:editable="editable"
:saving="saving"
@reroute="onInventoryRoutingReroute"
/>
</div>
</div>
</div>
<aside
class="min-w-0 space-y-2 xl:sticky xl:top-4"
data-testid="review-build-gate-rail"
:aria-label="t('chat.shippingOrderReview.workbench.summaryRail')"
>
<!-- 当前任务负责动作;建单门禁负责解释字段/证据/冲突,二者必须并存。 -->
<ReviewCurrentProcessingCard
v-if="mountCurrentProcessingCard"
:stage-code="currentProcessingStageDisplay.code"
:stage-label-key="currentProcessingStageDisplay.labelKey"
:stage-inconsistent="currentProcessingStageDisplay.inconsistent"
:task-missing="Boolean(displayCase?.task_missing)"
:task-no="displayCase?.confirmed_task_no || displayCase?.post_confirm_auto_progress?.task_no"
:confirmed-task-id="displayCase?.confirmed_task_id"
:show-admin-diagnosis="showAdminTaskMissingDiagnosis"
:user-status="currentTaskUserStatus"
:retryable="visibleCurrentTaskRetryable"
:blocking-reason="currentTaskBlockingReason"
:gate-status="currentTaskGateStatus"
:primary-action="visibleCurrentTaskPrimaryAction"
:recovery-actions="visibleCurrentTaskRecoveryActions"
:retrying="taskRetryButtonDisabled || progressRetrying || caseSwitchLoading"
:loading="caseContentSkeleton || formalTaskProjectionPending || formalTaskDetailLoading"
:status-detail="currentTaskStatusDetail"
@locate="(draftLineId, fieldId) => handleCurrentTaskLocate(draftLineId, fieldId)"
@action="(code, params) => void handleCurrentTaskAction(code, params)"
/>
<ReviewBuildEligibilitySummary
v-if="showEligibilityAsPrimary"
:eligibility="buildEligibility"
:field-conflicts="displayCase?.field_conflicts"
:customer-resolved="Boolean(displayCase?.customer_resolution?.resolved)"
:field-labels="reviewFieldLabels"
:exception-count="exceptionTargets.length"
:exception-ordinal="exceptionOrdinal"
:focus-buildability="hasActiveBusinessGate"
@open-details="openEligibilityDetails"
@navigate-exception="navigateExceptionField"
/>
<!-- 订单复核 Gate 统一收敛至右栏;主编辑列只保留字段、明细与证据。 -->
<template v-if="showOrderReviewEditor && activeCase">
<ReviewCustomerResolutionPanel
v-if="!activeCase.customer_resolution?.resolved"
ref="customerResolutionWideRef"
:case-no="activeCase.case_no"
:resolution="activeCase.customer_resolution"
:editable="editable"
@refreshed="handleReviewGateDataRefreshed"
/>
<ReviewFieldConflictPanel
ref="fieldConflictPanelRef"
:case-no="activeCase.case_no"
:draft-version="activeCase.draft?.draft_version"
:conflicts="activeCase.field_conflicts"
:evidence-issues="activeCase.evidence_issues"
:editable="editable"
@refreshed="handleReviewGateDataRefreshed"
@focus-conflict="focusFieldConflict"
/>
<ReviewDuplicatePanel
ref="duplicatePanelRef"
:case-no="activeCase.case_no"
:duplicate="activeCase.duplicate"
:editable="editable"
:can-force-create="Boolean(activeCase.duplicate?.allowed_actions?.includes('force_create'))"
@refreshed="handleReviewGateDataRefreshed"
/>
</template>
<!-- 预约单校验是订单复核 Gate:右栏显示异常与操作,左侧明细仍是唯一编辑位置。 -->
<ReviewReservationPanel
v-if="showOrderReviewEditor && activeCase"
:case-no="activeCase.case_no"
:draft-version="activeCase.draft?.draft_version"
:reservation="activeCase.reservation"
:editable="editable"
@refreshed="handleReviewGateDataRefreshed"
/>
<ReviewInventoryIssueFallbackCard
v-if="isLifecycleFulfillmentPrep && hasFormalOt && displayCase?.inventory_issue_fallback && !displayCase?.line_fulfillment?.has_line_inventory_projection"
:fallback="displayCase.inventory_issue_fallback"
:busy="false"
@retry-preparation="() => void retryCaseInventoryFallback()"
/>
<ReviewProfileMatchPanel
v-if="isLifecycleIntakeParse"
class="hidden xl:block"
:profile-match="displayCase?.profile_match"
/>
</aside>
</div>
</div>
</template>
</div>
</div>
</section>
</div>
<!-- 默认浮动证据面板:fixed 叠加,不参与主网格,底栏上方留白。 -->
<ReviewDocumentEvidenceDrawer
v-if="evidenceFloating"
:open="panelState.pdfOpen"
:pinned="panelState.pdfPinned"
:expanded="panelState.pdfExpanded"
:docked="false"
:float-side="panelState.pdfFloatSide"
:src="previewUrl"
:email-preview="selectedEvidenceIsEmail ? emailPreview : null"
:evidence="selectedEvidence"
:evidence-list="evidence || []"
:field-label="evidenceFieldLabel"
:draft-value="focusedLlmDraftValue"
:machine-value="evidenceMachineValue"
:value-source-label="evidenceValueSourceLabel"
:show-ai-actions="editable"
:reset-key="displayCase?.case_no || null"
@close="closeEvidenceMode"
@toggle-pin="togglePdfPinned"
@toggle-expand="togglePdfExpanded"
@toggle-dock="togglePdfDocked"
@toggle-side="togglePdfFloatSide"
@prev-evidence="navigateEvidence(-1)"
@next-evidence="navigateEvidence(1)"
@request-ai="requestSuggestion()"
@restore-machine="restoreEvidenceMachineValue"
/>
<ReviewBuildEligibilityDetailsDrawer
:open="panelState.eligibilityDetailsOpen"
:eligibility="buildEligibility"
:field-conflicts="displayCase?.field_conflicts"
:field-labels="Object.fromEntries((displayCase?.schema.fields || []).map((field) => [field.field_code, field.display_name]))"
:customer-resolved="Boolean(displayCase?.customer_resolution?.resolved)"
@close="closeEligibilityDetails"
@focus-line="(lineIndex) => { closeEligibilityDetails(); focusOrderLine(lineIndex); }"
/>
<ReviewVersionHistoryDrawer
:open="panelState.versionHistoryOpen"
:item-no="reviewProgressContext?.item_no || itemNoFromQuery"
:versions="versions"
:loading="versionsLoading"
:active-case-no="requestedCaseNo || displayCase?.case_no"
@close="closeVersionHistory"
@select="(caseNo) => { closeVersionHistory(); void selectVersionFromHistory(caseNo); }"
/>
<ReviewAuditTrailDrawer
:open="auditTrailOpen"
:case-no="activeCase?.case_no || ''"
@close="closeAuditTrail"
/>
<ReviewCloseFulfillmentDialog
v-model:open="closeFulfillmentOpen"
:case-no="activeCase?.case_no || ''"
:draft-version="activeCase?.draft?.draft_version"
:line-keys="closeFulfillmentLineKeys"
@confirmed="onCloseFulfillmentConfirmed"
/>
<div
v-if="releaseInventoryLine"
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 p-4"
data-testid="review-release-inventory-dialog"
@click.self="releaseInventoryLine = null"
>
<div class="w-full max-w-md rounded-xl border border-default bg-surface p-4 shadow-xl">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.lifecycle.prepare.releaseShortage') }}</h2>
<p class="mt-1 text-xs text-muted">{{ t('chat.shippingOrderReview.lifecycle.prepare.releaseShortageHint') }}</p>
<textarea
v-model="releaseInventoryReason"
rows="3"
class="mt-3 w-full rounded-md border border-default bg-surface px-2.5 py-2 text-sm"
:placeholder="t('chat.shippingOrderReview.lifecycle.prepare.releaseReasonPlaceholder')"
:disabled="releaseInventoryBusy"
/>
<dl v-if="(releaseInventoryLine.release_template_fields || []).some((field) => !field.requires_manual)" class="mt-3 divide-y divide-default rounded-md border border-default text-xs">
<template v-for="field in releaseInventoryLine.release_template_fields || []" :key="field.field_id">
<div v-if="!field.requires_manual" class="flex items-center justify-between gap-3 px-2.5 py-2">
<dt class="text-secondary">{{ field.display_name }}</dt>
<dd class="font-medium text-primary">{{ field.value || '—' }}</dd>
</div>
</template>
</dl>
<label v-for="field in releaseInventoryLine.release_required_fields || []" :key="field.field_id" class="mt-3 block text-xs font-medium text-secondary">
{{ field.display_name }} *
<input v-model="releaseInventoryFieldValues[field.field_id]" type="text" class="mt-1 w-full rounded-md border border-default bg-surface px-2.5 py-2 text-sm" :disabled="releaseInventoryBusy" />
</label>
<div class="mt-4 flex justify-end gap-2">
<button type="button" class="rounded border border-default px-3 py-1.5 text-sm" :disabled="releaseInventoryBusy" @click="releaseInventoryLine = null">{{ t('chat.shippingOrderReview.workbench.close') }}</button>
<button type="button" class="rounded bg-amber-600 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-50" :disabled="releaseInventoryBusy || (releaseInventoryLine.release_required_fields || []).some((field) => !releaseInventoryFieldValues[field.field_id]?.trim())" @click="confirmReleaseInventoryShortage">{{ t('chat.shippingOrderReview.lifecycle.prepare.releaseConfirm') }}</button>
</div>
</div>
</div>
<div
v-if="closeLineDialogLine"
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 p-4"
data-testid="review-close-line-dialog"
@click.self="closeLineDialogLine = null"
>
<div class="w-full max-w-md rounded-xl border border-default bg-surface p-4 shadow-xl">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.lineActions.closeLine') }}</h2>
<p class="mt-1 text-xs text-muted">{{ t('chat.shippingOrderReview.closeFulfillment.subtitle') }}</p>
<textarea
v-model="closeLineReason"
rows="3"
class="mt-3 w-full rounded-md border border-default bg-surface px-2.5 py-2 text-sm"
data-testid="review-close-line-reason"
:placeholder="t('chat.shippingOrderReview.lineActions.closeLineReason')"
:disabled="closeLineBusy"
/>
<div class="mt-4 flex justify-end gap-2">
<button type="button" class="rounded border border-default px-3 py-1.5 text-sm" :disabled="closeLineBusy" @click="closeLineDialogLine = null">{{ t('chat.shippingOrderReview.workbench.close') }}</button>
<button type="button" class="rounded bg-rose-600 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-50" data-testid="review-close-line-submit" :disabled="closeLineBusy || !closeLineReason.trim()" @click="confirmCloseLine">{{ t('chat.shippingOrderReview.lineActions.closeLineConfirm') }}</button>
</div>
</div>
</div>
<ReviewLlmSuggestionDrawer
:open="panelState.llmSuggestionOpen"
:active-case="activeCase"
:evidence="evidence"
:editable="editable"
:saving="saving"
:suggestions="llmSuggestions"
:suggestion-loading="suggestionLoading"
:focused-field-id="focusedFieldId"
:focused-line-key="focusedLineKey"
:draft-value="focusedLlmDraftValue"
@close="closeLlmSuggestionDrawer"
@request-suggestion="requestSuggestion()"
@adjudicate="({ suggestion, body }) => decideSuggestion(suggestion.suggestion_no, body)"
/>
<ReviewWorkbenchFooter
v-if="showOrderReviewEditor || isLifecycleIntakeParse"
:available-actions="availableActions"
:can-confirm-build="canConfirmBuild"
:hide-confirm-because-auto-gate="hideConfirmBecauseAutoGate"
:show-auto-gate-hint="showAutoGateHint"
:show-stp-retry="showObjectRetryOnFooter"
:auto-gate-hint="t(autoGateHintKey)"
:saving="saving"
:is-read-only="isReviewContentReadOnly"
:has-draft="Boolean(displayCase?.draft) || isLifecycleIntakeParse"
:unsaved-count="unsavedEditCount"
:flow-presentation="flowPresentation"
:automating="isProcessingAutomating"
:actions-executable="workbenchActionsExecutable"
:flow-busy="flowActionBusy"
:show-parse-dispositions="isLifecycleIntakeParse"
:show-validate="showOrderReviewEditor"
@mark-non-order="openActionDialog('non_order')"
@mark-quality-issue="openActionDialog('quality_issue')"
@reparse="openActionDialog('reparse')"
@validate="onValidate"
@confirm="openActionDialog('confirm')"
@retry-stp="() => void onFooterRetryAutomation()"
@flow-action="(item) => { void onUnifiedProcessingAction(item); }"
/>
<ReviewProcessDetailDrawer
:open="processDetailOpen"
:projection="shippingProcessingProjection"
:po-number="processDetailPoNumber"
:order-task-no="authoritativeOrderTaskNo"
:audit-available="Boolean(activeCase?.case_no)"
@close="processDetailOpen = false"
@open-audit="() => { processDetailOpen = false; auditTrailOpen = true; }"
/>
<ManualUploadEvidenceDialog
v-model:open="manualUploadRegistrationOpen"
:business-no="formalTaskDetail?.business_no || ''"
:artifact-id="formalTaskDetail?.export_artifacts?.[0]?.id || null"
:disabled="!workbenchActionsExecutable || !manualUploadRegistrationAuthorized || !formalTaskDetail?.business_no"
@success="() => { void handleManualUploadSuccess(); }"
/>
<ReviewUnsavedSwitchDialog
:open="unsavedSwitchOpen"
:unsaved-count="unsavedEditCount"
:saving="saving"
@cancel="() => { unsavedSwitchOpen = false; pendingSwitchCaseNo = null; }"
@discard="() => { void discardAndSwitchCase(); }"
@save-and-switch="() => { void saveAndSwitchCase(); }"
/>
<ReviewActionConfirmDialog
v-if="actionDialogOpen && pendingAction"
v-model="actionDialogOpen"
:action="pendingAction"
:confirm-loading="saving"
@confirm="submitPendingAction"
/>
</main>
</template>
<style scoped>
/**
* 用途:库存匹配明细在窄工作区保留业务列宽,且行级授权操作始终可用。
* 依赖:formalPreparationLines 与后端下发的 inventory_allowed_actions。
* 逻辑:仅表头/表体容器横向滚动(标题与选行条固定),右侧操作列 sticky。
*/
.review-fulfillment-prep-table {
width: max-content;
}
/* 行级操作始终可见,背景和阴影避免横向滚动内容穿透。 */
.review-fulfillment-sticky-action-head,
.review-fulfillment-sticky-action-cell {
position: sticky;
right: 0;
min-width: 88px;
border-left: 1px solid var(--border-default);
background-clip: padding-box;
box-shadow: -8px 0 16px -8px rgba(15, 23, 42, 0.18);
}
/* 复核主表只让字段列可调宽;操作列保持 sticky,避免横向浏览后丢失行级放行入口。 */
.review-line-column-head {
position: relative;
min-width: 88px;
}
.review-line-column-resizer {
position: absolute;
z-index: 2;
top: 0;
right: -4px;
width: 8px;
height: 100%;
border: 0;
background: transparent;
cursor: col-resize;
}
.review-line-column-resizer::after {
position: absolute;
top: 25%;
bottom: 25%;
left: 3px;
width: 1px;
background: transparent;
content: '';
}
.review-line-column-resizer:hover::after,
.review-line-column-resizer:focus-visible::after {
background: var(--color-brand-500, #0ea5e9);
}
.review-fulfillment-sticky-action-head {
z-index: 30;
background-color: var(--bg-surface-soft);
}
.review-fulfillment-sticky-action-cell {
z-index: 20;
background-color: var(--bg-surface);
}
</style>