为提升货代上传的自动化程度,减少人工操作,本提交实现完整的连接级自动上传功能,包含以下变更: - 新增数据库迁移与ShippingRpaProfile模型字段,存储连接级上传配置 - 完善RPA自动上传触发、回调与状态管理逻辑,支持三态结果与人工兜底 - 优化聊天界面任务卡片加载与按钮渲染,修复无文案幽灵按钮问题
5161 lines
239 KiB
Vue
5161 lines
239 KiB
Vue
<!--
|
||
features/chat/views/ShippingOrderReviewView.vue
|
||
用途:建单前/正式任务「订单生命周期工作台」(主编辑区 + 五阶段导航 + 工作台侧栏 + workbenchMode)。
|
||
依赖:路由参数、useShippingOrderReview、ReviewWorkbenchHeader/Footer、ReviewDocumentNavigation、
|
||
ReviewProcessDetailDrawer、ReviewUnsavedSwitchDialog、
|
||
ReviewWorkbenchModeToggle、ReviewDocumentEvidenceDrawer、ReviewVersionHistoryDrawer、
|
||
ReviewLlmSuggestionDrawer、ReviewActionConfirmDialog、ReviewLineNoOverrideDialog、
|
||
ReviewCustomerResolutionPanel / ReviewCurrentProcessingCard / ReviewCompletedChecksPanel /
|
||
ReviewBuildEligibilitySummary、ReviewInventory*、
|
||
ReviewLineInventoryOps(履约操作并入明细右侧列)、ReviewLineFulfillmentDetail(行内履约摘要)、
|
||
正式任务动作直接提交后端 Gate,避免以无界面组件充当隐藏执行器;
|
||
逻辑:建单前订单检查为主卡;正式 OT 后保持 standard,不自动切 formal_task 空壳;
|
||
当前 Case 的明确恢复动作优先右栏 CurrentProcessingCard,
|
||
不回落至底栏;库存动作仅明细行浮层;表单保存校验仅底栏。
|
||
-->
|
||
<script setup lang="ts">
|
||
import { computed, defineAsyncComponent, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||
import { useRoute, useRouter } from 'vue-router';
|
||
import { Bot, Check, ChevronDown, Crosshair, Download, MoreHorizontal, Plus, RefreshCw, Undo2, Copy, Trash2 } 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,
|
||
waveWorkspaceShippingOrderReviewLineFulfillment,
|
||
viewWorkspaceShippingOrderReviewHighlightDiagnostic,
|
||
} from '../api/shipping.api';
|
||
import type {
|
||
ShippingOrderReviewLineFulfillmentLine,
|
||
} from '../types/shipping.api.types';
|
||
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 ReviewLineNoOverrideDialog, {
|
||
type LineNoOverridePayload,
|
||
} from '../components/shipping-review/ReviewLineNoOverrideDialog.vue';
|
||
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();
|
||
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,
|
||
requestedCaseNo,
|
||
refreshWorkItemContext,
|
||
openCurrentVersion,
|
||
reloadLatestDraft,
|
||
toggleConflictDiff,
|
||
patchHeader,
|
||
patchLine,
|
||
addLine,
|
||
copyLine,
|
||
deleteLine,
|
||
validate,
|
||
rerouteInventoryRouting,
|
||
confirm,
|
||
createManualDraft,
|
||
markNonOrder,
|
||
markQualityIssue,
|
||
reparseDocument,
|
||
focusSuggestionField,
|
||
setEvidenceDrawerFocus,
|
||
clearEvidenceDrawerFocus,
|
||
requestSuggestion,
|
||
decideSuggestion,
|
||
editable,
|
||
formalEditable,
|
||
isFieldEditable,
|
||
showWorkflowProgress,
|
||
startWorkflowProgressPolling,
|
||
} = useShippingOrderReview({ onWorkflowRefresh: page.bumpWorkflowRefresh });
|
||
const msg = useMessage();
|
||
|
||
/**
|
||
* 右侧主卡阶段:优先 Progress 投影(与顶部同源);正式 OT 投影未到时用
|
||
* Case.current_stage(与投影同源 project_stage_for_task),建单前 automation 仅作降级。
|
||
* 无论哪一路都带 label_key,禁止把 code 当用户文案。
|
||
*/
|
||
const currentProcessingStageDisplay = computed(() => {
|
||
const projection = shippingProcessingProjection.value;
|
||
if (projection?.stage) {
|
||
return {
|
||
code: projection.stage,
|
||
labelKey: projection.stageLabelKey
|
||
|| (projection.stage === 'order_creating' ? 'waiting_system_start' : projection.stage),
|
||
inconsistent: false,
|
||
};
|
||
}
|
||
const caseStage = activeCase.value?.current_stage;
|
||
const caseCode = String(caseStage?.code || '').trim();
|
||
// 正式 OT 的 Case.current_stage 与统一投影同源(project_stage_for_task):
|
||
// 投影读取中(正式任务已存在、投影在途)也必须先展示真实阶段,
|
||
// 禁止被下方 automation 分支降级为“创建正式订单”自动建单阶段。
|
||
if (hasFormalOt.value && caseCode) {
|
||
return {
|
||
code: caseCode,
|
||
labelKey: caseStage?.label_key
|
||
|| (caseCode === 'order_creating' ? 'waiting_system_start' : caseCode),
|
||
inconsistent: Boolean(caseStage?.inconsistent),
|
||
};
|
||
}
|
||
// STP 建单前尚无正式 OT/processing projection;自动建单 Job 仍属于“创建正式订单”阶段。
|
||
const automationStatus = String(activeCase.value?.automation?.status || '').trim().toLowerCase();
|
||
if (['queued', 'running', 'failed', 'manual_fallback'].includes(automationStatus)) {
|
||
return {
|
||
code: 'order_creating',
|
||
labelKey: null,
|
||
inconsistent: false,
|
||
};
|
||
}
|
||
return {
|
||
code: caseCode || null,
|
||
labelKey: caseStage?.label_key
|
||
|| (caseCode === 'order_creating' ? 'waiting_system_start' : caseCode),
|
||
inconsistent: Boolean(caseStage?.inconsistent),
|
||
};
|
||
});
|
||
|
||
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 裁决。
|
||
*/
|
||
const lifecycleUiState = computed(() => {
|
||
const processing = shippingProcessingProjection.value?.uiState;
|
||
const formal = formalTaskDetail.value?.ui_state;
|
||
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,
|
||
};
|
||
}
|
||
// Review Case 尚未建正式任务时,Run/Queue 项仍由后端下发生命周期入口;
|
||
// 不得因 formal task 缺失而回退到前端默认订单复核。
|
||
const currentCaseNo = String(activeCase.value?.case_no || '').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';
|
||
}
|
||
return lifecycleEntryIsEnterable(entry) ? requested : lifecycleCurrentStageCode.value;
|
||
});
|
||
/** 当前后端投影明确在自动推进时,五阶段导航只为该阶段展示 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)
|
||
);
|
||
});
|
||
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');
|
||
/** 当前阶段重试只取 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(),
|
||
activeCase.value?.case_no
|
||
? ensureIntakeParseContextLoaded(activeCase.value.case_no)
|
||
: 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 仍停留在放行前的通知准备路由、用户未在放行后手动选阶段,且后端
|
||
* 权威投影已推进时替换深链。异步 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;
|
||
// 用户主动回看已完成阶段时,异步投影抵达不得将其强制带回当前阶段。
|
||
// 自动推进均使用 replace,不会写入该意图。
|
||
if (!options.replace) {
|
||
const caseNo = String(activeCase.value?.case_no || '').trim() || null;
|
||
lifecycleStagePinnedByUserForCase.value = caseNo;
|
||
if (pendingReleaseAutoAdvanceCaseNo.value === caseNo) {
|
||
pendingReleaseAutoAdvanceCaseNo.value = null;
|
||
}
|
||
}
|
||
if (code === 'intake_parse' && intakeParseContextAuthorized.value && activeCase.value?.case_no) {
|
||
void ensureIntakeParseContextLoaded(activeCase.value.case_no);
|
||
}
|
||
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;
|
||
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
|
||
&& 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);
|
||
/**
|
||
* 正式 OT 已存在且文件切换或统一处理投影读取中时,Case Gate 只是降级快照,不能先暴露可执行动作。
|
||
* Projection 返回后才拥有动作裁决权;非切换错误路径仍保留原有的 Case Gate 恢复能力。
|
||
*/
|
||
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',
|
||
]);
|
||
|
||
function isNoticeScopedAction(action: ShippingUnifiedAction | null | undefined): boolean {
|
||
return NOTICE_SCOPED_ACTION_CODES.has(String(action?.code || '').trim());
|
||
}
|
||
|
||
/**
|
||
* 将正式任务详情的已启用 Gate 动作适配为右侧当前任务卡的展示契约。
|
||
*
|
||
* 正式 OT 的写授权只能来自 ``ui_state.actions``;统一处理 Projection 仅承载
|
||
* 进度、阶段和阻断事实,不能以历史动作码替代正式 Gate 动作。
|
||
*/
|
||
function toCurrentTaskAction(action: ShippingUnifiedAction | null | undefined) {
|
||
if (!action?.enabled || !String(action.code || '').trim() || isNoticeScopedAction(action)) return null;
|
||
return {
|
||
code: String(action.code).trim(),
|
||
i18nKey: `workspace.shippingNotice.processGate.actionCodes.${action.code}`,
|
||
};
|
||
}
|
||
|
||
const formalTaskActions = computed(() => {
|
||
const actions = formalTaskDetail.value?.ui_state?.actions;
|
||
return [actions?.primary, ...(actions?.secondary || [])]
|
||
.filter((action): action is ShippingUnifiedAction => Boolean(action?.code));
|
||
});
|
||
|
||
const currentTaskPrimaryAction = computed(() => {
|
||
if (formalTaskProjectionPending.value) return null;
|
||
if (hasFormalOt.value) return toCurrentTaskAction(formalTaskActions.value[0]);
|
||
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(() => {
|
||
// 已确认 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';
|
||
return null;
|
||
});
|
||
const currentTaskBlockingReason = computed(() => {
|
||
if (formalTaskProjectionPending.value) return null;
|
||
return currentTaskUiState.value?.blocking_reason ?? null;
|
||
});
|
||
/** 当前 Gate 状态必须与右栏动作同源,均来自统一处理 Projection。 */
|
||
const currentTaskGateStatus = computed(() => {
|
||
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) {
|
||
return formalTaskActions.value.slice(1)
|
||
.filter((action) => String(action.code || '').trim() !== 'download_excel' && !isNoticeScopedAction(action))
|
||
.map(toCurrentTaskAction)
|
||
.filter((action): action is NonNullable<typeof action> => Boolean(action));
|
||
}
|
||
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(() => (
|
||
isLifecycleUploadComplete.value ? null : currentTaskPrimaryAction.value
|
||
));
|
||
const visibleCurrentTaskRecoveryActions = computed(() => (
|
||
isLifecycleUploadComplete.value ? [] : currentTaskRecoveryActions.value
|
||
));
|
||
const visibleCurrentTaskRetryable = computed(() => (
|
||
isLifecycleUploadComplete.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;
|
||
checkpoint: 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 || ''),
|
||
checkpoint: '',
|
||
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]?.line_key : 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.line_key || '').trim(), index] as const),
|
||
);
|
||
const schemaFields = activeCase.value?.schema?.fields || [];
|
||
const resolveLineIndex = (lineIndexRaw: unknown, lineKeyRaw?: unknown) => {
|
||
if (lineIndexRaw != null && lineIndexRaw !== '' && Number.isFinite(Number(lineIndexRaw))) {
|
||
return Number(lineIndexRaw);
|
||
}
|
||
const lineKey = String(lineKeyRaw || '').trim();
|
||
return lineKey ? lineIndexByKey.get(lineKey) : 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, lineKeyRaw?: unknown) => {
|
||
const fieldId = String(fieldIdRaw || '').trim();
|
||
if (!fieldId) return;
|
||
const lineIndex = resolveLineIndex(lineIndexRaw, lineKeyRaw);
|
||
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 & { line_key?: string | null };
|
||
push(reviewIssue.field_id || fieldIdForCode(reviewIssue.field_code), reviewIssue.line_index, reviewIssue.line_key);
|
||
}
|
||
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.line_key);
|
||
continue;
|
||
}
|
||
for (const fieldCode of fields) {
|
||
push(fieldIdForCode(fieldCode), issue.line_index, issue.line_key);
|
||
}
|
||
}
|
||
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);
|
||
});
|
||
|
||
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]?.line_key : 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]?.line_key
|
||
: 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
|
||
));
|
||
|
||
/**
|
||
* 按 line_key 取履约投影行。
|
||
*/
|
||
function lineFulfillmentFor(lineKey: string): ShippingOrderReviewLineFulfillmentLine | null {
|
||
const rows = displayCase.value?.line_fulfillment?.lines || [];
|
||
return rows.find((item) => String(item.line_key) === String(lineKey)) || 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)或字段冲突证据。
|
||
* 优先处理 line_key(从 line_key 解析行索引并滚动),无行号时回滚到字段冲突视图。
|
||
*/
|
||
function handleCurrentTaskLocate(
|
||
lineKey: string | null | undefined,
|
||
fieldId: string | null | undefined,
|
||
) {
|
||
if (lineKey) {
|
||
const draftLines = (activeCase.value?.draft?.lines || []) as Array<{
|
||
line_key?: string | null;
|
||
line_index?: number | null;
|
||
}>;
|
||
const draftLine = draftLines.find(
|
||
(row) => String(row.line_key || '') === String(lineKey),
|
||
);
|
||
if (draftLine?.line_index != null) {
|
||
focusOrderLine(draftLine.line_index);
|
||
return;
|
||
}
|
||
const m = /line[-_:\s]*([0-9]+)$/i.exec(String(lineKey));
|
||
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, lineKey: 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 } = {}) {
|
||
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 的所有可写动作都从任务详情的 ui_state.actions 原样委托。
|
||
// 缺少同码的正式动作即不执行,不能降级到历史 Projection 或 Case 快照。
|
||
if (hasFormalOt.value) {
|
||
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;
|
||
}
|
||
if (!(await ensureFormalTaskDetailReady())) 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) {
|
||
scrollWorkbenchAnchor('review-order-lines-table');
|
||
} 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 = lineFulfillmentFor(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();
|
||
}
|
||
|
||
/** 关闭 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;
|
||
lineKey: 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]?.line_key || '');
|
||
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(() => (
|
||
!isReadOnly.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);
|
||
|
||
/** 系统自动推进中:仅当存在确认 Job 时隐藏主写按钮;资格达标不算 automating。 */
|
||
const isProcessingAutomating = computed(() => {
|
||
// STP 建单前没有正式 OT 投影;已入队/运行时由 Case automation 作为唯一运行事实。
|
||
const stpStatus = String(activeCase.value?.automation?.status || '').trim().toLowerCase();
|
||
if (!hasFormalOt.value && ['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,
|
||
};
|
||
});
|
||
});
|
||
|
||
/** 流程详情标题用 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;
|
||
});
|
||
|
||
/** 工作台标题下的当前订单摘要;切换队列项后必须与正在编辑的 Case 同步。 */
|
||
const selectedOrderSummary = computed(() => {
|
||
const activeNo = String(activeCase.value?.case_no || '').trim();
|
||
const item = documentNavItems.value.find((candidate) => candidate.case_no === activeNo);
|
||
const draftVersion = activeCase.value?.draft?.draft_version;
|
||
return {
|
||
fileName: String(item?.file_name || '').trim() || t('chat.shippingOrderReview.unnamedDocument'),
|
||
poNumber: processDetailPoNumber.value,
|
||
caseNo: activeNo || null,
|
||
version: reviewProgressVersionLabel.value || (draftVersion ? `V${draftVersion}` : 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
|
||
));
|
||
|
||
const lifecycleProgressStepText = computed(() => {
|
||
const progress = lifecycleProgressForView.value;
|
||
if (!progress?.current_step_i18n_key || !te(progress.current_step_i18n_key)) return null;
|
||
return t(progress.current_step_i18n_key);
|
||
});
|
||
const lifecycleProgressReasonText = computed(() => {
|
||
const progress = lifecycleProgressForView.value;
|
||
if (!progress?.blocking_reason_i18n_key || !te(progress.blocking_reason_i18n_key)) return null;
|
||
return t(progress.blocking_reason_i18n_key);
|
||
});
|
||
/**
|
||
* Run 级进度横幅的统一展示消息。
|
||
*
|
||
* 核心逻辑:只有后端裁决 lifecycle_status == 'running' 才能声称「系统正在自动处理」;
|
||
* waiting(门禁待机)/ failed / cancelled 只展示等待/失败原因或步骤文本,禁止自动处理文案
|
||
* 与门禁状态自相矛盾;completed 时 Run 已无待办,横幅直接隐藏。
|
||
* 注意:后端仅在 running 下才有 current_step_i18n_key,因此旧逻辑在 waiting 时
|
||
* 会落入「系统正在自动处理」兜底文案,这正是本函数要消除的错误展示。
|
||
* 该横幅是「提取 Run(建单前流水线)」的运行提示,只在未有正式 OT 时展示
|
||
* (模板 v-if !hasFormalOt);正式 OT 后进度与操作指引由右栏当前任务卡承载。
|
||
*/
|
||
const lifecycleProgressMessage = computed<{
|
||
auto: boolean;
|
||
text: string;
|
||
reason: string | null;
|
||
} | null>(() => {
|
||
const progress = lifecycleProgressForView.value;
|
||
if (!progress) return null;
|
||
const status = String(progress.lifecycle_status || '').trim().toLowerCase();
|
||
const stepText = lifecycleProgressStepText.value;
|
||
const reasonText = lifecycleProgressReasonText.value;
|
||
if (status === 'running') {
|
||
return {
|
||
auto: true,
|
||
text: stepText || t('chat.shippingProcessing.progress.systemProcessingNeed'),
|
||
reason: reasonText,
|
||
};
|
||
}
|
||
if (status === 'completed') return null;
|
||
if (status === 'failed') {
|
||
return { auto: false, text: reasonText || t('chat.shippingProcessing.progress.lifecycleReason.failed'), reason: null };
|
||
}
|
||
if (status === 'cancelled') {
|
||
return { auto: false, text: reasonText || t('chat.shippingProcessing.progress.lifecycleReason.cancelled'), reason: null };
|
||
}
|
||
// waiting 或未知状态:绝不声称自动处理,优先展示后端原因,其次步骤文本。
|
||
return {
|
||
auto: false,
|
||
text: reasonText || stepText || t('chat.shippingProcessing.progress.lifecycleWaitingNeed'),
|
||
reason: 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(
|
||
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。 */
|
||
const confirmedNoticeTaskNo = computed(() => String(
|
||
displayCase.value?.confirmed_task_no
|
||
|| reviewProgressContext.value?.current_task_no
|
||
|| '',
|
||
).trim());
|
||
|
||
/** 确认后履约待办详情;任务中心不再挂工作台,由本工作台承接。 */
|
||
const formalTaskDetail = ref<ShippingTaskDetail | null>(null);
|
||
const freightNoticeGroups = ref<ShippingFreightNoticeGroup[]>([]);
|
||
const freightNoticeGroupsLoading = ref(false);
|
||
const freightNoticeGroupsReason = ref<string | null>(null);
|
||
const freightNoticeGroupsLoadFailed = ref(false);
|
||
const selectedFreightBusinessNos = ref<string[]>([]);
|
||
const freightBatchBusy = ref<'download' | 'confirm' | 'rpa' | 'regenerate' | null>(null);
|
||
/**
|
||
* 通知完成面的只读聚合:同 PO 中已有上传成功证据(upload_status=uploaded)的发货通知。
|
||
* 核心逻辑:与货代上传面消费同一份 freightNoticeGroups,仅按终态过滤;未上传的
|
||
* 通知仍留在货代上传面处理,完成面不出现混淆态。
|
||
*/
|
||
const uploadedFreightNoticeGroups = computed(() =>
|
||
freightNoticeGroups.value.filter((item) =>
|
||
String(item.upload_status || '').trim().toLowerCase() === 'uploaded',
|
||
),
|
||
);
|
||
/** 批次留底下载:把已完成通知全部打包为 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);
|
||
/**
|
||
* 正式任务详情只属于当前 PDF/Case。切换文件或任务后递增代际,拒绝旧异步响应覆盖
|
||
* lifecycle_entries;否则 B 文件会短暂显示 A 文件的阶段与入口。
|
||
*/
|
||
let formalTaskDetailGeneration = 0;
|
||
const manualUploadRegistrationOpen = ref(false);
|
||
|
||
/**
|
||
* 通知准备优先消费正式任务 ui_state;详情摘要暂时为空时,仅回退到当前 Case 的
|
||
* 已有 line_fulfillment 投影,避免 Case 与 OT 详情投影短暂不同步造成整表空白。
|
||
*/
|
||
const formalPreparationContext = computed(() => {
|
||
const preparation = formalTaskDetail.value?.ui_state?.stage_context?.preparation;
|
||
const fallbackLines = displayCase.value?.line_fulfillment?.lines || [];
|
||
if (!preparation && !fallbackLines.length) return null;
|
||
if (preparation?.lines?.length) return preparation;
|
||
if (!fallbackLines.length) return preparation;
|
||
return {
|
||
...(preparation || {}),
|
||
// [B1] 回退展示(任务详情未到、仅有 Case line_fulfillment)时不得伪造 status='processing':
|
||
// 那会让「processing → ready / blocked」看起来像二次刷新;真实状态由任务详情到达后显示,
|
||
// 徽章在状态为空时保持隐藏。
|
||
status: preparation?.status ?? null,
|
||
frozen_order: preparation?.frozen_order || {
|
||
task_no: confirmedNoticeTaskNo.value || null,
|
||
snapshot_id: null,
|
||
},
|
||
artifact: preparation?.artifact || { file_name: null, status: 'not_generated' },
|
||
has_match_result: true,
|
||
lines: fallbackLines.map((line) => ({
|
||
line_key: line.line_key,
|
||
reservation_id: line.reservation_id,
|
||
part_number: line.part_number,
|
||
required_qty: line.required_qty,
|
||
available_qty: line.available_qty,
|
||
shortage_qty: line.shortage_qty,
|
||
source_code: line.inventory_source_code,
|
||
status: line.line_status || line.match_result,
|
||
})),
|
||
inventory_source_code: preparation?.inventory_source_code
|
||
|| fallbackLines.find((line) => line.inventory_source_code)?.inventory_source_code
|
||
|| null,
|
||
};
|
||
});
|
||
|
||
/** 通知准备的唯一行级工作表;短缺优先呈现。 */
|
||
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),
|
||
})).sort((left, right) => Number(right.shortage_qty || 0) - Number(left.shortage_qty || 0));
|
||
});
|
||
|
||
/**
|
||
* 阶段详情只承载库存结果;Case 行投影承载行级库存源和动作授权。按 line_key 合并,
|
||
* 禁止用任务级 inventory_sources 回填到订单行。
|
||
*/
|
||
function formalPreparationLineFulfillment(line: { line_key?: string | null }): ShippingOrderReviewLineFulfillmentLine | null {
|
||
return lineFulfillmentFor(String(line.line_key || ''));
|
||
}
|
||
|
||
function formalPreparationLineSource(line: { line_key?: string | null; source_code?: string | null }): string {
|
||
const fulfillment = formalPreparationLineFulfillment(line);
|
||
const source = fulfillment?.inventory_source;
|
||
const label = String(source?.label || '').trim();
|
||
const code = String(source?.code || line.source_code || fulfillment?.inventory_source_code || '').trim();
|
||
if (label && code) return `${label}(${code})`;
|
||
return label || code || '—';
|
||
}
|
||
|
||
function formalPreparationLineAllows(
|
||
line: { line_key?: string | 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));
|
||
}
|
||
|
||
function formalPreparationLineStatusLabel(line: { line_key?: string | 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' && 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 key = `chat.shippingOrderReview.lifecycle.prepare.matchStatus.${status || 'unknown'}`;
|
||
return te(key) ? t(key) : status || '—';
|
||
}
|
||
|
||
const releaseInventoryLine = ref<ShippingOrderReviewLineFulfillmentLine | null>(null);
|
||
const releaseInventoryReason = ref('');
|
||
const releaseInventoryFieldValues = ref<Record<string, string>>({});
|
||
const releaseInventoryBusy = ref(false);
|
||
|
||
function openReleaseInventoryShortage(line: { line_key?: string | 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 || !reason || requiredFields.some((field) => !releaseInventoryFieldValues.value[field.field_id]?.trim()) || releaseInventoryBusy.value) return;
|
||
releaseInventoryBusy.value = true;
|
||
try {
|
||
await decideWorkspaceShippingOrderReviewLineFulfillment(caseNo, {
|
||
line_key: line.line_key,
|
||
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: { line_key?: string | null; inventory_file_no?: string | null }): string {
|
||
const fulfillment = formalPreparationLineFulfillment(line);
|
||
return String(line.inventory_file_no || fulfillment?.inventory_file_no || '').trim();
|
||
}
|
||
|
||
/** 下载行级实际匹配快照,禁止退回到任务级 active link。 */
|
||
async function downloadFormalPreparationLineInventoryFile(line: {
|
||
line_key?: string | 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 的精确动作,line_key 仅作为已授权 Gate 的上下文。 */
|
||
async function retryFormalPreparationLine(
|
||
lineKey: string,
|
||
actionCode: 'retry_inventory_preparation' | 'retry_inventory_matching',
|
||
) {
|
||
if (!lineKey) return;
|
||
await submitFormalGateAction(actionCode, { line_key: lineKey });
|
||
}
|
||
|
||
/**
|
||
* 人工上传登记是后端 Gate 的受控写动作;仅进入「货代上传」工作面不构成授权。
|
||
* 任务详情与批次中心共用 ui_state.actions,避免页面按上传状态或生命周期自行放行。
|
||
*/
|
||
const manualUploadRegistrationAuthorized = computed(() => {
|
||
const actions = formalTaskDetail.value?.ui_state?.actions;
|
||
const candidates = [actions?.primary, ...(actions?.secondary || [])];
|
||
return candidates.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 详情,否则登记已落库但页面仍会显示旧的人工上传阻断状态。
|
||
*/
|
||
async function handleManualUploadSuccess() {
|
||
manualUploadRegistrationOpen.value = false;
|
||
await reloadLatestDraft();
|
||
await Promise.all([
|
||
loadFormalTaskDetail(),
|
||
refreshShippingProcessing(),
|
||
]);
|
||
}
|
||
/**
|
||
* 拉取确认后的 Notice 履约详情,供 Gate Action 与 Artifact 视图使用。
|
||
*/
|
||
async function loadFormalTaskDetail() {
|
||
const taskNo = confirmedNoticeTaskNo.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;
|
||
}
|
||
formalTaskDetailLoadFailed.value = false;
|
||
formalTaskDetailLoading.value = true;
|
||
try {
|
||
const detail = await getWorkspaceShippingTask(taskNo);
|
||
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;
|
||
}
|
||
freightNoticeGroupsLoading.value = true;
|
||
freightNoticeGroupsLoadFailed.value = false;
|
||
freightNoticeGroupsReason.value = null;
|
||
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 {
|
||
freightNoticeGroupsLoading.value = false;
|
||
}
|
||
}
|
||
|
||
function toggleFreightNoticeSelection(businessNo: string, checked: boolean) {
|
||
selectedFreightBusinessNos.value = checked
|
||
? Array.from(new Set([...selectedFreightBusinessNos.value, businessNo]))
|
||
: selectedFreightBusinessNos.value.filter((item) => item !== businessNo);
|
||
}
|
||
|
||
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;
|
||
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);
|
||
}
|
||
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;
|
||
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);
|
||
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'
|
||
));
|
||
}
|
||
|
||
/** 仅展示 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.filter((field) => (
|
||
field.field_code !== 'line_no' && !isInventorySourceHintField(field)
|
||
));
|
||
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;
|
||
return primaryWithCustomerPoLine.length
|
||
? primaryWithCustomerPoLine
|
||
: ordered.slice(0, Math.min(4, ordered.length));
|
||
});
|
||
|
||
/** 主库存表是唯一明细入口;批量出单只允许库存满足或已人工放行的开放行。 */
|
||
const selectedPreparationLineKeys = ref<string[]>([]);
|
||
const preparationWaveBusy = ref(false);
|
||
const preparationCustomerPoLineField = computed(() => (
|
||
lineSchemaFields.value.find((field) => field.field_code === 'customer_po_line_no') || null
|
||
));
|
||
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) => selectedPreparationLineKeys.value.includes(String(line.line_key)))
|
||
));
|
||
|
||
function toggleAllPreparationLineSelection(checked: boolean) {
|
||
selectedPreparationLineKeys.value = checked
|
||
? preparationWaveSelectableLines.value.map((line) => String(line.line_key))
|
||
: [];
|
||
}
|
||
|
||
function togglePreparationLineSelection(lineKey: string, checked: boolean) {
|
||
const key = String(lineKey || '').trim();
|
||
if (!key) return;
|
||
const selected = new Set(selectedPreparationLineKeys.value);
|
||
if (checked) selected.add(key);
|
||
else selected.delete(key);
|
||
selectedPreparationLineKeys.value = [...selected];
|
||
}
|
||
|
||
function preparationLineCustomerPoLine(line: { line_key?: string | null; customer_po_line_no?: string | null }): string {
|
||
const key = String(line.line_key || '').trim();
|
||
const draftLine = displayDraftLines.value.find((item) => String(item.line_key || '').trim() === key);
|
||
const field = preparationCustomerPoLineField.value;
|
||
const draftValueText = field && draftLine
|
||
? String(lineFieldDisplayValue(draftLine as Record<string, unknown>, field) || '').trim()
|
||
: '';
|
||
return draftValueText || String(line.customer_po_line_no || '').trim() || '—';
|
||
}
|
||
|
||
/**
|
||
* 通知行项次展示:按后端 line_no_source 区分渲染。
|
||
* 核心逻辑:field=冻结字段真实值(普通展示);customer_po_line_no=客户 PO 行号(普通展示,
|
||
* 附带来源提示);sequence=系统行序(弱化样式 + 来源提示);缺失直接显示 —。
|
||
* 禁止前端按 position/序号自行推导业务项次。
|
||
*/
|
||
function freightLineNoDisplay(line: { line_no?: string | number | null; line_no_source?: string | null }): {
|
||
text: string;
|
||
muted: boolean;
|
||
title: string;
|
||
} {
|
||
const value = line.line_no ?? null;
|
||
if (value === null || value === '') return { text: '—', muted: false, title: '' };
|
||
const source = String(line.line_no_source || '').trim();
|
||
if (source === 'sequence') {
|
||
return {
|
||
text: String(value),
|
||
muted: true,
|
||
title: t('chat.shippingOrderReview.lifecycle.freightUpload.lineNoSourceSequence'),
|
||
};
|
||
}
|
||
if (source === 'customer_po_line_no') {
|
||
return {
|
||
text: String(value),
|
||
muted: false,
|
||
title: t('chat.shippingOrderReview.lifecycle.freightUpload.lineNoSourceCustomerPo'),
|
||
};
|
||
}
|
||
return { text: String(value), muted: false, title: '' };
|
||
}
|
||
|
||
/**
|
||
* 逐发货通知单的货代上传状态展示。
|
||
* 核心逻辑:upload_status 为后端事实;把 uploaded/uploading/failed/pending 映射为文案与色阶,
|
||
* 并携带 upload_error_code/upload_error_message 作为逐单失败原因。前端禁止按 upload_status 之外的状态猜原因,
|
||
* 未知状态一律回落 pending,避免把内部执行字段当作用户原因。
|
||
* @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 pendingHuman = String(group.pending_human_reason || '').trim().toLowerCase();
|
||
const reason = group.upload_error_message || group.upload_error_code || null;
|
||
if (['uploaded', 'succeeded', 'success'].includes(status)) {
|
||
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 (['uploading', 'upload_rpa_pending'].includes(status) || pendingHuman === 'upload_rpa_pending') {
|
||
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,
|
||
};
|
||
}
|
||
if (pendingHuman) {
|
||
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: reason ? t('chat.shippingOrderReview.lifecycle.freightUpload.uploadError', { reason }) : null,
|
||
};
|
||
}
|
||
return {
|
||
state: 'pending',
|
||
label: t('chat.shippingOrderReview.lifecycle.freightUpload.uploadStatus.pending'),
|
||
chipClass: 'bg-slate-100 text-slate-600 dark:bg-slate-800/60 dark:text-slate-300',
|
||
reason: 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 || !selectedPreparationLineKeys.value.length) return;
|
||
preparationWaveBusy.value = true;
|
||
try {
|
||
const result = await waveWorkspaceShippingOrderReviewLineFulfillment(caseNo, {
|
||
line_keys: [...selectedPreparationLineKeys.value],
|
||
expected_draft_version: draftVersion,
|
||
idempotency_key: `review-wave-${caseNo}-${Date.now()}-${selectedPreparationLineKeys.value.sort().join(',')}`,
|
||
});
|
||
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.fulfillmentDecision.waveSuccess', {
|
||
taskNo: result.notice_no || result.task_no || '',
|
||
}));
|
||
selectedPreparationLineKeys.value = [];
|
||
await handleReviewGateDataRefreshed();
|
||
} 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' && !isInventorySourceHintField(field)
|
||
)).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 { line_key?: string }).line_key || '') === 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'),
|
||
});
|
||
}
|
||
if (meta.override_reason_code) {
|
||
const reasonKey = `chat.shippingOrderReview.lineNoOverrideDialog.reasons.${meta.override_reason_code}`;
|
||
rows.push({
|
||
label: t('chat.shippingOrderReview.lineage.overrideReason'),
|
||
value: te(reasonKey) ? t(reasonKey) : meta.override_reason_code,
|
||
});
|
||
}
|
||
if (meta.override_reason_text) {
|
||
rows.push({
|
||
label: t('chat.shippingOrderReview.lineage.overrideNote'),
|
||
value: meta.override_reason_text,
|
||
});
|
||
}
|
||
if (meta.derivation?.source_field_code) {
|
||
rows.push({
|
||
label: t('chat.shippingOrderReview.lineage.derivedFrom'),
|
||
value: String(meta.derivation.source_field_code),
|
||
});
|
||
}
|
||
if (meta.derivation?.rule_id) {
|
||
rows.push({
|
||
label: t('chat.shippingOrderReview.lineage.ruleId'),
|
||
value: String(meta.derivation.rule_id),
|
||
});
|
||
}
|
||
if (meta.derivation?.skip_reason) {
|
||
rows.push({
|
||
label: t('chat.shippingOrderReview.lineage.skipReason'),
|
||
value: String(meta.derivation.skip_reason),
|
||
});
|
||
}
|
||
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);
|
||
const lineNoOverrideOpen = ref(false);
|
||
const pendingLineNoEdit = ref<{ lineKey: string; fieldId: string; value: string } | null>(null);
|
||
/** 当前 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
|
||
));
|
||
if (!normalizedCode || !gate || !authorized) {
|
||
msg.info(t('workspace.shippingNotice.processGate.noAction'));
|
||
return;
|
||
}
|
||
progressRetrying.value = true;
|
||
try {
|
||
const result = await submitProcessGatePrimaryAction(gate, {
|
||
actionCode: normalizedCode,
|
||
payload,
|
||
});
|
||
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> {
|
||
const taskNo = confirmedNoticeTaskNo.value;
|
||
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,
|
||
lineKey: first.line_key ?? 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 (lineKey?: string) => {
|
||
await reportSave(() => rerouteInventoryRouting(lineKey));
|
||
};
|
||
|
||
/** 打开指定类型的二次确认弹窗。 */
|
||
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.line_key || '');
|
||
if (!lineKey) return;
|
||
if (field.field_code === 'line_no') {
|
||
pendingLineNoEdit.value = { lineKey, fieldId: field.field_id, value };
|
||
lineNoOverrideOpen.value = true;
|
||
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.line_key || '') === 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);
|
||
}
|
||
}
|
||
});
|
||
};
|
||
|
||
/**
|
||
* 内部项次输入中:立即记录待提交值,提示尚未保存,失焦后再弹覆盖原因。
|
||
* @param line - 当前明细行
|
||
* @param field - Schema 字段
|
||
* @param value - 当前输入
|
||
*/
|
||
const onLineNoInput = (
|
||
line: Record<string, unknown>,
|
||
field: { field_id: string; field_code: string },
|
||
value: string,
|
||
) => {
|
||
const lineKey = String(line.line_key || '');
|
||
if (!lineKey) return;
|
||
const committed = draftValue(line, field.field_id);
|
||
if (value === committed && !lineNoOverrideOpen.value) {
|
||
if (pendingLineNoEdit.value?.lineKey === lineKey && pendingLineNoEdit.value.fieldId === field.field_id) {
|
||
pendingLineNoEdit.value = null;
|
||
}
|
||
return;
|
||
}
|
||
pendingLineNoEdit.value = { lineKey, fieldId: field.field_id, value };
|
||
};
|
||
|
||
/**
|
||
* 明细输入过程回调;仅内部项次需要即时未保存提示。
|
||
*/
|
||
const onLineFieldInput = (
|
||
line: Record<string, unknown>,
|
||
field: { field_id: string; field_code: string },
|
||
value: string,
|
||
) => {
|
||
const lineKey = String(line.line_key || '');
|
||
if (!lineKey) return;
|
||
pendingLineFieldInputValues.value.set(`${lineKey}:${field.field_id}`, value);
|
||
if (field.field_code === 'line_no') {
|
||
onLineNoInput(line, field, value);
|
||
}
|
||
};
|
||
|
||
/**
|
||
* 明细单元格展示值:覆盖弹窗打开或编辑中时优先显示待提交值,避免与草稿真值漂移。
|
||
*/
|
||
const lineFieldDisplayValue = (
|
||
line: Record<string, unknown>,
|
||
field: { field_id: string; field_code: string },
|
||
) => {
|
||
const lineKey = String(line.line_key || '');
|
||
if (
|
||
field.field_code === 'line_no'
|
||
&& pendingLineNoEdit.value
|
||
&& pendingLineNoEdit.value.lineKey === lineKey
|
||
&& pendingLineNoEdit.value.fieldId === field.field_id
|
||
) {
|
||
return pendingLineNoEdit.value.value;
|
||
}
|
||
return draftValue(line, field.field_id);
|
||
};
|
||
|
||
/**
|
||
* 确认内部项次覆盖:携带原因码写入 manual_override 并锁定。
|
||
* 核心逻辑:仅成功后关闭弹窗并清空 pending;失败保留原因表单与输入框待提交值。
|
||
* @param payload - 弹窗确认载荷
|
||
*/
|
||
const submitLineNoOverride = async (payload: LineNoOverridePayload) => {
|
||
const pending = pendingLineNoEdit.value;
|
||
if (!pending) return;
|
||
try {
|
||
await patchLine(pending.lineKey, pending.fieldId, payload.value, false, {
|
||
override_reason_code: payload.reasonCode,
|
||
override_reason_text: payload.reasonText,
|
||
});
|
||
pendingLineNoEdit.value = null;
|
||
lineNoOverrideOpen.value = false;
|
||
} catch (error) {
|
||
msg.error(resolveReviewErrorMessage(error));
|
||
}
|
||
};
|
||
|
||
/** 取消项次覆盖时丢弃待提交值,输入框回退为草稿真值。 */
|
||
const cancelLineNoOverride = () => {
|
||
pendingLineNoEdit.value = null;
|
||
lineNoOverrideOpen.value = false;
|
||
};
|
||
|
||
/**
|
||
* 确认弹窗提交:按 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,
|
||
checkpoint: parsed.checkpoint,
|
||
restoredFromProjection: false,
|
||
};
|
||
if (parsed.progressFailed) {
|
||
msg.warning(t('chat.shippingOrderReview.confirmProgressFailed', { taskNo: parsed.taskNo }));
|
||
}
|
||
}
|
||
return;
|
||
}
|
||
if (action === 'reparse') {
|
||
// 重识别是当前复核工作台内的异步子流程:保留旧 Case/字段快照,
|
||
// 由 composable 轮询到新 Case 后原位刷新,不切换路由或清空页面上下文。
|
||
await reparseDocument(payload.reasonCode || 'document_quality', payload.comment);
|
||
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,
|
||
};
|
||
};
|
||
|
||
/**
|
||
* 实际切换 Case(无未保存拦截)。
|
||
* 核心逻辑:清理证据焦点与确认成功条;非 dock 关闭证据模式;只更新 URL,
|
||
* 由 run/case watch 在同 Run 内走轻量 selectCase,避免整页 load 误报历史版与加载中。
|
||
*/
|
||
const select = async (caseNo: string) => {
|
||
const queueItem = documentNavItems.value.find((item) => item.case_no === caseNo);
|
||
// 文件切换是展示上下文切换,不是流程推进。仅消费目标文件后端已下发的
|
||
// current entry;目标未获生命周期授权时清除旧文件留下的深链阶段,保持 fail-closed。
|
||
const selectedLifecycleStage = (() => {
|
||
// Review Queue 经 API 规范化后使用 camelCase;保留 snake_case 兼容直连/旧快照。
|
||
// 两种形态均是后端已裁决的同一 DTO,前端只读取 target 的 current entry。
|
||
const rawQueueItem = queueItem as (typeof queueItem & {
|
||
lifecycleEntries?: ShippingProcessingLifecycleEntry[];
|
||
intakeParseAuthorized?: boolean;
|
||
}) | undefined;
|
||
const entries = rawQueueItem?.lifecycle_entries || rawQueueItem?.lifecycleEntries || [];
|
||
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;
|
||
})();
|
||
const sourceRunNo = String(queueItem?.source_run_no || runNo.value).trim();
|
||
if (sourceRunNo && sourceRunNo !== String(reviewRun.value?.run_no || '').trim()) {
|
||
pendingCrossRunCaseNo.value = caseNo;
|
||
try {
|
||
// 先原子提交目标 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(() => (pendingLineNoEdit.value ? 1 : 0));
|
||
const hasUnsavedEdits = computed(() => unsavedEditCount.value > 0);
|
||
|
||
/**
|
||
* 请求切换 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;
|
||
pendingLineNoEdit.value = null;
|
||
unsavedSwitchOpen.value = false;
|
||
pendingSwitchCaseNo.value = null;
|
||
if (target) await select(target);
|
||
};
|
||
|
||
/**
|
||
* 保存校验后切换(丢弃无法单独落库的行号 pending,再走 validate)。
|
||
*/
|
||
const saveAndSwitchCase = async () => {
|
||
const target = pendingSwitchCaseNo.value;
|
||
pendingLineNoEdit.value = null;
|
||
await onValidate();
|
||
unsavedSwitchOpen.value = false;
|
||
pendingSwitchCaseNo.value = null;
|
||
if (target) await select(target);
|
||
};
|
||
|
||
/**
|
||
* 版本历史面板选择:历史版本只读打开,当前版本正常编辑。
|
||
*/
|
||
const selectVersionFromHistory = async (caseNo: string) => {
|
||
await select(caseNo);
|
||
await refreshWorkItemContext(conversationId.value, reviewProgressContext.value?.item_no || itemNoFromQuery.value);
|
||
};
|
||
|
||
/**
|
||
* 跳转至工作项当前版本 Case。
|
||
*/
|
||
const jumpToCurrentVersion = async () => {
|
||
const target = await openCurrentVersion();
|
||
if (!target) {
|
||
msg.warning(t('chat.shippingOrderReview.currentVersionUnavailable'));
|
||
return;
|
||
}
|
||
await router.replace({
|
||
query: {
|
||
...route.query,
|
||
run_no: target.runNo,
|
||
case_no: target.caseNo,
|
||
case: undefined,
|
||
item_no: reviewProgressContext.value?.item_no || itemNoFromQuery.value || undefined,
|
||
},
|
||
});
|
||
};
|
||
|
||
/**
|
||
* 草稿版本冲突后重新加载服务端最新 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 === 'reparse'
|
||
|| workbenchMode.value === 'confirm_progress'
|
||
) {
|
||
workbenchMode.value = 'standard';
|
||
}
|
||
return;
|
||
}
|
||
if (
|
||
workbenchMode.value === 'reparse'
|
||
|| workbenchMode.value === 'confirm_progress'
|
||
|| workbenchMode.value === 'formal_task'
|
||
) {
|
||
workbenchMode.value = 'standard';
|
||
}
|
||
},
|
||
);
|
||
|
||
watch(
|
||
[lifecycleActiveStageCode, hasFormalOt, intakeParseContextAuthorized],
|
||
([code, , intakeAuthorized]) => {
|
||
// 重识别/确认进度是当前阶段内的短暂辅助视图,不由生命周期页签覆盖。
|
||
if (workbenchMode.value === 'reparse' || workbenchMode.value === 'confirm_progress') return;
|
||
// 未收到后端 lifecycle_entries 时只保留 Case 编辑上下文;禁止默认订单复核
|
||
// surface 反向成为前端阶段裁决。
|
||
if (code === null) return;
|
||
syncLifecycleWorkbenchMode(code);
|
||
if (code === 'intake_parse' && intakeAuthorized && activeCase.value?.case_no) {
|
||
void ensureIntakeParseContextLoaded(activeCase.value.case_no);
|
||
}
|
||
},
|
||
{ immediate: true },
|
||
);
|
||
|
||
watch(
|
||
lifecycleCurrentStageCode,
|
||
async (current, previous) => {
|
||
if (await syncPendingReleaseAutoAdvance()) return;
|
||
if (!current || !previous || current === previous) return;
|
||
// 只响应后端 current 阶段的真实推进:用户点击已完成阶段只会改路由,
|
||
// 绝不能触发自动跳转而被带回当前阶段。
|
||
const requested = String(route.query.lifecycle_stage || '').trim();
|
||
if (requested !== previous) return;
|
||
if (lifecycleStagePinnedByUserForCase.value === String(activeCase.value?.case_no || '').trim()) return;
|
||
const previousIndex = LIFECYCLE_STAGE_CODES.indexOf(previous);
|
||
const currentIndex = LIFECYCLE_STAGE_CODES.indexOf(current);
|
||
if (previousIndex < 0 || currentIndex <= previousIndex) return;
|
||
await selectLifecycleStage(current, { replace: true });
|
||
},
|
||
);
|
||
|
||
/** 通知准备详情失败时保留可见诊断和重试入口,禁止静默空白。 */
|
||
function retryFormalTaskDetail() {
|
||
void loadFormalTaskDetail();
|
||
}
|
||
|
||
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-slate-50 text-slate-900 dark:bg-slate-950 dark:text-slate-100"
|
||
data-testid="shipping-order-review-view"
|
||
:data-readonly="isReadOnly ? '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="isReadOnly"
|
||
: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-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.loading') }}</div>
|
||
<div
|
||
v-else-if="loadFailed"
|
||
class="m-4 rounded-lg border border-rose-300 bg-rose-50 p-4 text-sm text-rose-900 dark:border-rose-800 dark:bg-rose-950/30 dark:text-rose-100"
|
||
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="lifecycleProgressMessage && !hasFormalOt"
|
||
class="mt-2 rounded-md border-l-2 border-brand-500 bg-surface-soft px-2.5 py-1.5 text-xs text-secondary"
|
||
data-testid="review-run-lifecycle-current-step"
|
||
aria-live="polite"
|
||
>
|
||
<span
|
||
v-if="lifecycleProgressMessage.auto"
|
||
class="mr-1 inline-block h-2 w-2 animate-pulse rounded-full bg-brand-500"
|
||
aria-hidden="true"
|
||
/>
|
||
<span>{{ lifecycleProgressMessage.text }}</span>
|
||
<span v-if="lifecycleProgressMessage.reason" class="ml-1 text-warning">· {{ lifecycleProgressMessage.reason }}</span>
|
||
</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"
|
||
@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="formalPreparationContext">
|
||
<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"
|
||
>{{ formalPreparationContext.status }}</span>
|
||
</div>
|
||
<div v-if="formalPreparationContext.has_match_result && formalPreparationLines.length" class="review-fulfillment-prep-workspace mt-4 overflow-x-auto 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: formalPreparationLines.length }) }}</span>
|
||
</div>
|
||
<div v-if="formalEditable" 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: selectedPreparationLineKeys.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 || !selectedPreparationLineKeys.length" @click="confirmPreparationWave">{{ preparationWaveBusy ? t('chat.shippingOrderReview.fulfillmentDecision.waving') : t('chat.shippingOrderReview.fulfillmentDecision.confirmWave', { count: selectedPreparationLineKeys.length }) }}</button>
|
||
</div>
|
||
<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="formalEditable" 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="preparationCustomerPoLineField" class="whitespace-nowrap px-3 py-2">{{ preparationCustomerPoLineField.display_name }}</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 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><tr v-for="line in formalPreparationLines" :key="line.line_key || `${line.reservation_id}-${line.part_number}`" :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="formalEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="selectedPreparationLineKeys.includes(String(line.line_key))" :disabled="preparationWaveBusy || !preparationWaveSelectableLines.some((item) => String(item.line_key) === String(line.line_key))" :aria-label="`${t('chat.shippingOrderReview.fulfillmentDecision.selectReady')}: ${preparationLineCustomerPoLine(line)}`" :data-testid="`review-fulfillment-line-select-${line.line_key}`" @change="togglePreparationLineSelection(String(line.line_key), ($event.target as HTMLInputElement).checked)"></td><td v-if="preparationCustomerPoLineField" class="whitespace-nowrap px-3 py-2">{{ preparationLineCustomerPoLine(line) }}</td><td class="whitespace-nowrap px-3 py-2 font-medium text-primary">{{ line.reservation_id || '—' }}</td><td class="max-w-[220px] truncate px-3 py-2" :title="line.part_number || '—'">{{ line.part_number || '—' }}</td><td class="whitespace-nowrap px-3 py-2">{{ line.required_qty ?? '—' }}</td><td class="max-w-[220px] truncate px-3 py-2" :title="formalPreparationLineSource(line)">{{ formalPreparationLineSource(line) }}</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></td><td class="review-fulfillment-sticky-action-cell whitespace-nowrap px-3 py-2"><div class="flex justify-center gap-1"><button v-if="formalPreparationLineInventoryFileNo(line)" type="button" class="rounded p-1.5 text-brand-700 hover:bg-brand-50" :data-testid="`review-fulfillment-line-download-${line.line_key}`" :aria-label="t(inventoryActionLabelKey('download_inventory_file') || 'chat.shippingOrderReview.lifecycle.prepare.downloadInventory')" :title="t(inventoryActionLabelKey('download_inventory_file') || 'chat.shippingOrderReview.lifecycle.prepare.downloadInventory')" @click="downloadFormalPreparationLineInventoryFile(line)"><Download class="h-3.5 w-3.5" /></button><button v-if="formalPreparationLineAllows(line, 'retry_inventory_preparation')" type="button" class="rounded p-1.5 text-brand-700 hover:bg-brand-50" :data-testid="`review-fulfillment-line-retry-preparation-${line.line_key}`" :aria-label="t(inventoryActionLabelKey('retry_inventory_preparation')!)" :title="t(inventoryActionLabelKey('retry_inventory_preparation')!)" @click="retryFormalPreparationLine(String(line.line_key || ''), 'retry_inventory_preparation')"><Bot class="h-3.5 w-3.5" /></button><button v-if="formalPreparationLineAllows(line, 'retry_inventory_matching')" type="button" class="rounded p-1.5 text-brand-700 hover:bg-brand-50" :data-testid="`review-fulfillment-line-retry-matching-${line.line_key}`" :aria-label="t(inventoryActionLabelKey('retry_inventory_matching')!)" :title="t(inventoryActionLabelKey('retry_inventory_matching')!)" @click="retryFormalPreparationLine(String(line.line_key || ''), 'retry_inventory_matching')"><RefreshCw class="h-3.5 w-3.5" /></button><button v-if="formalPreparationLineAllows(line, 'release_inventory_shortage')" type="button" class="rounded p-1.5 text-amber-700 hover:bg-amber-50" :data-testid="`review-fulfillment-line-release-${line.line_key}`" :aria-label="t(inventoryActionLabelKey('release_inventory_shortage')!)" :title="t(inventoryActionLabelKey('release_inventory_shortage')!)" @click="openReleaseInventoryShortage(line)"><Check class="h-3.5 w-3.5" /></button></div></td></tr></tbody>
|
||
</table>
|
||
</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="formalTaskDetailLoading" 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" :disabled="!selectedFreightBusinessNos.length || 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" :disabled="!selectedFreightBusinessNos.length || 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" class="rounded-full px-2 py-0.5 font-medium">{{ 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>
|
||
<details class="relative">
|
||
<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="canRunFreightNoticeAction(group, 'retry_freight_upload_rpa')" type="button" class="rounded px-2 py-1 text-left text-[11px] text-primary hover:bg-surface-muted disabled:opacity-50" :disabled="freightBatchBusy !== null" @click="void runFreightNoticeAction(group, 'rpa')">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.batchRpa') }}</button>
|
||
<button v-if="canRunFreightNoticeAction(group, 'mark_manual_uploaded')" type="button" class="rounded px-2 py-1 text-left text-[11px] text-primary hover:bg-surface-muted disabled:opacity-50" :disabled="freightBatchBusy !== null" @click="void runFreightNoticeAction(group, 'confirm')">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.batchConfirm') }}</button>
|
||
<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>
|
||
<div v-if="freightUploadStatusDisplay(group).reason" class="border-b border-default bg-rose-50/50 px-3 py-2 text-xs text-rose-700 dark:bg-rose-950/10 dark:text-rose-300" data-testid="review-freight-upload-error">{{ freightUploadStatusDisplay(group).reason }}</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>
|
||
|
||
<!-- 聚合头:本批已上传数量 + 留底下载(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 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>
|
||
</section>
|
||
|
||
<ReviewIntakeParsePanel
|
||
v-if="isLifecycleIntakeParse"
|
||
:context="intakeParseContext"
|
||
:loading="intakeParseLoading"
|
||
:load-failed="intakeParseLoadFailed"
|
||
:preview-url="previewUrl || null"
|
||
:preview-loading="previewLoading"
|
||
@retry-context="() => { if (activeCase?.case_no) void ensureIntakeParseContextLoaded(activeCase.case_no); }"
|
||
@load-preview="() => { if (activeCase?.case_no) void ensurePreviewLoaded(activeCase.case_no); }"
|
||
/>
|
||
<!-- 仅「固定为侧栏」时 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-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900">
|
||
<div class="flex items-center justify-between gap-3">
|
||
<div>
|
||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.orderFields') }}</h2>
|
||
<p class="mt-1 text-xs text-slate-500">{{ t('chat.shippingOrderReview.schemaVersion', { version: displayCase?.schema.schema_version_id || '-' }) }}</p>
|
||
</div>
|
||
<span v-if="isReadOnly" class="rounded-full bg-slate-100 px-2 py-0.5 text-xs text-slate-600 dark:bg-slate-800 dark:text-slate-300">
|
||
{{ 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-slate-600 dark:text-slate-300">
|
||
<span class="truncate">{{ field.display_name }}<span v-if="field.required"> *</span></span>
|
||
<button
|
||
type="button"
|
||
class="shrink-0"
|
||
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 || !isFieldEditable(field.field_id) || saving"
|
||
class="mt-1 w-full rounded-md border border-slate-300 bg-white px-2.5 py-2 text-sm dark:border-slate-600 dark:bg-slate-950"
|
||
: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-slate-500">
|
||
<span>{{ valueSourceLabel(draftFieldMeta(displayHeaderValues as Record<string, unknown> | undefined, field.field_id).value_source) }}</span>
|
||
<button v-if="!caseContentSkeleton && isFieldEditable(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-slate-300 px-2.5 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
|
||
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-slate-300 p-3 text-sm text-slate-500 dark:border-slate-700">
|
||
<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-slate-200 bg-white shadow-sm dark:border-slate-800 dark:bg-slate-900">
|
||
<div class="flex items-center justify-between gap-3 border-b border-slate-200 px-4 py-3 dark:border-slate-800">
|
||
<div>
|
||
<h3 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.lines') }}</h3>
|
||
<p class="mt-1 text-xs text-slate-500">{{ 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-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
|
||
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-slate-50 text-slate-500 dark:bg-slate-950/40 dark:text-slate-400">
|
||
<tr>
|
||
<th class="sticky left-0 z-10 min-w-10 border-b border-slate-200 bg-slate-50 px-2 py-1.5 font-medium dark:border-slate-800 dark:bg-slate-950">#</th>
|
||
<template v-for="field in visibleLineSchemaFields" :key="field.field_id">
|
||
<th class="review-line-column-head border-b border-slate-200 px-2 py-1.5 font-medium dark:border-slate-800" :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-slate-200 px-2 py-1.5 font-medium dark:border-slate-800"
|
||
>
|
||
{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}
|
||
</th>
|
||
<th
|
||
v-if="showLineInventoryColumns && isQtySchemaField(field)"
|
||
class="min-w-16 border-b border-slate-200 px-2 py-1.5 font-medium dark:border-slate-800"
|
||
>
|
||
{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}
|
||
</th>
|
||
</template>
|
||
<template v-if="showLineInventoryColumns && !hasVisibleQtyField">
|
||
<th class="min-w-20 border-b border-slate-200 px-2 py-1.5 font-medium dark:border-slate-800">
|
||
{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}
|
||
</th>
|
||
<th class="min-w-16 border-b border-slate-200 px-2 py-1.5 font-medium dark:border-slate-800">
|
||
{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}
|
||
</th>
|
||
</template>
|
||
<th class="sticky right-0 z-10 min-w-28 border-b border-slate-200 bg-slate-50 px-2 py-1.5 dark:border-slate-800 dark:bg-slate-950">
|
||
<span class="sr-only">{{ t('chat.shippingOrderReview.fulfillmentDecision.actions') }}</span>
|
||
</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
<template
|
||
v-for="(line, index) in displayDraftLines"
|
||
:key="String(line.line_key || index)"
|
||
>
|
||
<tr
|
||
class="border-b border-slate-100 last:border-0 dark:border-slate-800"
|
||
:data-review-line-index="index"
|
||
>
|
||
<td class="sticky left-0 z-10 bg-white px-2 py-1.5 font-medium dark:bg-slate-900">{{ 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)">
|
||
<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="!isFieldEditable(field.field_id) || saving || (field.field_code === 'line_no' && Boolean(draftFieldMeta(line, field.field_id).locked))"
|
||
class="min-w-0 flex-1 rounded border border-slate-300 bg-white px-1.5 py-1 text-xs dark:border-slate-600 dark:bg-slate-950"
|
||
:class="{
|
||
'border-amber-400 ring-1 ring-amber-300 dark:border-amber-500': field.field_code === 'line_no'
|
||
&& pendingLineNoEdit?.lineKey === String(line.line_key || '')
|
||
&& pendingLineNoEdit.fieldId === field.field_id
|
||
&& !lineNoOverrideOpen,
|
||
'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="field.field_code === 'line_no' || 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-slate-100 px-1.5 py-0.5 text-[10px] text-slate-600 marker:content-none dark:bg-slate-800 dark:text-slate-300 [&::-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-slate-200 bg-white p-2 shadow-md dark:border-slate-700 dark:bg-slate-900"
|
||
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-slate-500 dark:text-slate-400">{{ row.label }}</dt>
|
||
<dd class="break-words text-[11px] text-slate-700 dark:text-slate-200">{{ row.value }}</dd>
|
||
</div>
|
||
</dl>
|
||
</div>
|
||
</details>
|
||
</div>
|
||
<p
|
||
v-if="field.field_code === 'line_no'
|
||
&& pendingLineNoEdit?.lineKey === String(line.line_key || '')
|
||
&& pendingLineNoEdit.fieldId === field.field_id
|
||
&& !lineNoOverrideOpen"
|
||
class="mt-0 text-[10px] text-amber-600 dark:text-amber-400"
|
||
>
|
||
{{ t('chat.shippingOrderReview.lineNoUnsavedHint') }}
|
||
</p>
|
||
</div>
|
||
<button
|
||
v-if="editable && field.field_code === 'line_no' && draftFieldMeta(line, field.field_id).locked"
|
||
type="button"
|
||
class="mt-0.5 text-[10px] text-sky-600 hover:underline"
|
||
@click="reportSave(() => patchLine(String(line.line_key), field.field_id, null, true))"
|
||
>
|
||
<Undo2 class="mr-0.5 inline h-2.5 w-2.5" />{{ t('chat.shippingOrderReview.restorePriorProjection') }}
|
||
</button>
|
||
</td>
|
||
<td
|
||
v-if="showLineInventoryColumns && isQtySchemaField(field)"
|
||
class="px-2 py-1.5 align-middle tabular-nums"
|
||
:class="lineFulfillmentFor(String(line.line_key || ''))?.is_shortage ? 'font-medium text-rose-600 dark:text-rose-400' : ''"
|
||
>
|
||
{{ displayAvailableQty(lineFulfillmentFor(String(line.line_key || ''))) }}
|
||
</td>
|
||
<td
|
||
v-if="showLineInventoryColumns && isQtySchemaField(field)"
|
||
class="px-2 py-1.5 align-middle tabular-nums"
|
||
:class="lineFulfillmentFor(String(line.line_key || ''))?.is_shortage ? 'font-medium text-rose-600 dark:text-rose-400' : ''"
|
||
>
|
||
{{ displayShortageQty(lineFulfillmentFor(String(line.line_key || ''))) }}
|
||
</td>
|
||
</template>
|
||
<template v-if="showLineInventoryColumns && !hasVisibleQtyField">
|
||
<td
|
||
class="px-2 py-1.5 align-middle tabular-nums"
|
||
:class="lineFulfillmentFor(String(line.line_key || ''))?.is_shortage ? 'font-medium text-rose-600 dark:text-rose-400' : ''"
|
||
>
|
||
{{ displayAvailableQty(lineFulfillmentFor(String(line.line_key || ''))) }}
|
||
</td>
|
||
<td
|
||
class="px-2 py-1.5 align-middle tabular-nums"
|
||
:class="lineFulfillmentFor(String(line.line_key || ''))?.is_shortage ? 'font-medium text-rose-600 dark:text-rose-400' : ''"
|
||
>
|
||
{{ displayShortageQty(lineFulfillmentFor(String(line.line_key || ''))) }}
|
||
</td>
|
||
</template>
|
||
<td class="sticky right-0 z-10 min-w-28 whitespace-nowrap bg-white px-2 py-1.5 dark:bg-slate-900">
|
||
<div class="flex items-center justify-end gap-0.5">
|
||
<button
|
||
type="button"
|
||
:disabled="!editable || saving"
|
||
class="rounded p-1.5 hover:bg-slate-100 disabled:opacity-50 dark:hover:bg-slate-800"
|
||
data-testid="review-copy-line"
|
||
:aria-label="t('chat.shippingOrderReview.copyLine')"
|
||
:title="t('chat.shippingOrderReview.copyLine')"
|
||
@click="reportSave(() => copyLine(String(line.line_key)))"
|
||
>
|
||
<Copy class="h-3.5 w-3.5" />
|
||
</button>
|
||
<button
|
||
type="button"
|
||
:disabled="!editable || saving || !canDeleteDraftLine(String(line.line_key || ''))"
|
||
class="rounded p-1.5 hover:bg-slate-100 disabled:opacity-50 dark:hover:bg-slate-800"
|
||
data-testid="review-delete-line"
|
||
:aria-label="t('chat.shippingOrderReview.deleteLine')"
|
||
:title="t('chat.shippingOrderReview.deleteLine')"
|
||
@click="reportSave(() => deleteLine(String(line.line_key)))"
|
||
>
|
||
<Trash2 class="h-3.5 w-3.5" />
|
||
</button>
|
||
<ReviewLineInventoryOps
|
||
:line="lineFulfillmentFor(String(line.line_key || ''))"
|
||
:editable="editable"
|
||
:busy="saving"
|
||
@close-line="openCloseFulfillmentDialog([String(line.line_key || '')])"
|
||
/>
|
||
</div>
|
||
</td>
|
||
</tr>
|
||
<tr
|
||
v-if="fulfillmentDetailLineKey && fulfillmentDetailLineKey === String(line.line_key || '')"
|
||
class="border-b border-slate-100 bg-slate-50/40 dark:border-slate-800 dark:bg-slate-950/30"
|
||
data-testid="review-line-fulfillment-detail-row"
|
||
>
|
||
<td :colspan="linesTableColumnCount" class="px-2 py-2">
|
||
<ReviewLineFulfillmentDetail
|
||
:line="lineFulfillmentFor(String(line.line_key || ''))"
|
||
: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-slate-50 text-slate-500 dark:bg-slate-950/40 dark:text-slate-400">
|
||
<tr>
|
||
<th class="sticky left-0 z-10 min-w-10 border-b border-slate-200 bg-slate-50 px-2 py-1.5 font-medium dark:border-slate-800 dark:bg-slate-950">#</th>
|
||
<template v-for="field in visibleLineSchemaFields" :key="`skeleton-${field.field_id}`">
|
||
<th class="border-b border-slate-200 px-2 py-1.5 font-medium dark:border-slate-800" :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-slate-200 px-2 py-1.5 font-medium dark:border-slate-800"
|
||
>
|
||
{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}
|
||
</th>
|
||
<th
|
||
v-if="showLineInventoryColumns && isQtySchemaField(field)"
|
||
class="min-w-16 border-b border-slate-200 px-2 py-1.5 font-medium dark:border-slate-800"
|
||
>
|
||
{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}
|
||
</th>
|
||
</template>
|
||
<th class="sticky right-0 z-10 min-w-28 border-b border-slate-200 bg-slate-50 px-2 py-1.5 dark:border-slate-800 dark:bg-slate-950">
|
||
<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-slate-100 last:border-0 dark:border-slate-800">
|
||
<td class="sticky left-0 z-10 bg-white px-2 py-2 dark:bg-slate-900">
|
||
<div class="h-4 w-4 animate-pulse rounded bg-slate-200 dark:bg-slate-700" />
|
||
</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-slate-200 dark:bg-slate-700" />
|
||
</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
<div v-else class="p-4 text-sm text-slate-500">{{ 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"
|
||
@locate="(lineKey, fieldId) => handleCurrentTaskLocate(lineKey, 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-slate-200 bg-white p-4 shadow-xl dark:border-slate-800 dark:bg-slate-900">
|
||
<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 || !releaseInventoryReason.trim() || (releaseInventoryLine.release_required_fields || []).some((field) => !releaseInventoryFieldValues[field.field_id]?.trim())" @click="confirmReleaseInventoryShortage">{{ t('chat.shippingOrderReview.lifecycle.prepare.releaseConfirm') }}</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="isReadOnly"
|
||
: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"
|
||
/>
|
||
<ReviewLineNoOverrideDialog
|
||
v-model="lineNoOverrideOpen"
|
||
:pending-value="pendingLineNoEdit?.value || ''"
|
||
:confirm-loading="saving"
|
||
@confirm="submitLineNoOverride"
|
||
@cancel="cancelLineNoOverride"
|
||
/>
|
||
</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>
|